Пример #1
0
async def scan():
    try:
        cm = CentralManager()
        print('Scanning for BLE devices...')
        print('Starting')
        await cm.start_scan(callback)
        #await cm.start_scan(callback, service_uuids=["fe59"])
        await asyncio.sleep(5)
        print('Stopping')
        await cm.stop_scan()
    except Exception as e:
        print(f'Exception: {e}')
Пример #2
0
async def connect_one():
    try:
        # Find Device
        cm_10 = CentralManager()
        await cm_10.start_scan(scan_callback_10)

        while d_10_device is None:
            await asyncio.sleep(.1)

        await cm_10.stop_scan()

        # Create Device
        d_10 = Device(d_10_device)

        d_10.connect_succeeded = connect_callback_10
        d_10.disconnect_succeeded = disconnect_callback_10
        d_10.services_resolved = services_resolved_10

        print('Connecting')

        try:
            await asyncio.wait_for(d_10.connect(), TIMEOUT_SEC)
        except asyncio.TimeoutError:
            raise Exception("Device was not found.")
            print('Disconnecting')
            await d_10.disconnect()

        is_d_10 = await d_10.is_connected()
        print(f'Connected_10: {is_d_10}')

        print('Writing Char')
        await d_10.write_char(TEST_WRITE_CHARACTERISTIC, WRITE_CHAR_TEST)

        print('Reading Char')
        print(await d_10.read_char(TEST_WRITE_CHARACTERISTIC))

        print('Starting Notify')
        await d_10.start_notify(TEST_NOTIFY_CHARACTERISTIC, notify_callback_10)

        await asyncio.sleep(5)

        print('Stopping Notify')
        await d_10.stop_notify(TEST_NOTIFY_CHARACTERISTIC)

        print('Disconnecting')
        await d_10.disconnect()

        is_d_10 = await d_10.is_connected()
        print(f'Connected_10: {is_d_10}')

    except Exception as ex:
        print(f"Exception, Failed to Connect: {ex}")
Пример #3
0
async def read_descr():
    try:
        # Find Device
        cm = CentralManager()
        await cm.start_scan(scan_callback)

        while d_device is None:
            await asyncio.sleep(0.1)

        await cm.stop_scan()

        # Create Device
        d = Device(d_device)

        d.connect_succeeded = connect_callback
        d.disconnect_succeeded = disconnect_callback
        d.services_resolved = services_resolved

        print("Connecting")

        try:
            await asyncio.wait_for(d.connect(), TIMEOUT_SEC)
        except asyncio.TimeoutError:
            raise Exception("Device was not found.")
            print("Disconnecting")
            await d.disconnect()

        is_d = await d.is_connected()
        print(f"Connected_10: {is_d}")

        print("\n[%s] \nResolved services" % (d.address))
        for service in d.services:
            print("\tService [%s]" % (service.uuid))
            for characteristic in service.characteristics:
                print("\t\tCharacteristic [%s]" % (characteristic.uuid))
                for descriptor in characteristic.descriptors:
                    value = await descriptor.read_value()
                    print("\t\t\tDescriptor [%s] (%s)" %
                          (descriptor.uuid, value))

        print("Disconnecting")
        await d.disconnect()

        is_d = await d.is_connected()
        print(f"Connected_10: {is_d}")

    except Exception as ex:
        print(f"Exception, Failed to Connect: {ex}")
Пример #4
0
    async def activate_dfu_buttonless(self):
        # Find Device
        cm = CentralManager()
        await cm.start_scan(self.scan_callback_app)

        while self.device_found_app is None:
            await asyncio.sleep(.1)

        await cm.stop_scan()

        device = Device(self.device_found_app)

        print('Connecting')

        try:
            await asyncio.wait_for(device.connect(), TIMEOUT_SEC)
        except asyncio.TimeoutError:
            raise Exception("Device was not found.")
            print('Disconnecting')
            await device.disconnect()

        is_c = await device.is_connected()
        print(f'Connected: {is_c}')

        def notify_callback(sender, data):
            # print(data)
            data_hex = [hex(x) for x in data]
            print(data_hex)

            # self.max_size = int.from_bytes(data[0:4], byteorder='little', signed=False)
            # self.offset = int.from_bytes(data[4:8], byteorder='little', signed=False)
            # self.crc = int.from_bytes(data[8:12], byteorder='little', signed=False)
            #
            # # print(f'{sender}: {values}')
            # print('max_size: {0} offset: {1} crc: {2}'.format(self.max_size, self.offset, self.crc))
            #
            # print('crc32: {0}'.format(binascii.crc32(bytearray(self.f_init_data))))

        # Setup Button Notify for Response Message
        await device.start_notify(BUTTON_UUID, notify_callback)

        # Write Buttonless DFU Char
        print('Activating Buttonless DFU')
        await device.write_char(BUTTON_UUID,
                                bytearray(OPERATIONS['BUTTON_COMMAND']))
Пример #5
0
    async def connect_dfu_bootloader(self):
        # Find Device
        cm = CentralManager()
        await cm.start_scan(self.scan_callback_bl, service_uuids=[NORDIC_UUID])

        while self.device_found_bl is None:
            await asyncio.sleep(.1)

        await cm.stop_scan()

        self.am = Device(self.device_found_bl)

        print('Connecting')

        try:
            await asyncio.wait_for(self.am.connect(), TIMEOUT_SEC)
        except asyncio.TimeoutError:
            raise Exception("Device was not found.")
            print('Disconnecting')
            await am.disconnect()

        is_c = await self.am.is_connected()
        print(f'Connected: {is_c}')

        def notify_callback(sender, data):
            data_hex = [hex(x) for x in data]
            print(data_hex)

            if hex(data[1]) == '0x6':
                print("data[1]: {0}".format(hex(data[1])))
                self.max_size = int.from_bytes(data[3:7],
                                               byteorder='little',
                                               signed=False)
                self.offset = int.from_bytes(data[7:11],
                                             byteorder='little',
                                             signed=False)
                self.crc = int.from_bytes(data[11:15],
                                          byteorder='little',
                                          signed=False)
                print('max_size: {0} offset: {1} crc: {2}'.format(
                    self.max_size, self.offset, self.crc))
            elif hex(data[1]) == '0x3':
                print("data[1]: {0}".format(hex(data[1])))
                self.transferred = int.from_bytes(data[3:7],
                                                  byteorder='little',
                                                  signed=False)
                self.crc = int.from_bytes(data[7:11],
                                          byteorder='little',
                                          signed=False)
                print('transferred: {0} crc: {1}'.format(
                    self.transferred, self.crc))

        # Setup Control Notifications
        await self.am.start_notify(CONTROL_UUID, notify_callback)

        # INIT - SELECT COMMAND
        await self.am.write_char(CONTROL_UUID,
                                 bytearray(OPERATIONS['SELECT_COMMAND']))

        await asyncio.sleep(0.2)

        await self.transferObjectInit()

        await asyncio.sleep(0.2)

        # INIT - SELECT COMMAND
        print("SELECT DATA")
        await self.am.write_char(CONTROL_UUID,
                                 bytearray(OPERATIONS['SELECT_DATA']))

        await asyncio.sleep(0.2)

        await self.transferObjectData()

        await asyncio.sleep(0.2)

        print('Disconnecting')
        await self.am.disconnect()
Пример #6
0
async def connect_two():
    try:
        # Find Devices
        cm_all = CentralManager()
        await cm_all.start_scan(scan_callback_all)

        while d_10_device is None or d_5_device is None:
            await asyncio.sleep(.1)

        await cm_all.stop_scan()

        print(d_10_device)
        print(d_5_device)

        # Create Devices
        d_10 = Device(d_10_device)
        d_5 = Device(d_5_device)

        d_10.connect_succeeded = connect_callback_10
        d_10.disconnect_succeeded = disconnect_callback_10
        d_10.services_resolved = services_resolved_10

        d_5.connect_succeeded = connect_callback_5
        d_5.disconnect_succeeded = disconnect_callback_5
        d_5.services_resolved = services_resolved_5

        print('Connecting')
        tasks = [d_10.connect(), d_5.connect()]
        done, pending = await asyncio.wait(tasks, timeout=TIMEOUT_SEC, return_when=asyncio.ALL_COMPLETED)

        if pending:
            raise Exception("Could not connect to both devices.")

        is_d_10 = await d_10.is_connected()
        is_d_5 = await d_5.is_connected()
        print(f'Connected_10: {is_d_10} Connected_5: {is_d_5}')

        print('Writing Char')
        await d_10.write_char(TEST_WRITE_CHARACTERISTIC, WRITE_CHAR_TEST)
        await d_5.write_char(TEST_WRITE_CHARACTERISTIC, WRITE_CHAR_TEST)

        print('Reading Char')
        print(await d_10.read_char(TEST_WRITE_CHARACTERISTIC))
        print(await d_5.read_char(TEST_WRITE_CHARACTERISTIC))

        print('Starting Notify')
        await d_5.start_notify(TEST_NOTIFY_CHARACTERISTIC, notify_callback_5)
        await d_10.start_notify(TEST_NOTIFY_CHARACTERISTIC, notify_callback_10)

        await asyncio.sleep(5)

        print('Stopping Notify')
        await d_5.stop_notify(TEST_NOTIFY_CHARACTERISTIC)
        await d_10.stop_notify(TEST_NOTIFY_CHARACTERISTIC)

        print('Disconnecting')
        await d_10.disconnect()
        await d_5.disconnect()

        is_d_10 = await d_10.is_connected()
        is_d_5 = await d_5.is_connected()
        print(f'Connected_10: {is_d_10} Connected_5: {is_d_5}')

    except Exception as ex:
        print(f"Exception, Failed to Connect: {ex}")
Пример #7
0
async def test_centralmanager(event_loop: asyncio.AbstractEventLoop):
    manager = CentralManager()
    await manager.start_scan(callback)
    await asyncio.sleep(5)
    assert manager is not None
    assert devices.__len__() == 0