Files
led-tool/http_device.py
T
jimmyandClaude Haiku 5.5 20a9b60d5f 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>
2026-11-17 00:34:22 +13:00

83 lines
3.0 KiB
Python

"""
Wi-Fi connection to the ESP-IDF led-driver.
The driver serves the same JSON API over HTTP on its address (led-driver main/web.cpp) that it
serves over USB (main/usb_cfg.cpp). HttpDevice has the same get/post/call interface as
idf_device.IdfDevice, so the settings code in cli.py works for both transports.
Not available over Wi-Fi: reboot (no HTTP route) and following the serial log.
"""
import http.client
import json
import socket
from typing import Any, Optional, Tuple
from idf_device import IdfError
class HttpDevice:
def __init__(self, host: str, port: int = 80, timeout: float = 5.0):
self.host = host
self.port = port
self.timeout = timeout
def open(self) -> "HttpDevice":
return self
def close(self) -> None:
pass
def __enter__(self) -> "HttpDevice":
return self
def __exit__(self, *exc) -> None:
pass
def call_raw(self, method: str, path: str, body: Any = None, host: Optional[str] = None,
timeout: Optional[float] = None) -> Tuple[int, Any]:
"""Send one request; return (status, parsed body). Does not raise on an error status."""
if host is not None:
raise IdfError(0, "relay through the driver is USB-only; use --port for that")
conn = http.client.HTTPConnection(self.host, self.port, timeout=timeout or self.timeout)
headers = {}
data = None
if body is not None:
data = json.dumps(body, separators=(",", ":")).encode()
headers["Content-Type"] = "application/json"
try:
conn.request(method, path, body=data, headers=headers)
r = conn.getresponse()
text = r.read().decode("utf-8", "replace")
except socket.timeout as e:
raise TimeoutError(f"no reply from {self.host} to {method} {path}") from e
except OSError as e:
raise TimeoutError(f"cannot reach {self.host}: {e}") from e
finally:
conn.close()
try:
parsed = json.loads(text) if text else {}
except ValueError:
parsed = text
return r.status, 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:
raise IdfError(0, "reboot is not available over Wi-Fi; use -r with --port (USB)")
def follow(self, seconds: Optional[float] = None) -> None:
raise IdfError(0, "following the log is not available over Wi-Fi; use -f with --port (USB)")