-
Notifications
You must be signed in to change notification settings - Fork 30
/
gattserver.py
99 lines (85 loc) · 2.89 KB
/
gattserver.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""
Example for a BLE 4.0 Server using a GATT dictionary of services and
characteristics
"""
import sys
import logging
import asyncio
import threading
from typing import Any, Dict, Union
from bless import ( # type: ignore
BlessServer,
BlessGATTCharacteristic,
GATTCharacteristicProperties,
GATTAttributePermissions,
)
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(name=__name__)
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
gatt: Dict = {
"A07498CA-AD5B-474E-940D-16F1FBE7E8CD": {
"51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B": {
"Properties": (
GATTCharacteristicProperties.read
| GATTCharacteristicProperties.write
| GATTCharacteristicProperties.indicate
),
"Permissions": (
GATTAttributePermissions.readable
| GATTAttributePermissions.writeable
),
"Value": None,
}
},
"5c339364-c7be-4f23-b666-a8ff73a6a86a": {
"bfc0c92f-317d-4ba9-976b-cc11ce77b4ca": {
"Properties": GATTCharacteristicProperties.read,
"Permissions": GATTAttributePermissions.readable,
"Value": bytearray(b"\x69"),
}
},
}
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
await server.add_gatt(gatt)
await server.start()
logger.debug(server.get_characteristic("51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B"))
logger.debug("Advertising")
logger.info(
"Write '0xF' to the advertised characteristic: "
+ "51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B"
)
if trigger.__module__ == "threading":
trigger.wait()
else:
await trigger.wait()
await asyncio.sleep(2)
logger.debug("Updating")
server.get_characteristic("51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B").value = bytearray(
b"i"
)
server.update_value(
"A07498CA-AD5B-474E-940D-16F1FBE7E8CD", "51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B"
)
await asyncio.sleep(5)
await server.stop()
loop = asyncio.get_event_loop()
loop.run_until_complete(run(loop))