lightball-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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: lightball-ble
3
+ Version: 0.1.0
4
+ Summary: CSRmesh BLE protocol and async client for Holiday Show Home LED Balls
5
+ Author: dallanwagz
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/dallanwagz/lightball-ble
8
+ Project-URL: Repository, https://github.com/dallanwagz/lightball-ble
9
+ Project-URL: Issues, https://github.com/dallanwagz/lightball-ble/issues
10
+ Keywords: bluetooth,ble,csrmesh,home-assistant,led,light
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Home Automation
16
+ Requires-Python: >=3.12
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: bleak>=0.22.0
20
+ Requires-Dist: bleak-retry-connector>=3.5.0
21
+ Requires-Dist: cryptography>=42.0.0
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest>=8; extra == "test"
24
+ Requires-Dist: pytest-asyncio>=0.23; extra == "test"
25
+ Requires-Dist: pytest-cov; extra == "test"
26
+ Requires-Dist: ruff; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # lightball-ble
30
+
31
+ Async BLE protocol and client for **Holiday Show Home "Show Home" LED Balls** — the
32
+ battery-powered RGB orbs sold under the Holiday Showtime / Show Home brands. They
33
+ speak Qualcomm/CSR's **CSRmesh** over a GATT bridge; this library reimplements that
34
+ framing so you can control a ball from Python (and powers the Home Assistant
35
+ [`lightball`](https://github.com/dallanwagz/lightball) integration).
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install lightball-ble
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ You provide a `bleak` `BLEDevice` (the ball rotates its BLE address, so re-resolve
46
+ it by the stable local name — e.g. `LAB00001CEB11` — before each use):
47
+
48
+ ```python
49
+ from bleak import BleakScanner
50
+ from lightball_ble import LightBall
51
+
52
+ device = await BleakScanner.find_device_by_name("LAB00001CEB11")
53
+ ball = LightBall(device, "LAB00001CEB11")
54
+
55
+ await ball.set_state(mode=1, color=0, level=2) # steady, red, mid brightness
56
+ await ball.set_show(6) # MultiColor animated show
57
+ await ball.turn_off()
58
+
59
+ # Re-resolve the address later, then reuse the client:
60
+ ball.set_ble_device(await BleakScanner.find_device_by_name("LAB00001CEB11"))
61
+ ```
62
+
63
+ ### Command reference
64
+
65
+ - `set_state(mode, color, level, *, turn_on=True)` — `commonMode`: animation `mode`
66
+ (0=off, 1=steady, 2=blink, 5=fade, 7=waves …), palette `color` index (0=red …
67
+ 28=MultiColor), brightness `level` 0–4.
68
+ - `set_show(show_sel, *, turn_on=True)` — `showView` animated preset
69
+ (0=Christmas … 6=MultiColor).
70
+ - `turn_off()`.
71
+
72
+ ## Protocol
73
+
74
+ `lightball_ble.protocol` exposes the low-level framing if you need it:
75
+
76
+ - **Network key**: `reverse(SHA-256(b"686868\x00MCP"))[:16]` (a fixed, product-line
77
+ shared key — `derive_key()`).
78
+ - **Packet**: AES-128 counter-mode payload + an 8-byte byte-reversed HMAC-SHA256 MIC
79
+ + a trailing `0xFF` (`make_packet`).
80
+ - **Transport**: packets > 20 bytes split across two GATT control points
81
+ (`split_writes`).
82
+
83
+ This was reverse-engineered from the official "Show Home" Android app; see the
84
+ [lightball](https://github.com/dallanwagz/lightball) project for the full writeup.
85
+
86
+ ## Develop
87
+
88
+ ```bash
89
+ pip install -e ".[test]"
90
+ pytest --cov=lightball_ble --cov-report=term-missing
91
+ ruff check . && ruff format --check .
92
+ ```
93
+
94
+ ## License
95
+
96
+ Apache-2.0.
@@ -0,0 +1,68 @@
1
+ # lightball-ble
2
+
3
+ Async BLE protocol and client for **Holiday Show Home "Show Home" LED Balls** — the
4
+ battery-powered RGB orbs sold under the Holiday Showtime / Show Home brands. They
5
+ speak Qualcomm/CSR's **CSRmesh** over a GATT bridge; this library reimplements that
6
+ framing so you can control a ball from Python (and powers the Home Assistant
7
+ [`lightball`](https://github.com/dallanwagz/lightball) integration).
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install lightball-ble
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ You provide a `bleak` `BLEDevice` (the ball rotates its BLE address, so re-resolve
18
+ it by the stable local name — e.g. `LAB00001CEB11` — before each use):
19
+
20
+ ```python
21
+ from bleak import BleakScanner
22
+ from lightball_ble import LightBall
23
+
24
+ device = await BleakScanner.find_device_by_name("LAB00001CEB11")
25
+ ball = LightBall(device, "LAB00001CEB11")
26
+
27
+ await ball.set_state(mode=1, color=0, level=2) # steady, red, mid brightness
28
+ await ball.set_show(6) # MultiColor animated show
29
+ await ball.turn_off()
30
+
31
+ # Re-resolve the address later, then reuse the client:
32
+ ball.set_ble_device(await BleakScanner.find_device_by_name("LAB00001CEB11"))
33
+ ```
34
+
35
+ ### Command reference
36
+
37
+ - `set_state(mode, color, level, *, turn_on=True)` — `commonMode`: animation `mode`
38
+ (0=off, 1=steady, 2=blink, 5=fade, 7=waves …), palette `color` index (0=red …
39
+ 28=MultiColor), brightness `level` 0–4.
40
+ - `set_show(show_sel, *, turn_on=True)` — `showView` animated preset
41
+ (0=Christmas … 6=MultiColor).
42
+ - `turn_off()`.
43
+
44
+ ## Protocol
45
+
46
+ `lightball_ble.protocol` exposes the low-level framing if you need it:
47
+
48
+ - **Network key**: `reverse(SHA-256(b"686868\x00MCP"))[:16]` (a fixed, product-line
49
+ shared key — `derive_key()`).
50
+ - **Packet**: AES-128 counter-mode payload + an 8-byte byte-reversed HMAC-SHA256 MIC
51
+ + a trailing `0xFF` (`make_packet`).
52
+ - **Transport**: packets > 20 bytes split across two GATT control points
53
+ (`split_writes`).
54
+
55
+ This was reverse-engineered from the official "Show Home" Android app; see the
56
+ [lightball](https://github.com/dallanwagz/lightball) project for the full writeup.
57
+
58
+ ## Develop
59
+
60
+ ```bash
61
+ pip install -e ".[test]"
62
+ pytest --cov=lightball_ble --cov-report=term-missing
63
+ ruff check . && ruff format --check .
64
+ ```
65
+
66
+ ## License
67
+
68
+ Apache-2.0.
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lightball-ble"
7
+ version = "0.1.0"
8
+ description = "CSRmesh BLE protocol and async client for Holiday Show Home LED Balls"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "Apache-2.0"
12
+ authors = [{ name = "dallanwagz" }]
13
+ keywords = ["bluetooth", "ble", "csrmesh", "home-assistant", "led", "light"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Topic :: Home Automation",
20
+ ]
21
+ dependencies = [
22
+ "bleak>=0.22.0",
23
+ "bleak-retry-connector>=3.5.0",
24
+ "cryptography>=42.0.0",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ test = ["pytest>=8", "pytest-asyncio>=0.23", "pytest-cov", "ruff"]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/dallanwagz/lightball-ble"
32
+ Repository = "https://github.com/dallanwagz/lightball-ble"
33
+ Issues = "https://github.com/dallanwagz/lightball-ble/issues"
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+
38
+ [tool.pytest.ini_options]
39
+ asyncio_mode = "auto"
40
+ testpaths = ["tests"]
41
+
42
+ [tool.ruff]
43
+ line-length = 88
44
+ target-version = "py312"
45
+
46
+ [tool.ruff.lint]
47
+ select = ["E", "F", "W", "I", "UP", "B", "SIM", "RET", "PTH", "ASYNC", "C4", "PIE"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,27 @@
1
+ """CSRmesh BLE protocol and client for Holiday Show Home LED Balls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .client import LightBall
6
+ from .protocol import (
7
+ CP1_UUID,
8
+ CP2_UUID,
9
+ MODE_CLOSE,
10
+ MODE_ON,
11
+ MODE_STEADY,
12
+ SERVICE_UUID,
13
+ derive_key,
14
+ make_packet,
15
+ )
16
+
17
+ __all__ = [
18
+ "LightBall",
19
+ "SERVICE_UUID",
20
+ "CP1_UUID",
21
+ "CP2_UUID",
22
+ "MODE_CLOSE",
23
+ "MODE_ON",
24
+ "MODE_STEADY",
25
+ "derive_key",
26
+ "make_packet",
27
+ ]
@@ -0,0 +1,98 @@
1
+ """Async BLE client for the Holiday Show Home LED Ball.
2
+
3
+ Wraps connection management (via bleak-retry-connector) and the CSRmesh command
4
+ set. The caller owns device discovery and passes in a fresh ``BLEDevice`` (the ball
5
+ uses a rotating private address, so the address must be refreshed before each use).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ import random
13
+
14
+ from bleak.backends.device import BLEDevice
15
+ from bleak_retry_connector import BleakClientWithServiceCache, establish_connection
16
+
17
+ from . import protocol
18
+
19
+ _LOGGER = logging.getLogger(__name__)
20
+
21
+
22
+ class LightBall:
23
+ """Connect to one LED Ball and send CSRmesh commands."""
24
+
25
+ def __init__(self, ble_device: BLEDevice, name: str) -> None:
26
+ self._ble_device = ble_device
27
+ self._name = name
28
+ self._lock = asyncio.Lock()
29
+ self._seq = random.randint(0x100000, 0xF00000)
30
+ self._txn = 0
31
+ # A fresh random source per session avoids the mesh replay filter.
32
+ self._source = random.randint(0x8001, 0xBFFE)
33
+
34
+ def set_ble_device(self, ble_device: BLEDevice) -> None:
35
+ """Refresh the backing BLEDevice (its address rotates)."""
36
+ self._ble_device = ble_device
37
+
38
+ def _next_seq(self) -> int:
39
+ self._seq = (self._seq + 1) & 0xFFFFFF
40
+ return self._seq
41
+
42
+ def _next_txn(self) -> int:
43
+ self._txn = self._txn % 15 + 1
44
+ return self._txn
45
+
46
+ async def _send(self, payloads: list[bytes]) -> None:
47
+ async with self._lock:
48
+ client = await establish_connection(
49
+ BleakClientWithServiceCache,
50
+ self._ble_device,
51
+ self._name,
52
+ max_attempts=4,
53
+ )
54
+ try:
55
+ for payload in payloads:
56
+ packet = protocol.make_packet(
57
+ payload, self._next_seq(), self._source
58
+ )
59
+ for char_uuid, data in protocol.split_writes(packet):
60
+ await client.write_gatt_char(char_uuid, data, response=False)
61
+ await asyncio.sleep(0.08)
62
+ finally:
63
+ await client.disconnect()
64
+
65
+ async def set_state(
66
+ self, mode: int, color: int, level: int, *, turn_on: bool = True
67
+ ) -> None:
68
+ """Select handshake -> (optional) power on -> commonMode(mode, color, level)."""
69
+ payloads = [
70
+ protocol.select_payload(self._next_txn()),
71
+ protocol.select_payload(self._next_txn()),
72
+ ]
73
+ if turn_on:
74
+ payloads.append(protocol.power_payload(True, self._next_txn()))
75
+ for _ in range(2): # BLE is lossy; send the command twice
76
+ payloads.append(
77
+ protocol.common_mode_payload(mode, color, level, self._next_txn())
78
+ )
79
+ await self._send(payloads)
80
+
81
+ async def set_show(self, show_sel: int, *, turn_on: bool = True) -> None:
82
+ """Activate an animated 'show' preset via showView (slot 1)."""
83
+ payloads = [
84
+ protocol.select_payload(self._next_txn()),
85
+ protocol.select_payload(self._next_txn()),
86
+ ]
87
+ if turn_on:
88
+ payloads.append(protocol.power_payload(True, self._next_txn()))
89
+ for _ in range(2):
90
+ payloads.append(protocol.show_payload(show_sel, self._next_txn()))
91
+ await self._send(payloads)
92
+
93
+ async def turn_off(self) -> None:
94
+ """Turn the ball off."""
95
+ payloads = [protocol.select_payload(self._next_txn())]
96
+ for _ in range(2):
97
+ payloads.append(protocol.power_payload(False, self._next_txn()))
98
+ await self._send(payloads)
@@ -0,0 +1,125 @@
1
+ """CSRmesh MTL crypto and command builders for the LED Ball.
2
+
3
+ Self-contained reimplementation of the framing the official "Show Home" app sends:
4
+ an AES-128 counter-mode payload, a byte-reversed truncated HMAC-SHA256 MIC, and a
5
+ trailing 0xFF, split across two GATT control-point characteristics for packets
6
+ longer than 20 bytes.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import hmac
13
+ import struct
14
+
15
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
16
+
17
+ # GATT bridge service and the two MTL control-point characteristics.
18
+ SERVICE_UUID = "0000fef1-0000-1000-8000-00805f9b34fb"
19
+ CP1_UUID = "c4edc000-9daf-11e3-8003-00025b000b00" # first 20 bytes of a packet
20
+ CP2_UUID = "c4edc000-9daf-11e3-8004-00025b000b00" # remainder
21
+
22
+ PASSPHRASE = b"686868"
23
+ TYPEID = 0xFFFF # product bitmask the app uses for the ball (all products)
24
+
25
+ MODE_CLOSE = 0
26
+ MODE_STEADY = 1
27
+ MODE_ON = 255
28
+
29
+ BROADCAST = 0x0000
30
+ DEFAULT_SOURCE = 0x8000
31
+
32
+
33
+ def derive_key(passphrase: bytes = PASSPHRASE) -> bytes:
34
+ """Network key = reverse(SHA-256(passphrase + b"\\x00MCP"))[:16]."""
35
+ return bytes(reversed(hashlib.sha256(passphrase + b"\x00MCP").digest()))[:16]
36
+
37
+
38
+ KEY = derive_key()
39
+
40
+
41
+ def _aes_block(block16: bytes) -> bytes:
42
+ enc = Cipher(algorithms.AES(KEY), modes.ECB()).encryptor()
43
+ return enc.update(block16) + enc.finalize()
44
+
45
+
46
+ def make_packet(payload: bytes, seq: int, source: int = DEFAULT_SOURCE) -> bytes:
47
+ """Frame and encrypt one MTL packet (payload = dest(2 LE) + message bytes)."""
48
+ seq3 = struct.pack("<I", seq & 0xFFFFFF)[:3]
49
+ src2 = struct.pack("<H", source & 0xFFFF)
50
+ counter = seq3 + b"\x00" + src2 + b"\x00" * 10
51
+ keystream = _aes_block(counter)
52
+ enc = bytes(p ^ k for p, k in zip(payload, keystream, strict=False))
53
+ mic = bytes(
54
+ reversed(
55
+ hmac.new(KEY, b"\x00" * 8 + seq3 + src2 + enc, hashlib.sha256).digest()
56
+ )
57
+ )[:8]
58
+ return seq3 + src2 + enc + mic + b"\xff"
59
+
60
+
61
+ def _data_block(vendor: bytes, dest: int = BROADCAST) -> bytes:
62
+ return struct.pack("<H", dest & 0xFFFF) + bytes([0x73]) + vendor
63
+
64
+
65
+ def _vendor(
66
+ txn: int, cmd: int, b5: int, b6: int, b7: int, typeid: int = TYPEID
67
+ ) -> bytes:
68
+ f = (txn & 0x0F) << 4
69
+ return bytes(
70
+ [
71
+ f | 0x3,
72
+ 0x00,
73
+ (typeid >> 8) & 0xFF,
74
+ typeid & 0xFF,
75
+ f | (cmd & 0x0F),
76
+ b5 & 0xFF,
77
+ b6 & 0xFF,
78
+ b7 & 0xFF,
79
+ 0x00,
80
+ 0x00,
81
+ ]
82
+ )
83
+
84
+
85
+ def select_payload(txn: int) -> bytes:
86
+ """sendSelect handshake: [txn|0xE, 0, FF, FF, 0x6]."""
87
+ f = (txn & 0x0F) << 4
88
+ return _data_block(bytes([f | 0xE, 0x00, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0]))
89
+
90
+
91
+ def common_mode_payload(mode: int, color: int, level: int, txn: int) -> bytes:
92
+ """commonMode(mode, color, brightness level 0-4); wire byte = 4 - level."""
93
+ return _data_block(_vendor(txn, 0x3, mode, color, (4 - level) & 0xFF))
94
+
95
+
96
+ def power_payload(on: bool, txn: int) -> bytes:
97
+ """commonMode power toggle (mode 255 = on, 0 = off)."""
98
+ return _data_block(_vendor(txn, 0x3, MODE_ON if on else MODE_CLOSE, 0, 0))
99
+
100
+
101
+ def show_payload(show_sel: int, txn: int, slot: int = 1) -> bytes:
102
+ """showView (animated preset): cmd nibble 0xA, byte5=slot(1-3), byte6=show index."""
103
+ f = (txn & 0x0F) << 4
104
+ v = bytes(
105
+ [
106
+ f | 0x3,
107
+ 0x00,
108
+ (TYPEID >> 8) & 0xFF,
109
+ TYPEID & 0xFF,
110
+ f | 0xA,
111
+ slot & 0xFF,
112
+ show_sel & 0xFF,
113
+ 0,
114
+ 0,
115
+ 0,
116
+ ]
117
+ )
118
+ return _data_block(v)
119
+
120
+
121
+ def split_writes(packet: bytes) -> list[tuple[str, bytes]]:
122
+ """GATT writes for a packet: >20 bytes splits across CP1 then CP2."""
123
+ if len(packet) > 20:
124
+ return [(CP1_UUID, packet[:20]), (CP2_UUID, packet[20:])]
125
+ return [(CP1_UUID, packet)]
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: lightball-ble
3
+ Version: 0.1.0
4
+ Summary: CSRmesh BLE protocol and async client for Holiday Show Home LED Balls
5
+ Author: dallanwagz
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/dallanwagz/lightball-ble
8
+ Project-URL: Repository, https://github.com/dallanwagz/lightball-ble
9
+ Project-URL: Issues, https://github.com/dallanwagz/lightball-ble/issues
10
+ Keywords: bluetooth,ble,csrmesh,home-assistant,led,light
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Home Automation
16
+ Requires-Python: >=3.12
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: bleak>=0.22.0
20
+ Requires-Dist: bleak-retry-connector>=3.5.0
21
+ Requires-Dist: cryptography>=42.0.0
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest>=8; extra == "test"
24
+ Requires-Dist: pytest-asyncio>=0.23; extra == "test"
25
+ Requires-Dist: pytest-cov; extra == "test"
26
+ Requires-Dist: ruff; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # lightball-ble
30
+
31
+ Async BLE protocol and client for **Holiday Show Home "Show Home" LED Balls** — the
32
+ battery-powered RGB orbs sold under the Holiday Showtime / Show Home brands. They
33
+ speak Qualcomm/CSR's **CSRmesh** over a GATT bridge; this library reimplements that
34
+ framing so you can control a ball from Python (and powers the Home Assistant
35
+ [`lightball`](https://github.com/dallanwagz/lightball) integration).
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install lightball-ble
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ You provide a `bleak` `BLEDevice` (the ball rotates its BLE address, so re-resolve
46
+ it by the stable local name — e.g. `LAB00001CEB11` — before each use):
47
+
48
+ ```python
49
+ from bleak import BleakScanner
50
+ from lightball_ble import LightBall
51
+
52
+ device = await BleakScanner.find_device_by_name("LAB00001CEB11")
53
+ ball = LightBall(device, "LAB00001CEB11")
54
+
55
+ await ball.set_state(mode=1, color=0, level=2) # steady, red, mid brightness
56
+ await ball.set_show(6) # MultiColor animated show
57
+ await ball.turn_off()
58
+
59
+ # Re-resolve the address later, then reuse the client:
60
+ ball.set_ble_device(await BleakScanner.find_device_by_name("LAB00001CEB11"))
61
+ ```
62
+
63
+ ### Command reference
64
+
65
+ - `set_state(mode, color, level, *, turn_on=True)` — `commonMode`: animation `mode`
66
+ (0=off, 1=steady, 2=blink, 5=fade, 7=waves …), palette `color` index (0=red …
67
+ 28=MultiColor), brightness `level` 0–4.
68
+ - `set_show(show_sel, *, turn_on=True)` — `showView` animated preset
69
+ (0=Christmas … 6=MultiColor).
70
+ - `turn_off()`.
71
+
72
+ ## Protocol
73
+
74
+ `lightball_ble.protocol` exposes the low-level framing if you need it:
75
+
76
+ - **Network key**: `reverse(SHA-256(b"686868\x00MCP"))[:16]` (a fixed, product-line
77
+ shared key — `derive_key()`).
78
+ - **Packet**: AES-128 counter-mode payload + an 8-byte byte-reversed HMAC-SHA256 MIC
79
+ + a trailing `0xFF` (`make_packet`).
80
+ - **Transport**: packets > 20 bytes split across two GATT control points
81
+ (`split_writes`).
82
+
83
+ This was reverse-engineered from the official "Show Home" Android app; see the
84
+ [lightball](https://github.com/dallanwagz/lightball) project for the full writeup.
85
+
86
+ ## Develop
87
+
88
+ ```bash
89
+ pip install -e ".[test]"
90
+ pytest --cov=lightball_ble --cov-report=term-missing
91
+ ruff check . && ruff format --check .
92
+ ```
93
+
94
+ ## License
95
+
96
+ Apache-2.0.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/lightball_ble/__init__.py
5
+ src/lightball_ble/client.py
6
+ src/lightball_ble/protocol.py
7
+ src/lightball_ble.egg-info/PKG-INFO
8
+ src/lightball_ble.egg-info/SOURCES.txt
9
+ src/lightball_ble.egg-info/dependency_links.txt
10
+ src/lightball_ble.egg-info/requires.txt
11
+ src/lightball_ble.egg-info/top_level.txt
12
+ tests/test_client.py
13
+ tests/test_protocol.py
@@ -0,0 +1,9 @@
1
+ bleak>=0.22.0
2
+ bleak-retry-connector>=3.5.0
3
+ cryptography>=42.0.0
4
+
5
+ [test]
6
+ pytest>=8
7
+ pytest-asyncio>=0.23
8
+ pytest-cov
9
+ ruff
@@ -0,0 +1 @@
1
+ lightball_ble
@@ -0,0 +1,52 @@
1
+ """Tests for the LightBall BLE client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from unittest.mock import AsyncMock, MagicMock, patch
6
+
7
+ from lightball_ble.client import LightBall
8
+ from lightball_ble.protocol import CP1_UUID
9
+
10
+
11
+ async def _run(method: str, *args) -> MagicMock:
12
+ """Drive one client method with a mocked BLE connection; return the gatt client."""
13
+ gatt = MagicMock()
14
+ gatt.write_gatt_char = AsyncMock()
15
+ gatt.disconnect = AsyncMock()
16
+ with patch(
17
+ "lightball_ble.client.establish_connection", AsyncMock(return_value=gatt)
18
+ ):
19
+ ball = LightBall(MagicMock(), "LAB00001CEB11")
20
+ await getattr(ball, method)(*args)
21
+ return gatt
22
+
23
+
24
+ async def test_set_state_connects_writes_and_disconnects() -> None:
25
+ """set_state opens a connection, writes packets, and always disconnects."""
26
+ gatt = await _run("set_state", 1, 0, 2)
27
+ assert gatt.write_gatt_char.await_count >= 1
28
+ # The first GATT write of any packet goes to the primary control point.
29
+ assert gatt.write_gatt_char.await_args_list[0].args[0] == CP1_UUID
30
+ gatt.disconnect.assert_awaited_once()
31
+
32
+
33
+ async def test_set_show_writes() -> None:
34
+ """set_show writes at least one packet and disconnects."""
35
+ gatt = await _run("set_show", 6)
36
+ assert gatt.write_gatt_char.await_count >= 1
37
+ gatt.disconnect.assert_awaited_once()
38
+
39
+
40
+ async def test_turn_off_writes() -> None:
41
+ """turn_off writes at least one packet and disconnects."""
42
+ gatt = await _run("turn_off")
43
+ assert gatt.write_gatt_char.await_count >= 1
44
+ gatt.disconnect.assert_awaited_once()
45
+
46
+
47
+ async def test_set_ble_device_updates_target() -> None:
48
+ """Refreshing the BLEDevice swaps the target used for the next connection."""
49
+ ball = LightBall(MagicMock(), "LAB00001CEB11")
50
+ new_device = MagicMock()
51
+ ball.set_ble_device(new_device)
52
+ assert ball._ble_device is new_device
@@ -0,0 +1,46 @@
1
+ """Tests for the CSRmesh protocol builders."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from lightball_ble import derive_key, make_packet, protocol
6
+
7
+
8
+ def test_network_key_matches_hardware() -> None:
9
+ """The derived key matches the value verified against real devices."""
10
+ assert derive_key().hex() == "6750aae5bf990f0c660e5ed351a8cd26"
11
+
12
+
13
+ def test_show_payload_multicolor_bytes() -> None:
14
+ """MultiColor (show 6, txn 8) matches the bytes captured from the app."""
15
+ assert protocol.show_payload(6, 8).hex() == "0000738300ffff8a0106000000"
16
+
17
+
18
+ def test_common_mode_brightness_is_inverted() -> None:
19
+ """Brightness is sent as 4 - level on the wire."""
20
+ payload = protocol.common_mode_payload(1, 0, 2, 1)
21
+ # vendor byte 7 (index 3+7 = 10) carries 4 - level.
22
+ assert payload[3 + 7] == 4 - 2
23
+
24
+
25
+ def test_split_writes_short_packet_single_write() -> None:
26
+ """A <=20 byte packet uses only the first control point."""
27
+ short = b"\x00" * 10
28
+ assert protocol.split_writes(short) == [(protocol.CP1_UUID, short)]
29
+
30
+
31
+ def test_split_writes_long_packet_two_control_points() -> None:
32
+ """A >20 byte packet splits 20 bytes to CP1 then the remainder to CP2."""
33
+ packet = bytes(range(25))
34
+ writes = protocol.split_writes(packet)
35
+ assert writes[0][0] == protocol.CP1_UUID
36
+ assert len(writes[0][1]) == 20
37
+ assert writes[1][0] == protocol.CP2_UUID
38
+ assert writes[1][1] == bytes(range(20, 25))
39
+
40
+
41
+ def test_make_packet_framing() -> None:
42
+ """A framed packet carries the seq/source header and a 0xFF terminator."""
43
+ packet = make_packet(b"\x00\x00\x73\x01", seq=0x123456, source=0x8001)
44
+ assert packet[:3] == b"\x56\x34\x12" # seq, little-endian 3 bytes
45
+ assert packet[3:5] == b"\x01\x80" # source, little-endian
46
+ assert packet[-1] == 0xFF