#!/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 json import os import select import socket import sys import termios import time from typing import Any, 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")) WFB_STATS_PORT = int(os.environ.get("WFB_STATS_PORT", "8003")) VRX_PUBLISH_INTERVAL_S = 0.5 THERMAL_ZONE_PATH = "/sys/class/thermal/thermal_zone0/temp" 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 read_soc_temp_c(path: str = THERMAL_ZONE_PATH) -> float: """Lit la température du SoC Radxa (en °C) depuis sysfs, ou -1.0 si indisponible.""" try: with open(path, "r", encoding="ascii") as f: raw = f.read().strip() val = float(raw) return val / 1000.0 if val > 200.0 else val except (OSError, ValueError): return -1.0 def parse_wfb_json_line(raw_line: str) -> Optional[dict[str, int]]: """Extrait RSSI antennes, FEC réparés/perdus et débit kbps depuis une ligne JSON `wfb_rx`.""" try: obj: Any = json.loads(raw_line) except (ValueError, TypeError): return None if not isinstance(obj, dict): return None if obj.get("type") not in (None, "rx"): return None rssi_vals: list[int] = [] ant_stats = obj.get("rx_ant_stats") if isinstance(ant_stats, dict): for entry in ant_stats.values(): if isinstance(entry, list) and len(entry) >= 3: try: rssi_vals.append(int(entry[2])) except (TypeError, ValueError): pass elif isinstance(entry, dict) and "rssi_avg" in entry: try: rssi_vals.append(int(entry["rssi_avg"])) except (TypeError, ValueError): pass rssi_a = rssi_vals[0] if len(rssi_vals) >= 1 else int(obj.get("rssi_a", -127)) rssi_b = rssi_vals[1] if len(rssi_vals) >= 2 else int(obj.get("rssi_b", -127)) packets = obj.get("packets") fec_rec = 0 fec_lost = 0 kbps = 0 if isinstance(packets, dict): def _delta(key: str) -> int: v = packets.get(key) if isinstance(v, list) and v: return int(v[0]) if isinstance(v, (int, float)): return int(v) return 0 fec_rec = max(0, _delta("fec_rec")) fec_lost = max(0, _delta("lost")) incoming_bytes = max(0, _delta("incoming_bytes") or _delta("out_bytes")) kbps = (incoming_bytes * 8) // 1000 else: fec_rec = max(0, int(obj.get("fec_rec", 0))) fec_lost = max(0, int(obj.get("fec_lost", 0))) kbps = max(0, int(obj.get("kbps", 0))) return { "rssi_a": max(-127, min(0, rssi_a)), "rssi_b": max(-127, min(0, rssi_b)), "fec_rec": fec_rec, "fec_lost": fec_lost, "kbps": kbps, } def format_vrx_line( temp_c: float, rssi_a: int, rssi_b: int, fec_rec: int, fec_lost: int, kbps: int, ) -> bytes: return f"$VRX,{temp_c:.1f},{rssi_a},{rssi_b},{fec_rec},{fec_lost},{kbps}\n".encode("ascii") class WfbStatsPoller: """Client TCP non-bloquant vers l'API stats JSON locale de `wfb_rx` (port 8003).""" def __init__(self, port: int = WFB_STATS_PORT) -> None: self.port = port self.sock: Optional[socket.socket] = None self.buf = "" self.last_connect_try = 0.0 self.latest: dict[str, int] = { "rssi_a": -127, "rssi_b": -127, "fec_rec": 0, "fec_lost": 0, "kbps": 0, } def _close(self) -> None: if self.sock is not None: try: self.sock.close() except OSError: pass self.sock = None self.buf = "" def poll(self, now: float) -> dict[str, int]: if self.sock is None: if now - self.last_connect_try >= 2.0: self.last_connect_try = now try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(False) err = s.connect_ex(("127.0.0.1", self.port)) if err in (0, errno.EINPROGRESS, errno.EALREADY): self.sock = s else: s.close() except OSError: pass return self.latest try: chunk = self.sock.recv(4096) if not chunk: self._close() return self.latest self.buf += chunk.decode("utf-8", errors="ignore") if len(self.buf) > 16384: self.buf = self.buf[-4096:] while "\n" in self.buf: line, self.buf = self.buf.split("\n", 1) parsed = parse_wfb_json_line(line.strip()) if parsed is not None: self.latest = parsed except BlockingIOError: pass except OSError: self._close() return self.latest 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 last_vrx_publish = 0.0 wfb_poller = WfbStatsPoller() 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) # 4. Publication périodique (2 Hz) des stats VRX Radxa ($VRX : température SoC + wfb_rx) now_vrx = time.monotonic() if now_vrx - last_vrx_publish >= VRX_PUBLISH_INTERVAL_S: last_vrx_publish = now_vrx stats = wfb_poller.poll(now_vrx) temp_c = read_soc_temp_c() vrx_line = format_vrx_line( temp_c, stats["rssi_a"], stats["rssi_b"], stats["fec_rec"], stats["fec_lost"], stats["kbps"], ) try: sock.sendto(vrx_line, last_casque_addr) except OSError: pass if __name__ == "__main__": main()