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>
This commit is contained in:
jimmyandClaude Haiku 5.5 committed 2026-11-17 00:34:22 +13:00
1 parent f5ab256b4a
commit 20a9b60d5f
5 files changed
+628 -131

No files matched your search

+248 -85
View File
@@ -17,6 +17,8 @@ from typing import Dict, Any, List, Optional
import tempfile
import os
from ota import ota_update
import driver_ota
import http_device
from device import copy_file, DeviceConnection, firmware_default_device_name
import idf_device
@@ -297,6 +299,11 @@ _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",
}
@@ -311,14 +318,8 @@ def _idf_show(dev: "idf_device.IdfDevice") -> Dict[str, Any]:
"master": status.get("master_brightness"),
},
"network": dev.get("/api/network"),
"wifi": dev.get("/api/wifi"),
"presets": {
"names": [p.get("name") for p in presets.get("presets", [])],
"selected": presets.get("selected"),
"startup": presets.get("startup"),
},
"running": {k: v for k, v in status.items() if k not in ("patterns",)},
"patterns": status.get("patterns", []),
"wifi": {"ssid": dev.get("/api/wifi").get("ssid")},
"startup_preset": presets.get("startup"),
}
@@ -330,15 +331,69 @@ def _idf_post(dev: "idf_device.IdfDevice", path: str, body: Dict[str, Any]) -> N
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)."""
port = args.port
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)
dev = idf_device.IdfDevice(port, verbose=args.verbose)
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:
@@ -434,15 +489,44 @@ def run_idf(args: argparse.Namespace, ordered_actions: List[tuple]) -> None:
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}
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
@@ -464,7 +548,8 @@ def run_idf(args: argparse.Namespace, ordered_actions: List[tuple]) -> None:
ssid = n.get("ssid") or "(hidden)"
print(f"{ssid:<{width}} {n.get('rssi', 0):>4} {'open' if n.get('open') else 'secured'}")
actions_only = (ordered_actions or args.scan) and not edited and not args.show
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:
@@ -479,74 +564,73 @@ def run_idf(args: argparse.Namespace, ordered_actions: List[tuple]) -> None:
def main() -> None:
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,
epilog="""
Examples:
# Download and print current settings
%(prog)s
Examples
Show settings (either driver):
%(prog)s -s
%(prog)s --host 192.168.4.20 -s
# Download, edit device name and brightness, then upload
%(prog)s -n "LED-Strip-1" -b 128
Settings (ESP-IDF, USB or Wi-Fi):
%(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
# Set multiple parameters
%(prog)s -n "MyLED" -b 200 --preset "rainbow"
Patterns and presets (ESP-IDF, USB or Wi-Fi):
%(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 number of LEDs, color order, and debug mode
%(prog)s -l 60 -o rgb -d 1
Reboot and logs (USB only):
%(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
# Reset the device
%(prog)s -r
Firmware:
%(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
# 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
# Update a v2 controller over Ethernet (image defaults to led_controller_v2.bin under ./v2/build, ./build or ../v2/build)
%(prog)s --ota 10.1.1.180
%(prog)s --ota 10.1.1.180 /path/to/led_controller_v2.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
ESP-IDF led-driver (found automatically on the port; force with --driver idf):
%(prog)s -s # hardware, brightness, network, Wi-Fi, presets
%(prog)s -l 60 -o rgb --pin 10 -b 128 # strip settings, applied live
%(prog)s -n bar1 --ssid home --wifi-password secret
%(prog)s --preset warm --pattern solid --default warm
%(prog)s --ap off --static 10.0.0.5 255.255.255.0 10.0.0.1 --dns 1.1.1.1
%(prog)s --scan # Wi-Fi networks the device can see
%(prog)s -r -f # reboot, then follow the log
MicroPython driver:
%(prog)s -n "MyStrip" -l 60 --default rainbow settings.json, then reset to apply
%(prog)s -u ./src upload a directory to the device
%(prog)s --reset-device-name
"""
)
parser.add_argument(
"-p", "--port",
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(
"-n", "--name",
help="Device name"
help="Device name (ESP-IDF: the Wi-Fi hostname, mDNS name <name>.local)"
)
parser.add_argument(
"--reset-device-name",
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(
@@ -554,21 +638,21 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
dest="device_id",
type=int,
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(
"--pin",
type=int,
metavar="N",
help="LED GPIO pin number (led_pin in settings.json)"
help="LED GPIO pin number (both drivers)"
)
parser.add_argument(
"-b", "--brightness",
type=int,
metavar="0-255",
help="Brightness (0-255)"
help="Brightness, 0-255 (both drivers)"
)
parser.add_argument(
@@ -576,7 +660,7 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
dest="leds",
type=int,
metavar="N",
help="Number of LEDs (num_leds in settings.json)"
help="Number of LEDs in the strip (both drivers)"
)
parser.add_argument(
@@ -585,20 +669,20 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
type=int,
choices=[0, 1],
metavar="0|1",
help="Debug mode (0 or 1)"
help="(MicroPython) debug mode, 0 or 1"
)
parser.add_argument(
"-o", "--order",
dest="color_order",
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(
"--preset",
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(
@@ -610,25 +694,25 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
parser.add_argument(
"--default",
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(
"--transport",
choices=["espnow", "wifi"],
help="led-driver transport_type",
help="(MicroPython) transport_type: espnow or wifi",
)
parser.add_argument(
"--ssid",
help="led-driver ssid (Wi-Fi network in wifi mode)",
help="Wi-Fi network to join (both drivers)",
)
parser.add_argument(
"--wifi-password",
dest="wifi_password",
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(
@@ -636,7 +720,7 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
dest="wifi_channel",
type=int,
metavar="1-11",
help="led-driver wifi_channel (ESP-NOW mode)",
help="(MicroPython) ESP-NOW channel, 1-11",
)
parser.add_argument(
@@ -649,7 +733,7 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
parser.add_argument(
"-r", "--reset",
action="store_true",
help="Reset the device"
help="Reboot the device (USB only, both drivers)"
)
parser.add_argument(
@@ -658,20 +742,20 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
const=None,
type=float,
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(
"-s", "--show",
action="store_true",
help="Display current settings from device"
help="Show the current settings (both drivers)"
)
parser.add_argument(
"-u", "--upload",
nargs='+',
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(
@@ -679,7 +763,7 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
nargs="?",
const="src",
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(
@@ -687,13 +771,13 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
nargs="?",
const="lib",
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(
"--all",
action="store_true",
help="Upload ./src (excluding patterns), ./src/patterns, and ./lib."
help="(MicroPython) upload ./src, ./src/patterns and ./lib"
)
parser.add_argument(
@@ -702,39 +786,76 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
nargs="?",
const=os.path.join("src", "patterns"),
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(
"--ls",
action="store_true",
help="List files on the device root (:/)"
help="(MicroPython) list files on the device root (:/)"
)
parser.add_argument(
"-e", "--erase",
dest="erase_all",
action="store_true",
help="Erase all code on the device (delete all files except settings.json)"
help="(MicroPython) erase all code on the device, keeping settings.json"
)
parser.add_argument(
"--rm",
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 a v2 controller over Ethernet: HOST [IMAGE]. No serial port is used and the tool exits afterwards"
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(
"--flash",
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(
@@ -748,7 +869,7 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
parser.add_argument(
"-v", "--verbose",
action="store_true",
help="ESP-IDF: print the device's log lines while talking to it",
help="(ESP-IDF, USB) print the device's log lines while talking to it",
)
idf = parser.add_argument_group("ESP-IDF led-driver only")
@@ -767,6 +888,32 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
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:
args = parser.parse_args()
@@ -775,11 +922,27 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
print(f"Error: {e}", file=sys.stderr)
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
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)
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: