feat: configure the ESP-IDF led-driver over USB
idf_device.py talks to the driver's USB API (led-driver main/usb_cfg.cpp). --driver auto (default) asks the port first and falls back to mpremote. Existing flags map to the driver's API (-s, --pin, -l, -o, -b, --preset, --default, --ssid/--wifi-password, -n, -r, -f); new ESP-IDF flags cover the rest of the network settings (--ap, --ap-ssid, --ap-password, --ddp, --dhcp, --static, --dns), --max-brightness and --scan. Opening the port keeps DTR high so connecting doesn't reset the C3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c9dea6e142
commit
f5ab256b4a
3 files changed
+442
-4
No files matched your search
@@ -18,6 +18,7 @@ import tempfile
|
||||
import os
|
||||
from ota import ota_update
|
||||
from device import copy_file, DeviceConnection, firmware_default_device_name
|
||||
import idf_device
|
||||
|
||||
|
||||
def resolve_flash_binary(path: str) -> Optional[str]:
|
||||
@@ -150,6 +151,7 @@ _FLAGS_WITH_VALUE = frozenset({
|
||||
'-l', '--leds', '-d', '-debug', '--debug', '-o', '--order',
|
||||
'--preset', '--pattern', '--default', '--transport', '--ssid',
|
||||
'--wifi-password', '--wifi-channel', '--ota', '--src', '--lib', '--patterns', '--paterns',
|
||||
'--driver', '--max-brightness', '--ap', '--ap-ssid', '--ap-password', '--ddp', '--dns',
|
||||
})
|
||||
|
||||
|
||||
@@ -284,6 +286,197 @@ def _get_ordered_actions(argv: List[str]) -> List[tuple]:
|
||||
return actions
|
||||
|
||||
|
||||
# Flags that only the MicroPython driver understands (settings.json / file uploads)
|
||||
_MPY_ONLY = {
|
||||
"device_id": "--id", "debug": "--debug", "transport": "--transport",
|
||||
"wifi_channel": "--wifi-channel", "upload": "-u", "src": "--src", "lib": "--lib",
|
||||
"all": "--all", "patterns_dir": "--patterns", "ls": "--ls", "erase_all": "-e", "rm": "--rm",
|
||||
}
|
||||
# And the reverse: flags only the ESP-IDF driver understands
|
||||
_IDF_ONLY = {
|
||||
"max_brightness": "--max-brightness", "ap": "--ap", "ap_ssid": "--ap-ssid",
|
||||
"ap_password": "--ap-password", "ddp": "--ddp", "dhcp": "--dhcp", "static": "--static",
|
||||
"dns": "--dns", "scan": "--scan",
|
||||
}
|
||||
|
||||
|
||||
def _idf_show(dev: "idf_device.IdfDevice") -> Dict[str, Any]:
|
||||
"""Everything the ESP-IDF driver will tell over USB, in one view."""
|
||||
status = dev.get("/api/status")
|
||||
presets = dev.get("/api/presets")
|
||||
return {
|
||||
"hardware": dev.get("/api/hardware"),
|
||||
"brightness": {
|
||||
"global": status.get("global_brightness"),
|
||||
"master": status.get("master_brightness"),
|
||||
},
|
||||
"network": dev.get("/api/network"),
|
||||
"wifi": dev.get("/api/wifi"),
|
||||
"presets": {
|
||||
"names": [p.get("name") for p in presets.get("presets", [])],
|
||||
"selected": presets.get("selected"),
|
||||
"startup": presets.get("startup"),
|
||||
},
|
||||
"running": {k: v for k, v in status.items() if k not in ("patterns",)},
|
||||
"patterns": status.get("patterns", []),
|
||||
}
|
||||
|
||||
|
||||
def _idf_post(dev: "idf_device.IdfDevice", path: str, body: Dict[str, Any]) -> None:
|
||||
reply = dev.post(path, body)
|
||||
msg = reply.get("message") if isinstance(reply, dict) else None
|
||||
print(f"{path}: {msg or 'ok'}", file=sys.stderr)
|
||||
if isinstance(reply, dict) and reply.get("address"):
|
||||
print(f" device address: {reply['address']}", file=sys.stderr)
|
||||
|
||||
|
||||
def run_idf(args: argparse.Namespace, ordered_actions: List[tuple]) -> None:
|
||||
"""Configure an ESP-IDF led-driver through its USB API (led-driver main/usb_cfg.cpp)."""
|
||||
port = args.port
|
||||
bad = [flag for dest, flag in _MPY_ONLY.items() if getattr(args, dest, None) not in (None, False)]
|
||||
if bad:
|
||||
print(f"Error: {', '.join(bad)}: MicroPython driver only (this is an ESP-IDF led-driver)", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
dev = idf_device.IdfDevice(port, verbose=args.verbose)
|
||||
try:
|
||||
dev.open()
|
||||
except Exception as e:
|
||||
print(f"Error: cannot open {port}: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
# Actions in command-line order (reset, pause, follow, flash, ota)
|
||||
for action_name, value in ordered_actions:
|
||||
if action_name == "pause":
|
||||
print(f"Pausing for {value} seconds...", file=sys.stderr)
|
||||
time.sleep(value)
|
||||
elif action_name == "reset":
|
||||
print(f"Rebooting device on {port}...", file=sys.stderr)
|
||||
dev.reboot()
|
||||
# The USB port drops and comes back during the restart
|
||||
dev.close()
|
||||
time.sleep(2.0)
|
||||
dev.open()
|
||||
elif action_name == "follow":
|
||||
if value is None:
|
||||
print(f"Following output from {port}... (Press Ctrl+C to stop)", file=sys.stderr)
|
||||
else:
|
||||
print(f"Following output from {port} for {value} seconds...", file=sys.stderr)
|
||||
try:
|
||||
dev.follow(value)
|
||||
except KeyboardInterrupt:
|
||||
print("\nStopped following.", file=sys.stderr)
|
||||
return
|
||||
elif action_name == "ota":
|
||||
ota_update(value[0], value[1] if len(value) > 1 else None)
|
||||
elif action_name == "flash":
|
||||
print("Error: --flash with an ESP-IDF driver: use idf.py flash (or --driver mpy for a merged image)",
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Settings edits, each sent to the API route that owns it. They apply live: no reset.
|
||||
hw: Dict[str, Any] = {}
|
||||
if args.pin is not None:
|
||||
hw["pin"] = args.pin
|
||||
if args.leds is not None:
|
||||
hw["num_leds"] = args.leds
|
||||
if args.color_order is not None:
|
||||
hw["rgb_order"] = args.color_order
|
||||
if args.max_brightness is not None:
|
||||
hw["max_brightness"] = args.max_brightness
|
||||
|
||||
net: Dict[str, Any] = {}
|
||||
if args.name is not None and args.reset_device_name:
|
||||
print("Error: use either --name or --reset-device-name, not both.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if args.name is not None:
|
||||
net["hostname"] = args.name
|
||||
elif args.reset_device_name:
|
||||
net["hostname"] = "led"
|
||||
if args.ap is not None:
|
||||
net["ap_enabled"] = args.ap == "on"
|
||||
if args.ap_ssid is not None:
|
||||
net["ap_ssid"] = args.ap_ssid
|
||||
if args.ap_password is not None:
|
||||
net["ap_password"] = args.ap_password
|
||||
if args.ddp is not None:
|
||||
net["ddp_enabled"] = args.ddp == "on"
|
||||
if args.dhcp and args.static:
|
||||
print("Error: use either --dhcp or --static, not both.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if args.dhcp:
|
||||
net["mode"] = "dhcp"
|
||||
if args.static:
|
||||
if len(args.static) not in (3, 4):
|
||||
print("Error: --static needs IP NETMASK GATEWAY [DNS]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
net["mode"] = "static"
|
||||
net.update(dict(zip(("ip", "netmask", "gateway", "dns"), args.static)))
|
||||
if args.dns is not None:
|
||||
if args.static and len(args.static) == 4:
|
||||
print("Error: DNS given twice (--static's 4th value and --dns)", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
net["dns"] = args.dns
|
||||
|
||||
wifi: Dict[str, Any] = {}
|
||||
if args.ssid is not None:
|
||||
wifi["ssid"] = args.ssid
|
||||
wifi["password"] = args.wifi_password or ""
|
||||
elif args.wifi_password is not None:
|
||||
print("Error: --wifi-password needs --ssid", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
edited = False
|
||||
if hw:
|
||||
_idf_post(dev, "/api/hardware", hw)
|
||||
edited = True
|
||||
if args.brightness is not None:
|
||||
_idf_post(dev, "/api/brightness", {"brightness": args.brightness})
|
||||
edited = True
|
||||
if args.preset is not None:
|
||||
body: Dict[str, Any] = {"name": args.preset}
|
||||
if args.pattern is not None:
|
||||
body["pattern"] = args.pattern
|
||||
_idf_post(dev, "/api/presets", body)
|
||||
edited = True
|
||||
if args.default is not None:
|
||||
_idf_post(dev, "/api/presets/startup", {"name": args.default})
|
||||
edited = True
|
||||
if wifi:
|
||||
_idf_post(dev, "/api/wifi", wifi)
|
||||
edited = True
|
||||
if net:
|
||||
# Last: it reconnects Wi-Fi (USB is unaffected)
|
||||
_idf_post(dev, "/api/network", net)
|
||||
edited = True
|
||||
if "dns" in net and net.get("mode", dev.get("/api/network").get("mode")) != "static":
|
||||
print(" note: DNS is used only with a static address (--static); DHCP supplies its own",
|
||||
file=sys.stderr)
|
||||
|
||||
if args.scan:
|
||||
print(f"Scanning for Wi-Fi networks on {port}...", file=sys.stderr)
|
||||
nets = dev.get("/api/wifi/scan", timeout=15).get("networks", [])
|
||||
nets.sort(key=lambda n: n.get("rssi", -999), reverse=True)
|
||||
width = max([len(n.get("ssid") or "") for n in nets] + [4])
|
||||
print(f"{'SSID':<{width}} RSSI SECURITY")
|
||||
for n in nets:
|
||||
ssid = n.get("ssid") or "(hidden)"
|
||||
print(f"{ssid:<{width}} {n.get('rssi', 0):>4} {'open' if n.get('open') else 'secured'}")
|
||||
|
||||
actions_only = (ordered_actions or args.scan) and not edited and not args.show
|
||||
if not actions_only:
|
||||
print_settings(_idf_show(dev))
|
||||
except idf_device.IdfError as e:
|
||||
print(f"Error from device: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except TimeoutError as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
finally:
|
||||
dev.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="LED Bar Configuration CLI Tool",
|
||||
@@ -327,6 +520,15 @@ Examples:
|
||||
|
||||
# Reset logical device name to firmware default (STA MAC based)
|
||||
%(prog)s --reset-device-name
|
||||
|
||||
ESP-IDF led-driver (found automatically on the port; force with --driver idf):
|
||||
%(prog)s -s # hardware, brightness, network, Wi-Fi, presets
|
||||
%(prog)s -l 60 -o rgb --pin 10 -b 128 # strip settings, applied live
|
||||
%(prog)s -n bar1 --ssid home --wifi-password secret
|
||||
%(prog)s --preset warm --pattern solid --default warm
|
||||
%(prog)s --ap off --static 10.0.0.5 255.255.255.0 10.0.0.1 --dns 1.1.1.1
|
||||
%(prog)s --scan # Wi-Fi networks the device can see
|
||||
%(prog)s -r -f # reboot, then follow the log
|
||||
"""
|
||||
)
|
||||
|
||||
@@ -401,10 +603,8 @@ Examples:
|
||||
|
||||
parser.add_argument(
|
||||
"--pattern",
|
||||
choices=[
|
||||
"off", "on", "blink", "rainbow", "pulse", "transition", "chase", "circle",
|
||||
],
|
||||
help="Pattern type for --preset (default: on)",
|
||||
help="Pattern for --preset (MicroPython: off, on, blink, rainbow, pulse, transition, chase, circle;"
|
||||
" ESP-IDF: any name from -s 'patterns'). MicroPython default: on",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
@@ -537,6 +737,37 @@ Examples:
|
||||
help="Flash firmware binary to device. Path can be full path or filename in bin/"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--driver",
|
||||
choices=["auto", "idf", "mpy"],
|
||||
default="auto",
|
||||
help="Device firmware: idf (ESP-IDF led-driver, USB API), mpy (MicroPython, mpremote), "
|
||||
"or auto (default: ask the port, fall back to mpy)",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-v", "--verbose",
|
||||
action="store_true",
|
||||
help="ESP-IDF: print the device's log lines while talking to it",
|
||||
)
|
||||
|
||||
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-ssid", dest="ap_ssid", metavar="NAME",
|
||||
help="Access point name (empty: led-XXXXXX)")
|
||||
idf.add_argument("--ap-password", dest="ap_password", metavar="PASS",
|
||||
help="Access point password, 8-63 characters (empty: open)")
|
||||
idf.add_argument("--ddp", choices=["on", "off"], help="Receive DDP pixels and frame sync")
|
||||
idf.add_argument("--dhcp", action="store_true", help="Wi-Fi client address from DHCP")
|
||||
idf.add_argument("--static", nargs="+", metavar="ADDR",
|
||||
help="Static Wi-Fi client address: IP NETMASK GATEWAY [DNS]")
|
||||
idf.add_argument("--dns", metavar="ADDR",
|
||||
help="DNS server for a static address (empty: use the gateway)")
|
||||
idf.add_argument("--scan", action="store_true",
|
||||
help="List the Wi-Fi networks the device can see")
|
||||
|
||||
try:
|
||||
args = parser.parse_args()
|
||||
ordered_actions = _get_ordered_actions(sys.argv)
|
||||
@@ -547,6 +778,21 @@ Examples:
|
||||
port = args.port
|
||||
ran_reset = False
|
||||
|
||||
use_idf = args.driver == "idf"
|
||||
serial_free = bool(ordered_actions) and all(a[0] in ("ota", "pause", "flash") for a in ordered_actions)
|
||||
if args.driver == "auto" and not serial_free:
|
||||
use_idf = idf_device.probe(port)
|
||||
if use_idf:
|
||||
print(f"ESP-IDF led-driver on {port}", file=sys.stderr)
|
||||
if use_idf:
|
||||
run_idf(args, ordered_actions)
|
||||
return
|
||||
bad = [flag for dest, flag in _IDF_ONLY.items() if getattr(args, dest, None) not in (None, False)]
|
||||
if bad:
|
||||
print(f"Error: {', '.join(bad)}: ESP-IDF led-driver only (no ESP-IDF driver answered on {port})",
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Execute actions in command-line order
|
||||
for action_name, value in ordered_actions:
|
||||
if action_name == 'pause':
|
||||
|
||||
Reference in new issue
Block a user