pixeljoy-ble 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.
- pixeljoy/__init__.py +5 -0
- pixeljoy/__main__.py +274 -0
- pixeljoy/client.py +314 -0
- pixeljoy/devices.json +562 -0
- pixeljoy/protocol.py +773 -0
- pixeljoy/render.py +48 -0
- pixeljoy_ble-0.1.0.dist-info/METADATA +149 -0
- pixeljoy_ble-0.1.0.dist-info/RECORD +12 -0
- pixeljoy_ble-0.1.0.dist-info/WHEEL +5 -0
- pixeljoy_ble-0.1.0.dist-info/entry_points.txt +2 -0
- pixeljoy_ble-0.1.0.dist-info/licenses/LICENSE +21 -0
- pixeljoy_ble-0.1.0.dist-info/top_level.txt +1 -0
pixeljoy/__init__.py
ADDED
pixeljoy/__main__.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""CLI: python -m pixeljoy {scan,gatt,info,time,clock,power,brightness,text,image,gif,raw}"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
import traceback
|
|
12
|
+
from dataclasses import asdict
|
|
13
|
+
|
|
14
|
+
from . import protocol as P
|
|
15
|
+
|
|
16
|
+
# Text limits by READ_PROPERTY's support600Txt flag (char indices are u8 vs u16).
|
|
17
|
+
TEXT_MAX = {False: 100, True: 600}
|
|
18
|
+
|
|
19
|
+
EXIT_ERROR, EXIT_INTERRUPTED = 1, 130
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# -- argument types -----------------------------------------------------------
|
|
23
|
+
|
|
24
|
+
def hex_color(s: str) -> tuple[int, int, int]:
|
|
25
|
+
if not re.fullmatch(r"#?[0-9a-fA-F]{6}", s):
|
|
26
|
+
raise argparse.ArgumentTypeError(f"{s!r} is not a colour; use rrggbb or #rrggbb")
|
|
27
|
+
s = s.lstrip("#")
|
|
28
|
+
return tuple(int(s[i:i + 2], 16) for i in (0, 2, 4))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def int_range(lo: int, hi: int):
|
|
32
|
+
def parse(s: str) -> int:
|
|
33
|
+
try:
|
|
34
|
+
v = int(s, 0)
|
|
35
|
+
except ValueError:
|
|
36
|
+
raise argparse.ArgumentTypeError(f"{s!r} is not an integer") from None
|
|
37
|
+
if not lo <= v <= hi:
|
|
38
|
+
raise argparse.ArgumentTypeError(f"{v} is out of range {lo}-{hi}")
|
|
39
|
+
return v
|
|
40
|
+
parse.__name__ = f"integer {lo}-{hi}"
|
|
41
|
+
return parse
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def hex_byte(s: str) -> int:
|
|
45
|
+
try:
|
|
46
|
+
v = int(s, 16)
|
|
47
|
+
except ValueError:
|
|
48
|
+
v = -1
|
|
49
|
+
if not 0 <= v <= 0xFF:
|
|
50
|
+
raise argparse.ArgumentTypeError(f"{s!r} is not a hex byte 00-FF")
|
|
51
|
+
return v
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def hex_bytes(s: str) -> bytes:
|
|
55
|
+
try:
|
|
56
|
+
return bytes.fromhex(s)
|
|
57
|
+
except ValueError:
|
|
58
|
+
raise argparse.ArgumentTypeError(f"{s!r} is not hex (e.g. '01 ff' or '01ff')") from None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# -- commands -----------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
def _say(args, msg: str) -> None:
|
|
64
|
+
if not args.quiet:
|
|
65
|
+
print(msg)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def _pick(args):
|
|
69
|
+
from .client import find
|
|
70
|
+
|
|
71
|
+
f = await find(args.timeout, args.address, args.name)
|
|
72
|
+
_say(args, f"using {f.name} {f.device.address} -> {f.model.name} {f.model.width}x{f.model.height}")
|
|
73
|
+
return f
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
async def main_async(args) -> None:
|
|
77
|
+
from .client import PixelJoy, PixelJoyError, scan
|
|
78
|
+
|
|
79
|
+
if args.cmd == "scan":
|
|
80
|
+
for f in await scan(args.timeout, show_all=args.all):
|
|
81
|
+
m = f"{f.model.name} {f.model.width}x{f.model.height}" if f.model else "-"
|
|
82
|
+
mfr = {k: v.hex() for k, v in f.manufacturer_data.items()}
|
|
83
|
+
print(f"{f.device.address} rssi={f.rssi} name={f.name!r} model={m}\n uuids={f.service_uuids}\n mfr={mfr}")
|
|
84
|
+
return
|
|
85
|
+
|
|
86
|
+
f = await _pick(args)
|
|
87
|
+
if args.cmd == "gatt":
|
|
88
|
+
from .client import dump_gatt
|
|
89
|
+
|
|
90
|
+
await dump_gatt(f.device)
|
|
91
|
+
return
|
|
92
|
+
async with PixelJoy(f.device, f.model, auto_time_sync=not args.no_time_sync, tz_name=args.tz) as pj:
|
|
93
|
+
if args.cmd == "time":
|
|
94
|
+
if args.no_time_sync: # otherwise connect() already did it
|
|
95
|
+
await pj.sync_time(args.tz)
|
|
96
|
+
_say(args, f"clock synced ({args.tz or P._local_tz_name()})")
|
|
97
|
+
elif args.cmd == "info":
|
|
98
|
+
info = {
|
|
99
|
+
"name": f.name, "address": f.device.address,
|
|
100
|
+
"model": f.model.name, "size": f"{f.model.width}x{f.model.height}",
|
|
101
|
+
"firmware": await pj.firmware_version(),
|
|
102
|
+
"properties": {k: (v.hex() if isinstance(v, bytes) else v) for k, v in asdict(pj.properties).items()},
|
|
103
|
+
}
|
|
104
|
+
if args.json:
|
|
105
|
+
print(json.dumps(info, indent=2))
|
|
106
|
+
else:
|
|
107
|
+
for k, v in info.items():
|
|
108
|
+
if k != "properties":
|
|
109
|
+
print(f"{k:<10} {v}")
|
|
110
|
+
print("properties:")
|
|
111
|
+
for k, v in info["properties"].items():
|
|
112
|
+
print(f" {k:<28} {v}")
|
|
113
|
+
elif args.cmd == "power":
|
|
114
|
+
await pj.power(args.state == "on")
|
|
115
|
+
elif args.cmd == "clock":
|
|
116
|
+
await pj.show_clock(args.style - 1, not args.h12, args.date, args.color)
|
|
117
|
+
elif args.cmd == "brightness":
|
|
118
|
+
await pj.brightness(args.level)
|
|
119
|
+
elif args.cmd == "text":
|
|
120
|
+
from .render import render_glyphs
|
|
121
|
+
|
|
122
|
+
limit = TEXT_MAX[bool(pj.properties and pj.properties.support_600_txt)]
|
|
123
|
+
if len(args.text) > limit:
|
|
124
|
+
raise PixelJoyError(f"text is {len(args.text)} chars; this panel takes at most {limit}")
|
|
125
|
+
style = P.TextStyle(color=args.color, rainbow=args.rainbow, speed=args.speed)
|
|
126
|
+
await pj.show_text(render_glyphs(args.text, f.model.height, args.font), style)
|
|
127
|
+
elif args.cmd == "image":
|
|
128
|
+
from .render import image_to_png
|
|
129
|
+
|
|
130
|
+
await pj.show_png(image_to_png(args.path, f.model.width, f.model.height, args.fit))
|
|
131
|
+
elif args.cmd == "gif":
|
|
132
|
+
await pj.show_gif(args.path.read(), args.speed)
|
|
133
|
+
elif args.cmd == "raw":
|
|
134
|
+
await pj._write(P.frame(args.cmd_byte, b"".join(args.payload)))
|
|
135
|
+
for r in await pj.drain(args.wait):
|
|
136
|
+
print(f"{r.head:02X} {r.cmd:02X} {r.payload.hex(' ')}{'' if r.crc_ok else ' (bad crc)'}")
|
|
137
|
+
return
|
|
138
|
+
await asyncio.sleep(0.5) # let the last write-without-response flush before disconnect
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# -- parser -------------------------------------------------------------------
|
|
142
|
+
|
|
143
|
+
def _add_globals(p: argparse.ArgumentParser, suppress: bool) -> None:
|
|
144
|
+
"""Global options. Subparsers get SUPPRESS defaults so they don't clobber values given before the subcommand."""
|
|
145
|
+
d = (lambda v: argparse.SUPPRESS) if suppress else (lambda v: v)
|
|
146
|
+
g = p.add_argument_group("global options")
|
|
147
|
+
g.add_argument("-v", "--verbose", action="store_true", default=d(False), help="log every TX/RX frame; full tracebacks on error")
|
|
148
|
+
g.add_argument("-q", "--quiet", action="store_true", default=d(False), help="only print command output and errors")
|
|
149
|
+
g.add_argument("--address", default=d(None), help="use the panel with this BLE address (macOS: CoreBluetooth UUID)")
|
|
150
|
+
g.add_argument("--name", default=d(None), help="use the first panel whose name contains this (case-insensitive)")
|
|
151
|
+
g.add_argument("--timeout", type=float, default=d(8.0), metavar="SECONDS", help="max scan time (default: 8)")
|
|
152
|
+
g.add_argument("--tz", default=d(None), metavar="ZONE", help="IANA time zone for the panel clock (default: this machine's)")
|
|
153
|
+
g.add_argument("--no-time-sync", action="store_true", default=d(False), help="don't sync the panel clock on connect")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
157
|
+
fmt = argparse.RawDescriptionHelpFormatter
|
|
158
|
+
ap = argparse.ArgumentParser(
|
|
159
|
+
prog="pixeljoy", formatter_class=fmt,
|
|
160
|
+
description="Control PixelJoy BLE LED matrix panels.\n\n"
|
|
161
|
+
"Every command except `scan` connects to the first matching panel, handshakes,\n"
|
|
162
|
+
"syncs the panel clock (unless --no-time-sync), runs, and disconnects.\n"
|
|
163
|
+
"Close the phone app first: the panel accepts one connection at a time.",
|
|
164
|
+
epilog="examples:\n"
|
|
165
|
+
" pixeljoy scan\n"
|
|
166
|
+
" pixeljoy info --json\n"
|
|
167
|
+
" pixeljoy text 'HELLO' --color '#00ff88'\n"
|
|
168
|
+
" pixeljoy -v --name A1B2 image cat.png --fit cover\n\n"
|
|
169
|
+
"exit codes: 0 ok, 1 error, 2 bad arguments, 130 interrupted\n"
|
|
170
|
+
"`pixeljoy COMMAND -h` for command help. Docs: docs/USAGE.md")
|
|
171
|
+
_add_globals(ap, suppress=False)
|
|
172
|
+
sub = ap.add_subparsers(dest="cmd", metavar="COMMAND")
|
|
173
|
+
|
|
174
|
+
def cmd(name: str, help: str, description: str, examples: list[str]) -> argparse.ArgumentParser:
|
|
175
|
+
s = sub.add_parser(name, help=help, description=description, formatter_class=fmt,
|
|
176
|
+
epilog="examples:\n" + "\n".join(f" pixeljoy {e}" for e in examples))
|
|
177
|
+
_add_globals(s, suppress=True)
|
|
178
|
+
return s
|
|
179
|
+
|
|
180
|
+
s = cmd("scan", "list nearby panels", "Scan for --timeout seconds and list PixelJoy panels with their model.",
|
|
181
|
+
["scan", "scan --all --timeout 15"])
|
|
182
|
+
s.add_argument("--all", action="store_true", help="show non-PixelJoy devices too")
|
|
183
|
+
|
|
184
|
+
cmd("gatt", "dump GATT services/characteristics",
|
|
185
|
+
"Connect without handshaking and print every service, characteristic and descriptor.", ["gatt"])
|
|
186
|
+
|
|
187
|
+
s = cmd("info", "show model, firmware and READ_PROPERTY flags",
|
|
188
|
+
"Handshake, read properties and firmware version.", ["info", "info --json | jq .properties"])
|
|
189
|
+
s.add_argument("--json", action="store_true", help="print JSON")
|
|
190
|
+
|
|
191
|
+
cmd("time", "sync the panel clock",
|
|
192
|
+
"Send time zone + DST rules, wall clock and start (this also happens on every connect).",
|
|
193
|
+
["time", "time --tz Europe/London"])
|
|
194
|
+
|
|
195
|
+
s = cmd("power", "turn the display on or off", "Turn the display on or off.", ["power off", "power on"])
|
|
196
|
+
s.add_argument("state", choices=["on", "off"])
|
|
197
|
+
|
|
198
|
+
s = cmd("clock", "show the live clock",
|
|
199
|
+
"Show the panel's built-in clock. The firmware draws the time from its own clock,\n"
|
|
200
|
+
"which is synced on every connect. Styles 1-10 are the app's clock styles, in the app's order.",
|
|
201
|
+
["clock", "clock --style 3 --color ff8800", "clock --12h --date"])
|
|
202
|
+
s.add_argument("--style", type=int_range(1, len(P.CLOCK_STYLES)), default=1, metavar="1-10", help="clock style (default: 1)")
|
|
203
|
+
s.add_argument("--12h", dest="h12", action="store_true", help="12-hour format (default: 24-hour)")
|
|
204
|
+
s.add_argument("--date", action="store_true", help="show the date too")
|
|
205
|
+
s.add_argument("--color", type=hex_color, default=(255, 255, 255), metavar="RRGGBB", help="digit colour (default: ffffff)")
|
|
206
|
+
|
|
207
|
+
s = cmd("brightness", "set brightness (percent, 1-100)",
|
|
208
|
+
"Set brightness as a percentage, 1-100. This is the same scale as the app's\n"
|
|
209
|
+
"brightness slider (0-100). The panel reads 0 back as 1, so 1 is the minimum.",
|
|
210
|
+
["brightness 1 # dimmest", "brightness 50", "brightness 100 # full"])
|
|
211
|
+
s.add_argument("level", type=int_range(1, 100), metavar="PERCENT", help="1-100")
|
|
212
|
+
|
|
213
|
+
s = cmd("text", "scroll text",
|
|
214
|
+
"Render text on this machine (the panel has no fonts), upload it and show it.\n"
|
|
215
|
+
"Max length is 600 chars if the panel reports support600Txt, else 100.",
|
|
216
|
+
["text 'HELLO'", "text 'SALE' --color ff0000 --speed 80", "text 'party' --rainbow 1",
|
|
217
|
+
"text 'Hi' --font /System/Library/Fonts/Supplemental/Arial.ttf"])
|
|
218
|
+
s.add_argument("text")
|
|
219
|
+
c = s.add_mutually_exclusive_group()
|
|
220
|
+
c.add_argument("--color", type=hex_color, default=(255, 255, 255), metavar="RRGGBB", help="text colour (default: ffffff)")
|
|
221
|
+
c.add_argument("--rainbow", type=int_range(0, 255), metavar="N", help="rainbow colour scheme index (scheme range unverified)")
|
|
222
|
+
s.add_argument("--speed", type=int_range(0, 255), default=50, help="scroll speed 0-255 (default: 50)")
|
|
223
|
+
s.add_argument("--font", metavar="TTF", help="path to a .ttf (default: Pillow's built-in font)")
|
|
224
|
+
|
|
225
|
+
s = cmd("image", "show a still image",
|
|
226
|
+
"Resize an image to the panel, upload it as PNG and show it.",
|
|
227
|
+
["image cat.png", "image logo.png --fit contain"])
|
|
228
|
+
s.add_argument("path", type=argparse.FileType("rb"), help="any image Pillow can open")
|
|
229
|
+
s.add_argument("--fit", choices=["stretch", "contain", "cover"], default="stretch",
|
|
230
|
+
help="stretch: ignore aspect; contain: letterbox in black; cover: crop to fill (default: stretch)")
|
|
231
|
+
|
|
232
|
+
s = cmd("gif", "show an animated GIF",
|
|
233
|
+
"Upload a GIF as-is and play it. Size it to the panel first; it is not resized.",
|
|
234
|
+
["gif nyan.gif", "gif nyan.gif --speed 900"])
|
|
235
|
+
s.add_argument("path", type=argparse.FileType("rb"), help="GIF file")
|
|
236
|
+
s.add_argument("--speed", type=int_range(0, 1050), default=600, help="0-1050, higher is faster (default: 600)")
|
|
237
|
+
|
|
238
|
+
s = cmd("raw", "send one raw A0 frame",
|
|
239
|
+
"Frame CMD + PAYLOAD as A0 cmd len payload crc, send it, and print replies for --wait seconds.",
|
|
240
|
+
["raw 2b", "raw 11 01", "raw 13 '0c'", "raw 0f --wait 5"])
|
|
241
|
+
s.add_argument("cmd_byte", type=hex_byte, metavar="CMD", help="command byte, hex 00-FF")
|
|
242
|
+
s.add_argument("payload", type=hex_bytes, nargs="*", help="payload hex; spaces allowed")
|
|
243
|
+
s.add_argument("--wait", type=float, default=2.0, metavar="SECONDS", help="how long to print replies (default: 2)")
|
|
244
|
+
return ap
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def main() -> None:
|
|
248
|
+
ap = build_parser()
|
|
249
|
+
args = ap.parse_args()
|
|
250
|
+
if args.cmd is None:
|
|
251
|
+
ap.print_help(sys.stderr)
|
|
252
|
+
sys.exit(2)
|
|
253
|
+
level = logging.DEBUG if args.verbose else logging.WARNING if args.quiet else logging.INFO
|
|
254
|
+
logging.basicConfig(level=level, format="%(asctime)s %(levelname)s %(message)s")
|
|
255
|
+
if not args.verbose:
|
|
256
|
+
logging.getLogger("bleak").setLevel(logging.WARNING)
|
|
257
|
+
|
|
258
|
+
from bleak.exc import BleakError
|
|
259
|
+
from .client import PixelJoyError
|
|
260
|
+
|
|
261
|
+
try:
|
|
262
|
+
asyncio.run(main_async(args))
|
|
263
|
+
except KeyboardInterrupt:
|
|
264
|
+
print("interrupted", file=sys.stderr)
|
|
265
|
+
sys.exit(EXIT_INTERRUPTED)
|
|
266
|
+
except (PixelJoyError, BleakError, asyncio.TimeoutError, TimeoutError, OSError) as e:
|
|
267
|
+
if args.verbose:
|
|
268
|
+
traceback.print_exc()
|
|
269
|
+
print(f"error: {e or type(e).__name__}", file=sys.stderr)
|
|
270
|
+
sys.exit(EXIT_ERROR)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
if __name__ == "__main__":
|
|
274
|
+
main()
|
pixeljoy/client.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""Async BLE client for PixelJoy panels (bleak).
|
|
2
|
+
|
|
3
|
+
Every TX/RX frame is logged at DEBUG level (``-v`` on the CLI).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import logging
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from bleak import BleakClient, BleakScanner
|
|
13
|
+
from bleak.backends.device import BLEDevice
|
|
14
|
+
|
|
15
|
+
from . import protocol as P
|
|
16
|
+
|
|
17
|
+
log = logging.getLogger("pixeljoy")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PixelJoyError(RuntimeError):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Found:
|
|
26
|
+
device: BLEDevice
|
|
27
|
+
name: str | None
|
|
28
|
+
rssi: int | None
|
|
29
|
+
service_uuids: list[str]
|
|
30
|
+
manufacturer_data: dict[int, bytes]
|
|
31
|
+
model: P.Model | None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def scan(timeout: float = 8.0, show_all: bool = False) -> list[Found]:
|
|
35
|
+
models = P.load_models()
|
|
36
|
+
seen = await BleakScanner.discover(timeout=timeout, return_adv=True)
|
|
37
|
+
out = []
|
|
38
|
+
for dev, adv in seen.values():
|
|
39
|
+
model = P.match_model(adv.local_name or dev.name, adv.service_uuids, models)
|
|
40
|
+
if model or show_all:
|
|
41
|
+
out.append(Found(dev, adv.local_name or dev.name, adv.rssi, list(adv.service_uuids),
|
|
42
|
+
dict(adv.manufacturer_data), model))
|
|
43
|
+
return out
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def find(timeout: float = 8.0, address: str | None = None, name: str | None = None) -> Found:
|
|
47
|
+
"""Return the first matching panel; stops scanning as soon as one is seen."""
|
|
48
|
+
models = P.load_models()
|
|
49
|
+
hit: list[Found] = []
|
|
50
|
+
|
|
51
|
+
def match(dev: BLEDevice, adv) -> bool:
|
|
52
|
+
adv_name = adv.local_name or dev.name
|
|
53
|
+
if address and dev.address.lower() != address.lower():
|
|
54
|
+
return False
|
|
55
|
+
if name and name.lower() not in (adv_name or "").lower():
|
|
56
|
+
return False
|
|
57
|
+
model = P.match_model(adv_name, adv.service_uuids, models)
|
|
58
|
+
if model:
|
|
59
|
+
hit.append(Found(dev, adv_name, adv.rssi, list(adv.service_uuids), dict(adv.manufacturer_data), model))
|
|
60
|
+
return model is not None
|
|
61
|
+
|
|
62
|
+
if await BleakScanner.find_device_by_filter(match, timeout=timeout) is None:
|
|
63
|
+
raise PixelJoyError("no PixelJoy panel found (is the phone app connected? try `scan --all`)")
|
|
64
|
+
return hit[-1]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def dump_gatt(address: str | BLEDevice) -> None:
|
|
69
|
+
"""Print every service/characteristic/descriptor with its properties."""
|
|
70
|
+
async with BleakClient(address) as c:
|
|
71
|
+
print(f"mtu={getattr(c, 'mtu_size', '?')}")
|
|
72
|
+
for s in c.services:
|
|
73
|
+
print(f"service {s.uuid} {s.description}")
|
|
74
|
+
for ch in s.characteristics:
|
|
75
|
+
print(f" char {ch.uuid} props={ch.properties} max_write_wo_resp={getattr(ch, 'max_write_without_response_size', '?')}")
|
|
76
|
+
for d in ch.descriptors:
|
|
77
|
+
print(f" desc {d.uuid} {d.description}")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class PixelJoy:
|
|
81
|
+
def __init__(self, address: str | BLEDevice, model: P.Model, auto_time_sync: bool = True, tz_name: str | None = None):
|
|
82
|
+
self.model = model
|
|
83
|
+
self.auto_time_sync = auto_time_sync
|
|
84
|
+
self.tz_name = tz_name
|
|
85
|
+
self._client = BleakClient(address)
|
|
86
|
+
self._rx: asyncio.Queue[P.Reply] = asyncio.Queue()
|
|
87
|
+
self.properties: P.Properties | None = None
|
|
88
|
+
self.pack_v2_num = 1
|
|
89
|
+
self._write_response = False
|
|
90
|
+
self._max_write: int | None = None
|
|
91
|
+
|
|
92
|
+
# -- plumbing ---------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def mtu(self) -> int:
|
|
96
|
+
return getattr(self._client, "mtu_size", 23) or 23
|
|
97
|
+
|
|
98
|
+
async def __aenter__(self) -> "PixelJoy":
|
|
99
|
+
await self.connect()
|
|
100
|
+
return self
|
|
101
|
+
|
|
102
|
+
async def __aexit__(self, *exc) -> None:
|
|
103
|
+
# Cleanup must not hang or mask the original error (e.g. on Ctrl+C).
|
|
104
|
+
try:
|
|
105
|
+
await asyncio.wait_for(self._client.disconnect(), 5)
|
|
106
|
+
except Exception as e: # noqa: BLE001
|
|
107
|
+
log.debug("disconnect failed: %r", e)
|
|
108
|
+
|
|
109
|
+
def _on_notify(self, _char, data: bytearray) -> None:
|
|
110
|
+
log.debug("RX %s", bytes(data).hex(" "))
|
|
111
|
+
try:
|
|
112
|
+
reply = P.parse_reply(bytes(data))
|
|
113
|
+
except P.FrameError as e:
|
|
114
|
+
log.warning("unparsed notification: %s", e)
|
|
115
|
+
return
|
|
116
|
+
if reply.head == P.HEAD_GET_TIME:
|
|
117
|
+
asyncio.get_running_loop().create_task(self._write(P.time_reply()))
|
|
118
|
+
return
|
|
119
|
+
self._rx.put_nowait(reply)
|
|
120
|
+
|
|
121
|
+
async def _write(self, data: bytes) -> None:
|
|
122
|
+
log.debug("TX %s", data.hex(" "))
|
|
123
|
+
# Chunk at ATT payload size; firmware reassembles A0 frames by length.
|
|
124
|
+
step = max(20, self._max_write or (self.mtu - 3))
|
|
125
|
+
for i in range(0, len(data), step):
|
|
126
|
+
await self._client.write_gatt_char(self.model.write_uuid, data[i : i + step], response=self._write_response)
|
|
127
|
+
|
|
128
|
+
async def _expect(self, *, cmd: int | None = None, heads: tuple[int, ...] = (P.HEAD_DEV,), timeout: float = 5.0) -> P.Reply:
|
|
129
|
+
loop = asyncio.get_running_loop()
|
|
130
|
+
deadline = loop.time() + timeout
|
|
131
|
+
while True:
|
|
132
|
+
remaining = deadline - loop.time()
|
|
133
|
+
if remaining <= 0:
|
|
134
|
+
raise PixelJoyError(f"timeout waiting for cmd={cmd!r} heads={[hex(h) for h in heads]}")
|
|
135
|
+
reply = await asyncio.wait_for(self._rx.get(), remaining)
|
|
136
|
+
if reply.head in heads and (cmd is None or reply.cmd == cmd):
|
|
137
|
+
return reply
|
|
138
|
+
log.debug("ignoring reply head=%02X cmd=%02X", reply.head, reply.cmd)
|
|
139
|
+
|
|
140
|
+
async def drain(self, seconds: float) -> list[P.Reply]:
|
|
141
|
+
"""Collect every reply that arrives within ``seconds``."""
|
|
142
|
+
loop = asyncio.get_running_loop()
|
|
143
|
+
deadline = loop.time() + seconds
|
|
144
|
+
out = []
|
|
145
|
+
while (remaining := deadline - loop.time()) > 0:
|
|
146
|
+
try:
|
|
147
|
+
out.append(await asyncio.wait_for(self._rx.get(), remaining))
|
|
148
|
+
except asyncio.TimeoutError:
|
|
149
|
+
break
|
|
150
|
+
return out
|
|
151
|
+
|
|
152
|
+
async def request(self, data: bytes, cmd: int, timeout: float = 5.0) -> P.Reply:
|
|
153
|
+
await self._write(data)
|
|
154
|
+
return await self._expect(cmd=cmd, timeout=timeout)
|
|
155
|
+
|
|
156
|
+
# -- session ----------------------------------------------------------
|
|
157
|
+
|
|
158
|
+
async def _open(self) -> None:
|
|
159
|
+
"""Connect the BLE link. Hosts with their own connection logic (Home Assistant) override this."""
|
|
160
|
+
await self._client.connect()
|
|
161
|
+
|
|
162
|
+
async def connect(self) -> None:
|
|
163
|
+
await self._open()
|
|
164
|
+
log.info("connected, mtu=%s", self.mtu)
|
|
165
|
+
char = self._client.services.get_characteristic(self.model.write_uuid)
|
|
166
|
+
if char is None:
|
|
167
|
+
raise PixelJoyError(f"write characteristic {self.model.write_uuid} not found; run `python -m pixeljoy gatt`")
|
|
168
|
+
# Match Android's default (the vendor app never sets a write type): if the
|
|
169
|
+
# characteristic supports write-without-response, that is what gets used.
|
|
170
|
+
self._write_response = "write-without-response" not in char.properties
|
|
171
|
+
self._max_write = getattr(char, "max_write_without_response_size", None) if not self._write_response else None
|
|
172
|
+
log.info("write char %s properties=%s -> response=%s max_write=%s",
|
|
173
|
+
char.uuid, char.properties, self._write_response, self._max_write)
|
|
174
|
+
await self._client.start_notify(self.model.notify_uuid, self._on_notify)
|
|
175
|
+
await self.handshake()
|
|
176
|
+
self.properties = await self.read_properties()
|
|
177
|
+
self.pack_v2_num = self.properties.preferred_pack_v2_num
|
|
178
|
+
if self.properties.support_pack_v2 and self.properties.pack_v2_num != self.pack_v2_num:
|
|
179
|
+
await self._write(P.set_multi_pack_v2(True, self.pack_v2_num))
|
|
180
|
+
if self.auto_time_sync:
|
|
181
|
+
await self.sync_time(self.tz_name)
|
|
182
|
+
|
|
183
|
+
async def handshake(self, attempts: int = 3) -> None:
|
|
184
|
+
for _ in range(attempts):
|
|
185
|
+
await self._write(P.handshake_first())
|
|
186
|
+
try:
|
|
187
|
+
r1 = await self._expect(cmd=P.Cmd.SHAKE_HAND_FIRST, timeout=1.0)
|
|
188
|
+
break
|
|
189
|
+
except PixelJoyError:
|
|
190
|
+
continue
|
|
191
|
+
else:
|
|
192
|
+
raise PixelJoyError("no reply to handshake 1")
|
|
193
|
+
log.info("handshake 1 reply payload: %s", r1.payload.hex(" "))
|
|
194
|
+
r2 = await self.request(P.handshake_second(r1.payload), P.Cmd.SHAKE_HAND_SECOND, timeout=3.0)
|
|
195
|
+
log.info("handshake 2 reply payload: %s", r2.payload.hex(" "))
|
|
196
|
+
if not P.handshake_second_ok(r2.payload):
|
|
197
|
+
raise PixelJoyError(f"handshake rejected: {r2.payload.hex(' ')}")
|
|
198
|
+
|
|
199
|
+
async def read_properties(self) -> P.Properties:
|
|
200
|
+
r = await self.request(P.read_property(), P.Cmd.READ_PROPERTY)
|
|
201
|
+
return P.parse_properties(r.payload)
|
|
202
|
+
|
|
203
|
+
# -- commands ---------------------------------------------------------
|
|
204
|
+
|
|
205
|
+
async def power(self, on: bool) -> None:
|
|
206
|
+
await self._write(P.switch_light(on))
|
|
207
|
+
|
|
208
|
+
async def show_clock(self, style: int = 0, h24: bool = True, date: bool = False,
|
|
209
|
+
color: tuple[int, int, int] = (255, 255, 255)) -> None:
|
|
210
|
+
await self._write(P.show_clock(style, h24, date, color))
|
|
211
|
+
|
|
212
|
+
async def brightness(self, level: int) -> None:
|
|
213
|
+
await self._write(P.set_brightness(level))
|
|
214
|
+
|
|
215
|
+
async def sync_time(self, tz_name: str | None = None) -> None:
|
|
216
|
+
"""Same sequence the app sends after connecting: time zone/DST, wall clock, start."""
|
|
217
|
+
tz_payload = P.time_zone_payload(tz_name)
|
|
218
|
+
log.info("time sync: tz=%s payload=%s", tz_name or P._local_tz_name(), tz_payload.hex(" "))
|
|
219
|
+
await self._write(P.frame(P.Cmd.SET_TIME_ZONE, tz_payload))
|
|
220
|
+
await self._write(P.sync_time())
|
|
221
|
+
await self._write(P.start_sync_time())
|
|
222
|
+
|
|
223
|
+
async def firmware_version(self) -> str:
|
|
224
|
+
return P.parse_version((await self.request(P.get_firmware_version(), P.Cmd.GET_FIRMWARE_VERSION)).payload)
|
|
225
|
+
|
|
226
|
+
async def send_multi(self, packets: list[bytes], expect_file_reply: bool) -> None:
|
|
227
|
+
"""Run the A2 flow-control loop (MultiPackUtilV2)."""
|
|
228
|
+
n = max(1, self.pack_v2_num)
|
|
229
|
+
no_wait = bool(self.properties and self.properties.support_no_response_a4 and expect_file_reply)
|
|
230
|
+
i = 0
|
|
231
|
+
while i < len(packets):
|
|
232
|
+
group_end = min(i + n, len(packets))
|
|
233
|
+
for j in range(i, group_end):
|
|
234
|
+
await self._write(packets[j])
|
|
235
|
+
i = group_end
|
|
236
|
+
if no_wait:
|
|
237
|
+
await asyncio.sleep(0.02)
|
|
238
|
+
# Still honour a lost-packet request if one is queued.
|
|
239
|
+
while not self._rx.empty():
|
|
240
|
+
r = self._rx.get_nowait()
|
|
241
|
+
if r.head == P.HEAD_MULTI_ACK_V2:
|
|
242
|
+
ack = P.parse_multi_ack(r)
|
|
243
|
+
if ack.resend_from:
|
|
244
|
+
i = ack.resend_from - 1
|
|
245
|
+
else:
|
|
246
|
+
self._rx.put_nowait(r)
|
|
247
|
+
break
|
|
248
|
+
continue
|
|
249
|
+
if i >= len(packets) and expect_file_reply:
|
|
250
|
+
break # final reply is A1 07
|
|
251
|
+
r = await self._expect(heads=(P.HEAD_MULTI_ACK, P.HEAD_MULTI_ACK_V2), timeout=10.0)
|
|
252
|
+
ack = P.parse_multi_ack(r)
|
|
253
|
+
if ack.resend_from:
|
|
254
|
+
log.warning("device requested resend from packet %d", ack.resend_from)
|
|
255
|
+
i = ack.resend_from - 1
|
|
256
|
+
|
|
257
|
+
async def upload(self, name: str, data: bytes) -> None:
|
|
258
|
+
multi, frames = P.send_file_frames(name, data, self.mtu)
|
|
259
|
+
log.info("upload %s: %d bytes in %d frame(s)", name, len(data), len(frames))
|
|
260
|
+
if multi:
|
|
261
|
+
await self.send_multi(frames, expect_file_reply=True)
|
|
262
|
+
else:
|
|
263
|
+
await self._write(frames[0])
|
|
264
|
+
r = await self._expect(cmd=P.Cmd.SEND_FILE, timeout=15.0)
|
|
265
|
+
if not r.payload or r.payload[0] != 1:
|
|
266
|
+
await self._write(P.delete_file(name))
|
|
267
|
+
raise PixelJoyError(f"upload failed: {r.payload.hex(' ')}")
|
|
268
|
+
|
|
269
|
+
async def _send_cmd(self, cmd: int, payload: bytes) -> None:
|
|
270
|
+
multi, frames = P.cmd_frames(cmd, payload, self.mtu)
|
|
271
|
+
if multi:
|
|
272
|
+
await self.send_multi(frames, expect_file_reply=False)
|
|
273
|
+
else:
|
|
274
|
+
await self._write(frames[0])
|
|
275
|
+
|
|
276
|
+
async def read_carousel(self) -> list[P.CarouselItem]:
|
|
277
|
+
"""The panel's carousel list (replies: "start", item frames, "end")."""
|
|
278
|
+
await self._write(P.frame(P.Cmd.READ_CAROUSEL_LIST, b"\x01"))
|
|
279
|
+
items: list[P.CarouselItem] = []
|
|
280
|
+
while True:
|
|
281
|
+
got = P.parse_carousel_list((await self._expect(cmd=P.Cmd.READ_CAROUSEL_LIST)).payload)
|
|
282
|
+
if got == "end":
|
|
283
|
+
return items
|
|
284
|
+
if isinstance(got, list):
|
|
285
|
+
items += got
|
|
286
|
+
|
|
287
|
+
async def resume_carousel(self) -> list[P.CarouselItem]:
|
|
288
|
+
"""Play the stored carousel. PLAY_CAROUSEL replaces the list, so read it and send it back."""
|
|
289
|
+
items = await self.read_carousel()
|
|
290
|
+
if not items:
|
|
291
|
+
raise PixelJoyError("the panel's carousel is empty; add items in the app first")
|
|
292
|
+
await self._send_cmd(P.Cmd.PLAY_CAROUSEL, P.play_carousel_payload(items))
|
|
293
|
+
return items
|
|
294
|
+
|
|
295
|
+
async def show_png(self, png: bytes, name: str | None = None) -> None:
|
|
296
|
+
name = name or P.file_name("img")
|
|
297
|
+
await self.upload(name, png)
|
|
298
|
+
await self._send_cmd(P.Cmd.SHOW_IMG, P.show_img_payload(name))
|
|
299
|
+
|
|
300
|
+
async def show_gif(self, gif: bytes, speed: int = 600, name: str | None = None) -> None:
|
|
301
|
+
name = name or P.file_name("gif")
|
|
302
|
+
await self.upload(name, gif)
|
|
303
|
+
await self._send_cmd(P.Cmd.SHOW_GIF, P.show_gif_payload(name, speed))
|
|
304
|
+
|
|
305
|
+
async def show_text(self, glyphs: list[P.Glyph], style: P.TextStyle = P.TextStyle(), name: str | None = None) -> None:
|
|
306
|
+
props = self.properties
|
|
307
|
+
s600 = bool(props and props.support_600_txt)
|
|
308
|
+
name = name or P.file_name("text")
|
|
309
|
+
await self.upload(name, P.text_file(glyphs, s600))
|
|
310
|
+
if props and not props.support_text_bg_color:
|
|
311
|
+
style.bg_color = None
|
|
312
|
+
if props and not props.support_text_align:
|
|
313
|
+
style.align = None
|
|
314
|
+
await self._send_cmd(P.Cmd.SHOW_TEXT, P.show_text_payload(name, len(glyphs), style, s600))
|