async def run():
    #devices = await discover()
    print("Trying to find NIST ET devices")
    et_devices = await list.get_et_list()
    conn = {}
    for device in et_devices:
        conn[device.name] = BleakClient(device.address)

    # for key in conn.keys():
    #     await connect(conn[key])

    # tasks = []
    # for key in conn.keys():
    #     task = loop.create_task(connect(conn[key]))
    #     tasks.append(task)
    # result = await asyncio.wait(tasks)
    # print("result", result)

    # for key in conn.keys():
    #     print(key, await conn[key].is_connected())
    # print(len(result))
    # excepted_list = []
    # for r in result[0]:
    #     if r.exception() is not None:
    #         excepted_list.append(r)
    # print(excepted_list)
    # for key in conn.keys():
    #     print(key, await conn[key].is_connected())
    # for key in conn.keys():
    for key in conn.keys():
        # key = 'NIST-GEN'
        await connect(conn[key])
        count = await conn[key].read_gatt_char(count_uuid)
        count = int.from_bytes(bytes(count), byteorder='little')
        print(key, conn[key].address, count)
        await conn[key].disconnect()
Beispiel #2
0
async def print_services(ble_address: str):
    """
    This finction checks for the BLE device internal
    services and identify the propper one for the uart via BT
    """
    global the_service
    device = await BleakScanner.find_device_by_address(ble_address,
                                                       timeout=20.0)

    if not device:
        raise BleakError(
            f"A device with address {ble_address} could not be found.")

    async with BleakClient(device) as client:
        svcs = await client.get_services()
        print("Services:")
        for service in svcs:
            print(service)
            if "Vendor specific" in str(service):
                print(service.characteristics)
                for inside in service.characteristics:
                    print(f"Sub info properties: {inside.properties}")
                    print(f"Sub info uuid: {inside.uuid}")
                    the_service = inside.uuid
Beispiel #3
0
async def explore_services(mac_addr: str):
    log = logging.getLogger(__name__)
    log.setLevel(logging.INFO)
    h = logging.StreamHandler(sys.stdout)
    h.setLevel(logging.INFO)
    log.addHandler(h)

    async with BleakClient(mac_addr) as client:
        for service in client.services:
            log.info(f"[Service] {service}")
            for char in service.characteristics:
                if "read" in char.properties:
                    try:
                        value = bytes(await client.read_gatt_char(char.uuid))
                        log.info(
                            f"\t[Characteristic] {char} ({','.join(char.properties)}), Value: {value}"
                        )
                    except Exception as e:
                        log.error(
                            f"\t[Characteristic] {char} ({','.join(char.properties)}), Value: {e}"
                        )
                else:
                    value = None
                    log.info(
                        f"\t[Characteristic] {char} ({','.join(char.properties)}), Value: {value}"
                    )

                for descriptor in char.descriptors:
                    try:
                        value = bytes(await client.read_gatt_descriptor(
                            descriptor.handle))
                        log.info(
                            f"\t\t[Descriptor] {descriptor}) | Value: {value}")
                    except Exception as e:
                        log.error(
                            f"\t\t[Descriptor] {descriptor}) | Value: {e}")
Beispiel #4
0
async def print_services(mac_addr: str):
    devices = await discover()
    batter_monitor_device = None
    for d in devices:
        if d.name == 'BatteryMonitor':
            batter_monitor_device = d.address
    device = await BleakScanner.find_device_by_address(batter_monitor_device)
    async with BleakClient(device) as client:

        for service in client.services:
            log.info("[Service] {0}: {1}".format(service.uuid,
                                                 service.description))
            for char in service.characteristics:
                if "read" in char.properties:
                    try:
                        value = bytes(await client.read_gatt_char(char.uuid))
                    except Exception as e:
                        value = str(e).encode()
                else:
                    value = None
                log.info(
                    "\t[Characteristic] {0}: (Handle: {1}) ({2}) | Name: {3}, Value: {4} "
                    .format(
                        char.uuid,
                        char.handle,
                        ",".join(char.properties),
                        char.description,
                        value,
                    ))
                for descriptor in char.descriptors:
                    value = await client.read_gatt_descriptor(descriptor.handle
                                                              )
                    log.info(
                        "\t\t[Descriptor] {0}: (Handle: {1}) | Value: {2} ".
                        format(descriptor.uuid, descriptor.handle,
                               bytes(value)))
Beispiel #5
0
    def __init__(self, path, name):
        # Configuration.
        parser = argparse.ArgumentParser()
        parser.add_argument("-i",
                            "--inifile",
                            default=os.path.join(path, name + '.ini'),
                            help="name of the configuration file")
        args = parser.parse_args()

        config = configparser.ConfigParser(inline_comment_prefixes=('#', ';'))
        config.read(args.inifile)

        # Redis.
        try:
            rds = redis.StrictRedis(host=config.get('redis', 'hostname'),
                                    port=config.getint('redis', 'port'),
                                    db=0,
                                    charset='utf-8',
                                    decode_responses=True)
        except redis.ConnectionError as e:
            raise RuntimeError(e)

        # Combine the patching from the configuration file and Redis.
        self.patch = EEGsynth.patch(config, rds)

        # BLE client.
        self.loop = asyncio.get_event_loop()

        self.ble_client = BleakClient(self.patch.getstring("input", "uuid"),
                                      loop=self.loop)

        self.monitor = EEGsynth.monitor(name=name,
                                        debug=self.patch.getint(
                                            "general", "debug"))

        self.loop.run_until_complete(self.discover())
Beispiel #6
0
async def run(address, dt=None):

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

        if dt is None:
            dt = datetime.now()

        set_date_command = bytearray([0xaa, 0x00, 0x08])
        start_data = bytes([0x01])
        end_data = bytes([0x05])

        encoded_now = encode_datetime(dt.year, dt.month, dt.day, dt.hour,
                                      dt.minute, dt.second)
        data_body = start_data + encoded_now + end_data
        write_data = set_date_command + data_body + crc8(data_body)

        await client.start_notify(CHAR_UART_NOTIFY, notification_handler)

        await client.write_gatt_char(CHAR_UART_RX, write_data)
        await asyncio.sleep(5.0)

        await client.stop_notify(CHAR_UART_NOTIFY)
Beispiel #7
0
async def run(address, loop):

    async with BleakClient(address, loop=loop) as client:

        #wait for BLE client to be connected
        x = await client.is_connected()
        print("Connected: {0}".format(x))

        #wait for data to be sent from client
        await client.start_notify(UART_RX_UUID, notification_handler)

        while True:

            #give some time to do other tasks
            await asyncio.sleep(0.01)

            #check if we received data
            global dataFlag
            if dataFlag:
                dataFlag = False

                #echo our received data back to the BLE device
                data = await client.read_gatt_char(UART_RX_UUID)
                await client.write_gatt_char(UART_TX_UUID, data)
 async def read(self, address, loop):
     try:
         async with BleakClient(address, loop=loop) as client:
             try:
                 print("TRY TO CONNECT")
                 await client.connect(timeout=10)
             except Exception as e:
                 print("Exception", e)
             except BleakDotNetTaskError as e:
                 print("BleakDotNetTaskError", e)
             except BleakError as e:
                 print("BleakError", e)
             finally:
                 if await client.is_connected():
                     services = await client.get_services()
                     services = vars(services)
                     data = {}
                     for k, v in services.items():
                         if 'characteristics' in k:
                             for sk, sv in v.items():
                                 sv = str(sv).replace(':', "").replace(' ', "")
                                 if sv in self.readable_chars:
                                     result = await client.read_gatt_char(sv)
                                     await asyncio.sleep(0.1, loop=loop)
                                     if sv == BATTERY_LEVEL_CHAR:
                                         result = str(int(result.hex(), 16))
                                     else:
                                         result = result.decode("utf-8")
                                     data[self.char_to_string_mapping[sv]] = result
                     data['mac_addr'] = address
                     self.client_conn.send(data)
                     return client
                 print("NOT CONNECTED")
                 return None
     except BleakError as e:
         print("BLEAK ERROR", e)
Beispiel #9
0
    async def _refresh_data(self):
        async with BleakClient(self.device) as client:
            raw_char_read = await client.read_gatt_char(CHAR_FEEDBACK)

        response = [hex(x) for x in raw_char_read]

        # Make sure the data is where we think it is
        assert response[5] == "0x43"  # color
        assert response[10] == "0x53"  # audio
        assert response[13] == "0x50"  # power

        red, green, blue, brightness = [int(x, 16) for x in response[6:10]]

        sound = PyHatchBabyRestSound(int(response[11], 16))

        volume = int(response[12], 16)

        power = not bool(int("11000000", 2) & int(response[14], 16))

        self.color = (red, green, blue)
        self.brightness = brightness
        self.sound = sound
        self.volume = volume
        self.power = power
Beispiel #10
0
async def connect():
    a = BleakClient(address)
    await a.connect()
    #await a.pair()
    try:
        await a.write_gatt_char(write_characteristic, b'p')
        print("started playing music")
        time.sleep(2)
        await a.write_gatt_char(write_characteristic, b'n')
        time.sleep(2)
        await a.write_gatt_char(write_characteristic, b'n')
        time.sleep(2)
        await a.write_gatt_char(write_characteristic, b'n')
        time.sleep(2)
        await a.write_gatt_char(write_characteristic, b'n')
        time.sleep(2)
        await a.write_gatt_char(write_characteristic, b's')
    except Exception as inst:
        print("Unexpected error:", inst)
        print("oh no")
    #finally:
    #    await a.unpair()
    await a.disconnect()
    print("stopped playing music")
 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"):
                 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 run_scan_services_bleview(lifebasemeter, loop, timeout):
    async with async_timeout.timeout(timeout):
        async with BleakClient(lifebasemeter.mac, loop=loop) as client:
            lifebasemeter.ble = await client.get_services()
            for s in lifebasemeter.ble.services.values():
                if lifebasemeter.servicefilter and s.uuid not in lifebasemeter.servicefilter:
                    continue
                service = Service(s.uuid)
                lifebasemeter.ble_services.append(service)
                service.set_handle_from_path(s.path)
                service.description = s.description
                for ch in s.characteristics:
                    if lifebasemeter.characteristicfilter and ch.uuid not in lifebasemeter.characteristicfilter:
                        continue
                    cc = Characteristic(ch.uuid)
                    service.characteristics.append(cc)
                    cc.set_handle_from_path(ch.path)
                    cc.description = ch.description
                    cc.properties = ch.properties
                    if "read" in ch.properties:
                        try:
                            cc.value = bytes(await
                                             client.read_gatt_char(ch.uuid))
                        except:
                            cc.value = None
                    for d in ch.descriptors:
                        if lifebasemeter.descriptorfilter and d.uuid not in lifebasemeter.descriptorfilter:
                            continue
                        descriptor = Descriptor(d.uuid)
                        cc.descriptors.append(descriptor)
                        descriptor.set_handle(d.handle)
                        try:
                            descriptor.description = await client.read_gatt_descriptor(
                                d.handle)
                        except:
                            descriptor.description = None
Beispiel #13
0
async def run(address, loop, debug=False):
    log = logging.getLogger(__name__)
    if debug:
        # loop.set_debug(True)
        log.setLevel(logging.DEBUG)
        h = logging.StreamHandler(sys.stdout)
        h.setLevel(logging.DEBUG)
        log.addHandler(h)

    # try until you can connect
    while (1):
        try:
            async with BleakClient(address, loop=loop) as client:
                x = await client.is_connected()
                log.info("Connected: {0}".format(x))
                for service in client.services:
                    for char in service.characteristics:
                        # player Music
                        if char.properties[0] == 'write':
                            v = random.randint(0, 2)
                            if v == 1:
                                res, aw = police()
                            else:
                                res, aw = happy_birthday()

                            for ct in range(len(res)):
                                i = int(res[ct])  # * 255)
                                print("Send:", bytes([i]))
                                value = await client.write_gatt_char(
                                    char.uuid, bytes([i]))
                                time.sleep(aw[ct])
                print("DataSend")

        except Exception as e:
            print(e)
            continue
Beispiel #14
0
    async def connect(self):
        print('Searching for progressor...')
        devices = await discover()
        TARGET_NAME = 'Progressor'
        address = None
        for d in devices:
            if d.name[:len(TARGET_NAME)] == TARGET_NAME:
                address = d.address
                print("Found \"{0}\" with address {1}".format(
                    d.name, d.address))
                break

        if address is None:
            raise RuntimeError('cannot find tindeq')

        self.client = BleakClient(address)
        await self.client.connect()
        success = self.client.is_connected
        if success:
            await self.client.start_notify(uuid.UUID(self.notify_uuid),
                                           self._notify_handler)
        else:
            raise RuntimeError('could not connect to progressor')
        return success
Beispiel #15
0
async def tacx_real(address, gpx_list):
    global cur_pos
    from bleak import BleakClient
    from pycycling2.tacx_trainer_control import TacxTrainerControl
    from gtacx import set_entry

    tacx_misc.running = True
    get_tacx_data.pdist = 0
    get_tacx_data.ndist = 0
    get_tacx_data.startdist = 0
    get_tacx_data.reset = True

    # goto start position
    cur_pos = goto_pos(gpx_list, tacx_misc.offset)
    if (cur_pos):
        tacx_misc.man_roadsurface_type = cur_pos.RoadSurface
        tacx_misc.man_roadsurface_intensity = 20

    set_entry(tacx_misc.guivars.w20, "Tacx Try to connect")
    async with BleakClient(address, timeout=20.0) as client:
        set_entry(tacx_misc.guivars.w20, "Tacx Connecting")
        await client.is_connected()
        set_entry(tacx_misc.guivars.w20, "Tacx Connected")
        trainer = TacxTrainerControl(client)

        ######################################################
        # handle commands from tacx; get current position:
        def my_page_handler(data):
            global cur_pos
            tacx_misc.tacx_data = get_tacx_data(str(data), tacx_misc.offset)
            if (tacx_misc.tacx_data.new_data):
                cur_pos = goto_pos(
                    gpx_list,
                    tacx_misc.tacx_data.distance + tacx_misc.guivars.add_dist)
                if (tacx_misc.man_roadsurface):
                    cur_pos.RoadSurface = tacx_misc.man_roadsurface_type
                    cur_pos.RoadSurface_intensity = tacx_misc.man_roadsurface_intensity
                    cur_pos.slope = tacx_misc.man_slope

        trainer.set_specific_trainer_data_page_handler(my_page_handler)
        trainer.set_general_fe_data_page_handler(my_page_handler)
        await trainer.enable_fec_notifications()

        #set fixed parameters
        await trainer.set_user_configuration(user_weight=75,
                                             bicycle_weight=10,
                                             bicycle_wheel_diameter=0.7,
                                             gear_ratio=1)
        set_entry(tacx_misc.guivars.w20, "Tacx Running")
        #print("Ready")

        ######################################################
        # Loop: send commands to tacx, check regularly if data from tacx changes
        while (tacx_misc.running):
            if (tacx_misc.tacx_data.new_data):
                if (cur_pos.end_track):
                    break

                from gtacx import show_pos
                show_pos(tacx_misc.tacx_data, cur_pos)
                await put_tacx_data(trainer, "set_track_resistance",
                                    cur_pos.slope, 0.002)
                await put_tacx_data(trainer, "set_RoadSurface",
                                    cur_pos.RoadSurface,
                                    int(cur_pos.RoadSurface_intensity))
                tacx_misc.tacx_data.new_data = False
            await asyncio.sleep(0.2)

        await trainer.disable_fec_notifications()
        if (cur_pos.end_track):
            set_entry(tacx_misc.guivars.w20, "End-of-track")
        else:
            set_entry(tacx_misc.guivars.w20,
                      "Stopped @ gpx={:.3f} km".format(cur_pos.dist / 1000.))
async def run(address, loop, info_toget):
    async with BleakClient(address, loop=loop) as client:
        dat = await client.read_gatt_char(info_toget)
        return (dat)
async def run(address):
    async with BleakClient(address) as client:
        irradiance = await client.read_gatt_char(IRRADIANCE_UUID)
        print("Irradiance: {0} W/m^2".format(
            int.from_bytes(irradiance, byteorder='little', signed=False) / 10))
Beispiel #18
0
async def print_services(mac_addr: str):
    async with BleakClient(mac_addr) as client:
        svcs = await client.get_services()
        print("Services:")
        for service in svcs:
            print(service)
Beispiel #19
0
 async def __connect(self, address):
     client = BleakClient(address, self._loop)
     await client.connect(timeout=1)
     return client
Beispiel #20
0
async def run(address, loop):
    async with BleakClient(address, loop=loop) as client:
        model_number = await client.read_gatt_char(MODEL_NBR_UUID)
        print("Model Number: {0}".format("".join(map(chr, model_number))))
Beispiel #21
0
async def run(device_number, number_to_find):
    print("run number_to_find", number_to_find)
    global g_client, g_total_expected, g_get_idx, g_ready, g_fp_out
    #devices = await discover()
    not_found = True
    while not_found:
        print("Trying to find NIST ET devices")
        et_devices = await list_et.get_et_list(number_to_find)
        # print(et_devices)
        name = 'NIST%04d'%device_number
        for device in et_devices:
            if device.name == name:
                not_found = False
                break
    print(device.name, device.address)
    # async with BleakClient(device.address) as client:
    if True:
        client = BleakClient(device.address)
        connected = False
        while not connected:
            try:
                connected = await client.connect()
            except Exception as e:
                print(e)
                print("Trying again")

        g_client = client
        print(device.name, end=" ")
        x = await client.is_connected()
        print("Connected: {0}".format(x))
        c = await client.read_gatt_char(rw_uuid)
        print('last rw command: ',c)
        count = await client.read_gatt_char(count_uuid)
        count = int.from_bytes(bytes(count), byteorder='little')
        print('count:', count)
        g_total_expected = count<<5;
        total_len = 0
        done_xfer = False
        if count==0:
            done_xfer = True
        else:
            date_suffix = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            g_fp_out = open('raw_'+device.name+'_'+date_suffix+'.bin', 'wb')
        print('*'*40)
        start=time.time()
        # kw = {'client': client, 'total_expected': g_total_expected}
        await client.start_notify(data_uuid, data_handler) # , kw)
        print("Started notify")
        await client.write_gatt_char(rw_uuid, bytearray(b'f'))
        print("sent f")
        g_get_idx = 0
        await client.write_gatt_char(data_uuid, g_get_idx.to_bytes(4,
                                                                 byteorder='little'))
        print("sent 0, for first packet")
        g_ready = False
        while data_handler.not_done:
            if g_ready:
                await client.write_gatt_char(data_uuid, g_get_idx.to_bytes(4,
                                                                 byteorder='little'))
                g_ready = False
            else:
                await asyncio.sleep(0.01)
        await client.stop_notify(data_uuid)
Beispiel #22
0
 async def disconnect(self):
     async with BleakClient(self.device) as client:
         return await client.disconnect()
Beispiel #23
0
 async def connected(self):
     async with BleakClient(self.device) as client:
         return await client.is_connected()
Beispiel #24
0
async def run(loop, lh_macs):
    if command == "discover":
        lh_macs = []
        createShortcuts = True if (
            "-cs" in sys.argv or "--create-shortcuts" in sys.argv) else False
        print(">> MODE: discover suitable V2 lighthouses")
        if createShortcuts: print("         and create desktop shortcuts")
        print(" ")
        print(">> Discovering BLE devices...")
        devices = await discover()
        for d in devices:
            deviceOk = False
            if d.name.find("LHB-") != 0:
                continue
            print(">> Found potential Valve Lighthouse at '" + d.address +
                  "' with name '" + d.name + "'...")
            services = None
            async with BleakClient(d.address) as client:
                try:
                    services = await client.get_services()
                except:
                    print(">> ERROR: could not get services.")
                    continue
            for s in services:
                if (s.uuid == __PWR_SERVICE):
                    print("   OK: Service " + __PWR_SERVICE + " found.")
                    for c in s.characteristics:
                        if c.uuid == __PWR_CHARACTERISTIC:
                            print("   OK: Characteristic " +
                                  __PWR_CHARACTERISTIC + " found.")
                            print(
                                ">> This seems to be a valid V2 Base Station.")
                            print(" ")
                            lh_macs.append(d.address)
                            deviceOk = True
            if not deviceOk:
                print(">> ERROR: Service or Characteristic not found.")
                print(">>        This is likely NOT a suitable Lighthouse V2.")
                print(" ")
        if len(lh_macs) > 0:
            print(">> OK: At least one compatible V2 lighthouse was found.")
            print(" ")
            if createShortcuts:
                print(">> Trying to create Desktop Shortcuts...")
                import winshell
                from win32com.client import Dispatch
                desktop = winshell.desktop()
                path = os.path.join(desktop, "LHv2-ON.lnk")
                shell = Dispatch('WScript.Shell')
                shortcut = shell.CreateShortCut(path)
                if cmdName.find(".py") > 0:
                    shortcut.Targetpath = sys.executable
                    shortcut.Arguments = '"' + cmdName + '" on ' + " ".join(
                        lh_macs)
                else:
                    shortcut.Targetpath = '"' + cmdPath + cmdName + '"'
                    shortcut.Arguments = "on " + " ".join(lh_macs)
                shortcut.WorkingDirectory = cmdPath[:-1]
                shortcut.IconLocation = cmdPath + "lhv2_on.ico"
                shortcut.save()
                print("   * OK: LHv2-ON.lnk was created successfully.")
                path = os.path.join(desktop, "LHv2-OFF.lnk")
                shell = Dispatch('WScript.Shell')
                shortcut = shell.CreateShortCut(path)
                if cmdName.find(".py") > 0:
                    shortcut.Targetpath = sys.executable
                    shortcut.Arguments = '"' + cmdName + '" off ' + " ".join(
                        lh_macs)
                else:
                    shortcut.Targetpath = '"' + cmdPath + cmdName + '"'
                    shortcut.Arguments = "off " + " ".join(lh_macs)
                shortcut.WorkingDirectory = cmdPath[:-1]
                shortcut.IconLocation = cmdPath + "lhv2_off.ico"
                shortcut.save()
                print("   * OK: LHv2-OFF.lnk was created successfully.")
            else:
                print(
                    "   OK, you need to manually create two links, for example on your desktop:"
                )
                print(" ")
                print("   To turn your lighthouses ON:")
                print("    * Link Target: " + cmdStr + " on " +
                      " ".join(lh_macs))
                print(" ")
                print("   To turn your lighthouses OFF:")
                print("    * Link Target: " + cmdStr + " off " +
                      " ".join(lh_macs))
        else:
            print(">> Sorry, not suitable V2 Lighthouses found.")
        print(" ")

    if command in ["on", "off"]:
        print(">> MODE: switch lighthouses " + command.upper())
        lh_macs.extend(sys.argv[2:])
        for mac in list(lh_macs):
            if re.match("[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}", mac):
                continue
            print("   * Invalid MAC address format: " + mac)
            lh_macs.remove(mac)
        if len(lh_macs) == 0:
            print(" ")
            print(">> ERROR: no (valid) base station MAC addresses given.")
            print(" ")
            sys.exit()
        for mac in lh_macs:
            print("   * " + mac)
        print(" ")
        for mac in lh_macs:
            print(">> Trying to connect to BLE MAC '" + mac + "'...")
            max_tries = 10
            try_count = 0
            success = False
            for try_count in range(0, max_tries):
                try:
                    client = BleakClient(mac, loop=loop)
                    await client.connect()
                    print(">> '" + mac + "' connected...")
                    await client.write_gatt_char(
                        __PWR_CHARACTERISTIC,
                        __PWR_ON if command == "on" else __PWR_STANDBY)
                    print(">> LH switched to '" + command +
                          "' successfully... ")
                    await client.disconnect()
                    print(">> disconnected. ")
                    success = True
                    break
                except Exception as e:
                    print(">> ERROR: " + str(e))
            if not success:
                print("Reached max tries ({}).".format(max_tries))
            print(" ")
async def robotTest(loop):

    # Handle is the TX characteristic UUID; does not change in our simple case.
    # Robot sends "enq" every 2 seconds to keep the connection "fresh"
    # Otherwise, it's a struct of the form:
    # bytes(type + length + data)
    # This struct shouldn't be more than 99 bytes long.

    def simpleHandler(handle, value):
        global time  # This is apparently needed.
        if (value == "enq".encode()):
            pass
        else:
            fmtstring = "BB" + str(len(value) - 2) + "s"
            code, length, data = unpack(fmtstring, value)
            '''
            Python doesn't have a switch statement, nor easily compatible
            enum support. This might be the easiest way to handle commands.
            '''
            if (Settings["OutputRawData"]):
                print(
                    f"Code: {getCommandName(code)} Length: {length} Data: {data}"
                )

            # Somewhat detach console output from Bluetooth handling.
            if (code == Commands.SER_TX.value):
                theRobot.pushMessage(str(data, encoding="UTF-8"))
                theRobot.obsData = [
                    1, 2, 3, 4, 5
                ]  #unpack array to store sensor data in obsData

            # Example of unpacking a little-endian 32-bit float.
            if (code == Commands.GIVE_FLOAT.value):
                print(unpack("<f", data))

            # Example of command-response.
            if (code == Commands.PONG.value):
                print(f"Got pong: round trip {time.time() - theRobot.now}")
                if (Settings["pingLoop"]):
                    loop.create_task(theRobot.ping())
                    # theRobot.newPing = True

            # Unpack from an example stream that transmits a 2-byte and a
            # 4-byte integer as quickly as possible, both little-endian.
            if (code == Commands.BYTESTREAM_TX.value):
                print(unpack("<LiIfff",
                             data))  #unpacks 1 long, 2 chars and 2 floats

    async def checkMessages():
        while True:
            if (theRobot.availMessage()):
                print(f"BTDebug: {theRobot.getMessage()}")
            await asyncio.sleep(0.1)

    # You can put a UUID (MacOS) or MAC address (Windows and Linux)
    # in Settings["Cached"].
    if (not Settings["cached"]):
        theRobot_bt = await getRobot()

    else:
        theRobot_bt = type("", (), {})()
        theRobot_bt.address = Settings["cached"]
    # print(theRobot_bt.address)
    while (not theRobot_bt):
        print("Robot not found")
        theRobot_bt = await getRobot()

    if (not Settings["cached"]):
        print(f"New robot found. Must cache \
            {theRobot_bt.address} manually in settings.py")

    async with BleakClient(theRobot_bt.address,
                           loop=loop,
                           device=Settings["adapter"]) as client:
        # if (await client.is_connected()):
        #    print("Robot connected!")
        # srv = await client.get_services()
        # print(srv)
        await client.is_connected()
        theRobot = Robot(client, bleak=True)
        theRobotHolder.setRobot(theRobot)
        await client.start_notify(Descriptors["TX_CHAR_UUID"].value,
                                  simpleHandler)

        # await client.write_gatt_char(Descriptors["RX_CHAR_UUID"].value, msg)
        async def myRobotTasks():
            pass

            #await theRobot.ping()

            # await theRobot.sendCommand(Commands.REQ_FLOAT)
            #await theRobot.sendCommand(Commands.START_BYTESTREAM_TX)
            # for i in range(0, 50):
            #     print("Sending message")
            #     await theRobot.sendMessage("Testing message")
            #     await asyncio.sleep(1)

            # await theRobot.testByteStream(25)

        async def motorLoop():
            while True:
                await theRobot.loopTask()
                await asyncio.sleep(0.1)

        await asyncio.gather(checkMessages(), myRobotTasks())
Beispiel #26
0
 async def __connect(self, address):
     client = BleakClient(address, timeout=1)
     await client.connect(timeout=1)
     await asyncio.sleep(1)
     await self.__get_service(client)
     return client
Beispiel #27
0
async def print_services(mac_addr: str, loop: asyncio.AbstractEventLoop):
    async with BleakClient(mac_addr, loop=loop) as client:
        svcs = await client.get_services()
        print("Services:", svcs)
Beispiel #28
0
async def run(addr1, add2, loop):
    async with BleakClient(addr1, loop=loop) as client:
        print('Connected to the first WeDo successfully!')

        async with BleakClient(add2, loop=loop) as client2:
            print('Connected to the second WeDo successfully!')

            await client.write_gatt_char(
                INPUT_COMMAND_UUID,
                bytearray([
                    0x01, 0x02, PORT_NUM, 0x23, 0x00, 0x01, 0x00, 0x00, 0x00,
                    0x02, 0x01
                ]), True)

            await client.start_notify(SENSOR_VAL_UUID, callback)

            # await client2.write_gatt_char(INPUT_COMMAND_UUID, bytearray([0x01,0x02,PORT_NUM,0x23,0x00,0x01,0x00,0x00,0x00,0x02,0x01]), True)

            # await client2.start_notify(SENSOR_VAL_UUID, callback)

            global outputted_value, prev_value, GLOBAL_Q

            try:
                while True:
                    await asyncio.sleep(0)

                    if not outputted_value == prev_value:

                        copy = outputted_value

                        GLOBAL_Q.append((client, OUTPUT_COMMAND_UUID,
                                         bytearray([0x06, 0x04, 0x01, copy])))
                        GLOBAL_Q.append(
                            (client2, OUTPUT_COMMAND_UUID,
                             bytearray(
                                 [0x01, 0x01, 0x01,
                                  translate_speed(copy > 0)])))
                        GLOBAL_Q.append(
                            (client2, OUTPUT_COMMAND_UUID,
                             bytearray([
                                 0x02, 0x01, 0x01,
                                 translate_speed(
                                     (copy > 0) * (-1 if copy < 4 else 1))
                             ])))

                        for q in GLOBAL_Q:
                            try:
                                # Write
                                c, uuid, data = q
                                await c.write_gatt_char(uuid, data, True)

                            except ValueError:
                                # Read
                                c, uuid = q
                                c.read_gatt_char(uuid)

                        GLOBAL_Q = []

                        # await client.write_gatt_char(OUTPUT_COMMAND_UUID, bytearray([0x06,0x04,0x01,copy]), True)

                        # await client2.write_gatt_char(OUTPUT_COMMAND_UUID, bytearray([0x06,0x04,0x01,copy]), True)
                        # await client2.write_gatt_char(OUTPUT_COMMAND_UUID, bytearray([0x01, 0x01, 0x01, translate_speed(copy/10) ]), True )
                        # await client2.write_gatt_char(OUTPUT_COMMAND_UUID, bytearray([0x02, 0x01, 0x021, translate_speed(-copy/10) ]), True )

                    prev_value = outputted_value

                    # await client.write_gatt_char(OUTPUT_COMMAND_UUID, bytearray([0x06,0x04,0x01,outputted_value]), True)
                    # print(await client.read_gatt_char(PORT_INFO_UUID))
                    # await client.write_gatt_char(OUTPUT_COMMAND_UUID, bytearray([0x02, 0x01, 0x01, translate_speed(outputted_value/10)]))

            except KeyboardInterrupt:
                print('Stopping notifications...')
                await client.stop_notify(SENSOR_VAL_UUID)
async def run(address):
    async with BleakClient(address) as client:
        await client.start_notify(constants.CHARACTERISTIC_UUID,
                                  notification_handler)
        await asyncio.sleep(2000)
Beispiel #30
0
async def run(mac_addr):
    client = BleakClient(mac_addr, timeout=60.0)
    try:
        x = await client.connect()
        print("Connected: {0}".format(x))
        
        data = await client.read_gatt_char(UUID_Bike_Model)
        print("Value: {0}".format("".join(map(chr, data))),"Raw:",data)
        
        #data = await client.read_gatt_char(UUID_Bike_Read)
        #print("Value: {0}".format("".join(map(chr, data))),"Raw:",data)
        
        
        cmd1 = [240, 172, 156]                                         # "0xf0ac9c" 
        write_value1 = bytearray(cmd1)            
        cmd2 = [240,203,2,0,8,255,1,0,109,1,1,0,0,0,1,0,50,0,1,0]      # "0xf0cb020008ff01006d0101000000010032000100"
        #cmd2 = [240,203,2,0,8,255,12,11,109,10,9,8,7,6,5,4,60,3,2,1]
        write_value2 = bytearray(cmd2)
        cmd3 = [1,0,1,0,0,0,106]                                       # "0x0100010000006a" 
        write_value3 = bytearray(cmd3)                
        cmd4 = [240, 201, 185]                                         # "0xf0c9b9" 
        write_value4 = bytearray(cmd4)
        cmd5 = [240, 163, 147]                                         # "0xf0a393" 
        write_value5 = bytearray(cmd5)
        cmd6 = [240, 164, 148]                                         # "0xf0a494" 
        write_value6 = bytearray(cmd6)

        try:
            await client.start_notify(UUID_Bike_Read, notification_handler)
            for x in range(10):                                        
                
                if(x == 1):
                    await client.write_gatt_char(UUID_Bike_Write, write_value2)
                    print("Writing cmd2")        
                    await client.write_gatt_char(UUID_Bike_Write, write_value3)
                    print("Writing cmd3")        
                
                if(x == 4):
                    await client.write_gatt_char(UUID_Bike_Write, write_value4)
                    print("Writing cmd4")

                if(x == 6):
                    await client.write_gatt_char(UUID_Bike_Write, write_value5)
                    print("Writing cmd5")

                if(x == 8):
                    await client.write_gatt_char(UUID_Bike_Write, write_value6)
                    print("Writing cmd6")

                if(x != 1 and x != 4 and x != 6 and x != 8):
                    await client.write_gatt_char(UUID_Bike_Write, write_value1)
                    print("Writing ___cmd1")

                await asyncio.sleep(2.0)

        except Exception as e:
            print(e)
        finally:
            await client.stop_notify(UUID_Bike_Read)
                
        
    except Exception as e:
        print(e)
    
    finally:        
        await client.disconnect()