pyminleon 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.
pyminleon/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """pyminleon: asyncio control of Minleon NDB-Pro LED controllers' built-in effects over HTTP."""
2
+
3
+ from pyminleon.exceptions import ConfigError, ControllerError, MinleonError
4
+ from pyminleon.ndb import SUPPORTED_MODELS, NDBController, NDBPreset, NDBState, identify
5
+
6
+ __all__ = [
7
+ "SUPPORTED_MODELS",
8
+ "ConfigError",
9
+ "ControllerError",
10
+ "MinleonError",
11
+ "NDBController",
12
+ "NDBPreset",
13
+ "NDBState",
14
+ "identify",
15
+ ]
pyminleon/_http.py ADDED
@@ -0,0 +1,169 @@
1
+ """A minimal asyncio HTTP/1.0 client for talking to Minleon controllers on the LAN. Private; stdlib only.
2
+
3
+ One ``asyncio.timeout`` bounds connect, request, head, and body together, so a server dripping one byte at a time
4
+ cannot stall a caller. Head and body are size-capped, redirects are never followed, and the host is validated so it
5
+ can never steer the path, port, or scheme.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import contextlib
12
+ import ipaddress
13
+ import logging
14
+ import math
15
+ import re
16
+ from dataclasses import dataclass
17
+
18
+ from pyminleon.exceptions import ConfigError, ControllerError
19
+
20
+ _LOGGER = logging.getLogger(__name__)
21
+
22
+ MAX_BODY = 64 * 1024
23
+ MAX_HEAD = 16 * 1024
24
+ _CHUNK = 4096
25
+ _PATH = re.compile(r"/[!-~]*")
26
+ _CHUNK_SIZE = re.compile(rb"[0-9A-Fa-f]{1,8}")
27
+ _HOSTNAME = re.compile(r"[A-Za-z0-9.-]+")
28
+
29
+ # What a failed exchange raises out of ``request``: no route, refused, reset, timed out, or a truncated/oversized head.
30
+ TRANSPORT_ERRORS = (TimeoutError, OSError, asyncio.IncompleteReadError, asyncio.LimitOverrunError)
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class Response:
35
+ """Status code (``None`` if unparsable) and body; the body is read only for a 200 (``None`` otherwise)."""
36
+
37
+ status: int | None
38
+ body: bytes | None
39
+
40
+
41
+ def validate_port(port: object) -> int:
42
+ if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
43
+ raise ConfigError(f"port must be 1 to 65535, got {port!r}")
44
+ return port
45
+
46
+
47
+ def validate_timeout(timeout: object) -> float:
48
+ if isinstance(timeout, bool) or not isinstance(timeout, int | float) or not math.isfinite(timeout) or timeout <= 0:
49
+ raise ConfigError(f"timeout must be a positive finite number of seconds, got {timeout!r}")
50
+ return float(timeout)
51
+
52
+
53
+ def url_host(host: str) -> str:
54
+ """``host`` as it goes in a URL: a hostname or IPv4 address as is, an IPv6 literal bracketed."""
55
+ literal = host[1:-1] if host.startswith("[") and host.endswith("]") else host
56
+ if ":" in literal:
57
+ try:
58
+ address = ipaddress.IPv6Address(literal)
59
+ except ValueError:
60
+ raise ConfigError(f"host {host!r} is not a valid IPv6 address") from None
61
+ if address.scope_id is not None:
62
+ raise ConfigError(f"host {host!r}: IPv6 scope IDs are not supported")
63
+ return f"[{literal}]"
64
+ if literal != host or not _HOSTNAME.fullmatch(host):
65
+ raise ConfigError(f"host {host!r} must be a hostname, IPv4 address, or IPv6 address")
66
+ return host
67
+
68
+
69
+ def request_path(path: str) -> str:
70
+ path = "/" + path.lstrip("/")
71
+ if not _PATH.fullmatch(path):
72
+ raise ConfigError(f"HTTP path {path!r} must be printable ASCII without spaces")
73
+ return path
74
+
75
+
76
+ def url(host: str, port: int, path: str) -> str:
77
+ """``http://HOST:PORT/PATH``; ``host`` must be a hostname, IPv4 address, or IPv6 literal (brackets optional)."""
78
+ return f"http://{url_host(host)}:{port}{request_path(path)}"
79
+
80
+
81
+ def _is_ascii_digits(text: str) -> bool:
82
+ """``str.isdigit()`` also accepts digits such as ``"\u00b2"`` that ``int()`` rejects."""
83
+ return text.isascii() and text.isdigit()
84
+
85
+
86
+ def _parse_head(head: bytes) -> tuple[int | None, dict[str, str]]:
87
+ """Status code (``None`` if unparsable) and lower-cased headers of an HTTP response head."""
88
+ status_line, *lines = head.decode("latin-1").split("\r\n")
89
+ parts = status_line.split(" ", 2)
90
+ status = int(parts[1]) if len(parts) >= 2 and _is_ascii_digits(parts[1]) else None
91
+ headers: dict[str, str] = {}
92
+ for line in lines:
93
+ name, sep, value = line.partition(":")
94
+ if sep:
95
+ headers[name.strip().lower()] = value.strip()
96
+ return status, headers
97
+
98
+
99
+ async def request(
100
+ host: str, port: int, path: str, *, timeout: float, method: str = "GET", body: bytes | None = None
101
+ ) -> Response:
102
+ """One HTTP/1.0 exchange under one deadline. Redirects are never followed.
103
+
104
+ Raises ``ConfigError`` for a bad host or path, ``ControllerError`` for a body over ``MAX_BODY``, and one of
105
+ ``TRANSPORT_ERRORS`` when the exchange fails or the deadline passes.
106
+ """
107
+ host_part = url_host(host)
108
+ path = request_path(path)
109
+ full_url = f"http://{host_part}:{port}{path}"
110
+ head = f"{method} {path} HTTP/1.0\r\nHost: {host_part}:{port}\r\nConnection: close\r\n"
111
+ if body is not None:
112
+ head += f"Content-Length: {len(body)}\r\n"
113
+ payload = (head + "\r\n").encode() + (body or b"")
114
+ _LOGGER.debug("HTTP %s %s (%d body bytes)", method, full_url, len(body or b""))
115
+ async with asyncio.timeout(timeout): # connect, request, head, body, and close together
116
+ return await _exchange(host_part, port, payload, method, full_url)
117
+
118
+
119
+ async def _read_chunked(reader: asyncio.StreamReader, full_url: str) -> bytes:
120
+ """A chunked body, capped at ``MAX_BODY``; trailers are skipped. ``ControllerError`` on malformed framing."""
121
+ received = bytearray()
122
+ while True:
123
+ size_text = (await reader.readuntil(b"\r\n"))[:-2].split(b";", 1)[0].strip()
124
+ if not _CHUNK_SIZE.fullmatch(size_text):
125
+ raise ControllerError(f"{full_url} sent a malformed chunk size {size_text[:20]!r}")
126
+ size = int(size_text, 16)
127
+ if size == 0:
128
+ break
129
+ if len(received) + size > MAX_BODY:
130
+ raise ControllerError(f"{full_url} returned more than {MAX_BODY} bytes")
131
+ received += await reader.readexactly(size)
132
+ if await reader.readexactly(2) != b"\r\n":
133
+ raise ControllerError(f"{full_url} sent a chunk without its closing CRLF")
134
+ while (await reader.readuntil(b"\r\n")) != b"\r\n":
135
+ pass # trailer fields
136
+ return bytes(received)
137
+
138
+
139
+ async def _exchange(host_part: str, port: int, payload: bytes, method: str, full_url: str) -> Response:
140
+ writer: asyncio.StreamWriter | None = None
141
+ try:
142
+ reader, writer = await asyncio.open_connection(host_part.strip("[]"), port, limit=MAX_HEAD)
143
+ writer.write(payload)
144
+ await writer.drain()
145
+ status, headers = _parse_head(await reader.readuntil(b"\r\n\r\n"))
146
+ if status != 200:
147
+ _LOGGER.debug("HTTP %s %s answered %s", method, full_url, status)
148
+ return Response(status, None)
149
+ if "chunked" in headers.get("transfer-encoding", "").lower():
150
+ # The NDB-Pro answers HTTP/1.0 requests with HTTP/1.1 chunked bodies.
151
+ return Response(status, await _read_chunked(reader, full_url))
152
+ raw_length = headers.get("content-length", "")
153
+ length = int(raw_length) if _is_ascii_digits(raw_length) else None # unparsable: read to EOF
154
+ if length is not None and length > MAX_BODY:
155
+ raise ControllerError(f"{full_url} returned more than {MAX_BODY} bytes")
156
+ received = bytearray()
157
+ while len(received) <= MAX_BODY and (length is None or len(received) < length):
158
+ chunk = await reader.read(_CHUNK)
159
+ if not chunk:
160
+ break
161
+ received += chunk
162
+ if len(received) > MAX_BODY:
163
+ raise ControllerError(f"{full_url} returned more than {MAX_BODY} bytes")
164
+ return Response(status, bytes(received[:length]))
165
+ finally:
166
+ if writer is not None:
167
+ writer.close()
168
+ with contextlib.suppress(OSError):
169
+ await writer.wait_closed()
@@ -0,0 +1,13 @@
1
+ """pyminleon exception hierarchy."""
2
+
3
+
4
+ class MinleonError(Exception):
5
+ """Base class for every pyminleon error."""
6
+
7
+
8
+ class ConfigError(MinleonError, ValueError):
9
+ """Invalid host, port, timeout, or call argument."""
10
+
11
+
12
+ class ControllerError(MinleonError):
13
+ """A controller could not be reached, timed out, answered with a non-200 status, or sent something unusable."""
pyminleon/ndb.py ADDED
@@ -0,0 +1,228 @@
1
+ """Control of the Minleon NDB-Pro over the HTTP endpoints its own web UI uses.
2
+
3
+ It selects the controller's built-in effects, sets their intensity, and recalls stored show presets; it never writes
4
+ the controller's saved settings (no ``saveon``, no preset ``Set``, no ``?s=N``). The controller exposes its effect
5
+ state only as HTML, so ``state`` and ``presets`` read the UI pages with strict regexes and raise ``ControllerError``
6
+ when the markup is not what firmware 2.0 serves. ``config`` and ``status`` return the raw JSON documents from
7
+ ``/api/config`` and ``/api/status``. Stdlib only.
8
+
9
+ DDP pixel data overrides the built-in effect while it flows; about 20 s after DDP stops the controller falls back to it.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import html
15
+ import json
16
+ import logging
17
+ import re
18
+ from dataclasses import dataclass
19
+ from typing import Any
20
+
21
+ from pyminleon import _http
22
+ from pyminleon.exceptions import ConfigError, ControllerError
23
+
24
+ _LOGGER = logging.getLogger(__name__)
25
+
26
+ _EFFECTS_PATH = "/pfx2.html"
27
+ _COLORS_PATH = "/pcolors.html"
28
+ _SHOWS_PATH = "/pshows.html"
29
+ _CONTROL_PATH = "/api/control"
30
+ _CONFIG_PATH = "/api/config"
31
+ _STATUS_PATH = "/api/status"
32
+ _PRESET_SLOTS = 20 # "Show 1" is slots 0-9, "Show 2" is 10-19
33
+
34
+ SUPPORTED_MODELS: frozenset[str] = frozenset({"NDBPRO"})
35
+ """Model ids (the ``mod`` field of ``/api/status``) that pyminleon supports."""
36
+
37
+ # <button id='fxb16' class='psel button' onclick='fx2b("Glow",16)'>; the page's JS defines fx2b(name,id), unquoted.
38
+ _BUTTON_START = re.compile(r"<button\s+id='fxb")
39
+ _EFFECT_BUTTON = re.compile(
40
+ r"""<button id='fxb(\d{1,4})' class='(psel|pnsel) button' onclick='fx2b\("([^"<>]+)",\1\)'>""", re.ASCII
41
+ )
42
+ # <input type='range' min='1' max='100' class='slider Cint' value='100'>
43
+ _INTENSITY_SLIDER = re.compile(r"<input\b[^>]*\bclass='slider Cint'[^>]*>")
44
+ _SLIDER_VALUE = re.compile(r"\bvalue='(\d{1,3})'", re.ASCII)
45
+ # <a href="/pshows.html?r=0">Recall</a><td>Off<td>0<td ...
46
+ _RECALL_LINK = re.compile(r'href="/pshows\.html\?r=')
47
+ _PRESET_ROW = re.compile(r'<a href="/pshows\.html\?r=(\d{1,2})">Recall</a><td>([^<]*)<td>(\d{1,3})<', re.ASCII)
48
+
49
+
50
+ @dataclass(frozen=True, slots=True)
51
+ class NDBState:
52
+ """What the controller's UI shows: the selected built-in effect, its intensity, and every effect it offers."""
53
+
54
+ effect: str | None # selected built-in effect; None if the page shows none selected
55
+ intensity: int | None # 0-100; None if the colors page has no intensity slider
56
+ effects: tuple[str, ...] # in page order
57
+
58
+
59
+ @dataclass(frozen=True, slots=True)
60
+ class NDBPreset:
61
+ """One stored show slot as listed on the shows page."""
62
+
63
+ slot: int # 0-19
64
+ effect: str
65
+ intensity: int # 0-100
66
+
67
+
68
+ class NDBController:
69
+ """Selects and reads the built-in effects of a Minleon NDB-Pro over plain HTTP.
70
+
71
+ Every call is one or two short HTTP/1.0 requests bounded by ``timeout`` each. ``ControllerError`` means the
72
+ controller could not be reached, timed out, answered with a status other than 200, or answered with a page or
73
+ document pyminleon cannot read.
74
+ """
75
+
76
+ def __init__(self, host: str, *, port: int = 80, timeout: float = 3.0) -> None:
77
+ _http.url_host(host)
78
+ self._host = host
79
+ self._port = _http.validate_port(port)
80
+ self._timeout = _http.validate_timeout(timeout)
81
+
82
+ async def state(self) -> NDBState:
83
+ """The selected effect and effect list from ``/pfx2.html``, and the intensity from ``/pcolors.html``."""
84
+ effects, selected = _parse_effects(await self._page(_EFFECTS_PATH), self._url(_EFFECTS_PATH))
85
+ intensity = _parse_intensity(await self._page(_COLORS_PATH), self._url(_COLORS_PATH))
86
+ return NDBState(effect=selected, intensity=intensity, effects=effects)
87
+
88
+ async def presets(self) -> tuple[NDBPreset, ...]:
89
+ """The stored show slots from ``/pshows.html``, in page order."""
90
+ return _parse_presets(await self._page(_SHOWS_PATH), self._url(_SHOWS_PATH))
91
+
92
+ async def config(self) -> dict[str, Any]:
93
+ """The raw JSON object from ``GET /api/config`` (the DDP-spec configuration document)."""
94
+ return await self._json_object(_CONFIG_PATH)
95
+
96
+ async def status(self) -> dict[str, Any]:
97
+ """The raw JSON object from ``GET /api/status`` (the DDP-spec status document)."""
98
+ return await self._json_object(_STATUS_PATH)
99
+
100
+ async def set_effect(self, name: str) -> None:
101
+ """Select the built-in effect ``name`` (as listed in ``NDBState.effects``); "Off" blanks the lights."""
102
+ if not isinstance(name, str) or not name.strip():
103
+ raise ConfigError(f"effect name must be a non-empty string, got {name!r}")
104
+ await self._control({"fx": name})
105
+
106
+ async def set_intensity(self, percent: int) -> None:
107
+ """Set the built-in effect intensity, 0 to 100 percent."""
108
+ if isinstance(percent, bool) or not isinstance(percent, int) or not 0 <= percent <= 100:
109
+ raise ConfigError(f"intensity must be an integer 0 to 100, got {percent!r}")
110
+ await self._control({"int": str(percent)})
111
+
112
+ async def recall_preset(self, slot: int) -> None:
113
+ """Recall stored show slot ``slot`` (0-9 are "Show 1", 10-19 "Show 2"). Never saves."""
114
+ if isinstance(slot, bool) or not isinstance(slot, int) or not 0 <= slot < _PRESET_SLOTS:
115
+ raise ConfigError(f"preset slot must be an integer 0 to {_PRESET_SLOTS - 1}, got {slot!r}")
116
+ await self._request("GET", f"{_SHOWS_PATH}?r={slot}")
117
+
118
+ def _url(self, path: str) -> str:
119
+ return _http.url(self._host, self._port, path)
120
+
121
+ async def _control(self, fields: dict[str, str]) -> None:
122
+ # Compact separators: byte-for-byte what the controller's own UI sends.
123
+ body = json.dumps(fields, separators=(",", ":")).encode()
124
+ await self._request("POST", _CONTROL_PATH, body)
125
+
126
+ async def _json_object(self, path: str) -> dict[str, Any]:
127
+ return _decode_object(await self._page(path), self._url(path))
128
+
129
+ async def _page(self, path: str) -> str:
130
+ url = self._url(path)
131
+ body = (await self._request("GET", path)).body or b"" # a 200 always carries a body, possibly empty
132
+ try:
133
+ return body.decode("utf-8")
134
+ except UnicodeDecodeError:
135
+ raise ControllerError(f"{url} is not UTF-8 text") from None
136
+
137
+ async def _request(self, method: str, path: str, body: bytes | None = None) -> _http.Response:
138
+ url = self._url(path)
139
+ try:
140
+ response = await _http.request(
141
+ self._host, self._port, path, timeout=self._timeout, method=method, body=body
142
+ )
143
+ except TimeoutError as exc:
144
+ raise ControllerError(f"{method} {url} timed out after {self._timeout:g} s") from exc
145
+ except _http.TRANSPORT_ERRORS as exc:
146
+ raise ControllerError(f"{method} {url} failed: {exc}") from exc
147
+ if response.status != 200:
148
+ raise ControllerError(f"{method} {url} answered {response.status}")
149
+ _LOGGER.debug("%s %s answered 200", method, url)
150
+ return response
151
+
152
+
153
+ async def identify(host: str, *, port: int = 80, timeout: float = 3.0) -> str | None:
154
+ """The supported model id (e.g. ``"NDBPRO"``) at ``host``, or ``None``.
155
+
156
+ ``None`` means the host did not answer in time, did not answer ``GET /api/status`` with a JSON status, or reports
157
+ a model not in ``SUPPORTED_MODELS``. ``ConfigError`` for a bad host, port, or timeout.
158
+ """
159
+ controller = NDBController(host, port=port, timeout=timeout)
160
+ try:
161
+ document = await controller.status()
162
+ except ControllerError:
163
+ return None
164
+ nested = document.get("status")
165
+ model = (nested if isinstance(nested, dict) else document).get("mod")
166
+ return model if isinstance(model, str) and model in SUPPORTED_MODELS else None
167
+
168
+
169
+ def _decode_object(page: str, url: str) -> dict[str, Any]:
170
+ try:
171
+ document = json.loads(page)
172
+ except ValueError:
173
+ raise ControllerError(f"{url} is not valid JSON") from None
174
+ if not isinstance(document, dict):
175
+ raise ControllerError(f"{url} is not a JSON object")
176
+ return document
177
+
178
+
179
+ def _parse_effects(page: str, url: str) -> tuple[tuple[str, ...], str | None]:
180
+ buttons = _EFFECT_BUTTON.findall(page)
181
+ if not buttons:
182
+ raise ControllerError(f"{url} has no effect buttons")
183
+ if len(buttons) != len(_BUTTON_START.findall(page)):
184
+ raise ControllerError(f"{url} has effect button markup pyminleon does not recognize")
185
+ effects: list[str] = []
186
+ selected: list[str] = []
187
+ for _, css, raw_name in buttons:
188
+ name = html.unescape(raw_name)
189
+ if name in effects:
190
+ raise ControllerError(f"{url} lists effect {name!r} more than once")
191
+ effects.append(name)
192
+ if css == "psel":
193
+ selected.append(name)
194
+ if len(selected) > 1:
195
+ raise ControllerError(f"{url} shows {len(selected)} effects selected: {selected!r}")
196
+ return tuple(effects), selected[0] if selected else None
197
+
198
+
199
+ def _parse_intensity(page: str, url: str) -> int | None:
200
+ sliders = _INTENSITY_SLIDER.findall(page)
201
+ if not sliders:
202
+ return None
203
+ if len(sliders) > 1:
204
+ raise ControllerError(f"{url} has {len(sliders)} intensity sliders")
205
+ value = _SLIDER_VALUE.search(sliders[0])
206
+ intensity = int(value.group(1)) if value else None
207
+ if intensity is None or intensity > 100:
208
+ raise ControllerError(f"{url} intensity slider has no value 0 to 100: {sliders[0]!r}")
209
+ return intensity
210
+
211
+
212
+ def _parse_presets(page: str, url: str) -> tuple[NDBPreset, ...]:
213
+ rows = _PRESET_ROW.findall(page)
214
+ if not rows:
215
+ raise ControllerError(f"{url} has no preset rows")
216
+ if len(rows) != len(_RECALL_LINK.findall(page)):
217
+ raise ControllerError(f"{url} has preset rows pyminleon does not recognize")
218
+ presets: list[NDBPreset] = []
219
+ seen: set[int] = set()
220
+ for raw_slot, raw_effect, raw_intensity in rows:
221
+ slot, effect, intensity = int(raw_slot), html.unescape(raw_effect).strip(), int(raw_intensity)
222
+ if slot >= _PRESET_SLOTS or slot in seen:
223
+ raise ControllerError(f"{url} lists preset slot {slot}, outside 0 to {_PRESET_SLOTS - 1} or repeated")
224
+ if not effect or intensity > 100:
225
+ raise ControllerError(f"{url} slot {slot}: effect {effect!r} at intensity {intensity} is not usable")
226
+ seen.add(slot)
227
+ presets.append(NDBPreset(slot, effect, intensity))
228
+ return tuple(presets)
pyminleon/py.typed ADDED
File without changes
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyminleon
3
+ Version: 0.1.0
4
+ Summary: Asyncio control of Minleon NDB-Pro LED controllers' built-in effects over HTTP
5
+ Project-URL: Documentation, https://amattas.github.io/pyminleon/
6
+ Project-URL: Source, https://github.com/amattas/pyminleon
7
+ Author-email: Anthony Mattas <anthony@mattas.net>
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: home-automation,led,lighting,minleon,ndb-pro
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Home Automation
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ Provides-Extra: dev
21
+ Requires-Dist: bandit==1.9.4; extra == 'dev'
22
+ Requires-Dist: build==1.6.1; extra == 'dev'
23
+ Requires-Dist: mypy==2.3.0; extra == 'dev'
24
+ Requires-Dist: pre-commit==4.7.0; extra == 'dev'
25
+ Requires-Dist: pytest-asyncio==1.4.0; extra == 'dev'
26
+ Requires-Dist: pytest-cov==7.1.0; extra == 'dev'
27
+ Requires-Dist: pytest==9.1.1; extra == 'dev'
28
+ Requires-Dist: pyyaml==6.0.3; extra == 'dev'
29
+ Requires-Dist: ruff==0.17.2; extra == 'dev'
30
+ Requires-Dist: types-pyyaml==6.0.12.20260906; extra == 'dev'
31
+ Provides-Extra: docs
32
+ Requires-Dist: pydoc-markdown==4.8.2; extra == 'docs'
33
+ Requires-Dist: zensical==0.0.50; extra == 'docs'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # pyminleon
37
+
38
+ Asyncio Python library that controls the built-in effects of Minleon NDB-Pro LED controllers over the HTTP endpoints
39
+ the controller's own web UI uses. Zero runtime dependencies (stdlib only), Python 3.12+.
40
+
41
+ It does not send pixel data. For that, use a DDP sender such as [aioddp](https://github.com/amattas/aioddp). While DDP
42
+ data flows it overrides the built-in effect; about 20 s after DDP stops the controller falls back to it.
43
+
44
+ ## Quick start
45
+
46
+ ```python
47
+ import asyncio
48
+
49
+ from pyminleon import NDBController, identify
50
+
51
+
52
+ async def main() -> None:
53
+ host = "10.0.40.20" # placeholder
54
+ if await identify(host) is None:
55
+ raise SystemExit("not a supported Minleon controller")
56
+
57
+ ndb = NDBController(host)
58
+ state = await ndb.state() # NDBState(effect="Glow", intensity=100, effects=("Off", ..., "Worms"))
59
+ await ndb.set_effect("Color Wave")
60
+ await ndb.set_intensity(60)
61
+ await ndb.recall_preset(3) # slots 0-9 are "Show 1", 10-19 "Show 2"
62
+ layout = await ndb.config() # raw JSON from GET /api/config (DDP-spec layout document)
63
+ print(state, layout["config"]["ports"][0], (await ndb.status())["status"]["mod"])
64
+
65
+
66
+ asyncio.run(main())
67
+ ```
68
+
69
+ ## API
70
+
71
+ - `NDBController(host, *, port=80, timeout=3.0)`
72
+ - `await state() -> NDBState` selected effect, intensity, and every effect the controller offers
73
+ - `await presets() -> tuple[NDBPreset, ...]` stored show slots
74
+ - `await set_effect(name)`, `await set_intensity(percent)`, `await recall_preset(slot)`
75
+ - `await config() -> dict[str, Any]`, `await status() -> dict[str, Any]` raw `/api/config` and `/api/status` documents
76
+ - `await identify(host, *, port=80, timeout=3.0) -> str | None` the model id (e.g. `"NDBPRO"`) if the host reports a
77
+ model in `SUPPORTED_MODELS`; `None` if it answers but is not a supported Minleon, or does not answer in time
78
+ - Errors: `MinleonError` > `ConfigError` (bad host, port, timeout, or argument), `ControllerError` (unreachable,
79
+ timed out, non-200, or an unreadable page or document)
80
+
81
+ ## Safety
82
+
83
+ - Nothing is ever written to the controller's saved settings. The library never requests `/pshows.html?s=N` (which
84
+ overwrites a preset slot) and never sends `saveon`. The only requests it makes are `POST /api/control`,
85
+ `GET /pshows.html?r=N` (recall), and read-only pages (`/pfx2.html`, `/pcolors.html`, `/pshows.html`,
86
+ `/api/config`, `/api/status`).
87
+ - `state()` and `presets()` parse the web UI's HTML with strict patterns written against firmware 2.0 and raise
88
+ `ControllerError` on anything else rather than guessing.
89
+ - HTTP responses are size-capped (64 KiB), redirects are never followed, and each call is bounded by `timeout`.
90
+ - Hosts are validated (hostname, IPv4, or IPv6 literal only) so a value can never steer the path, port, or scheme.
91
+
92
+ ## Documentation
93
+
94
+ https://amattas.github.io/pyminleon/
95
+
96
+ ## Development
97
+
98
+ ```bash
99
+ conda create -n pyminleon -c conda-forge python=3.14
100
+ conda run -n pyminleon python -m pip install -e ".[dev]"
101
+ conda run -n pyminleon python -m pytest -q
102
+ conda run -n pyminleon ruff check . && conda run -n pyminleon ruff format --check . && conda run -n pyminleon mypy
103
+ conda run -n pyminleon bandit -q -r src
104
+ ```
105
+
106
+ ## License
107
+
108
+ Apache-2.0
@@ -0,0 +1,9 @@
1
+ pyminleon/__init__.py,sha256=OQTQFwPsUrM00-Rp6alSRK6Bli93-Etas435FLwAoQA,434
2
+ pyminleon/_http.py,sha256=IQ3d_MkjiezsAcZhr_j1GsrlMX9tK9Bl_JoBIHvsoyk,7301
3
+ pyminleon/exceptions.py,sha256=v1Os0wBKBNZct3rzxaDdgm7yIMj-C0vDUJejmhpGxSQ,377
4
+ pyminleon/ndb.py,sha256=kFxss5sXl75z4Yn3wUHuFnkmPrQbXrMghykS68G3JBE,10446
5
+ pyminleon/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ pyminleon-0.1.0.dist-info/METADATA,sha256=liP8FWffiLc9TVFpVH2TUE_DwEX70ZL7nTjDYWWEnsY,4643
7
+ pyminleon-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ pyminleon-0.1.0.dist-info/licenses/LICENSE,sha256=lCpzvwGMJJJamfGDDLI4fGXa9nm10FMrZ2SNlGfcFB4,11343
9
+ pyminleon-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 PyDMP Contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.