def main(): """ Main function. The comments below try to explain what each section of the code does. """ # pygatt uses pexpect and if your device has a long list of characteristics, # pexpect will not catch them all. We increase the search window to # 2048 bytes for the this example. By default, it is 200. # Note: We need an instance of GATToolBackend per each device connection adapter = pygatt.GATTToolBackend(search_window_size=2048) try: # Start the adapter adapter.start() # Connect to the device with that given parameter. # For scanning, use adapter.scan() device = adapter.connect("1C:87:74:00:E5:A0") # Set the security level to medium device.bond() # Observes the given characteristics for indications. # When a response is available, calls data_handle_cb device.subscribe("00002a1c-0000-1000-8000-00805f9b34fb", callback=data_handler_cb, indication=True) input("Press enter to stop program...\n") finally: # Stop the adapter session adapter.stop() return 0
def start_read_insole_rawdata(self): #self.deviceName = self.name.replace("Thorsis","") #self.deviceName = self.name.replace("Thorsis Ins.","") #self.deviceName = self.name.replace("Thorsis Ins. ESS ","") #If followig case appears, then hciconfig hci0 reset #Can't init device hci0: Connection timed out (110) #sudo service bluetooth restart self.adapter = pygatt.GATTToolBackend(hci_device='hci0') self.adapter.start(True) print "Connecting Device "+self.deviceName print "With Address "+self.address while 1: try: time.sleep(2) #self.device = self.adapter.connect(self.address, 10) self.device = self.adapter.connect('00:07:80:D4:09:2D') time.sleep(2) break except: print "Error: reconnecting" self.adapter.disconnect self.adapter.sendline('mtu 64') time.sleep(2) self.callibrateSensor() print "Subscribe "+self.deviceName self.device.subscribe('00002b00-0000-1000-8000-00805f9b34fb', self.callback_func)
def __init__(self): """ Constructor. """ super(Meccanoid, self).__init__() self._gatt = pygatt.GATTToolBackend() self._gatt.start() self._device = None # These are stateful so we remember them and mutate accordingly self._servos = \ [0x08, 0x7f, 0x80, 0x00, 0xff, 0x80, 0x7f, 0x7f, 0x7f, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01] self._servo_lights = \ [0x0c, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x00] self._chest_lights = \ [0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] # These numbers make it yawn and say "I'm awake", and then # waggle its arms about self._im_awake =\ (0x19, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d)
def __init__(self): self.mac_addresses = [ # Player 4 'C8:FD:19:0B:52:5A' # Player 4B #'60:64:05:B3:FB:24' ] self.adapter = pygatt.GATTToolBackend() self.device = None self.socketio = SocketIO(host, port) self.socketio.on('dildon', self.on_event) self.socketio.on('dildoff', self.on_event) print "audio command thread" audioThread = Thread(target=AudioCommandThread) audioThread.daemon = True audioThread.start() self.connectToVibrator() self.receive_events_thread = Thread(target=self._receive_events_thread) self.receive_events_thread.daemon = True self.receive_events_thread.start() while True: try: check = raw_input() except EOFError: check = "" self.socketio.emit('event', check)
def __init__(self): self.mac_addresses = [ # Player 3 'C8:FD:19:0A:10:88' ] self.adapter = pygatt.GATTToolBackend() self.device = None self.stopFlag = Event() self.keepAliveThread = None self.socketio = SocketIO(host, port) self.socketio.on('dildon', self.on_event) self.socketio.on('dildoff', self.on_event) self.connectToVibrator() self.receive_events_thread = Thread(target=self._receive_events_thread) self.receive_events_thread.daemon = True self.receive_events_thread.start() while True: try: check = raw_input() except EOFError: check = "" self.socketio.emit('event', check)
def __init__(self, reset=False, log=False): # set logging if log: logging.basicConfig() logging.getLogger('pygatt').setLevel(logging.DEBUG) self.device = None self.adapter = pygatt.GATTToolBackend() self.adapter.start(reset_on_start=reset) self.reply_buf = {} self.config = { 'sensor_combination': 7, 'accelerometer_range': 0x0C, 'accelerometer_rate': 0x08, 'gyroscope_range': 0x03, 'gyroscope_rate': 0x08, 'magnetometer_rate': 0x00, 'enviromental_rate': 1, 'sensor_fusion_rate': 25, 'sensor_fusion_raw_en': 1, 'calibration_mode': 1, 'auto_calibration_mode': 0 } self.subscribed_uuids = [] self.subscribed_callbacks = {} self.run = None
def connect(self, interface=None, backend='auto'): """Connect to the device""" if self.backend == 'gatt': self.interface = self.interface or 'hci0' self.adapter = pygatt.GATTToolBackend(self.interface) else: self.adapter = pygatt.BGAPIBackend(serial_port=self.interface) self.adapter.start() if self.address is None: address = self.find_muse_address(self.name) if address is None: raise(ValueError("Can't find Muse Device")) else: self.address = address self.device = self.adapter.connect(self.address) # subscribes to EEG stream if self.enable_eeg: self._subscribe_eeg() if self.enable_control: self._subscribe_control() if self.enable_telemetry: self._subscribe_telemetry() if self.enable_acc: self._subscribe_acc() if self.enable_gyro: self._subscribe_gyro()
def _connect(address): adapter = pygatt.GATTToolBackend() adapter.start() device = adapter.connect(address, timeout=TIMEOUT, address_type=pygatt.BLEAddressType.random) return device
def __init__(self): self.in_count = bytearray([]) self.in_crc = bytearray([]) self.status = STATUS_READY self.characteristic = "a6e65511-80aa-11ea-ab12-0800200c9a66" self.adapter = pygatt.GATTToolBackend() self.adapter.start(reset_on_start=False) print("Scan...") scan_list = self.adapter.scan() device_address = "" for dev in scan_list: if dev["name"] == "Remote E-ink display": device_address = dev["address"] break if device_address == "": print("Remote E-ink display not found") self.status = STATUS_ERROR else: print("Connect to Remote E-ink display, address: %s" % device_address) self.device = self.adapter.connect(device_address) time.sleep(1) self.device.subscribe(self.characteristic, callback=self.handle_data, indication=True) time.sleep(1)
def main(argv=None): if argv is None: argv = sys.argv try: try: opts, args = getopt.getopt(argv[1:], "a:", ["address="]) except (getopt.error, msg): raise Usage(msg) for o, a in opts: if o in ("-a", "--address"): address = a else: assert False, "unhandled option" except (Usage, err): return 2 adapter = pygatt.GATTToolBackend(search_window_size=2048) try: adapter.start(reset_on_start=False) device = adapter.connect(address) device.bond() #print(device.discover_characteristics()) device.subscribe('0000ff02-0000-1000-8000-00805f9b34fb', callback=data_handler_cb, indication=True, wait_for_response=False) deskStatus(device) deskStatus(device) input("Press enter to stop program...\n") finally: adapter.stop() print("Data: {}".format(height)) return 0
def main(): loop = asyncio.get_event_loop() loop.run_until_complete(discover()) global MAC_ADDRESS global adapter if MAC_ADDRESS != None: adapter = pygatt.GATTToolBackend() try: adapter.start() device = adapter.connect(MAC_ADDRESS, address_type=ADDRESS_TYPE) for uuid in device.discover_characteristics().keys(): if uuid in BRUXISM_UUIDS: print(f"{bcolors.HEADER} CHARACTERISTIC {bcolors.END}\n") print( f" {bcolors.BOLD}{bcolors.OKGREEN} UUID {bcolors.END} -> {bcolors.BOLD}{bcolors.OKBLUE}{uuid}{bcolors.END}\n" ) print( f" {bcolors.BOLD}{bcolors.OKGREEN} VALUE {bcolors.END} -> {bcolors.BOLD}{bcolors.OKBLUE}{binascii.hexlify(device.char_read(uuid))}{bcolors.END}\n" ) #device.subscribe(ACCEL_UUID, callback=filter.accel_handler) #device.subscribe(GYRO_UUID, callback=filter.gyro_handler) #device.subscribe(FORCE_UUID, callback=force_handler) asyncio.run(detect_key_press(device)) #x = asyncio.new_event_loop() #asyncio.set_event_loop(x) #asyncio.ensure_future(detect_key_press(x)) #x.run_forever() except Exception as e: print(e)
def __init__(self, logger): # get logger self.lgr = logger # specify scheduler self.scheduler = BackgroundScheduler() self.scheduler.add_job(self._event_tick, 'cron', minute='*/2', second='10') # add error listener for logging self.scheduler.add_listener(self._on_job_error, mask=EVENT_JOB_ERROR) # gatttool self.btadapter = pygatt.GATTToolBackend() # threading: wait until all data is downloaded self.temps_done = Event() self.temps_done.clear() self.humids_done = Event() self.humids_done.clear() # data storage, newest events are first! self.last_temps = [] self.last_humids = []
def list_muses(backend='auto', interface=None): backend = helper.resolve_backend(backend) if backend == 'gatt': interface = interface or 'hci0' adapter = pygatt.GATTToolBackend(interface) elif backend == 'bluemuse': print( 'Starting BlueMuse, see BlueMuse window for interactive list of devices.' ) subprocess.call('start bluemuse:', shell=True) return else: adapter = pygatt.BGAPIBackend(serial_port=interface) adapter.start() print('Searching for Muses, this may take up to 10 seconds...') devices = adapter.scan(timeout=MUSE_SCAN_TIMEOUT) adapter.stop() muses = [] for device in devices: if device['name'] and 'Muse' in device['name']: muses = muses + [device] if (muses): for muse in muses: print('Found device %s, MAC Address %s' % (muse['name'], muse['address'])) else: print('No Muses found.') return muses
def __init__(self, mac): if not mac: raise "LionChief constructor needs mac address" self._adapter = pygatt.GATTToolBackend() self._adapter.start() self._device = self._adapter.connect(mac)
def try_get_best_possible_bluetooth_adapter(): """ Try to get the best possible, working Bluetooth adapter for the current environment """ if can_use_bt_gatttool(): return pygatt.GATTToolBackend() else: return pygatt.BGAPIBackend()
def __init__(self, address): self.adapter = pygatt.GATTToolBackend() pygatt.BLEDevice.receive_notification = self.notify self.adapter.start() self.device = self.adapter.connect( address, address_type=pygatt.BLEAddressType.random) self.enable_notifications()
def list_muses(backend='bgapi', interface=None): backend = resolve_backend(backend) if backend == 'gatt': interface = interface or 'hci0' adapter = pygatt.GATTToolBackend(interface) else: adapter = pygatt.BGAPIBackend(serial_port=interface) adapter.start() # print('Searching for Muses, this may take up to 10 seconds... ') devices = adapter.scan(timeout=10.5) adapter.stop() muses = [] for device in devices: if device['name'] and 'Muse' in device['name']: muses = muses + [device] if muses: for muse in muses: pass # print('Found device %s, MAC Address %s' % # (muse['name'], muse['address'])) else: pass # print('No Muses found.') return muses
def main(opt=[], show=False): parser = argparse.ArgumentParser() parser.add_argument('-i', '--interface', required=True) parser.add_argument('-d', '--duration-scan', type=int, default=2) parser.add_argument('-r', '--repeat', type=int, default=2) env = parse_envfile() env.extend(opt) args = parser.parse_args(env) try: adapter = pygatt.GATTToolBackend(hci_device=args.interface) except Exception as e: print(e) devices = scan_ble(adapter, args.duration_scan) for i in range(0, args.repeat - 1): devices_c = [] devices_b = scan_ble(adapter, args.duration_scan) for item_b in devices_b: for item_a in devices: if item_b['address'] == item_a['address']: devices_c.append(item_b) devices = devices_c if show: print(devices) return devices
def __init__(self, addr=None, adapter=None): if adapter is None: self.adapter = pygatt.GATTToolBackend() self.adapter.start() else: self.adapter = adapter if addr is None: devices = self.adapter.scan() for device in devices: if device["address"][:8] == "F3:53:11": addr = device["address"] break else: raise RuntimeError( "No address provided and could not find device via scan.") self.device = self.adapter.connect( addr, address_type=pygatt.BLEAddressType.random) self._char_tx = "02240002-5efd-47eb-9c1a-de53f7a2b232" self._char_feedback = "02260002-5efd-47eb-9c1a-de53f7a2b232" self._refresh_data()
async def find_devices(username: str, password: str): """Gather a list of device infos from the local network.""" result = [] adapter = pygatt.GATTToolBackend() devices = adapter.scan() _LOGGER.debug("Found %d devices" % (len(devices))) for dev in devices: if not dev.address.startswith(START_MAC_ADDRESS): _LOGGER.debug( "Skipped device %s [%s] the MAC address of this device does not start with valid sequence" % (dev.name, dev.address)) continue _LOGGER.debug("Device %s [%s]" % (dev.name, dev.address)) try: mylight = DeviceScanner._connect(dev.address, username, password) # if mylight.session_key: result.append({ 'mac': dev.address, 'name': mylight.getModelNumber() }) mylight.disconnect() except: _LOGGER.debug('Failed to connect [%s]' % dev.address)
def main(): # get the lock key with open(INPUT_FILE_PATH) as inputFile: global lockKey lockKey = inputFile.read() inputFile.close() try: adapter = pygatt.GATTToolBackend() adapter.start() # connect to the device global device device = adapter.connect(DEVICE_ADDRESS, address_type=pygatt.BLEAddressType.random) print('Connected to the device') print('Press any key to stop this program...\n') # subscribe to the notifications' channel device.subscribe(UUID_NOTIFY_CHARACTERISTIC_UUID, callback=onNotifyCallback) sendNewSessionKeyRequest() # wait until a keyboard key is pressed input() finally: adapter.stop()
def ble_proc(): # adapter = pygatt.BGAPIBackend() adapter = pygatt.GATTToolBackend() try: adapter.start() device = adapter.connect(microbit.mac_address, address_type=pygatt.BLEAddressType.random) device.subscribe(MicroBit.BLE_UUID['BUTTON_A_STATE'], callback=microbit.handle_button_a) device.subscribe(MicroBit.BLE_UUID['BUTTON_B_STATE'], callback=microbit.handle_button_b) device.subscribe(MicroBit.BLE_UUID['ACCELEROMETER'], callback=microbit.handle_accelerometer) device.subscribe(MicroBit.BLE_UUID['TEMPERATURE'], callback=microbit.handle_temperature) device.subscribe(MicroBit.BLE_UUID['MAGNETOMETER'], callback=microbit.handle_magnetometer) device.subscribe(MicroBit.BLE_UUID['MAGNETOMETER_BEARING'], callback=microbit.handle_magnetometer_bearing) microbit.device = device while True: try: cmd_line = microbit.command_queue.pop() process_command(cmd_line) except: pass time.sleep(0.01) finally: adapter.stop()
def connect(self, interface=None, backend='auto'): """Connect to the device""" if self.backend == 'gatt': self.interface = self.interface or 'hci0' self.adapter = pygatt.GATTToolBackend(self.interface) else: self.adapter = pygatt.BGAPIBackend(serial_port=self.interface) self.adapter.start() if self.address is None: address = self.find_muse_address(self.name) if address is None: raise (ValueError("Can't find Muse Device")) else: self.address = address self.device = self.adapter.connect(self.address) # subscribes to EEG stream if self.eeg: self._subscribe_eeg() # subscribes to Accelerometer if self.accelero: raise (NotImplementedError('Accelerometer not implemented')) # subscribes to Giroscope if self.giro: raise (NotImplementedError('Giroscope not implemented'))
def setUp(self): """ Setup the SmartWatch """ self.__bluetooth_adapter = pygatt.GATTToolBackend() self.__bluetooth_adapter.start() # Connect to the device while True: try: self.__bluetooth_device = self.__bluetooth_adapter.connect(smartwatch_MAC, timeout=3) break except pygatt.exceptions.NotConnectedError: print('Waiting...') # Configure message receiver self.__received_messages_processor = ReceivedMessagesProcessor() self.__received_messages_processor.start() self.__bluetooth_device.subscribe("c3e6fea2-e966-1000-8000-be99c223df6a", lambda handler, value: self.__received_messages_processor.add_message(handler, value)) # Configure the device self.__bluetooth_device.char_write_handle(0x15, bytearray([0x00, 0x01]), False) self.__bluetooth_device.char_write_handle(0x12, bytearray( ConfigurePackage(bluetooth_address_of_my_smartwatch).get_package()), False)
def setup(): load_dotenv() global THING_ID, THING_TOKEN, BLUETOOTH_DEVICE_MAC, ADDRESS_TYPE, GATT_CHARACTERISTIC_ORIENTATION, bleAdapter global my_thing, my_property, csvName, dataPath global start_time, dcd_start_time global ad, distance, fbm, collecting collecting = True ADDRESS_TYPE = pygatt.BLEAddressType.random THING_ID = os.environ['THING_ID'] THING_TOKEN = os.environ['THING_TOKEN'] csvName = 'defaultdata.csv' dataPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "defaultdata.csv") #bluetooth max & UUID of gatt service BLUETOOTH_DEVICE_MAC = "F4:36:23:1E:9E:54" GATT_CHARACTERISTIC_ORIENTATION = "02118833-4455-6677-8899-AABBCCDDEEFF" bleAdapter = pygatt.GATTToolBackend() bleAdapter.start() my_thing = Thing(thing_id=THING_ID, token=THING_TOKEN) my_thing.read() my_property = my_thing.find_or_create_property( "Wheelchair Speed", PropertyType.THREE_DIMENSIONS) start_time = time.time() dcd_start_time = datetime.now() ad = analysedata distance = 0 fbm = feedbackmanager
def __init__(self, auth_id=None, key=None, port=None, bgapi=False): self.auth_id = auth_id self.key = key if bgapi: self.adapter = pygatt.BGAPIBackend(serial_port=port) else: self.adapter = pygatt.GATTToolBackend() """ reset_on_start = True retries = 5 while( retries ): retval = self.adapter.start(reset_on_start=reset_on_start) if( None == retval ): log.error('BLEAdapter error: cannot connect to device') retries = retries - 1 self.connected = False else: retries = 0 self.connected = True """ reset_on_start = True try: #retval = self.adapter.start(reset_on_start=reset_on_start) self.adapter.start() self.connected = True except: log.error('BLEAdapter error: cannot start adapter') self.connected = False return
def list_muses(backend='auto', interface=None): backend = helper.resolve_backend(backend) if backend == 'gatt': interface = interface or 'hci0' adapter = pygatt.GATTToolBackend(interface) elif backend == 'bluemuse': print( 'Starting BlueMuse, see BlueMuse window for interactive list of devices.' ) subprocess.call('start bluemuse:', shell=True) return else: adapter = pygatt.BGAPIBackend(serial_port=interface) try: adapter.start() print('Searching for Muses, this may take up to 10 seconds...') devices = adapter.scan(timeout=MUSE_SCAN_TIMEOUT) adapter.stop() except pygatt.exceptions.BLEError as e: if backend == 'gatt': print('pygatt failed to scan for BLE devices. Trying with ' 'bluetoothctl.') return _list_muses_bluetoothctl(MUSE_SCAN_TIMEOUT) else: raise e muses = [d for d in devices if d['name'] and 'Muse' in d['name']] _print_muse_list(muses) return muses
def __init__(self, addr: str = None, adapter: pygatt.GATTToolBackend = None): """ Instantiate the interface. :param addr: A specific address to connect to. :param adapter: An already instantiated `pygatt.GATTToolBackend`. """ if adapter is None: self.adapter = pygatt.GATTToolBackend() self.adapter.start() else: self.adapter = adapter if addr is None: devices = self.adapter.scan() for device in devices: if device["name"] == "Hatch Rest": addr = device["address"] break else: raise RuntimeError( "No address provided and could not find device via scan.") self.device = self.adapter.connect( addr, address_type=pygatt.BLEAddressType.random) self._refresh_data()
def readSensors(sensors): adapter = pygatt.GATTToolBackend() values = [-1] * len(sensors) maxTries = 10 i = 0 adapter.start() while i < maxTries: for index, value in enumerate(values): if value == -1: sensor = sensors[index] try: print("connecting to address:", sensor[1]) device = adapter.connect(sensor[1]) print("reading char:", sensor[2]) reading = int.from_bytes(device.char_read(sensor[2]), "little") print('writing char') device.char_write(sensor[2], bytes(1), wait_for_response=False) print('char written') values[index] = reading except KeyboardInterrupt: exit() except: print("Round:", i, "Failed to read from device:", sensor) i += 1 adapter.stop() return zip([sensor[1] for sensor in sensors], values)
def start_read_insole_rawdata(self, data): self.adapter1 = pygatt.GATTToolBackend(hci_device='hci0') self.adapter1.start(True) self.adapter2 = pygatt.GATTToolBackend(hci_device='hci0') self.adapter2.start(True) self.names[0] = data.name[0].replace("Thorsis Ins. ESS ", "") self.names[1] = data.name[1].replace("Thorsis Ins. ESS ", "") print "Connecting " + self.names[0] + " " + data.address[0] while 1: try: time.sleep(2) self.device1 = self.adapter1.connect(data.address[0], 10) time.sleep(2) break except: print "Error: reconnecting" self.adapter1.disconnect print "Connecting " + self.names[1] + " " + data.address[1] while 1: try: self.device2 = self.adapter2.connect(data.address[1], 10) time.sleep(2) break except: print "Error: reconnecting" self.adapter2.disconnect self.adapter1.sendline('mtu 64') time.sleep(2) self.adapter2.sendline('mtu 64') time.sleep(2) self.callibrateSensor() print "Subscribe " + self.names[0] self.device1.subscribe("00002b00-0000-1000-8000-00805f9b34fb", self.callback_func1) print "Subscribe " + self.names[1] self.device2.subscribe("00002b00-0000-1000-8000-00805f9b34fb", self.callback_func2) print "Subscription for all devices completed" while 1: pass #hier Einstiegspunkt fuer Geraete An- und Abmeldung moeglich