Merge pull request #15 from bleackstorm/feat/android-fpv-core-and-dhcp

Feat/android fpv core and dhcp
This commit is contained in:
bleackstorm authored and GitHub committed 2026-11-27 10:15:45 +01:00
commit 5d4a9a40a4
68 files changed
+5166 -1301

No files matched your search

+50 -2
View File
@@ -41,10 +41,10 @@ jobs:
uses: Swatinem/rust-cache@v2 uses: Swatinem/rust-cache@v2
- name: Run cargo clippy (strict) - name: Run cargo clippy (strict)
run: cargo clippy --no-deps --all-targets -- -D warnings run: cargo clippy --workspace --no-deps --all-targets -- -D warnings
- name: Run cargo test - name: Run cargo test
run: cargo test run: cargo test --workspace
scripts-and-python: scripts-and-python:
name: Shell & Python Validation name: Shell & Python Validation
@@ -85,3 +85,51 @@ jobs:
arduino-cli compile \ arduino-cli compile \
--fqbn rp2040:rp2040:waveshare_rp2350_plus:usbstack=tinyusb \ --fqbn rp2040:rp2040:waveshare_rp2350_plus:usbstack=tinyusb \
firmware/g29_crsf firmware/g29_crsf
android-apk:
name: Android APK (arm64-v8a / Tab S8 Ultra)
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Java 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
- name: Setup Rust toolchain (aarch64-linux-android)
uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-linux-android
- name: Cache Cargo registry & build artifacts
uses: Swatinem/rust-cache@v2
- name: Install cargo-ndk
run: cargo install cargo-ndk --locked
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
- name: Ensure Android SDK 36 & Build Tools
run: |
yes | "${ANDROID_HOME}/cmdline-tools/latest/bin/sdkmanager" \
"platforms;android-36" "build-tools;36.0.0" >/dev/null
- name: Build Rust native library (arm64-v8a)
run: |
mkdir -p android/app/src/main/jniLibs
cargo ndk -t arm64-v8a --platform 31 -o android/app/src/main/jniLibs build -p fpv-android-ffi --release
- name: Build Android APK (debug, ready to install)
working-directory: android
run: ./gradlew assembleDebug
- name: Upload Android APK artifact
uses: actions/upload-artifact@v4
with:
name: steamframe-fpv-android-arm64-apk
path: android/app/build/outputs/apk/debug/app-debug.apk
retention-days: 14
+36 -1
View File
@@ -98,9 +98,44 @@ jobs:
name: firmware-rp2350 name: firmware-rp2350
path: dist/firmware/*.uf2 path: dist/firmware/*.uf2
build-android-arm64:
name: Build Android APK (arm64-v8a)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
- uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-linux-android
- uses: Swatinem/rust-cache@v2
- name: Install cargo-ndk
run: cargo install cargo-ndk --locked
- uses: gradle/actions/setup-gradle@v4
- name: Ensure Android SDK 36 & Build Tools
run: |
yes | "${ANDROID_HOME}/cmdline-tools/latest/bin/sdkmanager" \
"platforms;android-36" "build-tools;36.0.0" >/dev/null
- name: Build Rust native library (arm64-v8a)
run: |
mkdir -p android/app/src/main/jniLibs
cargo ndk -t arm64-v8a --platform 31 -o android/app/src/main/jniLibs build -p fpv-android-ffi --release
- name: Build & package Android APK
run: |
(cd android && ./gradlew assembleDebug)
mkdir -p dist/android
cp android/app/build/outputs/apk/debug/app-debug.apk \
"dist/android/steamframe-fpv-${GITHUB_REF_NAME}-android-arm64.apk"
- uses: actions/upload-artifact@v4
with:
name: steamframe-fpv-android-arm64
path: dist/android/*.apk
publish-release: publish-release:
name: Publish GitHub Release name: Publish GitHub Release
needs: [build-linux-x86_64, build-linux-arm64, build-firmware-rp2350] needs: [build-linux-x86_64, build-linux-arm64, build-firmware-rp2350, build-android-arm64]
if: startsWith(github.ref, 'refs/tags/v') if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
+6
View File
@@ -11,3 +11,9 @@ graphify-out/
.DS_Store .DS_Store
__pycache__/ __pycache__/
*.pyc *.pyc
android/.gradle/
android/build/
android/app/build/
android/app/src/main/jniLibs/
android/local.properties
android/.kotlin/
Generated
+175
View File
@@ -60,6 +60,23 @@ dependencies = [
"equator", "equator",
] ]
[[package]]
name = "android_log-sys"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84521a3cf562bc62942e294181d9eef17eb38ceb8c68677bc49f144e4c3d4f8d"
[[package]]
name = "android_logger"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05b07e8e73d720a1f2e4b6014766e6039fd2e96a4fa44e2a78d0e1fa2ff49826"
dependencies = [
"android_log-sys",
"env_filter",
"log",
]
[[package]] [[package]]
name = "android_system_properties" name = "android_system_properties"
version = "0.1.6" version = "0.1.6"
@@ -841,6 +858,12 @@ dependencies = [
"shlex 2.0.1", "shlex 2.0.1",
] ]
[[package]]
name = "cesu8"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
[[package]] [[package]]
name = "cexpr" name = "cexpr"
version = "0.6.0" version = "0.6.0"
@@ -1050,6 +1073,16 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "combine"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"
dependencies = [
"bytes",
"memchr",
]
[[package]] [[package]]
name = "command-fds" name = "command-fds"
version = "0.3.3" version = "0.3.3"
@@ -1616,6 +1649,16 @@ dependencies = [
"syn 2.0.119", "syn 2.0.119",
] ]
[[package]]
name = "env_filter"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2"
dependencies = [
"log",
"regex",
]
[[package]] [[package]]
name = "equator" name = "equator"
version = "0.4.2" version = "0.4.2"
@@ -1923,6 +1966,27 @@ dependencies = [
"percent-encoding", "percent-encoding",
] ]
[[package]]
name = "fpv-android-ffi"
version = "0.4.0"
dependencies = [
"android_logger",
"fpv-core",
"jni",
"log",
"parking_lot",
]
[[package]]
name = "fpv-core"
version = "0.4.0"
dependencies = [
"anyhow",
"glam",
"log",
"parking_lot",
]
[[package]] [[package]]
name = "freetype-sys" name = "freetype-sys"
version = "0.20.1" version = "0.20.1"
@@ -3182,6 +3246,50 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jni"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"
dependencies = [
"cesu8",
"cfg-if",
"combine",
"jni-sys 0.3.1",
"log",
"thiserror 1.0.69",
"walkdir",
"windows-sys 0.45.0",
]
[[package]]
name = "jni-sys"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
dependencies = [
"jni-sys 0.4.1",
]
[[package]]
name = "jni-sys"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
dependencies = [
"jni-sys-macros",
]
[[package]]
name = "jni-sys-macros"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
dependencies = [
"quote",
"syn 2.0.119",
]
[[package]] [[package]]
name = "jobserver" name = "jobserver"
version = "0.1.35" version = "0.1.35"
@@ -5427,6 +5535,7 @@ dependencies = [
"ash", "ash",
"chrono", "chrono",
"clap", "clap",
"fpv-core",
"glam", "glam",
"gpui", "gpui",
"gstreamer", "gstreamer",
@@ -6897,6 +7006,15 @@ dependencies = [
"windows-link 0.2.1", "windows-link 0.2.1",
] ]
[[package]]
name = "windows-sys"
version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
dependencies = [
"windows-targets 0.42.2",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.48.0" version = "0.48.0"
@@ -6933,6 +7051,21 @@ dependencies = [
"windows-link 0.2.1", "windows-link 0.2.1",
] ]
[[package]]
name = "windows-targets"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
dependencies = [
"windows_aarch64_gnullvm 0.42.2",
"windows_aarch64_msvc 0.42.2",
"windows_i686_gnu 0.42.2",
"windows_i686_msvc 0.42.2",
"windows_x86_64_gnu 0.42.2",
"windows_x86_64_gnullvm 0.42.2",
"windows_x86_64_msvc 0.42.2",
]
[[package]] [[package]]
name = "windows-targets" name = "windows-targets"
version = "0.48.5" version = "0.48.5"
@@ -6990,6 +7123,12 @@ dependencies = [
"windows-link 0.1.3", "windows-link 0.1.3",
] ]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]] [[package]]
name = "windows_aarch64_gnullvm" name = "windows_aarch64_gnullvm"
version = "0.48.5" version = "0.48.5"
@@ -7008,6 +7147,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]] [[package]]
name = "windows_aarch64_msvc" name = "windows_aarch64_msvc"
version = "0.48.5" version = "0.48.5"
@@ -7026,6 +7171,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
[[package]]
name = "windows_i686_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]] [[package]]
name = "windows_i686_gnu" name = "windows_i686_gnu"
version = "0.48.5" version = "0.48.5"
@@ -7056,6 +7207,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
[[package]]
name = "windows_i686_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]] [[package]]
name = "windows_i686_msvc" name = "windows_i686_msvc"
version = "0.48.5" version = "0.48.5"
@@ -7074,6 +7231,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]] [[package]]
name = "windows_x86_64_gnu" name = "windows_x86_64_gnu"
version = "0.48.5" version = "0.48.5"
@@ -7092,6 +7255,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]] [[package]]
name = "windows_x86_64_gnullvm" name = "windows_x86_64_gnullvm"
version = "0.48.5" version = "0.48.5"
@@ -7110,6 +7279,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
[[package]] [[package]]
name = "windows_x86_64_msvc" name = "windows_x86_64_msvc"
version = "0.48.5" version = "0.48.5"
+5
View File
@@ -1,3 +1,7 @@
[workspace]
members = [".", "crates/fpv-core", "crates/fpv-android-ffi"]
resolver = "2"
[package] [package]
name = "steamframe-fpv" name = "steamframe-fpv"
version = "0.4.0" version = "0.4.0"
@@ -9,6 +13,7 @@ anyhow = "1.0"
ash = "0.38" ash = "0.38"
chrono = "0.4" chrono = "0.4"
clap = { version = "4.5", features = ["derive"] } clap = { version = "4.5", features = ["derive"] }
fpv-core = { path = "crates/fpv-core" }
glam = "0.29" glam = "0.29"
gpui = "0.2.2" gpui = "0.2.2"
gstreamer = "0.23" gstreamer = "0.23"
+15
View File
@@ -0,0 +1,15 @@
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
+1
View File
@@ -0,0 +1 @@
/build
+87
View File
@@ -0,0 +1,87 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.compose.compiler)
alias(libs.plugins.kotlin.serialization)
}
android {
namespace = "com.steamframe.fpv"
compileSdk = 36
defaultConfig {
applicationId = "com.steamframe.fpv"
minSdk = 31
targetSdk = 36
versionCode = 1
versionName = "0.4.0"
ndk {
abiFilters += "arm64-v8a"
}
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
buildFeatures {
compose = true
aidl = false
buildConfig = false
shaders = false
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}
kotlin {
jvmToolchain(17)
}
dependencies {
val composeBom = platform(libs.androidx.compose.bom)
implementation(composeBom)
androidTestImplementation(composeBom)
// Core Android dependencies
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
// Arch Components
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.lifecycle.viewmodel.compose)
// Compose
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.compose.material3)
// Tooling
debugImplementation(libs.androidx.compose.ui.tooling)
// Instrumented tests
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
debugImplementation(libs.androidx.compose.ui.test.manifest)
// Local tests: jUnit, coroutines, Android runner
testImplementation(libs.junit)
testImplementation(libs.kotlinx.coroutines.test)
// Instrumented tests: jUnit rules and runners
androidTestImplementation(libs.androidx.test.core)
androidTestImplementation(libs.androidx.test.ext.junit)
androidTestImplementation(libs.androidx.test.runner)
androidTestImplementation(libs.androidx.test.espresso.core)
// Navigation
implementation(libs.androidx.navigation3.ui)
implementation(libs.androidx.navigation3.runtime)
implementation(libs.androidx.lifecycle.viewmodel.navigation3)
}
@@ -0,0 +1,26 @@
package com.steamframe.fpv.ui.main
import androidx.activity.ComponentActivity
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithText
import org.junit.Before
import org.junit.Rule
import org.junit.Test
/** UI tests for [com.steamframe.fpv.ui.main.MainScreen]. */
class MainScreenTest {
@get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Before
fun setup() {
composeTestRule.setContent { MainScreen(FAKE_DATA) }
}
@Test
fun firstItem_exists() {
FAKE_DATA.forEach { composeTestRule.onNodeWithText("Hello $it!").assertExists() }
}
}
private val FAKE_DATA = listOf("Sample1", "Sample2", "Sample3")
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:windowSoftInputMode="adjustResize"
android:theme="@style/Theme.SteamFrameFPV">
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="sensorLandscape"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,345 @@
package com.steamframe.fpv
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Surface as ComposeSurface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import java.util.Locale
private val HudBg = Color(0x990B1018)
private val HudGreen = Color(0xFF4ADE80)
private val HudAmber = Color(0xFFFBBF24)
private val HudRed = Color(0xFFF87171)
private val HudCyan = Color(0xFF38BDF8)
@Composable
fun CockpitScreen(
snapshot: FpvSnapshot,
osdEnabled: Boolean,
dvrRecording: Boolean,
codec: String,
transport: String,
pingStatus: String,
onSurfaceReady: (Surface?) -> Unit,
onToggleDvr: () -> Unit,
onToggleOsd: () -> Unit,
onCycleCodec: () -> Unit,
onCycleTransport: () -> Unit,
onPingRadxa: () -> Unit,
) {
var controlsVisible by remember { mutableStateOf(true) }
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
) { controlsVisible = !controlsVisible },
) {
// 1. Surface vidéo plein écran zéro-copie (MediaCodec -> SurfaceView)
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { ctx ->
SurfaceView(ctx).apply {
holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
onSurfaceReady(holder.surface)
}
override fun surfaceChanged(
holder: SurfaceHolder,
format: Int,
width: Int,
height: Int,
) {
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
onSurfaceReady(null)
}
})
}
},
)
// 2. Bannière d'attente signal si aucun paquet vidéo reçu
if (!snapshot.video.signalLive) {
Box(
modifier = Modifier
.align(Alignment.Center)
.background(HudBg, RoundedCornerShape(12.dp))
.padding(horizontal = 24.dp, vertical = 14.dp),
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "EN ATTENTE DU FLUX RADXA (UDP :5600 • ${codec.uppercase()} / ${transport.uppercase()})",
color = HudAmber,
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Monospace,
)
Spacer(Modifier.height(4.dp))
Text(
text = "Branchez la Radxa Zero 3W en USB-C (usb0 : 192.168.1.1) — Tap écran pour afficher/masquer les contrôles",
color = Color(0xFFCBD5E1),
fontSize = 13.sp,
)
}
}
}
// 3. Overlay OSD FPV vectoriel net (14,6" Tab S8 Ultra)
if (osdEnabled) {
OsdOverlay(
snapshot = snapshot,
dvrRecording = dvrRecording,
modifier = Modifier
.fillMaxSize()
.padding(18.dp),
)
}
// 4. Barre de contrôles tactiles escamotable en bas
AnimatedVisibility(
visible = controlsVisible,
enter = fadeIn(),
exit = fadeOut(),
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(bottom = 18.dp),
) {
ComposeSurface(
color = Color(0xCC0F172A),
shape = RoundedCornerShape(14.dp),
) {
Row(
modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
HudActionButton(
label = if (dvrRecording) "⏹ STOP DVR" else "⏺ DVR",
containerColor = if (dvrRecording) HudRed else Color(0xFF1E293B),
onClick = onToggleDvr,
)
HudActionButton(
label = if (osdEnabled) "OSD: ON" else "OSD: OFF",
containerColor = if (osdEnabled) Color(0xFF0F766E) else Color(0xFF1E293B),
onClick = onToggleOsd,
)
HudActionButton(
label = "CODEC: ${codec.uppercase()}",
containerColor = Color(0xFF1E293B),
onClick = onCycleCodec,
)
HudActionButton(
label = "FLUX: ${transport.uppercase()}",
containerColor = Color(0xFF1E293B),
onClick = onCycleTransport,
)
HudActionButton(
label = "PING RADXA",
containerColor = Color(0xFF1D4ED8),
onClick = onPingRadxa,
)
if (pingStatus.isNotBlank()) {
Text(
text = pingStatus,
color = HudCyan,
fontSize = 13.sp,
fontFamily = FontFamily.Monospace,
modifier = Modifier.padding(horizontal = 6.dp),
)
}
}
}
}
}
}
@Composable
private fun OsdOverlay(
snapshot: FpvSnapshot,
dvrRecording: Boolean,
modifier: Modifier = Modifier,
) {
val v = snapshot.video
val t = snapshot.telemetry
val g = snapshot.g29
Box(modifier = modifier) {
// Haut-gauche : Batterie LiPo Auto-détectée
HudPill(modifier = Modifier.align(Alignment.TopStart)) {
val battColor = when {
!t.live -> Color(0xFF94A3B8)
t.cellV in 0.1f..3.50f -> HudRed
t.cellV in 3.50f..3.65f -> HudAmber
else -> HudGreen
}
val battText = if (t.live && t.batteryV > 0.5f) {
if (t.cells > 0) {
String.format(Locale.US, "BAT %.2fV (%dS • %.2fV/c)", t.batteryV, t.cells, t.cellV)
} else {
String.format(Locale.US, "BAT %.2fV", t.batteryV)
}
} else {
"BAT --.-V"
}
Text(battText, color = battColor, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, fontSize = 15.sp)
if (t.flightMode.isNotBlank()) {
Text("MODE ${t.flightMode}", color = HudCyan, fontFamily = FontFamily.Monospace, fontSize = 13.sp)
}
}
// Haut-centre : Statut Armement / DVR / Toast G29
Column(
modifier = Modifier.align(Alignment.TopCenter),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (dvrRecording) {
HudPill {
Text("● REC", color = HudRed, fontWeight = FontWeight.ExtraBold, fontFamily = FontFamily.Monospace, fontSize = 15.sp)
}
}
if (g.live) {
HudPill {
val (armLbl, armCol) = when {
g.failsafe -> "FAILSAFE" to HudRed
g.armed -> "ARMED" to HudGreen
else -> "DISARMED" to HudAmber
}
Text(armLbl, color = armCol, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, fontSize = 15.sp)
}
}
}
if (g.toast.isNotBlank()) {
Spacer(Modifier.height(6.dp))
HudPill {
Text(g.toast, color = HudCyan, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, fontSize = 16.sp)
}
}
}
// Haut-droite : Métriques Vidéo & Lien Radio ELRS
HudPill(modifier = Modifier.align(Alignment.TopEnd)) {
val fpsCol = if (v.signalLive && v.fps >= 45f) HudGreen else HudAmber
Text(
text = String.format(Locale.US, "%.0f FPS • %.1fms • %d kbps", v.fps, v.jitterMs, v.bitrateKbps),
color = fpsCol,
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Monospace,
fontSize = 15.sp,
)
val lqCol = if (t.linkQuality >= 70) HudGreen else if (t.linkQuality >= 50) HudAmber else HudRed
Text(
text = if (t.live) "LQ ${t.linkQuality}% • ${t.rssiDbm} dBm • DROP ${v.droppedPackets}" else "LQ --% • DROP ${v.droppedPackets}",
color = if (t.live) lqCol else Color(0xFF94A3B8),
fontFamily = FontFamily.Monospace,
fontSize = 13.sp,
)
}
// Bas-gauche : GPS, Vitesse & Distance Home
HudPill(modifier = Modifier.align(Alignment.BottomStart).padding(bottom = 58.dp)) {
val gpsText = if (t.gpsFix) {
String.format(Locale.US, "GPS %d sats • %.1f km/h • ALT %.0fm", t.sats, t.speedKmh, t.altitudeM)
} else {
"GPS ${t.sats} sats (NO FIX)"
}
Text(gpsText, color = if (t.gpsFix) Color.White else Color(0xFF94A3B8), fontFamily = FontFamily.Monospace, fontSize = 14.sp)
if (t.homeDistM >= 0f) {
Text(
text = String.format(Locale.US, "HOME %.0fm • CAP %.0f°", t.homeDistM, t.homeBearingDeg),
color = HudCyan,
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Monospace,
fontSize = 14.sp,
)
}
}
// Bas-droite : Boîte de vitesses G29 + Pédales
if (g.live) {
HudPill(modifier = Modifier.align(Alignment.BottomEnd).padding(bottom = 58.dp)) {
Text(
text = "RAPPORT [${g.gearLabel}] • ${g.source}",
color = Color.White,
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Monospace,
fontSize = 15.sp,
)
Text(
text = "GAZ ${g.throttlePct}% • FREIN ${g.brakePct}% • DIR ${g.steeringPct}%",
color = HudAmber,
fontFamily = FontFamily.Monospace,
fontSize = 13.sp,
)
}
}
}
}
@Composable
private fun HudPill(
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
Column(
modifier = modifier
.background(HudBg, RoundedCornerShape(10.dp))
.padding(horizontal = 12.dp, vertical = 7.dp),
) {
content()
}
}
@Composable
private fun HudActionButton(
label: String,
containerColor: Color,
onClick: () -> Unit,
) {
Button(
onClick = onClick,
colors = ButtonDefaults.buttonColors(containerColor = containerColor, contentColor = Color.White),
shape = RoundedCornerShape(8.dp),
) {
Text(text = label, fontWeight = FontWeight.SemiBold, fontSize = 13.sp)
}
}
@@ -0,0 +1,336 @@
package com.steamframe.fpv
import android.content.ContentValues
import android.content.Context
import android.media.MediaCodec
import android.media.MediaFormat
import android.media.MediaMuxer
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.Surface
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.nio.ByteBuffer
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.concurrent.atomic.AtomicBoolean
/**
* Décodeur vidéo matériel ultra-basse latence (Snapdragon 8 Gen 1 / Tab S8 Ultra)
* rendu directement en zéro-copie sur un [Surface] + enregistreur DVR MP4 (`MediaMuxer`) & `.srt`.
*/
class LowLatencyVideoDecoder(private val context: Context) {
companion object {
private const val TAG = "SteamFrameFPV.Video"
}
private val lock = Any()
private var surface: Surface? = null
private var codec: MediaCodec? = null
private var mimeType: String = MediaFormat.MIMETYPE_VIDEO_AVC
private var codecConfigured = false
private var awaitingKeyframe = true
// Cache SPS / PPS / VPS pour (re)configurer instantanément MediaCodec & MediaMuxer
private var cachedConfigNals = mutableListOf<ByteArray>()
private var drainThread: Thread? = null
private val running = AtomicBoolean(false)
// DVR MP4 natif (zéro ré-encodage) + sous-titres .srt
private var muxer: MediaMuxer? = null
private var muxerTrackIndex = -1
private var muxerStarted = false
private var dvrStartPtsUs = -1L
private var dvrFile: File? = null
private var srtWriter: BufferedWriter? = null
private var srtSeq = 0
private var lastSrtMs = -1000L
private val dvrRecording = AtomicBoolean(false)
fun isRecording(): Boolean = dvrRecording.get()
fun setSurface(newSurface: Surface?, codecName: String) {
synchronized(lock) {
releaseCodecLocked()
surface = newSurface
mimeType = if (codecName.equals("h265", ignoreCase = true) || codecName.equals("hevc", ignoreCase = true)) {
MediaFormat.MIMETYPE_VIDEO_HEVC
} else {
MediaFormat.MIMETYPE_VIDEO_AVC
}
if (newSurface != null && newSurface.isValid) {
initCodecLocked(newSurface)
}
}
}
private fun initCodecLocked(targetSurface: Surface) {
try {
val mc = MediaCodec.createDecoderByType(mimeType)
val format = MediaFormat.createVideoFormat(mimeType, 1920, 1080).apply {
setInteger(MediaFormat.KEY_LOW_LATENCY, 1)
setInteger(MediaFormat.KEY_PRIORITY, 0) // Temps réel
setInteger(MediaFormat.KEY_OPERATING_RATE, Short.MAX_VALUE.toInt())
// Clé matérielle Qualcomm (Snapdragon 8 Gen 1 / Tab S8 Ultra) pour zéro frame buffering
setInteger("vendor.qti-ext-dec-low-latency.enable", 1)
}
mc.configure(format, targetSurface, null, 0)
mc.start()
codec = mc
codecConfigured = true
awaitingKeyframe = true
running.set(true)
// Réinjecter immédiatement SPS/PPS/VPS en cache si disponibles
for (cfg in cachedConfigNals) {
queueBufferLocked(mc, cfg, 0L, MediaCodec.BUFFER_FLAG_CODEC_CONFIG)
}
drainThread = Thread({ drainLoop(mc) }, "fpv-mediacodec-drain").apply {
priority = Thread.MAX_PRIORITY
start()
}
Log.i(TAG, "MediaCodec démarré ($mimeType, Low-Latency Snapdragon actif)")
} catch (e: Exception) {
Log.e(TAG, "Échec initialisation MediaCodec ($mimeType): ${e.message}")
releaseCodecLocked()
}
}
fun submitNal(data: ByteArray, ptsUs: Long, isKeyframe: Boolean, isCodecConfig: Boolean) {
synchronized(lock) {
if (isCodecConfig) {
if (cachedConfigNals.size >= 4) cachedConfigNals.clear()
cachedConfigNals.add(data.copyOf())
}
// Enregistrement DVR MP4 zéro-CPU
if (dvrRecording.get()) {
writeDvrSampleLocked(data, ptsUs, isKeyframe, isCodecConfig)
}
val mc = codec ?: return
if (!codecConfigured) return
if (awaitingKeyframe && !isCodecConfig && !isKeyframe) {
return
}
if (isKeyframe) {
awaitingKeyframe = false
}
var flags = 0
if (isCodecConfig) flags = flags or MediaCodec.BUFFER_FLAG_CODEC_CONFIG
if (isKeyframe) flags = flags or MediaCodec.BUFFER_FLAG_KEY_FRAME
queueBufferLocked(mc, data, ptsUs, flags)
}
}
private fun queueBufferLocked(mc: MediaCodec, data: ByteArray, ptsUs: Long, flags: Int) {
try {
val idx = mc.dequeueInputBuffer(5_000)
if (idx >= 0) {
val inputBuf = mc.getInputBuffer(idx) ?: return
inputBuf.clear()
if (data.size <= inputBuf.capacity()) {
inputBuf.put(data)
mc.queueInputBuffer(idx, 0, data.size, ptsUs, flags)
} else {
mc.queueInputBuffer(idx, 0, 0, 0L, 0)
}
}
} catch (e: Exception) {
Log.w(TAG, "Erreur queueInputBuffer, réarmement décodeur: ${e.message}")
val surf = surface
releaseCodecLocked()
if (surf != null && surf.isValid) {
initCodecLocked(surf)
}
}
}
private fun drainLoop(mc: MediaCodec) {
val info = MediaCodec.BufferInfo()
while (running.get()) {
try {
val outIdx = mc.dequeueOutputBuffer(info, 10_000)
if (outIdx >= 0) {
// render = true -> affichage immédiat sur SurfaceView sans attente de PTS (latence minimale)
mc.releaseOutputBuffer(outIdx, true)
}
} catch (_: IllegalStateException) {
break
} catch (e: Exception) {
Log.w(TAG, "Erreur drainLoop MediaCodec: ${e.message}")
break
}
}
}
fun startDvr(): Boolean {
synchronized(lock) {
if (dvrRecording.get()) return true
return try {
val ts = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
val dir = File(context.getExternalFilesDir(Environment.DIRECTORY_MOVIES), "SteamFrameFPV")
dir.mkdirs()
val outFile = File(dir, "fpv_$ts.mp4")
val srtFile = File(dir, "fpv_$ts.srt")
dvrFile = outFile
muxer = MediaMuxer(outFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)
muxerTrackIndex = -1
muxerStarted = false
dvrStartPtsUs = -1L
srtWriter = BufferedWriter(FileWriter(srtFile))
srtSeq = 0
lastSrtMs = -1000L
dvrRecording.set(true)
Log.i(TAG, "DVR démarré : ${outFile.absolutePath}")
true
} catch (e: Exception) {
Log.e(TAG, "Échec démarrage DVR : ${e.message}")
false
}
}
}
fun pushSrtCaption(caption: String) {
if (!dvrRecording.get() || caption.isBlank()) return
synchronized(lock) {
val w = srtWriter ?: return
if (dvrStartPtsUs < 0L) return
val elapsedMs = ((System.nanoTime() / 1000L) - dvrStartPtsUs).coerceAtLeast(0L) / 1000L
if (elapsedMs - lastSrtMs < 950L) return
lastSrtMs = elapsedMs
srtSeq += 1
try {
w.write("$srtSeq\n${formatSrtTs(elapsedMs)} --> ${formatSrtTs(elapsedMs + 1000L)}\n$caption\n\n")
} catch (_: Exception) {
}
}
}
fun stopDvr(): String? {
synchronized(lock) {
if (!dvrRecording.getAndSet(false)) return null
val savedPath = dvrFile?.absolutePath
try {
if (muxerStarted) {
muxer?.stop()
}
muxer?.release()
} catch (e: Exception) {
Log.w(TAG, "Arrêt MediaMuxer : ${e.message}")
}
muxer = null
muxerStarted = false
muxerTrackIndex = -1
try {
srtWriter?.flush()
srtWriter?.close()
} catch (_: Exception) {
}
srtWriter = null
// Publier dans la Galerie Samsung (MediaStore) si le fichier est non vide
dvrFile?.let { f ->
if (f.exists() && f.length() > 4096) {
exportToGallery(f)
}
}
return savedPath
}
}
private fun writeDvrSampleLocked(data: ByteArray, ptsUs: Long, isKeyframe: Boolean, isCodecConfig: Boolean) {
val mx = muxer ?: return
if (!muxerStarted) {
if (!isKeyframe || cachedConfigNals.isEmpty()) return
try {
val fmt = MediaFormat.createVideoFormat(mimeType, 1920, 1080)
val csd = ByteArray(cachedConfigNals.sumOf { it.size })
var pos = 0
for (c in cachedConfigNals) {
System.arraycopy(c, 0, csd, pos, c.size)
pos += c.size
}
fmt.setByteBuffer("csd-0", ByteBuffer.wrap(csd))
muxerTrackIndex = mx.addTrack(fmt)
mx.start()
muxerStarted = true
dvrStartPtsUs = ptsUs
} catch (e: Exception) {
Log.w(TAG, "Init MediaMuxer track échouée : ${e.message}")
return
}
}
if (isCodecConfig || muxerTrackIndex < 0) return
try {
val info = MediaCodec.BufferInfo().apply {
offset = 0
size = data.size
presentationTimeUs = (ptsUs - dvrStartPtsUs).coerceAtLeast(0L)
flags = if (isKeyframe) MediaCodec.BUFFER_FLAG_KEY_FRAME else 0
}
mx.writeSampleData(muxerTrackIndex, ByteBuffer.wrap(data), info)
} catch (e: Exception) {
Log.w(TAG, "writeSampleData DVR : ${e.message}")
}
}
private fun exportToGallery(file: File) {
try {
val values = ContentValues().apply {
put(MediaStore.Video.Media.DISPLAY_NAME, file.name)
put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
put(MediaStore.Video.Media.RELATIVE_PATH, "${Environment.DIRECTORY_MOVIES}/SteamFrameFPV")
}
val resolver = context.contentResolver
val uri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values) ?: return
resolver.openOutputStream(uri)?.use { out ->
file.inputStream().use { inp -> inp.copyTo(out) }
}
} catch (e: Exception) {
Log.w(TAG, "Export Galerie ignoré : ${e.message}")
}
}
private fun formatSrtTs(ms: Long): String {
val h = ms / 3_600_000
val m = (ms % 3_600_000) / 60_000
val s = (ms % 60_000) / 1_000
val rem = ms % 1_000
return String.format(Locale.US, "%02d:%02d:%02d,%03d", h, m, s, rem)
}
fun release() {
stopDvr()
synchronized(lock) {
releaseCodecLocked()
surface = null
}
}
private fun releaseCodecLocked() {
running.set(false)
codecConfigured = false
try {
codec?.stop()
} catch (_: Exception) {
}
try {
codec?.release()
} catch (_: Exception) {
}
codec = null
try {
drainThread?.join(200)
} catch (_: Exception) {
}
drainThread = null
}
}
@@ -0,0 +1,183 @@
package com.steamframe.fpv
import android.os.Bundle
import android.view.Surface
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.util.Locale
class MainActivity : ComponentActivity() {
private lateinit var decoder: LowLatencyVideoDecoder
private var nativeHandle: Long = 0L
private var currentSurface: Surface? = null
private var snapshot by mutableStateOf(FpvSnapshot())
private var osdEnabled by mutableStateOf(true)
private var dvrRecording by mutableStateOf(false)
private var codecName by mutableStateOf("h264")
private var transportName by mutableStateOf("rtp")
private var pingStatus by mutableStateOf("")
private val radxaIp = "192.168.1.1"
private val videoPort = 5600
private val g29Port = 14552
private val telemetryPort = 14551
private val nativeCallback = object : NativeFpvCallback {
override fun onVideoNal(
data: ByteArray,
ptsUs: Long,
isKeyframe: Boolean,
isCodecConfig: Boolean,
) {
decoder.submitNal(data, ptsUs, isKeyframe, isCodecConfig)
}
override fun onG29Action(actionCode: Int) {
runOnUiThread {
when (actionCode) {
NativeFpvEngine.ACTION_TOGGLE_DVR -> toggleDvr()
NativeFpvEngine.ACTION_TOGGLE_OSD -> {
osdEnabled = !osdEnabled
syncNativeFlags()
}
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
hideSystemBars()
decoder = LowLatencyVideoDecoder(applicationContext)
restartNativeEngine()
setContent {
LaunchedEffect(Unit) {
while (true) {
val h = nativeHandle
if (h != 0L) {
val json = withContext(Dispatchers.IO) {
NativeFpvEngine.nativePollSnapshotJson(h)
}
val snap = FpvSnapshot.fromJson(json)
snapshot = snap
if (dvrRecording && snap.telemetry.srtLine.isNotBlank()) {
decoder.pushSrtCaption(snap.telemetry.srtLine)
}
}
delay(50L) // Rafraîchissement OSD 20 Hz
}
}
CockpitScreen(
snapshot = snapshot,
osdEnabled = osdEnabled,
dvrRecording = dvrRecording,
codec = codecName,
transport = transportName,
pingStatus = pingStatus,
onSurfaceReady = { surf ->
currentSurface = surf
decoder.setSurface(surf, codecName)
},
onToggleDvr = { toggleDvr() },
onToggleOsd = {
osdEnabled = !osdEnabled
syncNativeFlags()
},
onCycleCodec = {
codecName = if (codecName == "h264") "h265" else "h264"
decoder.setSurface(currentSurface, codecName)
restartNativeEngine()
},
onCycleTransport = {
transportName = if (transportName == "rtp") "raw" else "rtp"
restartNativeEngine()
},
onPingRadxa = { runPingRadxa() },
)
}
}
private fun hideSystemBars() {
WindowCompat.setDecorFitsSystemWindows(window, false)
val controller = WindowInsetsControllerCompat(window, window.decorView)
controller.hide(WindowInsetsCompat.Type.systemBars())
controller.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
private fun restartNativeEngine() {
stopNativeEngine()
nativeHandle = NativeFpvEngine.nativeStart(
callback = nativeCallback,
videoPort = videoPort,
codec = codecName,
transport = transportName,
g29Port = g29Port,
telemetryPort = telemetryPort,
)
syncNativeFlags()
}
private fun stopNativeEngine() {
val h = nativeHandle
nativeHandle = 0L
if (h != 0L) {
NativeFpvEngine.nativeStop(h)
}
}
private fun syncNativeFlags() {
val h = nativeHandle
if (h != 0L) {
NativeFpvEngine.nativeSyncUiFlags(h, dvrRecording, osdEnabled)
}
}
private fun toggleDvr() {
if (dvrRecording) {
decoder.stopDvr()
dvrRecording = false
} else {
dvrRecording = decoder.startDvr()
}
syncNativeFlags()
}
private fun runPingRadxa() {
pingStatus = "Ping..."
Thread {
val rtt = NativeFpvEngine.nativePingRadxa(radxaIp, g29Port)
runOnUiThread {
pingStatus = if (rtt >= 0f) {
String.format(Locale.US, "Radxa %.1f ms", rtt)
} else {
"Radxa hors ligne"
}
}
}.start()
}
override fun onDestroy() {
stopNativeEngine()
decoder.release()
super.onDestroy()
}
}
@@ -0,0 +1,138 @@
package com.steamframe.fpv
import org.json.JSONObject
data class VideoMetricsSnapshot(
val fps: Float = 0f,
val jitterMs: Float = 0f,
val bitrateKbps: Int = 0,
val droppedPackets: Long = 0L,
val receivedPackets: Long = 0L,
val signalLive: Boolean = false,
)
data class TelemetrySnapshot(
val live: Boolean = false,
val batteryV: Float = 0f,
val cells: Int = 0,
val cellV: Float = 0f,
val batteryPct: Int = -1,
val rssiDbm: Int = -127,
val linkQuality: Int = 0,
val sats: Int = 0,
val gpsFix: Boolean = false,
val altitudeM: Float = 0f,
val speedKmh: Float = 0f,
val homeDistM: Float = -1f,
val homeBearingDeg: Float = 0f,
val flightMode: String = "",
val srtLine: String = "",
)
data class G29Snapshot(
val live: Boolean = false,
val armed: Boolean = false,
val failsafe: Boolean = false,
val gear: Int = 0,
val gearLabel: String = "N",
val steeringPct: Int = 0,
val throttlePct: Int = 0,
val brakePct: Int = 0,
val toast: String = "",
val source: String = "Volant G29",
)
data class FpvSnapshot(
val video: VideoMetricsSnapshot = VideoMetricsSnapshot(),
val telemetry: TelemetrySnapshot = TelemetrySnapshot(),
val g29: G29Snapshot = G29Snapshot(),
) {
companion object {
fun fromJson(raw: String): FpvSnapshot {
return try {
val root = JSONObject(raw)
val v = root.optJSONObject("video")
val t = root.optJSONObject("telemetry")
val g = root.optJSONObject("g29")
FpvSnapshot(
video = if (v != null) VideoMetricsSnapshot(
fps = v.optDouble("fps", 0.0).toFloat(),
jitterMs = v.optDouble("jitterMs", 0.0).toFloat(),
bitrateKbps = v.optInt("bitrateKbps", 0),
droppedPackets = v.optLong("droppedPackets", 0L),
receivedPackets = v.optLong("receivedPackets", 0L),
signalLive = v.optBoolean("signalLive", false),
) else VideoMetricsSnapshot(),
telemetry = if (t != null) TelemetrySnapshot(
live = t.optBoolean("live", false),
batteryV = t.optDouble("batteryV", 0.0).toFloat(),
cells = t.optInt("cells", 0),
cellV = t.optDouble("cellV", 0.0).toFloat(),
batteryPct = t.optInt("batteryPct", -1),
rssiDbm = t.optInt("rssiDbm", -127),
linkQuality = t.optInt("linkQuality", 0),
sats = t.optInt("sats", 0),
gpsFix = t.optBoolean("gpsFix", false),
altitudeM = t.optDouble("altitudeM", 0.0).toFloat(),
speedKmh = t.optDouble("speedKmh", 0.0).toFloat(),
homeDistM = t.optDouble("homeDistM", -1.0).toFloat(),
homeBearingDeg = t.optDouble("homeBearingDeg", 0.0).toFloat(),
flightMode = t.optString("flightMode", ""),
srtLine = t.optString("srtLine", ""),
) else TelemetrySnapshot(),
g29 = if (g != null) G29Snapshot(
live = g.optBoolean("live", false),
armed = g.optBoolean("armed", false),
failsafe = g.optBoolean("failsafe", false),
gear = g.optInt("gear", 0),
gearLabel = g.optString("gearLabel", "N"),
steeringPct = g.optInt("steeringPct", 0),
throttlePct = g.optInt("throttlePct", 0),
brakePct = g.optInt("brakePct", 0),
toast = g.optString("toast", ""),
source = g.optString("source", "Volant G29"),
) else G29Snapshot(),
)
} catch (_: Exception) {
FpvSnapshot()
}
}
}
}
interface NativeFpvCallback {
fun onVideoNal(data: ByteArray, ptsUs: Long, isKeyframe: Boolean, isCodecConfig: Boolean)
fun onG29Action(actionCode: Int)
}
object NativeFpvEngine {
const val ACTION_TOGGLE_DVR = 1
const val ACTION_TOGGLE_OSD = 2
const val ACTION_RECENTER_HT = 3
init {
System.loadLibrary("fpv_android_ffi")
}
@JvmStatic
external fun nativeStart(
callback: NativeFpvCallback,
videoPort: Int,
codec: String,
transport: String,
g29Port: Int,
telemetryPort: Int,
): Long
@JvmStatic
external fun nativeStop(handle: Long)
@JvmStatic
external fun nativeSyncUiFlags(handle: Long, dvrActive: Boolean, osdActive: Boolean)
@JvmStatic
external fun nativePollSnapshotJson(handle: Long): String
@JvmStatic
external fun nativePingRadxa(radxaIp: String, port: Int): Float
}
@@ -0,0 +1,27 @@
package com.steamframe.fpv
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.ui.NavDisplay
import com.steamframe.fpv.ui.main.MainScreen
@Composable
fun MainNavigation() {
val backStack = rememberNavBackStack(Main)
NavDisplay(
backStack = backStack,
onBack = { backStack.removeLastOrNull() },
entryProvider =
entryProvider {
entry<Main> {
MainScreen(onItemClick = { navKey -> backStack.add(navKey) })
}
},
)
}
@@ -0,0 +1,6 @@
package com.steamframe.fpv
import androidx.navigation3.runtime.NavKey
import kotlinx.serialization.Serializable
@Serializable data object Main : NavKey
@@ -0,0 +1,12 @@
package com.steamframe.fpv.data
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
interface DataRepository {
val data: Flow<List<String>>
}
class DefaultDataRepository : DataRepository {
override val data: Flow<List<String>> = flow { emit(listOf("Android")) }
}
@@ -0,0 +1,105 @@
package com.steamframe.fpv.ui.main
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation3.runtime.NavKey
import com.steamframe.fpv.R
import com.steamframe.fpv.data.DefaultDataRepository
import com.steamframe.fpv.ui.theme.SteamFrameFPVTheme
@Composable
fun MainScreen(
onItemClick: (NavKey) -> Unit,
modifier: Modifier = Modifier,
viewModel: MainScreenViewModel = viewModel { MainScreenViewModel(DefaultDataRepository()) },
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
when (val state = uiState) {
MainScreenUiState.Loading -> {
Box(
modifier = modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
is MainScreenUiState.Success -> {
MainScreen(data = state.data, modifier = modifier)
}
is MainScreenUiState.Error -> {
Text("Error loading data: ${state.throwable.message}")
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun MainScreen(data: List<String>, modifier: Modifier = Modifier) {
Scaffold(
modifier = modifier,
topBar = {
CenterAlignedTopAppBar(
title = { Text(stringResource(R.string.app_name)) },
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
titleContentColor = MaterialTheme.colorScheme.primary
)
)
}
) { innerPadding ->
// App Content
Column(
modifier = Modifier.padding(innerPadding),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
data.forEach { Greeting(it) }
Button(
modifier = Modifier.padding(24.dp, 24.dp),
onClick = { /* Button clicked */ }
) {
Text("OK")
}
// TODO: Extend app UI with more Jetpack Compose UI elements here
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name !",
modifier = modifier.padding(16.dp, 16.dp),
style = MaterialTheme.typography.bodyLarge
)
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun MainScreenPreview() {
SteamFrameFPVTheme { MainScreen(listOf("Android")) }
}
@@ -0,0 +1,27 @@
package com.steamframe.fpv.ui.main
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.steamframe.fpv.data.DataRepository
import com.steamframe.fpv.ui.main.MainScreenUiState.Success
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
class MainScreenViewModel(dataRepository: DataRepository) : ViewModel() {
val uiState: StateFlow<MainScreenUiState> =
dataRepository.data
.map<List<String>, MainScreenUiState>(::Success)
.catch { emit(MainScreenUiState.Error(it)) }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), MainScreenUiState.Loading)
}
sealed interface MainScreenUiState {
object Loading : MainScreenUiState
data class Error(val throwable: Throwable) : MainScreenUiState
data class Success(val data: List<String>) : MainScreenUiState
}
@@ -0,0 +1,275 @@
/*
* Copyright 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.steamframe.fpv.ui.theme
import androidx.compose.ui.graphics.Color
//Start - Partial Color List
//Light Colors
val primaryLight = Color(0xFF00506E)
val primaryContainerLight = Color(0xFF23759B)
val secondaryLight = Color(0xFF486271)
val tertiaryLight = Color(0xFF613A73)
//Dark Colors
val primaryDark = Color(0xFF87CFF9)
val primaryContainerDark = Color(0xFF005C7D)
val secondaryDark = Color(0xFFB0CADC)
val tertiaryDark = Color(0xFFE6B5F8)
//End - Partial Color List
/*
//Full Color List generated by the Google Material Theme Builder
// https://material-foundation.github.io/material-theme-builder/
// Source / Primary Color: 2300668B
// Color Match: true
//Light Colors
val primaryLight = Color(0xFF00506E)
val onPrimaryLight = Color(0xFFFFFFFF)
val primaryContainerLight = Color(0xFF23759B)
val onPrimaryContainerLight = Color(0xFFFFFFFF)
val secondaryLight = Color(0xFF486271)
val onSecondaryLight = Color(0xFFFFFFFF)
val secondaryContainerLight = Color(0xFFCFEAFD)
val onSecondaryContainerLight = Color(0xFF344D5C)
val tertiaryLight = Color(0xFF613A73)
val onTertiaryLight = Color(0xFFFFFFFF)
val tertiaryContainerLight = Color(0xFF885E9A)
val onTertiaryContainerLight = Color(0xFFFFFFFF)
val errorLight = Color(0xFFBA1A1A)
val onErrorLight = Color(0xFFFFFFFF)
val errorContainerLight = Color(0xFFFFDAD6)
val onErrorContainerLight = Color(0xFF410002)
val backgroundLight = Color(0xFFF7F9FD)
val onBackgroundLight = Color(0xFF191C1F)
val surfaceLight = Color(0xFFF7F9FD)
val onSurfaceLight = Color(0xFF191C1F)
val surfaceVariantLight = Color(0xFFDBE4EB)
val onSurfaceVariantLight = Color(0xFF40484E)
val outlineLight = Color(0xFF70787E)
val outlineVariantLight = Color(0xFFBFC8CF)
val scrimLight = Color(0xFF000000)
val inverseSurfaceLight = Color(0xFF2D3133)
val inverseOnSurfaceLight = Color(0xFFEFF1F4)
val inversePrimaryLight = Color(0xFF87CFF9)
val surfaceDimLight = Color(0xFFD8DADD)
val surfaceBrightLight = Color(0xFFF7F9FD)
val surfaceContainerLowestLight = Color(0xFFFFFFFF)
val surfaceContainerLowLight = Color(0xFFF2F4F7)
val surfaceContainerLight = Color(0xFFECEEF1)
val surfaceContainerHighLight = Color(0xFFE6E8EC)
val surfaceContainerHighestLight = Color(0xFFE0E3E6)
//Light Colors - Medium Contrast
val primaryLightMediumContrast = Color(0xFF004864)
val onPrimaryLightMediumContrast = Color(0xFFFFFFFF)
val primaryContainerLightMediumContrast = Color(0xFF23759B)
val onPrimaryContainerLightMediumContrast = Color(0xFFFFFFFF)
val secondaryLightMediumContrast = Color(0xFF2D4655)
val onSecondaryLightMediumContrast = Color(0xFFFFFFFF)
val secondaryContainerLightMediumContrast = Color(0xFF5E7888)
val onSecondaryContainerLightMediumContrast = Color(0xFFFFFFFF)
val tertiaryLightMediumContrast = Color(0xFF5A336C)
val onTertiaryLightMediumContrast = Color(0xFFFFFFFF)
val tertiaryContainerLightMediumContrast = Color(0xFF885E9A)
val onTertiaryContainerLightMediumContrast = Color(0xFFFFFFFF)
val errorLightMediumContrast = Color(0xFF8C0009)
val onErrorLightMediumContrast = Color(0xFFFFFFFF)
val errorContainerLightMediumContrast = Color(0xFFDA342E)
val onErrorContainerLightMediumContrast = Color(0xFFFFFFFF)
val backgroundLightMediumContrast = Color(0xFFF7F9FD)
val onBackgroundLightMediumContrast = Color(0xFF191C1F)
val surfaceLightMediumContrast = Color(0xFFF7F9FD)
val onSurfaceLightMediumContrast = Color(0xFF191C1F)
val surfaceVariantLightMediumContrast = Color(0xFFDBE4EB)
val onSurfaceVariantLightMediumContrast = Color(0xFF3C444A)
val outlineLightMediumContrast = Color(0xFF586066)
val outlineVariantLightMediumContrast = Color(0xFF737C82)
val scrimLightMediumContrast = Color(0xFF000000)
val inverseSurfaceLightMediumContrast = Color(0xFF2D3133)
val inverseOnSurfaceLightMediumContrast = Color(0xFFEFF1F4)
val inversePrimaryLightMediumContrast = Color(0xFF87CFF9)
val surfaceDimLightMediumContrast = Color(0xFFD8DADD)
val surfaceBrightLightMediumContrast = Color(0xFFF7F9FD)
val surfaceContainerLowestLightMediumContrast = Color(0xFFFFFFFF)
val surfaceContainerLowLightMediumContrast = Color(0xFFF2F4F7)
val surfaceContainerLightMediumContrast = Color(0xFFECEEF1)
val surfaceContainerHighLightMediumContrast = Color(0xFFE6E8EC)
val surfaceContainerHighestLightMediumContrast = Color(0xFFE0E3E6)
//Light Colors - High Contrast
val primaryLightHighContrast = Color(0xFF002536)
val onPrimaryLightHighContrast = Color(0xFFFFFFFF)
val primaryContainerLightHighContrast = Color(0xFF004864)
val onPrimaryContainerLightHighContrast = Color(0xFFFFFFFF)
val secondaryLightHighContrast = Color(0xFF082533)
val onSecondaryLightHighContrast = Color(0xFFFFFFFF)
val secondaryContainerLightHighContrast = Color(0xFF2D4655)
val onSecondaryContainerLightHighContrast = Color(0xFFFFFFFF)
val tertiaryLightHighContrast = Color(0xFF361048)
val onTertiaryLightHighContrast = Color(0xFFFFFFFF)
val tertiaryContainerLightHighContrast = Color(0xFF5A336C)
val onTertiaryContainerLightHighContrast = Color(0xFFFFFFFF)
val errorLightHighContrast = Color(0xFF4E0002)
val onErrorLightHighContrast = Color(0xFFFFFFFF)
val errorContainerLightHighContrast = Color(0xFF8C0009)
val onErrorContainerLightHighContrast = Color(0xFFFFFFFF)
val backgroundLightHighContrast = Color(0xFFF7F9FD)
val onBackgroundLightHighContrast = Color(0xFF191C1F)
val surfaceLightHighContrast = Color(0xFFF7F9FD)
val onSurfaceLightHighContrast = Color(0xFF000000)
val surfaceVariantLightHighContrast = Color(0xFFDBE4EB)
val onSurfaceVariantLightHighContrast = Color(0xFF1D252A)
val outlineLightHighContrast = Color(0xFF3C444A)
val outlineVariantLightHighContrast = Color(0xFF3C444A)
val scrimLightHighContrast = Color(0xFF000000)
val inverseSurfaceLightHighContrast = Color(0xFF2D3133)
val inverseOnSurfaceLightHighContrast = Color(0xFFFFFFFF)
val inversePrimaryLightHighContrast = Color(0xFFD9EFFF)
val surfaceDimLightHighContrast = Color(0xFFD8DADD)
val surfaceBrightLightHighContrast = Color(0xFFF7F9FD)
val surfaceContainerLowestLightHighContrast = Color(0xFFFFFFFF)
val surfaceContainerLowLightHighContrast = Color(0xFFF2F4F7)
val surfaceContainerLightHighContrast = Color(0xFFECEEF1)
val surfaceContainerHighLightHighContrast = Color(0xFFE6E8EC)
val surfaceContainerHighestLightHighContrast = Color(0xFFE0E3E6)
//Dark Colors
val primaryDark = Color(0xFF87CFF9)
val onPrimaryDark = Color(0xFF00344A)
val primaryContainerDark = Color(0xFF005C7D)
val onPrimaryContainerDark = Color(0xFFF4F9FF)
val secondaryDark = Color(0xFFB0CADC)
val onSecondaryDark = Color(0xFF193342)
val secondaryContainerDark = Color(0xFF294351)
val onSecondaryContainerDark = Color(0xFFBDD8EA)
val tertiaryDark = Color(0xFFE6B5F8)
val onTertiaryDark = Color(0xFF462058)
val tertiaryContainerDark = Color(0xFF6E4680)
val onTertiaryContainerDark = Color(0xFFFFF9FB)
val errorDark = Color(0xFFFFB4AB)
val onErrorDark = Color(0xFF690005)
val errorContainerDark = Color(0xFF93000A)
val onErrorContainerDark = Color(0xFFFFDAD6)
val backgroundDark = Color(0xFF101416)
val onBackgroundDark = Color(0xFFE0E3E6)
val surfaceDark = Color(0xFF101416)
val onSurfaceDark = Color(0xFFE0E3E6)
val surfaceVariantDark = Color(0xFF40484E)
val onSurfaceVariantDark = Color(0xFFBFC8CF)
val outlineDark = Color(0xFF899298)
val outlineVariantDark = Color(0xFF40484E)
val scrimDark = Color(0xFF000000)
val inverseSurfaceDark = Color(0xFFE0E3E6)
val inverseOnSurfaceDark = Color(0xFF2D3133)
val inversePrimaryDark = Color(0xFF00668A)
val surfaceDimDark = Color(0xFF101416)
val surfaceBrightDark = Color(0xFF363A3C)
val surfaceContainerLowestDark = Color(0xFF0B0F11)
val surfaceContainerLowDark = Color(0xFF191C1F)
val surfaceContainerDark = Color(0xFF1D2023)
val surfaceContainerHighDark = Color(0xFF272A2D)
val surfaceContainerHighestDark = Color(0xFF323538)
//Dark Colors - Medium Contrast
val primaryDarkMediumContrast = Color(0xFF8BD3FD)
val onPrimaryDarkMediumContrast = Color(0xFF001925)
val primaryContainerDarkMediumContrast = Color(0xFF4E99C0)
val onPrimaryContainerDarkMediumContrast = Color(0xFF000000)
val secondaryDarkMediumContrast = Color(0xFFB4CEE1)
val onSecondaryDarkMediumContrast = Color(0xFF001925)
val secondaryContainerDarkMediumContrast = Color(0xFF7A94A5)
val onSecondaryContainerDarkMediumContrast = Color(0xFF000000)
val tertiaryDarkMediumContrast = Color(0xFFEAB9FD)
val onTertiaryDarkMediumContrast = Color(0xFF29013B)
val tertiaryContainerDarkMediumContrast = Color(0xFFAD80BF)
val onTertiaryContainerDarkMediumContrast = Color(0xFF000000)
val errorDarkMediumContrast = Color(0xFFFFBAB1)
val onErrorDarkMediumContrast = Color(0xFF370001)
val errorContainerDarkMediumContrast = Color(0xFFFF5449)
val onErrorContainerDarkMediumContrast = Color(0xFF000000)
val backgroundDarkMediumContrast = Color(0xFF101416)
val onBackgroundDarkMediumContrast = Color(0xFFE0E3E6)
val surfaceDarkMediumContrast = Color(0xFF101416)
val onSurfaceDarkMediumContrast = Color(0xFFF9FBFE)
val surfaceVariantDarkMediumContrast = Color(0xFF40484E)
val onSurfaceVariantDarkMediumContrast = Color(0xFFC3CCD3)
val outlineDarkMediumContrast = Color(0xFF9CA4AB)
val outlineVariantDarkMediumContrast = Color(0xFF7C848B)
val scrimDarkMediumContrast = Color(0xFF000000)
val inverseSurfaceDarkMediumContrast = Color(0xFFE0E3E6)
val inverseOnSurfaceDarkMediumContrast = Color(0xFF272A2D)
val inversePrimaryDarkMediumContrast = Color(0xFF004E6B)
val surfaceDimDarkMediumContrast = Color(0xFF101416)
val surfaceBrightDarkMediumContrast = Color(0xFF363A3C)
val surfaceContainerLowestDarkMediumContrast = Color(0xFF0B0F11)
val surfaceContainerLowDarkMediumContrast = Color(0xFF191C1F)
val surfaceContainerDarkMediumContrast = Color(0xFF1D2023)
val surfaceContainerHighDarkMediumContrast = Color(0xFF272A2D)
val surfaceContainerHighestDarkMediumContrast = Color(0xFF323538)
//Dark Colors - High Contrast
val primaryDarkHighContrast = Color(0xFFF8FBFF)
val onPrimaryDarkHighContrast = Color(0xFF000000)
val primaryContainerDarkHighContrast = Color(0xFF8BD3FD)
val onPrimaryContainerDarkHighContrast = Color(0xFF000000)
val secondaryDarkHighContrast = Color(0xFFF8FBFF)
val onSecondaryDarkHighContrast = Color(0xFF000000)
val secondaryContainerDarkHighContrast = Color(0xFFB4CEE1)
val onSecondaryContainerDarkHighContrast = Color(0xFF000000)
val tertiaryDarkHighContrast = Color(0xFFFFF9FB)
val onTertiaryDarkHighContrast = Color(0xFF000000)
val tertiaryContainerDarkHighContrast = Color(0xFFEAB9FD)
val onTertiaryContainerDarkHighContrast = Color(0xFF000000)
val errorDarkHighContrast = Color(0xFFFFF9F9)
val onErrorDarkHighContrast = Color(0xFF000000)
val errorContainerDarkHighContrast = Color(0xFFFFBAB1)
val onErrorContainerDarkHighContrast = Color(0xFF000000)
val backgroundDarkHighContrast = Color(0xFF101416)
val onBackgroundDarkHighContrast = Color(0xFFE0E3E6)
val surfaceDarkHighContrast = Color(0xFF101416)
val onSurfaceDarkHighContrast = Color(0xFFFFFFFF)
val surfaceVariantDarkHighContrast = Color(0xFF40484E)
val onSurfaceVariantDarkHighContrast = Color(0xFFF8FBFF)
val outlineDarkHighContrast = Color(0xFF3C444A)
val outlineVariantDarkHighContrast = Color(0xFF3C444A)
val scrimDarkHighContrast = Color(0xFF000000)
val inverseSurfaceDarkHighContrast = Color(0xFFE0E3E6)
val inverseOnSurfaceDarkHighContrast = Color(0xFF000000)
val inversePrimaryDarkHighContrast = Color(0xFF002E41)
val surfaceDimDarkHighContrast = Color(0xFF101416)
val surfaceBrightDarkHighContrast = Color(0xFF363A3C)
val surfaceContainerLowestDarkHighContrast = Color(0xFF0B0F11)
val surfaceContainerLowDarkHighContrast = Color(0xFF191C1F)
val surfaceContainerDarkHighContrast = Color(0xFF1D2023)
val surfaceContainerHighDarkHighContrast = Color(0xFF272A2D)
val surfaceContainerHighestDarkHighContrast = Color(0xFF323538)
*/
@@ -0,0 +1,65 @@
/*
* Copyright 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.steamframe.fpv.ui.theme
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = primaryDark,
primaryContainer = primaryContainerDark,
secondary = secondaryDark,
tertiary = tertiaryDark
)
private val LightColorScheme = lightColorScheme(
primary = primaryLight,
primaryContainer = primaryContainerLight,
secondary = secondaryLight,
tertiary = tertiaryLight
)
@Composable
fun SteamFrameFPVTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = false,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
@@ -0,0 +1,36 @@
package com.steamframe.fpv.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography =
Typography(
bodyLarge =
TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp,
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>
@@ -0,0 +1,30 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 982 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

@@ -0,0 +1,3 @@
<resources>
<string name="app_name">SteamFrame FPV</string>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.SteamFrameFPV" parent="android:Theme.Material.Light.NoActionBar" />
</resources>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older than API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>
@@ -0,0 +1,27 @@
package com.steamframe.fpv.ui.main
import com.steamframe.fpv.data.DataRepository
import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runTest
import org.junit.Test
class MainScreenViewModelTest {
@Test
fun uiState_initiallyLoading() = runTest {
val viewModel = MainScreenViewModel(FakeMyModelRepository())
assertEquals(viewModel.uiState.first(), MainScreenUiState.Loading)
}
@Test
fun uiState_onItemSaved_isDisplayed() = runTest {
val viewModel = MainScreenViewModel(FakeMyModelRepository())
assertEquals(viewModel.uiState.first(), MainScreenUiState.Loading)
}
}
private class FakeMyModelRepository : DataRepository {
override val data: Flow<List<String>> = flow { emit(listOf("Sample")) }
}
+6
View File
@@ -0,0 +1,6 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.compose.compiler) apply false
alias(libs.plugins.kotlin.serialization) apply false
}
+29
View File
@@ -0,0 +1,29 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# Enables Gradle Build Cache.
# See https://docs.gradle.org/current/userguide/build_cache.html
org.gradle.caching=true
# Enables Gradle Configuration Cache, the preferred Gradle execution mode.
# See https://docs.gradle.org/current/userguide/configuration_cache.html
org.gradle.configuration-cache=true
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
+43
View File
@@ -0,0 +1,43 @@
[versions]
androidGradlePlugin = "9.0.1"
androidxCore = "1.18.0"
androidxLifecycle = "2.10.0"
androidxActivity = "1.13.0"
androidxComposeBom = "2026.03.01"
androidxTest = "1.7.0"
androidxTestExt = "1.3.0"
androidxTestRunner = "1.7.0"
androidxTestEspresso = "3.7.0"
coroutines = "1.10.2"
junit = "4.13.2"
kotlin = "2.3.20"
nav3Core = "1.0.1"
lifecycleViewmodelNav3 = "2.10.0"
[libraries]
androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "androidxCore" }
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidxActivity" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "androidxComposeBom" }
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3"}
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui"}
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview"}
androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4"}
androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling"}
androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest"}
androidx-lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "androidxLifecycle" }
androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "androidxLifecycle" }
androidx-lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "androidxLifecycle" }
androidx-test-core = { module = "androidx.test:core", version.ref = "androidxTest" }
androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestExt" }
androidx-test-espresso-core = { module = "androidx.test.espresso:espresso-core", version.ref = "androidxTestEspresso" }
androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" }
junit = { module = "junit:junit", version.ref = "junit" }
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
androidx-navigation3-runtime = { module = "androidx.navigation3:navigation3-runtime", version.ref = "nav3Core" }
androidx-navigation3-ui = { module = "androidx.navigation3:navigation3-ui", version.ref = "nav3Core" }
androidx-lifecycle-viewmodel-navigation3 = { module = "androidx.lifecycle:lifecycle-viewmodel-navigation3", version.ref = "lifecycleViewmodelNav3" }
[plugins]
android-application = { id = "com.android.application", version.ref = "androidGradlePlugin" }
compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip
distributionSha256Sum=a17ddd85a26b6a7f5ddb71ff8b05fc5104c0202c6e64782429790c933686c806
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
+84
View File
@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+35
View File
@@ -0,0 +1,35 @@
pluginManagement {
repositories {
google {
content {
includeGroupByRegex("androidx.*")
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
}
}
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google {
content {
includeGroupByRegex("androidx.*")
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
}
}
mavenCentral()
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
}
rootProject.name = "SteamFrame FPV"
include(":app")
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "fpv-android-ffi"
version = "0.4.0"
edition = "2021"
description = "Bridge JNI Rust (fpv-core) -> Android (Galaxy Tab S8 Ultra) pour vidéo UDP basse latence, télémétrie CRSF/MAVLink et passerelle G29"
[lib]
name = "fpv_android_ffi"
crate-type = ["cdylib", "rlib"]
[dependencies]
fpv-core = { path = "../fpv-core" }
jni = "0.21"
log = "0.4"
parking_lot = "0.12"
[target.'cfg(target_os = "android")'.dependencies]
android_logger = "0.14"
+338
View File
@@ -0,0 +1,338 @@
use fpv_core::{
FpvControlTarget, G29BridgeReceiver, G29State, StreamTransport, TelemetryReceiver,
TelemetryState, UdpVideoMetrics, UdpVideoReceiver, VideoCodec,
};
use jni::objects::{GlobalRef, JClass, JObject, JString, JValue};
use jni::sys::{jboolean, jfloat, jint, jlong, jstring};
use jni::{JNIEnv, JavaVM};
use parking_lot::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
/// Codes d'action transmis à Kotlin lorsqu'un bouton du volant G29 (`$G29_EVT`) est pressé.
const ACTION_TOGGLE_DVR: i32 = 1;
const ACTION_TOGGLE_OSD: i32 = 2;
const ACTION_RECENTER_HT: i32 = 3;
struct AndroidControlTarget {
vm: Arc<JavaVM>,
callback: Arc<GlobalRef>,
dvr_active: Arc<AtomicBool>,
osd_active: Arc<AtomicBool>,
}
impl AndroidControlTarget {
fn dispatch_action(&self, action: i32) {
if let Ok(mut env) = self.vm.attach_current_thread() {
let _ = env.call_method(
self.callback.as_obj(),
"onG29Action",
"(I)V",
&[JValue::Int(action)],
);
if env.exception_check().unwrap_or(false) {
let _ = env.exception_clear();
}
}
}
}
impl FpvControlTarget for AndroidControlTarget {
fn request_recenter(&self) {
self.dispatch_action(ACTION_RECENTER_HT);
}
fn toggle_dvr(&self) -> bool {
let next = !self.dvr_active.load(Ordering::Acquire);
self.dvr_active.store(next, Ordering::Release);
self.dispatch_action(ACTION_TOGGLE_DVR);
next
}
fn toggle_telemetry(&self) -> bool {
let next = !self.osd_active.load(Ordering::Acquire);
self.osd_active.store(next, Ordering::Release);
self.dispatch_action(ACTION_TOGGLE_OSD);
next
}
}
struct FpvAndroidSession {
_video: UdpVideoReceiver,
video_metrics: Arc<Mutex<UdpVideoMetrics>>,
_telemetry: Option<TelemetryReceiver>,
telemetry_state: Arc<Mutex<TelemetryState>>,
_g29: Option<G29BridgeReceiver>,
g29_state: Arc<Mutex<G29State>>,
dvr_active: Arc<AtomicBool>,
osd_active: Arc<AtomicBool>,
}
fn init_logging() {
#[cfg(target_os = "android")]
{
use std::sync::Once;
static INIT: Once = Once::new();
INIT.call_once(|| {
android_logger::init_once(
android_logger::Config::default()
.with_max_level(log::LevelFilter::Info)
.with_tag("SteamFrameFPV"),
);
});
}
}
fn jstring_to_rust(env: &mut JNIEnv, s: JString) -> String {
env.get_string(&s)
.map(|js| js.into())
.unwrap_or_default()
}
fn escape_json_str(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c.is_control() => {}
c => out.push(c),
}
}
out
}
#[no_mangle]
pub extern "system" fn Java_com_steamframe_fpv_NativeFpvEngine_nativeStart(
mut env: JNIEnv,
_class: JClass,
callback: JObject,
video_port: jint,
codec: JString,
transport: JString,
g29_port: jint,
telemetry_port: jint,
) -> jlong {
init_logging();
let vm = match env.get_java_vm() {
Ok(vm) => Arc::new(vm),
Err(e) => {
log::error!("[JNI] Impossible de récupérer JavaVM : {}", e);
return 0;
}
};
let callback_ref = match env.new_global_ref(callback) {
Ok(r) => Arc::new(r),
Err(e) => {
log::error!("[JNI] Impossible de créer GlobalRef callback : {}", e);
return 0;
}
};
let codec_enum = VideoCodec::from_str(&jstring_to_rust(&mut env, codec));
let transport_enum = StreamTransport::from_str(&jstring_to_rust(&mut env, transport));
let v_port = video_port.clamp(1, 65535) as u16;
let g_port = g29_port.clamp(1, 65535) as u16;
let t_port = telemetry_port.clamp(1, 65535) as u16;
// 1. Télémétrie MAVLink / CRSF (port 14551)
let telemetry_rx = TelemetryReceiver::start("0.0.0.0", t_port).ok();
let telemetry_state = telemetry_rx
.as_ref()
.map(|rx| rx.state())
.unwrap_or_else(|| Arc::new(Mutex::new(TelemetryState::default())));
// 2. Pont unifié G29 / CRSF / $G29_EVT (port 14552)
let dvr_active = Arc::new(AtomicBool::new(false));
let osd_active = Arc::new(AtomicBool::new(true));
let control_target = AndroidControlTarget {
vm: Arc::clone(&vm),
callback: Arc::clone(&callback_ref),
dvr_active: Arc::clone(&dvr_active),
osd_active: Arc::clone(&osd_active),
};
let g29_rx = G29BridgeReceiver::start(
"0.0.0.0",
g_port,
control_target,
Some(Arc::clone(&telemetry_state)),
Vec::new(),
)
.ok();
let g29_state = g29_rx
.as_ref()
.map(|rx| rx.state())
.unwrap_or_else(|| Arc::new(Mutex::new(G29State::default())));
// 3. Récepteur vidéo UDP basse latence (port 5600) -> callback JNI vers MediaCodec
let vm_vid = Arc::clone(&vm);
let cb_vid = Arc::clone(&callback_ref);
let video_rx = match UdpVideoReceiver::start(
"0.0.0.0",
v_port,
codec_enum,
transport_enum,
move |nal| {
if let Ok(mut jenv) = vm_vid.attach_current_thread() {
if let Ok(jbytes) = jenv.byte_array_from_slice(&nal.data) {
let obj = JObject::from(jbytes);
let _ = jenv.call_method(
cb_vid.as_obj(),
"onVideoNal",
"([BJZZ)V",
&[
JValue::Object(&obj),
JValue::Long(nal.pts_us as jlong),
JValue::Bool(nal.is_keyframe as jboolean),
JValue::Bool(nal.is_codec_config as jboolean),
],
);
if jenv.exception_check().unwrap_or(false) {
let _ = jenv.exception_clear();
}
}
}
},
) {
Ok(rx) => rx,
Err(e) => {
log::error!("[JNI] Échec ouverture UDP vidéo :{} : {}", v_port, e);
return 0;
}
};
let video_metrics = video_rx.metrics();
let session = Box::new(FpvAndroidSession {
_video: video_rx,
video_metrics,
_telemetry: telemetry_rx,
telemetry_state,
_g29: g29_rx,
g29_state,
dvr_active,
osd_active,
});
Box::into_raw(session) as jlong
}
#[no_mangle]
pub extern "system" fn Java_com_steamframe_fpv_NativeFpvEngine_nativeStop(
_env: JNIEnv,
_class: JClass,
handle: jlong,
) {
if handle != 0 {
unsafe {
let _ = Box::from_raw(handle as *mut FpvAndroidSession);
}
log::info!("[JNI] Session FpvAndroidSession arrêtée proprement.");
}
}
#[no_mangle]
pub extern "system" fn Java_com_steamframe_fpv_NativeFpvEngine_nativeSyncUiFlags(
_env: JNIEnv,
_class: JClass,
handle: jlong,
dvr_active: jboolean,
osd_active: jboolean,
) {
if handle == 0 {
return;
}
let session = unsafe { &*(handle as *const FpvAndroidSession) };
session.dvr_active.store(dvr_active != 0, Ordering::Release);
session.osd_active.store(osd_active != 0, Ordering::Release);
}
#[no_mangle]
pub extern "system" fn Java_com_steamframe_fpv_NativeFpvEngine_nativePollSnapshotJson(
env: JNIEnv,
_class: JClass,
handle: jlong,
) -> jstring {
if handle == 0 {
return env
.new_string("{}")
.map(|s| s.into_raw())
.unwrap_or(std::ptr::null_mut());
}
let session = unsafe { &*(handle as *const FpvAndroidSession) };
let vm = session.video_metrics.lock().clone();
let ts = session.telemetry_state.lock().clone();
let g29 = session.g29_state.lock().clone();
let cell_v = if ts.battery_cells_detected > 0 {
ts.battery_voltage_v / ts.battery_cells_detected as f32
} else {
0.0
};
let (home_dist_m, home_brg_deg) = ts.home_vector().unwrap_or((-1.0, 0.0));
let toast = g29.active_toast().unwrap_or("");
let srt_line = ts.format_dvr_srt_caption(0, g29.gear_label(), vm.fps, vm.jitter_ms);
let json = format!(
concat!(
"{{",
"\"video\":{{\"fps\":{:.1},\"jitterMs\":{:.2},\"bitrateKbps\":{:.0},\"droppedPackets\":{},\"receivedPackets\":{},\"signalLive\":{}}},",
"\"telemetry\":{{\"live\":{},\"batteryV\":{:.2},\"cells\":{},\"cellV\":{:.2},\"batteryPct\":{},\"rssiDbm\":{},\"linkQuality\":{},\"sats\":{},\"gpsFix\":{},\"altitudeM\":{:.1},\"speedKmh\":{:.1},\"homeDistM\":{:.1},\"homeBearingDeg\":{:.1},\"flightMode\":\"{}\",\"srtLine\":\"{}\"}},",
"\"g29\":{{\"live\":{},\"armed\":{},\"failsafe\":{},\"gear\":{},\"gearLabel\":\"{}\",\"steeringPct\":{},\"throttlePct\":{},\"brakePct\":{},\"toast\":\"{}\",\"source\":\"{}\"}}",
"}}"
),
vm.fps,
vm.jitter_ms,
vm.bitrate_kbps,
vm.dropped_packets,
vm.received_packets,
vm.signal_live,
ts.is_live(),
ts.battery_voltage_v,
ts.battery_cells_detected,
cell_v,
ts.battery_remaining_pct,
ts.rssi_dbm,
ts.link_quality_pct,
ts.gps_sats,
ts.gps_fix_valid,
ts.altitude_m,
ts.groundspeed_ms * 3.6,
home_dist_m,
home_brg_deg,
escape_json_str(&ts.flight_mode),
escape_json_str(&srt_line),
g29.is_live(),
g29.armed,
g29.failsafe,
g29.gear,
escape_json_str(g29.gear_label()),
g29.steering_pct,
g29.throttle_pct,
g29.brake_pct,
escape_json_str(toast),
escape_json_str(g29.remote_source.label()),
);
env.new_string(json)
.map(|s| s.into_raw())
.unwrap_or(std::ptr::null_mut())
}
#[no_mangle]
pub extern "system" fn Java_com_steamframe_fpv_NativeFpvEngine_nativePingRadxa(
mut env: JNIEnv,
_class: JClass,
radxa_ip: JString,
port: jint,
) -> jfloat {
let ip = jstring_to_rust(&mut env, radxa_ip);
let p = port.clamp(1, 65535) as u16;
match G29BridgeReceiver::ping_radxa_relay(&ip, p) {
Ok((rtt_ms, _uart_ok)) => rtt_ms,
Err(_) => -1.0,
}
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "fpv-core"
version = "0.4.0"
edition = "2021"
description = "Cœur Rust multiplateforme (Linux / SteamOS / Android) pour SteamFrame FPV : télémétrie CRSF/MAVLink, pont G29/Nomad, réception vidéo UDP RTP/Annex-B, Replay 30s et sous-titres SRT/GPX"
[dependencies]
anyhow = "1.0"
glam = "0.29"
log = "0.4"
parking_lot = "0.12"
+58
View File
@@ -0,0 +1,58 @@
/// Source de conduite active sur la passerelle RP2350 (`G29` ou `EXT` pour manette externe / Steam Controller).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum ControlSource {
#[default]
G29 = 0,
SteamController = 1,
}
impl ControlSource {
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Self {
let lower = s.trim().to_ascii_lowercase();
if lower == "steam"
|| lower == "steam_controller"
|| lower == "steam-controller"
|| lower == "controller"
|| lower == "gamepad"
|| lower == "ext"
{
Self::SteamController
} else {
Self::G29
}
}
pub fn from_u8(v: u8) -> Self {
match v {
1 => Self::SteamController,
_ => Self::G29,
}
}
pub fn as_u8(self) -> u8 {
self as u8
}
pub fn as_str(self) -> &'static str {
match self {
Self::G29 => "g29",
Self::SteamController => "steam",
}
}
pub fn wire_tag(self) -> &'static str {
match self {
Self::G29 => "G29",
Self::SteamController => "EXT",
}
}
pub fn label(self) -> &'static str {
match self {
Self::G29 => "Volant G29",
Self::SteamController => "Steam Controller",
}
}
}
+760
View File
@@ -0,0 +1,760 @@
use crate::control_source::ControlSource;
use crate::nomad_elrs::{CRSF_CHANNEL_MAX, CRSF_CHANNEL_MID, CRSF_CHANNEL_MIN};
use crate::telemetry::{TelemetryReceiver, TelemetryState};
use anyhow::Result;
use parking_lot::Mutex;
use std::net::UdpSocket;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
/// Interface générique pilotée par les événements boutons du volant G29 (`$G29_EVT`).
/// Implémentée par `EngineControlHandle` sur Steam Frame et par le pont FFI sur Android.
pub trait FpvControlTarget: Send + Sync + 'static {
fn is_vr_menu_open(&self) -> bool {
false
}
fn toggle_vr_menu(&self) -> bool {
false
}
fn close_vr_menu(&self) -> bool {
true
}
fn vr_menu_move(&self, _delta: i32) {}
fn vr_menu_adjust(&self, _delta: i32) {}
fn vr_menu_activate(&self) {}
fn request_recenter(&self) {}
fn toggle_dvr(&self) -> bool {
false
}
fn toggle_telemetry(&self) -> bool {
false
}
fn cycle_projection_mode(&self) -> &'static str {
"Écran Plat"
}
fn adjust_head_trim(&self, _pan_delta_deg: f32, _tilt_delta_deg: f32) {}
}
const G29_TIMEOUT_MS: u64 = 1500;
const TOAST_DURATION_MS: u64 = 1500;
/// État temps réel reçu depuis le volant G29 (RP2350 -> ESP32-C3 -> UDP)
#[derive(Debug, Clone)]
pub struct G29State {
pub connected: bool,
pub failsafe: bool,
pub armed: bool,
pub gear: i8,
pub steering_pct: i8,
pub throttle_pct: u8,
pub brake_pct: u8,
pub clutch_pct: u8,
pub steer_crsf: u16,
pub throttle_crsf: u16,
pub brake_crsf: u16,
pub clutch_crsf: u16,
pub ffb_raw: u8,
pub ffb_pct: u8,
pub vib_pct: u8,
pub remote_source: ControlSource,
pub packets_received: u64,
pub last_packet: Option<Instant>,
pub last_button: String,
pub last_button_at: Option<Instant>,
pub toast_text: String,
pub toast_until: Option<Instant>,
}
impl Default for G29State {
fn default() -> Self {
Self {
connected: false,
failsafe: false,
armed: false,
gear: 0,
steering_pct: 0,
throttle_pct: 0,
brake_pct: 0,
clutch_pct: 0,
steer_crsf: CRSF_CHANNEL_MID,
throttle_crsf: CRSF_CHANNEL_MID,
brake_crsf: CRSF_CHANNEL_MID,
clutch_crsf: CRSF_CHANNEL_MID,
ffb_raw: 140,
ffb_pct: 55,
vib_pct: 50,
remote_source: ControlSource::G29,
packets_received: 0,
last_packet: None,
last_button: String::new(),
last_button_at: None,
toast_text: String::new(),
toast_until: None,
}
}
}
impl G29State {
pub fn is_live(&self) -> bool {
self.connected
&& self
.last_packet
.map(|t| t.elapsed() <= Duration::from_millis(G29_TIMEOUT_MS))
.unwrap_or(false)
}
pub fn set_toast(&mut self, msg: impl Into<String>) {
self.toast_text = msg.into();
self.toast_until = Some(Instant::now() + Duration::from_millis(TOAST_DURATION_MS));
}
pub fn active_toast(&self) -> Option<&str> {
match self.toast_until {
Some(until) if Instant::now() < until && !self.toast_text.is_empty() => {
Some(&self.toast_text)
}
_ => None,
}
}
pub fn gear_label(&self) -> &'static str {
match self.gear {
-1 => "R",
0 => "N",
1 => "1",
2 => "2",
3 => "3",
_ => "?",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum G29ButtonEvent {
Cross,
Circle,
Square,
Triangle,
Share,
Options,
Ps,
L3,
R3,
DpadUp,
DpadDown,
DpadLeft,
DpadRight,
}
impl G29ButtonEvent {
pub fn from_name(name: &str) -> Option<Self> {
match name.trim() {
"CROSS" => Some(Self::Cross),
"CIRCLE" => Some(Self::Circle),
"SQUARE" => Some(Self::Square),
"TRIANGLE" => Some(Self::Triangle),
"SHARE" => Some(Self::Share),
"OPTIONS" => Some(Self::Options),
"PS" => Some(Self::Ps),
"L3" => Some(Self::L3),
"R3" => Some(Self::R3),
"DPAD_UP" => Some(Self::DpadUp),
"DPAD_DOWN" => Some(Self::DpadDown),
"DPAD_LEFT" => Some(Self::DpadLeft),
"DPAD_RIGHT" => Some(Self::DpadRight),
_ => None,
}
}
}
/// Récepteur UDP non-bloquant pour la passerelle Wi-Fi G29
pub struct G29BridgeReceiver {
state: Arc<Mutex<G29State>>,
stop_flag: Arc<AtomicBool>,
worker: Option<thread::JoinHandle<()>>,
}
impl G29BridgeReceiver {
pub fn start(
bind_ip: &str,
port: u16,
control: impl FpvControlTarget,
telemetry: Option<Arc<Mutex<TelemetryState>>>,
allowed_peers: Vec<std::net::IpAddr>,
) -> Result<Self> {
let addr = format!("{}:{}", bind_ip, port);
let socket = UdpSocket::bind(&addr)?;
socket.set_read_timeout(Some(Duration::from_millis(100)))?;
log::info!(
"[G29 Bridge] En écoute UDP unifiée sur {} (pairs autorisés: {:?})",
addr,
allowed_peers
);
let state = Arc::new(Mutex::new(G29State::default()));
let state_clone = Arc::clone(&state);
let stop_flag = Arc::new(AtomicBool::new(false));
let stop_clone = Arc::clone(&stop_flag);
let worker = thread::Builder::new()
.name("g29-udp-rx".into())
.spawn(move || {
let mut buf = [0u8; 2048];
let mut last_reject_log: Option<Instant> = None;
while !stop_clone.load(Ordering::Acquire) {
if let Ok((len, src)) = socket.recv_from(&mut buf) {
if !Self::is_peer_allowed(src.ip(), &allowed_peers) {
if last_reject_log
.is_none_or(|t| t.elapsed() >= Duration::from_secs(5))
{
log::warn!(
"[G29 Bridge] Paquet UDP rejeté depuis IP non autorisée : {}",
src
);
last_reject_log = Some(Instant::now());
}
continue;
}
if let Ok(text) = std::str::from_utf8(&buf[..len]) {
for line in text.lines() {
Self::process_line(
line,
&state_clone,
Some(&control),
telemetry.as_ref(),
);
}
}
}
// Vérifier le timeout G29 à chaque itération (même si des trames $CRSF continuent d'arriver)
{
let mut st = state_clone.lock();
if st.connected && !st.is_live() {
st.connected = false;
st.armed = false;
st.failsafe = true;
st.gear = 0;
st.throttle_pct = 0;
st.brake_pct = 0;
st.clutch_pct = 0;
log::warn!("[G29 Bridge] Perte de liaison avec le volant G29.");
}
}
}
log::info!("[G29 Bridge] Thread d'écoute UDP arrêté.");
})?;
Ok(Self {
state,
stop_flag,
worker: Some(worker),
})
}
#[allow(dead_code)]
pub fn send_command(target_ip: &str, target_port: u16, cmd: &str) -> Result<()> {
let socket = UdpSocket::bind("0.0.0.0:0")?;
let target = format!("{}:{}", target_ip.trim(), target_port);
let trimmed = cmd.trim();
let payload = if trimmed.starts_with('$') && !trimmed.contains('*') {
crate::nomad_elrs::NomadHeadTracker::append_nmea_crc8(trimmed)
} else {
format!("{}\n", trimmed)
};
socket.send_to(payload.as_bytes(), target)?;
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 {
src_ip.is_loopback() || allowed_peers.is_empty() || allowed_peers.contains(&src_ip)
}
pub fn state(&self) -> Arc<Mutex<G29State>> {
Arc::clone(&self.state)
}
/// Vérifie et retire le suffixe CRC-8 `*XX` optionnel sur les trames `$G29` / `$G29_EVT`.
/// Si `*` est présent, le CRC-8 DVB-S2 doit être valide (sinon la trame est rejetée).
fn verify_optional_crc8(line: &str) -> Option<&str> {
if let Some((body, crc_hex)) = line.rsplit_once('*') {
if crc_hex.len() != 2 {
return None;
}
let expected = u8::from_str_radix(crc_hex, 16).ok()?;
let calc = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(body.as_bytes());
if calc == expected {
Some(body)
} else {
None
}
} else {
Some(line)
}
}
pub fn process_line(
raw_line: &str,
state: &Arc<Mutex<G29State>>,
control: Option<&dyn FpvControlTarget>,
telemetry: Option<&Arc<Mutex<TelemetryState>>>,
) {
let line = raw_line.trim();
if line.starts_with("$G29,") {
if let Some(verified) = Self::verify_optional_crc8(line) {
if let Some(rest) = verified.strip_prefix("$G29,") {
Self::parse_status_fields(rest, state);
}
}
} else if line.starts_with("$G29_EVT,") {
if let Some(verified) = Self::verify_optional_crc8(line) {
if let Some(rest) = verified.strip_prefix("$G29_EVT,") {
Self::parse_button_event(rest, state, control);
}
}
} else if let Some(hex) = line.strip_prefix("$CRSF,") {
if let Some(telem) = telemetry {
Self::parse_crsf_hex(hex, telem);
}
}
}
fn parse_crsf_hex(hex: &str, telemetry: &Arc<Mutex<TelemetryState>>) {
let bytes = hex.trim().as_bytes();
if bytes.len() < 8 || !bytes.len().is_multiple_of(2) || bytes.len() > 128 {
return;
}
let mut raw = [0u8; 64];
let mut out_len = 0;
for chunk in bytes.as_chunks::<2>().0 {
let Some(hi) = Self::hex_nibble(chunk[0]) else {
return;
};
let Some(lo) = Self::hex_nibble(chunk[1]) else {
return;
};
raw[out_len] = (hi << 4) | lo;
out_len += 1;
}
TelemetryReceiver::parse_datagram(&raw[..out_len], telemetry);
}
#[inline]
fn hex_nibble(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
fn parse_status_fields(fields: &str, state: &Arc<Mutex<G29State>>) {
let mut st = state.lock();
let had_packets = st.packets_received > 0;
let prev_ffb_pct = st.ffb_pct;
let prev_vib_pct = st.vib_pct;
for pair in fields.split(',') {
let Some((k, v)) = pair.split_once('=') else {
continue;
};
match k.trim() {
"ARM" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.armed = val != 0;
}
}
"GEAR" => {
if let Ok(val) = v.trim().parse::<i8>() {
st.gear = val.clamp(-1, 3);
}
}
"THROT" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.throttle_pct = val.min(100);
}
}
"BRAKE" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.brake_pct = val.min(100);
}
}
"CLUTCH" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.clutch_pct = val.min(100);
}
}
"STEER" => {
if let Ok(val) = v.trim().parse::<i8>() {
st.steering_pct = val.clamp(-100, 100);
}
}
"CH1" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.steer_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"CH2" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.throttle_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"CH3" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.brake_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"CH4" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.clutch_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"FFB" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.ffb_raw = val;
st.ffb_pct = ((val as u16 * 100) / 255) as u8;
}
}
"VIB" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.vib_pct = val.min(100);
}
}
"FAIL" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.failsafe = val != 0;
}
}
"SRC" => {
st.remote_source = ControlSource::from_str(v);
}
_ => {}
}
}
if !st.connected {
log::info!("[G29 Bridge] Volant G29 connecté en Wi-Fi UDP.");
}
st.connected = true;
st.packets_received = st.packets_received.wrapping_add(1);
st.last_packet = Some(Instant::now());
if had_packets && st.ffb_pct != prev_ffb_pct {
let pct = st.ffb_pct;
st.set_toast(format!("FFB {}%", pct));
} else if had_packets && st.vib_pct != prev_vib_pct {
let pct = st.vib_pct;
st.set_toast(format!("VIB {}%", pct));
}
}
fn parse_button_event(
fields: &str,
state: &Arc<Mutex<G29State>>,
control: Option<&dyn FpvControlTarget>,
) {
let Some((_, btn_name)) = fields.split_once("BTN=") else {
return;
};
let Some(btn) = G29ButtonEvent::from_name(btn_name) else {
return;
};
log::info!("[G29 Bridge] Bouton volant reçu : {:?}", btn);
let menu_open = control.map(|c| c.is_vr_menu_open()).unwrap_or(false);
let toast = match btn {
G29ButtonEvent::Options | G29ButtonEvent::L3 => {
if let Some(ctrl) = control {
let open = ctrl.toggle_vr_menu();
Some(if open {
"MENU VR ON".to_string()
} else {
"MENU VR OFF".to_string()
})
} else {
Some("MENU VR".to_string())
}
}
G29ButtonEvent::Cross if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_activate();
}
None
}
G29ButtonEvent::Circle if menu_open => {
let closed = control.map(|ctrl| ctrl.close_vr_menu()).unwrap_or(true);
Some(if closed { "MENU VR OFF" } else { "RETOUR MENU" }.to_string())
}
G29ButtonEvent::DpadUp if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_move(-1);
}
None
}
G29ButtonEvent::DpadDown if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_move(1);
}
None
}
G29ButtonEvent::DpadLeft if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_adjust(-1);
}
None
}
G29ButtonEvent::DpadRight if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_adjust(1);
}
None
}
G29ButtonEvent::Cross | G29ButtonEvent::Ps | G29ButtonEvent::R3 => {
if let Some(ctrl) = control {
ctrl.request_recenter();
}
Some("TARE HT OK".to_string())
}
G29ButtonEvent::Share | G29ButtonEvent::Circle => {
if let Some(ctrl) = control {
let now_rec = ctrl.toggle_dvr();
Some(if now_rec {
"DVR REC".to_string()
} else {
"DVR STOP".to_string()
})
} else {
Some("DVR TOGGLE".to_string())
}
}
G29ButtonEvent::Triangle => {
if let Some(ctrl) = control {
let now_on = ctrl.toggle_telemetry();
Some(if now_on {
"OSD ON".to_string()
} else {
"OSD OFF".to_string()
})
} else {
Some("OSD TOGGLE".to_string())
}
}
G29ButtonEvent::Square => {
if let Some(ctrl) = control {
let mode_lbl = ctrl.cycle_projection_mode();
Some(format!("PROJ: {}", mode_lbl))
} else {
Some("PROJ CYCLE".to_string())
}
}
G29ButtonEvent::DpadUp => {
if let Some(ctrl) = control {
ctrl.adjust_head_trim(0.0, 1.0);
}
Some("TILT +1".to_string())
}
G29ButtonEvent::DpadDown => {
if let Some(ctrl) = control {
ctrl.adjust_head_trim(0.0, -1.0);
}
Some("TILT -1".to_string())
}
G29ButtonEvent::DpadLeft => {
if let Some(ctrl) = control {
ctrl.adjust_head_trim(-1.0, 0.0);
}
Some("PAN -1".to_string())
}
G29ButtonEvent::DpadRight => {
if let Some(ctrl) = control {
ctrl.adjust_head_trim(1.0, 0.0);
}
Some("PAN +1".to_string())
}
};
{
let mut st = state.lock();
st.connected = true;
st.last_packet = Some(Instant::now());
st.last_button = btn_name.trim().to_string();
st.last_button_at = Some(Instant::now());
if let Some(msg) = toast {
st.set_toast(msg);
}
}
}
}
impl Drop for G29BridgeReceiver {
fn drop(&mut self) {
self.stop_flag.store(true, Ordering::Release);
if let Some(handle) = self.worker.take() {
let _ = handle.join();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_g29_status_and_toast() {
let state = Arc::new(Mutex::new(G29State::default()));
G29BridgeReceiver::process_line(
"$G29,ARM=1,GEAR=2,THROT=64,BRAKE=12,FFB=140,VIB=50,FAIL=0",
&state,
None,
None,
);
{
let st = state.lock();
assert!(st.connected);
assert!(st.armed);
assert_eq!(st.gear, 2);
assert_eq!(st.gear_label(), "2");
assert_eq!(st.throttle_pct, 64);
assert_eq!(st.brake_pct, 12);
assert_eq!(st.ffb_raw, 140);
assert_eq!(st.vib_pct, 50);
assert!(!st.failsafe);
}
G29BridgeReceiver::process_line(
"$G29,ARM=1,GEAR=-1,THROT=0,BRAKE=80,CLUTCH=45,STEER=-35,CH1=1280,CH2=890,CH3=1640,CH4=1360,FFB=200,VIB=50,FAIL=0,SRC=EXT",
&state,
None,
None,
);
{
let st = state.lock();
assert_eq!(st.gear_label(), "R");
assert_eq!(st.brake_pct, 80);
assert_eq!(st.clutch_pct, 45);
assert_eq!(st.steering_pct, -35);
assert_eq!(st.steer_crsf, 1280);
assert_eq!(st.throttle_crsf, 890);
assert_eq!(st.brake_crsf, 1640);
assert_eq!(st.clutch_crsf, 1360);
assert_eq!(st.remote_source, ControlSource::SteamController);
assert_eq!(st.active_toast(), Some("FFB 78%"));
}
}
#[test]
fn test_parse_g29_button_event() {
let state = Arc::new(Mutex::new(G29State::default()));
G29BridgeReceiver::process_line("$G29_EVT,BTN=CROSS", &state, None, None);
let st = state.lock();
assert_eq!(st.last_button, "CROSS");
assert_eq!(st.active_toast(), Some("TARE HT OK"));
}
#[test]
fn test_parse_crsf_telemetry_hex() {
// Trame CRSF Battery Sensor (0x08) : 16.8V (168 = 0x00A8), 12.5A (125 = 0x007D), 1200 mAh, 75%
let mut frame = [0u8; 12];
frame[0] = 0xEA;
frame[1] = 10;
frame[2] = 0x08;
frame[3] = 0x00;
frame[4] = 0xA8; // 16.8V
frame[5] = 0x00;
frame[6] = 0x7D; // 12.5A
frame[7] = 0x00;
frame[8] = 0x04;
frame[9] = 0xB0; // 1200 mAh
frame[10] = 75; // 75%
frame[11] = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(&frame[2..11]);
let hex: String = frame.iter().map(|b| format!("{:02X}", b)).collect();
let line = format!("$CRSF,{}", hex);
let g29_state = Arc::new(Mutex::new(G29State::default()));
let telem_state = Arc::new(Mutex::new(TelemetryState::default()));
G29BridgeReceiver::process_line(&line, &g29_state, None, Some(&telem_state));
let ts = telem_state.lock();
assert_eq!(ts.packets_received, 1);
assert!((ts.battery_voltage_v - 16.8).abs() < 0.01);
assert!((ts.battery_current_a - 12.5).abs() < 0.01);
assert_eq!(ts.battery_remaining_pct, 75);
}
#[test]
fn test_udp_peer_allowlist() {
use std::net::{IpAddr, Ipv4Addr};
let allowed = vec![IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))];
assert!(G29BridgeReceiver::is_peer_allowed(
IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)),
&allowed
));
assert!(G29BridgeReceiver::is_peer_allowed(
IpAddr::V4(Ipv4Addr::LOCALHOST),
&allowed
));
assert!(!G29BridgeReceiver::is_peer_allowed(
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 99)),
&allowed
));
assert!(G29BridgeReceiver::is_peer_allowed(
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 99)),
&[]
));
}
#[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);
}
}
+21
View File
@@ -0,0 +1,21 @@
//! Cœur Rust multiplateforme (Linux / SteamOS / Android) de SteamFrame FPV.
//!
//! Ne dépend d'aucune bibliothèque graphique ou système Linux (`gpui`, `gstreamer`,
//! `openxr`, `ash`, `hidraw`) afin de se compiler directement en `aarch64-linux-android`.
pub mod control_source;
pub mod g29_bridge;
pub mod nomad_elrs;
pub mod telemetry;
pub mod video_udp;
pub use control_source::ControlSource;
pub use g29_bridge::{FpvControlTarget, G29BridgeReceiver, G29ButtonEvent, G29State};
pub use nomad_elrs::{
NomadHeadTracker, NomadProtocol, CRSF_CHANNEL_MAX, CRSF_CHANNEL_MID, CRSF_CHANNEL_MIN,
MSP_ELRS_BACKPACK_SET_PTR,
};
pub use telemetry::{TelemetryReceiver, TelemetryState};
pub use video_udp::{
RtpDepacketizer, StreamTransport, UdpVideoMetrics, UdpVideoReceiver, VideoCodec, VideoNalUnit,
};
+523
View File
@@ -0,0 +1,523 @@
use anyhow::{anyhow, Result};
use glam::{EulerRot, Quat};
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
use std::time::{Duration, Instant};
/// Opcode MSPv2 officiel ExpressLRS Backpack pour le Head Tracking (Pan, Tilt, Roll)
pub const MSP_ELRS_BACKPACK_SET_PTR: u16 = 0x0383;
/// Bornes CRSF standard (11 bits : 172 = 988µs, 992 = 1500µs, 1811 = 2012µs)
pub const CRSF_CHANNEL_MIN: u16 = 172;
pub const CRSF_CHANNEL_MID: u16 = 992;
pub const CRSF_CHANNEL_MAX: u16 = 1811;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NomadProtocol {
/// MSPv2 ELRS_BACKPACK_SET_PTR (0x0383) — mode AP Head-Tracking classique
Msp,
/// CRSF RC_CHANNELS_PACKED (0x16)
Crsf,
/// MAVLink v1 RC_CHANNELS_OVERRIDE (msgid 70) — compatible UDP Backpack /mavlink (port 14555)
Mavlink,
/// Pont unifié G29 / Radxa Zero 3W ($HT,<pan>,<tilt>,<roll>) — 100% filaire via usb0:14552
G29Bridge,
}
impl NomadProtocol {
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Self {
if s.eq_ignore_ascii_case("g29")
|| s.eq_ignore_ascii_case("g29_bridge")
|| s.eq_ignore_ascii_case("radxa")
{
Self::G29Bridge
} else if s.eq_ignore_ascii_case("crsf") {
Self::Crsf
} else if s.eq_ignore_ascii_case("mavlink") || s.eq_ignore_ascii_case("mav") {
Self::Mavlink
} else {
Self::Msp
}
}
pub fn label(self) -> &'static str {
match self {
Self::Msp => "MSPv2 0x0383",
Self::Crsf => "CRSF 0x16",
Self::Mavlink => "MAVLink v1 (RC Override)",
Self::G29Bridge => "G29 Hub ($HT)",
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct HeadPoseSample {
pub pan_deg: f32,
pub tilt_deg: f32,
pub roll_deg: f32,
pub pan_crsf: u16,
pub tilt_crsf: u16,
pub roll_crsf: u16,
pub packets_sent: u64,
pub send_errors: u64,
pub last_send_ok: bool,
}
impl Default for HeadPoseSample {
fn default() -> Self {
Self {
pan_deg: 0.0,
tilt_deg: 0.0,
roll_deg: 0.0,
pan_crsf: CRSF_CHANNEL_MID,
tilt_crsf: CRSF_CHANNEL_MID,
roll_crsf: CRSF_CHANNEL_MID,
packets_sent: 0,
send_errors: 0,
last_send_ok: false,
}
}
}
pub struct NomadHeadTracker {
socket: UdpSocket,
target: SocketAddr,
zero_quat_inv: Quat,
max_pan_deg: f32,
max_tilt_deg: f32,
max_roll_deg: f32,
protocol: NomadProtocol,
mav_seq: u8,
last_mav_heartbeat: Option<Instant>,
packets_sent: u64,
send_errors: u64,
last_error_log: Option<Instant>,
}
impl NomadHeadTracker {
pub fn new(
nomad_ip: &str,
nomad_port: u16,
max_pan_deg: f32,
max_tilt_deg: f32,
max_roll_deg: f32,
protocol: NomadProtocol,
) -> Result<Self> {
let trimmed_ip = nomad_ip.trim();
let host_port = format!("{}:{}", trimmed_ip, nomad_port);
let target = if let Ok(ip) = trimmed_ip.parse::<std::net::IpAddr>() {
SocketAddr::new(ip, nomad_port)
} else {
let addrs: Vec<SocketAddr> = host_port
.to_socket_addrs()
.map_err(|e| {
log::error!(
"[Wi-Fi Nomad] Impossible de résoudre la cible ({}) : {}",
host_port,
e
);
e
})?
.collect();
addrs
.iter()
.copied()
.find(|a| a.is_ipv4())
.or_else(|| addrs.into_iter().next())
.ok_or_else(|| anyhow!("Aucune adresse IP résolue pour {}", host_port))?
};
let bind_addr = if target.is_ipv6() { "[::]:0" } else { "0.0.0.0:0" };
let socket = UdpSocket::bind(bind_addr).map_err(|e| {
log::error!(
"[Wi-Fi Nomad] Impossible de créer le socket UDP sortant : {}",
e
);
e
})?;
socket.set_nonblocking(true)?;
log::info!(
"[Wi-Fi Nomad] Émetteur prêt vers {} ({}) (Protocole: {})",
host_port,
target,
protocol.label()
);
Ok(Self {
socket,
target,
zero_quat_inv: Quat::IDENTITY,
max_pan_deg,
max_tilt_deg,
max_roll_deg,
protocol,
mav_seq: 0,
last_mav_heartbeat: None,
packets_sent: 0,
send_errors: 0,
last_error_log: None,
})
}
/// Réinitialise le centre du suivi de tête (Tare) sur la posture actuelle du casque
pub fn recenter(&mut self, current_orientation: Quat) {
let safe_q = if current_orientation.is_finite()
&& current_orientation.length_squared() > 1e-8
{
current_orientation.normalize()
} else {
Quat::IDENTITY
};
self.zero_quat_inv = safe_q.inverse();
log::info!("[Head-Tracker] Centre (Tare) réinitialisé sur la position actuelle du casque.");
}
/// Calcule Pan/Tilt/Roll depuis le quaternion OpenXR et envoie la trame UDP au Nomad
pub fn send_pose(&mut self, current_orientation: Quat) -> Result<HeadPoseSample> {
let raw_rel = self.zero_quat_inv * current_orientation;
let relative = if raw_rel.is_finite() && raw_rel.length_squared() > 1e-8 {
raw_rel.normalize()
} else {
Quat::IDENTITY
};
let (yaw_rad, pitch_rad, roll_rad) = relative.to_euler(EulerRot::YXZ);
let pan_deg = -yaw_rad.to_degrees();
let tilt_deg = pitch_rad.to_degrees();
let roll_deg = -roll_rad.to_degrees();
self.send_manual_angles(pan_deg, tilt_deg, roll_deg)
}
/// Encode et envoie directement des angles Pan/Tilt/Roll (en degrés) vers la cible UDP
pub fn send_manual_angles(
&mut self,
pan_deg: f32,
tilt_deg: f32,
roll_deg: f32,
) -> Result<HeadPoseSample> {
let pan_crsf = Self::deg_to_crsf(pan_deg, self.max_pan_deg);
let tilt_crsf = Self::deg_to_crsf(tilt_deg, self.max_tilt_deg);
let roll_crsf = Self::deg_to_crsf(roll_deg, self.max_roll_deg);
let send_res = match self.protocol {
NomadProtocol::Crsf => {
let packet = Self::encode_crsf_rc_channels(pan_crsf, tilt_crsf, roll_crsf);
self.socket.send_to(&packet, self.target)
}
NomadProtocol::Msp => {
let packet = Self::encode_mspv2_ptr(pan_crsf, tilt_crsf, roll_crsf);
self.socket.send_to(&packet, self.target)
}
NomadProtocol::Mavlink => {
if self
.last_mav_heartbeat
.is_none_or(|t| t.elapsed() >= Duration::from_secs(1))
{
let hb = Self::encode_mavlink_heartbeat(self.mav_seq);
self.mav_seq = self.mav_seq.wrapping_add(1);
let _ = self.socket.send_to(&hb, self.target);
self.last_mav_heartbeat = Some(Instant::now());
}
let packet = Self::encode_mavlink_rc_override(
pan_crsf,
tilt_crsf,
roll_crsf,
self.mav_seq,
);
self.mav_seq = self.mav_seq.wrapping_add(1);
self.socket.send_to(&packet, self.target)
}
NomadProtocol::G29Bridge => {
let msg = Self::encode_g29_ht(pan_crsf, tilt_crsf, roll_crsf);
self.socket.send_to(msg.as_bytes(), self.target)
}
};
let last_send_ok = match send_res {
Ok(_) => {
self.packets_sent = self.packets_sent.wrapping_add(1);
true
}
Err(e) => {
self.send_errors = self.send_errors.wrapping_add(1);
let should_log = self
.last_error_log
.map(|t| t.elapsed() >= Duration::from_secs(3))
.unwrap_or(true);
if should_log {
log::error!(
"[Wi-Fi Nomad] Échec d'envoi UDP vers {} : {} (Vérifiez la connexion Wi-Fi au Backpack du RadioMaster Nomad)",
self.target,
e
);
self.last_error_log = Some(Instant::now());
}
false
}
};
Ok(HeadPoseSample {
pan_deg,
tilt_deg,
roll_deg,
pan_crsf,
tilt_crsf,
roll_crsf,
packets_sent: self.packets_sent,
send_errors: self.send_errors,
last_send_ok,
})
}
#[inline]
pub fn deg_to_crsf(angle_deg: f32, max_deg: f32) -> u16 {
if !angle_deg.is_finite() || !max_deg.is_finite() || max_deg <= 0.0 {
return CRSF_CHANNEL_MID;
}
let norm = (angle_deg / max_deg).clamp(-1.0, 1.0);
let crsf_val = if norm >= 0.0 {
CRSF_CHANNEL_MID as f32 + norm * (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32
} else {
CRSF_CHANNEL_MID as f32 + norm * (CRSF_CHANNEL_MID - CRSF_CHANNEL_MIN) as f32
};
(crsf_val.round() as u16).clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX)
}
/// Ajoute un suffixe CRC-8 DVB-S2 (`*XX\n`) à une trame texte `$...` pour validation UART RP2350.
pub fn append_nmea_crc8(payload: &str) -> String {
let crc = Self::crc8_dvb_s2(payload.as_bytes());
format!("{}*{:02X}\n", payload, crc)
}
pub fn encode_g29_ht(pan: u16, tilt: u16, roll: u16) -> String {
Self::append_nmea_crc8(&format!("$HT,{},{},{}", pan, tilt, roll))
}
pub fn encode_mspv2_ptr(pan: u16, tilt: u16, roll: u16) -> [u8; 15] {
let mut buf = [0u8; 15];
buf[0] = b'$';
buf[1] = b'X';
buf[2] = b'<';
buf[3] = 0x00;
buf[4..6].copy_from_slice(&MSP_ELRS_BACKPACK_SET_PTR.to_le_bytes());
buf[6..8].copy_from_slice(&6u16.to_le_bytes());
buf[8..10].copy_from_slice(&pan.to_le_bytes());
buf[10..12].copy_from_slice(&tilt.to_le_bytes());
buf[12..14].copy_from_slice(&roll.to_le_bytes());
buf[14] = Self::crc8_dvb_s2(&buf[3..14]);
buf
}
pub fn encode_crsf_rc_channels(pan: u16, tilt: u16, roll: u16) -> [u8; 26] {
let mut ch = [CRSF_CHANNEL_MID; 16];
ch[0] = pan.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
ch[1] = tilt.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
ch[2] = roll.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
let mut frame = [0u8; 26];
frame[0] = 0xEE;
frame[1] = 24;
frame[2] = 0x16;
let mut bit_buf: u32 = 0;
let mut bits_in_buf: u8 = 0;
let mut byte_idx = 3;
for &val in &ch {
bit_buf |= ((val & 0x07FF) as u32) << bits_in_buf;
bits_in_buf += 11;
while bits_in_buf >= 8 {
frame[byte_idx] = (bit_buf & 0xFF) as u8;
byte_idx += 1;
bit_buf >>= 8;
bits_in_buf -= 8;
}
}
frame[25] = Self::crc8_dvb_s2(&frame[2..25]);
frame
}
/// Convertit une valeur CRSF (172..1811, neutre 992) en microsecondes PWM (988..2012, neutre 1500)
#[inline]
pub fn crsf_to_pwm_us(crsf: u16) -> u16 {
let clamped = crsf.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX) as f32;
if clamped >= CRSF_CHANNEL_MID as f32 {
let norm = (clamped - CRSF_CHANNEL_MID as f32) / (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32;
(1500.0 + norm * 512.0).round() as u16
} else {
let norm = (clamped - CRSF_CHANNEL_MID as f32) / (CRSF_CHANNEL_MID - CRSF_CHANNEL_MIN) as f32;
(1500.0 + norm * 512.0).round() as u16
}
}
/// Encode une trame MAVLink v1 HEARTBEAT (msgid=0, crc_extra=50) pour s'identifier auprès du Backpack
pub fn encode_mavlink_heartbeat(seq: u8) -> [u8; 17] {
let mut payload = [0u8; 9];
payload[4] = 6; // MAV_TYPE_GCS
payload[5] = 8; // MAV_AUTOPILOT_INVALID
payload[8] = 3; // mavlink_version
Self::encode_mavlink_v1_frame::<9, 17>(0, seq, 50, &payload)
}
/// Encode une trame MAVLink v1 RC_CHANNELS_OVERRIDE (msgid=70, crc_extra=124) sur les canaux 1..3
pub fn encode_mavlink_rc_override(pan: u16, tilt: u16, roll: u16, seq: u8) -> [u8; 26] {
let mut payload = [0u8; 18];
let ch1 = Self::crsf_to_pwm_us(pan);
let ch2 = Self::crsf_to_pwm_us(tilt);
let ch3 = Self::crsf_to_pwm_us(roll);
let ignore = u16::MAX;
payload[0..2].copy_from_slice(&ch1.to_le_bytes());
payload[2..4].copy_from_slice(&ch2.to_le_bytes());
payload[4..6].copy_from_slice(&ch3.to_le_bytes());
payload[6..8].copy_from_slice(&ignore.to_le_bytes());
payload[8..10].copy_from_slice(&ignore.to_le_bytes());
payload[10..12].copy_from_slice(&ignore.to_le_bytes());
payload[12..14].copy_from_slice(&ignore.to_le_bytes());
payload[14..16].copy_from_slice(&ignore.to_le_bytes());
payload[16] = 1; // target_system
payload[17] = 1; // target_component
Self::encode_mavlink_v1_frame::<18, 26>(70, seq, 124, &payload)
}
fn encode_mavlink_v1_frame<const P: usize, const T: usize>(
msgid: u8,
seq: u8,
crc_extra: u8,
payload: &[u8; P],
) -> [u8; T] {
debug_assert_eq!(T, P + 8);
let mut buf = [0u8; T];
buf[0] = 0xFE;
buf[1] = P as u8;
buf[2] = seq;
buf[3] = 255; // GCS system_id
buf[4] = 190; // MAV_COMP_ID_MISSIONPLANNER / GCS
buf[5] = msgid;
buf[6..6 + P].copy_from_slice(payload);
let crc = Self::mavlink_crc16(&buf[1..6 + P], crc_extra);
buf[6 + P..8 + P].copy_from_slice(&crc.to_le_bytes());
buf
}
#[inline]
pub fn mavlink_crc16(data: &[u8], crc_extra: u8) -> u16 {
let mut crc: u16 = 0xFFFF;
for &b in data.iter().chain(std::iter::once(&crc_extra)) {
let mut tmp = b ^ (crc & 0xFF) as u8;
tmp ^= tmp << 4;
crc = (crc >> 8)
^ ((tmp as u16) << 8)
^ ((tmp as u16) << 3)
^ ((tmp as u16) >> 4);
}
crc
}
#[inline]
pub fn crc8_dvb_s2(data: &[u8]) -> u8 {
const TABLE: [u8; 256] = {
let mut table = [0u8; 256];
let mut i = 0;
while i < 256 {
let mut curr = i as u8;
let mut j = 0;
while j < 8 {
if (curr & 0x80) != 0 {
curr = (curr << 1) ^ 0xD5;
} else {
curr <<= 1;
}
j += 1;
}
table[i] = curr;
i += 1;
}
table
};
let mut crc: u8 = 0;
for &byte in data {
crc = TABLE[(crc ^ byte) as usize];
}
crc
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_deg_to_crsf_bounds() {
assert_eq!(NomadHeadTracker::deg_to_crsf(0.0, 90.0), CRSF_CHANNEL_MID);
assert_eq!(NomadHeadTracker::deg_to_crsf(90.0, 90.0), CRSF_CHANNEL_MAX);
assert_eq!(NomadHeadTracker::deg_to_crsf(-90.0, 90.0), CRSF_CHANNEL_MIN);
assert_eq!(NomadHeadTracker::deg_to_crsf(f32::NAN, 90.0), CRSF_CHANNEL_MID);
assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, f32::NAN), CRSF_CHANNEL_MID);
assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, 0.0), CRSF_CHANNEL_MID);
assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, -10.0), CRSF_CHANNEL_MID);
}
#[test]
fn test_mspv2_ptr_packet_header() {
let pkt = NomadHeadTracker::encode_mspv2_ptr(992, 992, 992);
assert_eq!(&pkt[0..3], b"$X<");
assert_eq!(u16::from_le_bytes([pkt[4], pkt[5]]), MSP_ELRS_BACKPACK_SET_PTR);
assert_eq!(u16::from_le_bytes([pkt[6], pkt[7]]), 6);
assert_eq!(pkt[14], NomadHeadTracker::crc8_dvb_s2(&pkt[3..14]));
}
#[test]
fn test_crsf_rc_channels_packet() {
let pkt = NomadHeadTracker::encode_crsf_rc_channels(992, 992, 992);
assert_eq!(pkt[0], 0xEE); // Sync CRSF
assert_eq!(pkt[1], 24); // Payload len
assert_eq!(pkt[2], 0x16); // Type RC_CHANNELS_PACKED
assert_eq!(pkt[25], NomadHeadTracker::crc8_dvb_s2(&pkt[2..25]));
}
#[test]
fn test_mavlink_rc_override_packet() {
assert_eq!(NomadHeadTracker::crsf_to_pwm_us(992), 1500);
let pkt = NomadHeadTracker::encode_mavlink_rc_override(992, 992, 992, 7);
assert_eq!(pkt[0], 0xFE);
assert_eq!(pkt[1], 18);
assert_eq!(pkt[2], 7);
assert_eq!(pkt[5], 70);
assert_eq!(u16::from_le_bytes([pkt[6], pkt[7]]), 1500);
assert_eq!(u16::from_le_bytes([pkt[8], pkt[9]]), 1500);
assert_eq!(u16::from_le_bytes([pkt[10], pkt[11]]), 1500);
let expected_crc = NomadHeadTracker::mavlink_crc16(&pkt[1..24], 124);
assert_eq!(u16::from_le_bytes([pkt[24], pkt[25]]), expected_crc);
}
#[test]
fn test_mavlink_heartbeat_packet() {
let pkt = NomadHeadTracker::encode_mavlink_heartbeat(1);
assert_eq!(pkt[0], 0xFE);
assert_eq!(pkt[1], 9);
assert_eq!(pkt[5], 0);
let expected_crc = NomadHeadTracker::mavlink_crc16(&pkt[1..15], 50);
assert_eq!(u16::from_le_bytes([pkt[15], pkt[16]]), expected_crc);
}
#[test]
fn test_hostname_resolution_default_ip() {
let ht = NomadHeadTracker::new("10.0.0.1", 14550, 90.0, 60.0, 45.0, NomadProtocol::Msp);
assert!(ht.is_ok());
}
#[test]
fn test_g29_bridge_ht_format() {
assert_eq!(NomadProtocol::from_str("g29"), NomadProtocol::G29Bridge);
let frame = NomadHeadTracker::encode_g29_ht(992, 1200, 800);
let (body, hex_crc) = frame.trim_end_matches('\n').split_once('*').unwrap();
assert_eq!(body, "$HT,992,1200,800");
let expected = format!("{:02X}", NomadHeadTracker::crc8_dvb_s2(body.as_bytes()));
assert_eq!(hex_crc, expected);
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod parser;
pub mod state;
pub use parser::TelemetryReceiver;
pub use state::TelemetryState;
File renamed without changes.
File renamed without changes.
+591
View File
@@ -0,0 +1,591 @@
use anyhow::Result;
use parking_lot::Mutex;
use std::net::UdpSocket;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
const ANNEX_B_START_CODE: [u8; 4] = [0x00, 0x00, 0x00, 0x01];
const SIGNAL_LOST_AFTER: Duration = Duration::from_secs(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VideoCodec {
H264,
H265,
}
impl VideoCodec {
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Self {
if s.eq_ignore_ascii_case("h265") || s.eq_ignore_ascii_case("hevc") {
Self::H265
} else {
Self::H264
}
}
pub fn mime_type(self) -> &'static str {
match self {
Self::H264 => "video/avc",
Self::H265 => "video/hevc",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StreamTransport {
Rtp,
Raw,
}
impl StreamTransport {
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Self {
if s.eq_ignore_ascii_case("raw") || s.eq_ignore_ascii_case("annexb") {
Self::Raw
} else {
Self::Rtp
}
}
}
/// Unité NAL ou Access Unit prête pour `MediaCodec` / `MediaMuxer` (format Annex-B `00 00 00 01 ...`).
#[derive(Debug, Clone)]
pub struct VideoNalUnit {
pub data: Vec<u8>,
pub pts_us: u64,
pub is_keyframe: bool,
pub is_codec_config: bool,
}
/// Métriques temps réel de la liaison vidéo UDP.
#[derive(Debug, Clone, Default)]
pub struct UdpVideoMetrics {
pub fps: f32,
pub jitter_ms: f32,
pub bitrate_kbps: f32,
pub received_packets: u64,
pub dropped_packets: u64,
pub signal_live: bool,
}
/// Détecte si un NAL (sans start code) est une image clé (IDR / IRAP) ou une config codec (VPS / SPS / PPS).
pub fn classify_nal(codec: VideoCodec, nal_header_byte: u8) -> (bool, bool) {
match codec {
VideoCodec::H264 => {
let nal_type = nal_header_byte & 0x1F;
let is_keyframe = nal_type == 5;
let is_config = matches!(nal_type, 7 | 8);
(is_keyframe, is_config)
}
VideoCodec::H265 => {
let nal_type = (nal_header_byte >> 1) & 0x3F;
let is_keyframe = matches!(nal_type, 19..=21);
let is_config = matches!(nal_type, 32..=34);
(is_keyframe, is_config)
}
}
}
/// Dépaqueteur RTP pur Rust (RFC 6184 H.264 / RFC 7798 H.265) sans dépendance GStreamer.
pub struct RtpDepacketizer {
codec: VideoCodec,
last_seq: Option<u16>,
fu_buf: Vec<u8>,
fu_active: bool,
fu_keyframe: bool,
fu_config: bool,
pub dropped_packets: u64,
}
impl RtpDepacketizer {
pub fn new(codec: VideoCodec) -> Self {
Self {
codec,
last_seq: None,
fu_buf: Vec::with_capacity(64 * 1024),
fu_active: false,
fu_keyframe: false,
fu_config: false,
dropped_packets: 0,
}
}
/// Traite un paquet UDP RTP brut et appelle `emit` pour chaque unité NAL complète (Annex-B).
pub fn push_rtp_packet<F>(&mut self, packet: &[u8], pts_us: u64, mut emit: F)
where
F: FnMut(VideoNalUnit),
{
// En-tête RTP minimal : 12 octets
if packet.len() < 12 {
return;
}
let v = packet[0] >> 6;
if v != 2 {
return;
}
let has_padding = (packet[0] & 0x20) != 0;
let has_extension = (packet[0] & 0x10) != 0;
let csrc_count = (packet[0] & 0x0F) as usize;
let seq = u16::from_be_bytes([packet[2], packet[3]]);
if let Some(prev) = self.last_seq {
let expected = prev.wrapping_add(1);
if seq != expected {
let gap = seq.wrapping_sub(expected) as u64;
if gap < 1000 {
self.dropped_packets = self.dropped_packets.saturating_add(gap);
}
// Fragmentation en cours invalidée par une perte de paquet
self.fu_active = false;
self.fu_buf.clear();
}
}
self.last_seq = Some(seq);
let mut offset = 12 + csrc_count * 4;
if offset > packet.len() {
return;
}
if has_extension {
if offset + 4 > packet.len() {
return;
}
let ext_words = u16::from_be_bytes([packet[offset + 2], packet[offset + 3]]) as usize;
offset += 4 + ext_words * 4;
if offset > packet.len() {
return;
}
}
let end = if has_padding {
let pad = packet[packet.len() - 1] as usize;
if pad == 0 || offset + pad > packet.len() {
return;
}
packet.len() - pad
} else {
packet.len()
};
let payload = &packet[offset..end];
if payload.is_empty() {
return;
}
match self.codec {
VideoCodec::H264 => self.handle_h264_payload(payload, pts_us, &mut emit),
VideoCodec::H265 => self.handle_h265_payload(payload, pts_us, &mut emit),
}
}
fn handle_h264_payload<F>(&mut self, payload: &[u8], pts_us: u64, emit: &mut F)
where
F: FnMut(VideoNalUnit),
{
let nal_type = payload[0] & 0x1F;
match nal_type {
1..=23 => {
self.fu_active = false;
self.fu_buf.clear();
let (is_keyframe, is_codec_config) = classify_nal(VideoCodec::H264, payload[0]);
let mut data = Vec::with_capacity(4 + payload.len());
data.extend_from_slice(&ANNEX_B_START_CODE);
data.extend_from_slice(payload);
emit(VideoNalUnit {
data,
pts_us,
is_keyframe,
is_codec_config,
});
}
24 => {
// STAP-A : plusieurs NAL préfixés par leur longueur sur 16 bits
self.fu_active = false;
self.fu_buf.clear();
let mut idx = 1usize;
while idx + 2 <= payload.len() {
let nalu_len = u16::from_be_bytes([payload[idx], payload[idx + 1]]) as usize;
idx += 2;
if nalu_len == 0 || idx + nalu_len > payload.len() {
break;
}
let nalu = &payload[idx..idx + nalu_len];
let (is_keyframe, is_codec_config) = classify_nal(VideoCodec::H264, nalu[0]);
let mut data = Vec::with_capacity(4 + nalu.len());
data.extend_from_slice(&ANNEX_B_START_CODE);
data.extend_from_slice(nalu);
emit(VideoNalUnit {
data,
pts_us,
is_keyframe,
is_codec_config,
});
idx += nalu_len;
}
}
28 => {
// FU-A : NAL fragmenté sur plusieurs paquets RTP
if payload.len() < 2 {
return;
}
let fu_indicator = payload[0];
let fu_header = payload[1];
let start_bit = (fu_header & 0x80) != 0;
let end_bit = (fu_header & 0x40) != 0;
let orig_nal_hdr = (fu_indicator & 0xE0) | (fu_header & 0x1F);
if start_bit {
self.fu_buf.clear();
self.fu_buf.extend_from_slice(&ANNEX_B_START_CODE);
self.fu_buf.push(orig_nal_hdr);
self.fu_buf.extend_from_slice(&payload[2..]);
let (is_key, is_cfg) = classify_nal(VideoCodec::H264, orig_nal_hdr);
self.fu_keyframe = is_key;
self.fu_config = is_cfg;
self.fu_active = true;
} else if self.fu_active {
self.fu_buf.extend_from_slice(&payload[2..]);
}
if end_bit && self.fu_active {
self.fu_active = false;
let data = std::mem::take(&mut self.fu_buf);
emit(VideoNalUnit {
data,
pts_us,
is_keyframe: self.fu_keyframe,
is_codec_config: self.fu_config,
});
}
}
_ => {}
}
}
fn handle_h265_payload<F>(&mut self, payload: &[u8], pts_us: u64, emit: &mut F)
where
F: FnMut(VideoNalUnit),
{
if payload.len() < 2 {
return;
}
let nal_type = (payload[0] >> 1) & 0x3F;
match nal_type {
0..=47 => {
self.fu_active = false;
self.fu_buf.clear();
let (is_keyframe, is_codec_config) = classify_nal(VideoCodec::H265, payload[0]);
let mut data = Vec::with_capacity(4 + payload.len());
data.extend_from_slice(&ANNEX_B_START_CODE);
data.extend_from_slice(payload);
emit(VideoNalUnit {
data,
pts_us,
is_keyframe,
is_codec_config,
});
}
48 => {
// AP (Aggregation Packet)
self.fu_active = false;
self.fu_buf.clear();
let mut idx = 2usize;
while idx + 2 <= payload.len() {
let nalu_len = u16::from_be_bytes([payload[idx], payload[idx + 1]]) as usize;
idx += 2;
if nalu_len == 0 || idx + nalu_len > payload.len() {
break;
}
let nalu = &payload[idx..idx + nalu_len];
let (is_keyframe, is_codec_config) = classify_nal(VideoCodec::H265, nalu[0]);
let mut data = Vec::with_capacity(4 + nalu.len());
data.extend_from_slice(&ANNEX_B_START_CODE);
data.extend_from_slice(nalu);
emit(VideoNalUnit {
data,
pts_us,
is_keyframe,
is_codec_config,
});
idx += nalu_len;
}
}
49 => {
// FU (Fragmentation Unit)
if payload.len() < 3 {
return;
}
let fu_header = payload[2];
let start_bit = (fu_header & 0x80) != 0;
let end_bit = (fu_header & 0x40) != 0;
let orig_type = fu_header & 0x3F;
let orig_hdr0 = (payload[0] & 0x81) | (orig_type << 1);
let orig_hdr1 = payload[1];
if start_bit {
self.fu_buf.clear();
self.fu_buf.extend_from_slice(&ANNEX_B_START_CODE);
self.fu_buf.push(orig_hdr0);
self.fu_buf.push(orig_hdr1);
self.fu_buf.extend_from_slice(&payload[3..]);
let (is_key, is_cfg) = classify_nal(VideoCodec::H265, orig_hdr0);
self.fu_keyframe = is_key;
self.fu_config = is_cfg;
self.fu_active = true;
} else if self.fu_active {
self.fu_buf.extend_from_slice(&payload[3..]);
}
if end_bit && self.fu_active {
self.fu_active = false;
let data = std::mem::take(&mut self.fu_buf);
emit(VideoNalUnit {
data,
pts_us,
is_keyframe: self.fu_keyframe,
is_codec_config: self.fu_config,
});
}
}
_ => {}
}
}
}
/// Récepteur vidéo UDP pur Rust (port `5600` par défaut) destiné au décodeur matériel Android (`MediaCodec`).
pub struct UdpVideoReceiver {
metrics: Arc<Mutex<UdpVideoMetrics>>,
stop_flag: Arc<AtomicBool>,
worker: Option<thread::JoinHandle<()>>,
}
impl UdpVideoReceiver {
pub fn start<F>(
bind_ip: &str,
port: u16,
codec: VideoCodec,
transport: StreamTransport,
mut on_nal: F,
) -> Result<Self>
where
F: FnMut(VideoNalUnit) + Send + 'static,
{
let addr = format!("{}:{}", bind_ip, port);
let socket = UdpSocket::bind(&addr)?;
socket.set_read_timeout(Some(Duration::from_millis(100)))?;
log::info!(
"[UDP Video] En écoute sur {} ({:?}, {:?})",
addr,
codec,
transport
);
let metrics = Arc::new(Mutex::new(UdpVideoMetrics::default()));
let metrics_clone = Arc::clone(&metrics);
let stop_flag = Arc::new(AtomicBool::new(false));
let stop_clone = Arc::clone(&stop_flag);
let worker = thread::Builder::new()
.name("fpv-udp-video".into())
.spawn(move || {
let mut buf = [0u8; 65536];
let mut depacketizer = RtpDepacketizer::new(codec);
let start_time = Instant::now();
let mut last_packet_at: Option<Instant> = None;
let mut last_frame_at: Option<Instant> = None;
let mut fps_window_start = Instant::now();
let mut fps_frames: u32 = 0;
let mut bytes_in_window: u64 = 0;
let mut jitter_ms_ewma: f32 = 0.0;
let mut expected_interval_ms: f32 = 16.67;
while !stop_clone.load(Ordering::Acquire) {
match socket.recv(&mut buf) {
Ok(len) if len > 0 => {
let now = Instant::now();
last_packet_at = Some(now);
bytes_in_window = bytes_in_window.saturating_add(len as u64);
let pts_us = start_time.elapsed().as_micros() as u64;
let mut emit_and_track = |nal: VideoNalUnit| {
if !nal.is_codec_config {
fps_frames = fps_frames.saturating_add(1);
if let Some(prev_f) = last_frame_at {
let dt_ms = now.duration_since(prev_f).as_secs_f32() * 1000.0;
if dt_ms > 1.0 && dt_ms < 250.0 {
expected_interval_ms =
expected_interval_ms * 0.9 + dt_ms * 0.1;
let diff = (dt_ms - expected_interval_ms).abs();
jitter_ms_ewma = jitter_ms_ewma * 0.85 + diff * 0.15;
}
}
last_frame_at = Some(now);
}
on_nal(nal);
};
match transport {
StreamTransport::Rtp => {
depacketizer.push_rtp_packet(
&buf[..len],
pts_us,
&mut emit_and_track,
);
}
StreamTransport::Raw => {
let is_key = has_keyframe_annex_b(codec, &buf[..len]);
emit_and_track(VideoNalUnit {
data: buf[..len].to_vec(),
pts_us,
is_keyframe: is_key,
is_codec_config: false,
});
}
}
let mut m = metrics_clone.lock();
m.received_packets = m.received_packets.saturating_add(1);
m.dropped_packets = depacketizer.dropped_packets;
m.signal_live = true;
}
_ => {}
}
let win_elapsed = fps_window_start.elapsed();
if win_elapsed >= Duration::from_millis(500) {
let secs = win_elapsed.as_secs_f32().max(0.001);
let live = last_packet_at
.map(|t| t.elapsed() < SIGNAL_LOST_AFTER)
.unwrap_or(false);
let mut m = metrics_clone.lock();
m.fps = if live { fps_frames as f32 / secs } else { 0.0 };
m.bitrate_kbps = if live {
(bytes_in_window as f32 * 8.0) / (secs * 1000.0)
} else {
0.0
};
m.jitter_ms = if live { jitter_ms_ewma } else { 0.0 };
m.signal_live = live;
fps_frames = 0;
bytes_in_window = 0;
fps_window_start = Instant::now();
}
}
})?;
Ok(Self {
metrics,
stop_flag,
worker: Some(worker),
})
}
pub fn metrics(&self) -> Arc<Mutex<UdpVideoMetrics>> {
Arc::clone(&self.metrics)
}
}
impl Drop for UdpVideoReceiver {
fn drop(&mut self) {
self.stop_flag.store(true, Ordering::Release);
if let Some(handle) = self.worker.take() {
let _ = handle.join();
}
}
}
fn has_keyframe_annex_b(codec: VideoCodec, bytes: &[u8]) -> bool {
let mut i = 0usize;
while i + 4 < bytes.len() {
let sc = if bytes[i] == 0 && bytes[i + 1] == 0 && bytes[i + 2] == 1 {
3
} else if bytes[i] == 0 && bytes[i + 1] == 0 && bytes[i + 2] == 0 && bytes[i + 3] == 1 {
4
} else {
i += 1;
continue;
};
let nal_idx = i + sc;
if nal_idx < bytes.len() {
let (is_key, _) = classify_nal(codec, bytes[nal_idx]);
if is_key {
return true;
}
}
i = nal_idx + 1;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
fn make_rtp(seq: u16, payload: &[u8]) -> Vec<u8> {
let mut pkt = vec![
0x80, 0x60, // V=2, PT=96
(seq >> 8) as u8,
(seq & 0xFF) as u8,
0, 0, 0, 1, // Timestamp
0x12, 0x34, 0x56, 0x78, // SSRC
];
pkt.extend_from_slice(payload);
pkt
}
#[test]
fn test_h264_single_nal_and_sps() {
let mut dep = RtpDepacketizer::new(VideoCodec::H264);
let mut out = Vec::new();
// SPS (NAL type 7)
let pkt = make_rtp(1, &[0x67, 0x42, 0x00, 0x1E]);
dep.push_rtp_packet(&pkt, 1000, |n| out.push(n));
assert_eq!(out.len(), 1);
assert!(out[0].is_codec_config);
assert!(!out[0].is_keyframe);
assert_eq!(&out[0].data[..4], &ANNEX_B_START_CODE);
assert_eq!(&out[0].data[4..], &[0x67, 0x42, 0x00, 0x1E]);
}
#[test]
fn test_h264_fua_reassembly_idr() {
let mut dep = RtpDepacketizer::new(VideoCodec::H264);
let mut out = Vec::new();
// FU-A start (IDR type 5, NRI=3 -> orig_hdr = 0x65)
let p1 = make_rtp(10, &[0x7C, 0x85, 0xAA, 0xBB]);
let p2 = make_rtp(11, &[0x7C, 0x45, 0xCC, 0xDD]);
dep.push_rtp_packet(&p1, 2000, |n| out.push(n));
assert!(out.is_empty());
dep.push_rtp_packet(&p2, 2000, |n| out.push(n));
assert_eq!(out.len(), 1);
assert!(out[0].is_keyframe);
assert_eq!(out[0].data, vec![0, 0, 0, 1, 0x65, 0xAA, 0xBB, 0xCC, 0xDD]);
}
#[test]
fn test_h264_fua_drop_on_seq_gap() {
let mut dep = RtpDepacketizer::new(VideoCodec::H264);
let mut out = Vec::new();
let p1 = make_rtp(10, &[0x7C, 0x85, 0xAA]);
// Seq 11 manquant -> Seq 12 ne doit pas émettre un NAL corrompu
let p3 = make_rtp(12, &[0x7C, 0x45, 0xCC]);
dep.push_rtp_packet(&p1, 2000, |n| out.push(n));
dep.push_rtp_packet(&p3, 2000, |n| out.push(n));
assert!(out.is_empty());
assert_eq!(dep.dropped_packets, 1);
}
#[test]
fn test_h265_fu_reassembly_idr() {
let mut dep = RtpDepacketizer::new(VideoCodec::H265);
let mut out = Vec::new();
// FU header (type 49 -> 49<<1 = 0x62), orig_type = 19 (IDR_W_RADL -> 19<<1 = 0x26)
let p1 = make_rtp(1, &[0x62, 0x01, 0x80 | 19, 0x11, 0x22]);
let p2 = make_rtp(2, &[0x62, 0x01, 0x40 | 19, 0x33, 0x44]);
dep.push_rtp_packet(&p1, 3000, |n| out.push(n));
dep.push_rtp_packet(&p2, 3000, |n| out.push(n));
assert_eq!(out.len(), 1);
assert!(out[0].is_keyframe);
assert_eq!(out[0].data, vec![0, 0, 0, 1, 0x26, 0x01, 0x11, 0x22, 0x33, 0x44]);
}
}
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# Compile le cœur Rust (fpv-android-ffi -> arm64-v8a) et l'APK Android pour Galaxy Tab S8 Ultra.
# Usage :
# ./scripts/build_android.sh # Build debug APK
# ./scripts/build_android.sh --release # Build release APK
# ./scripts/build_android.sh --install # Build debug + adb install -r sur la tablette
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
BUILD_TYPE="debug"
DO_INSTALL=0
for arg in "$@"; do
case "$arg" in
--release) BUILD_TYPE="release" ;;
--install) DO_INSTALL=1 ;;
*) echo "Option inconnue : $arg"; exit 1 ;;
esac
done
export ANDROID_HOME="${ANDROID_HOME:-$HOME/Android/Sdk}"
if [ -z "${ANDROID_NDK_HOME:-}" ]; then
ANDROID_NDK_HOME="$(ls -d "${ANDROID_HOME}/ndk/"* 2>/dev/null | sort -V | tail -n 1 || true)"
export ANDROID_NDK_HOME
fi
if [ ! -d "${ANDROID_NDK_HOME:-}" ]; then
echo "ERREUR : Android NDK introuvable dans ${ANDROID_HOME}/ndk/"
echo "Installez-le avec : android sdk install ndk/29.0.14206865"
exit 1
fi
echo "=== [1/3] Compilation Rust ARM64 (fpv-android-ffi) avec cargo-ndk ==="
echo " ANDROID_HOME = ${ANDROID_HOME}"
echo " ANDROID_NDK_HOME = ${ANDROID_NDK_HOME}"
JNI_OUT="${REPO_ROOT}/android/app/src/main/jniLibs"
mkdir -p "${JNI_OUT}"
(
cd "${REPO_ROOT}"
cargo ndk -t arm64-v8a --platform 31 -o "${JNI_OUT}" build -p fpv-android-ffi --release
)
echo "=== [2/3] Compilation APK Android (${BUILD_TYPE}) ==="
GRADLE_TASK="assembleDebug"
APK_PATH="${REPO_ROOT}/android/app/build/outputs/apk/debug/app-debug.apk"
if [ "${BUILD_TYPE}" = "release" ]; then
GRADLE_TASK="assembleRelease"
APK_PATH="${REPO_ROOT}/android/app/build/outputs/apk/release/app-release-unsigned.apk"
fi
(
cd "${REPO_ROOT}/android"
./gradlew "${GRADLE_TASK}"
)
echo "[+] APK généré : ${APK_PATH}"
if [ "${DO_INSTALL}" -eq 1 ]; then
echo "=== [3/3] Installation sur la Galaxy Tab S8 Ultra via ADB ==="
ADB="${ANDROID_HOME}/platform-tools/adb"
"${ADB}" install -r "${APK_PATH}"
"${ADB}" shell am start -n com.steamframe.fpv/.MainActivity
echo "[+] Application installée et lancée sur la tablette !"
fi
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# Configure un serveur DHCP léger (dnsmasq) sur l'interface usb0 (192.168.1.1)
# de la Radxa Zero 3W pour le plug-and-play sur Android (Galaxy Tab S8 Ultra)
# et Linux/SteamOS sans conflit avec les profils IP statiques existants.
#
# Usage : ./scripts/setup_radxa_dhcp_usb0.sh [root@192.168.1.1]
set -euo pipefail
RADXA_HOST="${1:-root@192.168.1.1}"
echo "=== Configuration du serveur DHCP usb0 sur ${RADXA_HOST} ==="
ssh "${RADXA_HOST}" bash -s << 'EOF'
set -euo pipefail
if ! command -v dnsmasq >/dev/null 2>&1; then
echo "[*] dnsmasq absent — tentative d'installation via apt-get..."
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq && apt-get install -y -qq dnsmasq-base || apt-get install -y -qq dnsmasq
fi
mkdir -p /etc/dnsmasq.d
# Configuration dédiée usb0 :
# - port=0 : désactive le serveur DNS (évite tout conflit avec systemd-resolved)
# - dhcp-option=3 (vide) : n'annonce AUCUNE passerelle par défaut (préserve le Wi-Fi/5G sur Android et Steam Frame)
# - dhcp-option=6 (vide) : n'annonce AUCUN DNS
# - plage 192.168.1.10..192.168.1.20 (premier bail = 192.168.1.10, cohérent avec les scripts existants)
cat << 'CONF' > /etc/dnsmasq.d/steamframe-usb0.conf
port=0
interface=usb0
bind-dynamic
dhcp-range=192.168.1.10,192.168.1.20,255.255.255.0,12h
dhcp-option=3
dhcp-option=6
dhcp-authoritative
dhcp-leasefile=/tmp/dnsmasq-usb0.leases
CONF
cat << 'UNIT' > /etc/systemd/system/steamframe-usb0-dhcp.service
[Unit]
Description=SteamFrame FPV DHCP Server on usb0 (Android & SteamOS Plug-and-Play)
After=usb0-setup.service network.target
Wants=usb0-setup.service
[Service]
Type=simple
ExecStart=/usr/sbin/dnsmasq --keep-in-foreground --no-daemon --conf-file=/etc/dnsmasq.d/steamframe-usb0.conf
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
UNIT
# Si le service dnsmasq global existe et risque d'occuper le port 67, on évite les conflits
if systemctl is-enabled dnsmasq.service >/dev/null 2>&1; then
systemctl disable --now dnsmasq.service || true
fi
systemctl daemon-reload
systemctl enable steamframe-usb0-dhcp.service
systemctl restart steamframe-usb0-dhcp.service
systemctl status --no-pager steamframe-usb0-dhcp.service || true
EOF
echo "[+] DHCP usb0 actif sur ${RADXA_HOST} (plage 192.168.1.10-20, sans passerelle ni DNS) !"
+36
View File
@@ -76,6 +76,42 @@ EOF
mkdir -p "${ROOTFS}/etc/systemd/system/multi-user.target.wants" mkdir -p "${ROOTFS}/etc/systemd/system/multi-user.target.wants"
ln -sf /etc/systemd/system/usb0-setup.service "${ROOTFS}/etc/systemd/system/multi-user.target.wants/usb0-setup.service" ln -sf /etc/systemd/system/usb0-setup.service "${ROOTFS}/etc/systemd/system/multi-user.target.wants/usb0-setup.service"
# 3b. Préparer la configuration DHCP légère sur usb0 (plug-and-play Android Tab S8 Ultra & SteamOS)
echo "[3b/5] Préparation de la config DHCP usb0 (sans passerelle ni DNS)..."
mkdir -p "${ROOTFS}/etc/dnsmasq.d"
cat << 'EOF' > "${ROOTFS}/etc/dnsmasq.d/steamframe-usb0.conf"
port=0
interface=usb0
bind-dynamic
dhcp-range=192.168.1.10,192.168.1.20,255.255.255.0,12h
dhcp-option=3
dhcp-option=6
dhcp-authoritative
dhcp-leasefile=/tmp/dnsmasq-usb0.leases
EOF
cat << 'EOF' > "${ROOTFS}/etc/systemd/system/steamframe-usb0-dhcp.service"
[Unit]
Description=SteamFrame FPV DHCP Server on usb0 (Android & SteamOS Plug-and-Play)
After=usb0-setup.service network.target
Wants=usb0-setup.service
[Service]
Type=simple
ExecStart=/usr/sbin/dnsmasq --keep-in-foreground --no-daemon --conf-file=/etc/dnsmasq.d/steamframe-usb0.conf
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
if [ -x "${ROOTFS}/usr/sbin/dnsmasq" ]; then
ln -sf /etc/systemd/system/steamframe-usb0-dhcp.service "${ROOTFS}/etc/systemd/system/multi-user.target.wants/steamframe-usb0-dhcp.service"
else
echo " -> Info : dnsmasq non présent sur l'image SD, lancez ./scripts/setup_radxa_dhcp_usb0.sh après le premier boot."
fi
# 4. Ajuster le port vidéo dans controller_settings.cfg vers 5600 # 4. Ajuster le port vidéo dans controller_settings.cfg vers 5600
echo "[4/5] Configuration du port vidéo Ruby vers 5600..." echo "[4/5] Configuration du port vidéo Ruby vers 5600..."
if [ -f "${ROOTFS}/home/radxa/ruby/config/controller_settings.cfg" ]; then if [ -f "${ROOTFS}/home/radxa/ruby/config/controller_settings.cfg" ]; then
+1 -56
View File
@@ -133,62 +133,7 @@ pub(super) fn eviocgabs(abs_code: u16) -> std::ffi::c_ulong {
// TYPES PUBLICS : SOURCE DE CONTRÔLE & ÉTAT STEAM CONTROLLER // TYPES PUBLICS : SOURCE DE CONTRÔLE & ÉTAT STEAM CONTROLLER
// ========================================================================= // =========================================================================
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub use fpv_core::ControlSource;
#[repr(u8)]
pub enum ControlSource {
#[default]
G29 = 0,
SteamController = 1,
}
impl ControlSource {
pub fn from_str(s: &str) -> Self {
let lower = s.trim().to_ascii_lowercase();
if lower == "steam"
|| lower == "steam_controller"
|| lower == "steam-controller"
|| lower == "controller"
|| lower == "gamepad"
|| lower == "ext"
{
Self::SteamController
} else {
Self::G29
}
}
pub fn from_u8(v: u8) -> Self {
match v {
1 => Self::SteamController,
_ => Self::G29,
}
}
pub fn as_u8(self) -> u8 {
self as u8
}
pub fn as_str(self) -> &'static str {
match self {
Self::G29 => "g29",
Self::SteamController => "steam",
}
}
pub fn wire_tag(self) -> &'static str {
match self {
Self::G29 => "G29",
Self::SteamController => "EXT",
}
}
pub fn label(self) -> &'static str {
match self {
Self::G29 => "Volant G29",
Self::SteamController => "Steam Controller",
}
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct SteamControllerConfig { pub struct SteamControllerConfig {
+26 -715
View File
@@ -1,716 +1,46 @@
use crate::controller::ControlSource; pub use fpv_core::g29_bridge::*;
use crate::engine::EngineControlHandle;
use crate::nomad_elrs::{CRSF_CHANNEL_MAX, CRSF_CHANNEL_MID, CRSF_CHANNEL_MIN};
use crate::telemetry_osd::{TelemetryReceiver, TelemetryState};
use anyhow::Result;
use parking_lot::Mutex;
use std::net::UdpSocket;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
const G29_TIMEOUT_MS: u64 = 1500; impl FpvControlTarget for crate::engine::EngineControlHandle {
const TOAST_DURATION_MS: u64 = 1500; fn is_vr_menu_open(&self) -> bool {
self.is_vr_menu_open()
/// État temps réel reçu depuis le volant G29 (RP2350 -> ESP32-C3 -> UDP)
#[derive(Debug, Clone)]
pub struct G29State {
pub connected: bool,
pub failsafe: bool,
pub armed: bool,
pub gear: i8,
pub steering_pct: i8,
pub throttle_pct: u8,
pub brake_pct: u8,
pub clutch_pct: u8,
pub steer_crsf: u16,
pub throttle_crsf: u16,
pub brake_crsf: u16,
pub clutch_crsf: u16,
pub ffb_raw: u8,
pub ffb_pct: u8,
pub vib_pct: u8,
pub remote_source: ControlSource,
pub packets_received: u64,
pub last_packet: Option<Instant>,
pub last_button: String,
pub last_button_at: Option<Instant>,
pub toast_text: String,
pub toast_until: Option<Instant>,
}
impl Default for G29State {
fn default() -> Self {
Self {
connected: false,
failsafe: false,
armed: false,
gear: 0,
steering_pct: 0,
throttle_pct: 0,
brake_pct: 0,
clutch_pct: 0,
steer_crsf: CRSF_CHANNEL_MID,
throttle_crsf: CRSF_CHANNEL_MID,
brake_crsf: CRSF_CHANNEL_MID,
clutch_crsf: CRSF_CHANNEL_MID,
ffb_raw: 140,
ffb_pct: 55,
vib_pct: 50,
remote_source: ControlSource::G29,
packets_received: 0,
last_packet: None,
last_button: String::new(),
last_button_at: None,
toast_text: String::new(),
toast_until: None,
} }
fn toggle_vr_menu(&self) -> bool {
self.toggle_vr_menu()
} }
} fn close_vr_menu(&self) -> bool {
self.close_vr_menu()
impl G29State {
pub fn is_live(&self) -> bool {
self.connected
&& self
.last_packet
.map(|t| t.elapsed() <= Duration::from_millis(G29_TIMEOUT_MS))
.unwrap_or(false)
} }
fn vr_menu_move(&self, delta: i32) {
pub fn set_toast(&mut self, msg: impl Into<String>) { self.vr_menu_move(delta as isize);
self.toast_text = msg.into();
self.toast_until = Some(Instant::now() + Duration::from_millis(TOAST_DURATION_MS));
} }
fn vr_menu_adjust(&self, delta: i32) {
pub fn active_toast(&self) -> Option<&str> { self.vr_menu_adjust(delta);
match self.toast_until {
Some(until) if Instant::now() < until && !self.toast_text.is_empty() => {
Some(&self.toast_text)
} }
_ => None, fn vr_menu_activate(&self) {
self.vr_menu_activate();
} }
fn request_recenter(&self) {
self.request_recenter();
} }
fn toggle_dvr(&self) -> bool {
pub fn gear_label(&self) -> &'static str { self.toggle_dvr()
match self.gear {
-1 => "R",
0 => "N",
1 => "1",
2 => "2",
3 => "3",
_ => "?",
} }
fn toggle_telemetry(&self) -> bool {
self.toggle_telemetry()
} }
} fn cycle_projection_mode(&self) -> &'static str {
self.cycle_projection_mode()
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum G29ButtonEvent {
Cross,
Circle,
Square,
Triangle,
Share,
Options,
Ps,
L3,
R3,
DpadUp,
DpadDown,
DpadLeft,
DpadRight,
}
impl G29ButtonEvent {
pub fn from_name(name: &str) -> Option<Self> {
match name.trim() {
"CROSS" => Some(Self::Cross),
"CIRCLE" => Some(Self::Circle),
"SQUARE" => Some(Self::Square),
"TRIANGLE" => Some(Self::Triangle),
"SHARE" => Some(Self::Share),
"OPTIONS" => Some(Self::Options),
"PS" => Some(Self::Ps),
"L3" => Some(Self::L3),
"R3" => Some(Self::R3),
"DPAD_UP" => Some(Self::DpadUp),
"DPAD_DOWN" => Some(Self::DpadDown),
"DPAD_LEFT" => Some(Self::DpadLeft),
"DPAD_RIGHT" => Some(Self::DpadRight),
_ => None,
}
}
}
/// Récepteur UDP non-bloquant pour la passerelle Wi-Fi G29
pub struct G29BridgeReceiver {
state: Arc<Mutex<G29State>>,
stop_flag: Arc<AtomicBool>,
worker: Option<thread::JoinHandle<()>>,
}
impl G29BridgeReceiver {
pub fn start(
bind_ip: &str,
port: u16,
control: EngineControlHandle,
telemetry: Option<Arc<Mutex<TelemetryState>>>,
allowed_peers: Vec<std::net::IpAddr>,
) -> Result<Self> {
let addr = format!("{}:{}", bind_ip, port);
let socket = UdpSocket::bind(&addr)?;
socket.set_read_timeout(Some(Duration::from_millis(100)))?;
log::info!(
"[G29 Bridge] En écoute UDP unifiée sur {} (pairs autorisés: {:?})",
addr,
allowed_peers
);
let state = Arc::new(Mutex::new(G29State::default()));
let state_clone = Arc::clone(&state);
let stop_flag = Arc::new(AtomicBool::new(false));
let stop_clone = Arc::clone(&stop_flag);
let worker = thread::Builder::new()
.name("g29-udp-rx".into())
.spawn(move || {
let mut buf = [0u8; 2048];
let mut last_reject_log: Option<Instant> = None;
while !stop_clone.load(Ordering::Acquire) {
if let Ok((len, src)) = socket.recv_from(&mut buf) {
if !Self::is_peer_allowed(src.ip(), &allowed_peers) {
if last_reject_log
.is_none_or(|t| t.elapsed() >= Duration::from_secs(5))
{
log::warn!(
"[G29 Bridge] Paquet UDP rejeté depuis IP non autorisée : {}",
src
);
last_reject_log = Some(Instant::now());
}
continue;
}
if let Ok(text) = std::str::from_utf8(&buf[..len]) {
for line in text.lines() {
Self::process_line(
line,
&state_clone,
Some(&control),
telemetry.as_ref(),
);
}
}
}
// Vérifier le timeout G29 à chaque itération (même si des trames $CRSF continuent d'arriver)
{
let mut st = state_clone.lock();
if st.connected && !st.is_live() {
st.connected = false;
st.armed = false;
st.failsafe = true;
st.gear = 0;
st.throttle_pct = 0;
st.brake_pct = 0;
st.clutch_pct = 0;
log::warn!("[G29 Bridge] Perte de liaison avec le volant G29.");
}
}
}
log::info!("[G29 Bridge] Thread d'écoute UDP arrêté.");
})?;
Ok(Self {
state,
stop_flag,
worker: Some(worker),
})
}
#[allow(dead_code)]
pub fn send_command(target_ip: &str, target_port: u16, cmd: &str) -> Result<()> {
let socket = UdpSocket::bind("0.0.0.0:0")?;
let target = format!("{}:{}", target_ip.trim(), target_port);
let trimmed = cmd.trim();
let payload = if trimmed.starts_with('$') && !trimmed.contains('*') {
crate::nomad_elrs::NomadHeadTracker::append_nmea_crc8(trimmed)
} else {
format!("{}\n", trimmed)
};
socket.send_to(payload.as_bytes(), target)?;
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 {
src_ip.is_loopback() || allowed_peers.is_empty() || allowed_peers.contains(&src_ip)
}
pub fn state(&self) -> Arc<Mutex<G29State>> {
Arc::clone(&self.state)
}
/// Vérifie et retire le suffixe CRC-8 `*XX` optionnel sur les trames `$G29` / `$G29_EVT`.
/// Si `*` est présent, le CRC-8 DVB-S2 doit être valide (sinon la trame est rejetée).
fn verify_optional_crc8(line: &str) -> Option<&str> {
if let Some((body, crc_hex)) = line.rsplit_once('*') {
if crc_hex.len() != 2 {
return None;
}
let expected = u8::from_str_radix(crc_hex, 16).ok()?;
let calc = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(body.as_bytes());
if calc == expected {
Some(body)
} else {
None
}
} else {
Some(line)
}
}
pub fn process_line(
raw_line: &str,
state: &Arc<Mutex<G29State>>,
control: Option<&EngineControlHandle>,
telemetry: Option<&Arc<Mutex<TelemetryState>>>,
) {
let line = raw_line.trim();
if line.starts_with("$G29,") {
if let Some(verified) = Self::verify_optional_crc8(line) {
if let Some(rest) = verified.strip_prefix("$G29,") {
Self::parse_status_fields(rest, state);
}
}
} else if line.starts_with("$G29_EVT,") {
if let Some(verified) = Self::verify_optional_crc8(line) {
if let Some(rest) = verified.strip_prefix("$G29_EVT,") {
Self::parse_button_event(rest, state, control);
}
}
} else if let Some(hex) = line.strip_prefix("$CRSF,") {
if let Some(telem) = telemetry {
Self::parse_crsf_hex(hex, telem);
}
}
}
fn parse_crsf_hex(hex: &str, telemetry: &Arc<Mutex<TelemetryState>>) {
let bytes = hex.trim().as_bytes();
if bytes.len() < 8 || !bytes.len().is_multiple_of(2) || bytes.len() > 128 {
return;
}
let mut raw = [0u8; 64];
let mut out_len = 0;
for chunk in bytes.as_chunks::<2>().0 {
let Some(hi) = Self::hex_nibble(chunk[0]) else {
return;
};
let Some(lo) = Self::hex_nibble(chunk[1]) else {
return;
};
raw[out_len] = (hi << 4) | lo;
out_len += 1;
}
TelemetryReceiver::parse_datagram(&raw[..out_len], telemetry);
}
#[inline]
fn hex_nibble(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
fn parse_status_fields(fields: &str, state: &Arc<Mutex<G29State>>) {
let mut st = state.lock();
let had_packets = st.packets_received > 0;
let prev_ffb_pct = st.ffb_pct;
let prev_vib_pct = st.vib_pct;
for pair in fields.split(',') {
let Some((k, v)) = pair.split_once('=') else {
continue;
};
match k.trim() {
"ARM" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.armed = val != 0;
}
}
"GEAR" => {
if let Ok(val) = v.trim().parse::<i8>() {
st.gear = val.clamp(-1, 3);
}
}
"THROT" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.throttle_pct = val.min(100);
}
}
"BRAKE" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.brake_pct = val.min(100);
}
}
"CLUTCH" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.clutch_pct = val.min(100);
}
}
"STEER" => {
if let Ok(val) = v.trim().parse::<i8>() {
st.steering_pct = val.clamp(-100, 100);
}
}
"CH1" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.steer_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"CH2" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.throttle_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"CH3" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.brake_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"CH4" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.clutch_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"FFB" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.ffb_raw = val;
st.ffb_pct = ((val as u16 * 100) / 255) as u8;
}
}
"VIB" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.vib_pct = val.min(100);
}
}
"FAIL" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.failsafe = val != 0;
}
}
"SRC" => {
st.remote_source = ControlSource::from_str(v);
}
_ => {}
}
}
if !st.connected {
log::info!("[G29 Bridge] Volant G29 connecté en Wi-Fi UDP.");
}
st.connected = true;
st.packets_received = st.packets_received.wrapping_add(1);
st.last_packet = Some(Instant::now());
if had_packets && st.ffb_pct != prev_ffb_pct {
let pct = st.ffb_pct;
st.set_toast(format!("FFB {}%", pct));
} else if had_packets && st.vib_pct != prev_vib_pct {
let pct = st.vib_pct;
st.set_toast(format!("VIB {}%", pct));
}
}
fn parse_button_event(
fields: &str,
state: &Arc<Mutex<G29State>>,
control: Option<&EngineControlHandle>,
) {
let Some((_, btn_name)) = fields.split_once("BTN=") else {
return;
};
let Some(btn) = G29ButtonEvent::from_name(btn_name) else {
return;
};
log::info!("[G29 Bridge] Bouton volant reçu : {:?}", btn);
let menu_open = control.map(|c| c.is_vr_menu_open()).unwrap_or(false);
let toast = match btn {
G29ButtonEvent::Options | G29ButtonEvent::L3 => {
if let Some(ctrl) = control {
let open = ctrl.toggle_vr_menu();
Some(if open {
"MENU VR ON".to_string()
} else {
"MENU VR OFF".to_string()
})
} else {
Some("MENU VR".to_string())
}
}
G29ButtonEvent::Cross if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_activate();
}
None
}
G29ButtonEvent::Circle if menu_open => {
let closed = control.map(|ctrl| ctrl.close_vr_menu()).unwrap_or(true);
Some(if closed { "MENU VR OFF" } else { "RETOUR MENU" }.to_string())
}
G29ButtonEvent::DpadUp if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_move(-1);
}
None
}
G29ButtonEvent::DpadDown if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_move(1);
}
None
}
G29ButtonEvent::DpadLeft if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_adjust(-1);
}
None
}
G29ButtonEvent::DpadRight if menu_open => {
if let Some(ctrl) = control {
ctrl.vr_menu_adjust(1);
}
None
}
G29ButtonEvent::Cross | G29ButtonEvent::Ps | G29ButtonEvent::R3 => {
if let Some(ctrl) = control {
ctrl.request_recenter();
}
Some("TARE HT OK".to_string())
}
G29ButtonEvent::Share | G29ButtonEvent::Circle => {
if let Some(ctrl) = control {
let now_rec = ctrl.toggle_dvr();
Some(if now_rec {
"DVR REC".to_string()
} else {
"DVR STOP".to_string()
})
} else {
Some("DVR TOGGLE".to_string())
}
}
G29ButtonEvent::Triangle => {
if let Some(ctrl) = control {
let now_on = ctrl.toggle_telemetry();
Some(if now_on {
"OSD ON".to_string()
} else {
"OSD OFF".to_string()
})
} else {
Some("OSD TOGGLE".to_string())
}
}
G29ButtonEvent::Square => {
if let Some(ctrl) = control {
let mode_lbl = ctrl.cycle_projection_mode();
Some(format!("PROJ: {}", mode_lbl))
} else {
Some("PROJ CYCLE".to_string())
}
}
G29ButtonEvent::DpadUp => {
if let Some(ctrl) = control {
ctrl.adjust_head_trim(0.0, 1.0);
}
Some("TILT +1".to_string())
}
G29ButtonEvent::DpadDown => {
if let Some(ctrl) = control {
ctrl.adjust_head_trim(0.0, -1.0);
}
Some("TILT -1".to_string())
}
G29ButtonEvent::DpadLeft => {
if let Some(ctrl) = control {
ctrl.adjust_head_trim(-1.0, 0.0);
}
Some("PAN -1".to_string())
}
G29ButtonEvent::DpadRight => {
if let Some(ctrl) = control {
ctrl.adjust_head_trim(1.0, 0.0);
}
Some("PAN +1".to_string())
}
};
{
let mut st = state.lock();
st.connected = true;
st.last_packet = Some(Instant::now());
st.last_button = btn_name.trim().to_string();
st.last_button_at = Some(Instant::now());
if let Some(msg) = toast {
st.set_toast(msg);
}
}
}
}
impl Drop for G29BridgeReceiver {
fn drop(&mut self) {
self.stop_flag.store(true, Ordering::Release);
if let Some(handle) = self.worker.take() {
let _ = handle.join();
} }
fn adjust_head_trim(&self, pan_delta_deg: f32, tilt_delta_deg: f32) {
self.adjust_head_trim(pan_delta_deg, tilt_delta_deg);
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use parking_lot::Mutex;
#[test] use std::sync::Arc;
fn test_parse_g29_status_and_toast() {
let state = Arc::new(Mutex::new(G29State::default()));
G29BridgeReceiver::process_line(
"$G29,ARM=1,GEAR=2,THROT=64,BRAKE=12,FFB=140,VIB=50,FAIL=0",
&state,
None,
None,
);
{
let st = state.lock();
assert!(st.connected);
assert!(st.armed);
assert_eq!(st.gear, 2);
assert_eq!(st.gear_label(), "2");
assert_eq!(st.throttle_pct, 64);
assert_eq!(st.brake_pct, 12);
assert_eq!(st.ffb_raw, 140);
assert_eq!(st.vib_pct, 50);
assert!(!st.failsafe);
}
G29BridgeReceiver::process_line(
"$G29,ARM=1,GEAR=-1,THROT=0,BRAKE=80,CLUTCH=45,STEER=-35,CH1=1280,CH2=890,CH3=1640,CH4=1360,FFB=200,VIB=50,FAIL=0,SRC=EXT",
&state,
None,
None,
);
{
let st = state.lock();
assert_eq!(st.gear_label(), "R");
assert_eq!(st.brake_pct, 80);
assert_eq!(st.clutch_pct, 45);
assert_eq!(st.steering_pct, -35);
assert_eq!(st.steer_crsf, 1280);
assert_eq!(st.throttle_crsf, 890);
assert_eq!(st.brake_crsf, 1640);
assert_eq!(st.clutch_crsf, 1360);
assert_eq!(st.remote_source, ControlSource::SteamController);
assert_eq!(st.active_toast(), Some("FFB 78%"));
}
}
#[test]
fn test_parse_g29_button_event() {
let state = Arc::new(Mutex::new(G29State::default()));
G29BridgeReceiver::process_line("$G29_EVT,BTN=CROSS", &state, None, None);
let st = state.lock();
assert_eq!(st.last_button, "CROSS");
assert_eq!(st.active_toast(), Some("TARE HT OK"));
}
#[test]
fn test_parse_crsf_telemetry_hex() {
// Trame CRSF Battery Sensor (0x08) : 16.8V (168 = 0x00A8), 12.5A (125 = 0x007D), 1200 mAh, 75%
let mut frame = [0u8; 12];
frame[0] = 0xEA;
frame[1] = 10;
frame[2] = 0x08;
frame[3] = 0x00;
frame[4] = 0xA8; // 16.8V
frame[5] = 0x00;
frame[6] = 0x7D; // 12.5A
frame[7] = 0x00;
frame[8] = 0x04;
frame[9] = 0xB0; // 1200 mAh
frame[10] = 75; // 75%
frame[11] = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(&frame[2..11]);
let hex: String = frame.iter().map(|b| format!("{:02X}", b)).collect();
let line = format!("$CRSF,{}", hex);
let g29_state = Arc::new(Mutex::new(G29State::default()));
let telem_state = Arc::new(Mutex::new(TelemetryState::default()));
G29BridgeReceiver::process_line(&line, &g29_state, None, Some(&telem_state));
let ts = telem_state.lock();
assert_eq!(ts.packets_received, 1);
assert!((ts.battery_voltage_v - 16.8).abs() < 0.01);
assert!((ts.battery_current_a - 12.5).abs() < 0.01);
assert_eq!(ts.battery_remaining_pct, 75);
}
#[test]
fn test_udp_peer_allowlist() {
use std::net::{IpAddr, Ipv4Addr};
let allowed = vec![IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))];
assert!(G29BridgeReceiver::is_peer_allowed(
IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)),
&allowed
));
assert!(G29BridgeReceiver::is_peer_allowed(
IpAddr::V4(Ipv4Addr::LOCALHOST),
&allowed
));
assert!(!G29BridgeReceiver::is_peer_allowed(
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 99)),
&allowed
));
assert!(G29BridgeReceiver::is_peer_allowed(
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 99)),
&[]
));
}
#[test] #[test]
fn test_vr_menu_g29_navigation() { fn test_vr_menu_g29_navigation() {
@@ -757,23 +87,4 @@ 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);
}
} }
+1 -522
View File
@@ -1,522 +1 @@
use anyhow::{anyhow, Result}; pub use fpv_core::nomad_elrs::*;
use glam::{EulerRot, Quat};
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
use std::time::{Duration, Instant};
/// Opcode MSPv2 officiel ExpressLRS Backpack pour le Head Tracking (Pan, Tilt, Roll)
pub const MSP_ELRS_BACKPACK_SET_PTR: u16 = 0x0383;
/// Bornes CRSF standard (11 bits : 172 = 988µs, 992 = 1500µs, 1811 = 2012µs)
pub const CRSF_CHANNEL_MIN: u16 = 172;
pub const CRSF_CHANNEL_MID: u16 = 992;
pub const CRSF_CHANNEL_MAX: u16 = 1811;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NomadProtocol {
/// MSPv2 ELRS_BACKPACK_SET_PTR (0x0383) — mode AP Head-Tracking classique
Msp,
/// CRSF RC_CHANNELS_PACKED (0x16)
Crsf,
/// MAVLink v1 RC_CHANNELS_OVERRIDE (msgid 70) — compatible UDP Backpack /mavlink (port 14555)
Mavlink,
/// Pont unifié G29 / Radxa Zero 3W ($HT,<pan>,<tilt>,<roll>) — 100% filaire via usb0:14552
G29Bridge,
}
impl NomadProtocol {
pub fn from_str(s: &str) -> Self {
if s.eq_ignore_ascii_case("g29")
|| s.eq_ignore_ascii_case("g29_bridge")
|| s.eq_ignore_ascii_case("radxa")
{
Self::G29Bridge
} else if s.eq_ignore_ascii_case("crsf") {
Self::Crsf
} else if s.eq_ignore_ascii_case("mavlink") || s.eq_ignore_ascii_case("mav") {
Self::Mavlink
} else {
Self::Msp
}
}
pub fn label(self) -> &'static str {
match self {
Self::Msp => "MSPv2 0x0383",
Self::Crsf => "CRSF 0x16",
Self::Mavlink => "MAVLink v1 (RC Override)",
Self::G29Bridge => "G29 Hub ($HT)",
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct HeadPoseSample {
pub pan_deg: f32,
pub tilt_deg: f32,
pub roll_deg: f32,
pub pan_crsf: u16,
pub tilt_crsf: u16,
pub roll_crsf: u16,
pub packets_sent: u64,
pub send_errors: u64,
pub last_send_ok: bool,
}
impl Default for HeadPoseSample {
fn default() -> Self {
Self {
pan_deg: 0.0,
tilt_deg: 0.0,
roll_deg: 0.0,
pan_crsf: CRSF_CHANNEL_MID,
tilt_crsf: CRSF_CHANNEL_MID,
roll_crsf: CRSF_CHANNEL_MID,
packets_sent: 0,
send_errors: 0,
last_send_ok: false,
}
}
}
pub struct NomadHeadTracker {
socket: UdpSocket,
target: SocketAddr,
zero_quat_inv: Quat,
max_pan_deg: f32,
max_tilt_deg: f32,
max_roll_deg: f32,
protocol: NomadProtocol,
mav_seq: u8,
last_mav_heartbeat: Option<Instant>,
packets_sent: u64,
send_errors: u64,
last_error_log: Option<Instant>,
}
impl NomadHeadTracker {
pub fn new(
nomad_ip: &str,
nomad_port: u16,
max_pan_deg: f32,
max_tilt_deg: f32,
max_roll_deg: f32,
protocol: NomadProtocol,
) -> Result<Self> {
let trimmed_ip = nomad_ip.trim();
let host_port = format!("{}:{}", trimmed_ip, nomad_port);
let target = if let Ok(ip) = trimmed_ip.parse::<std::net::IpAddr>() {
SocketAddr::new(ip, nomad_port)
} else {
let addrs: Vec<SocketAddr> = host_port
.to_socket_addrs()
.map_err(|e| {
log::error!(
"[Wi-Fi Nomad] Impossible de résoudre la cible ({}) : {}",
host_port,
e
);
e
})?
.collect();
addrs
.iter()
.copied()
.find(|a| a.is_ipv4())
.or_else(|| addrs.into_iter().next())
.ok_or_else(|| anyhow!("Aucune adresse IP résolue pour {}", host_port))?
};
let bind_addr = if target.is_ipv6() { "[::]:0" } else { "0.0.0.0:0" };
let socket = UdpSocket::bind(bind_addr).map_err(|e| {
log::error!(
"[Wi-Fi Nomad] Impossible de créer le socket UDP sortant : {}",
e
);
e
})?;
socket.set_nonblocking(true)?;
log::info!(
"[Wi-Fi Nomad] Émetteur prêt vers {} ({}) (Protocole: {})",
host_port,
target,
protocol.label()
);
Ok(Self {
socket,
target,
zero_quat_inv: Quat::IDENTITY,
max_pan_deg,
max_tilt_deg,
max_roll_deg,
protocol,
mav_seq: 0,
last_mav_heartbeat: None,
packets_sent: 0,
send_errors: 0,
last_error_log: None,
})
}
/// Réinitialise le centre du suivi de tête (Tare) sur la posture actuelle du casque
pub fn recenter(&mut self, current_orientation: Quat) {
let safe_q = if current_orientation.is_finite()
&& current_orientation.length_squared() > 1e-8
{
current_orientation.normalize()
} else {
Quat::IDENTITY
};
self.zero_quat_inv = safe_q.inverse();
log::info!("[Head-Tracker] Centre (Tare) réinitialisé sur la position actuelle du casque.");
}
/// Calcule Pan/Tilt/Roll depuis le quaternion OpenXR et envoie la trame UDP au Nomad
pub fn send_pose(&mut self, current_orientation: Quat) -> Result<HeadPoseSample> {
let raw_rel = self.zero_quat_inv * current_orientation;
let relative = if raw_rel.is_finite() && raw_rel.length_squared() > 1e-8 {
raw_rel.normalize()
} else {
Quat::IDENTITY
};
let (yaw_rad, pitch_rad, roll_rad) = relative.to_euler(EulerRot::YXZ);
let pan_deg = -yaw_rad.to_degrees();
let tilt_deg = pitch_rad.to_degrees();
let roll_deg = -roll_rad.to_degrees();
self.send_manual_angles(pan_deg, tilt_deg, roll_deg)
}
/// Encode et envoie directement des angles Pan/Tilt/Roll (en degrés) vers la cible UDP
pub fn send_manual_angles(
&mut self,
pan_deg: f32,
tilt_deg: f32,
roll_deg: f32,
) -> Result<HeadPoseSample> {
let pan_crsf = Self::deg_to_crsf(pan_deg, self.max_pan_deg);
let tilt_crsf = Self::deg_to_crsf(tilt_deg, self.max_tilt_deg);
let roll_crsf = Self::deg_to_crsf(roll_deg, self.max_roll_deg);
let send_res = match self.protocol {
NomadProtocol::Crsf => {
let packet = Self::encode_crsf_rc_channels(pan_crsf, tilt_crsf, roll_crsf);
self.socket.send_to(&packet, self.target)
}
NomadProtocol::Msp => {
let packet = Self::encode_mspv2_ptr(pan_crsf, tilt_crsf, roll_crsf);
self.socket.send_to(&packet, self.target)
}
NomadProtocol::Mavlink => {
if self
.last_mav_heartbeat
.is_none_or(|t| t.elapsed() >= Duration::from_secs(1))
{
let hb = Self::encode_mavlink_heartbeat(self.mav_seq);
self.mav_seq = self.mav_seq.wrapping_add(1);
let _ = self.socket.send_to(&hb, self.target);
self.last_mav_heartbeat = Some(Instant::now());
}
let packet = Self::encode_mavlink_rc_override(
pan_crsf,
tilt_crsf,
roll_crsf,
self.mav_seq,
);
self.mav_seq = self.mav_seq.wrapping_add(1);
self.socket.send_to(&packet, self.target)
}
NomadProtocol::G29Bridge => {
let msg = Self::encode_g29_ht(pan_crsf, tilt_crsf, roll_crsf);
self.socket.send_to(msg.as_bytes(), self.target)
}
};
let last_send_ok = match send_res {
Ok(_) => {
self.packets_sent = self.packets_sent.wrapping_add(1);
true
}
Err(e) => {
self.send_errors = self.send_errors.wrapping_add(1);
let should_log = self
.last_error_log
.map(|t| t.elapsed() >= Duration::from_secs(3))
.unwrap_or(true);
if should_log {
log::error!(
"[Wi-Fi Nomad] Échec d'envoi UDP vers {} : {} (Vérifiez la connexion Wi-Fi au Backpack du RadioMaster Nomad)",
self.target,
e
);
self.last_error_log = Some(Instant::now());
}
false
}
};
Ok(HeadPoseSample {
pan_deg,
tilt_deg,
roll_deg,
pan_crsf,
tilt_crsf,
roll_crsf,
packets_sent: self.packets_sent,
send_errors: self.send_errors,
last_send_ok,
})
}
#[inline]
pub fn deg_to_crsf(angle_deg: f32, max_deg: f32) -> u16 {
if !angle_deg.is_finite() || !max_deg.is_finite() || max_deg <= 0.0 {
return CRSF_CHANNEL_MID;
}
let norm = (angle_deg / max_deg).clamp(-1.0, 1.0);
let crsf_val = if norm >= 0.0 {
CRSF_CHANNEL_MID as f32 + norm * (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32
} else {
CRSF_CHANNEL_MID as f32 + norm * (CRSF_CHANNEL_MID - CRSF_CHANNEL_MIN) as f32
};
(crsf_val.round() as u16).clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX)
}
/// Ajoute un suffixe CRC-8 DVB-S2 (`*XX\n`) à une trame texte `$...` pour validation UART RP2350.
pub fn append_nmea_crc8(payload: &str) -> String {
let crc = Self::crc8_dvb_s2(payload.as_bytes());
format!("{}*{:02X}\n", payload, crc)
}
pub fn encode_g29_ht(pan: u16, tilt: u16, roll: u16) -> String {
Self::append_nmea_crc8(&format!("$HT,{},{},{}", pan, tilt, roll))
}
pub fn encode_mspv2_ptr(pan: u16, tilt: u16, roll: u16) -> [u8; 15] {
let mut buf = [0u8; 15];
buf[0] = b'$';
buf[1] = b'X';
buf[2] = b'<';
buf[3] = 0x00;
buf[4..6].copy_from_slice(&MSP_ELRS_BACKPACK_SET_PTR.to_le_bytes());
buf[6..8].copy_from_slice(&6u16.to_le_bytes());
buf[8..10].copy_from_slice(&pan.to_le_bytes());
buf[10..12].copy_from_slice(&tilt.to_le_bytes());
buf[12..14].copy_from_slice(&roll.to_le_bytes());
buf[14] = Self::crc8_dvb_s2(&buf[3..14]);
buf
}
pub fn encode_crsf_rc_channels(pan: u16, tilt: u16, roll: u16) -> [u8; 26] {
let mut ch = [CRSF_CHANNEL_MID; 16];
ch[0] = pan.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
ch[1] = tilt.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
ch[2] = roll.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
let mut frame = [0u8; 26];
frame[0] = 0xEE;
frame[1] = 24;
frame[2] = 0x16;
let mut bit_buf: u32 = 0;
let mut bits_in_buf: u8 = 0;
let mut byte_idx = 3;
for &val in &ch {
bit_buf |= ((val & 0x07FF) as u32) << bits_in_buf;
bits_in_buf += 11;
while bits_in_buf >= 8 {
frame[byte_idx] = (bit_buf & 0xFF) as u8;
byte_idx += 1;
bit_buf >>= 8;
bits_in_buf -= 8;
}
}
frame[25] = Self::crc8_dvb_s2(&frame[2..25]);
frame
}
/// Convertit une valeur CRSF (172..1811, neutre 992) en microsecondes PWM (988..2012, neutre 1500)
#[inline]
pub fn crsf_to_pwm_us(crsf: u16) -> u16 {
let clamped = crsf.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX) as f32;
if clamped >= CRSF_CHANNEL_MID as f32 {
let norm = (clamped - CRSF_CHANNEL_MID as f32) / (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32;
(1500.0 + norm * 512.0).round() as u16
} else {
let norm = (clamped - CRSF_CHANNEL_MID as f32) / (CRSF_CHANNEL_MID - CRSF_CHANNEL_MIN) as f32;
(1500.0 + norm * 512.0).round() as u16
}
}
/// Encode une trame MAVLink v1 HEARTBEAT (msgid=0, crc_extra=50) pour s'identifier auprès du Backpack
pub fn encode_mavlink_heartbeat(seq: u8) -> [u8; 17] {
let mut payload = [0u8; 9];
payload[4] = 6; // MAV_TYPE_GCS
payload[5] = 8; // MAV_AUTOPILOT_INVALID
payload[8] = 3; // mavlink_version
Self::encode_mavlink_v1_frame::<9, 17>(0, seq, 50, &payload)
}
/// Encode une trame MAVLink v1 RC_CHANNELS_OVERRIDE (msgid=70, crc_extra=124) sur les canaux 1..3
pub fn encode_mavlink_rc_override(pan: u16, tilt: u16, roll: u16, seq: u8) -> [u8; 26] {
let mut payload = [0u8; 18];
let ch1 = Self::crsf_to_pwm_us(pan);
let ch2 = Self::crsf_to_pwm_us(tilt);
let ch3 = Self::crsf_to_pwm_us(roll);
let ignore = u16::MAX;
payload[0..2].copy_from_slice(&ch1.to_le_bytes());
payload[2..4].copy_from_slice(&ch2.to_le_bytes());
payload[4..6].copy_from_slice(&ch3.to_le_bytes());
payload[6..8].copy_from_slice(&ignore.to_le_bytes());
payload[8..10].copy_from_slice(&ignore.to_le_bytes());
payload[10..12].copy_from_slice(&ignore.to_le_bytes());
payload[12..14].copy_from_slice(&ignore.to_le_bytes());
payload[14..16].copy_from_slice(&ignore.to_le_bytes());
payload[16] = 1; // target_system
payload[17] = 1; // target_component
Self::encode_mavlink_v1_frame::<18, 26>(70, seq, 124, &payload)
}
fn encode_mavlink_v1_frame<const P: usize, const T: usize>(
msgid: u8,
seq: u8,
crc_extra: u8,
payload: &[u8; P],
) -> [u8; T] {
debug_assert_eq!(T, P + 8);
let mut buf = [0u8; T];
buf[0] = 0xFE;
buf[1] = P as u8;
buf[2] = seq;
buf[3] = 255; // GCS system_id
buf[4] = 190; // MAV_COMP_ID_MISSIONPLANNER / GCS
buf[5] = msgid;
buf[6..6 + P].copy_from_slice(payload);
let crc = Self::mavlink_crc16(&buf[1..6 + P], crc_extra);
buf[6 + P..8 + P].copy_from_slice(&crc.to_le_bytes());
buf
}
#[inline]
pub fn mavlink_crc16(data: &[u8], crc_extra: u8) -> u16 {
let mut crc: u16 = 0xFFFF;
for &b in data.iter().chain(std::iter::once(&crc_extra)) {
let mut tmp = b ^ (crc & 0xFF) as u8;
tmp ^= tmp << 4;
crc = (crc >> 8)
^ ((tmp as u16) << 8)
^ ((tmp as u16) << 3)
^ ((tmp as u16) >> 4);
}
crc
}
#[inline]
pub fn crc8_dvb_s2(data: &[u8]) -> u8 {
const TABLE: [u8; 256] = {
let mut table = [0u8; 256];
let mut i = 0;
while i < 256 {
let mut curr = i as u8;
let mut j = 0;
while j < 8 {
if (curr & 0x80) != 0 {
curr = (curr << 1) ^ 0xD5;
} else {
curr <<= 1;
}
j += 1;
}
table[i] = curr;
i += 1;
}
table
};
let mut crc: u8 = 0;
for &byte in data {
crc = TABLE[(crc ^ byte) as usize];
}
crc
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_deg_to_crsf_bounds() {
assert_eq!(NomadHeadTracker::deg_to_crsf(0.0, 90.0), CRSF_CHANNEL_MID);
assert_eq!(NomadHeadTracker::deg_to_crsf(90.0, 90.0), CRSF_CHANNEL_MAX);
assert_eq!(NomadHeadTracker::deg_to_crsf(-90.0, 90.0), CRSF_CHANNEL_MIN);
assert_eq!(NomadHeadTracker::deg_to_crsf(f32::NAN, 90.0), CRSF_CHANNEL_MID);
assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, f32::NAN), CRSF_CHANNEL_MID);
assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, 0.0), CRSF_CHANNEL_MID);
assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, -10.0), CRSF_CHANNEL_MID);
}
#[test]
fn test_mspv2_ptr_packet_header() {
let pkt = NomadHeadTracker::encode_mspv2_ptr(992, 992, 992);
assert_eq!(&pkt[0..3], b"$X<");
assert_eq!(u16::from_le_bytes([pkt[4], pkt[5]]), MSP_ELRS_BACKPACK_SET_PTR);
assert_eq!(u16::from_le_bytes([pkt[6], pkt[7]]), 6);
assert_eq!(pkt[14], NomadHeadTracker::crc8_dvb_s2(&pkt[3..14]));
}
#[test]
fn test_crsf_rc_channels_packet() {
let pkt = NomadHeadTracker::encode_crsf_rc_channels(992, 992, 992);
assert_eq!(pkt[0], 0xEE); // Sync CRSF
assert_eq!(pkt[1], 24); // Payload len
assert_eq!(pkt[2], 0x16); // Type RC_CHANNELS_PACKED
assert_eq!(pkt[25], NomadHeadTracker::crc8_dvb_s2(&pkt[2..25]));
}
#[test]
fn test_mavlink_rc_override_packet() {
assert_eq!(NomadHeadTracker::crsf_to_pwm_us(992), 1500);
let pkt = NomadHeadTracker::encode_mavlink_rc_override(992, 992, 992, 7);
assert_eq!(pkt[0], 0xFE);
assert_eq!(pkt[1], 18);
assert_eq!(pkt[2], 7);
assert_eq!(pkt[5], 70);
assert_eq!(u16::from_le_bytes([pkt[6], pkt[7]]), 1500);
assert_eq!(u16::from_le_bytes([pkt[8], pkt[9]]), 1500);
assert_eq!(u16::from_le_bytes([pkt[10], pkt[11]]), 1500);
let expected_crc = NomadHeadTracker::mavlink_crc16(&pkt[1..24], 124);
assert_eq!(u16::from_le_bytes([pkt[24], pkt[25]]), expected_crc);
}
#[test]
fn test_mavlink_heartbeat_packet() {
let pkt = NomadHeadTracker::encode_mavlink_heartbeat(1);
assert_eq!(pkt[0], 0xFE);
assert_eq!(pkt[1], 9);
assert_eq!(pkt[5], 0);
let expected_crc = NomadHeadTracker::mavlink_crc16(&pkt[1..15], 50);
assert_eq!(u16::from_le_bytes([pkt[15], pkt[16]]), expected_crc);
}
#[test]
fn test_hostname_resolution_default_ip() {
let ht = NomadHeadTracker::new("10.0.0.1", 14550, 90.0, 60.0, 45.0, NomadProtocol::Msp);
assert!(ht.is_ok());
}
#[test]
fn test_g29_bridge_ht_format() {
assert_eq!(NomadProtocol::from_str("g29"), NomadProtocol::G29Bridge);
let frame = NomadHeadTracker::encode_g29_ht(992, 1200, 800);
let (body, hex_crc) = frame.trim_end_matches('\n').split_once('*').unwrap();
assert_eq!(body, "$HT,992,1200,800");
let expected = format!("{:02X}", NomadHeadTracker::crc8_dvb_s2(body.as_bytes()));
assert_eq!(hex_crc, expected);
}
}
+1 -4
View File
@@ -1,10 +1,7 @@
mod osd; mod osd;
mod parser;
mod state;
pub use fpv_core::telemetry::{TelemetryReceiver, TelemetryState};
pub use osd::{OsdExtraOptions, OsdOverlay, VrMenuPage, VrMenuRenderData}; pub use osd::{OsdExtraOptions, OsdOverlay, VrMenuPage, VrMenuRenderData};
pub use parser::TelemetryReceiver;
pub use state::TelemetryState;
/// Tampon de formatage rapide sur la pile pour éliminer toute allocation sur le tas dans l'OSD /// Tampon de formatage rapide sur la pile pour éliminer toute allocation sur le tas dans l'OSD
pub(super) struct StackStr<const N: usize> { pub(super) struct StackStr<const N: usize> {
+1 -1
View File
@@ -1,4 +1,4 @@
use super::state::TelemetryState; use super::TelemetryState;
use super::StackStr; use super::StackStr;
use crate::controller::ControlSource; use crate::controller::ControlSource;
use crate::g29_bridge::G29State; use crate::g29_bridge::G29State;