async def print_services(mac_addr: str, service_uuid: str, characteristic_uuid: str, loop: asyncio.AbstractEventLoop): service_flag = 0 char_flag = 0 connect_flag = 0 try: async with BleakClient(mac_addr, loop=loop, timeout=5.0) as client: connect_flag = 1 svcs = client.services for service in svcs: if (service.uuid == service_uuid): print("Service Found!") service_flag = 1 for char in service.characteristics: if (char.uuid == characteristic_uuid): print("Characteristic Found! Read Start") char_flag = 1 read = await client.read_gatt_char( characteristic_uuid) print(read) break except: print("not connected T.T please restart!!!!") if ((not service_flag) and connect_flag): print("There is No Service : " + SERVICE_UUID) if ((not char_flag) and connect_flag): print("There is No CHARACTERISTIC_UUID : " + CHARACTERISTIC_UUID)
async def connect_and_send(data): scanner = BleakScanner() scanner.register_detection_callback(detect_printer) await scanner.start() for x in range(50): await asyncio.sleep(0.1) if device: break await scanner.stop() if not device: raise BleakError(f"No device named GB01 could be found.") async with BleakClient(device) as client: # Set up callback to handle messages from the printer await client.start_notify(NotifyCharacteristic, notification_handler) while (data): # Cut the command stream up into pieces small enough for the printer to handle await client.write_gatt_char(PrinterCharacteristic, data[:PacketLength]) data = data[PacketLength:] while not transmit: # Pause transmission per printer request. # Note: doing it this way does not appear to actually work. await asyncio.sleep(0)
async def run(address): async with BleakClient(address) as client: x = await client.is_connected() await client.start_notify(CHARACTERISTIC_UUID, notification_handler) await asyncio.sleep(460.0) await client.stop_notify(CHARACTERISTIC_UUID)
async def run(self): while True: self.is_connected = False self.gui.status_field.SetLabel( "Looking for Mario. Switch on and press Bluetooth key.") self.gui.cam_field.SetLabel("") self.gui.accel_field.SetLabel("") devices = await BleakScanner.discover() for d in devices: if d.name.lower().startswith( "lego mario" ) or LEGO_SERVICE_UUID in d.metadata['uuids']: self.gui.status_field.SetLabel("Found Mario!") try: async with BleakClient(d.address) as client: await client.is_connected() self.gui.status_field.SetLabel( "Mario is connected") self.is_connected = True await client.start_notify( LEGO_CHARACTERISTIC_UUID, self.notification_handler) await asyncio.sleep(0.1) await client.write_gatt_char( LEGO_CHARACTERISTIC_UUID, SUBSCRIBE_IMU_COMMAND) await asyncio.sleep(0.1) await client.write_gatt_char( LEGO_CHARACTERISTIC_UUID, SUBSCRIBE_RGB_COMMAND) while await client.is_connected(): await self.process_keys() except: pass
async def sendToBoard(): device = await getBLEDevice() print(device) server = osc_server.AsyncIOOSCUDPServer(("127.0.0.1", 57121), dispatch, asyncio.get_event_loop()) transport, protocol = await server.create_serve_endpoint() def exitHandler(): transport.close() atexit.register(exitHandler) async with BleakClient(device) as client: # print(client.get_services) print("Awaiting supercollider commands...") # await client.start_notify(notify_characteristic, callback) isConnected = client.is_connected while isConnected: for i in range(num_servos): if (client.is_connected): if (prevValues[i] != values[i]): print("servo" + str(i) + " value: " + str(bytes_to_int(values[i]))) await client.write_gatt_char(write_characteristics[i], values[i], False) prevValues[i] = values[i] await asyncio.sleep(0.01) else: isConnected = False print("ServoCallback disconnected, reestablishing connection") transport.close() atexit.unregister(exitHandler)
async def run(address, loop, debug=False): if debug: import sys # loop.set_debug(True) # l = logging.getLogger("asyncio") # l.setLevel(logging.DEBUG) # h = logging.StreamHandler(sys.stdout) # h.setLevel(logging.DEBUG) # l.addHandler(h) async with BleakClient(address, loop=loop) as client: x = await client.is_connected() logger.info("Connected: {0}".format(x)) system_id = await client.read_gatt_char(SYSTEM_ID_UUID) print("System ID: {0}".format(":".join( ["{:02x}".format(x) for x in system_id[::-1]]))) model_number = await client.read_gatt_char(MODEL_NBR_UUID) print("Model Number: {0}".format("".join(map(chr, model_number)))) # device_name = await client.read_gatt_char(DEVICE_NAME_UUID) # print("Device Name: {0}".format("".join(map(chr, device_name)))) manufacturer_name = await client.read_gatt_char(MANUFACTURER_NAME_UUID) print("Manufacturer Name: {0}".format("".join( map(chr, manufacturer_name)))) firmware_revision = await client.read_gatt_char(FIRMWARE_REV_UUID) print("Firmware Revision: {0}".format("".join( map(chr, firmware_revision)))) hardware_revision = await client.read_gatt_char(HARDWARE_REV_UUID) print("Hardware Revision: {0}".format("".join( map(chr, hardware_revision)))) software_revision = await client.read_gatt_char(SOFTWARE_REV_UUID) print("Software Revision: {0}".format("".join( map(chr, software_revision)))) battery_level = await client.read_gatt_char(BATTERY_LEVEL_UUID) print("Battery Level: {0}%".format(int(battery_level[0]))) def keypress_handler(sender, data): print("{0}: {1}".format(sender, data)) write_value = bytearray([0xa0]) value = await client.read_gatt_char(IO_DATA_CHAR_UUID) print("I/O Data Pre-Write Value: {0}".format(value)) await client.write_gatt_char(IO_DATA_CHAR_UUID, write_value) value = await client.read_gatt_char(IO_DATA_CHAR_UUID) print("I/O Data Post-Write Value: {0}".format(value)) assert value == write_value await client.start_notify(KEY_PRESS_UUID, keypress_handler) await asyncio.sleep(5.0, loop=loop) await client.stop_notify(KEY_PRESS_UUID)
async def print_services(mac_addr: str): device = await BleakScanner.find_device_by_address(mac_addr) async with BleakClient(device) as client: svcs = await client.get_services() print("Services:") for service in svcs: print(service)
async def uart_terminal(): def handle_disconnect(_: BleakClient): print("Device was disconnected, goodbye.") # cancelling all tasks effectively ends the program for task in asyncio.all_tasks(): task.cancel() def handle_rx(_: int, data: bytearray): print(f"received: {data.decode()}", end='') device = await BleakScanner.find_device_by_address('E4:B6:8E:F3:A0:2E', timeout=20.0) if not device: raise BleakError('Device not found') async with BleakClient(device, disconnected_callback=handle_disconnect) as client: await client.start_notify(UART_TX_CHAR_UUID, handle_rx) svcs = await client.get_services() print("Services:") for service in svcs: print(service) data = b'Hello!\n' await client.write_gatt_char(UART_RX_CHAR_UUID, data, True) print("sent:", data) await asyncio.sleep(5)
async def run(address, loop): print("Discovering") devices=await discover() target=None for d in devices: print(d.address,d.name,d.rssi) print(d) if 'SPRE' in d.name: target=d break if target is None: print('SPRESENSE not found') return print(target.name) print("Connecting",target.address) async with BleakClient(target.address) as client: log = logging.getLogger(__name__) log.info(f"Connected: {client.is_connected}") # model_number = await client.read_gatt_char(MODEL_NBR_UUID) # print("Model Number: {0}".format("".join(map(chr, model_number)))) print("Pairing") paired = await client.pair(protection_level=2) log.info(f"Paired: {paired}") for n in range(5): print("Writing") # await client.write_gatt_char(CWR_UUID,b'$18F00115002552553E;') await client.write_gatt_char(CWR_UUID,b'SF I100 C120') time.sleep(0.1)
async def run(address, loop): async with BleakClient(address, loop=loop) as client: # await client.connect() print(await client.is_connected()) print(await client.get_services()) services = await client.get_services() pprint(services.descriptors) pprint(services.characteristics) pprint(services.services) # print(services.descriptors) # for key, val in services.descriptors.items(): # print(f"{key} + {val}") # # print(services.characteristics) # for key, val in services.characteristics.items(): # print(f"{key} + {val}") print(services) for x in services: print(x) for characteristic in x.characteristics: print("") print(characteristic) print(characteristic.properties) for descriptor in characteristic.descriptors: print(descriptor) print(x.description)
async def getFile_coroutine(address, loop): async with BleakClient(address, loop=loop) as client: print("Connected") await client.start_notify(UUID_NORDIC_RX, uart_data_received) print("Writing command") c = getFileCommand while len(c) > 0: await client.write_gatt_char(UUID_NORDIC_TX, bytearray(c[0:20]), True) c = c[20:] global dataReceived await asyncio.sleep(30.0, loop=loop) # wait for a response dataReceived = datetime.now() lastDataReceivedDelta = datetime.now() - dataReceived print("Data last recieved: " + str(dataReceived) + " Delta:" + str(lastDataReceivedDelta.seconds)) while (lastDataReceivedDelta.seconds < transferTimeout): await asyncio.sleep(transferTimeout, loop=loop) # wait for a response lastDataReceivedDelta = datetime.now() - dataReceived print("Data last recieved: " + str(dataReceived) + " Delta:" + str(lastDataReceivedDelta.seconds)) now = datetime.now() global fileName fileName = "ftclog-" + now.strftime( "%Y-%m-%d-%H-%M-%S") #-%Y-%m-%d-%H-%M-%S" f = open(fileName + ".csv", 'w') f.write(line)
async def _print(): global _taskQueue if _address == "": raise RuntimeError("No Printer address set.") device = await BleakScanner.find_device_by_address(_address, timeout=20.0) if not device: raise BleakError( f"No device with address {_address} could not be found.") async with BleakClient(device) as client: # Set energy used to a moderate level await client.write_gatt_char(PrinterCharacteristic, formatMessage(SetEnergy, [0x10, 0x00])) # Set print quality to high await client.write_gatt_char(PrinterCharacteristic, formatMessage(SetQuality, [5])) # Set mode to image mode await client.write_gatt_char(PrinterCharacteristic, formatMessage(DrawingMode, [0])) for task in _taskQueue: await task(client) time.sleep(0.1) clearQueue()
async def run(address): async with BleakClient(address) as client: while 1: await client.write_gatt_char(RED_LED_UUID, b'\x01') await client.write_gatt_char(GREEN_LED_UUID, b'\x00') time.sleep(1) await client.write_gatt_char(RED_LED_UUID, b'\x01') await client.write_gatt_char(GREEN_LED_UUID, b'\x01') time.sleep(1) await client.write_gatt_char(RED_LED_UUID, b'\x00') await client.write_gatt_char(GREEN_LED_UUID, b'\x01') time.sleep(1) await client.write_gatt_char(RED_LED_UUID, b'\x00') await client.write_gatt_char(GREEN_LED_UUID, b'\x00') time.sleep(1)
async def print_services(mac_addr: str): async with BleakClient(mac_addr) as client: svcs = await client.get_services() for s in svcs: print(s) for c in s.characteristics: print(c.uuid)
async def loop_setup(self): if (self.mac_address == ""): print("No mac address set for Polar") return if (self.connecting == True): print("Already connecting") return self.connecting = True try: print("Polar ({}): try connect...".format(self.mac_address)) self.client = BleakClient(self.mac_address) await self.client.__aenter__() #await self.printServices(self.client) print("Polar ({}): connected".format(self.mac_address)) except BleakError as e: print("Polar ({}): failed to connect\n{}".format( self.mac_address, e)) try: self.connected = await self.client.is_connected() except: pass if (self.connected): await self.start_notify() self.connecting = False
async def connect(client=None): """Attempt to connect to the desk""" # Attempt to load and connect to the pickled desk desk = unpickle_desk() if desk: pickled = True if not desk: # If that fails then rescan for the desk desk = await scan(config['mac_address']) if not desk: print('Could not find desk {}'.format(config['mac_address'])) os._exit(1) # Cache the Bleak device config to connect more quickly in future pickle_desk(desk) try: print('Connecting\r', end="") if not client: client = BleakClient(desk, device=config['adapter_name']) await client.connect(timeout=config['connection_timeout']) print("Connected {}".format(config['mac_address'])) return client except BleakError as e: if pickled: # Could be a bad pickle so remove it and try again try: os.remove(PICKLE_FILE) print('Connecting failed - Retrying without cached connection') except OSError: pass return await connect() else: print('Connecting failed') print(e) os._exit(1)
async def run(address): client = BleakClient(address) try: await client.connect() print("Connceted!") rx_char = client.services.get_characteristic( "8ba86974-935c-447c-91ad-bdcbad575f31") while True: color = input("input color hex:") if len(color) != 6: print('invalid hex length') continue try: hexcode = int(color, 16) await client.write_gatt_char(rx_char, color.encode('utf-8')) except ValueError: print("invalid hex string") time.sleep(1) except Exception as e: print(e) finally: await client.disconnect()
async def run_init(address): async with BleakClient(address) as client: logger.info(f"[*] Connected: {await client.is_connected()}") logger.info("[*] Reading Device Info...") system_id = await client.read_gatt_char(SYSTEM_ID_UUID) system_id = ":".join(["{:02x}".format(x) for x in system_id[::-1]]) logger.info("[+] System ID: " + system_id) model_number = ( await client.read_gatt_char(MODEL_NBR_UUID)).decode().rstrip("\x00") logger.info("[+] Model Number: " + model_number) device_name = ( await client.read_gatt_char(DEVICE_NAME_UUID)).decode().rstrip("\x00") logger.info("[+] Device Name: " + device_name) manufacturer_name = (await client.read_gatt_char(MANUFACTURER_NAME_UUID) ).decode().rstrip("\x00") logger.info("[+] Manufacturer Name: " + manufacturer_name) firmware_revision = ( await client.read_gatt_char(FIRMWARE_REV_UUID)).decode().rstrip("\x00") logger.info("[+] Firmware Revision: " + firmware_revision) hardware_revision = ( await client.read_gatt_char(HARDWARE_REV_UUID)).decode().rstrip("\x00") logger.info("[+] Hardware Revision: " + hardware_revision) software_revision = ( await client.read_gatt_char(SOFTWARE_REV_UUID)).decode().rstrip("\x00") logger.info("[+] Software Revision: " + software_revision) return (system_id, model_number, manufacturer_name, firmware_revision, hardware_revision, software_revision)
async def main(): queue = asyncio.Queue() def callback(device: BLEDevice, adv: AdvertisementData) -> None: # can use advertising data to filter here queue.put_nowait(device) async with BleakScanner(detection_callback=callback): # get the first matching device device = await queue.get() async with BleakClient(device) as client: # BlueZ doesn't have a proper way to get the MTU, so we have this hack. # If this doesn't work for you, you can set the client._mtu_size attribute # to override the value instead. if client.__class__.__name__ == "BleakClientBlueZDBus": await client._acquire_mtu() print("MTU:", client.mtu_size) # Write without response is limited to MTU - 3 bytes data = bytes(1000) # replace with real data chunk_size = client.mtu_size - 3 for chunk in (data[i:i + chunk_size] for i in range(0, len(data), chunk_size)): await client.write_gatt_char(CHAR_UUID, chunk)