1. Brian Thorne
  2. python-socket-examples

Source

python-socket-examples / bluetooth_car.py

import socket
import time

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.connect((mac_address, 1))
    
    def write(self, data_byte):
        self.socket.send(bytes([data_byte]))


class BluetoothCar:
    
    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)

    def left(self, duration=1.0):
        self.drive(0x57, duration)

    def right(self, duration=1.0):
        self.drive(0x67, duration)

    def stop(self):
        self.bluetooth_connection.write(0x00)

    def __del__(self):
        self.stop()

if __name__ == "__main__":
    car = BluetoothCar()
    while True:
        car.forwards(0.05)