1 Commits
Author SHA1 Message Date
jimmyandCursor 580fd11aca fix(cli): skip redundant settings uploads when unchanged
Only upload settings when edited values differ from current device settings to avoid unnecessary resets.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-04 22:48:54 +12:00
5 changed files with 20 additions and 568 deletions

No files matched your search

-21
View File
@@ -29,31 +29,10 @@ Connection is always via **`-p` / `--port`** (default `/dev/ttyACM0`). There is
| `--src`, `--lib` | Upload `src/` or a tree to `/lib` |
| `-e` | Erase device code (keeps `settings.json`) |
| `--rm` | Remove a path on the device |
| `--ota` | Update a v2 controller over Ethernet: `--ota HOST [IMAGE]` (no serial port; image defaults to `led_controller_v2.bin` in `./v2/build`, `./build` or `../v2/build`) |
| `--flash` | Flash a firmware binary (uses **esptool** on the host) |
**Default behaviour:** the tool always downloads `settings.json`, prints the merged view, and uploads again **only** when you pass setting edits (`--name`, `--leds`, …), **`--preset`**, or the relevant upload/flash/erase actions in order.
## ESP-IDF led-driver (USB)
The ESP-IDF led-driver (ESP32-C3) has no files to copy: its settings live in NVS. It serves its JSON API on the USB serial port instead (one `@api {...}` line per request, see `led-driver/main/usb_cfg.cpp`), and led-tool talks to it with **`idf_device.py`**. The tool asks the port first (`--driver auto`, the default) and falls back to mpremote when nothing answers; `--driver idf` or `--driver mpy` skips the check.
| Flag | Device API |
|------|-----------|
| `-s` | Hardware, brightness, network, Wi-Fi and presets in one view (also printed after edits) |
| `--pin`, `-l`, `-o`, `--max-brightness` | `/api/hardware` |
| `-b` | `/api/brightness` (this device's level) |
| `--preset NAME [--pattern P]`, `--default NAME` | `/api/presets`, `/api/presets/startup` |
| `--ssid`, `--wifi-password` | `/api/wifi` (save and connect) |
| `-n` (mDNS hostname), `--reset-device-name` (back to `led`), `--ap on/off`, `--ap-ssid`, `--ap-password`, `--ddp on/off`, `--dhcp`, `--static IP NETMASK GATEWAY [DNS]`, `--dns ADDR` (static only; empty uses the gateway) | `/api/network` |
| `--scan` | `/api/wifi/scan`: visible networks, strongest first |
| `-r`, `-f`, `--pause` | Reboot, follow the log, wait |
| `-v` | Print the device's log lines while talking to it |
Edits apply live, so there is no reset afterwards. `--id`, `--debug`, `--transport`, `--wifi-channel` and the file upload flags are MicroPython only; flash ESP-IDF firmware with `idf.py flash` or `--ota`.
Opening the port keeps DTR high and RTS low, so connecting doesn't reset the C3.
Run **`python cli.py -h`** for the full epilog and argument list.
## License
+20 -289
View File
@@ -16,9 +16,7 @@ from typing import Dict, Any, List, Optional
import tempfile
import os
from ota import ota_update
from device import copy_file, DeviceConnection, firmware_default_device_name
import idf_device
def resolve_flash_binary(path: str) -> Optional[str]:
@@ -150,15 +148,14 @@ _FLAGS_WITH_VALUE = frozenset({
'-p', '--port', '-n', '--name', '--pin', '-b', '--brightness',
'-l', '--leds', '-d', '-debug', '--debug', '-o', '--order',
'--preset', '--pattern', '--default', '--transport', '--ssid',
'--wifi-password', '--wifi-channel', '--ota', '--src', '--lib', '--patterns', '--paterns',
'--driver', '--max-brightness', '--ap', '--ap-ssid', '--ap-password', '--ddp', '--dns',
'--wifi-password', '--wifi-channel', '--src', '--lib', '--patterns', '--paterns',
})
def _get_ordered_actions(argv: List[str]) -> List[tuple]:
"""
Scan argv and return list of (action_name, value) in order of appearance.
Actions: flash, ota, pause, reset, upload, ls, erase_all, rm, follow.
Actions: flash, pause, reset, upload, ls, erase_all, rm, follow.
"""
actions = []
i = 1
@@ -182,16 +179,6 @@ def _get_ordered_actions(argv: List[str]) -> List[tuple]:
else:
raise ValueError("--flash requires an argument")
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'):
actions.append(('reset', None))
i += 1
@@ -286,197 +273,6 @@ def _get_ordered_actions(argv: List[str]) -> List[tuple]:
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",
}
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": 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", []),
}
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 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:
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.preset is not None:
body: Dict[str, Any] = {"name": args.preset}
if args.pattern is not None:
body["pattern"] = args.pattern
_idf_post(dev, "/api/presets", body)
edited = True
if args.default is not None:
_idf_post(dev, "/api/presets/startup", {"name": args.default})
edited = True
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'}")
actions_only = (ordered_actions or args.scan) 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:
parser = argparse.ArgumentParser(
description="LED Bar Configuration CLI Tool",
@@ -508,10 +304,6 @@ Examples:
%(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
@@ -520,15 +312,6 @@ Examples:
# 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
"""
)
@@ -603,8 +386,10 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
parser.add_argument(
"--pattern",
help="Pattern for --preset (MicroPython: off, on, blink, rainbow, pulse, transition, chase, circle;"
" ESP-IDF: any name from -s 'patterns'). MicroPython default: on",
choices=[
"off", "on", "blink", "rainbow", "pulse", "transition", "chase", "circle",
],
help="Pattern type for --preset (default: on)",
)
parser.add_argument(
@@ -724,50 +509,12 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
help="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"
)
parser.add_argument(
"--flash",
metavar="BINARY",
help="Flash firmware binary to device. Path can be full path or 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: 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")
try:
args = parser.parse_args()
ordered_actions = _get_ordered_actions(sys.argv)
@@ -778,21 +525,6 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
port = args.port
ran_reset = False
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
for action_name, value in ordered_actions:
if action_name == 'pause':
@@ -818,15 +550,6 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
print("Error: esptool not found. Install it with: pip install esptool", file=sys.stderr)
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':
ran_reset = True
try:
@@ -877,7 +600,7 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
src_entry = os.path.join(src_dir, entry)
dst_entry = os.path.join(temp_src, entry)
if os.path.isdir(src_entry):
shutil.copytree(src_entry, dst_entry, ignore=shutil.ignore_patterns('__pycache__', '*.pyc', '*.pyo'))
shutil.copytree(src_entry, dst_entry)
else:
shutil.copy2(src_entry, dst_entry)
print(
@@ -1030,10 +753,18 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
if not edits and args.preset is None:
return
# 2. Edit: apply edits to downloaded settings
if edits:
print(f"Applying {len(edits)} edit(s)...", file=sys.stderr)
settings.update(edits)
# 2. Edit: only apply/upload settings when values actually change
changed_edits: Dict[str, Any] = {}
for key, value in edits.items():
if settings.get(key) != value:
changed_edits[key] = value
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)
@@ -1064,7 +795,7 @@ ESP-IDF led-driver (found automatically on the port; force with --driver idf):
sys.exit(1)
# 3b. Settings upload (resets device)
if edits:
if changed_edits:
try:
print(f"\nUploading settings to {args.port}...", file=sys.stderr)
upload_settings(args.port, settings)
-9
View File
@@ -122,13 +122,6 @@ class DeviceConnection:
if not os.path.isdir(local_dir):
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()
try:
# Determine remote directory name
@@ -165,8 +158,6 @@ class DeviceConnection:
# Copy files
for file in files:
if file.endswith((".pyc", ".pyo")):
continue
local_file = os.path.join(root, file)
# Handle root directory case properly
if remote_base == '/':
-172
View File
@@ -1,172 +0,0 @@
"""
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
@@ -1,77 +0,0 @@
"""
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 the v2 controller?)")
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")