2023-08-22 05:14:38 -04:00
|
|
|
# SPDX-FileCopyrightText: 2018-2023 Espressif Systems (Shanghai) CO LTD
|
2022-06-07 12:16:23 -04:00
|
|
|
# SPDX-License-Identifier: Apache-2.0
|
2018-07-30 12:10:10 -04:00
|
|
|
#
|
|
|
|
|
|
|
|
import platform
|
|
|
|
|
2022-06-22 05:44:19 -04:00
|
|
|
from utils import hex_str_to_bytes, str_to_bytes
|
2018-07-30 12:10:10 -04:00
|
|
|
|
|
|
|
fallback = True
|
|
|
|
|
2018-12-01 08:23:34 -05:00
|
|
|
|
2022-06-07 12:16:23 -04:00
|
|
|
# Check if required packages are installed
|
2018-07-30 12:10:10 -04:00
|
|
|
# else fallback to console mode
|
2022-06-07 12:16:23 -04:00
|
|
|
try:
|
|
|
|
import bleak
|
|
|
|
fallback = False
|
|
|
|
except ImportError:
|
|
|
|
pass
|
2018-07-30 12:10:10 -04:00
|
|
|
|
2018-12-01 08:23:34 -05:00
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
|
2022-06-07 18:55:10 -04:00
|
|
|
def device_sort(device):
|
2023-07-19 04:35:55 -04:00
|
|
|
return device[0].address
|
2022-06-07 18:55:10 -04:00
|
|
|
|
|
|
|
|
2022-06-07 12:16:23 -04:00
|
|
|
class BLE_Bleak_Client:
|
2021-04-07 07:43:02 -04:00
|
|
|
def __init__(self):
|
2022-06-22 05:44:19 -04:00
|
|
|
self.adapter = None
|
2021-04-07 07:43:02 -04:00
|
|
|
self.adapter_props = None
|
2022-06-22 05:44:19 -04:00
|
|
|
self.characteristics = dict()
|
|
|
|
self.chrc_names = None
|
|
|
|
self.device = None
|
|
|
|
self.devname = None
|
|
|
|
self.iface = None
|
|
|
|
self.nu_lookup = None
|
|
|
|
self.services = None
|
|
|
|
self.srv_uuid_adv = None
|
|
|
|
self.srv_uuid_fallback = None
|
2021-04-07 07:43:02 -04:00
|
|
|
|
2022-06-07 12:16:23 -04:00
|
|
|
async def connect(self, devname, iface, chrc_names, fallback_srv_uuid):
|
2018-07-30 12:10:10 -04:00
|
|
|
self.devname = devname
|
2019-05-09 17:36:56 -04:00
|
|
|
self.srv_uuid_fallback = fallback_srv_uuid
|
|
|
|
self.chrc_names = [name.lower() for name in chrc_names]
|
2022-06-22 05:44:19 -04:00
|
|
|
self.iface = iface
|
2018-07-30 12:10:10 -04:00
|
|
|
|
2022-06-07 12:16:23 -04:00
|
|
|
print('Discovering...')
|
2018-07-30 12:10:10 -04:00
|
|
|
try:
|
2023-07-19 04:35:55 -04:00
|
|
|
discovery = await bleak.BleakScanner.discover(return_adv=True)
|
|
|
|
devices = list(discovery.values())
|
2022-06-07 12:16:23 -04:00
|
|
|
except bleak.exc.BleakDBusError as e:
|
|
|
|
if str(e) == '[org.bluez.Error.NotReady] Resource Not Ready':
|
|
|
|
raise RuntimeError('Bluetooth is not ready. Maybe try `bluetoothctl power on`?')
|
|
|
|
raise
|
|
|
|
|
2022-06-07 18:55:10 -04:00
|
|
|
found_device = None
|
|
|
|
|
|
|
|
if self.devname is None:
|
|
|
|
if len(devices) == 0:
|
|
|
|
print('No devices found!')
|
|
|
|
exit(1)
|
|
|
|
|
|
|
|
while True:
|
|
|
|
devices.sort(key=device_sort)
|
|
|
|
print('==== BLE Discovery results ====')
|
|
|
|
print('{0: >4} {1: <33} {2: <12}'.format(
|
|
|
|
'S.N.', 'Name', 'Address'))
|
2022-06-22 05:44:19 -04:00
|
|
|
for i, _ in enumerate(devices):
|
2023-07-19 04:35:55 -04:00
|
|
|
print('[{0: >2}] {1: <33} {2: <12}'.format(i + 1, devices[i][0].name or 'Unknown', devices[i][0].address))
|
2022-06-07 18:55:10 -04:00
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
select = int(input('Select device by number (0 to rescan) : '))
|
|
|
|
if select < 0 or select > len(devices):
|
|
|
|
raise ValueError
|
|
|
|
break
|
|
|
|
except ValueError:
|
|
|
|
print('Invalid input! Retry')
|
|
|
|
|
|
|
|
if select != 0:
|
|
|
|
break
|
|
|
|
|
2023-07-19 04:35:55 -04:00
|
|
|
discovery = await bleak.BleakScanner.discover(return_adv=True)
|
|
|
|
devices = list(discovery.values())
|
2022-06-07 18:55:10 -04:00
|
|
|
|
2023-07-19 04:35:55 -04:00
|
|
|
self.devname = devices[select - 1][0].name
|
2023-08-22 05:14:38 -04:00
|
|
|
found_device = devices[select - 1]
|
2022-06-07 18:55:10 -04:00
|
|
|
else:
|
|
|
|
for d in devices:
|
2023-08-22 05:14:38 -04:00
|
|
|
if d[0].name == self.devname:
|
2022-06-07 18:55:10 -04:00
|
|
|
found_device = d
|
|
|
|
|
|
|
|
if not found_device:
|
2022-06-07 12:16:23 -04:00
|
|
|
raise RuntimeError('Device not found')
|
|
|
|
|
2023-08-22 05:14:38 -04:00
|
|
|
uuids = found_device[1].service_uuids
|
2022-06-07 18:55:10 -04:00
|
|
|
# There should be 1 service UUID in advertising data
|
|
|
|
# If bluez had cached an old version of the advertisement data
|
|
|
|
# the list of uuids may be incorrect, in which case connection
|
|
|
|
# or service discovery may fail the first time. If that happens
|
|
|
|
# the cache will be refreshed before next retry
|
|
|
|
if len(uuids) == 1:
|
|
|
|
self.srv_uuid_adv = uuids[0]
|
|
|
|
|
2022-06-07 12:16:23 -04:00
|
|
|
print('Connecting...')
|
2023-08-22 05:14:38 -04:00
|
|
|
self.device = bleak.BleakClient(found_device[0].address)
|
2022-06-07 12:16:23 -04:00
|
|
|
await self.device.connect()
|
|
|
|
# must be paired on Windows to access characteristics;
|
|
|
|
# cannot be paired on Mac
|
|
|
|
if platform.system() == 'Windows':
|
|
|
|
await self.device.pair()
|
|
|
|
|
|
|
|
print('Getting Services...')
|
2023-07-19 04:35:55 -04:00
|
|
|
services = self.device.services
|
2022-06-07 12:16:23 -04:00
|
|
|
|
|
|
|
service = services[self.srv_uuid_adv] or services[self.srv_uuid_fallback]
|
|
|
|
if not service:
|
|
|
|
await self.device.disconnect()
|
2018-07-30 12:10:10 -04:00
|
|
|
self.device = None
|
2022-06-07 12:16:23 -04:00
|
|
|
raise RuntimeError('Provisioning service not found')
|
|
|
|
|
|
|
|
nu_lookup = dict()
|
|
|
|
for characteristic in service.characteristics:
|
|
|
|
for descriptor in characteristic.descriptors:
|
|
|
|
if descriptor.uuid[4:8] != '2901':
|
2019-05-09 17:36:56 -04:00
|
|
|
continue
|
2022-06-07 12:16:23 -04:00
|
|
|
readval = await self.device.read_gatt_descriptor(descriptor.handle)
|
|
|
|
found_name = ''.join(chr(b) for b in readval).lower()
|
|
|
|
nu_lookup[found_name] = characteristic.uuid
|
|
|
|
self.characteristics[characteristic.uuid] = characteristic
|
|
|
|
|
|
|
|
match_found = True
|
|
|
|
for name in self.chrc_names:
|
|
|
|
if name not in nu_lookup:
|
|
|
|
# Endpoint name not present
|
|
|
|
match_found = False
|
2019-05-09 17:36:56 -04:00
|
|
|
break
|
|
|
|
|
2022-06-07 12:16:23 -04:00
|
|
|
# Create lookup table only if all endpoint names found
|
|
|
|
self.nu_lookup = [None, nu_lookup][match_found]
|
|
|
|
|
|
|
|
return True
|
2018-07-30 12:10:10 -04:00
|
|
|
|
2019-05-09 17:36:56 -04:00
|
|
|
def get_nu_lookup(self):
|
|
|
|
return self.nu_lookup
|
2018-07-30 12:10:10 -04:00
|
|
|
|
|
|
|
def has_characteristic(self, uuid):
|
2022-06-07 12:16:23 -04:00
|
|
|
print('checking for characteristic ' + uuid)
|
2019-05-09 17:36:56 -04:00
|
|
|
if uuid in self.characteristics:
|
2018-07-30 12:10:10 -04:00
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2022-06-07 12:16:23 -04:00
|
|
|
async def disconnect(self):
|
2018-07-30 12:10:10 -04:00
|
|
|
if self.device:
|
2022-06-07 12:16:23 -04:00
|
|
|
print('Disconnecting...')
|
|
|
|
if platform.system() == 'Windows':
|
|
|
|
await self.device.unpair()
|
|
|
|
await self.device.disconnect()
|
2018-11-08 02:44:54 -05:00
|
|
|
self.device = None
|
2019-05-09 17:36:56 -04:00
|
|
|
self.nu_lookup = None
|
|
|
|
self.characteristics = dict()
|
2019-03-14 07:58:26 -04:00
|
|
|
|
2022-06-07 12:16:23 -04:00
|
|
|
async def send_data(self, characteristic_uuid, data):
|
|
|
|
await self.device.write_gatt_char(characteristic_uuid, bytearray(data.encode('latin-1')), True)
|
|
|
|
readval = await self.device.read_gatt_char(characteristic_uuid)
|
2019-03-14 07:58:26 -04:00
|
|
|
return ''.join(chr(b) for b in readval)
|
2018-12-01 08:23:34 -05:00
|
|
|
# --------------------------------------------------------------------
|
|
|
|
|
2018-07-30 12:10:10 -04:00
|
|
|
|
|
|
|
# Console based BLE client for Cross Platform support
|
|
|
|
class BLE_Console_Client:
|
2022-06-07 12:16:23 -04:00
|
|
|
async def connect(self, devname, iface, chrc_names, fallback_srv_uuid):
|
2021-01-25 21:49:01 -05:00
|
|
|
print('BLE client is running in console mode')
|
|
|
|
print('\tThis could be due to your platform not being supported or dependencies not being met')
|
|
|
|
print('\tPlease ensure all pre-requisites are met to run the full fledged client')
|
|
|
|
print('BLECLI >> Please connect to BLE device `' + devname + '` manually using your tool of choice')
|
|
|
|
resp = input('BLECLI >> Was the device connected successfully? [y/n] ')
|
2018-07-30 12:10:10 -04:00
|
|
|
if resp != 'Y' and resp != 'y':
|
|
|
|
return False
|
2021-01-25 21:49:01 -05:00
|
|
|
print('BLECLI >> List available attributes of the connected device')
|
2019-05-09 17:36:56 -04:00
|
|
|
resp = input("BLECLI >> Is the service UUID '" + fallback_srv_uuid + "' listed among available attributes? [y/n] ")
|
2018-07-30 12:10:10 -04:00
|
|
|
if resp != 'Y' and resp != 'y':
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2019-05-09 17:36:56 -04:00
|
|
|
def get_nu_lookup(self):
|
|
|
|
return None
|
|
|
|
|
2018-07-30 12:10:10 -04:00
|
|
|
def has_characteristic(self, uuid):
|
|
|
|
resp = input("BLECLI >> Is the characteristic UUID '" + uuid + "' listed among available attributes? [y/n] ")
|
|
|
|
if resp != 'Y' and resp != 'y':
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2022-06-07 12:16:23 -04:00
|
|
|
async def disconnect(self):
|
2018-07-30 12:10:10 -04:00
|
|
|
pass
|
|
|
|
|
2022-06-07 12:16:23 -04:00
|
|
|
async def send_data(self, characteristic_uuid, data):
|
2018-07-30 12:10:10 -04:00
|
|
|
print("BLECLI >> Write following data to characteristic with UUID '" + characteristic_uuid + "' :")
|
2022-06-22 05:44:19 -04:00
|
|
|
print('\t>> ' + str_to_bytes(data).hex())
|
2021-01-25 21:49:01 -05:00
|
|
|
print('BLECLI >> Enter data read from characteristic (in hex) :')
|
|
|
|
resp = input('\t<< ')
|
2022-06-22 05:44:19 -04:00
|
|
|
return hex_str_to_bytes(resp)
|
2018-07-30 12:10:10 -04:00
|
|
|
|
2018-12-01 08:23:34 -05:00
|
|
|
|
|
|
|
# --------------------------------------------------------------------
|
|
|
|
|
2018-07-30 12:10:10 -04:00
|
|
|
|
|
|
|
# Function to get client instance depending upon platform
|
|
|
|
def get_client():
|
|
|
|
if fallback:
|
|
|
|
return BLE_Console_Client()
|
2022-06-07 12:16:23 -04:00
|
|
|
return BLE_Bleak_Client()
|