Commits

Paul Craven committed e47cdaf

First commit

Comments (0)

Files changed (3)

Empty file added.
+import pygame
+import json
+import bluetooth
+import openxc_thread
+import threading
+import os
+import datetime
+import time
+
+# Define some colors
+BLACK    = (   0,   0,   0)
+WHITE    = ( 255, 255, 255)
+GREEN    = (   0, 255,   0)
+RED      = ( 255,   0,   0)
+ 
+os.environ['SDL_VIDEO_CENTERED'] = '1'
+pygame.init()
+ 
+GRAPH_TIME_RANGE = 30
+
+# Set the width and height of the screen [width, height]
+SCREEN_WIDTH = 1024
+SCREEN_HEIGHT = 600
+
+size = (SCREEN_WIDTH, SCREEN_HEIGHT)
+screen = pygame.display.set_mode(size)
+ 
+pygame.display.set_caption("Focus ST")
+ 
+# Loop until the user clicks the close button.
+done = False
+ 
+# Used to manage how fast the screen updates
+clock = pygame.time.Clock()
+
+data_thread = openxc_thread.OpenXCDataThread()
+data_thread.start()
+
+# Select the font to use, size, bold, italics
+font = pygame.font.SysFont('Calibri', 25, True, False)
+ 
+# -------- Main Program Loop -----------
+while not done:
+    # --- Main event loop
+    for event in pygame.event.get(): # User did something
+        if event.type == pygame.QUIT: # If user clicked close
+            done = True # Flag that we are done so we exit this loop
+ 
+    screen.fill(BLACK)
+ 
+    if len(data_thread.engine_speed) == 0:
+        text = font.render(data_thread.message, True, WHITE)
+    else:
+        text = font.render("RPM: "+str(data_thread.engine_speed[-1][1]), True, WHITE)
+
+    screen.blit(text, [10, 10])
+
+    if len(data_thread.vehicle_speed) == 0:
+        text = font.render("", True, WHITE)
+    else:
+        text = font.render("Vehicle Speed: {:.1f} kph".format(data_thread.vehicle_speed[-1][1]), True, WHITE)
+
+    screen.blit(text, [10, 40])
+        
+    if len(data_thread.transmission_gear_position) == 0:
+        text = font.render("", True, WHITE)
+    else:
+        text = font.render("Gear: "+str(data_thread.transmission_gear_position[-1][1]), True, WHITE)
+
+    screen.blit(text, [10, 70])
+      
+    start_data_pos = 0
+    if len(data_thread.engine_speed) > SCREEN_WIDTH:
+        start_data_pos = len(data_thread.engine_speed) - SCREEN_WIDTH
+        
+    for i in range(start_data_pos, len(data_thread.engine_speed)):
+        if i > 0:
+            v1 = data_thread.engine_speed[i-1][1]
+            t1 = data_thread.engine_speed[i-1][0]
+            v2 = data_thread.engine_speed[i][1]
+            t2 = data_thread.engine_speed[i][0]
+            y1 = SCREEN_HEIGHT - (v1 / 15)
+            y2 = SCREEN_HEIGHT - (v2 / 15)
+            
+            cur_time = time.time() * 1000
+            x1 = SCREEN_WIDTH - ( (cur_time - t1) / (GRAPH_TIME_RANGE * 1000.) * SCREEN_WIDTH) 
+            x2 = SCREEN_WIDTH - ( (cur_time - t2) / (GRAPH_TIME_RANGE * 1000.) * SCREEN_WIDTH) 
+            
+            pygame.draw.line(screen,WHITE,
+                             [x1, y1],
+                             [x2, y2], 2)
+
+    # --- Go ahead and update the screen with what we've drawn.
+    pygame.display.flip()
+ 
+    # --- Limit to 60 frames per second
+    clock.tick(60)
+ 
+# Close the window and quit.
+pygame.quit()
+import random
+import time
+import json
+import bluetooth
+import threading
+import datetime
+
+DEVICE_NAME = "OpenXC-VI-734B"
+
+class OpenXCDataThread(threading.Thread):
+    
+    engine_speed = None
+    vehicle_speed = None
+    transmission_gear_position = None
+    message = "Starting up..."
+    
+    def __init__(self):
+        threading.Thread.__init__(self)
+        self.engine_speed = list()
+        self.vehicle_speed = list()
+        self.transmission_gear_position = list()
+        
+    def run(self):
+        target_address = None
+        
+        self.message = "Searching for a paired device called \"" + DEVICE_NAME + "\"."
+        nearby_devices = bluetooth.discover_devices()
+        
+        for bdaddr in nearby_devices:
+            if DEVICE_NAME == bluetooth.lookup_name( bdaddr ):
+                target_address = bdaddr
+                break
+            else:
+                print (bluetooth.lookup_name( bdaddr ))
+        
+        target_found = True
+        if target_address is not None:
+            self.message = "Found target bluetooth device with address "+ target_address
+            
+        else:
+            self.message = "Could not find target bluetooth device nearby"
+        
+        if target_found:
+            port = 1
+            
+            connected = False
+            try_count = 1
+            while not connected:
+                self.message = "Trying to connect, try "+str(try_count)
+                try_count += 1
+                sock = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
+                try:
+                    sock.connect((target_address, port))
+                    connected = True
+                except IOError:
+                    print ("Failed to connect")
+                    
+            self.message = "Successfully accessed device, waiting for data."
+            
+            while True:
+                data = ''
+                char = ''
+                while len(char) == 0 or chr(char[0]) != '}':
+                    char = sock.recv(1)
+                    if len(char) > 0 and char[0] != 0:
+                        data += chr(char[0])
+                    
+                decoded = False
+                try:
+                    jdata = json.loads(data)
+                    decoded = True
+                except:
+                    print("Error decoding data. Does not appear to be JSON format.")
+                    
+                if decoded:
+
+                    if jdata['name'] == 'engine_speed':
+                        #print (jdata['value'])
+                        self.engine_speed.append((time.time() * 1000, jdata['value']))
+                        
+                    elif jdata['name'] == 'vehicle_speed':
+                        self.vehicle_speed.append((time.time() * 1000, jdata['value']))
+            
+                    elif jdata['name'] == 'transmission_gear_position ':
+                        self.transmission_gear_position.append((time.time() * 1000, jdata['value']))
+                
+