caerulea 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- caerulea/__init__.py +43 -0
- caerulea/__main__.py +309 -0
- caerulea/backends/__init__.py +32 -0
- caerulea/backends/android.py +634 -0
- caerulea/backends/android_proxies.py +88 -0
- caerulea/backends/base.py +138 -0
- caerulea/backends/bluez.py +778 -0
- caerulea/backends/corebluetooth.py +605 -0
- caerulea/backends/fake.py +326 -0
- caerulea/backends/winrt.py +711 -0
- caerulea/central.py +656 -0
- caerulea/errors.py +42 -0
- caerulea/model.py +108 -0
- caerulea/uuids.py +95 -0
- caerulea-0.1.0.dist-info/METADATA +102 -0
- caerulea-0.1.0.dist-info/RECORD +20 -0
- caerulea-0.1.0.dist-info/WHEEL +5 -0
- caerulea-0.1.0.dist-info/entry_points.txt +2 -0
- caerulea-0.1.0.dist-info/licenses/LICENSE +27 -0
- caerulea-0.1.0.dist-info/top_level.txt +1 -0
caerulea/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""caerulea: an asyncio Bluetooth Low Energy central library."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version as _version
|
|
4
|
+
|
|
5
|
+
from .central import Central, Connection, Scanner, Subscription
|
|
6
|
+
from .errors import (
|
|
7
|
+
AdapterUnavailable,
|
|
8
|
+
AttributeNotFound,
|
|
9
|
+
BluetoothError,
|
|
10
|
+
ConnectionFailed,
|
|
11
|
+
DeviceNotFound,
|
|
12
|
+
GattError,
|
|
13
|
+
NotConnected,
|
|
14
|
+
PermissionDenied,
|
|
15
|
+
)
|
|
16
|
+
from .model import Advertisement, Characteristic, Descriptor, Properties, Service
|
|
17
|
+
from .uuids import describe_uuid, format_uuid, normalize_uuid, short_uuid
|
|
18
|
+
|
|
19
|
+
__version__ = _version("caerulea")
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"AdapterUnavailable",
|
|
23
|
+
"Advertisement",
|
|
24
|
+
"AttributeNotFound",
|
|
25
|
+
"BluetoothError",
|
|
26
|
+
"Central",
|
|
27
|
+
"Characteristic",
|
|
28
|
+
"Connection",
|
|
29
|
+
"ConnectionFailed",
|
|
30
|
+
"Descriptor",
|
|
31
|
+
"DeviceNotFound",
|
|
32
|
+
"GattError",
|
|
33
|
+
"NotConnected",
|
|
34
|
+
"PermissionDenied",
|
|
35
|
+
"Properties",
|
|
36
|
+
"Scanner",
|
|
37
|
+
"Service",
|
|
38
|
+
"Subscription",
|
|
39
|
+
"describe_uuid",
|
|
40
|
+
"format_uuid",
|
|
41
|
+
"normalize_uuid",
|
|
42
|
+
"short_uuid",
|
|
43
|
+
]
|
caerulea/__main__.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"""Command-line tools for exploring BLE peripherals.
|
|
2
|
+
|
|
3
|
+
caerulea scan [--timeout S] [--name NAME] [--service UUID] [--every-packet]
|
|
4
|
+
caerulea explore TARGET [--no-read]
|
|
5
|
+
caerulea listen TARGET [UUID ...] [--duration S] [--reconnect] [--log FILE]
|
|
6
|
+
caerulea write TARGET UUID HEX [--no-response]
|
|
7
|
+
|
|
8
|
+
TARGET is a peripheral's identifier (a MAC address, or a UUID on Apple
|
|
9
|
+
platforms) or its advertised name.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import asyncio
|
|
16
|
+
import contextlib
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import re
|
|
20
|
+
import sys
|
|
21
|
+
import time
|
|
22
|
+
from datetime import datetime
|
|
23
|
+
|
|
24
|
+
from . import (
|
|
25
|
+
Advertisement,
|
|
26
|
+
BluetoothError,
|
|
27
|
+
Central,
|
|
28
|
+
Connection,
|
|
29
|
+
Properties,
|
|
30
|
+
describe_uuid,
|
|
31
|
+
normalize_uuid,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
IDENTIFIER = re.compile(
|
|
35
|
+
r"^([0-9a-f]{2}:){5}[0-9a-f]{2}$|^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$",
|
|
36
|
+
re.IGNORECASE,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def hexdump(data: bytes) -> str:
|
|
41
|
+
text = "".join(chr(b) if 32 <= b < 127 else "." for b in data)
|
|
42
|
+
return f"{data.hex(' ')} |{text}|" if data else "(empty)"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def stamp() -> str:
|
|
46
|
+
return datetime.now().strftime("%H:%M:%S.%f")[:-3]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def describe_advertisement(adv: Advertisement) -> str:
|
|
50
|
+
parts = [f"{adv.identifier} {adv.name or '(no name)'} rssi={adv.rssi}"]
|
|
51
|
+
if adv.connectable is False:
|
|
52
|
+
parts.append("not-connectable")
|
|
53
|
+
if adv.tx_power is not None:
|
|
54
|
+
parts.append(f"tx={adv.tx_power}")
|
|
55
|
+
for u in adv.service_uuids:
|
|
56
|
+
parts.append(f"service={describe_uuid(u)}")
|
|
57
|
+
for company, data in adv.manufacturer_data.items():
|
|
58
|
+
parts.append(f"mfr[{company:#06x}]={data.hex(' ')}")
|
|
59
|
+
for u, data in adv.service_data.items():
|
|
60
|
+
parts.append(f"data[{describe_uuid(u)}]={data.hex(' ')}")
|
|
61
|
+
return " ".join(parts)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
async def find_target(central: Central, target: str, timeout: float) -> Advertisement:
|
|
65
|
+
if IDENTIFIER.match(target):
|
|
66
|
+
return await central.find(identifier=target, timeout=timeout)
|
|
67
|
+
# Names often carry a serial-number suffix, so match on the prefix.
|
|
68
|
+
return await central.find(
|
|
69
|
+
match=lambda a: bool(a.name and a.name.startswith(target)), timeout=timeout
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def cmd_scan(central: Central, args) -> None:
|
|
74
|
+
services = [args.service] if args.service else []
|
|
75
|
+
seen: dict[str, Advertisement] = {}
|
|
76
|
+
content: dict[str, tuple] = {}
|
|
77
|
+
async with central.scan(service_uuids=services, timeout=args.timeout) as scanner:
|
|
78
|
+
async for adv in scanner:
|
|
79
|
+
if args.name and adv.name != args.name:
|
|
80
|
+
continue
|
|
81
|
+
# Print a device when first seen and whenever what it advertises
|
|
82
|
+
# changes; RSSI alone doesn't count.
|
|
83
|
+
key = (
|
|
84
|
+
adv.name,
|
|
85
|
+
adv.service_uuids,
|
|
86
|
+
sorted(adv.manufacturer_data.items()),
|
|
87
|
+
sorted((str(k), v) for k, v in adv.service_data.items()),
|
|
88
|
+
)
|
|
89
|
+
if args.every_packet or content.get(adv.identifier) != key:
|
|
90
|
+
print(
|
|
91
|
+
f"{stamp()} {'new ' if adv.identifier not in seen else 'chg '}"
|
|
92
|
+
f"{describe_advertisement(adv)}"
|
|
93
|
+
)
|
|
94
|
+
content[adv.identifier] = key
|
|
95
|
+
seen[adv.identifier] = adv
|
|
96
|
+
print(f"\n{len(seen)} peripheral(s) seen.")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
async def cmd_explore(central: Central, args) -> None:
|
|
100
|
+
adv = await find_target(central, args.target, args.timeout)
|
|
101
|
+
print(describe_advertisement(adv))
|
|
102
|
+
async with await central.connect(adv) as conn:
|
|
103
|
+
print(f"Connected; ATT MTU {conn.mtu}\n")
|
|
104
|
+
for svc in conn.services:
|
|
105
|
+
print(
|
|
106
|
+
f"Service {describe_uuid(svc.uuid)}"
|
|
107
|
+
f"{'' if svc.primary else ' (secondary)'}"
|
|
108
|
+
)
|
|
109
|
+
for ch in svc.characteristics:
|
|
110
|
+
print(
|
|
111
|
+
f" Characteristic {describe_uuid(ch.uuid)} "
|
|
112
|
+
f"[{ch.properties.describe()}]"
|
|
113
|
+
)
|
|
114
|
+
if Properties.READ in ch.properties and not args.no_read:
|
|
115
|
+
try:
|
|
116
|
+
print(f" value: {hexdump(await conn.read(ch))}")
|
|
117
|
+
except (BluetoothError, TimeoutError) as exc:
|
|
118
|
+
print(f" value: <{exc}>")
|
|
119
|
+
for desc in ch.descriptors:
|
|
120
|
+
line = f" Descriptor {describe_uuid(desc.uuid)}"
|
|
121
|
+
if not args.no_read:
|
|
122
|
+
try:
|
|
123
|
+
line += f": {hexdump(await conn.read_descriptor(desc))}"
|
|
124
|
+
except (BluetoothError, TimeoutError) as exc:
|
|
125
|
+
line += f": <{exc}>"
|
|
126
|
+
print(line)
|
|
127
|
+
print()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
async def _listen_once(
|
|
131
|
+
conn: Connection, uuids: list, log_file, deadline: float | None
|
|
132
|
+
) -> None:
|
|
133
|
+
if uuids:
|
|
134
|
+
chars = [conn.characteristic(u) for u in uuids]
|
|
135
|
+
else:
|
|
136
|
+
chars = [
|
|
137
|
+
c
|
|
138
|
+
for s in conn.services
|
|
139
|
+
for c in s.characteristics
|
|
140
|
+
if c.properties & (Properties.NOTIFY | Properties.INDICATE)
|
|
141
|
+
]
|
|
142
|
+
if not chars:
|
|
143
|
+
print("Nothing on this peripheral can notify.")
|
|
144
|
+
return
|
|
145
|
+
merged: asyncio.Queue = asyncio.Queue()
|
|
146
|
+
|
|
147
|
+
async def pump(sub):
|
|
148
|
+
async for data in sub:
|
|
149
|
+
await merged.put((sub.characteristic, data))
|
|
150
|
+
|
|
151
|
+
async with contextlib.AsyncExitStack() as stack:
|
|
152
|
+
tasks = []
|
|
153
|
+
for ch in chars:
|
|
154
|
+
sub = await stack.enter_async_context(conn.subscribe(ch))
|
|
155
|
+
print(f"{stamp()} subscribed to {describe_uuid(ch.uuid)}")
|
|
156
|
+
tasks.append(asyncio.create_task(pump(sub)))
|
|
157
|
+
closed = asyncio.create_task(conn.wait_disconnected())
|
|
158
|
+
try:
|
|
159
|
+
while True:
|
|
160
|
+
remaining = None if deadline is None else deadline - time.monotonic()
|
|
161
|
+
if remaining is not None and remaining <= 0:
|
|
162
|
+
return
|
|
163
|
+
get = asyncio.create_task(merged.get())
|
|
164
|
+
done, _ = await asyncio.wait(
|
|
165
|
+
{get, closed},
|
|
166
|
+
timeout=remaining,
|
|
167
|
+
return_when=asyncio.FIRST_COMPLETED,
|
|
168
|
+
)
|
|
169
|
+
if get not in done:
|
|
170
|
+
get.cancel()
|
|
171
|
+
if closed in done:
|
|
172
|
+
reason = conn.disconnect_error
|
|
173
|
+
print(
|
|
174
|
+
f"{stamp()} disconnected{f': {reason}' if reason else ''}"
|
|
175
|
+
)
|
|
176
|
+
return
|
|
177
|
+
continue
|
|
178
|
+
ch, data = get.result()
|
|
179
|
+
print(f"{stamp()} {describe_uuid(ch.uuid)} {hexdump(data)}")
|
|
180
|
+
if log_file:
|
|
181
|
+
log_file.write(
|
|
182
|
+
json.dumps(
|
|
183
|
+
{
|
|
184
|
+
"time": datetime.now().isoformat(),
|
|
185
|
+
"identifier": conn.identifier,
|
|
186
|
+
"characteristic": str(ch.uuid),
|
|
187
|
+
"data": data.hex(),
|
|
188
|
+
}
|
|
189
|
+
)
|
|
190
|
+
+ "\n"
|
|
191
|
+
)
|
|
192
|
+
log_file.flush()
|
|
193
|
+
finally:
|
|
194
|
+
closed.cancel()
|
|
195
|
+
for t in tasks:
|
|
196
|
+
t.cancel()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
async def cmd_listen(central: Central, args) -> None:
|
|
200
|
+
uuids = [normalize_uuid(u) for u in args.uuids]
|
|
201
|
+
deadline = None if args.duration is None else time.monotonic() + args.duration
|
|
202
|
+
log_file = open(args.log, "a") if args.log else None # noqa: ASYNC230, SIM115
|
|
203
|
+
try:
|
|
204
|
+
while True:
|
|
205
|
+
print(f"{stamp()} looking for {args.target}…")
|
|
206
|
+
try:
|
|
207
|
+
adv = await find_target(central, args.target, args.timeout)
|
|
208
|
+
print(f"{stamp()} found {describe_advertisement(adv)}")
|
|
209
|
+
async with await central.connect(adv) as conn:
|
|
210
|
+
print(f"{stamp()} connected (ATT MTU {conn.mtu})")
|
|
211
|
+
await _listen_once(conn, uuids, log_file, deadline)
|
|
212
|
+
except (BluetoothError, TimeoutError) as exc:
|
|
213
|
+
print(f"{stamp()} {type(exc).__name__}: {exc}")
|
|
214
|
+
if not args.reconnect:
|
|
215
|
+
raise
|
|
216
|
+
if not args.reconnect or (
|
|
217
|
+
deadline is not None and time.monotonic() >= deadline
|
|
218
|
+
):
|
|
219
|
+
return
|
|
220
|
+
finally:
|
|
221
|
+
if log_file:
|
|
222
|
+
log_file.close()
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
async def cmd_write(central: Central, args) -> None:
|
|
226
|
+
data = bytes.fromhex(args.hex.replace(":", " "))
|
|
227
|
+
adv = await find_target(central, args.target, args.timeout)
|
|
228
|
+
async with await central.connect(adv) as conn:
|
|
229
|
+
await conn.write(args.uuid, data, response=False if args.no_response else None)
|
|
230
|
+
print(f"Wrote {hexdump(data)} to {describe_uuid(normalize_uuid(args.uuid))}")
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def main(argv: list[str] | None = None) -> None:
|
|
234
|
+
parser = argparse.ArgumentParser(
|
|
235
|
+
prog="caerulea", description="Explore Bluetooth LE peripherals."
|
|
236
|
+
)
|
|
237
|
+
parser.add_argument(
|
|
238
|
+
"-v", "--verbose", action="store_true", help="log every operation"
|
|
239
|
+
)
|
|
240
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
241
|
+
|
|
242
|
+
p = commands.add_parser("scan", help="list advertising peripherals")
|
|
243
|
+
p.add_argument("--timeout", type=float, default=10.0)
|
|
244
|
+
p.add_argument("--name", help="only show peripherals with this name")
|
|
245
|
+
p.add_argument("--service", help="only peripherals advertising this service UUID")
|
|
246
|
+
p.add_argument(
|
|
247
|
+
"--every-packet",
|
|
248
|
+
action="store_true",
|
|
249
|
+
help="print every packet, not just changes",
|
|
250
|
+
)
|
|
251
|
+
p.set_defaults(func=cmd_scan)
|
|
252
|
+
|
|
253
|
+
p = commands.add_parser(
|
|
254
|
+
"explore", help="connect and print the GATT table with values"
|
|
255
|
+
)
|
|
256
|
+
p.add_argument("target")
|
|
257
|
+
p.add_argument(
|
|
258
|
+
"--timeout", type=float, default=20.0, help="how long to look for the target"
|
|
259
|
+
)
|
|
260
|
+
p.add_argument("--no-read", action="store_true", help="don't read values")
|
|
261
|
+
p.set_defaults(func=cmd_explore)
|
|
262
|
+
|
|
263
|
+
p = commands.add_parser("listen", help="print notifications as they arrive")
|
|
264
|
+
p.add_argument("target")
|
|
265
|
+
p.add_argument(
|
|
266
|
+
"uuids", nargs="*", help="characteristics to subscribe to (default: all)"
|
|
267
|
+
)
|
|
268
|
+
p.add_argument(
|
|
269
|
+
"--timeout", type=float, default=60.0, help="how long to look for the target"
|
|
270
|
+
)
|
|
271
|
+
p.add_argument("--duration", type=float, help="stop after this many seconds")
|
|
272
|
+
p.add_argument(
|
|
273
|
+
"--reconnect",
|
|
274
|
+
action="store_true",
|
|
275
|
+
help="find and reconnect after each disconnection",
|
|
276
|
+
)
|
|
277
|
+
p.add_argument("--log", help="append notifications to this JSON Lines file")
|
|
278
|
+
p.set_defaults(func=cmd_listen)
|
|
279
|
+
|
|
280
|
+
p = commands.add_parser("write", help="write bytes to a characteristic")
|
|
281
|
+
p.add_argument("target")
|
|
282
|
+
p.add_argument("uuid")
|
|
283
|
+
p.add_argument("hex", help="bytes to write, e.g. '01 02 0a'")
|
|
284
|
+
p.add_argument(
|
|
285
|
+
"--timeout", type=float, default=20.0, help="how long to look for the target"
|
|
286
|
+
)
|
|
287
|
+
p.add_argument("--no-response", action="store_true", help="use a write command")
|
|
288
|
+
p.set_defaults(func=cmd_write)
|
|
289
|
+
|
|
290
|
+
args = parser.parse_args(argv)
|
|
291
|
+
logging.basicConfig(
|
|
292
|
+
level=logging.DEBUG if args.verbose else logging.WARNING,
|
|
293
|
+
format="%(asctime)s %(name)s %(levelname)s %(message)s",
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
async def run() -> None:
|
|
297
|
+
async with Central() as central:
|
|
298
|
+
await args.func(central, args)
|
|
299
|
+
|
|
300
|
+
try:
|
|
301
|
+
asyncio.run(run())
|
|
302
|
+
except KeyboardInterrupt:
|
|
303
|
+
pass
|
|
304
|
+
except (BluetoothError, TimeoutError) as exc:
|
|
305
|
+
sys.exit(f"{type(exc).__name__}: {exc}")
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
if __name__ == "__main__":
|
|
309
|
+
main()
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Platform backends. `default_backend()` picks the one for this platform."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from .base import Backend, BackendConnection, ConnectionEvents
|
|
8
|
+
|
|
9
|
+
__all__ = ["Backend", "BackendConnection", "ConnectionEvents", "default_backend"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def default_backend() -> Backend:
|
|
13
|
+
if sys.platform == "android" or hasattr(sys, "getandroidapilevel"):
|
|
14
|
+
from .android import AndroidBackend
|
|
15
|
+
|
|
16
|
+
return AndroidBackend()
|
|
17
|
+
if sys.platform == "win32":
|
|
18
|
+
from .winrt import WinRTBackend
|
|
19
|
+
|
|
20
|
+
return WinRTBackend()
|
|
21
|
+
if sys.platform in ("darwin", "ios"):
|
|
22
|
+
from .corebluetooth import CoreBluetoothBackend
|
|
23
|
+
|
|
24
|
+
return CoreBluetoothBackend()
|
|
25
|
+
if sys.platform == "linux":
|
|
26
|
+
from .bluez import BlueZBackend
|
|
27
|
+
|
|
28
|
+
return BlueZBackend()
|
|
29
|
+
raise NotImplementedError(
|
|
30
|
+
f"caerulea has no backend for {sys.platform!r}; "
|
|
31
|
+
"pass backend=FakeBackend(...) to test without hardware."
|
|
32
|
+
)
|