mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
Merge pull request #13 from bleackstorm/feat/pilotage-terrain-and-ci-hygiene
Feat/pilotage terrain and ci hygiene
This commit is contained in:
24 files changed
+1045
-63
No files matched your search
@@ -56,8 +56,10 @@ jobs:
|
|||||||
- name: Validate shell scripts syntax (bash -n)
|
- name: Validate shell scripts syntax (bash -n)
|
||||||
run: bash -n launch.sh launch_vr.sh scripts/*.sh
|
run: bash -n launch.sh launch_vr.sh scripts/*.sh
|
||||||
|
|
||||||
- name: Validate Python relay syntax (py_compile)
|
- name: Validate Python relay syntax & unit tests
|
||||||
run: python3 -m py_compile scripts/radxa_g29_relay.py
|
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:
|
firmware-rp2350:
|
||||||
name: Firmware RP2350 (g29_crsf.ino)
|
name: Firmware RP2350 (g29_crsf.ino)
|
||||||
|
|||||||
@@ -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/*
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
/target
|
/target
|
||||||
target/
|
target/
|
||||||
*.log
|
*.log
|
||||||
|
*.log.old
|
||||||
steamframe_fpv.log
|
steamframe_fpv.log
|
||||||
|
steamframe_fpv.log.old
|
||||||
*.bin
|
*.bin
|
||||||
dist/
|
dist/
|
||||||
recordings/
|
recordings/
|
||||||
|
graphify-out/
|
||||||
.DS_Store
|
.DS_Store
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
+75
-28
@@ -106,6 +106,59 @@ def close_serial(serial_fd: Optional[int]) -> None:
|
|||||||
pass
|
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:
|
def main() -> None:
|
||||||
sock, bound_ip = bind_udp_socket()
|
sock, bound_ip = bind_udp_socket()
|
||||||
print(
|
print(
|
||||||
@@ -118,9 +171,13 @@ def main() -> None:
|
|||||||
serial_tx_buf = bytearray()
|
serial_tx_buf = bytearray()
|
||||||
last_casque_addr = (CASQUE_IP, UDP_PORT)
|
last_casque_addr = (CASQUE_IP, UDP_PORT)
|
||||||
last_udp_err_log = 0.0
|
last_udp_err_log = 0.0
|
||||||
|
last_serial_scan = 0.0
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
if serial_fd is None:
|
if serial_fd is None:
|
||||||
|
now = time.monotonic()
|
||||||
|
if now - last_serial_scan >= 0.5:
|
||||||
|
last_serial_scan = now
|
||||||
dev = find_serial_device()
|
dev = find_serial_device()
|
||||||
if dev is not None:
|
if dev is not None:
|
||||||
try:
|
try:
|
||||||
@@ -131,14 +188,9 @@ def main() -> None:
|
|||||||
except OSError as exc:
|
except OSError as exc:
|
||||||
print(f"[radxa_g29_relay] Erreur ouverture {dev}: {exc}", file=sys.stderr, flush=True)
|
print(f"[radxa_g29_relay] Erreur ouverture {dev}: {exc}", file=sys.stderr, flush=True)
|
||||||
serial_fd = None
|
serial_fd = None
|
||||||
time.sleep(1.0)
|
|
||||||
continue
|
|
||||||
else:
|
|
||||||
time.sleep(0.5)
|
|
||||||
continue
|
|
||||||
|
|
||||||
rlist = [sock.fileno(), serial_fd]
|
rlist = [sock.fileno()] + ([serial_fd] if serial_fd is not None else [])
|
||||||
wlist = [serial_fd] if serial_tx_buf else []
|
wlist = [serial_fd] if (serial_fd is not None and serial_tx_buf) else []
|
||||||
try:
|
try:
|
||||||
readable, writable, _ = select.select(rlist, wlist, [], 0.25)
|
readable, writable, _ = select.select(rlist, wlist, [], 0.25)
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
@@ -146,7 +198,7 @@ def main() -> None:
|
|||||||
serial_fd = None
|
serial_fd = None
|
||||||
continue
|
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:
|
if sock.fileno() in readable:
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
@@ -155,21 +207,23 @@ def main() -> None:
|
|||||||
break
|
break
|
||||||
except OSError:
|
except OSError:
|
||||||
break
|
break
|
||||||
if addr[0] not in (CASQUE_IP, "127.0.0.1"):
|
if not is_allowed_peer(addr[0]):
|
||||||
continue
|
continue
|
||||||
last_casque_addr = (addr[0], UDP_PORT)
|
last_casque_addr = (addr[0], UDP_PORT)
|
||||||
for raw_line in data.splitlines():
|
uart_lines, ping_lines = filter_inbound_lines(data)
|
||||||
line = raw_line.strip()
|
for pline in ping_lines:
|
||||||
if not line or not line.startswith(ALLOWED_INBOUND_PREFIXES):
|
pong = build_pong_reply(pline, serial_fd is not None)
|
||||||
continue
|
if pong is not None:
|
||||||
payload = line + b"\n"
|
try:
|
||||||
if len(serial_tx_buf) + len(payload) > MAX_SERIAL_TX_BUF:
|
sock.sendto(pong, (addr[0], addr[1]))
|
||||||
# Préférer la trame la plus récente en cas de saturation UART
|
except OSError:
|
||||||
serial_tx_buf.clear()
|
pass
|
||||||
serial_tx_buf.extend(payload)
|
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)
|
# 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:
|
try:
|
||||||
written = os.write(serial_fd, serial_tx_buf)
|
written = os.write(serial_fd, serial_tx_buf)
|
||||||
if written > 0:
|
if written > 0:
|
||||||
@@ -190,16 +244,9 @@ def main() -> None:
|
|||||||
if not chunk:
|
if not chunk:
|
||||||
raise OSError("EOF série")
|
raise OSError("EOF série")
|
||||||
serial_rx_buf.extend(chunk)
|
serial_rx_buf.extend(chunk)
|
||||||
if len(serial_rx_buf) > MAX_SERIAL_RX_BUF:
|
for outbound in extract_outbound_serial_lines(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:
|
try:
|
||||||
sock.sendto(line + b"\n", last_casque_addr)
|
sock.sendto(outbound, last_casque_addr)
|
||||||
except OSError as exc:
|
except OSError as exc:
|
||||||
# Une panne réseau usb0 (casque débranché) ne doit JAMAIS fermer le port série RP2350
|
# Une panne réseau usb0 (casque débranché) ne doit JAMAIS fermer le port série RP2350
|
||||||
now = time.monotonic()
|
now = time.monotonic()
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -72,6 +72,14 @@ pub struct AppConfig {
|
|||||||
#[arg(long, default_value_t = false)]
|
#[arg(long, default_value_t = false)]
|
||||||
pub controller_invert_steering: bool,
|
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%)
|
/// Intensité des vibrations haptiques du Steam Controller (0 = désactivé, 1..=100%)
|
||||||
#[arg(long, default_value_t = 100)]
|
#[arg(long, default_value_t = 100)]
|
||||||
pub controller_vibration: u8,
|
pub controller_vibration: u8,
|
||||||
@@ -244,6 +252,10 @@ pub struct AppConfig {
|
|||||||
#[arg(long, default_value_t = false)]
|
#[arg(long, default_value_t = false)]
|
||||||
pub zero_copy_dmabuf: bool,
|
pub zero_copy_dmabuf: bool,
|
||||||
|
|
||||||
|
/// Active le traceur de latence GStreamer natif (`GST_TRACERS=latency`) dans les logs
|
||||||
|
#[arg(long, default_value_t = false)]
|
||||||
|
pub gst_latency_trace: bool,
|
||||||
|
|
||||||
/// Chemin du fichier journal d'erreurs et de diagnostic
|
/// Chemin du fichier journal d'erreurs et de diagnostic
|
||||||
#[arg(long, default_value = "steamframe_fpv.log")]
|
#[arg(long, default_value = "steamframe_fpv.log")]
|
||||||
pub log_file: String,
|
pub log_file: String,
|
||||||
@@ -586,6 +598,8 @@ impl AppConfig {
|
|||||||
controller_expo = {:.3}\n\
|
controller_expo = {:.3}\n\
|
||||||
controller_deadzone = {:.3}\n\
|
controller_deadzone = {:.3}\n\
|
||||||
controller_invert_steering = {}\n\
|
controller_invert_steering = {}\n\
|
||||||
|
controller_throttle_expo = {:.3}\n\
|
||||||
|
controller_crawl_mode = {}\n\
|
||||||
controller_vibration = {}\n\
|
controller_vibration = {}\n\
|
||||||
gaz_avant_min = {}\n\
|
gaz_avant_min = {}\n\
|
||||||
gear_1_max = {}\n\
|
gear_1_max = {}\n\
|
||||||
@@ -642,6 +656,8 @@ impl AppConfig {
|
|||||||
self.controller_expo,
|
self.controller_expo,
|
||||||
self.controller_deadzone,
|
self.controller_deadzone,
|
||||||
self.controller_invert_steering,
|
self.controller_invert_steering,
|
||||||
|
self.controller_throttle_expo,
|
||||||
|
self.controller_crawl_mode,
|
||||||
self.controller_vibration,
|
self.controller_vibration,
|
||||||
self.gaz_avant_min,
|
self.gaz_avant_min,
|
||||||
self.gear_1_max,
|
self.gear_1_max,
|
||||||
@@ -785,6 +801,8 @@ impl AppConfig {
|
|||||||
load_parse!(controller_expo);
|
load_parse!(controller_expo);
|
||||||
load_parse!(controller_deadzone);
|
load_parse!(controller_deadzone);
|
||||||
load_parse!(controller_invert_steering);
|
load_parse!(controller_invert_steering);
|
||||||
|
load_parse!(controller_throttle_expo);
|
||||||
|
load_parse!(controller_crawl_mode);
|
||||||
load_parse!(controller_vibration);
|
load_parse!(controller_vibration);
|
||||||
load_parse!(gaz_avant_min);
|
load_parse!(gaz_avant_min);
|
||||||
load_parse!(gear_1_max);
|
load_parse!(gear_1_max);
|
||||||
@@ -818,6 +836,7 @@ impl AppConfig {
|
|||||||
self.lens_k1 = self.lens_k1.clamp(-0.50, 0.25);
|
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.screen_distance_m = self.screen_distance_m.clamp(0.5, 5.0);
|
||||||
self.controller_vibration = self.controller_vibration.min(100);
|
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_cells = self.battery_cells.min(6);
|
||||||
self.battery_warn_cell_v = self.battery_warn_cell_v.clamp(3.0, 4.2);
|
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);
|
self.battery_crit_cell_v = self.battery_crit_cell_v.clamp(2.8, self.battery_warn_cell_v);
|
||||||
|
|||||||
@@ -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)
|
(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.
|
/// Normalise une gâchette [0.0..1.0] avec zone morte, courbe expo cubique [0.0..0.8] et multiplicateur
|
||||||
pub fn throttle_to_crsf(
|
/// 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,
|
throttle_norm: f32,
|
||||||
deadzone: f32,
|
deadzone: f32,
|
||||||
|
expo: f32,
|
||||||
|
speed_scale: f32,
|
||||||
armed: bool,
|
armed: bool,
|
||||||
gear: i8,
|
gear: i8,
|
||||||
limits: GearSpeedLimits,
|
limits: GearSpeedLimits,
|
||||||
@@ -60,20 +63,31 @@ pub fn throttle_to_crsf(
|
|||||||
} else {
|
} else {
|
||||||
((clamped - dz) / (1.0 - dz)).clamp(0.0, 1.0)
|
((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);
|
return (pct, CRSF_CHANNEL_MID);
|
||||||
}
|
}
|
||||||
|
|
||||||
let s = limits.sanitized();
|
let s = limits.sanitized();
|
||||||
let crsf = if gear == -1 {
|
let crsf = if gear == -1 {
|
||||||
let span = s.reverse_min as f32 - s.reverse_max as f32;
|
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) {
|
} else if (1..=3).contains(&gear) {
|
||||||
let max_v = s.forward_max[(gear - 1) as usize];
|
let max_v = s.forward_max[(gear - 1) as usize];
|
||||||
let span = max_v as f32 - s.forward_min as f32;
|
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 {
|
} else {
|
||||||
CRSF_CHANNEL_MID
|
CRSF_CHANNEL_MID
|
||||||
};
|
};
|
||||||
@@ -81,6 +95,17 @@ pub fn throttle_to_crsf(
|
|||||||
(pct, crsf.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX))
|
(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).
|
/// 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) {
|
pub fn brake_to_crsf(brake_norm: f32, deadzone: f32) -> (u8, u16) {
|
||||||
if !brake_norm.is_finite() {
|
if !brake_norm.is_finite() {
|
||||||
@@ -142,3 +167,24 @@ pub fn encode_rc_frame(
|
|||||||
gear.clamp(-1, 3),
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
-3
@@ -6,7 +6,7 @@ mod types;
|
|||||||
|
|
||||||
pub use gearbox::{
|
pub use gearbox::{
|
||||||
brake_to_crsf, encode_gears_command, encode_rc_frame, encode_src_command, steering_to_crsf,
|
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)]
|
#[cfg(test)]
|
||||||
use haptics::encode_ibex_rumble_report;
|
use haptics::encode_ibex_rumble_report;
|
||||||
@@ -362,14 +362,19 @@ impl SteamControllerWorker {
|
|||||||
CRSF_CHANNEL_MID
|
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 {
|
if desired_source == ControlSource::SteamController {
|
||||||
// Mode actif : armement, boîte séquentielle, raccourcis cockpit et émission $RC 100 Hz
|
// Mode actif : armement, boîte séquentielle, raccourcis cockpit et émission $RC 100 Hz
|
||||||
let mut deferred_actions: Vec<DeferredControlAction> = Vec::new();
|
let mut deferred_actions: Vec<DeferredControlAction> = Vec::new();
|
||||||
let (armed, gear, throttle_crsf) = {
|
let (armed, gear, throttle_crsf) = {
|
||||||
let mut st = state.lock();
|
let mut st = state.lock();
|
||||||
let (pre_throt_pct, _) = throttle_to_crsf(
|
let (pre_throt_pct, _) = throttle_to_crsf_curved(
|
||||||
throttle_norm,
|
throttle_norm,
|
||||||
cfg.trigger_deadzone,
|
cfg.trigger_deadzone,
|
||||||
|
throttle_expo,
|
||||||
|
speed_scale,
|
||||||
st.armed,
|
st.armed,
|
||||||
st.gear,
|
st.gear,
|
||||||
current_gears,
|
current_gears,
|
||||||
@@ -400,9 +405,11 @@ impl SteamControllerWorker {
|
|||||||
st.last_button_at = Some(Instant::now());
|
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,
|
throttle_norm,
|
||||||
cfg.trigger_deadzone,
|
cfg.trigger_deadzone,
|
||||||
|
throttle_expo,
|
||||||
|
speed_scale,
|
||||||
st.armed,
|
st.armed,
|
||||||
st.gear,
|
st.gear,
|
||||||
current_gears,
|
current_gears,
|
||||||
|
|||||||
+91
@@ -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<BufWriter<File>>,
|
||||||
|
path: PathBuf,
|
||||||
|
points: u32,
|
||||||
|
last_emit: Option<Instant>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
|
||||||
|
<gpx version=\"1.1\" creator=\"steamframe-fpv\" xmlns=\"http://www.topografix.com/GPX/1/1\">\n\
|
||||||
|
<trk>\n\
|
||||||
|
<name>{}</name>\n\
|
||||||
|
<trkseg>",
|
||||||
|
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,
|
||||||
|
" <trkpt lat=\"{:.7}\" lon=\"{:.7}\"><ele>{:.1}</ele><time>{}</time></trkpt>",
|
||||||
|
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, " </trkseg>\n </trk>\n</gpx>");
|
||||||
|
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).
|
/// 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 {
|
pub fn detect_keyframe(bytes: &[u8], codec: &str, gst_is_delta: bool) -> bool {
|
||||||
if !gst_is_delta {
|
if !gst_is_delta {
|
||||||
@@ -424,6 +496,7 @@ pub struct DvrRecorder {
|
|||||||
frames_recorded: Arc<AtomicU64>,
|
frames_recorded: Arc<AtomicU64>,
|
||||||
is_recording: Arc<AtomicBool>,
|
is_recording: Arc<AtomicBool>,
|
||||||
srt_writer: Mutex<SrtWriterState>,
|
srt_writer: Mutex<SrtWriterState>,
|
||||||
|
gpx_writer: Mutex<GpxWriterState>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DvrRecorder {
|
impl DvrRecorder {
|
||||||
@@ -557,6 +630,7 @@ impl DvrRecorder {
|
|||||||
.map_err(|e| anyhow!("Impossible de démarrer le pipeline DVR : {}", e))?;
|
.map_err(|e| anyhow!("Impossible de démarrer le pipeline DVR : {}", e))?;
|
||||||
|
|
||||||
let srt_writer = Mutex::new(SrtWriterState::open_for_video(&file_path));
|
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 {
|
Ok(Arc::new(Self {
|
||||||
pipeline,
|
pipeline,
|
||||||
@@ -568,6 +642,7 @@ impl DvrRecorder {
|
|||||||
frames_recorded: Arc::new(AtomicU64::new(0)),
|
frames_recorded: Arc::new(AtomicU64::new(0)),
|
||||||
is_recording: Arc::new(AtomicBool::new(true)),
|
is_recording: Arc::new(AtomicBool::new(true)),
|
||||||
srt_writer,
|
srt_writer,
|
||||||
|
gpx_writer,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -628,6 +703,14 @@ impl DvrRecorder {
|
|||||||
self.srt_writer.lock().push_caption(elapsed_ms, caption);
|
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.
|
/// Sonde le bus GStreamer (non-bloquant) et rafraîchit la taille réelle du fichier sur disque.
|
||||||
fn poll_health_and_size(&self) {
|
fn poll_health_and_size(&self) {
|
||||||
if let Some(bus) = self.pipeline.bus() {
|
if let Some(bus) = self.pipeline.bus() {
|
||||||
@@ -708,6 +791,7 @@ impl DvrRecorder {
|
|||||||
|
|
||||||
let end_ms = self.start_time.elapsed().as_millis() as u64;
|
let end_ms = self.start_time.elapsed().as_millis() as u64;
|
||||||
self.srt_writer.lock().finish(end_ms);
|
self.srt_writer.lock().finish(end_ms);
|
||||||
|
self.gpx_writer.lock().finish();
|
||||||
|
|
||||||
let _ = self.appsrc.end_of_stream();
|
let _ = self.appsrc.end_of_stream();
|
||||||
|
|
||||||
@@ -810,6 +894,7 @@ mod tests {
|
|||||||
let dvr = DvrRecorder::start_composited_osd(&dir, DvrContainer::Mkv, 320, 240)
|
let dvr = DvrRecorder::start_composited_osd(&dir, DvrContainer::Mkv, 320, 240)
|
||||||
.expect("start dvr failed");
|
.expect("start dvr failed");
|
||||||
dvr.push_telemetry_caption("BAT 15.2V (3.80V/c) | LQ 99% | G2 | 24 km/h");
|
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];
|
let fake_rgba = vec![0u8; 320 * 240 * 4];
|
||||||
for _ in 0..10 {
|
for _ in 0..10 {
|
||||||
dvr.push_slice(&fake_rgba);
|
dvr.push_slice(&fake_rgba);
|
||||||
@@ -817,12 +902,18 @@ mod tests {
|
|||||||
}
|
}
|
||||||
let path = dvr.file_path().to_path_buf();
|
let path = dvr.file_path().to_path_buf();
|
||||||
let srt_path = path.with_extension("srt");
|
let srt_path = path.with_extension("srt");
|
||||||
|
let gpx_path = path.with_extension("gpx");
|
||||||
dvr.stop();
|
dvr.stop();
|
||||||
assert!(path.exists());
|
assert!(path.exists());
|
||||||
assert!(srt_path.exists());
|
assert!(srt_path.exists());
|
||||||
|
assert!(gpx_path.exists());
|
||||||
let srt_content = fs::read_to_string(&srt_path).expect("read srt");
|
let srt_content = fs::read_to_string(&srt_path).expect("read srt");
|
||||||
assert!(srt_content.contains("BAT 15.2V"));
|
assert!(srt_content.contains("BAT 15.2V"));
|
||||||
assert!(srt_content.contains("-->"));
|
assert!(srt_content.contains("-->"));
|
||||||
|
let gpx_content = fs::read_to_string(&gpx_path).expect("read gpx");
|
||||||
|
assert!(gpx_content.contains("<gpx"));
|
||||||
|
assert!(gpx_content.contains("48.8566140"));
|
||||||
|
assert!(gpx_content.contains("</gpx>"));
|
||||||
let meta = fs::metadata(&path).expect("file metadata");
|
let meta = fs::metadata(&path).expect("file metadata");
|
||||||
assert!(meta.len() > 0);
|
assert!(meta.len() > 0);
|
||||||
let _ = fs::remove_dir_all(&dir);
|
let _ = fs::remove_dir_all(&dir);
|
||||||
|
|||||||
@@ -42,6 +42,13 @@ impl EngineControlHandle {
|
|||||||
.shared
|
.shared
|
||||||
.controller_invert_steering
|
.controller_invert_steering
|
||||||
.load(Ordering::Acquire);
|
.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.gaz_avant_min = limits.forward_min;
|
||||||
cfg.gear_1_max = limits.forward_max[0];
|
cfg.gear_1_max = limits.forward_max[0];
|
||||||
cfg.gear_2_max = limits.forward_max[1];
|
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) {
|
pub fn request_recenter(&self) {
|
||||||
*self.shared.head_trim_deg.lock() = (0.0, 0.0);
|
*self.shared.head_trim_deg.lock() = (0.0, 0.0);
|
||||||
self.shared.recenter_flag.store(true, Ordering::Release);
|
self.shared.recenter_flag.store(true, Ordering::Release);
|
||||||
|
|||||||
@@ -96,6 +96,7 @@ pub fn run_desktop_fallback_loop(ctx: &mut EngineWorkerRefs<'_>) {
|
|||||||
let mut has_new_raw_frame = false;
|
let mut has_new_raw_frame = false;
|
||||||
let mut has_video_stream = false;
|
let mut has_video_stream = false;
|
||||||
let mut frame_fmt = PixelFormat::Rgba;
|
let mut frame_fmt = PixelFormat::Rgba;
|
||||||
|
let mut frame_received_at: Option<Instant> = None;
|
||||||
|
|
||||||
if let Some(rx) = ctx.video_rx_opt {
|
if let Some(rx) = ctx.video_rx_opt {
|
||||||
let (live, taken) = rx.take_latest_frame(
|
let (live, taken) = rx.take_latest_frame(
|
||||||
@@ -108,6 +109,7 @@ pub fn run_desktop_fallback_loop(ctx: &mut EngineWorkerRefs<'_>) {
|
|||||||
if meta.width == ctx.cfg.video_width && meta.height == ctx.cfg.video_height {
|
if meta.width == ctx.cfg.video_width && meta.height == ctx.cfg.video_height {
|
||||||
last_frame_id = meta.frame_id;
|
last_frame_id = meta.frame_id;
|
||||||
frame_fmt = meta.format;
|
frame_fmt = meta.format;
|
||||||
|
frame_received_at = Some(meta.received_at);
|
||||||
fps_counter += 1;
|
fps_counter += 1;
|
||||||
has_new_raw_frame = true;
|
has_new_raw_frame = true;
|
||||||
}
|
}
|
||||||
@@ -166,6 +168,7 @@ pub fn run_desktop_fallback_loop(ctx: &mut EngineWorkerRefs<'_>) {
|
|||||||
has_new_raw_frame,
|
has_new_raw_frame,
|
||||||
has_video_stream,
|
has_video_stream,
|
||||||
last_frame_id,
|
last_frame_id,
|
||||||
|
frame_received_at,
|
||||||
&mut fps_counter,
|
&mut fps_counter,
|
||||||
&mut fps_timer,
|
&mut fps_timer,
|
||||||
&mut last_preview_push,
|
&mut last_preview_push,
|
||||||
|
|||||||
@@ -69,6 +69,8 @@ impl FpvEngineController {
|
|||||||
control_source_flag: Arc::new(AtomicU8::new(ControlSource::G29.as_u8())),
|
control_source_flag: Arc::new(AtomicU8::new(ControlSource::G29.as_u8())),
|
||||||
controller_vibration_pct: Arc::new(AtomicU8::new(100)),
|
controller_vibration_pct: Arc::new(AtomicU8::new(100)),
|
||||||
controller_invert_steering: Arc::new(AtomicBool::new(false)),
|
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)),
|
controller_rumble_test: Arc::new(AtomicBool::new(false)),
|
||||||
gear_speed_limits: Arc::new(Mutex::new(GearSpeedLimits::default())),
|
gear_speed_limits: Arc::new(Mutex::new(GearSpeedLimits::default())),
|
||||||
preview_active_flag: Arc::new(AtomicBool::new(true)),
|
preview_active_flag: Arc::new(AtomicBool::new(true)),
|
||||||
@@ -169,6 +171,12 @@ impl FpvEngineController {
|
|||||||
self.shared
|
self.shared
|
||||||
.controller_invert_steering
|
.controller_invert_steering
|
||||||
.store(cfg.controller_invert_steering, Ordering::Relaxed);
|
.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
|
self.shared
|
||||||
.controller_rumble_test
|
.controller_rumble_test
|
||||||
.store(false, Ordering::Relaxed);
|
.store(false, Ordering::Relaxed);
|
||||||
@@ -659,6 +667,7 @@ pub fn compose_osd_and_publish(
|
|||||||
has_new_raw_frame: bool,
|
has_new_raw_frame: bool,
|
||||||
has_video_stream: bool,
|
has_video_stream: bool,
|
||||||
last_frame_id: u64,
|
last_frame_id: u64,
|
||||||
|
frame_received_at: Option<Instant>,
|
||||||
fps_counter: &mut u32,
|
fps_counter: &mut u32,
|
||||||
fps_timer: &mut Instant,
|
fps_timer: &mut Instant,
|
||||||
last_preview_push: &mut Option<Instant>,
|
last_preview_push: &mut Option<Instant>,
|
||||||
@@ -726,6 +735,13 @@ pub fn compose_osd_and_publish(
|
|||||||
if !caption.is_empty() {
|
if !caption.is_empty() {
|
||||||
if let Some(ref dvr) = *ctx.active_dvr {
|
if let Some(ref dvr) = *ctx.active_dvr {
|
||||||
dvr.push_telemetry_caption(&caption);
|
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);
|
ctx.shared.replay_buffer.push_caption(caption);
|
||||||
}
|
}
|
||||||
@@ -786,8 +802,10 @@ pub fn compose_osd_and_publish(
|
|||||||
let push_preview = ctx.control.is_preview_active()
|
let push_preview = ctx.control.is_preview_active()
|
||||||
&& last_preview_push.is_none_or(|t| t.elapsed() >= Duration::from_millis(33));
|
&& last_preview_push.is_none_or(|t| t.elapsed() >= Duration::from_millis(33));
|
||||||
|
|
||||||
|
if push_preview || fps_timer.elapsed() >= Duration::from_secs(1) || frame_received_at.is_some() {
|
||||||
if push_preview || fps_timer.elapsed() >= Duration::from_secs(1) {
|
if push_preview || fps_timer.elapsed() >= Duration::from_secs(1) {
|
||||||
sync_video_status(ctx.cfg, ctx.video_rx_opt, &ctx.shared.monitor);
|
sync_video_status(ctx.cfg, ctx.video_rx_opt, &ctx.shared.monitor);
|
||||||
|
}
|
||||||
let preview_arc = if push_preview {
|
let preview_arc = if push_preview {
|
||||||
*last_preview_push = Some(Instant::now());
|
*last_preview_push = Some(Instant::now());
|
||||||
// Conversion directe RGBA -> BGRA sur le worker (zéro swizzle/clone sur le thread UI GPUI)
|
// Conversion directe RGBA -> BGRA sur le worker (zéro swizzle/clone sur le thread UI GPUI)
|
||||||
@@ -797,6 +815,14 @@ pub fn compose_osd_and_publish(
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
let mut mon = ctx.shared.monitor.lock();
|
let mut mon = ctx.shared.monitor.lock();
|
||||||
|
if let Some(recv_at) = frame_received_at {
|
||||||
|
let eng_ms = recv_at.elapsed().as_secs_f32() * 1000.0;
|
||||||
|
mon.video_engine_latency_ms = if mon.video_engine_latency_ms <= 0.01 {
|
||||||
|
eng_ms
|
||||||
|
} else {
|
||||||
|
mon.video_engine_latency_ms * 0.8 + eng_ms * 0.2
|
||||||
|
};
|
||||||
|
}
|
||||||
if fps_timer.elapsed() >= Duration::from_secs(1) {
|
if fps_timer.elapsed() >= Duration::from_secs(1) {
|
||||||
if has_video_stream {
|
if has_video_stream {
|
||||||
mon.video_fps = *fps_counter as f32 / fps_timer.elapsed().as_secs_f32();
|
mon.video_fps = *fps_counter as f32 / fps_timer.elapsed().as_secs_f32();
|
||||||
@@ -825,6 +851,7 @@ pub fn compose_osd_and_publish(
|
|||||||
mon.preview_width = ctx.cfg.video_width;
|
mon.preview_width = ctx.cfg.video_width;
|
||||||
mon.preview_height = ctx.cfg.video_height;
|
mon.preview_height = ctx.cfg.video_height;
|
||||||
mon.preview_bgra = arc;
|
mon.preview_bgra = arc;
|
||||||
|
mon.preview_received_at = frame_received_at;
|
||||||
mon.preview_frame_seq = mon.preview_frame_seq.wrapping_add(1);
|
mon.preview_frame_seq = mon.preview_frame_seq.wrapping_add(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,9 +65,11 @@ pub struct RuntimeMonitor {
|
|||||||
pub dmabuf_active: bool,
|
pub dmabuf_active: bool,
|
||||||
pub video_fps: f32,
|
pub video_fps: f32,
|
||||||
pub video_jitter_ms: f32,
|
pub video_jitter_ms: f32,
|
||||||
|
pub video_engine_latency_ms: f32,
|
||||||
pub video_dropped_frames: u64,
|
pub video_dropped_frames: u64,
|
||||||
pub video_decoder_name: String,
|
pub video_decoder_name: String,
|
||||||
pub video_frames_total: u64,
|
pub video_frames_total: u64,
|
||||||
|
pub preview_received_at: Option<Instant>,
|
||||||
pub latest_head_pose: HeadPoseSample,
|
pub latest_head_pose: HeadPoseSample,
|
||||||
pub latest_telemetry: TelemetryState,
|
pub latest_telemetry: TelemetryState,
|
||||||
pub latest_g29: G29State,
|
pub latest_g29: G29State,
|
||||||
@@ -104,9 +106,11 @@ impl Default for RuntimeMonitor {
|
|||||||
dmabuf_active: false,
|
dmabuf_active: false,
|
||||||
video_fps: 0.0,
|
video_fps: 0.0,
|
||||||
video_jitter_ms: 0.0,
|
video_jitter_ms: 0.0,
|
||||||
|
video_engine_latency_ms: 0.0,
|
||||||
video_dropped_frames: 0,
|
video_dropped_frames: 0,
|
||||||
video_decoder_name: "auto".to_string(),
|
video_decoder_name: "auto".to_string(),
|
||||||
video_frames_total: 0,
|
video_frames_total: 0,
|
||||||
|
preview_received_at: None,
|
||||||
latest_head_pose: HeadPoseSample::default(),
|
latest_head_pose: HeadPoseSample::default(),
|
||||||
latest_telemetry: TelemetryState::default(),
|
latest_telemetry: TelemetryState::default(),
|
||||||
latest_g29: G29State::default(),
|
latest_g29: G29State::default(),
|
||||||
@@ -137,6 +141,8 @@ pub struct EngineSharedState {
|
|||||||
pub control_source_flag: Arc<AtomicU8>,
|
pub control_source_flag: Arc<AtomicU8>,
|
||||||
pub controller_vibration_pct: Arc<AtomicU8>,
|
pub controller_vibration_pct: Arc<AtomicU8>,
|
||||||
pub controller_invert_steering: Arc<AtomicBool>,
|
pub controller_invert_steering: Arc<AtomicBool>,
|
||||||
|
pub controller_throttle_expo_pct: Arc<AtomicU8>,
|
||||||
|
pub controller_crawl_mode: Arc<AtomicBool>,
|
||||||
pub controller_rumble_test: Arc<AtomicBool>,
|
pub controller_rumble_test: Arc<AtomicBool>,
|
||||||
pub gear_speed_limits: Arc<Mutex<GearSpeedLimits>>,
|
pub gear_speed_limits: Arc<Mutex<GearSpeedLimits>>,
|
||||||
pub preview_active_flag: Arc<AtomicBool>,
|
pub preview_active_flag: Arc<AtomicBool>,
|
||||||
|
|||||||
@@ -546,6 +546,7 @@ pub fn try_run_openxr_session(ctx: &mut EngineWorkerRefs<'_>) -> Result<()> {
|
|||||||
let mut has_new_raw_frame = false;
|
let mut has_new_raw_frame = false;
|
||||||
let mut has_video_stream = false;
|
let mut has_video_stream = false;
|
||||||
let mut taken_dmabuf: Option<DmaBufFrame> = None;
|
let mut taken_dmabuf: Option<DmaBufFrame> = None;
|
||||||
|
let mut frame_received_at: Option<Instant> = None;
|
||||||
|
|
||||||
if let Some(rx) = ctx.video_rx_opt {
|
if let Some(rx) = ctx.video_rx_opt {
|
||||||
rx.set_dmabuf_handoff(want_dmabuf);
|
rx.set_dmabuf_handoff(want_dmabuf);
|
||||||
@@ -559,6 +560,7 @@ pub fn try_run_openxr_session(ctx: &mut EngineWorkerRefs<'_>) -> Result<()> {
|
|||||||
if d.width == ctx.cfg.video_width && d.height == ctx.cfg.video_height {
|
if d.width == ctx.cfg.video_width && d.height == ctx.cfg.video_height {
|
||||||
last_frame_id = d.frame_id;
|
last_frame_id = d.frame_id;
|
||||||
raw_frame_format = d.format;
|
raw_frame_format = d.format;
|
||||||
|
frame_received_at = Some(d.received_at);
|
||||||
fps_counter += 1;
|
fps_counter += 1;
|
||||||
has_new_raw_frame = true;
|
has_new_raw_frame = true;
|
||||||
taken_dmabuf = Some(d);
|
taken_dmabuf = Some(d);
|
||||||
@@ -579,6 +581,7 @@ pub fn try_run_openxr_session(ctx: &mut EngineWorkerRefs<'_>) -> Result<()> {
|
|||||||
{
|
{
|
||||||
last_frame_id = meta.frame_id;
|
last_frame_id = meta.frame_id;
|
||||||
raw_frame_format = meta.format;
|
raw_frame_format = meta.format;
|
||||||
|
frame_received_at = Some(meta.received_at);
|
||||||
fps_counter += 1;
|
fps_counter += 1;
|
||||||
has_new_raw_frame = true;
|
has_new_raw_frame = true;
|
||||||
}
|
}
|
||||||
@@ -662,6 +665,7 @@ pub fn try_run_openxr_session(ctx: &mut EngineWorkerRefs<'_>) -> Result<()> {
|
|||||||
has_new_raw_frame,
|
has_new_raw_frame,
|
||||||
has_video_stream,
|
has_video_stream,
|
||||||
last_frame_id,
|
last_frame_id,
|
||||||
|
frame_received_at,
|
||||||
&mut fps_counter,
|
&mut fps_counter,
|
||||||
&mut fps_timer,
|
&mut fps_timer,
|
||||||
&mut last_preview_push,
|
&mut last_preview_push,
|
||||||
|
|||||||
@@ -240,6 +240,38 @@ impl G29BridgeReceiver {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ping applicatif UDP vers le relais Radxa Zero 3W (`$PING,<seq>` -> `$PONG,<seq>,<uart_ok>`).
|
||||||
|
/// 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::<u64>().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 {
|
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)
|
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_exit_requested());
|
||||||
assert!(!ctrl.is_vr_menu_open());
|
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!((0.0..250.0).contains(&rtt_ms));
|
||||||
|
assert!(uart_ok);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+80
-14
@@ -2,14 +2,17 @@ use chrono::Local;
|
|||||||
use log::{Level, LevelFilter, Log, Metadata, Record};
|
use log::{Level, LevelFilter, Log, Metadata, Record};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
use std::fs::OpenOptions;
|
use std::fs::{self, File, OpenOptions};
|
||||||
use std::io::{BufWriter, Write};
|
use std::io::{BufWriter, Write};
|
||||||
|
use std::path::Path;
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
use std::sync::mpsc::{self, SyncSender};
|
use std::sync::mpsc::{self, SyncSender};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::thread;
|
use std::thread;
|
||||||
|
|
||||||
const MAX_LOG_ENTRIES: usize = 1000;
|
const MAX_LOG_ENTRIES: usize = 1000;
|
||||||
|
/// Taille maximale du fichier journal avant rotation vers `<fichier>.old` (5 Mo).
|
||||||
|
const MAX_LOG_FILE_BYTES: u64 = 5 * 1024 * 1024;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum LogFilter {
|
pub enum LogFilter {
|
||||||
@@ -59,42 +62,64 @@ pub struct GuiLogger {
|
|||||||
file_tx: Option<SyncSender<FileLogCmd>>,
|
file_tx: Option<SyncSender<FileLogCmd>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ouvre le fichier journal en appliquant une rotation vers `<chemin>.old` si sa taille atteint `max_bytes`.
|
||||||
|
fn open_rotated_log_file(path: &str, max_bytes: u64) -> Option<(BufWriter<File>, 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 {
|
impl GuiLogger {
|
||||||
pub fn init(log_file_path: &str) -> Arc<Mutex<LogBuffer>> {
|
pub fn init(log_file_path: &str) -> Arc<Mutex<LogBuffer>> {
|
||||||
let buffer = Arc::new(Mutex::new(LogBuffer::default()));
|
let buffer = Arc::new(Mutex::new(LogBuffer::default()));
|
||||||
|
let log_path_owned = log_file_path.to_string();
|
||||||
let file_opt = OpenOptions::new()
|
let initial_writer = open_rotated_log_file(&log_path_owned, MAX_LOG_FILE_BYTES);
|
||||||
.create(true)
|
|
||||||
.append(true)
|
|
||||||
.open(log_file_path)
|
|
||||||
.ok();
|
|
||||||
|
|
||||||
let (tx, rx) = mpsc::sync_channel::<FileLogCmd>(512);
|
let (tx, rx) = mpsc::sync_channel::<FileLogCmd>(512);
|
||||||
let file_tx = thread::Builder::new()
|
let file_tx = thread::Builder::new()
|
||||||
.name("fpv-log-writer".into())
|
.name("fpv-log-writer".into())
|
||||||
.spawn(move || {
|
.spawn(move || {
|
||||||
let mut writer = file_opt.map(BufWriter::new);
|
let mut writer_state = initial_writer;
|
||||||
let mut stderr = std::io::stderr();
|
let mut stderr = std::io::stderr();
|
||||||
while let Ok(cmd) = rx.recv() {
|
while let Ok(cmd) = rx.recv() {
|
||||||
match cmd {
|
match cmd {
|
||||||
FileLogCmd::Line { text, flush } => {
|
FileLogCmd::Line { text, flush } => {
|
||||||
let _ = stderr.write_all(text.as_bytes());
|
let bytes = text.as_bytes();
|
||||||
if let Some(ref mut w) = writer {
|
let _ = stderr.write_all(bytes);
|
||||||
let _ = w.write_all(text.as_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 {
|
if flush {
|
||||||
let _ = w.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 => {
|
FileLogCmd::Flush => {
|
||||||
let _ = stderr.flush();
|
let _ = stderr.flush();
|
||||||
if let Some(ref mut w) = writer {
|
if let Some((ref mut w, _)) = writer_state {
|
||||||
let _ = w.flush();
|
let _ = w.flush();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
FileLogCmd::FlushSync(ack) => {
|
FileLogCmd::FlushSync(ack) => {
|
||||||
let _ = stderr.flush();
|
let _ = stderr.flush();
|
||||||
if let Some(ref mut w) = writer {
|
if let Some((ref mut w, _)) = writer_state {
|
||||||
let _ = w.flush();
|
let _ = w.flush();
|
||||||
}
|
}
|
||||||
let _ = ack.send(());
|
let _ = ack.send(());
|
||||||
@@ -102,7 +127,7 @@ impl GuiLogger {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let _ = stderr.flush();
|
let _ = stderr.flush();
|
||||||
if let Some(ref mut w) = writer {
|
if let Some((ref mut w, _)) = writer_state {
|
||||||
let _ = w.flush();
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -45,6 +45,14 @@ fn install_signal_handlers() {
|
|||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
install_signal_handlers();
|
install_signal_handlers();
|
||||||
let mut cfg = AppConfig::parse_with_saved();
|
let mut cfg = AppConfig::parse_with_saved();
|
||||||
|
if cfg.gst_latency_trace {
|
||||||
|
if std::env::var_os("GST_TRACERS").is_none() {
|
||||||
|
std::env::set_var("GST_TRACERS", "latency(flags=pipeline+element)");
|
||||||
|
}
|
||||||
|
if std::env::var_os("GST_DEBUG").is_none() {
|
||||||
|
std::env::set_var("GST_DEBUG", "GST_TRACER:7");
|
||||||
|
}
|
||||||
|
}
|
||||||
let log_buffer = GuiLogger::init(&cfg.log_file);
|
let log_buffer = GuiLogger::init(&cfg.log_file);
|
||||||
|
|
||||||
let mode_label = if cfg.vr_only {
|
let mode_label = if cfg.vr_only {
|
||||||
|
|||||||
@@ -167,6 +167,25 @@ impl OsdOverlay {
|
|||||||
scale,
|
scale,
|
||||||
[255, 60, 60, 255],
|
[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 {
|
} else {
|
||||||
Self::draw_heading_ribbon(
|
Self::draw_heading_ribbon(
|
||||||
rgba,
|
rgba,
|
||||||
@@ -331,6 +350,26 @@ impl OsdOverlay {
|
|||||||
telem.drone_pitch_rad,
|
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 bottom_y = height.saturating_sub(28 + 8 * scale) as i32;
|
||||||
let spd_kmh = telem.groundspeed_ms * 3.6;
|
let spd_kmh = telem.groundspeed_ms * 3.6;
|
||||||
let mut left_bottom_buf = StackStr::<48>::new();
|
let mut left_bottom_buf = StackStr::<48>::new();
|
||||||
|
|||||||
@@ -287,6 +287,10 @@ impl TelemetryReceiver {
|
|||||||
st.gps_sats = sats;
|
st.gps_sats = sats;
|
||||||
st.gps_alt_m = alt_off as f32 - 1000.0;
|
st.gps_alt_m = alt_off as f32 - 1000.0;
|
||||||
st.gps_fix_valid = sats >= 4 && (lat_raw != 0 || lon_raw != 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.groundspeed_ms = (gs_10kmh as f32 * 0.1) / 3.6;
|
||||||
st.altitude_m = st.gps_alt_m;
|
st.altitude_m = st.gps_alt_m;
|
||||||
if hdg_100 <= 36000 {
|
if hdg_100 <= 36000 {
|
||||||
|
|||||||
@@ -26,6 +26,9 @@ pub struct TelemetryState {
|
|||||||
/// Point Home mémorisé au premier armement avec fix GPS valide (>= 6 sats)
|
/// Point Home mémorisé au premier armement avec fix GPS valide (>= 6 sats)
|
||||||
pub home_lat_deg: Option<f64>,
|
pub home_lat_deg: Option<f64>,
|
||||||
pub home_lon_deg: Option<f64>,
|
pub home_lon_deg: Option<f64>,
|
||||||
|
/// 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<Instant>,
|
||||||
pub flight_mode: String,
|
pub flight_mode: String,
|
||||||
pub packets_received: u64,
|
pub packets_received: u64,
|
||||||
pub last_update: Option<Instant>,
|
pub last_update: Option<Instant>,
|
||||||
@@ -59,6 +62,8 @@ impl Default for TelemetryState {
|
|||||||
gps_fix_valid: false,
|
gps_fix_valid: false,
|
||||||
home_lat_deg: None,
|
home_lat_deg: None,
|
||||||
home_lon_deg: None,
|
home_lon_deg: None,
|
||||||
|
last_valid_gps: None,
|
||||||
|
last_valid_gps_at: None,
|
||||||
flight_mode: String::new(),
|
flight_mode: String::new(),
|
||||||
packets_received: 0,
|
packets_received: 0,
|
||||||
last_update: None,
|
last_update: None,
|
||||||
@@ -168,6 +173,22 @@ impl TelemetryState {
|
|||||||
Some((dist_m, rel))
|
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<String> {
|
||||||
|
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).
|
/// Formate une ligne compacte de télémétrie pour sous-titres DVR `.srt` (VLC/MPV).
|
||||||
pub fn format_dvr_srt_caption(
|
pub fn format_dvr_srt_caption(
|
||||||
&self,
|
&self,
|
||||||
|
|||||||
+70
-1
@@ -125,7 +125,12 @@ impl SteamFrameGpuiApp {
|
|||||||
.rounded_md()
|
.rounded_md()
|
||||||
.text_xs()
|
.text_xs()
|
||||||
.text_color(rgb(COLOR_TEXT_MUTED))
|
.text_color(rgb(COLOR_TEXT_MUTED))
|
||||||
.child(format!("{} trames", self.video_frames_total)),
|
.child(format!(
|
||||||
|
"{} trames • PC {:.1} ms (moteur {:.1} ms)",
|
||||||
|
self.video_frames_total,
|
||||||
|
self.video_pc_latency_ms,
|
||||||
|
self.video_engine_latency_ms
|
||||||
|
)),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
// 2.3 Overlay Supérieur Droit (VR & Format)
|
// 2.3 Overlay Supérieur Droit (VR & Format)
|
||||||
@@ -185,6 +190,35 @@ impl SteamFrameGpuiApp {
|
|||||||
"⏮ Replay 30s".to_string()
|
"⏮ Replay 30s".to_string()
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
.child(
|
||||||
|
div()
|
||||||
|
.id("btn_toggle_g2g")
|
||||||
|
.px_2p5()
|
||||||
|
.py_1()
|
||||||
|
.bg(rgba(0x0a101abb))
|
||||||
|
.border_1()
|
||||||
|
.border_color(if self.glass_to_glass_test {
|
||||||
|
rgb(COLOR_CYAN)
|
||||||
|
} else {
|
||||||
|
rgb(COLOR_BORDER_SUBTLE)
|
||||||
|
})
|
||||||
|
.rounded_md()
|
||||||
|
.text_xs()
|
||||||
|
.text_color(if self.glass_to_glass_test {
|
||||||
|
rgb(COLOR_CYAN)
|
||||||
|
} else {
|
||||||
|
rgb(COLOR_TEXT_MUTED)
|
||||||
|
})
|
||||||
|
.cursor_pointer()
|
||||||
|
.on_click(cx.listener(|this, _, _, cx| {
|
||||||
|
this.glass_to_glass_test = !this.glass_to_glass_test;
|
||||||
|
if this.glass_to_glass_test {
|
||||||
|
this.glass_to_glass_t0 = std::time::Instant::now();
|
||||||
|
}
|
||||||
|
cx.notify();
|
||||||
|
}))
|
||||||
|
.child("⏱️ Chrono G2G"),
|
||||||
|
)
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
.id("btn_toggle_hud")
|
.id("btn_toggle_hud")
|
||||||
@@ -208,6 +242,41 @@ impl SteamFrameGpuiApp {
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
// 2.3b Chrono haute précision pour mesure Glass-to-Glass (filmer l'écran avec la caméra FPV)
|
||||||
|
.when(self.glass_to_glass_test, |el| {
|
||||||
|
let elapsed_ms = self.glass_to_glass_t0.elapsed().as_millis();
|
||||||
|
let secs = elapsed_ms / 1000;
|
||||||
|
let ms = elapsed_ms % 1000;
|
||||||
|
el.child(
|
||||||
|
div()
|
||||||
|
.absolute()
|
||||||
|
.top_12()
|
||||||
|
.left_3()
|
||||||
|
.px_4()
|
||||||
|
.py_2()
|
||||||
|
.bg(rgb(0x000000))
|
||||||
|
.border_2()
|
||||||
|
.border_color(rgb(COLOR_CYAN))
|
||||||
|
.rounded_lg()
|
||||||
|
.flex()
|
||||||
|
.flex_col()
|
||||||
|
.gap_1()
|
||||||
|
.child(
|
||||||
|
div()
|
||||||
|
.text_xs()
|
||||||
|
.font_weight(gpui::FontWeight::BOLD)
|
||||||
|
.text_color(rgb(COLOR_CYAN))
|
||||||
|
.child("⏱️ TEST GLASS-TO-GLASS (pointer la caméra FPV ici)"),
|
||||||
|
)
|
||||||
|
.child(
|
||||||
|
div()
|
||||||
|
.text_2xl()
|
||||||
|
.font_weight(gpui::FontWeight::BOLD)
|
||||||
|
.text_color(rgb(0xffffff))
|
||||||
|
.child(format!("{:04}.{:03} s", secs, ms)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
})
|
||||||
// 2.4 Bandeau Flottant Inférieur (HUD Télémetrie & Suivi Tête discret)
|
// 2.4 Bandeau Flottant Inférieur (HUD Télémetrie & Suivi Tête discret)
|
||||||
.child(if self.show_hud_overlay {
|
.child(if self.show_hud_overlay {
|
||||||
div()
|
div()
|
||||||
|
|||||||
+37
-4
@@ -78,15 +78,22 @@ pub struct SteamFrameGpuiApp {
|
|||||||
dmabuf_active: bool,
|
dmabuf_active: bool,
|
||||||
video_fps: f32,
|
video_fps: f32,
|
||||||
video_jitter_ms: f32,
|
video_jitter_ms: f32,
|
||||||
|
video_engine_latency_ms: f32,
|
||||||
|
video_pc_latency_ms: f32,
|
||||||
video_dropped_frames: u64,
|
video_dropped_frames: u64,
|
||||||
video_decoder_name: String,
|
video_decoder_name: String,
|
||||||
video_frames_total: u64,
|
video_frames_total: u64,
|
||||||
|
glass_to_glass_test: bool,
|
||||||
|
glass_to_glass_t0: Instant,
|
||||||
latest_pose: HeadPoseSample,
|
latest_pose: HeadPoseSample,
|
||||||
latest_telem: TelemetryState,
|
latest_telem: TelemetryState,
|
||||||
latest_g29: G29State,
|
latest_g29: G29State,
|
||||||
latest_controller: SteamControllerState,
|
latest_controller: SteamControllerState,
|
||||||
control_switch_error: String,
|
control_switch_error: String,
|
||||||
profile_feedback: String,
|
profile_feedback: String,
|
||||||
|
ping_result_text: Arc<Mutex<String>>,
|
||||||
|
ping_busy: Arc<AtomicBool>,
|
||||||
|
gps_copy_feedback: String,
|
||||||
monitor_source_override: Option<ControlSource>,
|
monitor_source_override: Option<ControlSource>,
|
||||||
log_entries: Vec<LogEntry>,
|
log_entries: Vec<LogEntry>,
|
||||||
log_err_count: usize,
|
log_err_count: usize,
|
||||||
@@ -156,15 +163,22 @@ impl SteamFrameGpuiApp {
|
|||||||
dmabuf_active: false,
|
dmabuf_active: false,
|
||||||
video_fps: 0.0,
|
video_fps: 0.0,
|
||||||
video_jitter_ms: 0.0,
|
video_jitter_ms: 0.0,
|
||||||
|
video_engine_latency_ms: 0.0,
|
||||||
|
video_pc_latency_ms: 0.0,
|
||||||
video_dropped_frames: 0,
|
video_dropped_frames: 0,
|
||||||
video_decoder_name: "auto".to_string(),
|
video_decoder_name: "auto".to_string(),
|
||||||
video_frames_total: 0,
|
video_frames_total: 0,
|
||||||
|
glass_to_glass_test: false,
|
||||||
|
glass_to_glass_t0: Instant::now(),
|
||||||
latest_pose: HeadPoseSample::default(),
|
latest_pose: HeadPoseSample::default(),
|
||||||
latest_telem: TelemetryState::default(),
|
latest_telem: TelemetryState::default(),
|
||||||
latest_g29: G29State::default(),
|
latest_g29: G29State::default(),
|
||||||
latest_controller: SteamControllerState::default(),
|
latest_controller: SteamControllerState::default(),
|
||||||
control_switch_error: String::new(),
|
control_switch_error: String::new(),
|
||||||
profile_feedback: 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,
|
monitor_source_override: None,
|
||||||
log_entries: Vec::new(),
|
log_entries: Vec::new(),
|
||||||
log_err_count: 0,
|
log_err_count: 0,
|
||||||
@@ -251,11 +265,13 @@ impl SteamFrameGpuiApp {
|
|||||||
}
|
}
|
||||||
if (self.video_fps - mon.video_fps).abs() > 0.1
|
if (self.video_fps - mon.video_fps).abs() > 0.1
|
||||||
|| (self.video_jitter_ms - mon.video_jitter_ms).abs() > 0.1
|
|| (self.video_jitter_ms - mon.video_jitter_ms).abs() > 0.1
|
||||||
|
|| (self.video_engine_latency_ms - mon.video_engine_latency_ms).abs() > 0.2
|
||||||
|| self.video_dropped_frames != mon.video_dropped_frames
|
|| self.video_dropped_frames != mon.video_dropped_frames
|
||||||
|| self.video_decoder_name != mon.video_decoder_name
|
|| self.video_decoder_name != mon.video_decoder_name
|
||||||
{
|
{
|
||||||
self.video_fps = mon.video_fps;
|
self.video_fps = mon.video_fps;
|
||||||
self.video_jitter_ms = mon.video_jitter_ms;
|
self.video_jitter_ms = mon.video_jitter_ms;
|
||||||
|
self.video_engine_latency_ms = mon.video_engine_latency_ms;
|
||||||
self.video_dropped_frames = mon.video_dropped_frames;
|
self.video_dropped_frames = mon.video_dropped_frames;
|
||||||
self.video_decoder_name = mon.video_decoder_name.clone();
|
self.video_decoder_name = mon.video_decoder_name.clone();
|
||||||
changed = true;
|
changed = true;
|
||||||
@@ -315,13 +331,18 @@ impl SteamFrameGpuiApp {
|
|||||||
self.latest_controller = mon.latest_controller.clone();
|
self.latest_controller = mon.latest_controller.clone();
|
||||||
|
|
||||||
// Récupération directe du tampon BGRA pré-converti par le worker (zéro swizzle UI)
|
// Récupération directe du tampon BGRA pré-converti par le worker (zéro swizzle UI)
|
||||||
let frame_data: Option<(u32, u32, Arc<Vec<u8>>)> = if self.active_tab == ActiveTab::Cockpit
|
let frame_data = if self.active_tab == ActiveTab::Cockpit
|
||||||
&& mon.preview_frame_seq != self.last_frame_seq
|
&& mon.preview_frame_seq != self.last_frame_seq
|
||||||
&& !mon.preview_bgra.is_empty()
|
&& !mon.preview_bgra.is_empty()
|
||||||
&& mon.preview_width > 0
|
&& mon.preview_width > 0
|
||||||
&& mon.preview_height > 0
|
&& mon.preview_height > 0
|
||||||
{
|
{
|
||||||
Some((mon.preview_width, mon.preview_height, Arc::clone(&mon.preview_bgra)))
|
Some((
|
||||||
|
mon.preview_width,
|
||||||
|
mon.preview_height,
|
||||||
|
Arc::clone(&mon.preview_bgra),
|
||||||
|
mon.preview_received_at,
|
||||||
|
))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
@@ -340,7 +361,7 @@ impl SteamFrameGpuiApp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 2. Upload RenderImage GPU direct (pixels déjà en BGRA — plus de swizzle CPU sur thread UI)
|
// 2. Upload RenderImage GPU direct (pixels déjà en BGRA — plus de swizzle CPU sur thread UI)
|
||||||
if let Some((w, h, bgra_arc)) = new_frame_data {
|
if let Some((w, h, bgra_arc, recv_at_opt)) = new_frame_data {
|
||||||
let bgra_buf = match Arc::try_unwrap(bgra_arc) {
|
let bgra_buf = match Arc::try_unwrap(bgra_arc) {
|
||||||
Ok(v) => v,
|
Ok(v) => v,
|
||||||
Err(shared) => (*shared).clone(),
|
Err(shared) => (*shared).clone(),
|
||||||
@@ -354,6 +375,14 @@ impl SteamFrameGpuiApp {
|
|||||||
}
|
}
|
||||||
self.current_render_image = Some(new_render_image);
|
self.current_render_image = Some(new_render_image);
|
||||||
self.last_frame_seq = preview_frame_seq;
|
self.last_frame_seq = preview_frame_seq;
|
||||||
|
if let Some(recv_at) = recv_at_opt {
|
||||||
|
let pc_ms = recv_at.elapsed().as_secs_f32() * 1000.0;
|
||||||
|
self.video_pc_latency_ms = if self.video_pc_latency_ms <= 0.01 {
|
||||||
|
pc_ms
|
||||||
|
} else {
|
||||||
|
self.video_pc_latency_ms * 0.8 + pc_ms * 0.2
|
||||||
|
};
|
||||||
|
}
|
||||||
changed = true;
|
changed = true;
|
||||||
|
|
||||||
while self.images_to_drop.len() > 2 {
|
while self.images_to_drop.len() > 2 {
|
||||||
@@ -387,6 +416,10 @@ impl SteamFrameGpuiApp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if self.glass_to_glass_test && self.active_tab == ActiveTab::Cockpit {
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
changed
|
changed
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -769,7 +802,7 @@ impl Render for SteamFrameGpuiApp {
|
|||||||
.child(match self.active_tab {
|
.child(match self.active_tab {
|
||||||
ActiveTab::Cockpit => self.render_cockpit_view(cx).into_any_element(),
|
ActiveTab::Cockpit => self.render_cockpit_view(cx).into_any_element(),
|
||||||
ActiveTab::Settings => self.render_settings_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(),
|
ActiveTab::Logs => self.render_logs_view(cx).into_any_element(),
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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(
|
.child(self.render_setting_row(
|
||||||
"Vibrations Haptiques SC (25 Hz)",
|
"Vibrations Haptiques SC (25 Hz)",
|
||||||
div()
|
div()
|
||||||
|
|||||||
+152
-5
@@ -2,10 +2,13 @@ use super::theme::*;
|
|||||||
use super::SteamFrameGpuiApp;
|
use super::SteamFrameGpuiApp;
|
||||||
use crate::controller::ControlSource;
|
use crate::controller::ControlSource;
|
||||||
use crate::engine::SubsystemStatus;
|
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 {
|
impl SteamFrameGpuiApp {
|
||||||
pub(super) fn render_telemetry_view(&self) -> impl IntoElement {
|
pub(super) fn render_telemetry_view(&self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
let telem_live = self.latest_telem.is_live();
|
let telem_live = self.latest_telem.is_live();
|
||||||
let eff_cells = self.latest_telem.effective_cells(self.cfg.battery_cells);
|
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);
|
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()
|
"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()
|
div()
|
||||||
.flex()
|
.flex()
|
||||||
.flex_col()
|
.flex_col()
|
||||||
@@ -117,8 +149,11 @@ impl SteamFrameGpuiApp {
|
|||||||
"🎥 LIEN VIDÉO",
|
"🎥 LIEN VIDÉO",
|
||||||
&format!("{:.1} FPS", self.video_fps),
|
&format!("{:.1} FPS", self.video_fps),
|
||||||
&format!(
|
&format!(
|
||||||
"Jitter {:.1} ms • Drop {} • {}",
|
"Jitter {:.1} ms • PC {:.1} ms (mot. {:.1} ms) • Drop {}",
|
||||||
self.video_jitter_ms, self.video_dropped_frames, self.video_decoder_name
|
self.video_jitter_ms,
|
||||||
|
self.video_pc_latency_ms,
|
||||||
|
self.video_engine_latency_ms,
|
||||||
|
self.video_dropped_frames
|
||||||
),
|
),
|
||||||
if self.video_fps > 1.0 { COLOR_CYAN } else { COLOR_TEXT_MUTED },
|
if self.video_fps > 1.0 { COLOR_CYAN } else { COLOR_TEXT_MUTED },
|
||||||
))
|
))
|
||||||
@@ -297,9 +332,121 @@ impl SteamFrameGpuiApp {
|
|||||||
format!("{:.1} Mo", self.replay_buffered_bytes as f64 / (1024.0 * 1024.0))
|
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 {
|
fn render_stat_box(&self, title: &str, value: &str, sub: &str, color: u32) -> impl IntoElement {
|
||||||
|
|||||||
Reference in new issue
Block a user