1
|
|
|
"""Interface to the BLEAK library in Linux for BLE calls |
2
|
|
|
|
3
|
|
|
""" |
4
|
|
|
import curio, asyncio, threading, logging |
5
|
|
|
from curio.bridge import AsyncioLoop |
6
|
|
|
|
7
|
|
|
import bleak |
8
|
|
|
from bleak import BleakClient |
9
|
|
|
|
10
|
|
|
class Bleak: |
11
|
|
|
|
12
|
|
|
def __init__(self): |
13
|
|
|
# Need to start an event loop |
14
|
|
|
self.in_queue = curio.UniversalQueue() # Incoming message queue |
15
|
|
|
self.out_queue = curio.UniversalQueue() # Outgoing message queue |
16
|
|
|
|
17
|
|
|
self.devices = [] |
18
|
|
|
#self.loop = threading.Thread(target=self.run, daemon=True) |
19
|
|
|
#self.loop.start() |
20
|
|
|
|
21
|
|
|
def run(self): |
22
|
|
|
#self.loop = asyncio.new_event_loop() |
23
|
|
|
#asyncio.set_event_loop(self.loop) |
24
|
|
|
self.loop = asyncio.get_event_loop() |
25
|
|
|
self.loop.run_until_complete(self.asyncio_loop()) |
26
|
|
|
|
27
|
|
|
async def asyncio_loop(self): |
28
|
|
|
|
29
|
|
|
# Wait for messages on in_queue |
30
|
|
|
done = False |
31
|
|
|
while not done: |
32
|
|
|
msg = await self.in_queue.get() |
33
|
|
|
if isinstance(msg, tuple): |
34
|
|
|
msg, val = msg |
35
|
|
|
await self.in_queue.task_done() |
36
|
|
|
if msg == 'discover': |
37
|
|
|
print('Awaiting on bleak discover') |
38
|
|
|
devices = await bleak.discover(timeout=1, loop=self.loop) |
39
|
|
|
print('Done Awaiting on bleak discover') |
40
|
|
|
await self.out_queue.put(devices) |
41
|
|
|
elif msg == 'connect': |
42
|
|
|
device = BleakClient(address=val, loop=self.loop) |
|
|
|
|
43
|
|
|
self.devices.append(device) |
44
|
|
|
await device.connect() |
45
|
|
|
await self.out_queue.put(device) |
46
|
|
|
elif msg == 'tx': |
47
|
|
|
device, char_uuid, msg_bytes = val |
48
|
|
|
await device.write_gatt_char(char_uuid, msg_bytes) |
49
|
|
|
elif msg == 'notify': |
50
|
|
|
device, char_uuid, msg_handler = val |
51
|
|
|
await device.start_notify(char_uuid, msg_handler) |
52
|
|
|
elif msg =='quit': |
53
|
|
|
logging.info('quitting') |
54
|
|
|
for device in self.devices: |
55
|
|
|
await device.disconnect() |
56
|
|
|
done = True |
57
|
|
|
else: |
58
|
|
|
print(f'Unknown message to Bleak: {msg}') |
59
|
|
|
|
60
|
|
|
|
61
|
|
|
|
62
|
|
|
|
63
|
|
|
|