initial Commit
This commit is contained in:
69
pc/listen_buttons.py
Normal file
69
pc/listen_buttons.py
Normal file
@@ -0,0 +1,69 @@
|
||||
"""PC-side serial logger for the custom streamdeck Pico."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import serial
|
||||
import serial.tools.list_ports
|
||||
|
||||
DEFAULT_BAUD = 115200
|
||||
DEFAULT_LOG = Path(__file__).resolve().parent.parent / "button_log.txt"
|
||||
|
||||
|
||||
def find_pico_port() -> str | None:
|
||||
"""Return the first likely Raspberry Pi Pico serial port."""
|
||||
for port in serial.tools.list_ports.comports():
|
||||
vid = port.vid
|
||||
manufacturer = (port.manufacturer or "").lower()
|
||||
description = (port.description or "").lower()
|
||||
if vid == 0x2E8A or "pico" in description or "raspberry" in manufacturer:
|
||||
return port.device
|
||||
return None
|
||||
|
||||
|
||||
def format_event(raw_line: str) -> str:
|
||||
timestamp = datetime.now().isoformat(timespec="seconds")
|
||||
try:
|
||||
event = json.loads(raw_line)
|
||||
except json.JSONDecodeError:
|
||||
return f"{timestamp} raw {raw_line}"
|
||||
|
||||
button = event.get("button", "?")
|
||||
pin = event.get("pin", "?")
|
||||
action = event.get("event", "?")
|
||||
return f"{timestamp} button={button} pin=GP{pin} event={action}"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Listen for Pico button events and log them.")
|
||||
parser.add_argument("--port", help="Serial port, for example COM5. Auto-detects Pico if omitted.")
|
||||
parser.add_argument("--baud", type=int, default=DEFAULT_BAUD, help=f"Serial baud rate. Default: {DEFAULT_BAUD}")
|
||||
parser.add_argument("--log", type=Path, default=DEFAULT_LOG, help=f"Log file. Default: {DEFAULT_LOG}")
|
||||
args = parser.parse_args()
|
||||
|
||||
port = args.port or find_pico_port()
|
||||
if not port:
|
||||
print("Could not find a Pico serial port. Try: python pc/listen_buttons.py --port COM5")
|
||||
return 1
|
||||
|
||||
args.log.parent.mkdir(parents=True, exist_ok=True)
|
||||
print(f"Listening on {port} at {args.baud} baud. Logging to {args.log}")
|
||||
print("Press Ctrl+C to stop.")
|
||||
|
||||
with serial.Serial(port, args.baud, timeout=1) as ser, args.log.open("a", encoding="utf-8") as log_file:
|
||||
while True:
|
||||
raw = ser.readline().decode("utf-8", errors="replace").strip()
|
||||
if not raw:
|
||||
continue
|
||||
line = format_event(raw)
|
||||
print(line, flush=True)
|
||||
log_file.write(line + "\n")
|
||||
log_file.flush()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user