""" 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": ""} @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