Example #1
0
 def get_mac_addr(self) -> str:
     try:
         with Popen(["bt-device", "--list"], stdout=PIPE,
                    text=True) as btdevice_process:
             exit_code = btdevice_process.wait()
             if exit_code:
                 raise ConnectionError("Failed to find any TAP decive")
             connected_bt_devices = btdevice_process.stdout.read(
             ).splitlines()
             tap_devices = list(
                 filter(lambda line: line.startswith("Tap_"),
                        connected_bt_devices))
             for d in tap_devices:
                 logger.info("Found tap device: {}".format(d))
             if len(tap_devices) > 1:
                 raise ValueError(
                     "Found more than 1 Tap device. Set the MAC address of the device you want to connect to "
                     "and try again.")
             if len(tap_devices) == 0:
                 raise ValueError(
                     "No Tap device was found. Make sure the device is connected and its human readable name "
                     "starts with Tap_.")
             device_decs = tap_devices[0]
             tap_mac_address = device_decs[
                 -18:-1]  # only the mac_address part of the description.
             return tap_mac_address
     except Exception as e:
         logger.error("Failed to find any TAP device: {}".format(e))
         raise e
Example #2
0
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, timeout=1.0, loop=loop) as client:

        queue = asyncio.Queue()

        def keypress_handler(sender, data):

            print('{}'.format(data.decode('ascii')), end='', flush=True)
            queue.put_nowait(data)

        x = await client.is_connected()
        logger.info("Connected: {0}".format(x))
        current_string = ""
        await client.start_notify(RX_UUID, keypress_handler)
        while (1):
            await asyncio.sleep(0.1, loop=loop)
            try:
                send_data = queue.get_nowait()
                await client.write_gatt_char(TX_UUID, send_data)
            except:
                pass
        await client.stop_notify(RX_UUID)
Example #3
0
async def run(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.INFO)
        l.addHandler(h)
        logger.addHandler(h)

    client = TapSDK(loop)
    # devices = await client.list_connected_taps()
    x = await client.manager.connect_retrieved()
    x = await client.manager.is_connected()
    logger.info("Connected: {0}".format(x))

    await client.set_input_mode(TapInputMode("controller"))

    await client.register_air_gesture_events(OnGesture)
    await client.register_tap_events(OnTapped)
    # await client.register_raw_data_events(OnRawData)
    await client.register_mouse_events(OnMoused)
    await client.register_air_gesture_state_events(OnMouseModeChange)

    await asyncio.sleep(3)
    # await client.set_input_mode(TapInputMode("raw", sensitivity=[0,0,0]))
    # await asyncio.sleep(3)
    # await client.set_input_mode(TapInputMode("text"))
    # await asyncio.sleep(3)
    # await client.set_input_mode(TapInputMode("raw", sensitivity=[2,2,2]))
    # await client.send_vibration_sequence([100, 200, 300, 400, 500])

    await asyncio.sleep(50.0, loop=loop)
Example #4
0
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)
Example #5
0
async def run():
    devices = await discover()
    addresses = []
    for d in devices:
        if d.metadata['uuids'] is not None:
            if service_uuid in d.metadata['uuids']:
                print(d.__dict__.keys())
                addresses.append(d.address)

    # async with BleakClient(address, loop=loop) as client:
    address = addresses[0]
    for address in addresses:
        print('*'*80)
        print('address', address)
        async with BleakClient(address) as client:
            x = await client.is_connected()
            logger.info("Connected: {0}".format(x))

            c = await client.read_gatt_char(rw_uuid)
            print('c: ',c)
            count = await client.read_gatt_char(count_uuid)
            print('count', count, int.from_bytes(bytes(count), byteorder='little'))

            await client.start_notify(data_uuid, notification_handler)
            await client.write_gatt_char(rw_uuid, bytearray(b'f'))
            await asyncio.sleep(15.0, loop=loop)
            await client.stop_notify(data_uuid)
Example #6
0
async def run(loop=None, debug=False):
    if debug:
        import sys

        loop.set_debug(True)
        h = logging.StreamHandler(sys.stdout)
        h.setLevel(logging.WARNING)
        logger.addHandler(h)

    client = TapSDK(None, loop)
    if not await client.client.connect_retrieved():
        logger.error("Failed to connect the the Device.")
        return

    logger.info("Connected to {}".format(client.client.address))

    await client.set_input_mode(TapInputMode("controller"))

    await client.register_air_gesture_events(OnGesture)
    await client.register_tap_events(OnTapped)
    await client.register_raw_data_events(OnRawData)
    await client.register_mouse_events(OnMoused)
    await client.register_air_gesture_state_events(OnMouseModeChange)

    # logger.info("Changing to text mode")
    await client.set_input_mode(TapInputMode("text"))
    # await asyncio.sleep(30))
    logger.info("Changing to raw mode")
    await client.set_input_mode(TapInputMode("raw"))
    # await client.send_vibration_sequence([100, 200, 300, 400, 500])

    await asyncio.sleep(50.0, loop=loop)
Example #7
0
 async def connect_retrieved(self, **kwargs) -> bool:
     await self.connect()
     connected = await self.is_connected()
     if connected:
         logger.info("Connected to {0}".format(self.address))
         await self.__debug()
     else:
         logger.error("Failed to connect to {0}".format(self.address))
     return connected
Example #8
0
async def sensortag_com_handler(address, debug=False):
    device = await BleakScanner.find_device_by_address(address)
    if not device:
        print("Could not find device with address {}".format(address))
        return

    async with BleakClient(address) 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))))

        try:
            device_name = await client.read_gatt_char(DEVICE_NAME_UUID)
            print("Device Name: {0}".format("".join(map(chr, device_name))))
        except Exception:
            pass

        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])))

        # activate temp/humid sensor
        write_value = bytearray([0x01])
        await client.write_gatt_char(TEMP_CONFIG_CHAR_UUID, write_value)

        # subscribe
        await client.start_notify(TEMP_CHAR_UUID, notification_handler)

        while True:
            await asyncio.sleep(1.0)
Example #9
0
    async def connect(self, debug=False):
        if debug:
            import sys
            l = logging.getLogger("asyncio")
            l.setLevel(logging.DEBUG)
            h = logging.StreamHandler(sys.stdout)
            h.setLevel(logging.DEBUG)
            l.addHandler(h)
            logger.addHandler(h)

        self.client = BleakClient(self.wand_address, loop=self.loop)
        await self.client.connect()
        x = await self.client.is_connected()
        logger.info("Connected: {0}".format(x))
async def run(address, loop, debug=False):
    if debug:
        import sys
        l = logging.getLogger("asyncio")
        l.setLevel(logging.DEBUG)
        h = logging.StreamHandler(sys.stdout)
        h.setLevel(logging.DEBUG)
        l.addHandler(h)
        logger.addHandler(h)
    async with BleakClient(address, loop=loop) as client:
        x = await client.is_connected()
        logger.info("Connected: {0}".format(x))
        await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
        await asyncio.sleep(60.0, loop=loop)
        await client.stop_notify(CHARACTERISTIC_UUID)
Example #11
0
def temp_handler(sender, data):
    global temp
    type = int(data[0])
    count = int(data[1])
    channel2 = int(data[2])
    temperature = int(data[3]) - 40
    humidity = int(data[4])
    if count == 1:
        logger.info(
            "[+] DATA: type={}, count={} (CURRENT), channel2={}, TEMPERATURE={}℃ , HUMIDITY={}%"
            .format(type, count, channel2, temperature, humidity))
        temp = (temperature, humidity)
    else:
        logger.info(
            "[+] DATA: type={}, count={} (archive), channel2={}, temperature={}℃ , humidity={}%"
            .format(type, count, channel2, temperature, humidity))
async def run(address, debug=False):
    global stream
    if debug:
        l = logging.getLogger("asyncio")
        l.setLevel(logging.DEBUG)
        h = logging.StreamHandler(sys.stdout)
        h.setLevel(logging.DEBUG)
        l.addHandler(h)
        logger.addHandler(h)

    print("Trying to connect...")
    async with BleakClient(address) as client:
        x = await client.is_connected()
        logger.info("Connected to: {0}".format(x))

        await client.start_notify(SHORT_PATH_CHAR_UUID, notification_handler)
        await client.start_notify(LONG_PATH_CHAR_UUID, notification_handler)
        while stream:
            await asyncio.sleep(0.1)
        await client.stop_notify(CHARACTERISTIC_UUID)
Example #13
0
 async def __debug(self):
     for service in self.services:
         logger.info("[service] {}: {}".format(service.uuid,
                                               service.description))
         for char in service.characteristics:
             if "read" in char.properties:
                 try:
                     value = bytes(await self.read_gatt_char(char.uuid))
                 except Exception as e:
                     value = str(e).encode
             else:
                 value = None
             # if value:
             logger.info(
                 "\t[Characteristic] {0}: (Handle: {1}) ({2}) | Name: {3}, Value: {4} "
                 .format(
                     char.uuid,
                     "<handle geos here>",  # char.handle,
                     ",".join(char.properties),
                     char.description,
                     value,
                 ))
Example #14
0
def OnRawData(identifier, *packets):
    identifier = ""
    imu_msg = dict([m for m in packets if m.get("type") == "imu"][0])
    if len(imu_msg) > 0:
        OnRawData.cnt += 1
        if OnRawData.cnt == 10:
            OnRawData.cnt = 0
            logger.info(identifier + " raw imu : " + str(imu_msg["ts"]))

    for m in packets:
        if m.get("type") == "imu":
            # print("imu")
            print(
                "imu, " + "{:.3f}".format(time.time()) + ", " +
                str(list(map(lambda x: "{:7d}".format(x), m.get("payload")))))
            OnRawData.imu_cnt += 1
            if OnRawData.imu_cnt == 208:
                OnRawData.imu_cnt = 0
                # print("imu, " + str(time.time()) + ", " + str(m.get("payload")))
        if m.get("type") == "accl":
            # print("accl")
            OnRawData.accl_cnt += 1
            if OnRawData.accl_cnt == 200:
                OnRawData.accl_cnt = 0
Example #15
0
async def run(address):
    async with BleakClient(address) as client:
        logger.info(f"[*] Connected: {await client.is_connected()}")
        logger.info("[*] Reading Measurement Data")
        battery_level = int((await
                             client.read_gatt_char(BATTERY_LEVEL_UUID))[0])
        logger.info("[+] Battery Level: {0}%".format(battery_level))
        while True:
            await client.start_notify(TEMP_NOTIFY_UUID, temp_handler)
            await asyncio.sleep(1.0)
        # await client.stop_notify(TEMP_NOTIFY_UUID)
    return temp
Example #16
0
    logging.addLevelName(LOG_DATA, "DATA")
    logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',
                        level=LOG_DATA,
                        datefmt='%Y-%m-%d %H:%M:%S')

    logger.setLevel(logging.INFO)

    succeeded = False
    while not succeeded:
        try:
            loop = asyncio.get_event_loop()
            ret = loop.run_until_complete(run_init(address))
            succeeded = True
        except:
            logger.info("[!] Connection Error!")

    logger.log(LOG_DATA, ret)

    readagain = True
    while (loopdelay >= 0):
        while readagain:
            try:
                loop = asyncio.get_event_loop()
                ret = loop.run_until_complete(run(address))
                readagain = False
            except:
                logger.info("[!] Connection Error!")
        readagain = True
        logger.log(LOG_DATA, ret)
        logger.info(
Example #17
0
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)
Example #18
0
async def run_specific_device_leaf(addr, debug=False):

    global rxed_data
    global rxed_data_2
    global dev_list
    global do_dev_list
    global is_leaf_locked
    global trigger_size

    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)
        logger.addHandler(h)

    # Do an initial connection to wake it up
    #async with bleak.BleakClient(addr) as client:
    #    x = await client.is_connected()
    #    l.info("Connected: {0}".format(x))

    #await asyncio.sleep(40.0)

    # Now do the connection where we lock and read data
    async with bleak.BleakClient(addr) as client:
        x = await client.is_connected()
        l.info("Connected: {0}".format(x))
        y = await client.get_services()
        y_serv = y.get_service(SERVICE_UUID.lower())
        l.info(y_serv)
        y_char = y.get_characteristic(READ_CHAR_UUID.lower())
        l.info(y_char)
        l.info(y_char.service_uuid)

        await client.start_notify(READ_CHAR_UUID, notification_handler_leaf)

        if False:
            #await client.write_gatt_char(WRITE_CHAR_UUID, bytearray(struct.pack('<2I', INSTRUCTION_CODE__IDENTIFY_SELF, 0)))  # no data, just send 0
            #await asyncio.sleep(2.0)

            await client.write_gatt_char(
                WRITE_CHAR_UUID,
                bytearray(
                    struct.pack('<2I', INSTRUCTION_CODE__QUERY_IS_SYNCED,
                                0)))  # no data, just send 0
            await asyncio.sleep(0.2)

        else:

            #  #await client.write_gatt_char(WRITE_CHAR_UUID, bytearray([0xe,0,0,0,0xff,0xff,0xff,0xff]))
            await client.write_gatt_char(
                WRITE_CHAR_UUID,
                bytearray(
                    struct.pack('<2I', INSTRUCTION_CODE__QUERY_IS_SYNCED,
                                0)))  # no data, just send 0
            await asyncio.sleep(0.2)
            await client.write_gatt_char(
                WRITE_CHAR_UUID,
                bytearray(
                    struct.pack('<2I', INSTRUCTION_CODE__QUERY_CURRENT_TIME,
                                0)))  # no data, just send 0
            await asyncio.sleep(0.2)
            await client.write_gatt_char(
                WRITE_CHAR_UUID,
                bytearray(struct.pack('<2I', INSTRUCTION_CODE__IS_LOCKED,
                                      0)))  # no data, just send 0
            await asyncio.sleep(0.2)

            #await client.write_gatt_char(WRITE_CHAR_UUID, bytearray(struct.pack('<2I', INSTRUCTION_CODE__LOCK, 0xFFFFFFFF)))  # 0xFFFFFFFF means current time
            #await asyncio.sleep(0.4)
            await client.write_gatt_char(
                WRITE_CHAR_UUID,
                bytearray(struct.pack('<2I', INSTRUCTION_CODE__IS_LOCKED,
                                      0)))  # no data, just send 0
            await asyncio.sleep(
                5.)  # Need to give sufficient time for the buffer to fill up.
            # If not sufficient, nothing will be returned

            rxed_data = b''

            #await client.write_gatt_char(WRITE_CHAR_UUID, bytearray(struct.pack('<2I', INSTRUCTION_CODE__READ_OUT, 0)))  # no data, just send 0
            #await asyncio.sleep(0.2)

        a = 0
        kk = 0
        while a < 1000:
            await asyncio.sleep(1.0)

            if do_dev_list:
                do_dev_list = False
                for dd in dev_list:
                    async with bleak.BleakClient(dd) as client_2:
                        x_2 = await client.is_connected()
                        l.info("Connected: {0}".format(x_2))
                        await client_2.start_notify(
                            READ_CHAR_UUID, notification_handler_leaf_2)
                        await asyncio.sleep(1.2)
                        await client_2.write_gatt_char(
                            WRITE_CHAR_UUID,
                            bytearray(
                                struct.pack('<2I',
                                            INSTRUCTION_CODE__QUERY_IS_SYNCED,
                                            0)))  # no data, just send 0
                        await asyncio.sleep(0.2)
                        await client_2.write_gatt_char(
                            WRITE_CHAR_UUID,
                            bytearray(
                                struct.pack(
                                    '<2I',
                                    INSTRUCTION_CODE__QUERY_CURRENT_TIME,
                                    0)))  # no data, just send 0
                        await asyncio.sleep(0.2)
                        await client_2.write_gatt_char(
                            WRITE_CHAR_UUID,
                            bytearray(
                                struct.pack('<2I', INSTRUCTION_CODE__IS_LOCKED,
                                            0)))  # no data, just send 0
                        await asyncio.sleep(0.4)

                        await client_2.stop_notify(READ_CHAR_UUID)

                        z_2 = await client_2.disconnect()
                        l.info("Disconnected: {0}".format(z_2))
            if trigger_size > 0:
                with open("Trigger_list.txt", "a") as f3:
                    f3.write(datetime.datetime.now().strftime(
                        "%Y/%m/%d %H:%M:%S  ") +
                             "{0}   {1}\n".format(trigger_size, len(dev_list)))
                trigger_size = 0
                for dd in dev_list:
                    async with bleak.BleakClient(dd) as client_2:
                        x_2 = await client.is_connected()
                        l.info("Connected: {0}".format(x_2))
                        await client_2.start_notify(
                            READ_CHAR_UUID, notification_handler_leaf_2)
                        await asyncio.sleep(1.2)
                        await client_2.write_gatt_char(
                            WRITE_CHAR_UUID,
                            bytearray(
                                struct.pack('<2I',
                                            INSTRUCTION_CODE__QUERY_IS_SYNCED,
                                            0)))  # no data, just send 0
                        await asyncio.sleep(0.2)
                        await client_2.write_gatt_char(
                            WRITE_CHAR_UUID,
                            bytearray(
                                struct.pack(
                                    '<2I',
                                    INSTRUCTION_CODE__QUERY_CURRENT_TIME,
                                    0)))  # no data, just send 0
                        await asyncio.sleep(0.2)
                        is_leaf_locked = False
                        await client_2.write_gatt_char(
                            WRITE_CHAR_UUID,
                            bytearray(
                                struct.pack('<2I', INSTRUCTION_CODE__IS_LOCKED,
                                            0)))  # no data, just send 0
                        await asyncio.sleep(0.4)
                        if is_leaf_locked:
                            rxed_data_2 = b''
                            await client_2.write_gatt_char(
                                WRITE_CHAR_UUID,
                                bytearray(
                                    struct.pack('<2I',
                                                INSTRUCTION_CODE__READ_OUT,
                                                0)))  # no data, just send 0
                            await asyncio.sleep(5.2)
                            if len(rxed_data_2) > 0:
                                with open(
                                        datetime.datetime.now().strftime(
                                            "%Y%m%d_%H%M%S_") +
                                        "{0:03d}_".format(kk) + dd + ".bin",
                                        "wb") as f1:
                                    f1.write(rxed_data_2)

                        await client_2.stop_notify(READ_CHAR_UUID)

                        z_2 = await client_2.disconnect()
                        l.info("Disconnected: {0}".format(z_2))
                kk += 1
            a += 1

        # Now save any data that has been received
        if len(rxed_data) > 0:
            with open(datetime.datetime.now().strftime("%Y%m%d_%H%M%S.bin"),
                      "wb") as f1:
                f1.write(rxed_data)
            with open(datetime.datetime.now().strftime("%Y%m%d_%H%M%S.txt"),
                      "w") as f1:
                i = 0
                j = 0
                while i + 8 <= len(rxed_data):
                    tt = struct.unpack('<4h', rxed_data[i:i + 8])

                    f1.write("{0},{1},{2},{3},{4}\n".format(
                        j, tt[0], tt[1], tt[2], tt[3]))
                    i += 8
                    j += 1

        rxed_data = b''
        await client.stop_notify(READ_CHAR_UUID)

        z = await client.disconnect()
        logger.info("Disconnected: {0}".format(z))
        await asyncio.sleep(1.0)
Example #19
0
async def run_specific_device(addr, 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)
        logger.addHandler(h)

    async with bleak.BleakClient(addr) as client:
        x = await client.is_connected()
        l.info("Connected: {0}".format(x))
        y = await client.get_services()
        y_serv = y.get_service(SERVICE_UUID.lower())
        l.info(y_serv)
        y_char = y.get_characteristic(READ_CHAR_UUID.lower())
        l.info(y_char)
        l.info(y_char.service_uuid)

        #c_serv = y.get_service(CONFIG_SERVICE_UUID.lower())
        #l.info(c_serv)
        #c_char = y.get_characteristic(CONFIG_3_CHAR_UUID.lower())
        #l.info(c_char)
        #l.info(c_char.service_uuid)

        char_1_val = await client.read_gatt_char(CONFIG_1_CHAR_UUID.lower())
        print("Char 1 Value: 0x{0:04X}".format(char_1_val[0]))
        print("Char 1 length: {0}".format(len(char_1_val)))
        char_2_val = await client.read_gatt_char(CONFIG_2_CHAR_UUID.lower())
        print("Char 2 Value: 0x{0:02X} {1:02X} {2:02X} {3:02X}".format(
            char_2_val[0], char_2_val[1], char_2_val[2], char_2_val[3]))
        print("Char 2 length: {0}".format(len(char_2_val)))
        char_3_val = await client.read_gatt_char(CONFIG_3_CHAR_UUID.lower())
        print("Char 3 Value: 0x{0:04X}".format(char_3_val[0]))
        print("Char 3 length: {0}".format(len(char_3_val)))

        if False:
            x = bytearray(randbytes(1))
            print("Writing Char1 to 0x{0:02X}".format(x[0]))
            await client.write_gatt_char(CONFIG_1_CHAR_UUID, x)
            x = bytearray(randbytes(4))
            print("Writing Char2 to 0x{0:02X} {1:02X} {2:02X} {3:02X}".format(
                x[0], x[1], x[2], x[3]))
            await client.write_gatt_char(CONFIG_2_CHAR_UUID, x)
            await asyncio.sleep(0.6)
            print("Done")

        await client.start_notify(READ_CHAR_UUID, notification_handler)
        #  #await client.write_gatt_char(WRITE_CHAR_UUID, bytearray([0xe,0,0,0,0xff,0xff,0xff,0xff]))
        #await client.write_gatt_char(WRITE_CHAR_UUID, bytearray([0x21,0,0,0,0,0,0,0]))
        #await asyncio.sleep(0.2)
        #await client.write_gatt_char(WRITE_CHAR_UUID, bytearray([0x0E,0,0,0,0,0,0,0]))
        await asyncio.sleep(25.0)
        await client.stop_notify(READ_CHAR_UUID)

        z = await client.disconnect()
        logger.info("Disconnected: {0}".format(z))
        await asyncio.sleep(1.0)
Example #20
0
async def run(address_ledstrip):
    async with BleakClient(address_ledstrip) as client:
        x = await client.is_connected()
        logger.info("Connected: {0}".format(x))
        await client.write_gatt_char(IO_DATA_CHAR_UUID, state_on)
Example #21
0
async def run_all_devices(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)
        logger.addHandler(h)

    x = await bleak.BleakScanner.discover()
    l.info("*********** Start of discovered list *************")
    i = 1
    for d in x:
        #l.info(d)
        #l.info(bleak.utils.mac_str_2_int(d.address))
        print("[{0}]   ".format(i) + d.address + "  " + d.name)
        i += 1
        if i >= 10:
            break
        #if d.address == TARGET_ADDRESS:
        #    await found_unit(d)
    l.info("*********** End of discovered list ***************")

    print("Enter number to connect (or anything else to cancel):")

    s = input()

    try:
        j_s = int(s)
    except ValueError:
        j_s = -1

    if j_s > 0 and j_s <= len(x):
        # a good value!
        async with bleak.BleakClient(x[j_s - 1].address) as client:
            y = await client.is_connected()
            l.info("Connected: {0}".format(y))
            w = await client.get_services()
            w_serv = w.get_service(CONFIG_SERVICE_UUID.lower())
            l.info(w_serv)
            w_char = [
                w.get_characteristic(CONFIG_1_CHAR_UUID.lower()),
                w.get_characteristic(CONFIG_2_CHAR_UUID.lower()),
                w.get_characteristic(CONFIG_3_CHAR_UUID.lower())
            ]
            l.info(w_char[0].service_uuid)
            l.info(w_char[0])
            l.info(w_char[1].service_uuid)
            l.info(w_char[1])
            l.info(w_char[2].service_uuid)
            l.info(w_char[2])

            t_0 = await client.read_gatt_char(w_char[0])
            t_1 = await client.read_gatt_char(w_char[1])
            t_2 = await client.read_gatt_char(w_char[2])

            print(t_0)
            print(t_1)
            print(t_2)

            is_central = False

            if len(t_0) >= 1:
                is_central = ((t_0[0] & 0x01) != 0)
                if is_central:
                    print("This is a central device. Choose:")
                    print("[1] change to peripheral")
                    print("[2] no change (remain as central)")

                    s = input()

                    try:
                        k_s = int(s)
                    except ValueError:
                        k_s = 2

                    if k_s == 1:
                        await client.write_gatt_char(w_char[0],
                                                     bytearray(b'\x00'))
                        is_central = False
                        print("Changed")
                else:
                    print("This is a peripheral device. Choose:")
                    print("[1] no change (remain as peripheral)")
                    print("[2] change to central")

                    s = input()

                    try:
                        k_s = int(s)
                    except ValueError:
                        k_s = 1

                    if k_s == 2:
                        await client.write_gatt_char(w_char[0],
                                                     bytearray(b'\x01'))
                        print("Changed")
                        is_central = True

            if len(t_1) >= 4 and is_central:
                val_2 = struct.unpack('<I', t_1)[0]
                print("This is a central device with trigger threshold {0}.".
                      format(0x3FFF & val_2))
                print("Enter a new value, or <Enter> to keep old one:")

                s = input()

                try:
                    k_s = int(s)
                except ValueError:
                    k_s = -1

                if k_s >= 0:
                    new_val = (val_2 & 0xFFFFC000) | (k_s & 0x3FFF)
                    await client.write_gatt_char(
                        w_char[1], bytearray(struct.pack('<I', new_val)))
                    print("Changed")
                else:
                    print("No change")

            z = await client.disconnect()
            logger.info("Disconnected: {0}".format(z))
            await asyncio.sleep(1.0)

    await asyncio.sleep(1.0)