From 9f0c64f873b0be0691149da1ff124c67a0fed8bc Mon Sep 17 00:00:00 2001 From: bleackstorm Date: Thu, 26 Nov 2026 12:15:20 +0100 Subject: [PATCH] feat(terrain,ci): add lost-model GPS, GPX trace, inclinometer, throttle expo/crawl, relay ping, log rotation & release CI --- .github/workflows/ci.yml | 6 +- .github/workflows/release.yml | 115 ++++++++++++++++++++ .gitignore | 3 + scripts/radxa_g29_relay.py | 145 +++++++++++++++++--------- scripts/test_radxa_g29_relay.py | 79 ++++++++++++++ src/config.rs | 15 +++ src/controller/gearbox.rs | 58 +++++++++-- src/controller/mod.rs | 13 ++- src/dvr.rs | 91 ++++++++++++++++ src/engine/control_handle.rs | 49 +++++++++ src/engine/mod.rs | 15 +++ src/engine/types.rs | 2 + src/g29_bridge.rs | 51 +++++++++ src/logger.rs | 94 ++++++++++++++--- src/telemetry_osd/osd.rs | 39 +++++++ src/telemetry_osd/parser.rs | 4 + src/telemetry_osd/state.rs | 21 ++++ src/ui/mod.rs | 8 +- src/ui/settings/controls_profiles.rs | 46 ++++++++ src/ui/telemetry.rs | 150 ++++++++++++++++++++++++++- 20 files changed, 926 insertions(+), 78 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 scripts/test_radxa_g29_relay.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab36952..c00a052 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,8 +56,10 @@ jobs: - name: Validate shell scripts syntax (bash -n) run: bash -n launch.sh launch_vr.sh scripts/*.sh - - name: Validate Python relay syntax (py_compile) - run: python3 -m py_compile scripts/radxa_g29_relay.py + - name: Validate Python relay syntax & unit tests + run: | + python3 -m py_compile scripts/radxa_g29_relay.py scripts/test_radxa_g29_relay.py + python3 -m unittest discover -s scripts -p "test_*.py" -v firmware-rp2350: name: Firmware RP2350 (g29_crsf.ino) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..826094e --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,115 @@ +name: Release + +on: + push: + tags: + - "v*" + workflow_dispatch: + +permissions: + contents: write + +env: + CARGO_TERM_COLOR: always + +jobs: + build-linux-x86_64: + name: Build Linux x86_64 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install native Linux dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + build-essential pkg-config \ + libglib2.0-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \ + libxkbcommon-dev libxkbcommon-x11-dev libwayland-dev \ + libvulkan-dev libopenxr-dev libgl1-mesa-dev libfontconfig1-dev + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Build release binary (x86_64) + run: cargo build --release --locked + - name: Package tarball + run: | + mkdir -p dist/steamframe-fpv-linux-x86_64 + cp target/release/steamframe-fpv launch.sh launch_vr.sh steamframe-fpv.desktop steamframe-fpv-vr.desktop dist/steamframe-fpv-linux-x86_64/ + cp -r scripts dist/steamframe-fpv-linux-x86_64/ + tar -C dist -czf "dist/steamframe-fpv-${GITHUB_REF_NAME}-linux-x86_64.tar.gz" steamframe-fpv-linux-x86_64 + - uses: actions/upload-artifact@v4 + with: + name: steamframe-fpv-linux-x86_64 + path: dist/steamframe-fpv-*-linux-x86_64.tar.gz + + build-linux-arm64: + name: Build Steam Frame ARM64 (aarch64) + runs-on: ubuntu-24.04-arm + steps: + - uses: actions/checkout@v4 + - name: Install native ARM64 dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + build-essential pkg-config \ + libglib2.0-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \ + libxkbcommon-dev libxkbcommon-x11-dev libwayland-dev \ + libvulkan-dev libopenxr-dev libgl1-mesa-dev libfontconfig1-dev + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Build release binary (aarch64) + run: cargo build --release --locked + - name: Package tarball + run: | + mkdir -p dist/steamframe-fpv-linux-aarch64 + cp target/release/steamframe-fpv launch.sh launch_vr.sh steamframe-fpv.desktop steamframe-fpv-vr.desktop dist/steamframe-fpv-linux-aarch64/ + cp -r scripts dist/steamframe-fpv-linux-aarch64/ + tar -C dist -czf "dist/steamframe-fpv-${GITHUB_REF_NAME}-linux-aarch64.tar.gz" steamframe-fpv-linux-aarch64 + - uses: actions/upload-artifact@v4 + with: + name: steamframe-fpv-linux-aarch64 + path: dist/steamframe-fpv-*-linux-aarch64.tar.gz + + build-firmware-rp2350: + name: Build Firmware RP2350 (.uf2) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install arduino-cli, rp2040 core and firmware libraries + run: | + mkdir -p "$HOME/.local/bin" + curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR="$HOME/.local/bin" sh + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + "$HOME/.local/bin/arduino-cli" config init + "$HOME/.local/bin/arduino-cli" config set board_manager.additional_urls \ + https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json + "$HOME/.local/bin/arduino-cli" core update-index + "$HOME/.local/bin/arduino-cli" core install rp2040:rp2040 + "$HOME/.local/bin/arduino-cli" lib install "Pico PIO USB" "Adafruit NeoPixel" + - name: Compile g29_crsf firmware (.uf2) + run: | + mkdir -p dist/firmware + arduino-cli compile \ + --fqbn rp2040:rp2040:waveshare_rp2350_plus:usbstack=tinyusb \ + --output-dir dist/firmware \ + firmware/g29_crsf + mv dist/firmware/g29_crsf.ino.uf2 "dist/firmware/g29_crsf-${GITHUB_REF_NAME}-waveshare_rp2350_plus.uf2" + - uses: actions/upload-artifact@v4 + with: + name: firmware-rp2350 + path: dist/firmware/*.uf2 + + publish-release: + name: Publish GitHub Release + needs: [build-linux-x86_64, build-linux-arm64, build-firmware-rp2350] + if: startsWith(github.ref, 'refs/tags/v') + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v4 + with: + path: release-assets + merge-multiple: true + - name: Create GitHub Release + uses: softprops/action-gh-release@v2 + with: + generate_release_notes: true + files: release-assets/* diff --git a/.gitignore b/.gitignore index 900377d..7de017b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,13 @@ /target target/ *.log +*.log.old steamframe_fpv.log +steamframe_fpv.log.old *.bin dist/ recordings/ +graphify-out/ .DS_Store __pycache__/ *.pyc diff --git a/scripts/radxa_g29_relay.py b/scripts/radxa_g29_relay.py index 5919618..4b8ee64 100755 --- a/scripts/radxa_g29_relay.py +++ b/scripts/radxa_g29_relay.py @@ -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,[*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( @@ -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: diff --git a/scripts/test_radxa_g29_relay.py b/scripts/test_radxa_g29_relay.py new file mode 100644 index 0000000..ccb27be --- /dev/null +++ b/scripts/test_radxa_g29_relay.py @@ -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() diff --git a/src/config.rs b/src/config.rs index ab5e896..40dc0a2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -72,6 +72,14 @@ pub struct AppConfig { #[arg(long, default_value_t = false)] pub controller_invert_steering: bool, + /// Courbe exponentielle de la gâchette de gaz Steam Controller (0.0 = linéaire, 0.5 = crawler doux, max 0.8) + #[arg(long, default_value_t = 0.0)] + pub controller_throttle_expo: f32, + + /// Mode Précision / Rampant (plafonne la course des gaz à 50 % pour les franchissements techniques) + #[arg(long, default_value_t = false)] + pub controller_crawl_mode: bool, + /// Intensité des vibrations haptiques du Steam Controller (0 = désactivé, 1..=100%) #[arg(long, default_value_t = 100)] pub controller_vibration: u8, @@ -586,6 +594,8 @@ impl AppConfig { controller_expo = {:.3}\n\ controller_deadzone = {:.3}\n\ controller_invert_steering = {}\n\ + controller_throttle_expo = {:.3}\n\ + controller_crawl_mode = {}\n\ controller_vibration = {}\n\ gaz_avant_min = {}\n\ gear_1_max = {}\n\ @@ -642,6 +652,8 @@ impl AppConfig { self.controller_expo, self.controller_deadzone, self.controller_invert_steering, + self.controller_throttle_expo, + self.controller_crawl_mode, self.controller_vibration, self.gaz_avant_min, self.gear_1_max, @@ -785,6 +797,8 @@ impl AppConfig { load_parse!(controller_expo); load_parse!(controller_deadzone); load_parse!(controller_invert_steering); + load_parse!(controller_throttle_expo); + load_parse!(controller_crawl_mode); load_parse!(controller_vibration); load_parse!(gaz_avant_min); load_parse!(gear_1_max); @@ -818,6 +832,7 @@ impl AppConfig { self.lens_k1 = self.lens_k1.clamp(-0.50, 0.25); self.screen_distance_m = self.screen_distance_m.clamp(0.5, 5.0); self.controller_vibration = self.controller_vibration.min(100); + self.controller_throttle_expo = self.controller_throttle_expo.clamp(0.0, 0.8); self.battery_cells = self.battery_cells.min(6); self.battery_warn_cell_v = self.battery_warn_cell_v.clamp(3.0, 4.2); self.battery_crit_cell_v = self.battery_crit_cell_v.clamp(2.8, self.battery_warn_cell_v); diff --git a/src/controller/gearbox.rs b/src/controller/gearbox.rs index b468771..8e5fea0 100644 --- a/src/controller/gearbox.rs +++ b/src/controller/gearbox.rs @@ -38,10 +38,13 @@ pub fn steering_to_crsf(raw_norm: f32, deadzone: f32, expo: f32, invert: bool) - (crsf.round() as u16).clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX) } -/// Normalise une gâchette [0.0..1.0] avec zone morte et calcule le canal gaz CRSF selon la boîte séquentielle. -pub fn throttle_to_crsf( +/// Normalise une gâchette [0.0..1.0] avec zone morte, courbe expo cubique [0.0..0.8] et multiplicateur +/// de vitesse (ex. 0.5 en mode Précision/Rampant), puis calcule le canal gaz CRSF selon la boîte séquentielle. +pub fn throttle_to_crsf_curved( throttle_norm: f32, deadzone: f32, + expo: f32, + speed_scale: f32, armed: bool, gear: i8, limits: GearSpeedLimits, @@ -60,20 +63,31 @@ pub fn throttle_to_crsf( } else { ((clamped - dz) / (1.0 - dz)).clamp(0.0, 1.0) }; - let pct = (active * 100.0).round() as u8; + let e = if expo.is_finite() { + expo.clamp(0.0, 0.8) + } else { + 0.0 + }; + let scale = if speed_scale.is_finite() { + speed_scale.clamp(0.25, 1.0) + } else { + 1.0 + }; + let curved = (active * (1.0 - e + e * active * active) * scale).clamp(0.0, 1.0); + let pct = (curved * 100.0).round() as u8; - if !armed || active <= 0.0 || gear == 0 { + if !armed || curved <= 0.0 || gear == 0 { return (pct, CRSF_CHANNEL_MID); } let s = limits.sanitized(); let crsf = if gear == -1 { let span = s.reverse_min as f32 - s.reverse_max as f32; - (s.reverse_min as f32 - active * span).round() as u16 + (s.reverse_min as f32 - curved * span).round() as u16 } else if (1..=3).contains(&gear) { let max_v = s.forward_max[(gear - 1) as usize]; let span = max_v as f32 - s.forward_min as f32; - (s.forward_min as f32 + active * span).round() as u16 + (s.forward_min as f32 + curved * span).round() as u16 } else { CRSF_CHANNEL_MID }; @@ -81,6 +95,17 @@ pub fn throttle_to_crsf( (pct, crsf.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX)) } +/// Normalise une gâchette [0.0..1.0] avec zone morte et calcule le canal gaz CRSF selon la boîte séquentielle. +pub fn throttle_to_crsf( + throttle_norm: f32, + deadzone: f32, + armed: bool, + gear: i8, + limits: GearSpeedLimits, +) -> (u8, u16) { + throttle_to_crsf_curved(throttle_norm, deadzone, 0.0, 1.0, armed, gear, limits) +} + /// Normalise la gâchette frein [0.0..1.0] et convertit en CRSF (992..1811). pub fn brake_to_crsf(brake_norm: f32, deadzone: f32) -> (u8, u16) { if !brake_norm.is_finite() { @@ -142,3 +167,24 @@ pub fn encode_rc_frame( gear.clamp(-1, 3), )) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn throttle_expo_and_crawl_mode_soften_curve() { + let limits = GearSpeedLimits::default(); + let (pct_lin, crsf_lin) = throttle_to_crsf_curved(0.5, 0.0, 0.0, 1.0, true, 3, limits); + let (pct_expo, crsf_expo) = throttle_to_crsf_curved(0.5, 0.0, 0.5, 1.0, true, 3, limits); + let (pct_crawl, crsf_crawl) = throttle_to_crsf_curved(1.0, 0.0, 0.0, 0.5, true, 3, limits); + + assert_eq!(pct_lin, 50); + // Avec expo 0.5 à mi-course : 0.5 * (0.5 + 0.5 * 0.25) = 0.3125 -> 31 % + assert_eq!(pct_expo, 31); + assert!(crsf_expo < crsf_lin); + // Mode Précision (50 %) plein gaz -> moitié de la course + assert_eq!(pct_crawl, 50); + assert_eq!(crsf_crawl, crsf_lin); + } +} diff --git a/src/controller/mod.rs b/src/controller/mod.rs index a6bce50..90dc417 100644 --- a/src/controller/mod.rs +++ b/src/controller/mod.rs @@ -6,7 +6,7 @@ mod types; pub use gearbox::{ brake_to_crsf, encode_gears_command, encode_rc_frame, encode_src_command, steering_to_crsf, - throttle_to_crsf, + throttle_to_crsf, throttle_to_crsf_curved, }; #[cfg(test)] use haptics::encode_ibex_rumble_report; @@ -362,14 +362,19 @@ impl SteamControllerWorker { CRSF_CHANNEL_MID }; + let throttle_expo = control.throttle_expo(); + let speed_scale = if control.crawl_mode() { 0.5 } else { 1.0 }; + if desired_source == ControlSource::SteamController { // Mode actif : armement, boîte séquentielle, raccourcis cockpit et émission $RC 100 Hz let mut deferred_actions: Vec = Vec::new(); let (armed, gear, throttle_crsf) = { let mut st = state.lock(); - let (pre_throt_pct, _) = throttle_to_crsf( + let (pre_throt_pct, _) = throttle_to_crsf_curved( throttle_norm, cfg.trigger_deadzone, + throttle_expo, + speed_scale, st.armed, st.gear, current_gears, @@ -400,9 +405,11 @@ impl SteamControllerWorker { st.last_button_at = Some(Instant::now()); } - let (throt_pct, throt_crsf) = throttle_to_crsf( + let (throt_pct, throt_crsf) = throttle_to_crsf_curved( throttle_norm, cfg.trigger_deadzone, + throttle_expo, + speed_scale, st.armed, st.gear, current_gears, diff --git a/src/dvr.rs b/src/dvr.rs index b3f9540..97b1ec7 100644 --- a/src/dvr.rs +++ b/src/dvr.rs @@ -154,6 +154,78 @@ impl SrtWriterState { } } +/// Écrivain de trace GPS `.gpx` 1.1 compagnon du fichier DVR (throttlé ~1 Hz, supprimé si 0 point GPS). +struct GpxWriterState { + writer: Option>, + path: PathBuf, + points: u32, + last_emit: Option, +} + +impl GpxWriterState { + fn open_for_video(video_path: &Path) -> Self { + let gpx_path = video_path.with_extension("gpx"); + let mut writer = File::create(&gpx_path).ok().map(BufWriter::new); + if let Some(ref mut w) = writer { + let name = video_path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("steamframe_fpv"); + let _ = writeln!( + w, + "\n\ + \n\ + \n\ + {}\n\ + ", + name + ); + } + Self { + writer, + path: gpx_path, + points: 0, + last_emit: None, + } + } + + fn push_point(&mut self, lat_deg: f64, lon_deg: f64, alt_m: f32) { + if !lat_deg.is_finite() || !lon_deg.is_finite() || (lat_deg.abs() < 1e-4 && lon_deg.abs() < 1e-4) { + return; + } + if let Some(last) = self.last_emit { + if last.elapsed() < Duration::from_millis(950) { + return; + } + } + self.last_emit = Some(Instant::now()); + if let Some(ref mut w) = self.writer { + let iso_utc = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"); + let ele = if alt_m.is_finite() { alt_m } else { 0.0 }; + if writeln!( + w, + " {:.1}", + lat_deg, lon_deg, ele, iso_utc + ) + .is_ok() + { + self.points = self.points.saturating_add(1); + } + } + } + + fn finish(&mut self) { + if let Some(ref mut w) = self.writer { + let _ = writeln!(w, " \n \n"); + let _ = w.flush(); + } + self.writer = None; + if self.points == 0 { + let _ = fs::remove_file(&self.path); + } + } +} + /// Détecte si un paquet bitstream H.264 ou H.265 contient une image clé (IDR / SPS / IRAP / VPS). pub fn detect_keyframe(bytes: &[u8], codec: &str, gst_is_delta: bool) -> bool { if !gst_is_delta { @@ -424,6 +496,7 @@ pub struct DvrRecorder { frames_recorded: Arc, is_recording: Arc, srt_writer: Mutex, + gpx_writer: Mutex, } impl DvrRecorder { @@ -557,6 +630,7 @@ impl DvrRecorder { .map_err(|e| anyhow!("Impossible de démarrer le pipeline DVR : {}", e))?; let srt_writer = Mutex::new(SrtWriterState::open_for_video(&file_path)); + let gpx_writer = Mutex::new(GpxWriterState::open_for_video(&file_path)); Ok(Arc::new(Self { pipeline, @@ -568,6 +642,7 @@ impl DvrRecorder { frames_recorded: Arc::new(AtomicU64::new(0)), is_recording: Arc::new(AtomicBool::new(true)), srt_writer, + gpx_writer, })) } @@ -628,6 +703,14 @@ impl DvrRecorder { self.srt_writer.lock().push_caption(elapsed_ms, caption); } + /// Enregistre un point GPS dans la trace `.gpx` compagnon (throttlé ~1 Hz). + pub fn push_gps_point(&self, lat_deg: f64, lon_deg: f64, alt_m: f32) { + if !self.is_recording.load(Ordering::Acquire) { + return; + } + self.gpx_writer.lock().push_point(lat_deg, lon_deg, alt_m); + } + /// Sonde le bus GStreamer (non-bloquant) et rafraîchit la taille réelle du fichier sur disque. fn poll_health_and_size(&self) { if let Some(bus) = self.pipeline.bus() { @@ -708,6 +791,7 @@ impl DvrRecorder { let end_ms = self.start_time.elapsed().as_millis() as u64; self.srt_writer.lock().finish(end_ms); + self.gpx_writer.lock().finish(); let _ = self.appsrc.end_of_stream(); @@ -810,6 +894,7 @@ mod tests { let dvr = DvrRecorder::start_composited_osd(&dir, DvrContainer::Mkv, 320, 240) .expect("start dvr failed"); dvr.push_telemetry_caption("BAT 15.2V (3.80V/c) | LQ 99% | G2 | 24 km/h"); + dvr.push_gps_point(48.856614, 2.3522219, 35.4); let fake_rgba = vec![0u8; 320 * 240 * 4]; for _ in 0..10 { dvr.push_slice(&fake_rgba); @@ -817,12 +902,18 @@ mod tests { } let path = dvr.file_path().to_path_buf(); let srt_path = path.with_extension("srt"); + let gpx_path = path.with_extension("gpx"); dvr.stop(); assert!(path.exists()); assert!(srt_path.exists()); + assert!(gpx_path.exists()); let srt_content = fs::read_to_string(&srt_path).expect("read srt"); assert!(srt_content.contains("BAT 15.2V")); assert!(srt_content.contains("-->")); + let gpx_content = fs::read_to_string(&gpx_path).expect("read gpx"); + assert!(gpx_content.contains("")); let meta = fs::metadata(&path).expect("file metadata"); assert!(meta.len() > 0); let _ = fs::remove_dir_all(&dir); diff --git a/src/engine/control_handle.rs b/src/engine/control_handle.rs index 10f0e5f..156195c 100644 --- a/src/engine/control_handle.rs +++ b/src/engine/control_handle.rs @@ -42,6 +42,13 @@ impl EngineControlHandle { .shared .controller_invert_steering .load(Ordering::Acquire); + cfg.controller_throttle_expo = + (self.shared.controller_throttle_expo_pct.load(Ordering::Acquire).min(80) as f32) + / 100.0; + cfg.controller_crawl_mode = self + .shared + .controller_crawl_mode + .load(Ordering::Acquire); cfg.gaz_avant_min = limits.forward_min; cfg.gear_1_max = limits.forward_max[0]; cfg.gear_2_max = limits.forward_max[1]; @@ -180,6 +187,48 @@ impl EngineControlHandle { } } + pub fn throttle_expo(&self) -> f32 { + (self + .shared + .controller_throttle_expo_pct + .load(Ordering::Acquire) + .min(80) as f32) + / 100.0 + } + + pub fn set_throttle_expo(&self, expo: f32) { + let pct = (expo.clamp(0.0, 0.8) * 100.0).round() as u8; + let prev = self + .shared + .controller_throttle_expo_pct + .swap(pct, Ordering::AcqRel); + if prev != pct { + log::info!( + "[Action Utilisateur] Expo gaz Steam Controller : {:.2}", + pct as f32 / 100.0 + ); + self.persist_live_config(); + } + } + + pub fn crawl_mode(&self) -> bool { + self.shared.controller_crawl_mode.load(Ordering::Acquire) + } + + pub fn set_crawl_mode(&self, enabled: bool) { + let prev = self + .shared + .controller_crawl_mode + .swap(enabled, Ordering::AcqRel); + if prev != enabled { + log::info!( + "[Action Utilisateur] Mode Précision / Rampant (50%) : {}", + if enabled { "ACTIF" } else { "DÉSACTIVÉ" } + ); + self.persist_live_config(); + } + } + pub fn request_recenter(&self) { *self.shared.head_trim_deg.lock() = (0.0, 0.0); self.shared.recenter_flag.store(true, Ordering::Release); diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 8631751..df9c951 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -69,6 +69,8 @@ impl FpvEngineController { control_source_flag: Arc::new(AtomicU8::new(ControlSource::G29.as_u8())), controller_vibration_pct: Arc::new(AtomicU8::new(100)), controller_invert_steering: Arc::new(AtomicBool::new(false)), + controller_throttle_expo_pct: Arc::new(AtomicU8::new(0)), + controller_crawl_mode: Arc::new(AtomicBool::new(false)), controller_rumble_test: Arc::new(AtomicBool::new(false)), gear_speed_limits: Arc::new(Mutex::new(GearSpeedLimits::default())), preview_active_flag: Arc::new(AtomicBool::new(true)), @@ -169,6 +171,12 @@ impl FpvEngineController { self.shared .controller_invert_steering .store(cfg.controller_invert_steering, Ordering::Relaxed); + self.shared + .controller_throttle_expo_pct + .store((cfg.controller_throttle_expo.clamp(0.0, 0.8) * 100.0).round() as u8, Ordering::Relaxed); + self.shared + .controller_crawl_mode + .store(cfg.controller_crawl_mode, Ordering::Relaxed); self.shared .controller_rumble_test .store(false, Ordering::Relaxed); @@ -726,6 +734,13 @@ pub fn compose_osd_and_publish( if !caption.is_empty() { if let Some(ref dvr) = *ctx.active_dvr { dvr.push_telemetry_caption(&caption); + if telem_snapshot.gps_fix_valid { + dvr.push_gps_point( + telem_snapshot.gps_lat_deg, + telem_snapshot.gps_lon_deg, + telem_snapshot.gps_alt_m, + ); + } } ctx.shared.replay_buffer.push_caption(caption); } diff --git a/src/engine/types.rs b/src/engine/types.rs index b393162..d9b4201 100644 --- a/src/engine/types.rs +++ b/src/engine/types.rs @@ -137,6 +137,8 @@ pub struct EngineSharedState { pub control_source_flag: Arc, pub controller_vibration_pct: Arc, pub controller_invert_steering: Arc, + pub controller_throttle_expo_pct: Arc, + pub controller_crawl_mode: Arc, pub controller_rumble_test: Arc, pub gear_speed_limits: Arc>, pub preview_active_flag: Arc, diff --git a/src/g29_bridge.rs b/src/g29_bridge.rs index aa9a503..37c0bd4 100644 --- a/src/g29_bridge.rs +++ b/src/g29_bridge.rs @@ -240,6 +240,38 @@ impl G29BridgeReceiver { Ok(()) } + /// Ping applicatif UDP vers le relais Radxa Zero 3W (`$PING,` -> `$PONG,,`). + /// Retourne `(rtt_ms, rp2350_uart_connected)`. + pub fn ping_radxa_relay(target_ip: &str, target_port: u16) -> Result<(f32, bool)> { + let socket = UdpSocket::bind("0.0.0.0:0")?; + socket.set_read_timeout(Some(Duration::from_millis(450)))?; + let target = format!("{}:{}", target_ip.trim(), target_port); + let seq: u64 = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64 % 1_000_000) + .unwrap_or(1); + let payload = format!("$PING,{}\n", seq); + let t0 = Instant::now(); + socket.send_to(payload.as_bytes(), &target)?; + let mut buf = [0u8; 128]; + let (len, _) = socket.recv_from(&mut buf)?; + let rtt_ms = t0.elapsed().as_secs_f32() * 1000.0; + let reply = std::str::from_utf8(&buf[..len])?.trim(); + let rest = reply + .strip_prefix("$PONG,") + .ok_or_else(|| anyhow::anyhow!("Réponse inattendue : {}", reply))?; + let mut parts = rest.split(','); + let rx_seq = parts + .next() + .and_then(|s| s.parse::().ok()) + .ok_or_else(|| anyhow::anyhow!("Séquence PONG invalide : {}", reply))?; + if rx_seq != seq { + anyhow::bail!("Séquence PONG discordante ({} != {})", rx_seq, seq); + } + let uart_ok = parts.next().map(|s| s.trim() == "1").unwrap_or(false); + Ok((rtt_ms, uart_ok)) + } + pub fn is_peer_allowed(src_ip: std::net::IpAddr, allowed_peers: &[std::net::IpAddr]) -> bool { src_ip.is_loopback() || allowed_peers.is_empty() || allowed_peers.contains(&src_ip) } @@ -725,4 +757,23 @@ mod tests { assert!(ctrl.is_exit_requested()); assert!(!ctrl.is_vr_menu_open()); } + + #[test] + fn test_ping_radxa_relay_roundtrip() { + let server = UdpSocket::bind("127.0.0.1:0").expect("bind loopback"); + let port = server.local_addr().unwrap().port(); + let handle = thread::spawn(move || { + let mut buf = [0u8; 64]; + let (len, src) = server.recv_from(&mut buf).unwrap(); + let req = std::str::from_utf8(&buf[..len]).unwrap().trim(); + let seq = req.strip_prefix("$PING,").unwrap(); + let pong = format!("$PONG,{},1\n", seq); + server.send_to(pong.as_bytes(), src).unwrap(); + }); + let (rtt_ms, uart_ok) = G29BridgeReceiver::ping_radxa_relay("127.0.0.1", port) + .expect("ping should succeed"); + handle.join().unwrap(); + assert!(rtt_ms >= 0.0 && rtt_ms < 250.0); + assert!(uart_ok); + } } diff --git a/src/logger.rs b/src/logger.rs index dd3b1a1..b6c0a93 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -2,14 +2,17 @@ use chrono::Local; use log::{Level, LevelFilter, Log, Metadata, Record}; use parking_lot::Mutex; use std::collections::VecDeque; -use std::fs::OpenOptions; +use std::fs::{self, File, OpenOptions}; use std::io::{BufWriter, Write}; +use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{self, SyncSender}; use std::sync::Arc; use std::thread; const MAX_LOG_ENTRIES: usize = 1000; +/// Taille maximale du fichier journal avant rotation vers `.old` (5 Mo). +const MAX_LOG_FILE_BYTES: u64 = 5 * 1024 * 1024; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LogFilter { @@ -59,42 +62,64 @@ pub struct GuiLogger { file_tx: Option>, } +/// Ouvre le fichier journal en appliquant une rotation vers `.old` si sa taille atteint `max_bytes`. +fn open_rotated_log_file(path: &str, max_bytes: u64) -> Option<(BufWriter, u64)> { + let p = Path::new(path); + let mut current_size = fs::metadata(p).map(|m| m.len()).unwrap_or(0); + if current_size >= max_bytes { + let backup = format!("{}.old", path); + let _ = fs::remove_file(&backup); + let _ = fs::rename(p, &backup); + current_size = 0; + } + let file = OpenOptions::new() + .create(true) + .append(true) + .open(p) + .ok()?; + Some((BufWriter::new(file), current_size)) +} + impl GuiLogger { pub fn init(log_file_path: &str) -> Arc> { let buffer = Arc::new(Mutex::new(LogBuffer::default())); - - let file_opt = OpenOptions::new() - .create(true) - .append(true) - .open(log_file_path) - .ok(); + let log_path_owned = log_file_path.to_string(); + let initial_writer = open_rotated_log_file(&log_path_owned, MAX_LOG_FILE_BYTES); let (tx, rx) = mpsc::sync_channel::(512); let file_tx = thread::Builder::new() .name("fpv-log-writer".into()) .spawn(move || { - let mut writer = file_opt.map(BufWriter::new); + let mut writer_state = initial_writer; let mut stderr = std::io::stderr(); while let Ok(cmd) = rx.recv() { match cmd { FileLogCmd::Line { text, flush } => { - let _ = stderr.write_all(text.as_bytes()); - if let Some(ref mut w) = writer { - let _ = w.write_all(text.as_bytes()); + let bytes = text.as_bytes(); + let _ = stderr.write_all(bytes); + if let Some((ref mut w, ref mut written_bytes)) = writer_state { + if w.write_all(bytes).is_ok() { + *written_bytes = written_bytes.saturating_add(bytes.len() as u64); + } if flush { let _ = w.flush(); } + if *written_bytes >= MAX_LOG_FILE_BYTES { + let _ = w.flush(); + writer_state = + open_rotated_log_file(&log_path_owned, MAX_LOG_FILE_BYTES); + } } } FileLogCmd::Flush => { let _ = stderr.flush(); - if let Some(ref mut w) = writer { + if let Some((ref mut w, _)) = writer_state { let _ = w.flush(); } } FileLogCmd::FlushSync(ack) => { let _ = stderr.flush(); - if let Some(ref mut w) = writer { + if let Some((ref mut w, _)) = writer_state { let _ = w.flush(); } let _ = ack.send(()); @@ -102,7 +127,7 @@ impl GuiLogger { } } let _ = stderr.flush(); - if let Some(ref mut w) = writer { + if let Some((ref mut w, _)) = writer_state { let _ = w.flush(); } }) @@ -202,3 +227,44 @@ impl Log for GuiLogger { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn log_rotation_moves_oversized_file_to_old() { + let dir = std::env::temp_dir().join(format!( + "steamframe_log_rot_test_{}", + std::process::id() + )); + let _ = fs::create_dir_all(&dir); + let log_path = dir.join("test.log"); + let backup_path = dir.join("test.log.old"); + let _ = fs::remove_file(&log_path); + let _ = fs::remove_file(&backup_path); + + let path_str = log_path.to_str().unwrap(); + // Écrire 200 octets initiaux + { + let (mut w, sz) = open_rotated_log_file(path_str, 100).unwrap(); + assert_eq!(sz, 0); + w.write_all(&[b'A'; 200]).unwrap(); + w.flush().unwrap(); + } + // La réouverture avec seuil 100 doit tourner test.log -> test.log.old + { + let (mut w, sz) = open_rotated_log_file(path_str, 100).unwrap(); + assert_eq!(sz, 0); + w.write_all(b"fresh\n").unwrap(); + w.flush().unwrap(); + } + + assert_eq!(fs::metadata(&backup_path).unwrap().len(), 200); + assert_eq!(fs::read_to_string(&log_path).unwrap(), "fresh\n"); + + let _ = fs::remove_file(&log_path); + let _ = fs::remove_file(&backup_path); + let _ = fs::remove_dir(&dir); + } +} diff --git a/src/telemetry_osd/osd.rs b/src/telemetry_osd/osd.rs index 1e9f08d..fbf6ae5 100644 --- a/src/telemetry_osd/osd.rs +++ b/src/telemetry_osd/osd.rs @@ -167,6 +167,25 @@ impl OsdOverlay { scale, [255, 60, 60, 255], ); + // Mode « Véhicule Perdu » : afficher immédiatement la dernière position GPS valide connue + if extra.show_gps { + if let Some((lat, lon, _, sats)) = telem.last_valid_gps { + let mut last_gps_buf = StackStr::<64>::new(); + let _ = write!(last_gps_buf, "LAST GPS {:.5},{:.5} ({}S)", lat, lon, sats); + let gx = (width as i32 / 2) + - ((last_gps_buf.as_str().chars().count() as i32 * 6 * scale as i32) / 2); + Self::draw_text( + rgba, + width, + height, + gx, + top_center_bottom + 2, + last_gps_buf.as_str(), + scale, + [255, 200, 50, 255], + ); + } + } } else { Self::draw_heading_ribbon( rgba, @@ -331,6 +350,26 @@ impl OsdOverlay { telem.drone_pitch_rad, ); + // Inclinomètre numérique (Pitch / Roll en degrés) avec alerte dévers crawler/aile (>= 25° orange, >= 35° rouge) + if telem.is_live() { + let pitch_deg = telem.drone_pitch_rad.to_degrees(); + let roll_deg = telem.drone_roll_rad.to_degrees(); + let max_tilt = pitch_deg.abs().max(roll_deg.abs()); + let inc_color = if max_tilt >= 35.0 { + [255, 60, 60, 255] + } else if max_tilt >= 25.0 { + [255, 185, 45, 255] + } else { + [180, 230, 255, 220] + }; + let mut inc_buf = StackStr::<32>::new(); + let _ = write!(inc_buf, "P:{:+3.0}° R:{:+3.0}°", pitch_deg, roll_deg); + let ix = (width as i32 / 2) + - ((inc_buf.as_str().chars().count() as i32 * 6 * scale as i32) / 2); + let iy = (height as i32 / 2) + 52; + Self::draw_text(rgba, width, height, ix, iy, inc_buf.as_str(), scale, inc_color); + } + let bottom_y = height.saturating_sub(28 + 8 * scale) as i32; let spd_kmh = telem.groundspeed_ms * 3.6; let mut left_bottom_buf = StackStr::<48>::new(); diff --git a/src/telemetry_osd/parser.rs b/src/telemetry_osd/parser.rs index e9e8b5e..afddd5f 100644 --- a/src/telemetry_osd/parser.rs +++ b/src/telemetry_osd/parser.rs @@ -287,6 +287,10 @@ impl TelemetryReceiver { st.gps_sats = sats; st.gps_alt_m = alt_off as f32 - 1000.0; st.gps_fix_valid = sats >= 4 && (lat_raw != 0 || lon_raw != 0); + if st.gps_fix_valid { + st.last_valid_gps = Some((st.gps_lat_deg, st.gps_lon_deg, st.gps_alt_m, sats)); + st.last_valid_gps_at = Some(Instant::now()); + } st.groundspeed_ms = (gs_10kmh as f32 * 0.1) / 3.6; st.altitude_m = st.gps_alt_m; if hdg_100 <= 36000 { diff --git a/src/telemetry_osd/state.rs b/src/telemetry_osd/state.rs index 42236d2..e312a61 100644 --- a/src/telemetry_osd/state.rs +++ b/src/telemetry_osd/state.rs @@ -26,6 +26,9 @@ pub struct TelemetryState { /// Point Home mémorisé au premier armement avec fix GPS valide (>= 6 sats) pub home_lat_deg: Option, pub home_lon_deg: Option, + /// Dernière position GPS valide connue (lat, lon, alt_m, sats) — figée en cas de perte liaison (Lost Model) + pub last_valid_gps: Option<(f64, f64, f32, u8)>, + pub last_valid_gps_at: Option, pub flight_mode: String, pub packets_received: u64, pub last_update: Option, @@ -59,6 +62,8 @@ impl Default for TelemetryState { gps_fix_valid: false, home_lat_deg: None, home_lon_deg: None, + last_valid_gps: None, + last_valid_gps_at: None, flight_mode: String::new(), packets_received: 0, last_update: None, @@ -168,6 +173,22 @@ impl TelemetryState { Some((dist_m, rel)) } + /// Retourne `(distance_m, azimut_depuis_home_deg)` entre le point Home et la dernière position GPS valide connue. + /// Utile en mode « Véhicule Perdu » (Lost Model) pour savoir dans quelle direction marcher. + pub fn last_known_gps_from_home(&self) -> Option<(f32, f32)> { + let (hlat, hlon) = (self.home_lat_deg?, self.home_lon_deg?); + let (lat, lon, _, _) = self.last_valid_gps?; + let dist_m = haversine_distance_m(hlat, hlon, lat, lon); + let bearing = initial_bearing_deg(hlat, hlon, lat, lon); + Some((dist_m, bearing)) + } + + /// URL Google Maps vers la dernière position GPS valide connue. + pub fn last_known_gps_maps_url(&self) -> Option { + let (lat, lon, _, _) = self.last_valid_gps?; + Some(format!("https://maps.google.com/?q={:.6},{:.6}", lat, lon)) + } + /// Formate une ligne compacte de télémétrie pour sous-titres DVR `.srt` (VLC/MPV). pub fn format_dvr_srt_caption( &self, diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 16609df..b544511 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -87,6 +87,9 @@ pub struct SteamFrameGpuiApp { latest_controller: SteamControllerState, control_switch_error: String, profile_feedback: String, + ping_result_text: Arc>, + ping_busy: Arc, + gps_copy_feedback: String, monitor_source_override: Option, log_entries: Vec, log_err_count: usize, @@ -165,6 +168,9 @@ impl SteamFrameGpuiApp { latest_controller: SteamControllerState::default(), control_switch_error: String::new(), profile_feedback: String::new(), + ping_result_text: Arc::new(Mutex::new("Non testé".to_string())), + ping_busy: Arc::new(AtomicBool::new(false)), + gps_copy_feedback: String::new(), monitor_source_override: None, log_entries: Vec::new(), log_err_count: 0, @@ -769,7 +775,7 @@ impl Render for SteamFrameGpuiApp { .child(match self.active_tab { ActiveTab::Cockpit => self.render_cockpit_view(cx).into_any_element(), ActiveTab::Settings => self.render_settings_view(cx).into_any_element(), - ActiveTab::Telemetry => self.render_telemetry_view().into_any_element(), + ActiveTab::Telemetry => self.render_telemetry_view(cx).into_any_element(), ActiveTab::Logs => self.render_logs_view(cx).into_any_element(), }), ) diff --git a/src/ui/settings/controls_profiles.rs b/src/ui/settings/controls_profiles.rs index a1f6881..0ff4759 100644 --- a/src/ui/settings/controls_profiles.rs +++ b/src/ui/settings/controls_profiles.rs @@ -242,6 +242,52 @@ self.render_settings_card( )), ), )) + .child(self.render_setting_row( + "Expo Gaz & Mode Précision (Crawler)", + div() + .flex() + .flex_wrap() + .items_center() + .gap_2() + .children( + [ + (0.0f32, "Linéaire (0.0)"), + (0.25, "Doux (0.25)"), + (0.50, "Crawler (0.50)"), + (0.70, "Ultra-fin (0.70)"), + ] + .into_iter() + .enumerate() + .map(|(i, (val, lbl))| { + let active = (self.cfg.controller_throttle_expo - val).abs() < 0.05; + self.render_selectable_pill( + SharedString::from(format!("pill_throt_expo_{}", i)), + lbl, + active, + cx.listener(move |this, _, _, cx| { + this.cfg.controller_throttle_expo = val; + this.controls.set_throttle_expo(val); + cx.notify(); + }), + ) + }), + ) + .child(self.render_selectable_pill( + "pill_crawl_mode", + if self.cfg.controller_crawl_mode { + "🐢 Précision 50% : ON" + } else { + "🐢 Précision 50% : OFF" + }, + self.cfg.controller_crawl_mode, + cx.listener(|this, _, _, cx| { + let next = !this.cfg.controller_crawl_mode; + this.cfg.controller_crawl_mode = next; + this.controls.set_crawl_mode(next); + cx.notify(); + }), + )), + )) .child(self.render_setting_row( "Vibrations Haptiques SC (25 Hz)", div() diff --git a/src/ui/telemetry.rs b/src/ui/telemetry.rs index 4226ca7..ec8b16b 100644 --- a/src/ui/telemetry.rs +++ b/src/ui/telemetry.rs @@ -2,10 +2,13 @@ use super::theme::*; use super::SteamFrameGpuiApp; use crate::controller::ControlSource; use crate::engine::SubsystemStatus; -use gpui::{div, prelude::*, px, rgb, IntoElement}; +use crate::g29_bridge::G29BridgeReceiver; +use gpui::{div, prelude::*, px, rgb, rgba, ClipboardItem, Context, IntoElement}; +use std::sync::atomic::Ordering; +use std::sync::Arc; impl SteamFrameGpuiApp { - pub(super) fn render_telemetry_view(&self) -> impl IntoElement { + pub(super) fn render_telemetry_view(&self, cx: &mut Context) -> impl IntoElement { let telem_live = self.latest_telem.is_live(); let eff_cells = self.latest_telem.effective_cells(self.cfg.battery_cells); let cell_v_opt = self.latest_telem.cell_voltage_v(self.cfg.battery_cells); @@ -91,6 +94,35 @@ impl SteamFrameGpuiApp { "Aucun fix GPS".to_string() }; + let ping_text = self.ping_result_text.lock().clone(); + let last_gps_info = self.latest_telem.last_valid_gps.map(|(lat, lon, alt, sats)| { + let from_home = self + .latest_telem + .last_known_gps_from_home() + .map(|(dist_m, brg)| format!(" • Depuis Home : {:.0} m (cap {:.0}°)", dist_m, brg)) + .unwrap_or_default(); + let maps_url = self + .latest_telem + .last_known_gps_maps_url() + .unwrap_or_default(); + ( + format!( + "{:.6}, {:.6} ({} sats, alt {:.0} m){}", + lat, lon, sats, alt, from_home + ), + maps_url, + ) + }); + let attitude_str = if telem_live { + format!( + "Pitch {:+.1}° • Roll {:+.1}°", + self.latest_telem.drone_pitch_rad.to_degrees(), + self.latest_telem.drone_roll_rad.to_degrees() + ) + } else { + "Hors ligne".to_string() + }; + div() .flex() .flex_col() @@ -297,9 +329,121 @@ impl SteamFrameGpuiApp { format!("{:.1} Mo", self.replay_buffered_bytes as f64 / (1024.0 * 1024.0)) }, )) - .child(self.render_stat_row("Dernière émission :", if self.latest_pose.last_send_ok { "Succès (OK)" } else { "En attente" })), + .child(self.render_stat_row("Inclinomètre :", &attitude_str)) + .child(self.render_stat_row("Dernière émission :", if self.latest_pose.last_send_ok { "Succès (OK)" } else { "En attente" })) + .child(self.render_stat_row("Ping Radxa/RP2350 :", &ping_text)) + .child( + div() + .id("btn_ping_radxa") + .mt_1() + .px_3() + .py_1p5() + .rounded_md() + .bg(rgba(0x00e5ff1a)) + .border_1() + .border_color(rgb(COLOR_CYAN)) + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(rgb(COLOR_CYAN)) + .cursor_pointer() + .on_click(cx.listener(|this, _, _, cx| { + if this.ping_busy.swap(true, Ordering::AcqRel) { + return; + } + *this.ping_result_text.lock() = "Ping en cours...".to_string(); + let target_ip = this.cfg.radxa_vrx_ip.clone(); + let target_port = this.cfg.g29_udp_port; + let res_slot = Arc::clone(&this.ping_result_text); + let busy = Arc::clone(&this.ping_busy); + std::thread::spawn(move || { + let msg = match G29BridgeReceiver::ping_radxa_relay( + &target_ip, + target_port, + ) { + Ok((rtt_ms, uart_ok)) => format!( + "RTT {:.1} ms • RP2350 {}", + rtt_ms, + if uart_ok { "UART OK" } else { "UART ABSENT" } + ), + Err(e) => format!("Injoignable ({})", e), + }; + *res_slot.lock() = msg; + busy.store(false, Ordering::Release); + }); + cx.notify(); + })) + .child("🏓 Tester Ping Radxa / RP2350"), + ), ), ) + // Panneau Mode « Véhicule Perdu » (Dernier GPS valide figé + copie lien Google Maps) + .when_some(last_gps_info, |el, (coords_line, maps_url)| { + let is_lost = !telem_live; + el.child( + div() + .flex() + .items_center() + .justify_between() + .gap_3() + .bg(if is_lost { rgb(0x2a1215) } else { rgb(COLOR_SURFACE_ELEVATED) }) + .border_1() + .border_color(if is_lost { rgb(COLOR_RED) } else { rgb(COLOR_BORDER_SUBTLE) }) + .rounded_xl() + .p_3() + .child( + div() + .flex() + .flex_col() + .gap_1() + .child( + div() + .text_xs() + .font_weight(gpui::FontWeight::BOLD) + .text_color(if is_lost { rgb(COLOR_RED) } else { rgb(COLOR_GREEN) }) + .child(if is_lost { + "🆘 MODE VÉHICULE PERDU — DERNIER GPS CONNU" + } else { + "📍 Dernière Position GPS Valide (Sauvegarde Véhicule Perdu)" + }), + ) + .child( + div() + .text_xs() + .text_color(rgb(COLOR_TEXT_MAIN)) + .child(coords_line), + ) + .when(!self.gps_copy_feedback.is_empty(), |d| { + d.child( + div() + .text_xs() + .text_color(rgb(COLOR_CYAN)) + .child(self.gps_copy_feedback.clone()), + ) + }), + ) + .child( + div() + .id("btn_copy_gps_maps") + .px_3() + .py_1p5() + .rounded_md() + .bg(rgba(0x10b98122)) + .border_1() + .border_color(rgb(COLOR_GREEN)) + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(rgb(COLOR_GREEN)) + .cursor_pointer() + .on_click(cx.listener(move |this, _, _, cx| { + cx.write_to_clipboard(ClipboardItem::new_string(maps_url.clone())); + this.gps_copy_feedback = + format!("Lien copié dans le presse-papiers : {}", maps_url); + cx.notify(); + })) + .child("📋 Copier Google Maps"), + ), + ) + }) } fn render_stat_box(&self, title: &str, value: &str, sub: &str, color: u32) -> impl IntoElement {