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

+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