#!/usr/bin/env python3 """ Pont série <-> UDP bidirectionnel pour Radxa Zero 3W (Tout-en-un SteamFrame FPV). Relie la Waveshare RP2350 (g29_crsf) au casque Steam Frame (192.168.1.10:14552) via l'interface USB Gadget RNDIS (usb0) sans aucune dépendance externe (stdlib seule). """ import errno import fcntl import glob import os import select import socket import sys import termios import time from typing import Optional BAUD_RATE = termios.B460800 BIND_IP = os.environ.get("STEAMFRAME_BIND_IP", "192.168.1.1") CASQUE_IP = os.environ.get("STEAMFRAME_CASQUE_IP", "192.168.1.10") UDP_PORT = int(os.environ.get("STEAMFRAME_G29_PORT", "14552")) MAX_SERIAL_RX_BUF = 4096 MAX_SERIAL_TX_BUF = 4096 # Préfixes autorisés du casque vers la RP2350 (bloque toute commande CLI brute comme B=BOOTSEL ou R=Reset) ALLOWED_INBOUND_PREFIXES = (b"$HT,", b"$RC,", b"$SRC,", b"$GEARS,") # Ordre de détection : USB CDC direct puis UART9_M1 (/dev/ttyS9, brochage Radxa Zero 3W documenté) SERIAL_CANDIDATES = ( "/dev/ttyACM0", "/dev/ttyACM1", "/dev/ttyS9", "/dev/ttyS4", "/dev/ttyS5", "/dev/ttyS3", "/dev/ttyS0", "/dev/ttyAMA0", ) def open_serial(dev_path: str) -> int: fd = os.open(dev_path, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) try: try: fcntl.ioctl(fd, termios.TIOCEXCL) except OSError: pass attrs = termios.tcgetattr(fd) # Mode raw 8N1 sans contrôle de flux attrs[0] = 0 # iflag attrs[1] = 0 # oflag attrs[2] = termios.CS8 | termios.CREAD | termios.CLOCAL # cflag attrs[3] = 0 # lflag attrs[4] = BAUD_RATE attrs[5] = BAUD_RATE attrs[6][termios.VMIN] = 0 attrs[6][termios.VTIME] = 0 termios.tcsetattr(fd, termios.TCSANOW, attrs) termios.tcflush(fd, termios.TCIOFLUSH) except Exception: os.close(fd) raise return fd def find_serial_device() -> Optional[str]: forced = os.environ.get("G29_SERIAL_DEV") if forced: return forced if os.path.exists(forced) else None for pattern in SERIAL_CANDIDATES: for path in sorted(glob.glob(pattern)): if os.path.exists(path): return path return None def bind_udp_socket() -> tuple[socket.socket, str]: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Attendre brièvement au démarrage que usb0 (192.168.1.1) soit configurée avant fallback for attempt in range(5): try: sock.bind((BIND_IP, UDP_PORT)) sock.setblocking(False) return sock, BIND_IP except OSError as exc: if attempt < 4: time.sleep(0.5) else: print( f"[radxa_g29_relay] Bind {BIND_IP}:{UDP_PORT} impossible ({exc}), fallback 0.0.0.0", file=sys.stderr, flush=True, ) sock.bind(("0.0.0.0", UDP_PORT)) sock.setblocking(False) return sock, "0.0.0.0" def close_serial(serial_fd: Optional[int]) -> None: if serial_fd is not None: try: os.close(serial_fd) except OSError: pass def is_allowed_peer(ip: str, casque_ip: str = CASQUE_IP) -> bool: return ip in (casque_ip, "127.0.0.1") def build_pong_reply(line: bytes, serial_connected: bool) -> Optional[bytes]: """Répond à `$PING,[*CRC]` par `$PONG,,\\n` (diagnostic RTT + UART).""" if not line.startswith(b"$PING,"): return None body = line.split(b"*", 1)[0] parts = body.split(b",", 1) seq = parts[1].strip() if len(parts) == 2 else b"0" if not seq or len(seq) > 20 or not seq.isdigit(): return None uart_flag = b"1" if serial_connected else b"0" return b"$PONG," + seq + b"," + uart_flag + b"\n" def filter_inbound_lines(data: bytes) -> tuple[list[bytes], list[bytes]]: """Sépare les lignes entrantes en (lignes_uart_autorisées, lignes_ping).""" uart_lines: list[bytes] = [] ping_lines: list[bytes] = [] for raw_line in data.splitlines(): line = raw_line.strip() if not line: continue if line.startswith(b"$PING,"): ping_lines.append(line) elif line.startswith(ALLOWED_INBOUND_PREFIXES): uart_lines.append(line + b"\n") return uart_lines, ping_lines def enqueue_tx_payload(serial_tx_buf: bytearray, payload: bytes, max_buf: int = MAX_SERIAL_TX_BUF) -> None: if len(serial_tx_buf) + len(payload) > max_buf: # Préférer la trame la plus récente en cas de saturation UART serial_tx_buf.clear() serial_tx_buf.extend(payload) def extract_outbound_serial_lines(serial_rx_buf: bytearray, max_buf: int = MAX_SERIAL_RX_BUF) -> list[bytes]: """Extrait les trames `$G29*` / `$CRSF*` complètes depuis le tampon série avec protection anti-OOM.""" if len(serial_rx_buf) > max_buf: del serial_rx_buf[:-512] out: list[bytes] = [] while b"\n" in serial_rx_buf: nl_idx = serial_rx_buf.index(b"\n") line = bytes(serial_rx_buf[: nl_idx + 1]).strip() del serial_rx_buf[: nl_idx + 1] if line.startswith((b"$G29", b"$CRSF")): out.append(line + b"\n") return out def main() -> None: sock, bound_ip = bind_udp_socket() print( f"[radxa_g29_relay] UDP {bound_ip}:{UDP_PORT} <-> {CASQUE_IP}:{UDP_PORT} (filtre IP + protocole $ actif)", flush=True, ) serial_fd: Optional[int] = None serial_rx_buf = bytearray() serial_tx_buf = bytearray() last_casque_addr = (CASQUE_IP, UDP_PORT) last_udp_err_log = 0.0 last_serial_scan = 0.0 while True: if serial_fd is None: now = time.monotonic() if now - last_serial_scan >= 0.5: last_serial_scan = now dev = find_serial_device() if dev is not None: try: serial_fd = open_serial(dev) serial_rx_buf.clear() serial_tx_buf.clear() print(f"[radxa_g29_relay] Connecté à la RP2350 sur {dev}", flush=True) except OSError as exc: print(f"[radxa_g29_relay] Erreur ouverture {dev}: {exc}", file=sys.stderr, flush=True) serial_fd = None rlist = [sock.fileno()] + ([serial_fd] if serial_fd is not None else []) wlist = [serial_fd] if (serial_fd is not None and serial_tx_buf) else [] try: readable, writable, _ = select.select(rlist, wlist, [], 0.25) except (OSError, ValueError): close_serial(serial_fd) serial_fd = None continue # 1. Réception UDP depuis le casque -> file d'émission UART + réponse $PING/$PONG immédiate if sock.fileno() in readable: while True: try: data, addr = sock.recvfrom(1024) except BlockingIOError: break except OSError: break if not is_allowed_peer(addr[0]): continue last_casque_addr = (addr[0], UDP_PORT) uart_lines, ping_lines = filter_inbound_lines(data) for pline in ping_lines: pong = build_pong_reply(pline, serial_fd is not None) if pong is not None: try: sock.sendto(pong, (addr[0], addr[1])) except OSError: pass if serial_fd is not None: for payload in uart_lines: enqueue_tx_payload(serial_tx_buf, payload) # 2. Vidange non-bloquante de la file TX vers la RP2350 (gère écritures partielles et EAGAIN) if serial_fd is not None and serial_tx_buf and (serial_fd in writable or sock.fileno() in readable): try: written = os.write(serial_fd, serial_tx_buf) if written > 0: del serial_tx_buf[:written] except BlockingIOError: pass except OSError as exc: if exc.errno not in (errno.EAGAIN, errno.EWOULDBLOCK): close_serial(serial_fd) serial_fd = None print(f"[radxa_g29_relay] Erreur écriture RP2350 ({exc}), reconnexion...", flush=True) continue # 3. Lecture non-bloquante depuis la RP2350 -> émission UDP vers le casque if serial_fd is not None and serial_fd in readable: try: chunk = os.read(serial_fd, 512) if not chunk: raise OSError("EOF série") serial_rx_buf.extend(chunk) for outbound in extract_outbound_serial_lines(serial_rx_buf): try: sock.sendto(outbound, last_casque_addr) except OSError as exc: # Une panne réseau usb0 (casque débranché) ne doit JAMAIS fermer le port série RP2350 now = time.monotonic() if now - last_udp_err_log >= 5.0: last_udp_err_log = now print( f"[radxa_g29_relay] Casque {last_casque_addr[0]} injoignable ({exc})", file=sys.stderr, flush=True, ) except BlockingIOError: pass except OSError as exc: if exc.errno not in (errno.EAGAIN, errno.EWOULDBLOCK): close_serial(serial_fd) serial_fd = None print("[radxa_g29_relay] Liaison RP2350 perdue, attente reconnexion...", flush=True) if __name__ == "__main__": main()