pixeljoy-ble 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rob Gray
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: pixeljoy-ble
3
+ Version: 0.1.0
4
+ Summary: Reverse-engineered BLE protocol + client for PixelJoy LED matrix panels
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/rgr4y/pixeljoy-ble
7
+ Project-URL: Issues, https://github.com/rgr4y/pixeljoy-ble/issues
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: bleak>=0.22
12
+ Requires-Dist: Pillow>=10
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest; extra == "test"
15
+ Dynamic: license-file
16
+
17
+ # pixeljoy-ble
18
+
19
+ <img src="docs/img/panel.png" alt="PixelJoy flexible LED panel with the PixelJoy app and remote" width="420">
20
+
21
+ *The kind of panel this targets ([example listing](https://www.aliexpress.us/item/3256812441943754.html); vendor product photo).*
22
+
23
+ Open protocol notes and a Python client for the **PixelJoy** flexible
24
+ Bluetooth LED matrix panels. These are the cheap "LED MATRIX PANEL" units
25
+ sold for car windows and shop signs, controlled by the *PixelJoy* app
26
+ (Shenzhen Wanshun Zhilian Technology) and a small 2.4 GHz remote (BLE adverts, not IR). They are built
27
+ on a JieLi AC695x/AC6951C BLE SoC.
28
+
29
+ **Status: protocol extracted from the Android app by static analysis and
30
+ confirmed on a P0AF (32×16, firmware 1.8.5) panel: handshake, properties,
31
+ clock sync, text, image.** See [`docs/PROTOCOL.md`](docs/PROTOCOL.md).
32
+ CLI reference: [`docs/USAGE.md`](docs/USAGE.md).
33
+
34
+ ## Prior art
35
+
36
+ As of Nov 2026 nothing public decodes PixelJoy specifically. Its protocol is
37
+ **not** iPixel Color, iDotMatrix, CoolLED, BK-Light or Badge Magic. It is
38
+ its own scheme:
39
+
40
+ * per-model GATT UUIDs `Exxx`/`Axxx`/`Fxxx`, where `xxx` is the model PID
41
+ * `A0 cmd len payload crc16-modbus` frames
42
+ * a `"CCHIP"` XOR challenge handshake
43
+ * an `A2` chunked transfer for files
44
+
45
+ The phone renders text into 1-bpp glyphs. Images go up as ordinary PNG
46
+ files and animations as GIFs.
47
+
48
+ ## Install
49
+
50
+ Not on PyPI. Install from GitHub or a clone. Python 3.10+.
51
+
52
+ **CLI, isolated (pipx):**
53
+
54
+ ```bash
55
+ pipx install git+https://github.com/rgr4y/pixeljoy-ble.git
56
+ pixeljoy --help
57
+ ```
58
+
59
+ From a clone: `pipx install .` (add `--force` to upgrade in place).
60
+
61
+ **Library, into your own project or venv:**
62
+
63
+ ```bash
64
+ pip install git+https://github.com/rgr4y/pixeljoy-ble.git
65
+ ```
66
+
67
+ Or pin it in your `requirements.txt` as
68
+ `pixeljoy-ble @ git+https://github.com/rgr4y/pixeljoy-ble.git@<tag-or-sha>`.
69
+ The import name is `pixeljoy`. See the Python API in [`docs/USAGE.md`](docs/USAGE.md#python-api).
70
+
71
+ **Development:**
72
+
73
+ ```bash
74
+ python -m venv .venv && . .venv/bin/activate
75
+ pip install -r requirements.txt # runtime deps only: bleak, Pillow
76
+ pip install -e '.[test]' # editable install + pytest
77
+ pytest tests
78
+ ```
79
+
80
+ `requirements.txt` is the single source of runtime dependencies; `pyproject.toml` reads it.
81
+
82
+ ## Quick start
83
+
84
+ ```bash
85
+ pixeljoy scan # find the panel, prints name/UUIDs/model
86
+ pixeljoy -v info # handshake + READ_PROPERTY, logs every frame
87
+ pixeljoy power off
88
+ pixeljoy brightness 50
89
+ pixeljoy -v text "HELLO" --color 00ff88
90
+ pixeljoy -v image cat.png # resized to the panel, uploaded as PNG
91
+ pixeljoy raw 41 01 # send one raw A0 frame, print replies
92
+ ```
93
+
94
+ Full CLI reference, exit codes and troubleshooting: [`docs/USAGE.md`](docs/USAGE.md).
95
+
96
+ `-v` logs every TX/RX frame in hex. Please capture that output on first
97
+ contact with a panel.
98
+
99
+ ## Home Assistant
100
+
101
+ `custom_components/pixeljoy` is a Home Assistant integration built on the same library. Its structure is
102
+ adapted from [XTimt/LEDDMX](https://github.com/XTimt/LEDDMX) (MIT). It uses HA's own Bluetooth stack:
103
+ local adapters and ESPHome proxies both work.
104
+
105
+ - **Discovery:** panels are found by their scan UUID and model name (all 40 models). They can also be
106
+ picked from the list of panels in range.
107
+ - **Light:** on/off and brightness. The panel's 1–100 % maps onto HA's 0–255. State is read from the
108
+ panel when HA connects; until then it is shown as assumed.
109
+ - **Services:** `pixeljoy.show_text`, `show_clock` (style 1–10; higher styles are rejected because they
110
+ corrupt the panel's RAM), `show_image` and `show_gif` (files must be under `allowlist_external_dirs`),
111
+ and `sync_time` (uses HA's time zone).
112
+ - **Remote:** `event.<panel>_remote` fires for each key press on the 2.4 GHz `LZ` remote. These are
113
+ passive BLE adverts with no connection, so presses arrive even when the panel is off. Repeated
114
+ transmissions of the same press are dropped. Event types come from the firmware's key table:
115
+ `power`, `off`, `left`, `right`, `brightness_up`/`brightness_down`, `flip`, `clock`, `carousel`, `timer_12h`, `button_1`..`button_3` and the six car signs (`sign_left`, `sign_right`, `sign_warning`, ...).
116
+ - **Connection:** the BLE link opens on demand and drops after 60 s idle, so the phone app can still connect.
117
+
118
+ **Install (Home Assistant 2026.11+ Marketplace):**
119
+
120
+ 1. Settings → Marketplace → ⋮ → Custom repositories.
121
+ 2. Add `https://github.com/rgr4y/pixeljoy-ble`, type **Integration**.
122
+ 3. Install **PixelJoy LED Panel**, restart Home Assistant. Panels in range are offered for setup automatically.
123
+
124
+ The component imports the library from PyPI (`pixeljoy-ble`, pinned in `manifest.json`). HA installs it on first load.
125
+
126
+ Tests run against a real HA core with BLE mocked:
127
+ `pip install -e . pytest-homeassistant-custom-component` then `pytest tests_ha -o asyncio_mode=auto`.
128
+
129
+ ## Layout
130
+
131
+ | Path | What |
132
+ |---|---|
133
+ | `docs/USAGE.md` | CLI reference, troubleshooting, Python API example |
134
+ | `docs/PROTOCOL.md` | the spec, with references to the vendor classes it came from |
135
+ | `pixeljoy/protocol.py` | pure encoders/decoders (framing, CRC, handshake, multi-pack, text/PNG, replies) |
136
+ | `pixeljoy/client.py` | async `bleak` client: handshake, flow control, upload/show |
137
+ | `pixeljoy/render.py` | Pillow text → glyphs, image → panel-sized PNG |
138
+ | `pixeljoy/devices.json` | 40 known models (size, chip, UUIDs) from the app's `th_dev_cfg.json` |
139
+ | `tools/fetch_apk.sh` | re-download the vendor APK and decompile it with jadx (output is git-ignored) |
140
+ | `tools/patch_apk.py` | rebuild the vendor app without telemetry for personal use (`--offline` also drops INTERNET); see `docs/APP_PRIVACY.md` |
141
+ | `docs/APP_PRIVACY.md` | what the app sends home (hardware device ID on every request, IP geolocation, Tencent cloud speech) and what the patch removes |
142
+ | `tests/` | unit tests for the encoders (`pytest`) |
143
+ | `custom_components/pixeljoy/` | Home Assistant integration (imports the `pixeljoy-ble` library from PyPI) |
144
+ | `hacs.json` | Marketplace (HACS) metadata |
145
+ | `tests_ha/` | HA integration tests (`pytest-homeassistant-custom-component`) |
146
+
147
+ ## License
148
+
149
+ MIT. See [`LICENSE`](LICENSE).
@@ -0,0 +1,133 @@
1
+ # pixeljoy-ble
2
+
3
+ <img src="docs/img/panel.png" alt="PixelJoy flexible LED panel with the PixelJoy app and remote" width="420">
4
+
5
+ *The kind of panel this targets ([example listing](https://www.aliexpress.us/item/3256812441943754.html); vendor product photo).*
6
+
7
+ Open protocol notes and a Python client for the **PixelJoy** flexible
8
+ Bluetooth LED matrix panels. These are the cheap "LED MATRIX PANEL" units
9
+ sold for car windows and shop signs, controlled by the *PixelJoy* app
10
+ (Shenzhen Wanshun Zhilian Technology) and a small 2.4 GHz remote (BLE adverts, not IR). They are built
11
+ on a JieLi AC695x/AC6951C BLE SoC.
12
+
13
+ **Status: protocol extracted from the Android app by static analysis and
14
+ confirmed on a P0AF (32×16, firmware 1.8.5) panel: handshake, properties,
15
+ clock sync, text, image.** See [`docs/PROTOCOL.md`](docs/PROTOCOL.md).
16
+ CLI reference: [`docs/USAGE.md`](docs/USAGE.md).
17
+
18
+ ## Prior art
19
+
20
+ As of Nov 2026 nothing public decodes PixelJoy specifically. Its protocol is
21
+ **not** iPixel Color, iDotMatrix, CoolLED, BK-Light or Badge Magic. It is
22
+ its own scheme:
23
+
24
+ * per-model GATT UUIDs `Exxx`/`Axxx`/`Fxxx`, where `xxx` is the model PID
25
+ * `A0 cmd len payload crc16-modbus` frames
26
+ * a `"CCHIP"` XOR challenge handshake
27
+ * an `A2` chunked transfer for files
28
+
29
+ The phone renders text into 1-bpp glyphs. Images go up as ordinary PNG
30
+ files and animations as GIFs.
31
+
32
+ ## Install
33
+
34
+ Not on PyPI. Install from GitHub or a clone. Python 3.10+.
35
+
36
+ **CLI, isolated (pipx):**
37
+
38
+ ```bash
39
+ pipx install git+https://github.com/rgr4y/pixeljoy-ble.git
40
+ pixeljoy --help
41
+ ```
42
+
43
+ From a clone: `pipx install .` (add `--force` to upgrade in place).
44
+
45
+ **Library, into your own project or venv:**
46
+
47
+ ```bash
48
+ pip install git+https://github.com/rgr4y/pixeljoy-ble.git
49
+ ```
50
+
51
+ Or pin it in your `requirements.txt` as
52
+ `pixeljoy-ble @ git+https://github.com/rgr4y/pixeljoy-ble.git@<tag-or-sha>`.
53
+ The import name is `pixeljoy`. See the Python API in [`docs/USAGE.md`](docs/USAGE.md#python-api).
54
+
55
+ **Development:**
56
+
57
+ ```bash
58
+ python -m venv .venv && . .venv/bin/activate
59
+ pip install -r requirements.txt # runtime deps only: bleak, Pillow
60
+ pip install -e '.[test]' # editable install + pytest
61
+ pytest tests
62
+ ```
63
+
64
+ `requirements.txt` is the single source of runtime dependencies; `pyproject.toml` reads it.
65
+
66
+ ## Quick start
67
+
68
+ ```bash
69
+ pixeljoy scan # find the panel, prints name/UUIDs/model
70
+ pixeljoy -v info # handshake + READ_PROPERTY, logs every frame
71
+ pixeljoy power off
72
+ pixeljoy brightness 50
73
+ pixeljoy -v text "HELLO" --color 00ff88
74
+ pixeljoy -v image cat.png # resized to the panel, uploaded as PNG
75
+ pixeljoy raw 41 01 # send one raw A0 frame, print replies
76
+ ```
77
+
78
+ Full CLI reference, exit codes and troubleshooting: [`docs/USAGE.md`](docs/USAGE.md).
79
+
80
+ `-v` logs every TX/RX frame in hex. Please capture that output on first
81
+ contact with a panel.
82
+
83
+ ## Home Assistant
84
+
85
+ `custom_components/pixeljoy` is a Home Assistant integration built on the same library. Its structure is
86
+ adapted from [XTimt/LEDDMX](https://github.com/XTimt/LEDDMX) (MIT). It uses HA's own Bluetooth stack:
87
+ local adapters and ESPHome proxies both work.
88
+
89
+ - **Discovery:** panels are found by their scan UUID and model name (all 40 models). They can also be
90
+ picked from the list of panels in range.
91
+ - **Light:** on/off and brightness. The panel's 1–100 % maps onto HA's 0–255. State is read from the
92
+ panel when HA connects; until then it is shown as assumed.
93
+ - **Services:** `pixeljoy.show_text`, `show_clock` (style 1–10; higher styles are rejected because they
94
+ corrupt the panel's RAM), `show_image` and `show_gif` (files must be under `allowlist_external_dirs`),
95
+ and `sync_time` (uses HA's time zone).
96
+ - **Remote:** `event.<panel>_remote` fires for each key press on the 2.4 GHz `LZ` remote. These are
97
+ passive BLE adverts with no connection, so presses arrive even when the panel is off. Repeated
98
+ transmissions of the same press are dropped. Event types come from the firmware's key table:
99
+ `power`, `off`, `left`, `right`, `brightness_up`/`brightness_down`, `flip`, `clock`, `carousel`, `timer_12h`, `button_1`..`button_3` and the six car signs (`sign_left`, `sign_right`, `sign_warning`, ...).
100
+ - **Connection:** the BLE link opens on demand and drops after 60 s idle, so the phone app can still connect.
101
+
102
+ **Install (Home Assistant 2026.11+ Marketplace):**
103
+
104
+ 1. Settings → Marketplace → ⋮ → Custom repositories.
105
+ 2. Add `https://github.com/rgr4y/pixeljoy-ble`, type **Integration**.
106
+ 3. Install **PixelJoy LED Panel**, restart Home Assistant. Panels in range are offered for setup automatically.
107
+
108
+ The component imports the library from PyPI (`pixeljoy-ble`, pinned in `manifest.json`). HA installs it on first load.
109
+
110
+ Tests run against a real HA core with BLE mocked:
111
+ `pip install -e . pytest-homeassistant-custom-component` then `pytest tests_ha -o asyncio_mode=auto`.
112
+
113
+ ## Layout
114
+
115
+ | Path | What |
116
+ |---|---|
117
+ | `docs/USAGE.md` | CLI reference, troubleshooting, Python API example |
118
+ | `docs/PROTOCOL.md` | the spec, with references to the vendor classes it came from |
119
+ | `pixeljoy/protocol.py` | pure encoders/decoders (framing, CRC, handshake, multi-pack, text/PNG, replies) |
120
+ | `pixeljoy/client.py` | async `bleak` client: handshake, flow control, upload/show |
121
+ | `pixeljoy/render.py` | Pillow text → glyphs, image → panel-sized PNG |
122
+ | `pixeljoy/devices.json` | 40 known models (size, chip, UUIDs) from the app's `th_dev_cfg.json` |
123
+ | `tools/fetch_apk.sh` | re-download the vendor APK and decompile it with jadx (output is git-ignored) |
124
+ | `tools/patch_apk.py` | rebuild the vendor app without telemetry for personal use (`--offline` also drops INTERNET); see `docs/APP_PRIVACY.md` |
125
+ | `docs/APP_PRIVACY.md` | what the app sends home (hardware device ID on every request, IP geolocation, Tencent cloud speech) and what the patch removes |
126
+ | `tests/` | unit tests for the encoders (`pytest`) |
127
+ | `custom_components/pixeljoy/` | Home Assistant integration (imports the `pixeljoy-ble` library from PyPI) |
128
+ | `hacs.json` | Marketplace (HACS) metadata |
129
+ | `tests_ha/` | HA integration tests (`pytest-homeassistant-custom-component`) |
130
+
131
+ ## License
132
+
133
+ MIT. See [`LICENSE`](LICENSE).
@@ -0,0 +1,5 @@
1
+ """PixelJoy BLE LED panel protocol (reverse-engineered)."""
2
+
3
+ from . import protocol # noqa: F401
4
+
5
+ __all__ = ["protocol"]
@@ -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()