Files
led-driver/dev.py
2026-04-05 16:41:23 +12:00

94 lines
3.3 KiB
Python
Executable File

#!/usr/bin/env python3
import shutil
import subprocess
import serial
import sys
from pathlib import Path
def mpremote_base():
"""mpremote on PATH, or same interpreter as this script (e.g. pipenv venv)."""
exe = shutil.which("mpremote")
if exe:
return [exe]
return [sys.executable, "-m", "mpremote"]
print(sys.argv)
# Extract port (first arg if it's not a command)
commands = ["src", "lib", "ls", "reset", "follow", "db", "test"]
port = None
if len(sys.argv) > 1 and sys.argv[1] not in commands:
port = sys.argv[1]
for cmd in sys.argv[1:]:
print(cmd)
match cmd:
case "src":
if port:
subprocess.call(
[*mpremote_base(), "connect", port, "fs", "cp", "-r", ".", ":"],
cwd="src",
)
else:
print("Error: Port required for 'src' command")
case "lib":
if port:
subprocess.call([*mpremote_base(), "connect", port, "fs", "cp", "-r", "lib", ":"])
else:
print("Error: Port required for 'lib' command")
case "ls":
if port:
subprocess.call([*mpremote_base(), "connect", port, "fs", "ls", ":"])
else:
print("Error: Port required for 'ls' command")
case "reset":
if port:
with serial.Serial(port, baudrate=115200) as ser:
ser.write(b'\x03\x03\x04')
else:
print("Error: Port required for 'reset' command")
case "follow":
if port:
with serial.Serial(port, baudrate=115200) as ser:
while True:
if ser.in_waiting > 0: # Check if there is data in the buffer
data = ser.readline().decode('utf-8').strip() # Read and decode the data
print(data)
else:
print("Error: Port required for 'follow' command")
case "db":
if port:
subprocess.call([*mpremote_base(), "connect", port, "fs", "cp", "-r", "db", ":"])
else:
print("Error: Port required for 'db' command")
case "test":
if port:
if "all" in sys.argv[1:]:
test_files = sorted(
str(path)
for path in Path("test").rglob("*.py")
if path.is_file()
)
failed = []
for test_file in test_files:
print(f"Running {test_file}")
code = subprocess.call(
[*mpremote_base(), "connect", port, "run", test_file]
)
if code != 0:
failed.append((test_file, code))
if failed:
print("Some tests failed:")
for test_file, code in failed:
print(f" {test_file} (exit {code})")
else:
subprocess.call(
[*mpremote_base(), "connect", port, "run", "test/all.py"]
)
else:
print("Error: Port required for 'test' command")