feat(terrain,ci): add lost-model GPS, GPX trace, inclinometer, throttle expo/crawl, relay ping, log rotation & release CI

This commit is contained in:
bleackstorm committed 2026-11-26 12:15:20 +01:00
1 parent c83f90570f
commit 9f0c64f873
20 files changed
+926 -78

No files matched your search

+96 -49
View File
@@ -106,6 +106,59 @@ def close_serial(serial_fd: Optional[int]) -> None:
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,<seq>[*CRC]` par `$PONG,<seq>,<serial_ok>\\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(
@@ -118,27 +171,26 @@ def main() -> None:
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:
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
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]
wlist = [serial_fd] if serial_tx_buf else []
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):
@@ -146,7 +198,7 @@ def main() -> None:
serial_fd = None
continue
# 1. Réception UDP depuis le casque -> file d'émission UART (filtrée et non-bloquante)
# 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:
@@ -155,21 +207,23 @@ def main() -> None:
break
except OSError:
break
if addr[0] not in (CASQUE_IP, "127.0.0.1"):
if not is_allowed_peer(addr[0]):
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)
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_tx_buf and (serial_fd in writable or sock.fileno() in readable):
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:
@@ -190,26 +244,19 @@ def main() -> None:
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,
)
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:
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Tests unitaires pour le relais série <-> UDP Radxa Zero 3W (radxa_g29_relay.py)."""
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import radxa_g29_relay as relay
class TestRadxaG29Relay(unittest.TestCase):
def test_is_allowed_peer(self) -> None:
self.assertTrue(relay.is_allowed_peer("192.168.1.10", "192.168.1.10"))
self.assertTrue(relay.is_allowed_peer("127.0.0.1", "192.168.1.10"))
self.assertFalse(relay.is_allowed_peer("192.168.1.99", "192.168.1.10"))
self.assertFalse(relay.is_allowed_peer("10.0.0.5", "192.168.1.10"))
def test_filter_inbound_blocks_cli_and_accepts_protocol(self) -> None:
raw = (
b"B\n"
b"R\n"
b"$HT,992,992,992*AB\n"
b"$RC,992,1065,992,992,1,2*12\n"
b"$SRC,EXT*34\n"
b"$GEARS,1065,1100,1150,1220,905,800*56\n"
b"$PING,42\n"
b"DROP TABLE\n"
)
uart_lines, ping_lines = relay.filter_inbound_lines(raw)
self.assertEqual(
uart_lines,
[
b"$HT,992,992,992*AB\n",
b"$RC,992,1065,992,992,1,2*12\n",
b"$SRC,EXT*34\n",
b"$GEARS,1065,1100,1150,1220,905,800*56\n",
],
)
self.assertEqual(ping_lines, [b"$PING,42"])
def test_build_pong_reply(self) -> None:
self.assertEqual(relay.build_pong_reply(b"$PING,123", True), b"$PONG,123,1\n")
self.assertEqual(relay.build_pong_reply(b"$PING,7*FF", False), b"$PONG,7,0\n")
self.assertIsNone(relay.build_pong_reply(b"$PING,abc", True))
self.assertIsNone(relay.build_pong_reply(b"$HT,992,992,992", True))
def test_enqueue_tx_payload_drops_stale_on_overflow(self) -> None:
buf = bytearray(b"A" * 10)
relay.enqueue_tx_payload(buf, b"$HT,1,2,3\n", max_buf=15)
self.assertEqual(bytes(buf), b"$HT,1,2,3\n")
def test_extract_outbound_serial_lines_filters_and_protects_oom(self) -> None:
rx = bytearray(
b"DEBUG boot ok\n"
b"$G29,ARM=1,GEAR=2\n"
b"$CRSF,C80A1400\n"
b"$G29_EVT,CROSS\n"
b"PARTIAL"
)
lines = relay.extract_outbound_serial_lines(rx)
self.assertEqual(
lines,
[
b"$G29,ARM=1,GEAR=2\n",
b"$CRSF,C80A1400\n",
b"$G29_EVT,CROSS\n",
],
)
self.assertEqual(bytes(rx), b"PARTIAL")
# Anti-OOM sur bruit série sans \n
noisy = bytearray(b"X" * 5000)
self.assertEqual(relay.extract_outbound_serial_lines(noisy, max_buf=4096), [])
self.assertEqual(len(noisy), 512)
if __name__ == "__main__":
unittest.main()