diff --git a/cli.py b/cli.py index b18b50e..7f64210 100755 --- a/cli.py +++ b/cli.py @@ -875,7 +875,9 @@ Examples 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", choices=["on", "off"], + help="Turn the access point on or off (off needs a joined Wi-Fi network or ESP-NOW: " + "--mode espnow --ap 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", diff --git a/espnow_ap_off.py b/espnow_ap_off.py new file mode 100644 index 0000000..2a55d2c --- /dev/null +++ b/espnow_ap_off.py @@ -0,0 +1,333 @@ +#!/usr/bin/env python3 +"""Flash ESP-IDF led-drivers over USB and turn their access point off (ESP-NOW mode). + +For each board: check its hostname (default mid1, mid2, ...), flash led-driver/build-v61 with the +ESP-IDF v6.1 image, turn the access point off, reboot it, and check the access point stays off and +ESP-NOW is running. The access point can only be turned off on a driver in ESP-NOW mode with the new +firmware (led-driver main/net.cpp), so flashing comes first. + +Bridge boards are never opened: a port is matched to a board by the MAC udev reports for it, and the +controller's serial bridges (GET /settings/bridge) are left out. Opening a bridge's port can knock it +off its link with the controller. + + python3 led-tool/espnow_ap_off.py --watch # plug in boards one after another; Ctrl+C to stop + python3 led-tool/espnow_ap_off.py --port /dev/ttyACM0 + python3 led-tool/espnow_ap_off.py --watch --channel 11 --no-flash +""" + +import argparse +import glob +import json +import os +import re +import subprocess +import sys +import time +import urllib.request +from typing import Dict, List, Optional, Set + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import idf_device # noqa: E402 + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +DRIVER_DIR = os.path.join(ROOT, "led-driver") +IDF_IMAGE = os.environ.get("IDF_IMAGE", "espressif/idf:v6.1") +PORT_GLOBS = ("/dev/ttyACM*", "/dev/ttyUSB*") +SETTLE_S = 5.0 # wait after a board is plugged in, before touching its port (see main) + + +def say(msg: str) -> None: + print(msg, flush=True) + + +def usb_mac(port: str) -> Optional[str]: + """The MAC udev reports for an Espressif USB-Serial-JTAG port (12 lowercase hex), without opening it.""" + try: + out = subprocess.run(["udevadm", "info", "-q", "property", "-n", port], + capture_output=True, text=True, timeout=5).stdout + except (OSError, subprocess.SubprocessError): + return None + m = re.search(r"^ID_SERIAL_SHORT=([0-9A-Fa-f:]{17})$", out, re.M) + return m.group(1).replace(":", "").lower() if m else None + + +def bridge_macs(controller: str) -> Optional[Set[str]]: + """MACs of the controller's serial bridge boards, or None when the controller can't be asked.""" + try: + with urllib.request.urlopen(controller.rstrip("/") + "/settings/bridge", timeout=5) as r: + data = json.load(r) + except Exception: + return None + macs = set() + for b in data.get("bridges", []): + st = b.get("status") or {} + if b.get("kind") == "serial" and st.get("mac"): + macs.add(st["mac"].replace(":", "").lower()) + addr = b.get("addr", "") + if addr.startswith("usb:"): + macs.add(addr[4:].lower()) + macs.discard("000000000000") + return macs + + +def candidate_ports(skip_macs: Set[str]) -> Dict[str, Optional[str]]: + """Serial ports that are not a bridge: port -> its USB MAC (None when udev has none).""" + ports = {} + for pat in PORT_GLOBS: + for p in sorted(glob.glob(pat)): + mac = usb_mac(p) + if mac not in skip_macs: + ports[p] = mac + return ports + + +def open_when_ready(port: str, timeout: float = 25.0) -> idf_device.IdfDevice: + """Open the port and wait until the driver answers (it re-enumerates after a flash or reboot).""" + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + if os.path.exists(port): + dev = idf_device.IdfDevice(port) + try: + dev.open() + dev.get("/api/network", timeout=2.0) + return dev + except Exception as e: # not up yet + last = e + dev.close() + time.sleep(1.0) + raise RuntimeError(f"{port}: no answer from the driver ({last})") + + +def read_state(dev: idf_device.IdfDevice) -> Dict[str, object]: + n = dev.get("/api/network") + s = dev.get("/api/status") + e = dev.get("/api/espnow") + return { + "hostname": n.get("hostname"), + "mac": s.get("mac"), + "ap": n.get("ap_enabled"), + "espnow": e.get("enabled"), + "running": e.get("running"), + "channel": e.get("channel"), + "radio": e.get("radio_channel"), + "controller": e.get("controller") or "", + } + + +FLASH_TRIES = 3 + + +def flash(port: str, build: str = "build-v61") -> None: + if not os.path.isdir(os.path.join(DRIVER_DIR, build)): + hint = (' (idf.py -B build-espnow -D SDKCONFIG=build-espnow/sdkconfig ' + '-D "SDKCONFIG_DEFAULTS=sdkconfig;sdkconfig.espnow" build)') if build == "build-espnow" else "" + raise RuntimeError(f"led-driver/{build} is missing: build it with the v6.1 image first{hint}") + # Rootless Docker: the container's root is this user, so no -u (that would map to a subuid). + # IDF_FLASH_FULL=1: write every image, not only what differs from the last board flashed from this build. + cmd = ["docker", "run", "--rm", "--device", port, "-e", "IDF_FLASH_FULL=1", "-v", f"{DRIVER_DIR}:/project", + "-w", "/project", IDF_IMAGE, "idf.py", "-B", build, "-p", port, "flash"] + for attempt in range(1, FLASH_TRIES + 1): + if not wait_for_port(port, 15): + raise RuntimeError(f"{port} went away") + r = subprocess.run(cmd, capture_output=True, text=True) + out = r.stdout + r.stderr + verified = out.count("Hash of data verified") + if r.returncode == 0 and verified: + say(f" flashed ({verified} images verified)") + return + # A USB error part-way (often another program probing the port, e.g. ModemManager) is worth a retry: + # the chip's ROM loader is always there, so a half-written app does not stop the next try + errs = [ln.strip() for ln in out.splitlines() if "Error" in ln and ln.strip()] + say(f" flash attempt {attempt} failed: {errs[-1] if errs else 'exit %d' % r.returncode}") + time.sleep(3.0) + raise RuntimeError(f"flash failed {FLASH_TRIES} times (see led-driver/{build}/log)") + + +def answers_ping(controller: str, mac: str, tries: int = 4) -> Optional[int]: + """The controller's broadcast ping: this driver's round trip in ms, or None if it never answers.""" + for _ in range(tries): + req = urllib.request.Request(controller.rstrip("/") + "/devices/ping", + data=json.dumps({"timeout_s": 3, "broadcast": True}).encode(), method="POST", + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=20) as r: + rsp = (json.load(r).get("responses") or {}).get(mac) + if rsp: + return rsp.get("rtt_ms") + except Exception: + pass + time.sleep(2.0) + return None + + +def wait_for_port(port: str, timeout: float) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if os.path.exists(port): + return True + time.sleep(0.5) + return False + + +def controller_name_for(controller: str, mac: Optional[str]) -> Optional[str]: + """The controller's name for the driver with this MAC (its record key or address), if it has one.""" + if not mac: + return None + try: + with urllib.request.urlopen(controller.rstrip("/") + "/devices", timeout=5) as r: + devs = json.load(r) + except Exception: + return None + for key, d in (devs.items() if isinstance(devs, dict) else []): + if isinstance(d, dict) and mac in (str(key).lower(), str(d.get("address", "")).lower()): + return d.get("name") + return None + + +def process(port: str, args: argparse.Namespace) -> bool: + """One board. Returns True when its access point ends up off with ESP-NOW running.""" + try: + dev = open_when_ready(port, timeout=10) + try: + st = read_state(dev) + finally: + dev.close() + name = st["hostname"] or "?" + say(f"{port}: {name} ({st['mac']}) ap={'on' if st['ap'] else 'off'} " + f"espnow={'on' if st['espnow'] else 'off'} ch {st['channel']}") + except Exception as e: + # No answer: a board whose app is broken (a flash cut off part-way) can't say who it is. Ask the + # controller instead, by the MAC udev reports, and flash it if that name matches. + mac = usb_mac(port) + name = controller_name_for(args.controller, mac) + say(f"{port}: no answer from the driver ({e}); the controller knows {mac or '?'} as {name or 'nothing'}") + if args.no_flash or not (name or args.port): + say(" skipped: can't tell which board this is (name its port with --port to flash it anyway)") + return False + if not name: # --port: the user picked this board (a bridge's port was refused already) + say(" flashing it anyway: you named this port with --port") + name = None + if name is not None and not re.fullmatch(args.name, str(name)): + say(f" skipped: hostname {name!r} does not match {args.name!r} (--name)") + return False + + if not args.no_flash: + flash(port) + dev = open_when_ready(port) + try: + st = read_state(dev) + want_ch = args.channel if args.channel is not None else st["channel"] + if not st["espnow"] or st["channel"] != want_ch: + if args.channel is None: + say(" skipped: ESP-NOW is off (give --channel N to turn it on)") + return False + dev.post("/api/espnow", {"enabled": True, "channel": args.channel}) + say(f" ESP-NOW on, channel {args.channel}") + if st["ap"]: + dev.post("/api/network", {"ap_enabled": False}) + say(" access point off") + dev.reboot() + finally: + dev.close() + + time.sleep(2.0) + dev = open_when_ready(port) + try: + st = read_state(dev) + finally: + dev.close() + ok = st["ap"] is False and st["espnow"] and st["running"] and st["radio"] == want_ch + say(f" after reboot: ap={'on' if st['ap'] else 'off'} espnow running={st['running']} " + f"radio ch {st['radio']} controller {st['controller'] or '-'} -> " + f"{('set up' if args.bare else 'OK') if ok else 'CHECK THIS BOARD'}") + if not ok or not args.bare: + return bool(ok) + + # The bare ESP-NOW image last: it keeps these settings (NVS), but has no USB config, so from here the + # controller is the only way to it, and the check is whether it answers the controller's ping + mac = str(st["mac"] or usb_mac(port) or "").replace(":", "").lower() + flash(port, "build-espnow") + time.sleep(4.0) + rtt = answers_ping(args.controller, mac) + say(f" bare ESP-NOW image: {'answers the controller in %s ms -> OK' % rtt if rtt is not None else 'no answer to the controller -> CHECK THIS BOARD'}") + return rtt is not None + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--port", help="Only this port (a bridge's port is still refused)") + ap.add_argument("--watch", action="store_true", help="Wait for boards to be plugged in, one after another") + ap.add_argument("--name", default=r"mid\d+", help="Hostname a board must have (regex, default mid)") + ap.add_argument("--channel", type=int, help="ESP-NOW channel to set (default: keep the board's)") + ap.add_argument("--no-flash", action="store_true", help="Boards already have the new firmware") + ap.add_argument("--bare", action="store_true", + help="After setting a board up, flash the bare ESP-NOW image (led-driver/build-espnow: no USB " + "config, so the controller sets it up from then on) and check it answers the controller") + ap.add_argument("--controller", default="http://localhost:8080", help="Controller to ask for its bridges") + ap.add_argument("--bridge-mac", action="append", default=[], + help="MAC of a bridge board to leave alone, if the controller is not running (repeatable)") + args = ap.parse_args() + + skip = {m.replace(":", "").lower() for m in args.bridge_mac} + found = bridge_macs(args.controller) + if found is None and not skip and not args.port: + say(f"Can't ask {args.controller} for its bridges: give --bridge-mac or --port, so a bridge is never opened") + return 2 + skip |= found or set() + if skip: + say("Leaving bridge boards alone: " + ", ".join(sorted(skip))) + + if args.port: + if usb_mac(args.port) in skip: + say(f"{args.port} is a bridge board: not touching it") + return 2 + try: + return 0 if process(args.port, args) else 1 + except Exception as e: + say(f" failed: {e}") + return 1 + + # Boards handled while they stay plugged in, by USB MAC (or port, when udev has none). A board is forgotten + # only after it has been gone for GONE_POLLS polls: it re-enumerates for a moment when it reboots. + GONE_POLLS = 3 + done: Dict[str, int] = {} # key -> polls it has been missing + failed = 0 + if args.watch: + say("Watching for boards. Plug one in; unplug it when it says OK. Ctrl+C to stop.") + try: + while True: + ports = candidate_ports(skip) + present = {mac or p for p, mac in ports.items()} + for key in list(done): + done[key] = 0 if key in present else done[key] + 1 + if done[key] >= GONE_POLLS: + del done[key] + todo = [p for p, mac in ports.items() if (mac or p) not in done] + if todo and args.watch: + # ModemManager and the like probe a newly plugged serial port for a few seconds; touching it + # meanwhile can cut a flash off part-way (USB "Protocol error") + say(f"Board on {', '.join(todo)}: letting it settle for {SETTLE_S:.0f} s...") + time.sleep(SETTLE_S) + for p in todo: + done[ports[p] or p] = 0 + try: + if not process(p, args): + failed += 1 + except Exception as e: + failed += 1 + say(f" failed: {e}") + if args.watch: + say("Next board, or Ctrl+C to stop.") + if not args.watch: + if not todo: + say("No driver boards plugged in.") + return 1 if failed else 0 + time.sleep(1.0) + except KeyboardInterrupt: + say("\nStopped.") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main())