-
Notifications
You must be signed in to change notification settings - Fork 30
/
server.py
84 lines (68 loc) · 2.42 KB
/
server.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""
Example for a BLE 4.0 Server
"""
import sys
import logging
import asyncio
import threading
from typing import Any, Union
from bless import ( # type: ignore
BlessServer,
BlessGATTCharacteristic,
GATTCharacteristicProperties,
GATTAttributePermissions,
)
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(name=__name__)
# NOTE: Some systems require different synchronization methods.
trigger: Union[asyncio.Event, threading.Event]
if sys.platform in ["darwin", "win32"]:
trigger = threading.Event()
else:
trigger = asyncio.Event()
def read_request(characteristic: BlessGATTCharacteristic, **kwargs) -> bytearray:
logger.debug(f"Reading {characteristic.value}")
return characteristic.value
def write_request(characteristic: BlessGATTCharacteristic, value: Any, **kwargs):
characteristic.value = value
logger.debug(f"Char value set to {characteristic.value}")
if characteristic.value == b"\x0f":
logger.debug("NICE")
trigger.set()
async def run(loop):
trigger.clear()
# Instantiate the server
my_service_name = "Test Service"
server = BlessServer(name=my_service_name, loop=loop)
server.read_request_func = read_request
server.write_request_func = write_request
# Add Service
my_service_uuid = "A07498CA-AD5B-474E-940D-16F1FBE7E8CD"
await server.add_new_service(my_service_uuid)
# Add a Characteristic to the service
my_char_uuid = "51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B"
char_flags = (
GATTCharacteristicProperties.read
| GATTCharacteristicProperties.write
| GATTCharacteristicProperties.indicate
)
permissions = GATTAttributePermissions.readable | GATTAttributePermissions.writeable
await server.add_new_characteristic(
my_service_uuid, my_char_uuid, char_flags, None, permissions
)
logger.debug(server.get_characteristic(my_char_uuid))
await server.start()
logger.debug("Advertising")
logger.info(f"Write '0xF' to the advertised characteristic: {my_char_uuid}")
if trigger.__module__ == "threading":
trigger.wait()
else:
await trigger.wait()
await asyncio.sleep(2)
logger.debug("Updating")
server.get_characteristic(my_char_uuid)
server.update_value(my_service_uuid, "51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B")
await asyncio.sleep(5)
await server.stop()
loop = asyncio.get_event_loop()
loop.run_until_complete(run(loop))