-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.py
50 lines (40 loc) · 1.27 KB
/
monitor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import json
import logging
import asyncio
from io import StringIO
from ble_serial.bluetooth.ble_interface import BLE_interface
async def main():
ADAPTER = "hci0"
SERVICE_UUID = None
WRITE_UUID = "0000fff2-0000-1000-8000-00805f9b34fb"
READ_UUID = "0000fff1-0000-1000-8000-00805f9b34fb"
DEVICE = "EC:23:08:00:3C:39"
lines = asyncio.Queue()
cache = StringIO()
def receive_callback(data: bytes):
for b in data:
if chr(b) == '\n':
lines.put_nowait(cache.getvalue())
cache.seek(0)
cache.truncate()
else:
cache.write(chr(b))
async def print_data():
while True:
data = await lines.get()
try:
json_data = json.loads(data)
print(json_data)
except json.JSONDecodeError:
...
ble = BLE_interface(ADAPTER, SERVICE_UUID)
ble.set_receiver(receive_callback)
try:
await ble.connect(DEVICE, "public", 10.0)
await ble.setup_chars(WRITE_UUID, READ_UUID, "rw")
await asyncio.gather(ble.send_loop(), print_data())
finally:
await ble.disconnect()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
asyncio.run(main())