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>
1245 lines
48 KiB
Python
Executable File
1245 lines
48 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
LED Bar Configuration CLI Tool
|
|
|
|
Command-line interface for downloading, editing, and uploading settings.json
|
|
to/from MicroPython devices via mpremote.
|
|
"""
|
|
|
|
import json
|
|
import argparse
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import shutil
|
|
from typing import Dict, Any, List, Optional
|
|
|
|
import tempfile
|
|
import os
|
|
from ota import ota_update
|
|
import driver_ota
|
|
import http_device
|
|
from device import copy_file, DeviceConnection, firmware_default_device_name
|
|
import idf_device
|
|
|
|
|
|
def resolve_flash_binary(path: str) -> Optional[str]:
|
|
"""Resolve binary path: full path or in bin/ directory."""
|
|
if os.path.isabs(path):
|
|
return path if os.path.exists(path) else None
|
|
if os.path.exists(path):
|
|
return os.path.abspath(path)
|
|
bin_path = os.path.join("bin", path)
|
|
return os.path.abspath(bin_path) if os.path.exists(bin_path) else None
|
|
|
|
|
|
def download_settings(device: str) -> dict:
|
|
"""
|
|
Download settings.json from the device.
|
|
|
|
Returns an empty dict if the file does not exist so that the tool
|
|
can be used on a fresh device before settings.json has been created.
|
|
"""
|
|
temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False)
|
|
temp_path = temp_file.name
|
|
temp_file.close()
|
|
|
|
try:
|
|
copy_file(from_device=True, device=device, remote_path="settings.json", local_path=temp_path)
|
|
with open(temp_path, "r", encoding="utf-8") as f:
|
|
return json.load(f)
|
|
except (OSError, RuntimeError) as e:
|
|
# If the file is missing on the device, treat it as empty settings
|
|
msg = str(e).lower()
|
|
if "errno 2" in msg or "enoent" in msg or "not found" in msg:
|
|
return {}
|
|
raise
|
|
finally:
|
|
if os.path.exists(temp_path):
|
|
try:
|
|
os.unlink(temp_path)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def upload_settings(device: str, settings: dict) -> None:
|
|
"""Upload settings.json to the device and reset device."""
|
|
temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False)
|
|
temp_path = temp_file.name
|
|
|
|
try:
|
|
json.dump(settings, temp_file, indent=2)
|
|
temp_file.close()
|
|
|
|
copy_file(from_device=False, device=device, remote_path="settings.json", local_path=temp_path)
|
|
|
|
# Reset device (best effort)
|
|
try:
|
|
conn = DeviceConnection(device)
|
|
conn.connect()
|
|
conn.reset()
|
|
conn.disconnect()
|
|
except Exception:
|
|
pass
|
|
finally:
|
|
if os.path.exists(temp_path):
|
|
try:
|
|
os.unlink(temp_path)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
PRESETS_REMOTE = "presets.json"
|
|
|
|
|
|
def download_presets(device: str) -> dict:
|
|
"""Download presets.json from the device; missing file -> {}."""
|
|
temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False)
|
|
temp_path = temp_file.name
|
|
temp_file.close()
|
|
|
|
try:
|
|
copy_file(from_device=True, device=device, remote_path=PRESETS_REMOTE, local_path=temp_path)
|
|
with open(temp_path, "r", encoding="utf-8") as f:
|
|
return json.load(f)
|
|
except (OSError, RuntimeError) as e:
|
|
msg = str(e).lower()
|
|
if "errno 2" in msg or "enoent" in msg or "not found" in msg:
|
|
return {}
|
|
raise
|
|
finally:
|
|
if os.path.exists(temp_path):
|
|
try:
|
|
os.unlink(temp_path)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def upload_presets(device: str, presets: dict, *, reset: bool = True) -> None:
|
|
"""Upload presets.json; optional reset (skip when caller will reset via settings upload)."""
|
|
temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False)
|
|
temp_path = temp_file.name
|
|
|
|
try:
|
|
json.dump(presets, temp_file, indent=2)
|
|
temp_file.close()
|
|
|
|
copy_file(from_device=False, device=device, remote_path=PRESETS_REMOTE, local_path=temp_path)
|
|
|
|
if reset:
|
|
try:
|
|
conn = DeviceConnection(device)
|
|
conn.connect()
|
|
conn.reset()
|
|
conn.disconnect()
|
|
except Exception:
|
|
pass
|
|
finally:
|
|
if os.path.exists(temp_path):
|
|
try:
|
|
os.unlink(temp_path)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def print_settings(settings: Dict[str, Any]) -> None:
|
|
"""Pretty print settings dictionary."""
|
|
print(json.dumps(settings, indent=2))
|
|
|
|
|
|
# Flags that consume the next argv as their value (for skipping during order scan)
|
|
_FLAGS_WITH_VALUE = frozenset({
|
|
'-p', '--port', '-n', '--name', '--pin', '-b', '--brightness',
|
|
'-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',
|
|
})
|
|
|
|
|
|
def _get_ordered_actions(argv: List[str]) -> List[tuple]:
|
|
"""
|
|
Scan argv and return list of (action_name, value) in order of appearance.
|
|
Actions: flash, ota, pause, reset, upload, ls, erase_all, rm, follow.
|
|
"""
|
|
actions = []
|
|
i = 1
|
|
while i < len(argv):
|
|
arg = argv[i]
|
|
if arg == '--pause':
|
|
if i + 1 < len(argv):
|
|
try:
|
|
secs = float(argv[i + 1])
|
|
actions.append(('pause', secs))
|
|
except ValueError:
|
|
raise ValueError("--pause requires a number (seconds)")
|
|
i += 2
|
|
else:
|
|
raise ValueError("--pause requires an argument")
|
|
continue
|
|
if arg == '--flash':
|
|
if i + 1 < len(argv):
|
|
actions.append(('flash', argv[i + 1]))
|
|
i += 2
|
|
else:
|
|
raise ValueError("--flash requires an argument")
|
|
continue
|
|
if arg == '--ota':
|
|
vals = []
|
|
i += 1
|
|
while i < len(argv) and not argv[i].startswith('-') and len(vals) < 2:
|
|
vals.append(argv[i])
|
|
i += 1
|
|
if not vals:
|
|
raise ValueError("--ota requires a host (and optionally an image path)")
|
|
actions.append(('ota', vals))
|
|
continue
|
|
if arg in ('-r', '--reset'):
|
|
actions.append(('reset', None))
|
|
i += 1
|
|
continue
|
|
if arg in ('-u', '--upload'):
|
|
vals = []
|
|
i += 1
|
|
while i < len(argv) and not argv[i].startswith('-'):
|
|
vals.append(argv[i])
|
|
i += 1
|
|
if len(vals) >= 2:
|
|
break
|
|
if vals:
|
|
actions.append(('upload', vals))
|
|
continue
|
|
if arg == '--src':
|
|
# Upload local DIR (default: ./src) to device root (:/
|
|
local_dir = "src"
|
|
if i + 1 < len(argv) and not argv[i + 1].startswith('-'):
|
|
local_dir = argv[i + 1]
|
|
i += 2
|
|
else:
|
|
i += 1
|
|
# Upload source tree excluding patterns/ (handled by --patterns).
|
|
actions.append(('upload_src_no_patterns', local_dir))
|
|
continue
|
|
if arg in ('--patterns', '--paterns'):
|
|
# Upload local patterns DIR (default: ./src/patterns) to /patterns.
|
|
local_dir = os.path.join("src", "patterns")
|
|
if i + 1 < len(argv) and not argv[i + 1].startswith('-'):
|
|
local_dir = argv[i + 1]
|
|
i += 2
|
|
else:
|
|
i += 1
|
|
actions.append(('upload', [local_dir, "patterns"]))
|
|
continue
|
|
if arg == '--all':
|
|
actions.append(('upload_src_no_patterns', "src"))
|
|
actions.append(('upload', [os.path.join("src", "patterns"), "patterns"]))
|
|
actions.append(('upload', ["lib", "lib"]))
|
|
i += 1
|
|
continue
|
|
if arg == '--lib':
|
|
# Upload local DIR (default: ./lib) to /lib on device
|
|
local_dir = "lib"
|
|
if i + 1 < len(argv) and not argv[i + 1].startswith('-'):
|
|
local_dir = argv[i + 1]
|
|
i += 2
|
|
else:
|
|
i += 1
|
|
actions.append(('upload', [local_dir, "lib"]))
|
|
continue
|
|
if arg == '--ls':
|
|
actions.append(('ls', None))
|
|
i += 1
|
|
continue
|
|
if arg == '-e':
|
|
actions.append(('erase_all', None))
|
|
i += 1
|
|
continue
|
|
if arg == '--erase':
|
|
actions.append(('erase_all', None))
|
|
i += 1
|
|
continue
|
|
if arg == '--rm':
|
|
if i + 1 < len(argv):
|
|
actions.append(('rm', argv[i + 1]))
|
|
i += 2
|
|
else:
|
|
raise ValueError("--rm requires an argument")
|
|
continue
|
|
if arg in ('-f', '--follow'):
|
|
# Optional duration in seconds: --follow [SECONDS]
|
|
follow_secs = None
|
|
if i + 1 < len(argv) and not argv[i + 1].startswith('-'):
|
|
try:
|
|
follow_secs = float(argv[i + 1])
|
|
i += 2
|
|
except ValueError:
|
|
# Not a number, treat as flag-only
|
|
i += 1
|
|
actions.append(('follow', follow_secs))
|
|
else:
|
|
actions.append(('follow', None))
|
|
i += 1
|
|
continue
|
|
# Skip non-action flags and their values
|
|
if arg in _FLAGS_WITH_VALUE and i + 1 < len(argv):
|
|
i += 2
|
|
else:
|
|
i += 1
|
|
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",
|
|
"play": "--play", "select": "--select", "delete": "--delete", "presets_defaults": "--presets-defaults",
|
|
"preset_order": "--preset-order", "list_presets": "--list-presets", "list_patterns": "--list-patterns",
|
|
"colors": "--colors", "background": "--background", "delay": "--delay",
|
|
"preset_brightness": "--preset-brightness", "fade": "--fade", "reverse": "--reverse",
|
|
"auto": "--auto", "beat_time": "--beat-time",
|
|
}
|
|
|
|
|
|
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": {"ssid": dev.get("/api/wifi").get("ssid")},
|
|
"startup_preset": presets.get("startup"),
|
|
}
|
|
|
|
|
|
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 _hex_rgb(text: str) -> List[int]:
|
|
"""'#ff8000' or 'ff8000' -> [255, 128, 0]."""
|
|
t = text.lstrip("#")
|
|
if len(t) != 6:
|
|
raise ValueError(f"colour must be six hex digits, e.g. #ff8000: {text}")
|
|
try:
|
|
return [int(t[i:i + 2], 16) for i in (0, 2, 4)]
|
|
except ValueError:
|
|
raise ValueError(f"colour must be six hex digits, e.g. #ff8000: {text}") from None
|
|
|
|
|
|
def _preset_content(args: argparse.Namespace) -> Dict[str, Any]:
|
|
"""The preset fields given on the command line (only those; the driver keeps the rest)."""
|
|
c: Dict[str, Any] = {}
|
|
if args.colors is not None:
|
|
c["colors"] = [_hex_rgb(x) for x in args.colors]
|
|
if args.background is not None:
|
|
c["background"] = _hex_rgb(args.background)
|
|
if args.delay is not None:
|
|
c["delay"] = args.delay
|
|
if args.preset_brightness is not None:
|
|
c["brightness"] = args.preset_brightness
|
|
if args.fade is not None:
|
|
c["fade"] = args.fade
|
|
if args.reverse is not None:
|
|
c["reverse"] = args.reverse == "on"
|
|
if args.auto is not None:
|
|
c["auto"] = args.auto == "on"
|
|
if args.beat_time is not None:
|
|
c["beat_time"] = args.beat_time == "on"
|
|
return c
|
|
|
|
|
|
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)."""
|
|
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)
|
|
|
|
try:
|
|
content = _preset_content(args)
|
|
except ValueError as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
if args.preset is not None and args.play is not None:
|
|
print("Error: use either --preset (saved) or --play (live), not both", file=sys.stderr)
|
|
sys.exit(1)
|
|
if content and args.preset is None and args.play is None:
|
|
print("Error: colour, delay and other preset options need --preset NAME or --play PATTERN",
|
|
file=sys.stderr)
|
|
sys.exit(1)
|
|
if args.pattern is not None and args.preset is None and args.play is None:
|
|
print("Error: --pattern needs --preset NAME or --play", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
if args.host:
|
|
# Same API over Wi-Fi: everything below works unchanged, except reboot and follow
|
|
port = args.host
|
|
dev = http_device.HttpDevice(args.host)
|
|
else:
|
|
port = args.port
|
|
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.presets_defaults:
|
|
added = dev.post("/api/presets/defaults", {}).get("added", 0)
|
|
print(f"/api/presets/defaults: added {added} preset(s)", file=sys.stderr)
|
|
edited = True
|
|
if args.preset is not None:
|
|
body: Dict[str, Any] = {"name": args.preset, **content}
|
|
if args.pattern is not None:
|
|
body["pattern"] = args.pattern
|
|
_idf_post(dev, "/api/presets", body)
|
|
edited = True
|
|
if args.delete is not None:
|
|
_idf_post(dev, "/api/presets/delete", {"name": args.delete})
|
|
edited = True
|
|
if args.preset_order is not None:
|
|
_idf_post(dev, "/api/presets/order", {"names": args.preset_order})
|
|
edited = True
|
|
if args.default is not None:
|
|
_idf_post(dev, "/api/presets/startup", {"name": args.default})
|
|
edited = True
|
|
if args.select is not None:
|
|
_idf_post(dev, "/api/presets/select", {"name": args.select})
|
|
edited = True
|
|
if args.play is not None:
|
|
_idf_post(dev, "/api/pattern", {"pattern": args.play, **content})
|
|
edited = True
|
|
if args.list_presets:
|
|
presets = dev.get("/api/presets")
|
|
startup = presets.get("startup")
|
|
for p in presets.get("presets", []):
|
|
mark = " (startup)" if p.get("name") == startup else ""
|
|
print(f"{p.get('name')}{mark}")
|
|
if args.list_patterns:
|
|
for name in dev.get("/api/status").get("patterns", []):
|
|
print(name)
|
|
if args.mode is not None:
|
|
_idf_post(dev, "/api/espnow", {"enabled": args.mode == "espnow"})
|
|
edited = True
|
|
print(f" mode: {args.mode} (restart to apply: -r)", file=sys.stderr)
|
|
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'}")
|
|
|
|
listed = args.list_presets or args.list_patterns
|
|
actions_only = (ordered_actions or args.scan or listed) 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 tool.
|
|
|
|
Two firmwares are supported, found automatically on the serial port:
|
|
ESP-IDF led-driver (ESP32-C3, JSON API). Settings apply live, no reset needed.
|
|
MicroPython driver (mpremote). Settings are written to settings.json and need a reset.
|
|
|
|
The ESP-IDF driver also takes its settings over Wi-Fi: use --host ADDR instead of -p.
|
|
Flags marked (ESP-IDF) or (MicroPython) only apply to that firmware.""",
|
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
epilog="""
|
|
Examples
|
|
Show settings (either driver):
|
|
%(prog)s -s
|
|
%(prog)s --host 192.168.4.20 -s
|
|
|
|
Settings (ESP-IDF, USB or Wi-Fi):
|
|
%(prog)s -l 60 -o grb --pin 10 -b 128 strip: LEDs, colour order, GPIO, brightness
|
|
%(prog)s -n bar1 --ssid home --wifi-password secret
|
|
%(prog)s --ap off --static 10.0.0.5 255.255.255.0 10.0.0.1 --dns 1.1.1.1
|
|
%(prog)s --dhcp --ddp on
|
|
%(prog)s --scan list Wi-Fi networks the device can see
|
|
|
|
Patterns and presets (ESP-IDF, USB or Wi-Fi):
|
|
%(prog)s --list-patterns pattern names the driver has
|
|
%(prog)s --list-presets saved presets, startup marked
|
|
%(prog)s --preset warm --pattern chase --colors '#ff0000' '#00ff00' --delay 50
|
|
%(prog)s --preset warm --default warm save a preset and make it the startup
|
|
%(prog)s --select warm show a saved preset now
|
|
%(prog)s --play rainbow --fade 200 show a pattern now, without saving
|
|
%(prog)s --delete old --preset-order warm
|
|
%(prog)s --presets-defaults add the default presets that are missing
|
|
|
|
Reboot and logs (USB only):
|
|
%(prog)s -r reboot
|
|
%(prog)s -f follow the serial log (Ctrl+C to stop)
|
|
%(prog)s -r --pause 2 -f reboot, wait 2 s, then follow
|
|
|
|
Firmware:
|
|
%(prog)s --flash firmware.bin MicroPython: flash over serial
|
|
%(prog)s --ota-drivers --ota-image led-driver/build/led_driver.bin
|
|
find every ESP-IDF driver on this Wi-Fi subnet
|
|
and update them in parallel
|
|
%(prog)s --ota-drivers 192.168.4 --ota-list only list the drivers found on 192.168.4.x
|
|
%(prog)s --ota 10.1.1.180 [image] update one v2 controller over Ethernet
|
|
|
|
MicroPython driver:
|
|
%(prog)s -n "MyStrip" -l 60 --default rainbow settings.json, then reset to apply
|
|
%(prog)s -u ./src upload a directory to the device
|
|
%(prog)s --reset-device-name
|
|
"""
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-p", "--port",
|
|
default="/dev/ttyACM0",
|
|
help="Serial port of the device, USB (default: /dev/ttyACM0). Not used with --host"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-n", "--name",
|
|
help="Device name (ESP-IDF: the Wi-Fi hostname, mDNS name <name>.local)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--reset-device-name",
|
|
action="store_true",
|
|
help="Reset the name to the firmware default (MicroPython: led-<MAC>; ESP-IDF: led)",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--id",
|
|
dest="device_id",
|
|
type=int,
|
|
metavar="0-255",
|
|
help="(MicroPython) numeric device ID for ESP-NOW (0-255)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--pin",
|
|
type=int,
|
|
metavar="N",
|
|
help="LED GPIO pin number (both drivers)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-b", "--brightness",
|
|
type=int,
|
|
metavar="0-255",
|
|
help="Brightness, 0-255 (both drivers)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-l", "--leds",
|
|
dest="leds",
|
|
type=int,
|
|
metavar="N",
|
|
help="Number of LEDs in the strip (both drivers)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-d", "-debug", "--debug",
|
|
dest="debug",
|
|
type=int,
|
|
choices=[0, 1],
|
|
metavar="0|1",
|
|
help="(MicroPython) debug mode, 0 or 1"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-o", "--order",
|
|
dest="color_order",
|
|
choices=["rgb", "rbg", "grb", "gbr", "brg", "bgr"],
|
|
help="LED colour order (both drivers)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--preset",
|
|
metavar="NAME",
|
|
help="Create or replace preset NAME (both drivers; add --pattern and the preset options under Patterns and presets)",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--pattern",
|
|
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(
|
|
"--default",
|
|
metavar="NAME",
|
|
help="Startup preset: the one that runs at boot (both drivers)",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--transport",
|
|
choices=["espnow", "wifi"],
|
|
help="(MicroPython) transport_type: espnow or wifi",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--ssid",
|
|
help="Wi-Fi network to join (both drivers)",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--wifi-password",
|
|
dest="wifi_password",
|
|
metavar="PASS",
|
|
help="Wi-Fi password for --ssid (both drivers; empty for an open network)",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--wifi-channel",
|
|
dest="wifi_channel",
|
|
type=int,
|
|
metavar="1-11",
|
|
help="(MicroPython) ESP-NOW channel, 1-11",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--pause",
|
|
type=float,
|
|
metavar="SECONDS",
|
|
help="Pause for N seconds (use in action sequence, e.g. --reset --pause 2 --follow)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-r", "--reset",
|
|
action="store_true",
|
|
help="Reboot the device (USB only, both drivers)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-f", "--follow",
|
|
nargs="?",
|
|
const=None,
|
|
type=float,
|
|
metavar="SECONDS",
|
|
help="(ESP-IDF and MicroPython, USB only) follow the device output like tail -f; optionally stop after SECONDS"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-s", "--show",
|
|
action="store_true",
|
|
help="Show the current settings (both drivers)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-u", "--upload",
|
|
nargs='+',
|
|
metavar=("SRC", "DEST"),
|
|
help="(MicroPython) upload a directory recursively to the device: -u SRC [DEST] (DEST defaults to the basename of SRC)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--src",
|
|
nargs="?",
|
|
const="src",
|
|
metavar="DIR",
|
|
help="(MicroPython) upload DIR to the device root, excluding patterns/ (default: ./src)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--lib",
|
|
nargs="?",
|
|
const="lib",
|
|
metavar="DIR",
|
|
help="(MicroPython) upload DIR to /lib on the device (default: ./lib)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--all",
|
|
action="store_true",
|
|
help="(MicroPython) upload ./src, ./src/patterns and ./lib"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--patterns", "--paterns",
|
|
dest="patterns_dir",
|
|
nargs="?",
|
|
const=os.path.join("src", "patterns"),
|
|
metavar="DIR",
|
|
help="(MicroPython) upload DIR to /patterns on the device (default: ./src/patterns)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--ls",
|
|
action="store_true",
|
|
help="(MicroPython) list files on the device root (:/)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"-e", "--erase",
|
|
dest="erase_all",
|
|
action="store_true",
|
|
help="(MicroPython) erase all code on the device, keeping settings.json"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--rm",
|
|
metavar="PATH",
|
|
help="(MicroPython) delete a file or directory on the device (recursive for directories)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--ota",
|
|
nargs="+",
|
|
metavar=("HOST", "IMAGE"),
|
|
help="Update one v2 controller (the ESP32-S3 controller, not an LED driver) over Ethernet: HOST [IMAGE]. Exits afterwards"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--ota-drivers",
|
|
nargs="*",
|
|
metavar="TARGET",
|
|
help="Find LED drivers on the network and update them in parallel. TARGET is auto (this machine's /24, "
|
|
"the default), a /24 such as 192.168.4, a CIDR network such as 10.0.0.0/23, an address range such as "
|
|
"192.168.4.10-40 or 192.168.4.10-192.168.4.40, or one address. Several targets can be given, "
|
|
"separated by spaces or commas. No serial port is used and the tool exits afterwards",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--host",
|
|
metavar="ADDR",
|
|
help="Configure an ESP-IDF led-driver over Wi-Fi at ADDR (IP or name) instead of USB. Every settings "
|
|
"flag works the same; -r and -f need USB",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--ota-image",
|
|
metavar="PATH",
|
|
help="Driver firmware for --ota-drivers (required, e.g. led-driver/build/led_driver.bin)",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--ota-jobs",
|
|
type=int,
|
|
default=4,
|
|
metavar="N",
|
|
help="Simultaneous uploads for --ota-drivers (default 4)",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--ota-list",
|
|
action="store_true",
|
|
help="With --ota-drivers: only discover and list the drivers, do not update",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--flash",
|
|
metavar="BINARY",
|
|
help="(MicroPython) flash a firmware binary over serial. Path, or a 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, USB) 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")
|
|
idf.add_argument("--mode", choices=["espnow", "wifi"],
|
|
help="ESP-NOW (the Wi-Fi client stays off) or the Wi-Fi client (ESP-NOW off); "
|
|
"applies on restart (-r)")
|
|
|
|
pat = parser.add_argument_group("ESP-IDF led-driver patterns and presets")
|
|
pat.add_argument("--play", metavar="PATTERN",
|
|
help="Show PATTERN now without saving it (ESP-IDF: names from -s 'patterns')")
|
|
pat.add_argument("--select", metavar="NAME", help="Show the saved preset NAME now")
|
|
pat.add_argument("--delete", metavar="NAME", help="Delete the saved preset NAME")
|
|
pat.add_argument("--presets-defaults", action="store_true",
|
|
help="Add the default presets that are missing")
|
|
pat.add_argument("--preset-order", nargs="+", metavar="NAME",
|
|
help="Order of the saved presets, by name (names not listed keep their place at the end)")
|
|
pat.add_argument("--list-presets", action="store_true", help="Print the saved preset names")
|
|
pat.add_argument("--list-patterns", action="store_true", help="Print the pattern names the driver has")
|
|
pat.add_argument("--colors", nargs="+", metavar="HEX",
|
|
help="Colours for --preset or --play, e.g. #ff0000 #00ff00")
|
|
pat.add_argument("--background", metavar="HEX", help="Background colour, e.g. #000000")
|
|
pat.add_argument("--delay", type=int, metavar="MS", help="Delay between steps in milliseconds")
|
|
pat.add_argument("--preset-brightness", dest="preset_brightness", type=int, metavar="0-255",
|
|
help="Brightness of the preset (not the global brightness)")
|
|
pat.add_argument("--fade", type=int, metavar="MS", help="Fade time in milliseconds")
|
|
pat.add_argument("--reverse", choices=["on", "off"], help="Run the pattern in reverse")
|
|
pat.add_argument("--auto", choices=["on", "off"], help="Autorun flag of the preset")
|
|
pat.add_argument("--beat-time", dest="beat_time", choices=["on", "off"],
|
|
help="Time the pattern to the beat")
|
|
|
|
try:
|
|
args = parser.parse_args()
|
|
ordered_actions = _get_ordered_actions(sys.argv)
|
|
except ValueError as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
if args.ota_drivers is not None:
|
|
if not args.ota_list and not args.ota_image:
|
|
print("Error: --ota-drivers needs --ota-image PATH (the driver firmware, e.g. "
|
|
"led-driver/build/led_driver.bin)", file=sys.stderr)
|
|
sys.exit(1)
|
|
sys.exit(driver_ota.ota_drivers(args.ota_drivers or ["auto"], args.ota_image, args.ota_jobs,
|
|
args.ota_list))
|
|
|
|
port = args.port
|
|
ran_reset = False
|
|
|
|
if args.host:
|
|
if args.driver == "mpy":
|
|
print("Error: --host is for the ESP-IDF led-driver (Wi-Fi API); MicroPython has no Wi-Fi API here",
|
|
file=sys.stderr)
|
|
sys.exit(1)
|
|
run_idf(args, ordered_actions)
|
|
return
|
|
|
|
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':
|
|
print(f"Pausing for {value} seconds...", file=sys.stderr)
|
|
time.sleep(value)
|
|
elif action_name == 'flash':
|
|
resolved = resolve_flash_binary(value)
|
|
if not resolved:
|
|
print(f"Error: binary not found: {value} (checked bin/)", file=sys.stderr)
|
|
sys.exit(1)
|
|
try:
|
|
print(f"Erasing flash on {port}...", file=sys.stderr)
|
|
subprocess.run(["esptool", "-p", port, "erase_flash"], check=True)
|
|
print(f"Writing {resolved} to flash at 0...", file=sys.stderr)
|
|
subprocess.run(["esptool", "-p", port, "write_flash", "0", resolved], check=True)
|
|
print("Flash complete.", file=sys.stderr)
|
|
print("Waiting 2s for device to boot...", file=sys.stderr)
|
|
time.sleep(2)
|
|
except subprocess.CalledProcessError as e:
|
|
print(f"Error flashing: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
except FileNotFoundError:
|
|
print("Error: esptool not found. Install it with: pip install esptool", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
elif action_name == 'ota':
|
|
try:
|
|
ota_update(value[0], value[1] if len(value) > 1 else None)
|
|
except Exception as e:
|
|
print(f"Error: OTA failed: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
if all(a[0] in ('ota', 'pause') for a in ordered_actions):
|
|
return # network-only: nothing to download over serial
|
|
|
|
elif action_name == 'reset':
|
|
ran_reset = True
|
|
try:
|
|
print(f"Resetting device on {port}...", file=sys.stderr)
|
|
conn = DeviceConnection(port)
|
|
conn.reset()
|
|
print("Device reset.", file=sys.stderr)
|
|
except Exception as e:
|
|
print(f"Error resetting device: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
elif action_name == 'upload':
|
|
if len(value) > 2:
|
|
print("Error: -u accepts at most 2 arguments (source and optional destination)", file=sys.stderr)
|
|
sys.exit(1)
|
|
upload_dir = value[0]
|
|
remote_dir = value[1] if len(value) > 1 else None
|
|
if not os.path.exists(upload_dir):
|
|
print(f"Error: Directory does not exist: {upload_dir}", file=sys.stderr)
|
|
sys.exit(1)
|
|
if not os.path.isdir(upload_dir):
|
|
print(f"Error: Not a directory: {upload_dir}", file=sys.stderr)
|
|
sys.exit(1)
|
|
try:
|
|
if remote_dir:
|
|
print(f"Uploading {upload_dir} to {remote_dir} on device {port}...", file=sys.stderr)
|
|
else:
|
|
print(f"Uploading {upload_dir} to device on {port}...", file=sys.stderr)
|
|
conn = DeviceConnection(port)
|
|
files_copied, dirs_created = conn.upload_directory(upload_dir, remote_dir)
|
|
print(f"Upload complete: {files_copied} files, {dirs_created} directories created.", file=sys.stderr)
|
|
except Exception as e:
|
|
print(f"Error uploading directory: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
elif action_name == 'upload_src_no_patterns':
|
|
src_dir = value
|
|
if not os.path.exists(src_dir):
|
|
print(f"Error: Directory does not exist: {src_dir}", file=sys.stderr)
|
|
sys.exit(1)
|
|
if not os.path.isdir(src_dir):
|
|
print(f"Error: Not a directory: {src_dir}", file=sys.stderr)
|
|
sys.exit(1)
|
|
try:
|
|
with tempfile.TemporaryDirectory() as temp_src:
|
|
for entry in sorted(os.listdir(src_dir)):
|
|
if entry == "patterns":
|
|
continue
|
|
src_entry = os.path.join(src_dir, entry)
|
|
dst_entry = os.path.join(temp_src, entry)
|
|
if os.path.isdir(src_entry):
|
|
shutil.copytree(src_entry, dst_entry, ignore=shutil.ignore_patterns('__pycache__', '*.pyc', '*.pyo'))
|
|
else:
|
|
shutil.copy2(src_entry, dst_entry)
|
|
print(
|
|
f"Uploading {src_dir} (excluding patterns/) to device root on {port}...",
|
|
file=sys.stderr,
|
|
)
|
|
conn = DeviceConnection(port)
|
|
files_copied, dirs_created = conn.upload_directory(temp_src, "")
|
|
print(
|
|
f"Upload complete: {files_copied} files, {dirs_created} directories created.",
|
|
file=sys.stderr,
|
|
)
|
|
except Exception as e:
|
|
print(f"Error uploading src (excluding patterns): {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
elif action_name == 'ls':
|
|
try:
|
|
print(f"Listing files on device {port}...", file=sys.stderr)
|
|
conn = DeviceConnection(port)
|
|
items = conn.list_files('')
|
|
for name, is_dir, size in items:
|
|
marker = "d" if is_dir else "-"
|
|
print(f"{marker} {size:>8} {name}")
|
|
except Exception as e:
|
|
print(f"Error listing files: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
elif action_name == 'erase_all':
|
|
try:
|
|
print(f"Erasing all code on device {port}...", file=sys.stderr)
|
|
conn = DeviceConnection(port)
|
|
items = conn.list_files('')
|
|
for name, is_dir, size in items:
|
|
if name == "settings.json":
|
|
continue
|
|
conn.delete(name)
|
|
print("Erase complete.", file=sys.stderr)
|
|
except Exception as e:
|
|
print(f"Error erasing device: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
elif action_name == 'rm':
|
|
try:
|
|
print(f"Deleting {value} on device {port}...", file=sys.stderr)
|
|
conn = DeviceConnection(port)
|
|
conn.delete(value)
|
|
print(f"Successfully deleted: {value}", file=sys.stderr)
|
|
except Exception as e:
|
|
print(f"Error deleting {value}: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
elif action_name == 'follow':
|
|
if ran_reset:
|
|
time.sleep(0.5)
|
|
try:
|
|
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)
|
|
conn = DeviceConnection(port)
|
|
conn.follow_output(value)
|
|
except KeyboardInterrupt:
|
|
print("\nStopped following.", file=sys.stderr)
|
|
sys.exit(0)
|
|
except Exception as e:
|
|
print(f"Error following output: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
return # follow blocks; when interrupted we're done
|
|
|
|
default_name_from_device: Optional[str] = None
|
|
if args.reset_device_name:
|
|
if args.name is not None:
|
|
print(
|
|
"Error: use either --name or --reset-device-name, not both.",
|
|
file=sys.stderr,
|
|
)
|
|
sys.exit(1)
|
|
try:
|
|
print(
|
|
f"Reading firmware default device name (STA MAC) on {port}...",
|
|
file=sys.stderr,
|
|
)
|
|
default_name_from_device = firmware_default_device_name(port)
|
|
print(
|
|
f"Default name will be {default_name_from_device!r}.",
|
|
file=sys.stderr,
|
|
)
|
|
except Exception as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
# Collect all edit parameters
|
|
edits: Dict[str, Any] = {}
|
|
|
|
if args.name is not None:
|
|
edits["name"] = args.name
|
|
elif default_name_from_device is not None:
|
|
edits["name"] = default_name_from_device
|
|
|
|
if args.pin is not None:
|
|
edits["led_pin"] = args.pin
|
|
|
|
if args.brightness is not None:
|
|
edits["brightness"] = args.brightness
|
|
|
|
if args.leds is not None:
|
|
edits["num_leds"] = args.leds
|
|
|
|
if args.debug is not None:
|
|
edits["debug"] = bool(args.debug)
|
|
|
|
if args.color_order is not None:
|
|
edits["color_order"] = args.color_order
|
|
|
|
if args.default is not None:
|
|
edits["default"] = args.default
|
|
|
|
if args.transport is not None:
|
|
edits["transport_type"] = args.transport
|
|
|
|
if args.ssid is not None:
|
|
edits["ssid"] = args.ssid
|
|
|
|
if args.wifi_password is not None:
|
|
edits["password"] = args.wifi_password
|
|
|
|
if args.wifi_channel is not None:
|
|
edits["wifi_channel"] = max(1, min(11, args.wifi_channel))
|
|
|
|
if args.device_id is not None:
|
|
# Clamp into single-byte range; store as int in settings.json
|
|
edits["id"] = max(0, min(255, args.device_id))
|
|
|
|
# 1. Download: get current settings from device
|
|
try:
|
|
print(f"Downloading settings from {args.port}...", file=sys.stderr)
|
|
settings = download_settings(args.port)
|
|
print("Settings downloaded successfully.", file=sys.stderr)
|
|
except Exception as e:
|
|
if "timeout" in str(e).lower() or "connection" in str(e).lower():
|
|
print(f"Error: Connection timeout. Check device connection on {args.port}", file=sys.stderr)
|
|
else:
|
|
print(f"Error downloading settings: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
# If --show only, print and exit (unless presets or settings are being written)
|
|
if args.show:
|
|
print_settings(settings)
|
|
if not edits and args.preset is None:
|
|
return
|
|
|
|
# 2. Edit: apply edits to downloaded settings
|
|
if edits:
|
|
print(f"Applying {len(edits)} edit(s)...", file=sys.stderr)
|
|
settings.update(edits)
|
|
|
|
print_settings(settings)
|
|
|
|
# 3a. Presets file (led-driver presets.json)
|
|
if args.preset is not None:
|
|
pattern = args.pattern if args.pattern is not None else "on"
|
|
try:
|
|
print(f"Downloading presets from {args.port}...", file=sys.stderr)
|
|
presets_data = download_presets(args.port)
|
|
entry = presets_data.get(args.preset)
|
|
if not isinstance(entry, dict):
|
|
entry = {}
|
|
entry["p"] = pattern
|
|
presets_data[args.preset] = entry
|
|
print(
|
|
f"Writing preset {args.preset!r} (pattern={pattern}) to {PRESETS_REMOTE}...",
|
|
file=sys.stderr,
|
|
)
|
|
upload_presets(args.port, presets_data, reset=not bool(edits))
|
|
print("Presets uploaded successfully.", file=sys.stderr)
|
|
if not edits:
|
|
print("Device will reset.", file=sys.stderr)
|
|
except Exception as e:
|
|
if "timeout" in str(e).lower() or "connection" in str(e).lower():
|
|
print(f"Error: Connection timeout. Check device connection on {args.port}", file=sys.stderr)
|
|
else:
|
|
print(f"Error uploading presets: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
# 3b. Settings upload (resets device)
|
|
if edits:
|
|
try:
|
|
print(f"\nUploading settings to {args.port}...", file=sys.stderr)
|
|
upload_settings(args.port, settings)
|
|
print("Settings uploaded successfully. Device will reset.", file=sys.stderr)
|
|
except Exception as e:
|
|
if "timeout" in str(e).lower() or "connection" in str(e).lower():
|
|
print(f"Error: Connection timeout. Check device connection on {args.port}", file=sys.stderr)
|
|
else:
|
|
print(f"Error uploading settings: {e}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|