Author SHA1 Message Date
jimmyandClaude Haiku 5.5 20a9b60d5f feat: device configuration over HTTP and OTA updates for the CLI
The CLI reaches a device over HTTP as well as USB: http_device.py holds the
request helpers, driver_ota.py uploads driver firmware, and cli.py and
ota.py use them. The README documents the new options.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-17 00:34:22 +13:00
jimmyandClaude Opus 5.5 f5ab256b4a feat: configure the ESP-IDF led-driver over USB
idf_device.py talks to the driver's USB API (led-driver main/usb_cfg.cpp).
--driver auto (default) asks the port first and falls back to mpremote.
Existing flags map to the driver's API (-s, --pin, -l, -o, -b, --preset,
--default, --ssid/--wifi-password, -n, -r, -f); new ESP-IDF flags cover
the rest of the network settings (--ap, --ap-ssid, --ap-password, --ddp,
--dhcp, --static, --dns), --max-brightness and --scan. Opening the port
keeps DTR high so connecting doesn't reset the C3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:34:36 +13:00
jimmyandClaude Haiku 5.5 c9dea6e142 chore: in-progress CLI and device changes
Work in progress from the same tree as the controller's sequences-v2 changes.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 14:10:55 +13:00
jimmyandClaude Sonnet 5.5 892ccaec71 feat(cli): add --ota to update a v2 controller over Ethernet
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 00:22:55 +13:00
14 changed files with 1162 additions and 1474 deletions

No files matched your search

+144 -39
View File
@@ -1,59 +1,164 @@
# led-tool # led-tool
CLI helpers for MicroPython LED devices: **`settings.json`** download/upload via **mpremote**, resets, follow/tail, recursive uploads, optional firmware flash, and **led-driver**-oriented flags (presets, transport, Wi-Fi fields). Command-line tool for the LED drivers. It configures both firmwares found in this repo, and updates their firmware:
Connection is always via **`-p` / `--port`** (default `/dev/ttyACM0`). There is **no** separate “server IP” flag; the Pi or PC address is configured on the device in **`settings.json`** when using Wi-Fi mode. - **ESP-IDF led-driver** (ESP32-C3): settings, patterns and presets over **USB** or **Wi-Fi**. Changes apply live, so no reset is needed.
- **MicroPython driver**: `settings.json`, presets and files over USB (via mpremote). Changes need a reset to apply.
## Common flags The tool detects the firmware on the serial port. Use `--driver idf` or `--driver mpy` to skip detection.
| Flag | Purpose | Run `python cli.py -h` for every flag, grouped by firmware, with examples at the end.
|------|--------|
| `-p`, `--port` | Serial device (default `/dev/ttyACM0`) |
| `-s`, `--show` | Print current settings from the device |
| `-n`, `--name` | Device **name** |
| `--reset-device-name` | Set **name** to firmware default (`led-` + STA MAC hex, same as `Settings.set_defaults` on led-driver) |
| `--id` | Numeric device id (ESP-NOW, 0–255) |
| `--pin` | LED GPIO (`led_pin`) |
| `-b`, `--brightness` | Brightness 0–255 |
| `-l`, `--leds` | LED count (`num_leds`) |
| `-d`, `--debug` | Debug 0 or 1 |
| `-o`, `--order` | LED colour order (`rgb`, `grb`, …) |
| `--preset` / `--pattern` | Create or replace a named preset in **led-driver** `presets.json` |
| `--default` | Startup preset name |
| `--transport` | `espnow` or `wifi` (`transport_type` on device) |
| `--ssid`, `--wifi-password`, `--wifi-channel` | Wi-Fi / channel fields for the driver |
| `-r`, `--reset` | Reset the device |
| `-f`, `--follow` | Follow serial output (optional timeout seconds) |
| `--pause` | Sleep N seconds (for chained actions) |
| `-u`, `--upload` | Recursive upload: `-u SRC [DEST]` (skips unchanged files via `file_hashes.json` on device) |
| `--src`, `--lib`, `--all` | Deploy led-driver trees to flash root, `patterns/`, and `lib/` |
| `--force-upload` | Upload every file; ignore `file_hashes.json` |
| `-e`, `--erase` | Erase everything at device root (including `settings.json` and `presets.json`) |
| `--rm` | Remove a path on the device |
| `--flash` | Flash a firmware binary (uses **esptool** on the host) |
**Settings I/O:** With no arguments, **`led-cli`** prints help (no device access). **`--show`** downloads `settings.json` and prints it (read-only). Setting fields (`--name`, `-b`, …) download once, merge, print, and **upload only when a value actually changed**. **`--preset`** alone only touches **`presets.json`** (no `settings.json` download). Ordered actions (`--reset`, `--upload`, `-e`, …) run without touching settings unless you also pass **`--show`** or setting / preset edits as above. ## Connecting
Run **`python cli.py -h`** for the full epilog and argument list. | Connection | Flag | Notes |
|---|---|---|
| USB serial (default) | `-p`, `--port` | Default `/dev/ttyACM0`. Opening the port keeps DTR high and RTS low, so the C3 is not reset on connect. |
| Wi-Fi | `--host ADDR` | IP or name of an ESP-IDF driver, for example `--host 192.168.4.20` or `--host bar1.local`. Port 80. |
## Web UI (`static/` + `web.py`) Over `--host` every settings, pattern and preset flag works the same as over USB. Two flags need USB: `-r` (reboot) and `-f` (follow the serial log). MicroPython is USB only.
Edit **`settings.json`** in the browser: ## ESP-IDF led-driver
- **Web Serial** — USB on the machine running the browser (Chrome/Edge). Use **Connect USB**, then **Download** / **Upload**. ### Settings (USB or Wi-Fi)
- **Host serial** — USB on the Pi/PC running **`led-cli`** (port list + **`led-cli`** merge/upload).
**Standalone (Flask):** | Flag | Setting |
|---|---|
| `--pin`, `-l`, `-o`, `--max-brightness` | LED GPIO, LED count, colour order, global ceiling |
| `-b` | Brightness |
| `-n NAME`, `--reset-device-name` | Hostname (mDNS `NAME.local`); reset gives `led` |
| `--ap on\|off`, `--ap-ssid NAME`, `--ap-password PASS` | Access point (empty name: `led-XXXXXX`; empty password: open) |
| `--ddp on\|off` | Receive DDP pixels and frame sync |
| `--dhcp`, `--static IP NETMASK GATEWAY [DNS]`, `--dns ADDR` | Wi-Fi client address |
| `--ssid SSID`, `--wifi-password PASS` | Wi-Fi network to join; the device reconnects |
| `--default NAME` | Startup preset (runs at boot) |
| `--scan` | List the Wi-Fi networks the device can see |
`-s` shows the settings: hardware, brightness, network, Wi-Fi SSID and the startup preset. It is printed after any change.
Network changes can move the device to a new address. If you change `--static` or `--dhcp` over `--host`, the next command needs the new address.
### Patterns and presets (USB or Wi-Fi)
Presets are saved on the device. Patterns named with `--play` or `--pattern` are the driver's own names; see `--list-patterns`.
| Flag | Does |
|---|---|
| `--list-patterns` | Print the pattern names the driver has |
| `--list-presets` | Print the saved preset names, with the startup one marked |
| `--preset NAME [--pattern P] [options]` | Create or replace a saved preset. Only the fields given are changed. |
| `--play PATTERN [options]` | Show a pattern now, without saving it |
| `--select NAME` | Show a saved preset now |
| `--delete NAME` | Delete a saved preset |
| `--preset-order NAME [NAME ...]` | Set the order of the saved presets |
| `--presets-defaults` | Add the default presets that are missing |
Options for `--preset` and `--play`:
| Option | Meaning |
|---|---|
| `--colors HEX [HEX ...]` | Colours, for example `#ff0000 #00ff00` |
| `--background HEX` | Background colour |
| `--delay MS` | Delay between steps |
| `--preset-brightness 0-255` | Brightness of this preset (not the global level) |
| `--fade MS` | Fade time |
| `--reverse on\|off` | Run in reverse |
| `--auto on\|off` | Autorun flag |
| `--beat-time on\|off` | Time the pattern to the beat |
`--preset` and `--play` cannot be used together. Options given without one of them are an error.
Not yet exposed: the preset's numeric parameters `n1`–`n4` and `mode`.
```bash
python cli.py --list-presets
python cli.py --preset warm --pattern chase --colors '#ff0000' '#00ff00' --delay 50 --default warm
python cli.py --select warm
python cli.py --play rainbow --fade 200
python cli.py --host 192.168.4.20 --preset warm --pattern solid --colors '#ffa000'
```
### Reboot and logs (USB only)
```bash
python cli.py -r # reboot
python cli.py -f # follow the serial log, Ctrl+C to stop
python cli.py -r --pause 2 -f
```
## Firmware updates
Both update over Wi-Fi with the driver's `/ota` endpoint. The image is always given explicitly for LED drivers.
| Flag | Does |
|---|---|
| `--ota HOST [IMAGE]` | Update one **v2 controller** (ESP32-S3, Ethernet). Image defaults to `led_controller_v2.bin` under `./v2/build`, `./build` or `../v2/build`. |
| `--ota-drivers [TARGET ...]` | Find ESP-IDF LED drivers in the given targets and update them in parallel. Default `auto` is this machine's `/24`. See the target forms below. |
| `--ota-image PATH` | Driver firmware for `--ota-drivers`. **Required**, for example `../led-driver/build/led_driver.bin`. |
| `--ota-jobs N` | Simultaneous uploads (default 4). |
| `--ota-list` | Only find and list the drivers; do not update. |
Targets:
| Form | Scans |
|---|---|
| `auto` | This machine's `/24` (default) |
| `192.168.4` | The `/24`, the same as `192.168.4.0/24` |
| `10.0.0.0/23` | A CIDR network (up to 4096 addresses per run) |
| `192.168.4.10-40` or `192.168.4.10-192.168.4.40` | An inclusive address range |
| `192.168.4.25` | One address |
Give several targets separated by spaces or commas. Duplicates are scanned once. A run can probe at most 4096 addresses; larger targets are refused, so narrow them.
```bash ```bash
cd led-tool cd led-tool
python web.py python cli.py --ota-drivers --ota-image ../led-driver/build/led_driver.bin
# open http://<host>:5000/editor python cli.py --ota-drivers 192.168.4.10-40 --ota-list
python cli.py --ota-drivers 192.168.4.0/24 10.0.0.0/25 --ota-jobs 2 --ota-image ../led-driver/build/led_driver.bin
python cli.py --ota-drivers 192.168.4.10-40,192.168.5.7 --ota-image ../led-driver/build/led_driver.bin
``` ```
**Embedded in led-controller:** open **LED Tool** in the main UI, or visit **`/led-tool/editor`**. `--ota-drivers` probes `GET /ota` on each address in the targets, so it only finds devices that run the driver firmware. Drivers are reported with their partition and build; a driver that comes back on the same partition is reported as a failure.
Legacy Flask form UI remains at **`/`** on port 5000; prefer **`/editor`** for Web Serial support. Build the driver image first with `make build` in `led-driver`.
## MicroPython driver
These flags apply to the MicroPython driver only, and are rejected when an ESP-IDF driver answers.
| Flag | Does |
|---|---|
| `-n NAME`, `-l N`, `-b`, `-o`, `--pin` | Settings written to `settings.json` |
| `--preset NAME --pattern P` | Create or replace a preset in `presets.json` (patterns: off, on, blink, rainbow, pulse, transition, chase, circle) |
| `--default NAME` | Startup preset |
| `--transport espnow\|wifi`, `--ssid`, `--wifi-password`, `--wifi-channel`, `--id`, `-d` | Transport and radio settings |
| `-u SRC [DEST]`, `--src [DIR]`, `--lib [DIR]`, `--patterns [DIR]`, `--all` | Upload directories to the device |
| `--ls`, `--rm PATH`, `-e` | List, delete or erase files on the device |
| `--flash BINARY` | Flash a firmware binary with esptool (path, or a filename in `bin/`) |
| `--reset-device-name` | Name becomes `led-` + the STA MAC |
Without setting edits, the tool downloads `settings.json` and prints the merged view. It uploads again only when you pass edits, `--preset`, or an upload, flash or erase action. Actions run in the order given on the command line, for example `--reset --pause 2 --follow`.
## Installing
`install.sh` installs the Python dependencies with pipenv, builds `dist/led-cli` with PyInstaller, and copies it to `~/.local/bin`.
```bash
./install.sh
```
Run from source with `python cli.py` after `pipenv install`.
## Files
| File | Purpose |
|---|---|
| `cli.py` | Argument parsing and the commands for both firmwares |
| `idf_device.py` | ESP-IDF API over USB (`@api` lines on the serial port) |
| `http_device.py` | The same ESP-IDF API over Wi-Fi (`--host`) |
| `device.py` | MicroPython device access via mpremote |
| `ota.py` | Firmware upload to one device, used by `--ota` and `--ota-drivers` |
| `driver_ota.py` | Discovery of ESP-IDF drivers on a subnet and parallel update |
## License ## License
+525 -159
View File
@@ -2,10 +2,8 @@
""" """
LED Bar Configuration CLI Tool LED Bar Configuration CLI Tool
Command-line interface for editing settings.json on MicroPython devices via mpremote. Command-line interface for downloading, editing, and uploading settings.json
Settings are downloaded from the device only when displaying (--show) or when applying to/from MicroPython devices via mpremote.
setting changes; uploads occur only when something changed. Use --erase to clear the
device filesystem (including settings).
""" """
import json import json
@@ -18,7 +16,11 @@ from typing import Dict, Any, List, Optional
import tempfile import tempfile
import os import os
from ota import ota_update
import driver_ota
import http_device
from device import copy_file, DeviceConnection, firmware_default_device_name from device import copy_file, DeviceConnection, firmware_default_device_name
import idf_device
def resolve_flash_binary(path: str) -> Optional[str]: def resolve_flash_binary(path: str) -> Optional[str]:
@@ -150,14 +152,15 @@ _FLAGS_WITH_VALUE = frozenset({
'-p', '--port', '-n', '--name', '--pin', '-b', '--brightness', '-p', '--port', '-n', '--name', '--pin', '-b', '--brightness',
'-l', '--leds', '-d', '-debug', '--debug', '-o', '--order', '-l', '--leds', '-d', '-debug', '--debug', '-o', '--order',
'--preset', '--pattern', '--default', '--transport', '--ssid', '--preset', '--pattern', '--default', '--transport', '--ssid',
'--wifi-password', '--wifi-channel', '--src', '--lib', '--patterns', '--paterns', '--wifi-password', '--wifi-channel', '--ota', '--src', '--lib', '--patterns', '--paterns',
'--driver', '--max-brightness', '--ap', '--ap-ssid', '--ap-password', '--ddp', '--dns',
}) })
def _get_ordered_actions(argv: List[str]) -> List[tuple]: def _get_ordered_actions(argv: List[str]) -> List[tuple]:
""" """
Scan argv and return list of (action_name, value) in order of appearance. Scan argv and return list of (action_name, value) in order of appearance.
Actions: flash, pause, reset, upload, ls, erase_all, rm, follow. Actions: flash, ota, pause, reset, upload, ls, erase_all, rm, follow.
""" """
actions = [] actions = []
i = 1 i = 1
@@ -181,6 +184,16 @@ def _get_ordered_actions(argv: List[str]) -> List[tuple]:
else: else:
raise ValueError("--flash requires an argument") raise ValueError("--flash requires an argument")
continue continue
if arg == '--ota':
vals = []
i += 1
while i < len(argv) and not argv[i].startswith('-') and len(vals) < 2:
vals.append(argv[i])
i += 1
if not vals:
raise ValueError("--ota requires a host (and optionally an image path)")
actions.append(('ota', vals))
continue
if arg in ('-r', '--reset'): if arg in ('-r', '--reset'):
actions.append(('reset', None)) actions.append(('reset', None))
i += 1 i += 1
@@ -223,10 +236,6 @@ def _get_ordered_actions(argv: List[str]) -> List[tuple]:
actions.append(('upload', ["lib", "lib"])) actions.append(('upload', ["lib", "lib"]))
i += 1 i += 1
continue continue
if arg == '--force-upload':
# Handled via argparse; skip during action scan
i += 1
continue
if arg == '--lib': if arg == '--lib':
# Upload local DIR (default: ./lib) to /lib on device # Upload local DIR (default: ./lib) to /lib on device
local_dir = "lib" local_dir = "lib"
@@ -279,47 +288,330 @@ def _get_ordered_actions(argv: List[str]) -> List[tuple]:
return actions return actions
# Flags that only the MicroPython driver understands (settings.json / file uploads)
_MPY_ONLY = {
"device_id": "--id", "debug": "--debug", "transport": "--transport",
"wifi_channel": "--wifi-channel", "upload": "-u", "src": "--src", "lib": "--lib",
"all": "--all", "patterns_dir": "--patterns", "ls": "--ls", "erase_all": "-e", "rm": "--rm",
}
# And the reverse: flags only the ESP-IDF driver understands
_IDF_ONLY = {
"max_brightness": "--max-brightness", "ap": "--ap", "ap_ssid": "--ap-ssid",
"ap_password": "--ap-password", "ddp": "--ddp", "dhcp": "--dhcp", "static": "--static",
"dns": "--dns", "scan": "--scan",
"play": "--play", "select": "--select", "delete": "--delete", "presets_defaults": "--presets-defaults",
"preset_order": "--preset-order", "list_presets": "--list-presets", "list_patterns": "--list-patterns",
"colors": "--colors", "background": "--background", "delay": "--delay",
"preset_brightness": "--preset-brightness", "fade": "--fade", "reverse": "--reverse",
"auto": "--auto", "beat_time": "--beat-time",
}
def _idf_show(dev: "idf_device.IdfDevice") -> Dict[str, Any]:
"""Everything the ESP-IDF driver will tell over USB, in one view."""
status = dev.get("/api/status")
presets = dev.get("/api/presets")
return {
"hardware": dev.get("/api/hardware"),
"brightness": {
"global": status.get("global_brightness"),
"master": status.get("master_brightness"),
},
"network": dev.get("/api/network"),
"wifi": {"ssid": dev.get("/api/wifi").get("ssid")},
"startup_preset": presets.get("startup"),
}
def _idf_post(dev: "idf_device.IdfDevice", path: str, body: Dict[str, Any]) -> None:
reply = dev.post(path, body)
msg = reply.get("message") if isinstance(reply, dict) else None
print(f"{path}: {msg or 'ok'}", file=sys.stderr)
if isinstance(reply, dict) and reply.get("address"):
print(f" device address: {reply['address']}", file=sys.stderr)
def _hex_rgb(text: str) -> List[int]:
"""'#ff8000' or 'ff8000' -> [255, 128, 0]."""
t = text.lstrip("#")
if len(t) != 6:
raise ValueError(f"colour must be six hex digits, e.g. #ff8000: {text}")
try:
return [int(t[i:i + 2], 16) for i in (0, 2, 4)]
except ValueError:
raise ValueError(f"colour must be six hex digits, e.g. #ff8000: {text}") from None
def _preset_content(args: argparse.Namespace) -> Dict[str, Any]:
"""The preset fields given on the command line (only those; the driver keeps the rest)."""
c: Dict[str, Any] = {}
if args.colors is not None:
c["colors"] = [_hex_rgb(x) for x in args.colors]
if args.background is not None:
c["background"] = _hex_rgb(args.background)
if args.delay is not None:
c["delay"] = args.delay
if args.preset_brightness is not None:
c["brightness"] = args.preset_brightness
if args.fade is not None:
c["fade"] = args.fade
if args.reverse is not None:
c["reverse"] = args.reverse == "on"
if args.auto is not None:
c["auto"] = args.auto == "on"
if args.beat_time is not None:
c["beat_time"] = args.beat_time == "on"
return c
def run_idf(args: argparse.Namespace, ordered_actions: List[tuple]) -> None:
"""Configure an ESP-IDF led-driver through its USB API (led-driver main/usb_cfg.cpp)."""
bad = [flag for dest, flag in _MPY_ONLY.items() if getattr(args, dest, None) not in (None, False)]
if bad:
print(f"Error: {', '.join(bad)}: MicroPython driver only (this is an ESP-IDF led-driver)", file=sys.stderr)
sys.exit(1)
try:
content = _preset_content(args)
except ValueError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if args.preset is not None and args.play is not None:
print("Error: use either --preset (saved) or --play (live), not both", file=sys.stderr)
sys.exit(1)
if content and args.preset is None and args.play is None:
print("Error: colour, delay and other preset options need --preset NAME or --play PATTERN",
file=sys.stderr)
sys.exit(1)
if args.pattern is not None and args.preset is None and args.play is None:
print("Error: --pattern needs --preset NAME or --play", file=sys.stderr)
sys.exit(1)
if args.host:
# Same API over Wi-Fi: everything below works unchanged, except reboot and follow
port = args.host
dev = http_device.HttpDevice(args.host)
else:
port = args.port
dev = idf_device.IdfDevice(port, verbose=args.verbose)
try:
dev.open()
except Exception as e:
print(f"Error: cannot open {port}: {e}", file=sys.stderr)
sys.exit(1)
try:
# Actions in command-line order (reset, pause, follow, flash, ota)
for action_name, value in ordered_actions:
if action_name == "pause":
print(f"Pausing for {value} seconds...", file=sys.stderr)
time.sleep(value)
elif action_name == "reset":
print(f"Rebooting device on {port}...", file=sys.stderr)
dev.reboot()
# The USB port drops and comes back during the restart
dev.close()
time.sleep(2.0)
dev.open()
elif action_name == "follow":
if value is None:
print(f"Following output from {port}... (Press Ctrl+C to stop)", file=sys.stderr)
else:
print(f"Following output from {port} for {value} seconds...", file=sys.stderr)
try:
dev.follow(value)
except KeyboardInterrupt:
print("\nStopped following.", file=sys.stderr)
return
elif action_name == "ota":
ota_update(value[0], value[1] if len(value) > 1 else None)
elif action_name == "flash":
print("Error: --flash with an ESP-IDF driver: use idf.py flash (or --driver mpy for a merged image)",
file=sys.stderr)
sys.exit(1)
# Settings edits, each sent to the API route that owns it. They apply live: no reset.
hw: Dict[str, Any] = {}
if args.pin is not None:
hw["pin"] = args.pin
if args.leds is not None:
hw["num_leds"] = args.leds
if args.color_order is not None:
hw["rgb_order"] = args.color_order
if args.max_brightness is not None:
hw["max_brightness"] = args.max_brightness
net: Dict[str, Any] = {}
if args.name is not None and args.reset_device_name:
print("Error: use either --name or --reset-device-name, not both.", file=sys.stderr)
sys.exit(1)
if args.name is not None:
net["hostname"] = args.name
elif args.reset_device_name:
net["hostname"] = "led"
if args.ap is not None:
net["ap_enabled"] = args.ap == "on"
if args.ap_ssid is not None:
net["ap_ssid"] = args.ap_ssid
if args.ap_password is not None:
net["ap_password"] = args.ap_password
if args.ddp is not None:
net["ddp_enabled"] = args.ddp == "on"
if args.dhcp and args.static:
print("Error: use either --dhcp or --static, not both.", file=sys.stderr)
sys.exit(1)
if args.dhcp:
net["mode"] = "dhcp"
if args.static:
if len(args.static) not in (3, 4):
print("Error: --static needs IP NETMASK GATEWAY [DNS]", file=sys.stderr)
sys.exit(1)
net["mode"] = "static"
net.update(dict(zip(("ip", "netmask", "gateway", "dns"), args.static)))
if args.dns is not None:
if args.static and len(args.static) == 4:
print("Error: DNS given twice (--static's 4th value and --dns)", file=sys.stderr)
sys.exit(1)
net["dns"] = args.dns
wifi: Dict[str, Any] = {}
if args.ssid is not None:
wifi["ssid"] = args.ssid
wifi["password"] = args.wifi_password or ""
elif args.wifi_password is not None:
print("Error: --wifi-password needs --ssid", file=sys.stderr)
sys.exit(1)
edited = False
if hw:
_idf_post(dev, "/api/hardware", hw)
edited = True
if args.brightness is not None:
_idf_post(dev, "/api/brightness", {"brightness": args.brightness})
edited = True
if args.presets_defaults:
added = dev.post("/api/presets/defaults", {}).get("added", 0)
print(f"/api/presets/defaults: added {added} preset(s)", file=sys.stderr)
edited = True
if args.preset is not None:
body: Dict[str, Any] = {"name": args.preset, **content}
if args.pattern is not None:
body["pattern"] = args.pattern
_idf_post(dev, "/api/presets", body)
edited = True
if args.delete is not None:
_idf_post(dev, "/api/presets/delete", {"name": args.delete})
edited = True
if args.preset_order is not None:
_idf_post(dev, "/api/presets/order", {"names": args.preset_order})
edited = True
if args.default is not None:
_idf_post(dev, "/api/presets/startup", {"name": args.default})
edited = True
if args.select is not None:
_idf_post(dev, "/api/presets/select", {"name": args.select})
edited = True
if args.play is not None:
_idf_post(dev, "/api/pattern", {"pattern": args.play, **content})
edited = True
if args.list_presets:
presets = dev.get("/api/presets")
startup = presets.get("startup")
for p in presets.get("presets", []):
mark = " (startup)" if p.get("name") == startup else ""
print(f"{p.get('name')}{mark}")
if args.list_patterns:
for name in dev.get("/api/status").get("patterns", []):
print(name)
if args.mode is not None:
_idf_post(dev, "/api/espnow", {"enabled": args.mode == "espnow"})
edited = True
print(f" mode: {args.mode} (restart to apply: -r)", file=sys.stderr)
if wifi:
_idf_post(dev, "/api/wifi", wifi)
edited = True
if net:
# Last: it reconnects Wi-Fi (USB is unaffected)
_idf_post(dev, "/api/network", net)
edited = True
if "dns" in net and net.get("mode", dev.get("/api/network").get("mode")) != "static":
print(" note: DNS is used only with a static address (--static); DHCP supplies its own",
file=sys.stderr)
if args.scan:
print(f"Scanning for Wi-Fi networks on {port}...", file=sys.stderr)
nets = dev.get("/api/wifi/scan", timeout=15).get("networks", [])
nets.sort(key=lambda n: n.get("rssi", -999), reverse=True)
width = max([len(n.get("ssid") or "") for n in nets] + [4])
print(f"{'SSID':<{width}} RSSI SECURITY")
for n in nets:
ssid = n.get("ssid") or "(hidden)"
print(f"{ssid:<{width}} {n.get('rssi', 0):>4} {'open' if n.get('open') else 'secured'}")
listed = args.list_presets or args.list_patterns
actions_only = (ordered_actions or args.scan or listed) and not edited and not args.show
if not actions_only:
print_settings(_idf_show(dev))
except idf_device.IdfError as e:
print(f"Error from device: {e}", file=sys.stderr)
sys.exit(1)
except TimeoutError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
finally:
dev.close()
def main() -> None: def main() -> None:
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="LED Bar Configuration CLI Tool", description="""LED bar configuration tool.
Two firmwares are supported, found automatically on the serial port:
ESP-IDF led-driver (ESP32-C3, JSON API). Settings apply live, no reset needed.
MicroPython driver (mpremote). Settings are written to settings.json and need a reset.
The ESP-IDF driver also takes its settings over Wi-Fi: use --host ADDR instead of -p.
Flags marked (ESP-IDF) or (MicroPython) only apply to that firmware.""",
formatter_class=argparse.RawDescriptionHelpFormatter, formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=""" epilog="""
Examples: Examples
# Show help (no device I/O) Show settings (either driver):
%(prog)s %(prog)s -s
%(prog)s --host 192.168.4.20 -s
# Show current settings.json from device (read-only) Settings (ESP-IDF, USB or Wi-Fi):
%(prog)s --show %(prog)s -l 60 -o grb --pin 10 -b 128 strip: LEDs, colour order, GPIO, brightness
%(prog)s -n bar1 --ssid home --wifi-password secret
%(prog)s --ap off --static 10.0.0.5 255.255.255.0 10.0.0.1 --dns 1.1.1.1
%(prog)s --dhcp --ddp on
%(prog)s --scan list Wi-Fi networks the device can see
# Edit device name and brightness, then upload only if values changed Patterns and presets (ESP-IDF, USB or Wi-Fi):
%(prog)s -n "LED-Strip-1" -b 128 %(prog)s --list-patterns pattern names the driver has
%(prog)s --list-presets saved presets, startup marked
%(prog)s --preset warm --pattern chase --colors '#ff0000' '#00ff00' --delay 50
%(prog)s --preset warm --default warm save a preset and make it the startup
%(prog)s --select warm show a saved preset now
%(prog)s --play rainbow --fade 200 show a pattern now, without saving
%(prog)s --delete old --preset-order warm
%(prog)s --presets-defaults add the default presets that are missing
# Set multiple parameters Reboot and logs (USB only):
%(prog)s -n "MyLED" -b 200 --preset "rainbow" %(prog)s -r reboot
%(prog)s -f follow the serial log (Ctrl+C to stop)
%(prog)s -r --pause 2 -f reboot, wait 2 s, then follow
# Set number of LEDs, color order, and debug mode Firmware:
%(prog)s -l 60 -o rgb -d 1 %(prog)s --flash firmware.bin MicroPython: flash over serial
%(prog)s --ota-drivers --ota-image led-driver/build/led_driver.bin
find every ESP-IDF driver on this Wi-Fi subnet
and update them in parallel
%(prog)s --ota-drivers 192.168.4 --ota-list only list the drivers found on 192.168.4.x
%(prog)s --ota 10.1.1.180 [image] update one v2 controller over Ethernet
# Reset the device MicroPython driver:
%(prog)s -r %(prog)s -n "MyStrip" -l 60 --default rainbow settings.json, then reset to apply
%(prog)s -u ./src upload a directory to the device
# Follow device output
%(prog)s -f
# Reset and then follow output
%(prog)s -r -f
# Flash firmware binary (full path or filename in bin/)
%(prog)s --flash firmware.bin
%(prog)s -p /dev/ttyUSB0 --flash /path/to/firmware.bin
# Reset, pause 2 seconds, then follow output
%(prog)s --reset --pause 2 --follow
# Set name, num_leds, default pattern, and upload
%(prog)s --name "MyStrip" -l 60 --default rainbow
# Reset logical device name to firmware default (STA MAC based)
%(prog)s --reset-device-name %(prog)s --reset-device-name
""" """
) )
@@ -327,18 +619,18 @@ Examples:
parser.add_argument( parser.add_argument(
"-p", "--port", "-p", "--port",
default="/dev/ttyACM0", default="/dev/ttyACM0",
help="Serial port/device path (default: /dev/ttyACM0)" help="Serial port of the device, USB (default: /dev/ttyACM0). Not used with --host"
) )
parser.add_argument( parser.add_argument(
"-n", "--name", "-n", "--name",
help="Device name" help="Device name (ESP-IDF: the Wi-Fi hostname, mDNS name <name>.local)"
) )
parser.add_argument( parser.add_argument(
"--reset-device-name", "--reset-device-name",
action="store_true", action="store_true",
help="Set name to firmware default (led-<STA MAC hex>, same as fresh settings.json on led-driver)", help="Reset the name to the firmware default (MicroPython: led-<MAC>; ESP-IDF: led)",
) )
parser.add_argument( parser.add_argument(
@@ -346,21 +638,21 @@ Examples:
dest="device_id", dest="device_id",
type=int, type=int,
metavar="0-255", metavar="0-255",
help="Numeric device ID used for ESPNow (0-255)" help="(MicroPython) numeric device ID for ESP-NOW (0-255)"
) )
parser.add_argument( parser.add_argument(
"--pin", "--pin",
type=int, type=int,
metavar="N", metavar="N",
help="LED GPIO pin number (led_pin in settings.json)" help="LED GPIO pin number (both drivers)"
) )
parser.add_argument( parser.add_argument(
"-b", "--brightness", "-b", "--brightness",
type=int, type=int,
metavar="0-255", metavar="0-255",
help="Brightness (0-255)" help="Brightness, 0-255 (both drivers)"
) )
parser.add_argument( parser.add_argument(
@@ -368,7 +660,7 @@ Examples:
dest="leds", dest="leds",
type=int, type=int,
metavar="N", metavar="N",
help="Number of LEDs (num_leds in settings.json)" help="Number of LEDs in the strip (both drivers)"
) )
parser.add_argument( parser.add_argument(
@@ -377,52 +669,50 @@ Examples:
type=int, type=int,
choices=[0, 1], choices=[0, 1],
metavar="0|1", metavar="0|1",
help="Debug mode (0 or 1)" help="(MicroPython) debug mode, 0 or 1"
) )
parser.add_argument( parser.add_argument(
"-o", "--order", "-o", "--order",
dest="color_order", dest="color_order",
choices=["rgb", "rbg", "grb", "gbr", "brg", "bgr"], choices=["rgb", "rbg", "grb", "gbr", "brg", "bgr"],
help="Color order (rgb, rbg, grb, gbr, brg, bgr)" help="LED colour order (both drivers)"
) )
parser.add_argument( parser.add_argument(
"--preset", "--preset",
metavar="NAME", metavar="NAME",
help="Create or replace preset NAME in presets.json (led-driver; use --pattern)", help="Create or replace preset NAME (both drivers; add --pattern and the preset options under Patterns and presets)",
) )
parser.add_argument( parser.add_argument(
"--pattern", "--pattern",
choices=[ help="Pattern for --preset (MicroPython: off, on, blink, rainbow, pulse, transition, chase, circle;"
"off", "on", "blink", "rainbow", "pulse", "transition", "chase", "circle", " ESP-IDF: any name from -s 'patterns'). MicroPython default: on",
],
help="Pattern type for --preset (default: on)",
) )
parser.add_argument( parser.add_argument(
"--default", "--default",
metavar="NAME", metavar="NAME",
help="Default/startup preset name in settings.json (which preset runs at boot)", help="Startup preset: the one that runs at boot (both drivers)",
) )
parser.add_argument( parser.add_argument(
"--transport", "--transport",
choices=["espnow", "wifi"], choices=["espnow", "wifi"],
help="led-driver transport_type", help="(MicroPython) transport_type: espnow or wifi",
) )
parser.add_argument( parser.add_argument(
"--ssid", "--ssid",
help="led-driver ssid (Wi-Fi network in wifi mode)", help="Wi-Fi network to join (both drivers)",
) )
parser.add_argument( parser.add_argument(
"--wifi-password", "--wifi-password",
dest="wifi_password", dest="wifi_password",
metavar="PASS", metavar="PASS",
help="led-driver password (Wi-Fi PSK in wifi mode)", help="Wi-Fi password for --ssid (both drivers; empty for an open network)",
) )
parser.add_argument( parser.add_argument(
@@ -430,7 +720,7 @@ Examples:
dest="wifi_channel", dest="wifi_channel",
type=int, type=int,
metavar="1-11", metavar="1-11",
help="led-driver wifi_channel (ESP-NOW mode)", help="(MicroPython) ESP-NOW channel, 1-11",
) )
parser.add_argument( parser.add_argument(
@@ -443,7 +733,7 @@ Examples:
parser.add_argument( parser.add_argument(
"-r", "--reset", "-r", "--reset",
action="store_true", action="store_true",
help="Reset the device" help="Reboot the device (USB only, both drivers)"
) )
parser.add_argument( parser.add_argument(
@@ -452,20 +742,20 @@ Examples:
const=None, const=None,
type=float, type=float,
metavar="SECONDS", metavar="SECONDS",
help="Follow device output continuously (like tail -f). Optionally specify SECONDS to limit follow duration." help="(ESP-IDF and MicroPython, USB only) follow the device output like tail -f; optionally stop after SECONDS"
) )
parser.add_argument( parser.add_argument(
"-s", "--show", "-s", "--show",
action="store_true", action="store_true",
help="Display current settings from device" help="Show the current settings (both drivers)"
) )
parser.add_argument( parser.add_argument(
"-u", "--upload", "-u", "--upload",
nargs='+', nargs='+',
metavar=("SRC", "DEST"), metavar=("SRC", "DEST"),
help="Upload a directory recursively to the device. Usage: -u SRC [DEST] (DEST is optional, defaults to basename of SRC)" help="(MicroPython) upload a directory recursively to the device: -u SRC [DEST] (DEST defaults to the basename of SRC)"
) )
parser.add_argument( parser.add_argument(
@@ -473,7 +763,7 @@ Examples:
nargs="?", nargs="?",
const="src", const="src",
metavar="DIR", metavar="DIR",
help="Upload DIR recursively to device root (:/, no leading directory), excluding patterns/. If DIR is omitted, uses local ./src." help="(MicroPython) upload DIR to the device root, excluding patterns/ (default: ./src)"
) )
parser.add_argument( parser.add_argument(
@@ -481,19 +771,13 @@ Examples:
nargs="?", nargs="?",
const="lib", const="lib",
metavar="DIR", metavar="DIR",
help="Upload DIR recursively to /lib on device. If DIR is omitted, uses local ./lib." help="(MicroPython) upload DIR to /lib on the device (default: ./lib)"
) )
parser.add_argument( parser.add_argument(
"--all", "--all",
action="store_true", action="store_true",
help="Upload ./src (excluding patterns), ./src/patterns, and ./lib." help="(MicroPython) upload ./src, ./src/patterns and ./lib"
)
parser.add_argument(
"--force-upload",
action="store_true",
help="Upload every file; ignore file_hashes.json on the device",
) )
parser.add_argument( parser.add_argument(
@@ -502,47 +786,176 @@ Examples:
nargs="?", nargs="?",
const=os.path.join("src", "patterns"), const=os.path.join("src", "patterns"),
metavar="DIR", metavar="DIR",
help="Upload DIR recursively to /patterns on device. If DIR is omitted, uses local ./src/patterns." help="(MicroPython) upload DIR to /patterns on the device (default: ./src/patterns)"
) )
parser.add_argument( parser.add_argument(
"--ls", "--ls",
action="store_true", action="store_true",
help="List files on the device root (:/)" help="(MicroPython) list files on the device root (:/)"
) )
parser.add_argument( parser.add_argument(
"-e", "--erase", "-e", "--erase",
dest="erase_all", dest="erase_all",
action="store_true", action="store_true",
help="Erase the device filesystem: delete all files and directories at device root (including settings.json and presets.json)", help="(MicroPython) erase all code on the device, keeping settings.json"
) )
parser.add_argument( parser.add_argument(
"--rm", "--rm",
metavar="PATH", metavar="PATH",
help="Delete a file or directory on the device (recursive for directories)" help="(MicroPython) delete a file or directory on the device (recursive for directories)"
)
parser.add_argument(
"--ota",
nargs="+",
metavar=("HOST", "IMAGE"),
help="Update one v2 controller (the ESP32-S3 controller, not an LED driver) over Ethernet: HOST [IMAGE]. Exits afterwards"
)
parser.add_argument(
"--ota-drivers",
nargs="*",
metavar="TARGET",
help="Find LED drivers on the network and update them in parallel. TARGET is auto (this machine's /24, "
"the default), a /24 such as 192.168.4, a CIDR network such as 10.0.0.0/23, an address range such as "
"192.168.4.10-40 or 192.168.4.10-192.168.4.40, or one address. Several targets can be given, "
"separated by spaces or commas. No serial port is used and the tool exits afterwards",
)
parser.add_argument(
"--host",
metavar="ADDR",
help="Configure an ESP-IDF led-driver over Wi-Fi at ADDR (IP or name) instead of USB. Every settings "
"flag works the same; -r and -f need USB",
)
parser.add_argument(
"--ota-image",
metavar="PATH",
help="Driver firmware for --ota-drivers (required, e.g. led-driver/build/led_driver.bin)",
)
parser.add_argument(
"--ota-jobs",
type=int,
default=4,
metavar="N",
help="Simultaneous uploads for --ota-drivers (default 4)",
)
parser.add_argument(
"--ota-list",
action="store_true",
help="With --ota-drivers: only discover and list the drivers, do not update",
) )
parser.add_argument( parser.add_argument(
"--flash", "--flash",
metavar="BINARY", metavar="BINARY",
help="Flash firmware binary to device. Path can be full path or filename in bin/" help="(MicroPython) flash a firmware binary over serial. Path, or a filename in bin/"
) )
parser.add_argument(
"--driver",
choices=["auto", "idf", "mpy"],
default="auto",
help="Device firmware: idf (ESP-IDF led-driver, USB API), mpy (MicroPython, mpremote), "
"or auto (default: ask the port, fall back to mpy)",
)
parser.add_argument(
"-v", "--verbose",
action="store_true",
help="(ESP-IDF, USB) print the device's log lines while talking to it",
)
idf = parser.add_argument_group("ESP-IDF led-driver only")
idf.add_argument("--max-brightness", dest="max_brightness", type=int, metavar="0-255",
help="Ceiling for every output colour")
idf.add_argument("--ap", choices=["on", "off"], help="Turn the access point on or off")
idf.add_argument("--ap-ssid", dest="ap_ssid", metavar="NAME",
help="Access point name (empty: led-XXXXXX)")
idf.add_argument("--ap-password", dest="ap_password", metavar="PASS",
help="Access point password, 8-63 characters (empty: open)")
idf.add_argument("--ddp", choices=["on", "off"], help="Receive DDP pixels and frame sync")
idf.add_argument("--dhcp", action="store_true", help="Wi-Fi client address from DHCP")
idf.add_argument("--static", nargs="+", metavar="ADDR",
help="Static Wi-Fi client address: IP NETMASK GATEWAY [DNS]")
idf.add_argument("--dns", metavar="ADDR",
help="DNS server for a static address (empty: use the gateway)")
idf.add_argument("--scan", action="store_true",
help="List the Wi-Fi networks the device can see")
idf.add_argument("--mode", choices=["espnow", "wifi"],
help="ESP-NOW (the Wi-Fi client stays off) or the Wi-Fi client (ESP-NOW off); "
"applies on restart (-r)")
pat = parser.add_argument_group("ESP-IDF led-driver patterns and presets")
pat.add_argument("--play", metavar="PATTERN",
help="Show PATTERN now without saving it (ESP-IDF: names from -s 'patterns')")
pat.add_argument("--select", metavar="NAME", help="Show the saved preset NAME now")
pat.add_argument("--delete", metavar="NAME", help="Delete the saved preset NAME")
pat.add_argument("--presets-defaults", action="store_true",
help="Add the default presets that are missing")
pat.add_argument("--preset-order", nargs="+", metavar="NAME",
help="Order of the saved presets, by name (names not listed keep their place at the end)")
pat.add_argument("--list-presets", action="store_true", help="Print the saved preset names")
pat.add_argument("--list-patterns", action="store_true", help="Print the pattern names the driver has")
pat.add_argument("--colors", nargs="+", metavar="HEX",
help="Colours for --preset or --play, e.g. #ff0000 #00ff00")
pat.add_argument("--background", metavar="HEX", help="Background colour, e.g. #000000")
pat.add_argument("--delay", type=int, metavar="MS", help="Delay between steps in milliseconds")
pat.add_argument("--preset-brightness", dest="preset_brightness", type=int, metavar="0-255",
help="Brightness of the preset (not the global brightness)")
pat.add_argument("--fade", type=int, metavar="MS", help="Fade time in milliseconds")
pat.add_argument("--reverse", choices=["on", "off"], help="Run the pattern in reverse")
pat.add_argument("--auto", choices=["on", "off"], help="Autorun flag of the preset")
pat.add_argument("--beat-time", dest="beat_time", choices=["on", "off"],
help="Time the pattern to the beat")
try: try:
if len(sys.argv) <= 1:
parser.print_help()
return
args = parser.parse_args() args = parser.parse_args()
ordered_actions = _get_ordered_actions(sys.argv) ordered_actions = _get_ordered_actions(sys.argv)
except ValueError as e: except ValueError as e:
print(f"Error: {e}", file=sys.stderr) print(f"Error: {e}", file=sys.stderr)
sys.exit(1) sys.exit(1)
if args.ota_drivers is not None:
if not args.ota_list and not args.ota_image:
print("Error: --ota-drivers needs --ota-image PATH (the driver firmware, e.g. "
"led-driver/build/led_driver.bin)", file=sys.stderr)
sys.exit(1)
sys.exit(driver_ota.ota_drivers(args.ota_drivers or ["auto"], args.ota_image, args.ota_jobs,
args.ota_list))
port = args.port port = args.port
ran_reset = False ran_reset = False
if args.host:
if args.driver == "mpy":
print("Error: --host is for the ESP-IDF led-driver (Wi-Fi API); MicroPython has no Wi-Fi API here",
file=sys.stderr)
sys.exit(1)
run_idf(args, ordered_actions)
return
use_idf = args.driver == "idf"
serial_free =bool(ordered_actions) and all(a[0] in ("ota", "pause", "flash") for a in ordered_actions)
if args.driver == "auto" and not serial_free:
use_idf = idf_device.probe(port)
if use_idf:
print(f"ESP-IDF led-driver on {port}", file=sys.stderr)
if use_idf:
run_idf(args, ordered_actions)
return
bad = [flag for dest, flag in _IDF_ONLY.items() if getattr(args, dest, None) not in (None, False)]
if bad:
print(f"Error: {', '.join(bad)}: ESP-IDF led-driver only (no ESP-IDF driver answered on {port})",
file=sys.stderr)
sys.exit(1)
# Execute actions in command-line order # Execute actions in command-line order
for action_name, value in ordered_actions: for action_name, value in ordered_actions:
if action_name == 'pause': if action_name == 'pause':
@@ -568,6 +981,15 @@ Examples:
print("Error: esptool not found. Install it with: pip install esptool", file=sys.stderr) print("Error: esptool not found. Install it with: pip install esptool", file=sys.stderr)
sys.exit(1) sys.exit(1)
elif action_name == 'ota':
try:
ota_update(value[0], value[1] if len(value) > 1 else None)
except Exception as e:
print(f"Error: OTA failed: {e}", file=sys.stderr)
sys.exit(1)
if all(a[0] in ('ota', 'pause') for a in ordered_actions):
return # network-only: nothing to download over serial
elif action_name == 'reset': elif action_name == 'reset':
ran_reset = True ran_reset = True
try: try:
@@ -597,14 +1019,8 @@ Examples:
else: else:
print(f"Uploading {upload_dir} to device on {port}...", file=sys.stderr) print(f"Uploading {upload_dir} to device on {port}...", file=sys.stderr)
conn = DeviceConnection(port) conn = DeviceConnection(port)
files_copied, dirs_created, files_skipped = conn.upload_directory( files_copied, dirs_created = conn.upload_directory(upload_dir, remote_dir)
upload_dir, remote_dir, force=args.force_upload print(f"Upload complete: {files_copied} files, {dirs_created} directories created.", file=sys.stderr)
)
print(
f"Upload complete: {files_copied} uploaded, {files_skipped} skipped, "
f"{dirs_created} directories created.",
file=sys.stderr,
)
except Exception as e: except Exception as e:
print(f"Error uploading directory: {e}", file=sys.stderr) print(f"Error uploading directory: {e}", file=sys.stderr)
sys.exit(1) sys.exit(1)
@@ -624,7 +1040,7 @@ Examples:
src_entry = os.path.join(src_dir, entry) src_entry = os.path.join(src_dir, entry)
dst_entry = os.path.join(temp_src, entry) dst_entry = os.path.join(temp_src, entry)
if os.path.isdir(src_entry): if os.path.isdir(src_entry):
shutil.copytree(src_entry, dst_entry) shutil.copytree(src_entry, dst_entry, ignore=shutil.ignore_patterns('__pycache__', '*.pyc', '*.pyo'))
else: else:
shutil.copy2(src_entry, dst_entry) shutil.copy2(src_entry, dst_entry)
print( print(
@@ -632,12 +1048,9 @@ Examples:
file=sys.stderr, file=sys.stderr,
) )
conn = DeviceConnection(port) conn = DeviceConnection(port)
files_copied, dirs_created, files_skipped = conn.upload_directory( files_copied, dirs_created = conn.upload_directory(temp_src, "")
temp_src, "", force=args.force_upload
)
print( print(
f"Upload complete: {files_copied} uploaded, {files_skipped} skipped, " f"Upload complete: {files_copied} files, {dirs_created} directories created.",
f"{dirs_created} directories created.",
file=sys.stderr, file=sys.stderr,
) )
except Exception as e: except Exception as e:
@@ -658,12 +1071,14 @@ Examples:
elif action_name == 'erase_all': elif action_name == 'erase_all':
try: try:
print(f"Erasing device filesystem on {port}...", file=sys.stderr) print(f"Erasing all code on device {port}...", file=sys.stderr)
conn = DeviceConnection(port) conn = DeviceConnection(port)
items = conn.list_files('') items = conn.list_files('')
for name, is_dir, size in items: for name, is_dir, size in items:
if name == "settings.json":
continue
conn.delete(name) conn.delete(name)
print("Erase complete (device root is empty).", file=sys.stderr) print("Erase complete.", file=sys.stderr)
except Exception as e: except Exception as e:
print(f"Error erasing device: {e}", file=sys.stderr) print(f"Error erasing device: {e}", file=sys.stderr)
sys.exit(1) sys.exit(1)
@@ -760,42 +1175,32 @@ Examples:
# Clamp into single-byte range; store as int in settings.json # Clamp into single-byte range; store as int in settings.json
edits["id"] = max(0, min(255, args.device_id)) edits["id"] = max(0, min(255, args.device_id))
settings_work = args.show or bool(edits) # 1. Download: get current settings from device
if settings_work:
try: try:
print(f"Downloading settings from {args.port}...", file=sys.stderr) print(f"Downloading settings from {args.port}...", file=sys.stderr)
settings = download_settings(args.port) settings = download_settings(args.port)
print("Settings downloaded successfully.", file=sys.stderr) print("Settings downloaded successfully.", file=sys.stderr)
except Exception as e: except Exception as e:
if "timeout" in str(e).lower() or "connection" in str(e).lower(): if "timeout" in str(e).lower() or "connection" in str(e).lower():
print( print(f"Error: Connection timeout. Check device connection on {args.port}", file=sys.stderr)
f"Error: Connection timeout. Check device connection on {args.port}",
file=sys.stderr,
)
else: else:
print(f"Error downloading settings: {e}", file=sys.stderr) print(f"Error downloading settings: {e}", file=sys.stderr)
sys.exit(1) sys.exit(1)
# If --show only, print and exit (unless presets or settings are being written)
if args.show: if args.show:
print_settings(settings) print_settings(settings)
if not edits and args.preset is None: if not edits and args.preset is None:
return return
changed_edits: Dict[str, Any] = {} # 2. Edit: apply edits to downloaded settings
for key, value in edits.items(): if edits:
if settings.get(key) != value: print(f"Applying {len(edits)} edit(s)...", file=sys.stderr)
changed_edits[key] = value settings.update(edits)
if edits and not changed_edits:
print("No settings changes detected; skipping settings upload.", file=sys.stderr)
if changed_edits:
print(f"Applying {len(changed_edits)} setting change(s)...", file=sys.stderr)
settings.update(changed_edits)
print_settings(settings) print_settings(settings)
# 3a. Presets file (led-driver presets.json)
if args.preset is not None: if args.preset is not None:
pattern = args.pattern if args.pattern is not None else "on" pattern = args.pattern if args.pattern is not None else "on"
try: try:
@@ -816,62 +1221,23 @@ Examples:
print("Device will reset.", file=sys.stderr) print("Device will reset.", file=sys.stderr)
except Exception as e: except Exception as e:
if "timeout" in str(e).lower() or "connection" in str(e).lower(): if "timeout" in str(e).lower() or "connection" in str(e).lower():
print( print(f"Error: Connection timeout. Check device connection on {args.port}", file=sys.stderr)
f"Error: Connection timeout. Check device connection on {args.port}",
file=sys.stderr,
)
else: else:
print(f"Error uploading presets: {e}", file=sys.stderr) print(f"Error uploading presets: {e}", file=sys.stderr)
sys.exit(1) sys.exit(1)
if changed_edits: # 3b. Settings upload (resets device)
if edits:
try: try:
print(f"\nUploading settings to {args.port}...", file=sys.stderr) print(f"\nUploading settings to {args.port}...", file=sys.stderr)
upload_settings(args.port, settings) upload_settings(args.port, settings)
print("Settings uploaded successfully. Device will reset.", file=sys.stderr) print("Settings uploaded successfully. Device will reset.", file=sys.stderr)
except Exception as e: except Exception as e:
if "timeout" in str(e).lower() or "connection" in str(e).lower(): if "timeout" in str(e).lower() or "connection" in str(e).lower():
print( print(f"Error: Connection timeout. Check device connection on {args.port}", file=sys.stderr)
f"Error: Connection timeout. Check device connection on {args.port}",
file=sys.stderr,
)
else: else:
print(f"Error uploading settings: {e}", file=sys.stderr) print(f"Error uploading settings: {e}", file=sys.stderr)
sys.exit(1) sys.exit(1)
return
if args.preset is not None:
pattern = args.pattern if args.pattern is not None else "on"
try:
print(f"Downloading presets from {args.port}...", file=sys.stderr)
presets_data = download_presets(args.port)
entry = presets_data.get(args.preset)
if not isinstance(entry, dict):
entry = {}
entry["p"] = pattern
presets_data[args.preset] = entry
print(
f"Writing preset {args.preset!r} (pattern={pattern}) to {PRESETS_REMOTE}...",
file=sys.stderr,
)
upload_presets(args.port, presets_data, reset=True)
print("Presets uploaded successfully.", file=sys.stderr)
print("Device will reset.", file=sys.stderr)
except Exception as e:
if "timeout" in str(e).lower() or "connection" in str(e).lower():
print(
f"Error: Connection timeout. Check device connection on {args.port}",
file=sys.stderr,
)
else:
print(f"Error uploading presets: {e}", file=sys.stderr)
sys.exit(1)
return
if ordered_actions:
return
parser.print_help()
if __name__ == "__main__": if __name__ == "__main__":
-45
View File
@@ -1,45 +0,0 @@
"""
Host-side helpers for file_hashes.json (same format as led-driver/src/file_hashes.py).
"""
import hashlib
import json
import os
MANIFEST_VERSION = 1
MANIFEST_FILENAME = "file_hashes.json"
HASH_ALGO = "sha256"
def normalize_remote_path(remote_file: str) -> str:
"""Device-relative path with forward slashes (no leading slash)."""
return remote_file.replace("\\", "/").lstrip("/")
def sha256_hex_file(path: str) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
def parse_manifest(data: bytes) -> dict:
"""Return path -> hash map from manifest bytes."""
try:
doc = json.loads(data.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError):
return {}
if not isinstance(doc, dict):
return {}
files = doc.get("files")
return dict(files) if isinstance(files, dict) else {}
def build_manifest_bytes(files: dict) -> bytes:
doc = {
"version": MANIFEST_VERSION,
"algorithm": HASH_ALGO,
"files": files,
}
return json.dumps(doc, separators=(",", ":")).encode("utf-8")
+12 -57
View File
@@ -10,14 +10,6 @@ import os
import time import time
import serial import serial
from deploy_manifest import (
MANIFEST_FILENAME,
build_manifest_bytes,
normalize_remote_path,
parse_manifest,
sha256_hex_file,
)
# Add lib directory to path - handle both normal execution and PyInstaller bundle # Add lib directory to path - handle both normal execution and PyInstaller bundle
if getattr(sys, 'frozen', False): if getattr(sys, 'frozen', False):
# Running as a PyInstaller bundle # Running as a PyInstaller bundle
@@ -117,47 +109,26 @@ class DeviceConnection:
finally: finally:
self.disconnect() self.disconnect()
def _manifest_remote_path(self) -> str: def upload_directory(self, local_dir, remote_dir=None):
return "/" + MANIFEST_FILENAME
def read_hash_manifest(self) -> dict:
"""Load path -> sha256 hex map from file_hashes.json on the device."""
remote = self._manifest_remote_path()
if not self.transport.fs_exists(remote):
return {}
try:
data = self.transport.fs_readfile(remote)
return parse_manifest(data)
except Exception:
return {}
def write_hash_manifest(self, files: dict) -> None:
"""Write merged file_hashes.json to the device root."""
self._fs_writefile_with_wdt(
self._manifest_remote_path(),
build_manifest_bytes(files),
)
def upload_directory(self, local_dir, remote_dir=None, *, force: bool = False):
""" """
Upload a directory recursively to the device. Upload a directory recursively to the device.
Skips files whose sha256 matches file_hashes.json on the device unless
force is True. Updates the manifest after upload.
Args: Args:
local_dir: Local directory path to upload local_dir: Local directory path to upload
remote_dir: Remote directory path (default: root, uses basename of local_dir) remote_dir: Remote directory path (default: root, uses basename of local_dir)
force: Upload every file even when the manifest hash matches
Returns:
(files_copied, dirs_created, files_skipped)
""" """
import os import os
if not os.path.isdir(local_dir): if not os.path.isdir(local_dir):
raise ValueError(f"{local_dir} is not a directory") raise ValueError(f"{local_dir} is not a directory")
# Host bytecode must never reach the device: remove it before uploading.
import shutil
for root, dirs, _files in os.walk(local_dir):
for d in [d for d in dirs if d == "__pycache__"]:
shutil.rmtree(os.path.join(root, d), ignore_errors=True)
dirs.remove(d)
self.connect() self.connect()
try: try:
# Determine remote directory name # Determine remote directory name
@@ -165,19 +136,15 @@ class DeviceConnection:
remote_dir = os.path.basename(os.path.abspath(local_dir)) remote_dir = os.path.basename(os.path.abspath(local_dir))
# Ensure remote directory exists # Ensure remote directory exists
if remote_dir and not self.transport.fs_exists(remote_dir): if not self.transport.fs_exists(remote_dir):
self.transport.fs_mkdir(remote_dir) self.transport.fs_mkdir(remote_dir)
manifest = {} if force else self.read_hash_manifest()
# Walk through local directory and copy files # Walk through local directory and copy files
files_copied = 0 files_copied = 0
files_skipped = 0
dirs_created = 0 dirs_created = 0
for root, dirs, files in os.walk(local_dir): for root, dirs, files in os.walk(local_dir):
# Never upload Python bytecode trees (MicroPython does not use them). # Calculate relative path from local_dir
dirs[:] = [d for d in dirs if d != "__pycache__"]
rel_path = os.path.relpath(root, local_dir) rel_path = os.path.relpath(root, local_dir)
# Build remote path # Build remote path
@@ -196,12 +163,10 @@ class DeviceConnection:
self.transport.fs_mkdir(remote_base) self.transport.fs_mkdir(remote_base)
dirs_created += 1 dirs_created += 1
# Copy files (skip bytecode; __pycache__ dirs are pruned above) # Copy files
for file in files: for file in files:
if file.endswith((".pyc", ".pyo")): if file.endswith((".pyc", ".pyo")):
continue continue
if file == MANIFEST_FILENAME:
continue
local_file = os.path.join(root, file) local_file = os.path.join(root, file)
# Handle root directory case properly # Handle root directory case properly
if remote_base == '/': if remote_base == '/':
@@ -209,23 +174,13 @@ class DeviceConnection:
else: else:
remote_file = '/'.join([remote_base, file]) remote_file = '/'.join([remote_base, file])
manifest_key = normalize_remote_path(remote_file)
local_hash = sha256_hex_file(local_file)
if not force and manifest.get(manifest_key) == local_hash:
print(f"Skipping (unchanged): {remote_file}", file=sys.stderr)
files_skipped += 1
continue
print(f"Uploading: {remote_file}", file=sys.stderr) print(f"Uploading: {remote_file}", file=sys.stderr)
with open(local_file, 'rb') as f: with open(local_file, 'rb') as f:
data = f.read() data = f.read()
self._fs_writefile_with_wdt(remote_file, data) self._fs_writefile_with_wdt(remote_file, data)
manifest[manifest_key] = local_hash
files_copied += 1 files_copied += 1
self.write_hash_manifest(manifest) return files_copied, dirs_created
return files_copied, dirs_created, files_skipped
finally: finally:
self.disconnect() self.disconnect()
+148
View File
@@ -0,0 +1,148 @@
"""
Find every LED driver on a Wi-Fi network or address range, and update them in parallel.
A driver answers GET /ota with its partition and build info, so discovery is a parallel probe
of each address in the targets. Each driver found then gets the same image, `jobs` at a time.
Uses ota.py for the per-device upload.
Targets (one or more, comma-separated or as separate arguments):
auto this machine's /24
192.168.4 a /24 (same as 192.168.4.0/24)
192.168.4.0/24 a CIDR network
192.168.4.10-192.168.4.40 an inclusive range
192.168.4.10-40 the same, short form
192.168.4.25 one address
"""
import concurrent.futures as cf
import ipaddress
import os
import socket
import sys
from typing import List, Optional, Tuple
from ota import _info, ota_update
# Largest number of addresses one run will probe, so a typo like 10.0.0.0/8 is refused
MAX_TARGETS = 4096
def local_subnet() -> str:
"""First three octets of the address this machine uses to reach the network."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("192.0.2.1", 9)) # UDP connect sends no packet
ip = s.getsockname()[0]
finally:
s.close()
return ".".join(ip.split(".")[:3])
def _ip(text: str) -> ipaddress.IPv4Address:
try:
return ipaddress.IPv4Address(text.strip())
except ValueError:
raise ValueError(f"not an IPv4 address: {text}") from None
def _expand(part: str) -> List[ipaddress.IPv4Address]:
"""One target (see the module docstring) -> the addresses it covers."""
if part == "auto":
part = local_subnet()
if "/" in part:
try:
net = ipaddress.IPv4Network(part, strict=False)
except ValueError:
raise ValueError(f"not a network: {part}") from None
if net.num_addresses > MAX_TARGETS:
raise ValueError(f"network too large (max {MAX_TARGETS} addresses): {part}")
return list(net.hosts()) if net.num_addresses > 2 else list(net)
if "-" in part:
first, last = part.split("-", 1)
start = _ip(first)
end = _ip(last) if last.count(".") == 3 else _ip(".".join(first.split(".")[:3] + [last]))
if int(end) < int(start):
raise ValueError(f"range ends before it starts: {part}")
if int(end) - int(start) >= MAX_TARGETS:
raise ValueError(f"range too large (max {MAX_TARGETS} addresses): {part}")
return [ipaddress.IPv4Address(i) for i in range(int(start), int(end) + 1)]
if part.count(".") == 2:
# Three octets: the whole /24, as before
return list(ipaddress.IPv4Network(part + ".0/24").hosts())
return [_ip(part)]
def parse_targets(specs: List[str]) -> List[str]:
"""All addresses named by the targets, in order, without duplicates."""
seen = set()
out: List[str] = []
for spec in specs:
for part in spec.split(","):
part = part.strip()
if not part:
continue
for addr in _expand(part):
if addr not in seen:
seen.add(addr)
out.append(str(addr))
if len(out) > MAX_TARGETS:
raise ValueError(f"too many addresses ({len(out)}; max {MAX_TARGETS}). Narrow the targets.")
return out
def discover(hosts: List[str], port: int = 80, workers: int = 64) -> List[Tuple[str, dict]]:
"""Probe each host for a driver. Returns (host, info) sorted by address."""
found = []
with cf.ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(_info, h, port): h for h in hosts}
for fut in cf.as_completed(futures):
info = fut.result()
if info:
found.append((futures[fut], info))
return sorted(found, key=lambda t: int(ipaddress.IPv4Address(t[0])))
def ota_drivers(specs: List[str], image: Optional[str], jobs: int, list_only: bool,
port: int = 80) -> int:
"""Discover drivers in the targets and update them. Returns a process exit code."""
if not list_only:
if not image or not os.path.isfile(image):
print(f"Error: image not found: {image}", file=sys.stderr)
return 1
try:
hosts = parse_targets(specs or ["auto"])
except ValueError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
if not hosts:
print("Error: no addresses to scan", file=sys.stderr)
return 1
print(f"Scanning {len(hosts)} address(es) on port {port}: {hosts[0]} .. {hosts[-1]}", file=sys.stderr)
drivers = discover(hosts, port)
if not drivers:
print("No drivers found.", file=sys.stderr)
return 1
print(f"Found {len(drivers)} driver(s):", file=sys.stderr)
for host, info in drivers:
print(f" {host:<16} {info.get('partition', '?'):<8} built {info.get('built', '?')}", file=sys.stderr)
if list_only:
return 0
print(f"\nUpdating {len(drivers)} driver(s) with {image}, {jobs} at a time...", file=sys.stderr)
failed = []
with cf.ThreadPoolExecutor(max_workers=jobs) as pool:
futures = {pool.submit(ota_update, h, image, port): h for h, _ in drivers}
for fut in cf.as_completed(futures):
host = futures[fut]
try:
fut.result()
print(f"OK {host}", file=sys.stderr)
except Exception as e:
failed.append(host)
print(f"FAILED {host}: {e}", file=sys.stderr)
ok = len(drivers) - len(failed)
print(f"\n{ok} updated, {len(failed)} failed" + (f": {' '.join(failed)}" if failed else ""), file=sys.stderr)
return 1 if failed else 0
-25
View File
@@ -1,25 +0,0 @@
"""Host serial port list filtering for led-tool /ports API."""
import re
# Exclude /dev/ttyS2 and higher (keep ttyS0, ttyS1; keep ttyACM*, ttyUSB*, etc.)
_TTYS_HIGH = re.compile(r"^/dev/ttyS([2-9]|[1-9]\d+)$")
def include_host_serial_device(device: str) -> bool:
return not _TTYS_HIGH.match(device or "")
def _is_na(value: str) -> bool:
return (value or "").strip().lower() in ("n/a", "na")
def include_host_serial_port(port: dict) -> bool:
if not include_host_serial_device(port.get("device", "")):
return False
if _is_na(port.get("description")) or _is_na(port.get("hwid")):
return False
return True
def filter_port_dicts(ports: list) -> list:
return [p for p in ports if include_host_serial_port(p)]
+82
View File
@@ -0,0 +1,82 @@
"""
Wi-Fi connection to the ESP-IDF led-driver.
The driver serves the same JSON API over HTTP on its address (led-driver main/web.cpp) that it
serves over USB (main/usb_cfg.cpp). HttpDevice has the same get/post/call interface as
idf_device.IdfDevice, so the settings code in cli.py works for both transports.
Not available over Wi-Fi: reboot (no HTTP route) and following the serial log.
"""
import http.client
import json
import socket
from typing import Any, Optional, Tuple
from idf_device import IdfError
class HttpDevice:
def __init__(self, host: str, port: int = 80, timeout: float = 5.0):
self.host = host
self.port = port
self.timeout = timeout
def open(self) -> "HttpDevice":
return self
def close(self) -> None:
pass
def __enter__(self) -> "HttpDevice":
return self
def __exit__(self, *exc) -> None:
pass
def call_raw(self, method: str, path: str, body: Any = None, host: Optional[str] = None,
timeout: Optional[float] = None) -> Tuple[int, Any]:
"""Send one request; return (status, parsed body). Does not raise on an error status."""
if host is not None:
raise IdfError(0, "relay through the driver is USB-only; use --port for that")
conn = http.client.HTTPConnection(self.host, self.port, timeout=timeout or self.timeout)
headers = {}
data = None
if body is not None:
data = json.dumps(body, separators=(",", ":")).encode()
headers["Content-Type"] = "application/json"
try:
conn.request(method, path, body=data, headers=headers)
r = conn.getresponse()
text = r.read().decode("utf-8", "replace")
except socket.timeout as e:
raise TimeoutError(f"no reply from {self.host} to {method} {path}") from e
except OSError as e:
raise TimeoutError(f"cannot reach {self.host}: {e}") from e
finally:
conn.close()
try:
parsed = json.loads(text) if text else {}
except ValueError:
parsed = text
return r.status, parsed
def call(self, method: str, path: str, body: Any = None, **kw) -> Any:
"""Send one request; return the parsed body. Raises IdfError on status >= 400."""
status, parsed = self.call_raw(method, path, body, **kw)
if status >= 400:
msg = parsed.get("error") if isinstance(parsed, dict) else None
raise IdfError(status, msg or str(parsed))
return parsed
def get(self, path: str, **kw) -> Any:
return self.call("GET", path, **kw)
def post(self, path: str, body: Any, **kw) -> Any:
return self.call("POST", path, body, **kw)
def reboot(self) -> None:
raise IdfError(0, "reboot is not available over Wi-Fi; use -r with --port (USB)")
def follow(self, seconds: Optional[float] = None) -> None:
raise IdfError(0, "following the log is not available over Wi-Fi; use -f with --port (USB)")
+172
View File
@@ -0,0 +1,172 @@
"""
USB connection to the ESP-IDF led-driver (ESP32-C3).
The driver serves its JSON API on the USB serial port (led-driver main/usb_cfg.cpp):
@api {"id": n, "method": "GET" or "POST", "path": "/api/...", "body": {...}}
-> @api {"id": n, "status": 200, "body": "<JSON text>"}
@reboot -> @ok, then the device restarts
Every other line on the port is log output.
"""
import json
import sys
import time
from typing import Any, Dict, Optional, Tuple
import serial
API = "@api "
class IdfError(RuntimeError):
"""The device answered with an error status."""
def __init__(self, status: int, message: str):
super().__init__(f"{status}: {message}")
self.status = status
self.message = message
class IdfDevice:
def __init__(self, port: str, verbose: bool = False):
self.port = port
self.verbose = verbose
self._id = 0
self._ser: Optional[serial.Serial] = None
def open(self) -> "IdfDevice":
if self._ser is None:
ser = serial.Serial()
ser.port = self.port
ser.baudrate = 115200
ser.timeout = 0.1
# On the C3's USB-Serial-JTAG, RTS high with DTR low resets the chip. Linux raises both
# on open and pyserial then sets DTR before RTS, so DTR must stay high (DTR low first
# would pass through RTS high, DTR low and reset it). RTS low keeps it running.
ser.dtr = True
ser.rts = False
ser.open()
self._ser = ser
return self
def close(self) -> None:
if self._ser is not None:
self._ser.close()
self._ser = None
def __enter__(self) -> "IdfDevice":
return self.open()
def __exit__(self, *exc) -> None:
self.close()
def _log(self, line: str) -> None:
if self.verbose and line:
print(f"[device] {line}", file=sys.stderr)
def _readline(self, deadline: float) -> Optional[str]:
"""One line from the device, or None at the deadline."""
buf = b""
while time.monotonic() < deadline:
chunk = self._ser.readline()
if not chunk:
continue
buf += chunk
if buf.endswith(b"\n"):
return buf.decode("utf-8", "replace").rstrip("\r\n")
return None
def call_raw(self, method: str, path: str, body: Any = None, host: Optional[str] = None,
timeout: float = 3.0) -> Tuple[int, Any]:
"""Send one request; return (status, parsed body). Does not raise on an error status."""
self.open()
self._id += 1
msg: Dict[str, Any] = {"id": self._id, "method": method, "path": path}
if body is not None:
msg["body"] = body
if host:
msg["host"] = host
self._ser.reset_input_buffer()
self._ser.write(("\n" + API + json.dumps(msg, separators=(",", ":")) + "\n").encode())
self._ser.flush()
deadline = time.monotonic() + timeout
while True:
line = self._readline(deadline)
if line is None:
raise TimeoutError(f"no reply from {self.port} to {method} {path}")
at = line.find(API + "{")
if at < 0:
self._log(line)
continue
if at > 0:
self._log(line[:at])
try:
env = json.loads(line[at + len(API):])
except ValueError:
continue
if env.get("id") != self._id:
continue
text = env.get("body", "")
try:
parsed = json.loads(text) if text else {}
except ValueError:
parsed = text
return int(env.get("status", 0)), parsed
def call(self, method: str, path: str, body: Any = None, **kw) -> Any:
"""Send one request; return the parsed body. Raises IdfError on status >= 400."""
status, parsed = self.call_raw(method, path, body, **kw)
if status >= 400:
msg = parsed.get("error") if isinstance(parsed, dict) else None
raise IdfError(status, msg or str(parsed))
return parsed
def get(self, path: str, **kw) -> Any:
return self.call("GET", path, **kw)
def post(self, path: str, body: Any, **kw) -> Any:
return self.call("POST", path, body, **kw)
def reboot(self) -> None:
"""Restart the device: the @reboot command, or an RTS reset pulse if it doesn't answer."""
self.open()
self._ser.reset_input_buffer()
self._ser.write(b"\n@reboot\n")
self._ser.flush()
deadline = time.monotonic() + 1.5
while True:
line = self._readline(deadline)
if line is None:
break
if line.strip() == "@ok":
return
self._log(line)
# Hardware reset: RTS high with DTR low holds the chip in reset (DTR low alone would
# mean "boot mode" at release, so RTS goes low first)
self._ser.rts = True
self._ser.dtr = False
time.sleep(0.1)
self._ser.rts = False
self._ser.dtr = True
def follow(self, seconds: Optional[float] = None) -> None:
"""Print the device's output until Ctrl+C, or for SECONDS."""
self.open()
end = time.monotonic() + seconds if seconds is not None else None
while end is None or time.monotonic() < end:
chunk = self._ser.read(256)
if chunk:
sys.stdout.write(chunk.decode("utf-8", "replace"))
sys.stdout.flush()
def probe(port: str, timeout: float = 1.0) -> bool:
"""True if an ESP-IDF led-driver answers the USB API on PORT."""
try:
with IdfDevice(port) as dev:
dev.call_raw("GET", "/api/status", timeout=timeout)
return True
except (TimeoutError, serial.SerialException, OSError):
return False
+77
View File
@@ -0,0 +1,77 @@
"""
Over-the-air firmware update for the v2 ESP32-S3 controller (Ethernet, plain HTTP).
The controller takes the raw app image on POST /ota, writes it to the idle slot and reboots.
"""
import http.client
import json
import os
import time
from typing import Optional
IMAGE_NAME = "led_controller_v2.bin"
# Searched in order when no image is given (relative to where the tool is run, since the
# PyInstaller binary has no useful location of its own)
DEFAULT_IMAGES = [
os.path.join("v2", "build", IMAGE_NAME),
os.path.join("build", IMAGE_NAME),
os.path.join("..", "v2", "build", IMAGE_NAME),
]
def _default_image() -> Optional[str]:
return next((p for p in DEFAULT_IMAGES if os.path.isfile(p)), None)
def _info(host: str, port: int) -> Optional[dict]:
try:
conn = http.client.HTTPConnection(host, port, timeout=5)
conn.request("GET", "/ota")
r = conn.getresponse()
return json.loads(r.read().decode()) if r.status == 200 else None
except (OSError, ValueError):
return None
def ota_update(host: str, image: Optional[str] = None, port: int = 80) -> None:
"""Upload image to host and wait for it to come back. Raises RuntimeError on failure."""
image = image or _default_image()
if not image:
raise RuntimeError(f"no image given and {IMAGE_NAME} not found under ./v2/build, ./build or ../v2/build")
if not os.path.isfile(image):
raise RuntimeError(f"image not found: {image}")
size = os.path.getsize(image)
before = _info(host, port)
if before is None:
raise RuntimeError(f"no OTA endpoint at http://{host}:{port}/ota (is this an LED device?)")
print(f"Running {before['partition']} (built {before['built']})")
print(f"Uploading {image} ({size} bytes)...")
conn = http.client.HTTPConnection(host, port, timeout=60)
with open(image, "rb") as f:
conn.request("POST", "/ota", body=f, headers={
"Content-Length": str(size),
"Content-Type": "application/octet-stream",
})
r = conn.getresponse()
body = r.read().decode()
if r.status != 200:
try:
body = json.loads(body).get("error", body)
except ValueError:
pass
raise RuntimeError(f"update rejected ({r.status}): {body}")
print("Written, waiting for reboot...")
time.sleep(3)
for _ in range(30):
after = _info(host, port)
if after:
print(f"Back up on {after['partition']} (built {after['built']})")
if after["partition"] == before["partition"]:
raise RuntimeError("controller came back on the same slot: new image was rejected or rolled back")
return
time.sleep(1)
raise RuntimeError("controller did not come back within 30 s")
-209
View File
@@ -1,209 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>LED device settings</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
:root {
color-scheme: dark;
--text: #e5e7eb;
--muted: #9ca3af;
--border: #374151;
--accent: #3b82f6;
--danger: #f87171;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: system-ui, sans-serif;
background: #0b1020;
color: var(--text);
padding: 1rem;
}
h1 { font-size: 1.15rem; margin: 0 0 0.35rem; }
.muted { color: var(--muted); font-size: 0.9rem; margin-bottom: 1rem; }
.card {
border: 1px solid var(--border);
border-radius: 8px;
padding: 1rem;
margin-bottom: 1rem;
background: #111827;
}
label { display: block; font-size: 0.85rem; margin-bottom: 0.25rem; color: var(--muted); }
input, select, textarea {
width: 100%;
padding: 0.5rem;
border-radius: 4px;
border: 1px solid var(--border);
background: #1f2937;
color: var(--text);
margin-bottom: 0.65rem;
}
.row { display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: flex-end; }
.row > * { flex: 1; min-width: 10rem; }
.btn {
padding: 0.45rem 0.85rem;
border: none;
border-radius: 4px;
cursor: pointer;
background: #4b5563;
color: #fff;
font-size: 0.9rem;
}
.btn-primary { background: var(--accent); }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr));
gap: 0 0.5rem;
}
#status { font-size: 0.85rem; margin-top: 0.5rem; }
#status.error { color: var(--danger); }
.flash {
display: none;
padding: 0.5rem 0.75rem;
border-radius: 4px;
margin-bottom: 0.75rem;
background: #14532d;
color: #86efac;
}
.flash.error { background: #5e1b1b; color: #fca5a5; }
.flash.show { display: block; }
[hidden] { display: none !important; }
</style>
</head>
<body data-api-base="/led-tool">
<h1>Device settings (USB)</h1>
<p class="muted">Edit <code>settings.json</code> via <strong>Web Serial</strong> (USB on this computer) or <strong>host serial</strong> (Pi running <code>led-cli</code>). Use <strong>Connect</strong> for your transport, then <strong>Download</strong> or <strong>Upload</strong>.</p>
<div id="flash" class="flash"></div>
<div class="card" id="webserial-wrap" hidden>
<h2 style="font-size:1rem;margin:0 0 0.5rem;">Web Serial</h2>
<div class="row">
<button type="button" class="btn btn-primary" id="webserial-connect">Connect USB</button>
<button type="button" class="btn" id="webserial-disconnect" hidden>Disconnect</button>
</div>
</div>
<div class="card" id="host-serial-wrap">
<h2 style="font-size:1rem;margin:0 0 0.5rem;">Host serial</h2>
<label for="host-port">Port</label>
<select id="host-port"><option value="">Select port</option></select>
<div class="row">
<button type="button" class="btn btn-primary" id="host-connect">Connect</button>
<button type="button" class="btn" id="host-disconnect" hidden>Disconnect</button>
<button type="button" class="btn" id="btn-refresh-ports">Refresh ports</button>
</div>
</div>
<div class="card">
<div class="row" style="margin-bottom:0.75rem;">
<button type="button" class="btn btn-primary" id="btn-download">Download</button>
<button type="button" class="btn btn-primary" id="btn-upload">Upload &amp; reset</button>
<button type="button" class="btn" id="btn-from-json">JSON → form</button>
<button type="button" class="btn" id="btn-to-json">Form → JSON</button>
</div>
<p id="status">Ready</p>
<div class="grid">
<div>
<label for="name">Name</label>
<input id="name" data-setting="name" type="text" />
</div>
<div>
<label for="num_leds">Num LEDs</label>
<input id="num_leds" data-setting="num_leds" type="number" min="1" />
</div>
<div>
<label for="led_pin">LED pin</label>
<input id="led_pin" data-setting="led_pin" type="number" min="0" />
</div>
<div>
<label for="brightness">Brightness</label>
<input id="brightness" data-setting="brightness" type="number" min="0" max="255" />
</div>
<div>
<label for="color_order">Colour order</label>
<select id="color_order" data-setting="color_order">
<option value=""></option>
<option value="rgb">rgb</option>
<option value="rbg">rbg</option>
<option value="grb">grb</option>
<option value="gbr">gbr</option>
<option value="brg">brg</option>
<option value="bgr">bgr</option>
</select>
</div>
<div>
<label for="transport_type">Transport</label>
<select id="transport_type" data-setting="transport_type">
<option value=""></option>
<option value="espnow">espnow</option>
<option value="wifi">wifi</option>
</select>
</div>
<div>
<label for="ssid">WiFi SSID</label>
<input id="ssid" data-setting="ssid" type="text" />
</div>
<div>
<label for="password">WiFi password</label>
<input id="password" data-setting="password" type="password" />
</div>
<div>
<label for="wifi_channel">WiFi channel</label>
<input id="wifi_channel" data-setting="wifi_channel" type="number" min="1" max="11" />
</div>
<div>
<label for="default">Default preset</label>
<input id="default" data-setting="default" type="text" />
</div>
<div>
<label for="id">Device id (ESP-NOW)</label>
<input id="id" data-setting="id" type="number" min="0" max="255" />
</div>
<div>
<label for="debug">Debug</label>
<select id="debug" data-setting="debug">
<option value=""></option>
<option value="False">False</option>
<option value="True">True</option>
</select>
</div>
</div>
</div>
<div class="card">
<label for="raw_json">Raw settings.json</label>
<textarea id="raw_json" rows="14" spellcheck="false">{}</textarea>
</div>
<script>
(function () {
const api =
document.body.getAttribute('data-api-base') ??
(location.pathname.includes('/led-tool') ? '/led-tool' : '');
const prefix = api + '/static';
function loadScript(url) {
return new Promise((resolve, reject) => {
const s = document.createElement('script');
s.src = url;
s.onload = () => resolve();
s.onerror = () => reject(new Error('Failed to load ' + url));
document.body.appendChild(s);
});
}
loadScript(prefix + '/web_serial.js')
.then(() => loadScript(prefix + '/settings_editor.js'))
.catch((e) => {
const el = document.getElementById('flash');
if (el) {
el.textContent = e.message;
el.className = 'flash error show';
}
});
})();
</script>
</body>
</html>
-380
View File
@@ -1,380 +0,0 @@
(function () {
const LOG = '[led-tool/editor]';
const log = (...args) => console.log(LOG, ...args);
const apiBase =
(document.body && document.body.dataset.apiBase) ||
(window.location.pathname.includes('/led-tool') ? '/led-tool' : '');
const statusEl = document.getElementById('status');
const messageEl = document.getElementById('flash');
const portSelect = document.getElementById('host-port');
const rawJson = document.getElementById('raw_json');
const hostWrap = document.getElementById('host-serial-wrap');
const webWrap = document.getElementById('webserial-wrap');
const connectBtn = document.getElementById('webserial-connect');
const disconnectBtn = document.getElementById('webserial-disconnect');
const hostConnectBtn = document.getElementById('host-connect');
const hostDisconnectBtn = document.getElementById('host-disconnect');
const refreshPortsBtn = document.getElementById('btn-refresh-ports');
const DEFAULT_HOST_PORT = '/dev/ttyACM0';
let webClient = null;
let webPort = null;
let hostConnected = false;
let hostConnectedPort = '';
let transferBusy = false;
const webSerialOk = window.LedToolWebSerial && window.LedToolWebSerial.supported();
function setStatus(text, isError) {
if (!statusEl) return;
statusEl.textContent = text;
statusEl.classList.toggle('error', Boolean(isError));
}
function flash(text, isError) {
if (!messageEl) return;
messageEl.textContent = text;
messageEl.className = isError ? 'flash error show' : 'flash show';
setTimeout(() => messageEl.classList.remove('show'), 5000);
}
function formToObject() {
const out = {};
document.querySelectorAll('[data-setting]').forEach((el) => {
const key = el.getAttribute('data-setting');
if (!key) return;
const raw = (el.value || '').trim();
if (raw === '') return;
if (el.type === 'number') {
const n = parseInt(raw, 10);
if (!Number.isNaN(n)) out[key] = n;
} else if (el.tagName === 'SELECT' && el.id === 'debug') {
out[key] = raw === 'True';
} else {
out[key] = raw;
}
});
return out;
}
function objectToForm(settings) {
if (!settings || typeof settings !== 'object') return;
document.querySelectorAll('[data-setting]').forEach((el) => {
const key = el.getAttribute('data-setting');
if (!key || !Object.prototype.hasOwnProperty.call(settings, key)) return;
const v = settings[key];
if (el.id === 'debug') {
el.value = v === true || v === 'True' ? 'True' : 'False';
} else {
el.value = v === undefined || v === null ? '' : String(v);
}
});
if (rawJson) rawJson.value = JSON.stringify(settings, null, 2);
}
function usingWebSerial() {
return webClient && webClient.connected;
}
function usingHostSerial() {
return hostConnected && Boolean(hostConnectedPort);
}
function updateUi() {
const webOpen = usingWebSerial();
const hostOpen = usingHostSerial();
if (webWrap) webWrap.hidden = !webSerialOk || hostOpen;
if (connectBtn) connectBtn.hidden = webOpen || hostOpen || !webSerialOk;
if (disconnectBtn) disconnectBtn.hidden = !webOpen;
if (hostWrap) hostWrap.hidden = webOpen;
const hostFieldsLocked = webOpen || hostOpen;
if (portSelect) portSelect.disabled = hostFieldsLocked;
if (refreshPortsBtn) refreshPortsBtn.disabled = hostFieldsLocked;
if (hostConnectBtn) hostConnectBtn.hidden = hostOpen || webOpen;
if (hostDisconnectBtn) hostDisconnectBtn.hidden = !hostOpen || webOpen;
if (webOpen) {
setStatus('USB open (device not reset until Download/Upload).');
} else if (hostOpen) {
setStatus(`Host serial: ${hostConnectedPort} (use Download or Upload).`);
} else if (webSerialOk) {
setStatus('Connect host serial or Web Serial USB, then Download or Upload.');
} else {
setStatus(`Connect host serial (default ${DEFAULT_HOST_PORT}).`);
}
}
async function loadHostPorts() {
if (!portSelect) return;
try {
const res = await fetch(`${apiBase}/ports`);
const data = await res.json();
const prev = portSelect.value;
portSelect.innerHTML = '<option value="">Select port</option>';
for (const p of data.ports || []) {
const opt = document.createElement('option');
opt.value = p.device;
opt.textContent = `${p.device} - ${p.description || 'device'}`;
portSelect.appendChild(opt);
}
const acm0 = DEFAULT_HOST_PORT;
const hasAcm0 = [...portSelect.options].some((o) => o.value === acm0);
if (hasAcm0) {
portSelect.value = acm0;
} else if (prev && [...portSelect.options].some((o) => o.value === prev)) {
portSelect.value = prev;
}
} catch (e) {
flash(`Could not list host ports: ${e.message}`, true);
}
}
function selectedHostPort() {
return portSelect && portSelect.value ? portSelect.value.trim() : '';
}
function hostPort() {
if (hostConnected && hostConnectedPort) return hostConnectedPort;
return selectedHostPort();
}
function connectHostSerial() {
if (usingWebSerial()) {
disconnectWebSerial();
}
const port = selectedHostPort();
if (!port) {
flash('Select a host serial port.', true);
return;
}
hostConnectedPort = port;
hostConnected = true;
log('connectHostSerial', port);
updateUi();
flash(`Host serial ready: ${port}`, false);
}
function disconnectHostSerial() {
hostConnected = false;
hostConnectedPort = '';
updateUi();
}
async function downloadHost() {
const port = hostConnectedPort || hostPort();
if (!port) {
flash('Connect host serial first.', true);
return;
}
log('downloadHost', port);
setStatus('Downloading from device (host serial)...');
const res = await fetch(`${apiBase}/settings?port=${encodeURIComponent(port)}`);
const data = await res.json();
log('downloadHost response', { ok: res.ok, status: res.status, data });
if (!res.ok) {
throw new Error(data.error || 'Download failed');
}
if (!data.settings) {
throw new Error('No settings in response (check CLI output)');
}
objectToForm(data.settings);
flash('Settings downloaded.', false);
setStatus(`Downloaded from ${port}`);
}
async function uploadHost() {
const port = hostConnectedPort || hostPort();
if (!port) {
flash('Connect host serial first.', true);
return;
}
const payload = { port, ...formToObject() };
log('uploadHost', payload);
setStatus('Uploading via host serial (led-cli)...');
const res = await fetch(`${apiBase}/settings`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Upload failed');
if (!data.ok) throw new Error(data.stderr || 'led-cli failed');
flash('Settings uploaded; device resetting.', false);
setStatus('Upload complete.');
}
async function connectWebSerial() {
if (!window.LedToolWebSerial || !window.LedToolWebSerial.supported()) {
flash('Web Serial not supported (use Chrome or Edge over HTTPS or localhost).', true);
return;
}
if (usingHostSerial()) {
disconnectHostSerial();
}
log('connectWebSerial: requestPort');
setStatus('Opening USB port…');
webPort = await window.LedToolWebSerial.requestPort();
log('connectWebSerial: port selected', webPort);
webClient = new window.LedToolWebSerial.MicroPythonRawRepl();
await webClient.connect(webPort);
updateUi();
flash('USB port open. Use Download or Upload to talk to the device.', false);
}
async function disconnectWebSerial() {
if (webClient) {
try {
await webClient.disconnect();
} catch (_) {
/* ignore */
}
}
webClient = null;
webPort = null;
updateUi();
}
async function downloadWebSerial() {
log('downloadWebSerial');
setStatus('Reading settings from device (Web Serial)…');
const settings = await webClient.readSettingsJson();
log('downloadWebSerial result', settings);
objectToForm(settings);
if (rawJson) rawJson.value = JSON.stringify(settings, null, 2);
flash('Settings read over Web Serial.', false);
setStatus('Downloaded via Web Serial.');
}
async function uploadWebSerial() {
log('uploadWebSerial');
let settings = {};
if (rawJson && rawJson.value.trim()) {
try {
settings = JSON.parse(rawJson.value);
} catch (e) {
flash('Invalid JSON in raw panel.', true);
return;
}
} else {
settings = await webClient.readSettingsJson();
Object.assign(settings, formToObject());
}
await webClient.writeSettingsJson(settings);
flash('Uploaded via Web Serial; device resetting.', false);
setStatus('Upload complete.');
await disconnectWebSerial();
}
document.getElementById('btn-download')?.addEventListener('click', async () => {
if (transferBusy) return;
transferBusy = true;
try {
if (usingWebSerial()) {
await downloadWebSerial();
} else if (usingHostSerial()) {
await downloadHost();
} else {
flash(
webSerialOk
? 'Connect host serial or Web Serial USB first.'
: 'Click Connect on host serial first.',
true,
);
}
} catch (e) {
console.error(LOG, 'download failed', e);
if (rawJson) rawJson.value = String(e.message || e);
flash(e.message, true);
setStatus(e.message, true);
} finally {
transferBusy = false;
}
});
document.getElementById('btn-upload')?.addEventListener('click', async () => {
if (transferBusy) return;
transferBusy = true;
try {
if (usingWebSerial()) {
await uploadWebSerial();
} else if (usingHostSerial()) {
await uploadHost();
} else {
flash(
webSerialOk
? 'Connect host serial or Web Serial USB first.'
: 'Click Connect on host serial first.',
true,
);
}
} catch (e) {
console.error(LOG, 'upload failed', e);
flash(e.message, true);
setStatus(e.message, true);
} finally {
transferBusy = false;
}
});
document.getElementById('btn-from-json')?.addEventListener('click', () => {
try {
const parsed = JSON.parse(rawJson.value || '{}');
objectToForm(parsed);
flash('Form updated from JSON.', false);
} catch (e) {
flash('Invalid JSON.', true);
}
});
document.getElementById('btn-to-json')?.addEventListener('click', () => {
const merged = formToObject();
if (rawJson && rawJson.value.trim()) {
try {
Object.assign(merged, JSON.parse(rawJson.value));
} catch (_) {
/* use form only */
}
}
rawJson.value = JSON.stringify(merged, null, 2);
flash('JSON updated from form.', false);
});
connectBtn?.addEventListener('click', () => {
connectWebSerial().catch((e) => {
disconnectWebSerial();
const msg =
e.name === 'NotFoundError'
? 'No USB device selected.'
: e.name === 'SecurityError'
? 'Web Serial blocked (open LED Tool in a top-level tab, or use host serial on the Pi).'
: e.message || String(e);
flash(msg, true);
setStatus(msg, true);
});
});
disconnectBtn?.addEventListener('click', () => {
disconnectWebSerial();
flash('Web Serial disconnected.', false);
});
refreshPortsBtn?.addEventListener('click', () => loadHostPorts());
hostConnectBtn?.addEventListener('click', () => connectHostSerial());
hostDisconnectBtn?.addEventListener('click', () => {
disconnectHostSerial();
flash('Host serial disconnected.', false);
});
window.addEventListener('beforeunload', () => {
if (webClient) {
webClient.disconnect();
}
});
log('settings editor ready', { apiBase, webSerialOk });
updateUi();
loadHostPorts();
})();
-396
View File
@@ -1,396 +0,0 @@
/**
* MicroPython raw REPL over Web Serial (mpremote-compatible).
*/
(function (global) {
const RAW_REPL_BANNER = 'raw REPL; CTRL-B to exit\r\n';
const SOFT_REBOOT = 'soft reboot\r\n';
const LOG = '[led-tool/serial]';
function log(...args) {
console.log(LOG, ...args);
}
function logDebug(...args) {
console.debug(LOG, ...args);
}
function describeBytes(data) {
if (!data || !data.length) return '(empty)';
const u8 = data instanceof Uint8Array ? data : new Uint8Array(data);
if (u8.length <= 64) {
return Array.from(u8)
.map((b) => (b >= 0x20 && b < 0x7f ? String.fromCharCode(b) : `\\x${b.toString(16).padStart(2, '0')}`))
.join('');
}
return `${u8.length} bytes: ${decodeText(u8.slice(0, 80))}…`;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function bytesEndsWith(buf, suffix) {
if (buf.length < suffix.length) return false;
for (let i = 0; i < suffix.length; i += 1) {
if (buf[buf.length - suffix.length + i] !== suffix[i]) return false;
}
return true;
}
function decodeText(u8) {
return new TextDecoder('utf-8', { fatal: false }).decode(u8);
}
function extractJsonObject(text) {
const t = (text || '').trim();
const start = t.indexOf('{');
const end = t.lastIndexOf('}');
if (start === -1 || end === -1 || end < start) {
throw new Error(`No JSON object in device output: ${t.slice(0, 400)}`);
}
return JSON.parse(t.slice(start, end + 1));
}
class MicroPythonRawRepl {
constructor() {
this.port = null;
this.reader = null;
this.writer = null;
this.portOpen = false;
this.inRawRepl = false;
this._rxBuf = [];
this.useRawPaste = true;
this._replLock = null;
}
get connected() {
return Boolean(this.portOpen && this.writer);
}
_appendRx(chunk) {
if (!chunk || !chunk.length) return;
logDebug('rx chunk', chunk.length, describeBytes(chunk));
for (let i = 0; i < chunk.length; i += 1) this._rxBuf.push(chunk[i]);
}
async _readStreamChunk(timeoutMs) {
if (!this.reader) return null;
const result = await Promise.race([
this.reader.read(),
sleep(timeoutMs).then(() => ({ timedOut: true })),
]);
if (result.timedOut) return null;
if (result.done) return null;
return result.value || null;
}
async readUntil(suffixBytes, timeoutMs = 15000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (bytesEndsWith(this._rxBuf, suffixBytes)) {
const matched = Uint8Array.from(this._rxBuf);
this._rxBuf.length = 0;
logDebug('readUntil matched', JSON.stringify(decodeText(suffixBytes)), 'len', matched.length);
return matched;
}
const chunk = await this._readStreamChunk(Math.min(300, Math.max(1, deadline - Date.now())));
if (chunk && chunk.length) {
this._appendRx(chunk);
} else {
await sleep(5);
}
}
const tail = decodeText(Uint8Array.from(this._rxBuf.slice(-240)));
const err = `Timed out waiting for ${JSON.stringify(decodeText(suffixBytes))} (tail: ${JSON.stringify(tail)})`;
log('readUntil timeout', err);
throw new Error(err);
}
async readExact(n, timeoutMs = 10000) {
const deadline = Date.now() + timeoutMs;
while (this._rxBuf.length < n && Date.now() < deadline) {
const chunk = await this._readStreamChunk(Math.min(300, Math.max(1, deadline - Date.now())));
if (chunk && chunk.length) this._appendRx(chunk);
else await sleep(5);
}
if (this._rxBuf.length < n) {
throw new Error(`Expected ${n} bytes, got ${this._rxBuf.length}`);
}
return Uint8Array.from(this._rxBuf.splice(0, n));
}
async connect(serialPort) {
log('connect: opening port');
await this.disconnect();
this.port = serialPort;
this._rxBuf = [];
await this.port.open({
baudRate: 115200,
dataBits: 8,
stopBits: 1,
parity: 'none',
flowControl: 'none',
bufferSize: 65536,
});
if (this.port.setSignals) {
try {
await this.port.setSignals({ dataTerminalReady: false, requestToSend: false });
} catch (_) {
/* ignore */
}
}
this.reader = this.port.readable.getReader();
this.writer = this.port.writable.getWriter();
this.portOpen = true;
await sleep(100);
await this.drainInput(300);
log('connect: port open (raw REPL not entered yet)');
}
async ensureRawRepl() {
if (this.inRawRepl) return;
if (this._replLock) {
await this._replLock;
return;
}
log('ensureRawRepl: entering raw REPL');
this._replLock = this.enterRawRepl(true).finally(() => {
this._replLock = null;
});
await this._replLock;
}
async disconnect() {
log('disconnect');
this._replLock = null;
const wasRaw = this.inRawRepl;
this.inRawRepl = false;
this.portOpen = false;
this.useRawPaste = true;
if (this.writer && wasRaw) {
try {
await this.writer.write(new Uint8Array([0x0d, 0x02]));
} catch (_) {
/* ignore */
}
}
if (this.reader) {
try {
await this.reader.cancel();
this.reader.releaseLock();
} catch (_) {
/* ignore */
}
this.reader = null;
}
if (this.writer) {
try {
await this.writer.close();
this.writer.releaseLock();
} catch (_) {
/* ignore */
}
this.writer = null;
}
if (this.port) {
try {
await this.port.close();
} catch (_) {
/* ignore */
}
this.port = null;
}
this._rxBuf = [];
}
async writeBytes(data) {
if (!this.writer) throw new Error('Serial not connected');
logDebug('tx', describeBytes(data));
await this.writer.write(data);
}
async drainInput(maxMs = 400) {
const deadline = Date.now() + maxMs;
while (Date.now() < deadline) {
const chunk = await this._readStreamChunk(40);
if (!chunk || !chunk.length) break;
}
this._rxBuf.length = 0;
}
/** Match mpremote SerialTransport.enter_raw_repl(soft_reset). */
async enterRawRepl(softReset = true) {
log('enterRawRepl', { softReset });
await this.writeBytes(new Uint8Array([0x0d, 0x03]));
await this.drainInput(400);
await this.writeBytes(new Uint8Array([0x0d, 0x01]));
if (softReset) {
log('enterRawRepl: wait banner+>, soft reset');
await this.readUntil(new TextEncoder().encode(RAW_REPL_BANNER + '>'), 15000);
await this.writeBytes(new Uint8Array([0x04]));
try {
await this.readUntil(new TextEncoder().encode(SOFT_REBOOT), 15000);
log('enterRawRepl: saw soft reboot');
} catch (e) {
log('enterRawRepl: no soft reboot banner', e.message);
}
}
try {
await this.readUntil(new TextEncoder().encode(RAW_REPL_BANNER), 45000);
} catch (e) {
log('enterRawRepl: retry ctrl-A after', e.message);
await this.writeBytes(new Uint8Array([0x0d, 0x01]));
await this.readUntil(new TextEncoder().encode(RAW_REPL_BANNER), 30000);
}
this.inRawRepl = true;
log('enterRawRepl: ready');
}
async rawPasteWrite(commandBytes) {
await this.writeBytes(new Uint8Array([0x05, 0x41, 0x01]));
const hdr = await this.readExact(2, 8000);
const windowSize = hdr[0] | (hdr[1] << 8);
let windowRemain = windowSize;
let i = 0;
while (i < commandBytes.length) {
while (windowRemain === 0) {
const b = await this.readExact(1, 15000);
if (b[0] === 0x01) {
windowRemain += windowSize;
} else if (b[0] === 0x04) {
await this.writeBytes(new Uint8Array([0x04]));
return;
} else {
throw new Error(`Unexpected byte during raw paste: 0x${b[0].toString(16)}`);
}
}
const n = Math.min(windowRemain, commandBytes.length - i);
await this.writeBytes(commandBytes.subarray(i, i + n));
windowRemain -= n;
i += n;
}
await this.writeBytes(new Uint8Array([0x04]));
await this.readUntil(new Uint8Array([0x04]), 30000);
}
async execRawNoFollow(commandBytes) {
log('execRawNoFollow', commandBytes.length, 'bytes');
await this.readUntil(new TextEncoder().encode('>'), 10000);
if (this.useRawPaste) {
await this.writeBytes(new Uint8Array([0x05, 0x41, 0x01]));
let data;
try {
data = await this.readExact(2, 3000);
} catch (_) {
this.useRawPaste = false;
data = null;
}
if (data) {
if (data[0] === 0x52 && data[1] === 0x01) {
log('exec: using raw paste mode');
await this.rawPasteWrite(commandBytes);
const ok = await this.readExact(2, 15000);
if (ok[0] !== 0x4f || ok[1] !== 0x4b) {
throw new Error(`Device did not return OK after paste (got ${decodeText(ok)})`);
}
log('exec: paste OK');
return;
}
if (data[0] === 0x52 && data[1] === 0x00) {
log('exec: raw paste not supported (R\\x00)');
this.useRawPaste = false;
} else {
log('exec: raw paste probe unexpected', describeBytes(data));
this.useRawPaste = false;
try {
await this.readUntil(new TextEncoder().encode(RAW_REPL_BANNER + '>'), 5000);
} catch (_) {
/* ignore */
}
}
}
}
for (let i = 0; i < commandBytes.length; i += 256) {
await this.writeBytes(commandBytes.subarray(i, Math.min(i + 256, commandBytes.length)));
await sleep(10);
}
log('exec: standard raw REPL write');
await this.writeBytes(new Uint8Array([0x04]));
const ok = await this.readExact(2, 15000);
if (ok[0] !== 0x4f || ok[1] !== 0x4b) {
throw new Error(`Device did not return OK (got ${decodeText(ok)})`);
}
log('exec: got OK');
}
async follow(timeoutMs = 30000) {
const out1 = await this.readUntil(new Uint8Array([0x04]), timeoutMs);
const stdout = decodeText(out1.slice(0, -1));
const out2 = await this.readUntil(new Uint8Array([0x04]), timeoutMs);
const stderr = decodeText(out2.slice(0, -1));
log('follow stdout', stdout.slice(0, 500));
if (stderr) log('follow stderr', stderr.slice(0, 500));
return { stdout, stderr };
}
async exec(command, timeoutMs = 30000) {
const preview =
typeof command === 'string' ? command.split('\n').slice(0, 3).join('\n') : '<bytes>';
log('exec', preview);
await this.ensureRawRepl();
const commandBytes =
typeof command === 'string' ? new TextEncoder().encode(command) : command;
await this.execRawNoFollow(commandBytes);
return this.follow(timeoutMs);
}
async readSettingsJson() {
log('readSettingsJson');
const code = [
'import json',
'try:',
" f=open('settings.json','r')",
' d=json.load(f)',
' f.close()',
'except Exception:',
' d={}',
'print(json.dumps(d))',
].join('\n');
const { stdout, stderr } = await this.exec(code);
const text = (stdout || '').trim() || (stderr || '').trim();
if (!text) {
log('readSettingsJson: empty response');
return {};
}
const parsed = extractJsonObject(text);
log('readSettingsJson: ok', Object.keys(parsed));
return parsed;
}
async writeSettingsJson(settings) {
log('writeSettingsJson', settings);
const jsonText = JSON.stringify(settings);
const escaped = JSON.stringify(jsonText);
const code = [
'import json',
`s=json.loads(${escaped})`,
"f=open('settings.json','w')",
'f.write(s)',
'f.close()',
'import machine',
'machine.reset()',
].join('\n');
await this.exec(code, 60000);
}
}
global.LedToolWebSerial = {
supported: () => typeof navigator !== 'undefined' && 'serial' in navigator,
requestPort: () => navigator.serial.requestPort(),
MicroPythonRawRepl,
};
})(typeof window !== 'undefined' ? window : globalThis);
-52
View File
@@ -1,52 +0,0 @@
"""Tests for deploy_manifest helpers (host Python)."""
import json
import os
import tempfile
import unittest
from deploy_manifest import (
MANIFEST_FILENAME,
build_manifest_bytes,
normalize_remote_path,
parse_manifest,
sha256_hex_file,
)
class DeployManifestTests(unittest.TestCase):
def test_normalize_remote_path(self):
self.assertEqual(normalize_remote_path("/patterns/chase.py"), "patterns/chase.py")
self.assertEqual(normalize_remote_path("main.py"), "main.py")
def test_round_trip_manifest(self):
files = {"main.py": "abc", "patterns/x.py": "def"}
blob = build_manifest_bytes(files)
parsed = parse_manifest(blob)
self.assertEqual(parsed, files)
doc = json.loads(blob.decode())
self.assertEqual(doc["version"], 1)
self.assertEqual(doc["algorithm"], "sha256")
def test_parse_manifest_invalid(self):
self.assertEqual(parse_manifest(b"not json"), {})
self.assertEqual(parse_manifest(b'{"files": "nope"}'), {})
def test_sha256_hex_file(self):
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(b"hello")
path = f.name
try:
self.assertEqual(
sha256_hex_file(path),
"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
)
finally:
os.unlink(path)
def test_manifest_filename(self):
self.assertEqual(MANIFEST_FILENAME, "file_hashes.json")
if __name__ == "__main__":
unittest.main()
+2 -112
View File
@@ -19,7 +19,6 @@ from flask import (
redirect, redirect,
url_for, url_for,
flash, flash,
send_from_directory,
) )
@@ -697,119 +696,10 @@ def handle_action():
) )
def _static_dir() -> str:
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
@app.route("/ports")
def api_list_ports():
from host_ports import filter_port_dicts
from serial.tools import list_ports
ports = filter_port_dicts(
[
{"device": i.device, "description": i.description, "hwid": i.hwid}
for i in list_ports.comports()
]
)
cli = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cli.py")
return json.dumps({"ports": ports, "led_cli_exists": os.path.exists(cli)})
@app.route("/settings", methods=["GET"])
def api_read_settings():
import subprocess
import sys
port = (request.args.get("port") or "").strip()
if not port:
return json.dumps({"error": "port is required"}), 400
cli = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cli.py")
result = subprocess.run(
[sys.executable, cli, "--port", port, "--show"],
capture_output=True,
text=True,
timeout=180,
cwd=os.path.dirname(cli),
)
settings = None
try:
settings = json.loads((result.stdout or "").strip())
except json.JSONDecodeError:
pass
return json.dumps(
{
"ok": result.returncode == 0,
"returncode": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr,
"settings": settings,
}
)
@app.route("/settings", methods=["POST"])
def api_write_settings():
import subprocess
import sys
data = request.get_json(silent=True) or {}
port = str(data.get("port") or "").strip()
if not port:
return json.dumps({"error": "port is required"}), 400
cli = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cli.py")
cmd = [sys.executable, cli, "--port", port]
flag_map = (
("name", "--name"),
("led_pin", "--pin"),
("num_leds", "--leds"),
("brightness", "--brightness"),
("transport", "--transport"),
("ssid", "--ssid"),
("password", "--wifi-password"),
("wifi_channel", "--wifi-channel"),
("default", "--default"),
)
for key, flag in flag_map:
val = data.get(key)
if val is None:
continue
s = str(val).strip()
if s:
cmd.extend([flag, s])
cmd.append("--follow")
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=180,
cwd=os.path.dirname(cli),
)
return json.dumps(
{
"ok": result.returncode == 0,
"returncode": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr,
}
)
@app.route("/editor")
def settings_editor():
"""Static settings editor (Web Serial + host serial). Prefer this over the legacy form."""
return send_from_directory(_static_dir(), "settings_editor.html")
@app.route("/static/<path:filename>")
def settings_static(filename):
return send_from_directory(_static_dir(), filename)
def main() -> None: def main() -> None:
# Bind to all interfaces so you can reach it from your LAN: # Bind to all interfaces so you can reach it from your LAN:
# python web.py # python web_app.py
# Then open: http://<pi-ip>:5000/editor # Then open: http://<pi-ip>:5000/
app.run(host="0.0.0.0", port=5000, debug=False) app.run(host="0.0.0.0", port=5000, debug=False)