def _tryQueryMbService(self, uuid): conn = GATTRequester(uuid, False, self.devName) try: conn.connect(False, "random") max_time = time.time() + 5 while not conn.is_connected(): if time.time() > max_time: return False time.sleep(0.5) DEV_NAME_SERVICE_UUID = "00002a00-0000-1000-8000-00805f9b34fb" # 2A00, device name try: value = "".join(conn.read_by_uuid(DEV_NAME_SERVICE_UUID)) except RuntimeError as err: msg = err.message.lower() if "no attribute found": return False else: raise value = value.lower() return ("mibp" in value or "mib-push" in value) finally: if conn.is_connected(): conn.disconnect() while conn.is_connected(): time.sleep(0.5)
class Driver(object): handle = 0x16 commands = { 'press' : '\x57\x01\x00', 'on' : '\x57\x01\x01', 'off' : '\x57\x01\x02', } def __init__(self, device, bt_interface=None, timeout_secs=None): self.device = device self.bt_interface = bt_interface self.timeout_secs = timeout_secs if timeout_secs else 5 self.req = None def connect(self): if self.bt_interface: self.req = GATTRequester(self.device, False, self.bt_interface) else: self.req = GATTRequester(self.device, False) self.req.connect(True, 'random') connect_start_time = time.time() while not self.req.is_connected(): if time.time() - connect_start_time >= self.timeout_secs: raise RuntimeError('Connection to {} timed out after {} seconds' .format(self.device, self.timeout_secs)) def run_command(self, command): return self.req.write_by_handle(self.handle, self.commands[command])
def connect(device: str, bt_interface: str, timeout: float): if bt_interface: req = GATTRequester(device, False, bt_interface) else: req = GATTRequester(device, False) req.connect(False, 'random') connect_start_time = time.time() while not req.is_connected(): if time.time() - connect_start_time >= timeout: raise ConnectionError( 'Connection to {} timed out after {} seconds'.format( device, timeout)) time.sleep(0.1) yield req if req.is_connected(): req.disconnect()
class Toio(object): HANDLER = {'motor': "TBU"} DIRECTION = {'fwd': 1, 'bck': 2} MOTOR = {'1st': 1, '2nd': 2} SPEED_MAX = 100 def __init__(self, addr): self.req = "" if not addr: return self.req = GATTRequester(addr, False) print("Connecting...: {}".format(addr)) self.req.connect(wait=True, channel_type="random") print("Connected: {}".format(addr)) def request_data(self, uuid): return self.req.read_by_uuid(uuid)[0] def write_data(self, handler, data): self.req.write_by_handle(handler, data) def disconnect(self): self.req.disconnect() def is_connected(self): if not self.req: return False return self.req.is_connected() def _move(self, motor_1st_dir, motor_1st_speed, motor_2nd_dir, motor_2nd_speed, duration_sec): self.write_data(self.HANDLER['motor'], str( bytearray([2, self.MOTOR['1st'], motor_1st_dir, motor_1st_speed, self.MOTOR['2nd'], motor_2nd_dir, motor_2nd_speed, int(duration_sec * 100)]))) import time time.sleep(duration_sec) def straight(self): self._move(self.DIRECTION['fwd'], self.SPEED_MAX, self.DIRECTION['fwd'], self.SPEED_MAX, 1) def turn_left(self): self._move(self.DIRECTION['fwd'], self.SPEED_MAX / 2, self.DIRECTION['fwd'], self.SPEED_MAX, 1) def turn_right(self): self._move(self.DIRECTION['fwd'], self.SPEED_MAX, self.DIRECTION['fwd'], self.SPEED_MAX / 2, 1) def back(self): self._move(self.DIRECTION['bck'], self.SPEED_MAX, self.DIRECTION['bck'], self.SPEED_MAX, 1) def spin_turn_180(self): self._move(self.DIRECTION['bck'], self.SPEED_MAX, self.DIRECTION['fwd'], self.SPEED_MAX, 0.5) def spin_turn_360(self): self._move(self.DIRECTION['bck'], self.SPEED_MAX, self.DIRECTION['fwd'], self.SPEED_MAX, 1)
# SM,2,0010 # # The characteristic handle (72 in the example above) must match the handle created for the service. # import time from bluetooth.ble import GATTRequester # # the MAC address of the BLE device. Replace 'D8:80:39:FC:7B:F5' with the address of your device. # grq = GATTRequester('D8:80:39:FC:7B:F5', False) grq.connect() print("Waiting to connect...") while not grq.is_connected(): time.sleep(1) print("Connected.") characteristics = grq.discover_characteristics() # # the UUID of the service on the BLE device. # sample_uuid = '59c889e0-5364-11e7-b114-b2f933d5fe66' # find the handle for the characteristic. vh_sample = None for c12c in characteristics: if c12c['uuid'] == sample_uuid: vh_sample = c12c['value_handle']
class Blimp: def __init__(self, mac="C4:C3:00:01:07:3F"): # Check for empty arg and correct MAC address format # Default MAC address is given otherwise if not re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()): print("Using default MAC: C4:C3:00:01:07:3F") self.mac = "C4:C3:00:01:07:3F" else: self.mac = mac self.service = DiscoveryService() self.devices = self.service.discover(2) self.requester = GATTRequester(self.mac, False) def find_blimp(self, blimp_name): self.devices = self.service.discover(2) for address, name in self.devices: if name == blimp_name: self.mac = address print(blimp_name + " found with MAC Address " + address) break def connect(self): try: self.requester.connect(True) except: print("Failed to connect; Make sure target is turned on and correct MAC address is provided") def disconnect(self): try: self.requester.disconnect(True) except: print("Failed to disconnect; try again") def is_connected(self): return self.requester.is_connected() # Enter value between -32767 to 32767 # Negative value commands backward thrust, and vice versa with positive value, for left propeller def left(self, value): if self.is_connected(): if -32768 < value < 32768: if value < 0: command = '{:04x}'.format(-1*int(value)) else: command = '{:04x}'.format(65535 - int(value)) self.requester.write_by_handle(34, command.decode('hex')) else: print("Command value is must be integer between -32767 & 32767") else: print("First connect to target before commanding thrust") # Enter value between -32767 to 32767 # Negative value commands backward thrust, and vice versa with positive value, for right propeller def right(self, value): if self.is_connected(): if -32768 < value < 32768: if value < 0: command = '{:04x}'.format(-1*int(value)) else: command = '{:04x}'.format(65535 - int(value)) self.requester.write_by_handle(36, command.decode('hex')) else: print("Command value is must be integer between -32767 & 32767") else: print("First connect to target before commanding thrust") # Enter value between -32767 to 32767 # Negative value commands backward thrust, and vice versa with positive value, for down propeller def down(self, value): if self.is_connected(): if -32768 < value < 32768: if value < 0: command = '{:04x}'.format(-1*int(value)) else: command = '{:04x}'.format(65535 - int(value)) self.requester.write_by_handle(38, command.decode('hex')) else: print("Command value is must be integer between -32767 & 32767") else: print("First connect to target before commanding thrust") # Function to stop all actuators def stop(self): if self.is_connected(): command = '{:04x}'.format(65535) self.requester.write_by_handle(34, command.decode('hex')) self.requester.write_by_handle(36, command.decode('hex')) self.requester.write_by_handle(38, command.decode('hex')) else: print("Command failed; not connected to target")
class Reader(object): def __init__(self, address): self.requester = GATTRequester(address, False) self.connect() t = threading.Thread(name=address,target=self.periodical_request) t.daemon = True t.start() def connect(self): self.requester.connect(True,"random","medium",0,32) print ("Connected") def request_uuid(self): self.uuid = self.requester.read_by_uuid("D6F8BDCC-3885-11E6-AC61-9E71128CAE77")[0] print("uuid read:", self.uuid) if len(self.uuid) < 37: self.uuid = self.uuid + self.requester.read_by_uuid("D6F8BDCC-3885-11E6-AC61-9E71128CAE77")[0] print("complete uuid:", self.uuid[0:35]) def periodical_request(self): tracked_devices.append(threading.current_thread().getName()) try: self.request_uuid() except RuntimeError: tracked_devices.remove(threading.current_thread().getName()) return count = 0 while True: self.request_data() count = count + 1 print("Count:",count) time.sleep(1) def request_data(self): if not self.requester.is_connected(): print("Reconnecting") self.requester.disconnect() try: self.requester.connect(True,"random","medium",0,32) except RuntimeError: # End the thread bc cannot reconnect if threading.current_thread().getName() in tracked_devices: # should be in the tracked devices list # remove when thread is going to end tracked_devices.remove(threading.current_thread().getName()) else : print("Error: thread should be tracked") print("Encountered error when reconnecting. Now exit thread.") sys.exit() print("Reconnected") try: start_time = current_milli_time() data = self.requester.read_by_uuid( "16864516-21E0-11E6-B67B-9E71128CAE77")[0] except RuntimeError as e: print("RuntimeError", e) self.requester.disconnect() return try: d = decode_string_to_double(data) print ("Device name:",self.uuid,"Device motion:", d) if socket_open: socket_connect.sendMotionAndUUID(d,self.uuid) motion_manager.process_data(self.uuid[0:35], self.uuid[36],d) except AttributeError: print ("Device name: " + data)
from __future__ import print_function from bluetooth.ble import DiscoveryService, GATTRequester import sys import time service = DiscoveryService() devices = service.discover(2) for address, name in devices.items(): print("name: {}, address: {}".format(name, address)) r = GATTRequester(address) print("Connecting...", end=' ') sys.stdout.flush() print(dir(r), r.is_connected()) time.sleep(2) r.connect(True)