Exemplo n.º 1
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)
Exemplo n.º 2
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)
Exemplo n.º 3
0
async def run_any_device(debug=False):
    async def found_unit(dev):
        await asyncio.sleep(1.0)
        async with bleak.BleakClient(dev.address) as client:
            svcs = await client.get_services()
            print("Services:", svcs.services)

    if debug:
        import sys
        import logging

        # 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 *************")
    for d in x:
        l.info(d)
        l.info(bleak.utils.mac_str_2_int(d.address))
        if d.address == TARGET_ADDRESS:
            await found_unit(d)
    l.info("*********** End of discovered list ***************")
    await asyncio.sleep(1.0)
Exemplo n.º 4
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))
Exemplo n.º 5
0
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)
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
async def run(address, debug=True):
    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) as client:
        # logger.info(f"Connected: {client.is_connected}")
        print(f"Connected: {client.is_connected}")

        await client.start_notify(CHARACTERISTIC_UUID_1, notification_handler)
        await client.start_notify(CHARACTERISTIC_UUID_2, notification_handler)
        await asyncio.sleep(60.0)
        await client.stop_notify(CHARACTERISTIC_UUID_1)
        await client.stop_notify(CHARACTERISTIC_UUID_2)
        await client.disconnect()
Exemplo n.º 8
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)
Exemplo n.º 9
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)
Exemplo n.º 10
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)