Commits

Brian Thorne committed df51739

Add RawBluetoothSocket class and refactor bluetooth car to use

Comments (0)

Files changed (2)

 import socket
 import time
 
-class BluetoothCar:
+class RawBluetoothSocket:
     def __init__(self, mac_address="00:12:05:09:98:36"):
-        self.socket = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
+        self.socket = socket.socket(socket.AF_BLUETOOTH, 
+                                    socket.SOCK_STREAM, 
+                                    socket.BTPROTO_RFCOMM)
         self.socket.connect((mac_address, 1))
     
-    def _write(self, data_byte):
+    def write(self, data_byte):
         self.socket.send(bytes([data_byte]))
+
+
+class BluetoothCar:
     
-    def drive(self, command, duration=1.0):
-        self._write(command)
-        time.sleep(duration)
-        self.stop()
-        
+    def __init__(self):
+        self.bluetooth_connection = RawBluetoothSocket()
+
+    def drive(self, command, duration=None):
+        self.bluetooth_connection.write(command)
+        if duration is not None:
+            time.sleep(duration)
+            self.stop()
+
     def forwards(self, duration=1.0):
         self.drive(0x16, duration)
-        
+
     def reverse(self, duration=1.0):
         self.drive(0x26, duration)
 
         self.drive(0x67, duration)
 
     def stop(self):
-        self._write(0x00)
-    
+        self.bluetooth_connection.write(0x00)
+
     def __del__(self):
         self.stop()
 

can_controlled_car.py

 from real_raw_can import filtered_receiver
 from bluetooth_car import BluetoothCar
 
-
 def can_drive_car(stop, q):
     car = BluetoothCar()
     duration = 0.1
         'left': car.left,
         'right': car.right
         }
+    
     while not stop.is_set():
         command = q.get().decode()
         if command in commands:
             commands[command](duration)
-        
+
 
 if __name__ == "__main__":
     stop = threading.Event()