From 892ccaec7124ca967df5a6ffa9e0e351cabcc022 Mon Sep 17 00:00:00 2001 From: jimmy Date: Sun, 1 Nov 2026 00:22:55 +1300 Subject: [PATCH] feat(cli): add --ota to update a v2 controller over Ethernet Co-Authored-By: Claude Sonnet 5.5 --- README.md | 1 + cli.py | 35 +++++++++++++++++++++++-- ota.py | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 111 insertions(+), 2 deletions(-) create mode 100644 ota.py diff --git a/README.md b/README.md index 5d3324b..b00753e 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ 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. diff --git a/cli.py b/cli.py index 225dfaa..6aeaeda 100755 --- a/cli.py +++ b/cli.py @@ -16,6 +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 @@ -148,14 +149,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', '--src', '--lib', '--patterns', '--paterns', + '--wifi-password', '--wifi-channel', '--ota', '--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, pause, reset, upload, ls, erase_all, rm, follow. + Actions: flash, ota, pause, reset, upload, ls, erase_all, rm, follow. """ actions = [] i = 1 @@ -179,6 +180,16 @@ 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 @@ -304,6 +315,10 @@ 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 @@ -509,6 +524,13 @@ Examples: 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", @@ -550,6 +572,15 @@ Examples: 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: diff --git a/ota.py b/ota.py new file mode 100644 index 0000000..80661c1 --- /dev/null +++ b/ota.py @@ -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 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")