Files
SteamFrame-FPV-Control-Center/scripts/radxa_g29_relay.py
T

224 lines
8.1 KiB
Python
Executable File

#!/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 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
while True:
if serial_fd is None:
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
time.sleep(1.0)
continue
else:
time.sleep(0.5)
continue
rlist = [sock.fileno(), serial_fd]
wlist = [serial_fd] if 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 (filtrée et non-bloquante)
if sock.fileno() in readable:
while True:
try:
data, addr = sock.recvfrom(1024)
except BlockingIOError:
break
except OSError:
break
if addr[0] not in (CASQUE_IP, "127.0.0.1"):
continue
last_casque_addr = (addr[0], UDP_PORT)
for raw_line in data.splitlines():
line = raw_line.strip()
if not line or not line.startswith(ALLOWED_INBOUND_PREFIXES):
continue
payload = line + b"\n"
if len(serial_tx_buf) + len(payload) > MAX_SERIAL_TX_BUF:
# Préférer la trame la plus récente en cas de saturation UART
serial_tx_buf.clear()
serial_tx_buf.extend(payload)
# 2. Vidange non-bloquante de la file TX vers la RP2350 (gère écritures partielles et EAGAIN)
if 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)
if len(serial_rx_buf) > MAX_SERIAL_RX_BUF:
# Protection anti-OOM si bruit série sans retour à la ligne
del serial_rx_buf[:-512]
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")):
try:
sock.sendto(line + b"\n", 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()