gp2040ce-hostlighting 1.0.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.
@@ -0,0 +1,30 @@
1
+ <!--
2
+ gp2040ce-hostlighting (GP2040-CE Host Lighting library and tools)
3
+ Filename: README.md
4
+ Folder: gp2040ce_hostlighting
5
+ https://github.com/djGLiTCH/gp2040ce-hostlighting
6
+ SPDX-FileCopyrightText: (C) 2026 Jacob Simpson (DJ GLiTCH)
7
+ SPDX-License-Identifier: GPL-3.0-or-later
8
+ See LICENSES/GPL-3.0-or-later.txt at the repository root.
9
+ -->
10
+
11
+ # gp2040ce_hostlighting
12
+
13
+ The library, imported as `gp2040ce_hostlighting`. The repository's README shows
14
+ how a host uses it; the commands are in [`tools/`](tools/).
15
+
16
+ | File | What it does |
17
+ |---|---|
18
+ | `__init__.py` | Marks the package; it imports nothing, so importing the package changes nothing in the program that imports it |
19
+ | `protocol.py` | The protocol: constants, framing, the decoders, the errors, the device (`HostLightingDevice`), board discovery and the capability checks |
20
+ | `records.py` | The records and field groups every decoder returns |
21
+ | `claim.py` | `LightsClaim`, which takes, renews, follows and gives up the claim on a board's lights |
22
+ | `frames.py` | `Frame` and `publish_frame()`, the frames a streaming host sends |
23
+ | `cache.py` | `ConfigurationCache`, the configuration pages, read again only when they change |
24
+ | `session.py` | `Session`, the specification's whole host flow: handshake, claim, settings, events, cache, frames and shutdown |
25
+ | `runner.py` | `SessionRunner` and `AsyncSession`, a session on a thread of its own, and `BoardWatcher` and `SessionGroup`, every board on the bus |
26
+ | `layout.py` | `lights_by_cell()` and `Canvas`, the LED layout grid |
27
+ | `enums.py` | GP2040-CE's enum names, read from its `.proto` files |
28
+ | `conformance.py` | The conformance checks, and the round trip and frame-rate measurements |
29
+ | `testing.py` | Fake boards, a model board and report builders, to test host software without a board |
30
+ | `py.typed` | Tells type checkers the package carries type hints |
@@ -0,0 +1,12 @@
1
+ # gp2040ce-hostlighting (GP2040-CE Host Lighting library and tools)
2
+ # Filename: __init__.py
3
+ # Folder: gp2040ce_hostlighting
4
+ # https://github.com/djGLiTCH/gp2040ce-hostlighting
5
+ # SPDX-FileCopyrightText: (C) 2026 Jacob Simpson (DJ GLiTCH)
6
+ # SPDX-License-Identifier: GPL-3.0-or-later
7
+ # See LICENSES/GPL-3.0-or-later.txt at the repository root.
8
+
9
+ """Tools for GP2040-CE's Host Lighting add-on.
10
+
11
+ Importing the package has no side effects: no logging set-up, no command-line parsing and no heavy imports.
12
+ """
@@ -0,0 +1,215 @@
1
+ # gp2040ce-hostlighting (GP2040-CE Host Lighting library and tools)
2
+ # Filename: cache.py
3
+ # Folder: gp2040ce_hostlighting
4
+ # https://github.com/djGLiTCH/gp2040ce-hostlighting
5
+ # SPDX-FileCopyrightText: (C) 2026 Jacob Simpson (DJ GLiTCH)
6
+ # SPDX-License-Identifier: GPL-3.0-or-later
7
+ # See LICENSES/GPL-3.0-or-later.txt at the repository root.
8
+
9
+ """Keep a board's configuration pages, reading again only the pages that changed.
10
+
11
+ The state token changes whenever anything a configuration page reports changes, and the Summary's change
12
+ counters say which pages changed. ConfigurationCache reads the Summary, then each kept page with a moved counter,
13
+ under the Summary's token, so that the pages it keeps never mix two states. Lights are read whole once, then
14
+ groups 1 to 3 alone, the groups a profile switch changes.
15
+
16
+ Like the device, a cache belongs to one thread.
17
+ """
18
+ from typing import Any, Optional
19
+
20
+ from gp2040ce_hostlighting.protocol import (ADDRESSING_ACTION, ADDRESSING_KIND, ADDRESSING_LIGHT, ADDRESSING_PIN,
21
+ PAGE_ANIMATIONS, PAGE_CONTROLS, PAGE_GROUPS, PAGE_KEYBOARD_MAPPING,
22
+ PAGE_LIGHTS, PAGE_PROFILES, PAGE_SUMMARY, HostLightingDevice,
23
+ HostLightingError, HostLightingIncompatibleError,
24
+ HostLightingStaleTokenError)
25
+ from gp2040ce_hostlighting.records import (AnimationRecord, ControlRecord, Hello, KeyboardMappingRecord, LightRecord,
26
+ ProfileRecord, Summary)
27
+
28
+ __all__ = ['ConfigurationCache']
29
+
30
+ # the configuration pages, the Summary first
31
+ _CONFIGURATION_PAGES = (PAGE_SUMMARY, PAGE_PROFILES, PAGE_CONTROLS, PAGE_KEYBOARD_MAPPING, PAGE_LIGHTS,
32
+ PAGE_ANIMATIONS)
33
+ # the configuration pages with change counters in the Summary, 8 to 15
34
+ _COUNTED_PAGES = range(PAGE_SUMMARY, PAGE_SUMMARY + 8)
35
+ # the Lights groups a profile switch changes: kind and flags, owner, owner instances
36
+ _LIGHTS_CHANGING = 0b1110
37
+ _SUMMARY_CHANGES = 0b10
38
+
39
+
40
+ class ConfigurationCache:
41
+ """A board's configuration pages, as last read."""
42
+
43
+ def __init__(self, hello: Hello, masks: Optional[dict[int, int]] = None) -> None:
44
+ """Hold nothing read yet.
45
+
46
+ :param hello: the board's HELLO reply, its page bitmap saying which pages it has
47
+ :param masks: the field groups read per page, by default every group the library decodes. A mask of 0
48
+ is every group, as for GET_PAGE. The Summary's change counters are read whatever its mask says
49
+ :raises HostLightingIncompatibleError: for a board that does not list the Summary
50
+ """
51
+ if PAGE_SUMMARY not in hello.pages:
52
+ raise HostLightingIncompatibleError("the board does not list page 8 (Summary), which the cache reads "
53
+ "first")
54
+ self.hello = hello
55
+ every = {page: (1 << len(PAGE_GROUPS[page])) - 1 for page in _CONFIGURATION_PAGES}
56
+ self.masks = {page: (masks or {}).get(page) or mask for page, mask in every.items()}
57
+ # the configuration pages to keep, of those this library defines. The Summary is read whatever this holds
58
+ self.pages = frozenset(page for page in _CONFIGURATION_PAGES if page in hello.pages)
59
+ self.summary: Optional[Summary] = None
60
+ self.token: Optional[int] = None
61
+ self.counters: Optional[tuple[int, ...]] = None # the Summary's change counters, pages 8 to 15
62
+ # the configuration pages with a counter that moved at the last refresh, kept or not
63
+ self.moved: frozenset[int] = frozenset()
64
+ self._tables: dict[int, tuple[Any, ...]] = {}
65
+
66
+ def lights_reached(self, addressing: int, address: int) -> Optional[tuple[int, ...]]:
67
+ """Give the ordinals of the lights a STAGE entry reaches, as the board resolves it.
68
+
69
+ A light ordinal reaches that light, a pin (a page 10 key) or an action the lights it owns, and a kind
70
+ the lights of that kind. A light is reached only with an LED below the Summary's addressable LED limit.
71
+
72
+ :param addressing: ADDRESSING_LIGHT, ADDRESSING_PIN, ADDRESSING_ACTION or ADDRESSING_KIND
73
+ :param address: the entry's address
74
+ :return: the ordinals, or None while the Summary or the Lights groups this needs are not read
75
+ :raises ValueError: for a run's addressing
76
+ """
77
+ group = {ADDRESSING_LIGHT: 'leds', ADDRESSING_PIN: 'owner', ADDRESSING_ACTION: 'owner',
78
+ ADDRESSING_KIND: 'kind'}.get(addressing)
79
+ if group is None:
80
+ raise ValueError(f"addressing {addressing} is a run, not an entry")
81
+ lights = self.lights
82
+ if self.summary is None or lights is None or not all(
83
+ light.has('leds') and light.has(group) for light in lights):
84
+ return None
85
+ limit = self.summary.led_limit
86
+
87
+ def matches(light: LightRecord) -> bool:
88
+ if addressing == ADDRESSING_LIGHT:
89
+ return light.ordinal == address
90
+ if addressing == ADDRESSING_KIND:
91
+ return light.kind.value == address
92
+ owner = light.owner
93
+ return (owner.pin if addressing == ADDRESSING_PIN else owner.action) == address
94
+ return tuple(light.ordinal for light in lights
95
+ if matches(light) and light.leds.led_count and light.leds.first_led < limit)
96
+
97
+ def controls_with(self, key: Optional[int] = None,
98
+ action: Optional[int] = None) -> Optional[tuple[ControlRecord, ...]]:
99
+ """Give the controls with a page 10 key, an action, or both.
100
+
101
+ :return: the records, none when the board has no such control, or None while the Controls page's input
102
+ group is not read
103
+ """
104
+ controls = self.controls
105
+ if controls is None or not all(control.has('input') for control in controls):
106
+ return None
107
+ return tuple(control for control in controls if (key is None or control.input.key == key) and
108
+ (action is None or control.input.action == action))
109
+
110
+ def keyboard_code(self, action: int) -> Optional[int]:
111
+ """Give the code of a page 10 action's button, from the page 11 record with that action, if there is one.
112
+
113
+ A control sends it while the gamepad holds the button, with the exceptions the specification gives for page
114
+ 11. Up to Right on a GPIO pin or a Hall-effect trigger hold their D-pad direction only in the digital D-pad
115
+ mode (page 1's State dpad_mode), and an I/O-expander pin's in every mode. A Digital Direction action on a
116
+ GPIO pin holds the D-pad direction of that name, which page 3's names join, unless an add-on that runs
117
+ later sets the D-pad, which no page reports. A Dual Directional action, a macro action and a custom button
118
+ combo hold buttons no page reports. An I/O-expander pin holds only the buttons of BUTTON_PRESS_UP to
119
+ BUTTON_PRESS_R3, and other actions on an add-on input hold no button page 11 lists.
120
+
121
+ :return: the code, or None when page 11 has no record with the action or while its group is not read
122
+ """
123
+ mapping = self.keyboard_mapping
124
+ if mapping is None or not all(record.has('button') for record in mapping):
125
+ return None
126
+ return next((record.button.code for record in mapping if record.button.action == action), None)
127
+
128
+ def sends_key(self, action: int) -> Optional[bool]:
129
+ """Say whether the keyboard interface sends a page 10 action's button as its key, from page 11's flags.
130
+
131
+ Such a button leaves the controller's input. Every flag is clear while the keyboard interface is not present,
132
+ and a direction's flag is clear in the analog D-pad modes, where it stays on the controller.
133
+
134
+ :return: the flag, or None when page 11 has no record with the action or while its groups are not read
135
+ """
136
+ mapping = self.keyboard_mapping
137
+ if mapping is None or not all(record.has('button') and record.has('flags') for record in mapping):
138
+ return None
139
+ return next((record.flags.sends_key for record in mapping if record.button.action == action), None)
140
+
141
+ @property
142
+ def profiles(self) -> Optional[tuple[ProfileRecord, ...]]:
143
+ """The page 9 records, or None until read."""
144
+ return self._tables.get(PAGE_PROFILES)
145
+
146
+ @property
147
+ def controls(self) -> Optional[tuple[ControlRecord, ...]]:
148
+ """The page 10 records, or None until read."""
149
+ return self._tables.get(PAGE_CONTROLS)
150
+
151
+ @property
152
+ def keyboard_mapping(self) -> Optional[tuple[KeyboardMappingRecord, ...]]:
153
+ """The page 11 records, or None until read."""
154
+ return self._tables.get(PAGE_KEYBOARD_MAPPING)
155
+
156
+ @property
157
+ def lights(self) -> Optional[tuple[LightRecord, ...]]:
158
+ """The page 12 records, or None until read."""
159
+ return self._tables.get(PAGE_LIGHTS)
160
+
161
+ @property
162
+ def animations(self) -> Optional[tuple[AnimationRecord, ...]]:
163
+ """The page 13 records, or None until read."""
164
+ return self._tables.get(PAGE_ANIMATIONS)
165
+
166
+ def clear(self) -> None:
167
+ """Drop everything read, as a host does after a replug, reboot or input-mode change."""
168
+ self.summary = self.token = self.counters = None
169
+ self.moved = frozenset()
170
+ self._tables = {}
171
+
172
+ def refresh(self, device: HostLightingDevice, attempts: int = 3) -> frozenset[int]:
173
+ """Read the Summary, then each kept page with a moved change counter, or that was never read.
174
+
175
+ Each page is read under the Summary's state token. A read the board answers as stale starts again from
176
+ the Summary. Nothing is kept until every read has landed. `moved` then names every configuration page
177
+ with a moved counter, kept or not, so that a host that keeps neither Controls nor Lights still learns
178
+ that its frame has to be staged again.
179
+
180
+ :param device: the opened device
181
+ :param attempts: how many times to start from the Summary before giving up
182
+ :return: the pages read again, with page 8 when the Summary itself changed
183
+ :raises ValueError: for a kept page outside the pages this library defines, which it cannot decode
184
+ :raises HostLightingError: when the configuration keeps changing under the reads
185
+ """
186
+ unknown = sorted(self.pages - set(_CONFIGURATION_PAGES))
187
+ if unknown:
188
+ raise ValueError(f"the cache keeps pages {', '.join(map(str, _CONFIGURATION_PAGES))}, not {unknown[0]}")
189
+ for _ in range(attempts):
190
+ read = device.read_record(PAGE_SUMMARY, self.masks[PAGE_SUMMARY] | _SUMMARY_CHANGES)
191
+ record = read.records[0]
192
+ counters = record.changes.counters
193
+ moved = frozenset() if self.counters is None else frozenset(
194
+ page for page in _COUNTED_PAGES if counters[page - PAGE_SUMMARY] != self.counters[page - PAGE_SUMMARY])
195
+ due = [page for page in sorted(self.pages - {PAGE_SUMMARY})
196
+ if page not in self._tables or self.counters is None or page in moved]
197
+ try:
198
+ tables = {page: self._read(device, page, read.token) for page in due}
199
+ except HostLightingStaleTokenError:
200
+ continue
201
+ summary = record.summary if record.has('summary') else self.summary
202
+ changed = set(due) | ({PAGE_SUMMARY} if summary != self.summary else set())
203
+ self.summary, self.token, self.counters, self.moved = summary, read.token, counters, moved
204
+ self._tables.update(tables)
205
+ return frozenset(changed)
206
+ raise HostLightingError("the board's configuration kept changing while it was read")
207
+
208
+ def _read(self, device: HostLightingDevice, page: int, token: int) -> tuple[Any, ...]:
209
+ """Read one page under a token. Lights already held are read again by the groups that can change."""
210
+ mask, held = self.masks[page], self._tables.get(page)
211
+ if page == PAGE_LIGHTS and held is not None and mask & _LIGHTS_CHANGING:
212
+ records = device.read_table(page, mask & _LIGHTS_CHANGING, token).records
213
+ if len(records) == len(held):
214
+ return tuple(old.merged(new) for old, new in zip(held, records))
215
+ return device.read_table(page, mask, token).records