Files
meshcore-tth/tools/serial_tcp_proxy.py

87 lines
2.5 KiB
Python
Executable File

#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Bridge a bench XIAO's USB console to a localhost TCP port.
tools/serial_tcp_proxy.py <usb-serial|board> <tcp-port>
Holds the console open with DTR/RTS up (as fleet_test.py does) and serves it
on 127.0.0.1:<tcp-port>, one client at a time, so a board on another host
joins a test run here through an SSH tunnel:
ssh -L 7001:127.0.0.1:7001 lab-pc \\
'python3 MeshCore/tools/serial_tcp_proxy.py b1 7001'
tools/fleet_test.py --boards 4 --remote 1=socket://127.0.0.1:7001
Localhost only. Matches the board by its USB serial number, never ttyACM*;
a board name/alias is looked up in the local config (tools/mctools_config.py)
of the host it runs on. Refuses a board whose config entry sets `refuse`
(e.g. the radio of an observer, which runs other firmware).
"""
import glob
import socket
import sys
import threading
from mctools_config import field, serial_for
def serve(ser, srv: socket.socket) -> None:
while True:
conn, _ = srv.accept()
conn.settimeout(0.05)
alive = [True]
def to_client() -> None:
while alive[0]:
try:
data = ser.read(4096)
if data:
conn.sendall(data)
except OSError:
alive[0] = False
t = threading.Thread(target=to_client, daemon=True)
t.start()
while alive[0]:
try:
data = conn.recv(4096)
if not data:
break
ser.write(data)
except socket.timeout:
continue
except OSError:
break
alive[0] = False
t.join(1)
conn.close()
def main() -> None:
if len(sys.argv) != 3 or sys.argv[1] in ("-h", "--help"):
print(__doc__)
sys.exit(0)
sn, tport = serial_for(sys.argv[1]), int(sys.argv[2])
why = field(sn, "refuse")
if why:
sys.exit(f"refused: {why}")
ports = [p for p in glob.glob("/dev/serial/by-id/*Seeed_Studio_XIAO*") if sn in p]
if not ports:
sys.exit(f"{sn}: no MeshCore XIAO port")
import serial # after --help: the help works without pyserial
ser = serial.Serial(ports[0], 115200, timeout=0.05)
ser.dtr = True
ser.rts = True
srv = socket.socket()
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", tport))
srv.listen(1)
print(f"{ports[0]} <-> 127.0.0.1:{tport}", flush=True)
serve(ser, srv)
if __name__ == "__main__":
main()