Merge pull request #10 from bleackstorm/fix/critical-safety-and-crc8

Fix/critical safety and crc8
This commit is contained in:
bleackstorm authored and GitHub committed 2026-11-23 22:39:38 +01:00
commit fb422e941b
11 files changed
+805 -101

No files matched your search

+125 -30
View File
@@ -116,7 +116,7 @@ const uint16_t GAZ_AVANT_MAX_PAR_VITESSE[3] = {
#define PENTE_RESSORT_G29 7 // Raideur autour du centre : 1 a 7
#define ETAPES_INIT_FFB_TOTAL 2 // Nombre d'etapes d'init FFB initiales (0=Range, 1=Spring)
#define VIBRATION_DEFAUT 50 // Intensite par defaut des vibrations (0 a 100%)
#define MAGIC_NUMBER_CONFIG 0x4A // Identifiant de validite en EEPROM (mis a jour pour 50% vibrations)
#define MAGIC_NUMBER_CONFIG 0x4B // Identifiant de validite en EEPROM (mis a jour pour vitesses CRSF)
Adafruit_NeoPixel rgb_led(NUM_PIXELS, PIN_LED_RGB, NEO_GRB + NEO_KHZ800);
Adafruit_USBH_Host USBHost;
@@ -137,6 +137,10 @@ struct __attribute__((packed)) ConfigG29 {
uint16_t angleSouhaiteTotal; // Plage totale en degrés : 40 à 900
float expoVolant; // Expo volant : 0.0f à 0.8f
uint8_t intensiteVibration; // Intensité globale des vibrations : 0 à 100%
uint16_t gazAvantMin; // Seuil de démarrage marche avant (défaut 1065)
uint16_t gazAvantMax[3]; // Plafonds 1ère, 2ème, 3ème vitesse
uint16_t gazArriereMin; // Seuil de démarrage marche arrière (défaut 905)
uint16_t gazArriereMax; // Plafond marche arrière (défaut 800)
uint8_t magicNumber; // Identifiant de validité en EEPROM (MAGIC_NUMBER_CONFIG)
};
@@ -238,17 +242,31 @@ volatile uint8_t extEmbrayagePct = 0;
volatile int8_t extVolantPct = 0;
volatile uint32_t dernierPaquetRC_ms = 0;
static inline uint16_t crsfChannelLoad(uint8_t idx) {
return __atomic_load_n(&crsf_channels[idx], __ATOMIC_RELAXED);
}
static inline void crsfChannelStore(uint8_t idx, uint16_t val) {
__atomic_store_n(&crsf_channels[idx], val, __ATOMIC_RELAXED);
}
static inline bool estActuellementArme() {
return (sourceActive == SRC_EXT) ? extArme : estArme;
uint8_t src = __atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE);
return (src == SRC_EXT)
? __atomic_load_n(&extArme, __ATOMIC_ACQUIRE)
: __atomic_load_n(&estArme, __ATOMIC_ACQUIRE);
}
static inline int8_t rapportActuel() {
return (sourceActive == SRC_EXT) ? extRapport : rapportEngage;
uint8_t src = __atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE);
return (src == SRC_EXT)
? __atomic_load_n(&extRapport, __ATOMIC_ACQUIRE)
: __atomic_load_n(&rapportEngage, __ATOMIC_ACQUIRE);
}
static inline void assignerCanalCRSF(uint8_t numeroCh, uint16_t valeur11bits) {
if (numeroCh >= 1 && numeroCh <= 16 && numeroCh != CANAL_ARM) {
crsf_channels[numeroCh - 1] = valeur11bits;
crsfChannelStore(numeroCh - 1, valeur11bits);
}
}
@@ -262,9 +280,9 @@ void reinitialiserCanauxCRSF() {
if (htActif && (i == (CANAL_HT_PAN - 1) || i == (CANAL_HT_TILT - 1) || i == (CANAL_HT_ROLL - 1))) {
continue;
}
crsf_channels[i] = CRSF_VAL_MID;
crsfChannelStore((uint8_t)i, CRSF_VAL_MID);
}
crsf_channels[CANAL_ARM - 1] = CRSF_VAL_MIN; // Toujours désarmé par défaut
crsfChannelStore(CANAL_ARM - 1, CRSF_VAL_MIN); // Toujours désarmé par défaut
}
void reinitialiserConfigurationDefaut() {
@@ -277,13 +295,22 @@ void reinitialiserConfigurationDefaut() {
configSysteme.angleSouhaiteTotal = ANGLE_DEFAUT_TOTAL;
configSysteme.expoVolant = EXPO_DEFAUT;
configSysteme.intensiteVibration = VIBRATION_DEFAUT;
configSysteme.gazAvantMin = GAZ_AVANT_MIN;
configSysteme.gazAvantMax[0] = GAZ_AVANT_MAX_PAR_VITESSE[0];
configSysteme.gazAvantMax[1] = GAZ_AVANT_MAX_PAR_VITESSE[1];
configSysteme.gazAvantMax[2] = GAZ_AVANT_MAX_PAR_VITESSE[2];
configSysteme.gazArriereMin = GAZ_ARRIERE_MIN;
configSysteme.gazArriereMax = GAZ_ARRIERE_MAX;
configSysteme.magicNumber = MAGIC_NUMBER_CONFIG;
recalculerParametresVolant();
}
void sauvegarderConfiguration() {
ConfigG29 cfgActuelle;
// Geler brièvement le Cœur 1 pour garantir un instantané cohérent de configSysteme.
rp2040.idleOtherCore();
memcpy(&cfgActuelle, (const void*)&configSysteme, sizeof(ConfigG29));
rp2040.resumeOtherCore();
ConfigG29 cfgStockee;
EEPROM.get(0, cfgStockee);
@@ -313,7 +340,14 @@ void afficherConfiguration() {
Serial.printf("Source active : %s [$SRC,G29 | $SRC,EXT]\n",
(sourceActive == SRC_EXT) ? "EXT (Steam Controller)" : "G29 (Volant)");
Serial.printf("Vibrations (T) : %d%% [Boutons +/- ou T=0..100] (0 = desactive)\n", configSysteme.intensiteVibration);
Serial.println("Commandes : V=ch, A=ch, F=ch, E=ch, D=val, P=val, X=val, T=val, $SRC,G29|EXT, $RC,..., $HT,..., S(save), R(reset), B(bootsel), ?");
Serial.printf("Vitesses CRSF : AV_MIN=%u | 1=%u | 2=%u | 3=%u | AR_MIN=%u | AR_MAX=%u\n",
configSysteme.gazAvantMin,
configSysteme.gazAvantMax[0],
configSysteme.gazAvantMax[1],
configSysteme.gazAvantMax[2],
configSysteme.gazArriereMin,
configSysteme.gazArriereMax);
Serial.println("Commandes : V=ch, A=ch, F=ch, E=ch, D=val, P=val, X=val, T=val, $SRC,G29|EXT, $GEARS,..., $RC,..., $HT,..., S(save), R(reset), B(bootsel), ?");
}
void chargerConfiguration() {
@@ -345,10 +379,17 @@ void chargerConfiguration() {
bool vibValide = (configSysteme.intensiteVibration <= 100);
if (configSysteme.magicNumber != MAGIC_NUMBER_CONFIG || conflitArm || !canauxValides || !canauxDistincts || !expoValide || !angleValide || !vibValide) {
bool vitessesValides = (configSysteme.gazAvantMin >= CRSF_VAL_MID && configSysteme.gazAvantMin <= CRSF_VAL_MAX) &&
(configSysteme.gazAvantMax[0] >= configSysteme.gazAvantMin && configSysteme.gazAvantMax[0] <= CRSF_VAL_MAX) &&
(configSysteme.gazAvantMax[1] >= configSysteme.gazAvantMin && configSysteme.gazAvantMax[1] <= CRSF_VAL_MAX) &&
(configSysteme.gazAvantMax[2] >= configSysteme.gazAvantMin && configSysteme.gazAvantMax[2] <= CRSF_VAL_MAX) &&
(configSysteme.gazArriereMin >= CRSF_VAL_MIN && configSysteme.gazArriereMin <= CRSF_VAL_MID) &&
(configSysteme.gazArriereMax >= CRSF_VAL_MIN && configSysteme.gazArriereMax <= configSysteme.gazArriereMin);
if (configSysteme.magicNumber != MAGIC_NUMBER_CONFIG || conflitArm || !canauxValides || !canauxDistincts || !expoValide || !angleValide || !vibValide || !vitessesValides) {
if (conflitArm) Serial.println("!! Un axe etait mappe sur le canal ARM : configuration reinitialisee !!");
else if (!canauxValides || !canauxDistincts) Serial.println("!! Conflit ou canal invalide en EEPROM : configuration reinitialisee !!");
else if (!expoValide || !angleValide || !vibValide) Serial.println("!! Valeur invalide en EEPROM : configuration reinitialisee !!");
else if (!expoValide || !angleValide || !vibValide || !vitessesValides) Serial.println("!! Valeur invalide en EEPROM : configuration reinitialisee !!");
else Serial.println(">> Initialisation configuration d'usine par defaut...");
reinitialiserConfigurationDefaut();
sauvegarderConfiguration();
@@ -529,13 +570,32 @@ void traiterLigneSerie(char* commande) {
return;
}
// Validation CRC-8 DVB-S2 (*XX) obligatoire sur toutes les trames $... (anti-corruption UART)
if (commande[0] == '$') {
char* star = strrchr(commande, '*');
if (!star || strlen(star + 1) != 2) {
return;
}
char* endPtr = nullptr;
unsigned long crcRecu = strtoul(star + 1, &endPtr, 16);
if (endPtr != star + 3) {
return;
}
size_t bodyLen = (size_t)(star - commande);
uint8_t crcCalc = calculerCrc8Crsf((const uint8_t*)commande, bodyLen);
if ((uint8_t)crcRecu != crcCalc) {
return;
}
*star = '\0';
}
// Injection Head-Tracking depuis SteamFrame FPV : $HT,<pan>,<tilt>,<roll> (172..1811)
if (strncmp(commande, "$HT,", 4) == 0) {
int pan = CRSF_VAL_MID, tilt = CRSF_VAL_MID, roll = CRSF_VAL_MID;
if (sscanf(commande + 4, "%d,%d,%d", &pan, &tilt, &roll) == 3) {
crsf_channels[CANAL_HT_PAN - 1] = (uint16_t)constrain(pan, CRSF_VAL_MIN, CRSF_VAL_MAX);
crsf_channels[CANAL_HT_TILT - 1] = (uint16_t)constrain(tilt, CRSF_VAL_MIN, CRSF_VAL_MAX);
crsf_channels[CANAL_HT_ROLL - 1] = (uint16_t)constrain(roll, CRSF_VAL_MIN, CRSF_VAL_MAX);
crsfChannelStore(CANAL_HT_PAN - 1, (uint16_t)constrain(pan, CRSF_VAL_MIN, CRSF_VAL_MAX));
crsfChannelStore(CANAL_HT_TILT - 1, (uint16_t)constrain(tilt, CRSF_VAL_MIN, CRSF_VAL_MAX));
crsfChannelStore(CANAL_HT_ROLL - 1, (uint16_t)constrain(roll, CRSF_VAL_MIN, CRSF_VAL_MAX));
dernierPaquetHT_ms = millis();
htActif = true;
}
@@ -585,6 +645,41 @@ void traiterLigneSerie(char* commande) {
return;
}
// Synchronisation des plages de vitesses CRSF depuis SteamFrame FPV :
// $GEARS,<fwd_min>,<g1_max>,<g2_max>,<g3_max>,<rev_min>,<rev_max>
if (strncmp(commande, "$GEARS,", 7) == 0) {
int fMin = 0, g1 = 0, g2 = 0, g3 = 0, rMin = 0, rMax = 0;
if (sscanf(commande + 7, "%d,%d,%d,%d,%d,%d", &fMin, &g1, &g2, &g3, &rMin, &rMax) == 6) {
uint16_t vFMin = (uint16_t)constrain(fMin, CRSF_VAL_MID, CRSF_VAL_MAX);
uint16_t vG1 = (uint16_t)constrain(g1, (int)vFMin, CRSF_VAL_MAX);
uint16_t vG2 = (uint16_t)constrain(g2, (int)vFMin, CRSF_VAL_MAX);
uint16_t vG3 = (uint16_t)constrain(g3, (int)vFMin, CRSF_VAL_MAX);
uint16_t vRMin = (uint16_t)constrain(rMin, CRSF_VAL_MIN, CRSF_VAL_MID);
uint16_t vRMax = (uint16_t)constrain(rMax, CRSF_VAL_MIN, (int)vRMin);
bool modifie = (configSysteme.gazAvantMin != vFMin) ||
(configSysteme.gazAvantMax[0] != vG1) ||
(configSysteme.gazAvantMax[1] != vG2) ||
(configSysteme.gazAvantMax[2] != vG3) ||
(configSysteme.gazArriereMin != vRMin) ||
(configSysteme.gazArriereMax != vRMax);
configSysteme.gazAvantMin = vFMin;
configSysteme.gazAvantMax[0] = vG1;
configSysteme.gazAvantMax[1] = vG2;
configSysteme.gazAvantMax[2] = vG3;
configSysteme.gazArriereMin = vRMin;
configSysteme.gazArriereMax = vRMax;
if (modifie) {
sauvegarderConfiguration();
Serial.printf(">> [VITESSES] AV_MIN=%u | 1=%u | 2=%u | 3=%u | AR_MIN=%u | AR_MAX=%u\n",
vFMin, vG1, vG2, vG3, vRMin, vRMax);
}
}
return;
}
// Injection conduite externe (Steam Controller via SteamFrame FPV) :
// $RC,<steer>,<accel>,<brake>,<clutch>,<arm>,<gear>
if (strncmp(commande, "$RC,", 4) == 0) {
@@ -631,11 +726,11 @@ void traiterLigneSerie(char* commande) {
}
uint8_t accelPct = 0;
if (extArme && extRapport >= 1 && extRapport <= 3 && vAccel >= GAZ_AVANT_MIN) {
uint16_t maxV = GAZ_AVANT_MAX_PAR_VITESSE[extRapport - 1];
accelPct = (uint8_t)constrain(map(vAccel, GAZ_AVANT_MIN, maxV, 0, 100), 0, 100);
} else if (extArme && extRapport == -1 && vAccel <= GAZ_ARRIERE_MIN) {
accelPct = (uint8_t)constrain(map(vAccel, GAZ_ARRIERE_MIN, GAZ_ARRIERE_MAX, 0, 100), 0, 100);
if (extArme && extRapport >= 1 && extRapport <= 3 && vAccel >= configSysteme.gazAvantMin) {
uint16_t maxV = configSysteme.gazAvantMax[extRapport - 1];
accelPct = (uint8_t)constrain(map(vAccel, configSysteme.gazAvantMin, maxV, 0, 100), 0, 100);
} else if (extArme && extRapport == -1 && vAccel <= configSysteme.gazArriereMin) {
accelPct = (uint8_t)constrain(map(vAccel, configSysteme.gazArriereMin, configSysteme.gazArriereMax, 0, 100), 0, 100);
}
uint8_t brakePct = (vBrake > CRSF_VAL_MID)
? (uint8_t)constrain(map(vBrake, CRSF_VAL_MID, CRSF_VAL_MAX, 0, 100), 0, 100)
@@ -656,7 +751,7 @@ void traiterLigneSerie(char* commande) {
assignerCanalCRSF(configSysteme.accel, vAccel);
assignerCanalCRSF(configSysteme.frein, vBrake);
assignerCanalCRSF(configSysteme.embrayage, vClutch);
crsf_channels[CANAL_ARM - 1] = extArme ? CRSF_VAL_MAX : CRSF_VAL_MIN;
crsfChannelStore(CANAL_ARM - 1, extArme ? CRSF_VAL_MAX : CRSF_VAL_MIN);
dernierPaquetRC_ms = millis();
if (!extRcActif) {
@@ -750,7 +845,7 @@ void __not_in_flash_func(envoyer_paquet_crsf)(bool neutre) {
uint16_t ch[16];
for (int i = 0; i < 16; i++) {
ch[i] = neutre ? CRSF_VAL_MID : crsf_channels[i];
ch[i] = neutre ? CRSF_VAL_MID : crsfChannelLoad((uint8_t)i);
}
if (neutre) ch[CANAL_ARM - 1] = CRSF_VAL_MIN; // Failsafe : toujours désarmé
@@ -1052,10 +1147,10 @@ void gererSortieCockpit() {
int steer = (sourceActive == SRC_EXT)
? (int)extVolantPct
: (int)constrain(((float)dernierVolantCentre / (float)dMax) * 100.0f, -100.0f, 100.0f);
uint16_t ch1 = failsafeActif ? CRSF_VAL_MID : crsf_channels[configSysteme.volant - 1];
uint16_t ch2 = failsafeActif ? CRSF_VAL_MID : crsf_channels[configSysteme.accel - 1];
uint16_t ch3 = failsafeActif ? CRSF_VAL_MID : crsf_channels[configSysteme.frein - 1];
uint16_t ch4 = failsafeActif ? CRSF_VAL_MID : crsf_channels[configSysteme.embrayage - 1];
uint16_t ch1 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.volant - 1);
uint16_t ch2 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.accel - 1);
uint16_t ch3 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.frein - 1);
uint16_t ch4 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.embrayage - 1);
const char* srcStr = (sourceActive == SRC_EXT) ? "EXT" : "G29";
char bufEtat[176];
snprintf(bufEtat, sizeof(bufEtat),
@@ -1081,9 +1176,9 @@ void gererSortieCockpit() {
void gererTimeoutHeadTracking() {
if (htActif && (millis() - dernierPaquetHT_ms > TIMEOUT_HT_MS)) {
htActif = false;
crsf_channels[CANAL_HT_PAN - 1] = CRSF_VAL_MID;
crsf_channels[CANAL_HT_TILT - 1] = CRSF_VAL_MID;
crsf_channels[CANAL_HT_ROLL - 1] = CRSF_VAL_MID;
crsfChannelStore(CANAL_HT_PAN - 1, CRSF_VAL_MID);
crsfChannelStore(CANAL_HT_TILT - 1, CRSF_VAL_MID);
crsfChannelStore(CANAL_HT_ROLL - 1, CRSF_VAL_MID);
}
}
@@ -1875,10 +1970,10 @@ void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t i
uint16_t vAccel = CRSF_VAL_MID;
if (estArme && accelRaw > DEADZONE_PEDALE) { // Désarmé : gaz coupés quoi qu'il arrive
if (rapportEngage == -1) {
vAccel = constrain(map(accelRaw, DEADZONE_PEDALE, 65535, GAZ_ARRIERE_MIN, GAZ_ARRIERE_MAX), CRSF_VAL_MIN, CRSF_VAL_MAX);
vAccel = constrain(map(accelRaw, DEADZONE_PEDALE, 65535, configSysteme.gazArriereMin, configSysteme.gazArriereMax), CRSF_VAL_MIN, CRSF_VAL_MAX);
} else if (rapportEngage >= 1 && rapportEngage <= 3) {
uint16_t maxVitesse = GAZ_AVANT_MAX_PAR_VITESSE[rapportEngage - 1];
vAccel = constrain(map(accelRaw, DEADZONE_PEDALE, 65535, GAZ_AVANT_MIN, maxVitesse), CRSF_VAL_MIN, CRSF_VAL_MAX);
uint16_t maxVitesse = configSysteme.gazAvantMax[rapportEngage - 1];
vAccel = constrain(map(accelRaw, DEADZONE_PEDALE, 65535, configSysteme.gazAvantMin, maxVitesse), CRSF_VAL_MIN, CRSF_VAL_MAX);
}
}
@@ -1894,7 +1989,7 @@ void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t i
assignerCanalCRSF(configSysteme.accel, vAccel);
assignerCanalCRSF(configSysteme.frein, vFrein);
assignerCanalCRSF(configSysteme.embrayage, vEmbrayage);
crsf_channels[CANAL_ARM - 1] = estArme ? CRSF_VAL_MAX : CRSF_VAL_MIN;
crsfChannelStore(CANAL_ARM - 1, __atomic_load_n(&estArme, __ATOMIC_ACQUIRE) ? CRSF_VAL_MAX : CRSF_VAL_MIN);
// Horodatage APRÈS l'écriture des canaux : à la sortie d'un failsafe, le cœur 0
// ne peut pas renvoyer d'anciennes valeurs (d'avant la coupure) pendant un paquet.
+18 -2
View File
@@ -15,6 +15,7 @@ import time
from typing import Optional
BAUD_RATE = termios.B460800
BIND_IP = os.environ.get("STEAMFRAME_BIND_IP", "192.168.1.1")
CASQUE_IP = os.environ.get("STEAMFRAME_CASQUE_IP", "192.168.1.10")
UDP_PORT = int(os.environ.get("STEAMFRAME_G29_PORT", "14552"))
SERIAL_CANDIDATES = (
@@ -58,9 +59,22 @@ def find_serial_device() -> Optional[str]:
def main() -> None:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("0.0.0.0", UDP_PORT))
try:
sock.bind((BIND_IP, UDP_PORT))
bound_ip = BIND_IP
except OSError as exc:
print(
f"[radxa_g29_relay] Bind {BIND_IP}:{UDP_PORT} impossible ({exc}), fallback 0.0.0.0",
file=sys.stderr,
flush=True,
)
sock.bind(("0.0.0.0", UDP_PORT))
bound_ip = "0.0.0.0"
sock.setblocking(False)
print(f"[radxa_g29_relay] UDP :0.0.0.0:{UDP_PORT} <-> {CASQUE_IP}:{UDP_PORT}", flush=True)
print(
f"[radxa_g29_relay] UDP {bound_ip}:{UDP_PORT} <-> {CASQUE_IP}:{UDP_PORT} (filtre IP actif)",
flush=True,
)
serial_fd: Optional[int] = None
serial_buf = bytearray()
@@ -97,6 +111,8 @@ def main() -> None:
if sock.fileno() in readable:
try:
data, addr = sock.recvfrom(512)
if addr[0] not in (CASQUE_IP, "127.0.0.1"):
continue
last_casque_addr = (addr[0], UDP_PORT)
if data:
os.write(serial_fd, data)
+24
View File
@@ -72,6 +72,30 @@ pub struct AppConfig {
#[arg(long, default_value_t = 100)]
pub controller_vibration: u8,
/// Seuil CRSF de démarrage des gaz en marche avant (1ère, 2ème, 3ème)
#[arg(long, default_value_t = 1065)]
pub gaz_avant_min: u16,
/// Plafond CRSF de la 1ère vitesse (Manœuvre)
#[arg(long, default_value_t = 1100)]
pub gear_1_max: u16,
/// Plafond CRSF de la 2ème vitesse (Normale)
#[arg(long, default_value_t = 1150)]
pub gear_2_max: u16,
/// Plafond CRSF de la 3ème vitesse (Rapide)
#[arg(long, default_value_t = 1220)]
pub gear_3_max: u16,
/// Seuil CRSF de démarrage des gaz en marche arrière (R)
#[arg(long, default_value_t = 905)]
pub gaz_arriere_min: u16,
/// Plafond CRSF de la marche arrière (R)
#[arg(long, default_value_t = 800)]
pub gear_reverse_max: u16,
/// Codec vidéo reçu depuis le VRX OpenIPC / Ruby ("h264" ou "h265")
#[arg(long, default_value = "h264")]
pub codec: String,
+133 -25
View File
@@ -58,6 +58,46 @@ const GAZ_AVANT_MAX_PAR_VITESSE: [u16; 3] = [
const GAZ_ARRIERE_MIN: u16 = 905;
const GAZ_ARRIERE_MAX: u16 = 800;
/// Bornes CRSF configurables de la boîte séquentielle (marche avant 1/2/3 et marche arrière R).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GearSpeedLimits {
pub forward_min: u16,
pub forward_max: [u16; 3],
pub reverse_min: u16,
pub reverse_max: u16,
}
impl Default for GearSpeedLimits {
fn default() -> Self {
Self {
forward_min: GAZ_AVANT_MIN,
forward_max: GAZ_AVANT_MAX_PAR_VITESSE,
reverse_min: GAZ_ARRIERE_MIN,
reverse_max: GAZ_ARRIERE_MAX,
}
}
}
impl GearSpeedLimits {
/// Contraint chaque valeur dans les bornes CRSF valides et cohérentes.
pub fn sanitized(self) -> Self {
let forward_min = self.forward_min.clamp(CRSF_CHANNEL_MID, CRSF_CHANNEL_MAX);
let forward_max = [
self.forward_max[0].clamp(forward_min, CRSF_CHANNEL_MAX),
self.forward_max[1].clamp(forward_min, CRSF_CHANNEL_MAX),
self.forward_max[2].clamp(forward_min, CRSF_CHANNEL_MAX),
];
let reverse_min = self.reverse_min.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MID);
let reverse_max = self.reverse_max.clamp(CRSF_CHANNEL_MIN, reverse_min);
Self {
forward_min,
forward_max,
reverse_min,
reverse_max,
}
}
}
const TOAST_DURATION_MS: u64 = 1500;
const RC_SEND_INTERVAL_MS: u64 = 10; // 100 Hz vers RP2350
const HAPTICS_INTERVAL_MS: u64 = 40; // 25 Hz (identique au G29)
@@ -353,7 +393,13 @@ pub fn steering_to_crsf(raw_norm: f32, deadzone: f32, expo: f32, invert: bool) -
}
/// Normalise une gâchette [0.0..1.0] avec zone morte et calcule le canal gaz CRSF selon la boîte séquentielle.
pub fn throttle_to_crsf(throttle_norm: f32, deadzone: f32, armed: bool, gear: i8) -> (u8, u16) {
pub fn throttle_to_crsf(
throttle_norm: f32,
deadzone: f32,
armed: bool,
gear: i8,
limits: GearSpeedLimits,
) -> (u8, u16) {
let dz = deadzone.clamp(0.0, 0.45);
let clamped = throttle_norm.clamp(0.0, 1.0);
let active = if clamped <= dz {
@@ -367,13 +413,14 @@ pub fn throttle_to_crsf(throttle_norm: f32, deadzone: f32, armed: bool, gear: i8
return (pct, CRSF_CHANNEL_MID);
}
let s = limits.sanitized();
let crsf = if gear == -1 {
let span = GAZ_ARRIERE_MIN as f32 - GAZ_ARRIERE_MAX as f32;
(GAZ_ARRIERE_MIN as f32 - active * span).round() as u16
let span = s.reverse_min as f32 - s.reverse_max as f32;
(s.reverse_min as f32 - active * span).round() as u16
} else if (1..=3).contains(&gear) {
let max_v = GAZ_AVANT_MAX_PAR_VITESSE[(gear - 1) as usize];
let span = max_v as f32 - GAZ_AVANT_MIN as f32;
(GAZ_AVANT_MIN as f32 + active * span).round() as u16
let max_v = s.forward_max[(gear - 1) as usize];
let span = max_v as f32 - s.forward_min as f32;
(s.forward_min as f32 + active * span).round() as u16
} else {
CRSF_CHANNEL_MID
};
@@ -401,7 +448,20 @@ pub fn brake_to_crsf(brake_norm: f32, deadzone: f32) -> (u8, u16) {
}
pub fn encode_src_command(source: ControlSource) -> String {
format!("$SRC,{}\n", source.wire_tag())
crate::nomad_elrs::NomadHeadTracker::append_nmea_crc8(&format!("$SRC,{}", source.wire_tag()))
}
pub fn encode_gears_command(limits: GearSpeedLimits) -> String {
let s = limits.sanitized();
crate::nomad_elrs::NomadHeadTracker::append_nmea_crc8(&format!(
"$GEARS,{},{},{},{},{},{}",
s.forward_min,
s.forward_max[0],
s.forward_max[1],
s.forward_max[2],
s.reverse_min,
s.reverse_max,
))
}
pub fn encode_rc_frame(
@@ -412,15 +472,15 @@ pub fn encode_rc_frame(
armed: bool,
gear: i8,
) -> String {
format!(
"$RC,{},{},{},{},{},{}\n",
crate::nomad_elrs::NomadHeadTracker::append_nmea_crc8(&format!(
"$RC,{},{},{},{},{},{}",
steer.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX),
accel.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX),
brake.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX),
clutch.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX),
if armed { 1 } else { 0 },
gear.clamp(-1, 3),
)
))
}
// =========================================================================
@@ -672,6 +732,8 @@ impl OpenEvdevGamepad {
fn query_abs(file: &File, code: u16) -> Option<LinuxInputAbsInfo> {
let mut info = LinuxInputAbsInfo::default();
// SAFETY: `file` est un fd evdev valide ouvert, `eviocgabs(code)` encode `struct input_absinfo` (24 octets)
// et `info` est un `LinuxInputAbsInfo` #[repr(C)] de même taille passé par pointeur mutable valide.
let ret = unsafe {
ioctl(
file.as_raw_fd(),
@@ -698,6 +760,7 @@ impl OpenEvdevGamepad {
Ok(n) => {
let count = n / EV_SIZE;
for i in 0..count {
// SAFETY: `i < n / EV_SIZE` garantit que `i * EV_SIZE + EV_SIZE <= n <= buf.len()`.
let ev = unsafe {
std::ptr::read_unaligned(
buf.as_ptr().add(i * EV_SIZE) as *const LinuxInputEvent
@@ -1346,6 +1409,7 @@ impl SteamControllerWorker {
active_source: Arc<AtomicU8>,
vibration_pct: Arc<AtomicU8>,
rumble_test_flag: Arc<AtomicBool>,
gear_speed_limits: Arc<Mutex<GearSpeedLimits>>,
control: EngineControlHandle,
g29_state_opt: Option<Arc<Mutex<G29State>>>,
telemetry_state_opt: Option<Arc<Mutex<TelemetryState>>>,
@@ -1384,6 +1448,7 @@ impl SteamControllerWorker {
active_source,
vibration_pct,
rumble_test_flag,
gear_speed_limits,
control,
g29_state_opt,
telemetry_state_opt,
@@ -1411,6 +1476,7 @@ impl SteamControllerWorker {
active_source: Arc<AtomicU8>,
vibration_pct: Arc<AtomicU8>,
rumble_test_flag: Arc<AtomicBool>,
gear_speed_limits: Arc<Mutex<GearSpeedLimits>>,
control: EngineControlHandle,
g29_state_opt: Option<Arc<Mutex<G29State>>>,
telemetry_state_opt: Option<Arc<Mutex<TelemetryState>>>,
@@ -1426,13 +1492,27 @@ impl SteamControllerWorker {
let mut last_haptics_tick = Instant::now() - Duration::from_millis(HAPTICS_INTERVAL_MS);
let mut rumble_is_zero = true;
// Synchronisation initiale de la source souhaitée auprès de la RP2350
// Synchronisation initiale de la source souhaitée et des vitesses auprès de la RP2350
let init_cmd = encode_src_command(last_source);
let _ = socket.send_to(init_cmd.as_bytes(), target);
let mut last_sent_gears = gear_speed_limits.lock().sanitized();
let init_gears_cmd = encode_gears_command(last_sent_gears);
let _ = socket.send_to(init_gears_cmd.as_bytes(), target);
while !stop_flag.load(Ordering::Acquire) {
let loop_start = Instant::now();
let desired_source = ControlSource::from_u8(active_source.load(Ordering::Acquire));
let current_gears = gear_speed_limits.lock().sanitized();
if current_gears != last_sent_gears {
last_sent_gears = current_gears;
let gears_cmd = encode_gears_command(current_gears);
let _ = socket.send_to(gears_cmd.as_bytes(), target);
log::info!(
"[Contrôleur] Vitesses CRSF synchronisées vers {} : {}",
target,
gears_cmd.trim()
);
}
let mut haptics_force_tick = false;
// 1. Changement de source actif (G29 <-> Steam Controller)
@@ -1563,6 +1643,7 @@ impl SteamControllerWorker {
cfg.trigger_deadzone,
st.armed,
st.gear,
current_gears,
);
let gas_released = pre_throt_pct == 0;
@@ -1589,6 +1670,7 @@ impl SteamControllerWorker {
cfg.trigger_deadzone,
st.armed,
st.gear,
current_gears,
);
st.steering_norm = steer_norm;
st.throttle_pct = throt_pct;
@@ -1623,8 +1705,13 @@ impl SteamControllerWorker {
} else {
// Mode veille (G29 actif) : mise à jour lecture seule pour le moniteur des Réglages
// sans armer, sans déclencher les actions cockpit et sans envoyer de trame $RC.
let (throt_pct, _) =
throttle_to_crsf(throttle_norm, cfg.trigger_deadzone, false, 0);
let (throt_pct, _) = throttle_to_crsf(
throttle_norm,
cfg.trigger_deadzone,
false,
0,
current_gears,
);
let mut st = state.lock();
if let Some(&last_key) = pressed_keys.last() {
st.last_button = key_code_label(last_key);
@@ -1874,16 +1961,26 @@ mod tests {
#[test]
fn test_sequential_gearbox_throttle_and_brake() {
let def = GearSpeedLimits::default();
// Désarmé : toujours au neutre
assert_eq!(throttle_to_crsf(1.0, 0.05, false, 2), (100, CRSF_CHANNEL_MID));
assert_eq!(throttle_to_crsf(1.0, 0.05, false, 2, def), (100, CRSF_CHANNEL_MID));
// Point mort N : toujours au neutre
assert_eq!(throttle_to_crsf(1.0, 0.05, true, 0), (100, CRSF_CHANNEL_MID));
assert_eq!(throttle_to_crsf(1.0, 0.05, true, 0, def), (100, CRSF_CHANNEL_MID));
// 1ère vitesse plein gaz -> 1100
assert_eq!(throttle_to_crsf(1.0, 0.05, true, 1), (100, 1100));
assert_eq!(throttle_to_crsf(1.0, 0.05, true, 1, def), (100, 1100));
// 3ème vitesse plein gaz -> 1220
assert_eq!(throttle_to_crsf(1.0, 0.05, true, 3), (100, 1220));
assert_eq!(throttle_to_crsf(1.0, 0.05, true, 3, def), (100, 1220));
// Marche arrière plein gaz -> 800
assert_eq!(throttle_to_crsf(1.0, 0.05, true, -1), (100, 800));
assert_eq!(throttle_to_crsf(1.0, 0.05, true, -1, def), (100, 800));
// Valeurs personnalisées
let custom = GearSpeedLimits {
forward_min: 1080,
forward_max: [1140, 1250, 1400],
reverse_min: 890,
reverse_max: 720,
};
assert_eq!(throttle_to_crsf(1.0, 0.05, true, 2, custom), (100, 1250));
assert_eq!(throttle_to_crsf(1.0, 0.05, true, -1, custom), (100, 720));
// Frein plein -> 1811
assert_eq!(brake_to_crsf(1.0, 0.05), (100, CRSF_CHANNEL_MAX));
assert_eq!(brake_to_crsf(0.02, 0.05), (0, CRSF_CHANNEL_MID));
@@ -1891,14 +1988,25 @@ mod tests {
#[test]
fn test_encode_rc_and_src_frames() {
assert_eq!(encode_src_command(ControlSource::G29), "$SRC,G29\n");
assert_eq!(
encode_src_command(ControlSource::SteamController),
"$SRC,EXT\n"
);
assert_eq!(
let check_crc = |frame: String, expected_body: &str| {
assert!(frame.ends_with('\n'));
let (body, hex_crc) = frame.trim_end_matches('\n').split_once('*').unwrap();
assert_eq!(body, expected_body);
let expected = format!(
"{:02X}",
crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(body.as_bytes())
);
assert_eq!(hex_crc, expected);
};
check_crc(encode_src_command(ControlSource::G29), "$SRC,G29");
check_crc(encode_src_command(ControlSource::SteamController), "$SRC,EXT");
check_crc(
encode_rc_frame(992, 1150, 992, 992, true, 2),
"$RC,992,1150,992,992,1,2\n"
"$RC,992,1150,992,992,1,2",
);
check_crc(
encode_gears_command(GearSpeedLimits::default()),
"$GEARS,1065,1100,1150,1220,905,800",
);
}
+72 -20
View File
@@ -1,6 +1,7 @@
use crate::config::AppConfig;
use crate::controller::{
ControlSource, SteamControllerConfig, SteamControllerState, SteamControllerWorker,
ControlSource, GearSpeedLimits, SteamControllerConfig, SteamControllerState,
SteamControllerWorker,
};
use crate::dome_projection::{DomeWarpLut, ProjectionMode};
use crate::dvr::{DvrContainer, DvrMode, DvrRecorder};
@@ -66,7 +67,7 @@ pub struct RuntimeMonitor {
pub latest_telemetry: TelemetryState,
pub latest_g29: G29State,
pub latest_controller: SteamControllerState,
pub preview_rgba: Vec<u8>,
pub preview_rgba: Arc<Vec<u8>>,
pub preview_width: u32,
pub preview_height: u32,
pub preview_frame_seq: u64,
@@ -98,7 +99,7 @@ impl Default for RuntimeMonitor {
latest_telemetry: TelemetryState::default(),
latest_g29: G29State::default(),
latest_controller: SteamControllerState::default(),
preview_rgba: Vec::new(),
preview_rgba: Arc::new(Vec::new()),
preview_width: 0,
preview_height: 0,
preview_frame_seq: 0,
@@ -120,6 +121,7 @@ pub struct EngineControlHandle {
control_source_flag: Arc<AtomicU8>,
controller_vibration_pct: Arc<AtomicU8>,
controller_rumble_test: Arc<AtomicBool>,
gear_speed_limits: Arc<Mutex<GearSpeedLimits>>,
monitor_ref: Arc<Mutex<RuntimeMonitor>>,
optical_params: Arc<Mutex<LiveOpticalParams>>,
dvr_toggle_cmd: Arc<Mutex<Option<bool>>>,
@@ -216,24 +218,23 @@ impl EngineControlHandle {
if current == target {
return Ok(());
}
{
let mon = self.monitor_ref.lock();
let armed_now = match current {
ControlSource::G29 => mon.latest_g29.is_live() && mon.latest_g29.armed,
ControlSource::SteamController => mon.latest_controller.armed,
};
if armed_now {
let msg = format!(
"Bascule vers {} refusée : désarmez d'abord le véhicule !",
target.label()
);
log::warn!("[Contrôleur] {}", msg);
return Err(msg);
}
// Verrou unique englobant vérification + bascule pour éviter toute race TOCTOU sur l'armement.
let mut mon = self.monitor_ref.lock();
let armed_now = match current {
ControlSource::G29 => mon.latest_g29.is_live() && mon.latest_g29.armed,
ControlSource::SteamController => mon.latest_controller.armed,
};
if armed_now {
let msg = format!(
"Bascule vers {} refusée : désarmez d'abord le véhicule !",
target.label()
);
log::warn!("[Contrôleur] {}", msg);
return Err(msg);
}
self.control_source_flag
.store(target.as_u8(), Ordering::Release);
self.monitor_ref.lock().active_control_source = target;
mon.active_control_source = target;
log::info!(
"[Action Utilisateur] Source de conduite basculée sur : {}",
target.label()
@@ -266,6 +267,24 @@ impl EngineControlHandle {
self.controller_rumble_test.store(true, Ordering::Release);
log::info!("[Action Utilisateur] Test haptique Steam Controller déclenché.");
}
/// Met à jour à chaud les seuils/plafonds CRSF des vitesses (G29 + Steam Controller).
pub fn set_gear_speed_limits(&self, limits: GearSpeedLimits) {
let sanitized = limits.sanitized();
let mut guard = self.gear_speed_limits.lock();
if *guard != sanitized {
*guard = sanitized;
log::info!(
"[Action Utilisateur] Vitesses CRSF réglées : AV_MIN={} | 1ère={} | 2ème={} | 3ème={} | AR_MIN={} | AR_MAX={}",
sanitized.forward_min,
sanitized.forward_max[0],
sanitized.forward_max[1],
sanitized.forward_max[2],
sanitized.reverse_min,
sanitized.reverse_max
);
}
}
}
pub struct FpvEngineController {
@@ -282,6 +301,7 @@ pub struct FpvEngineController {
control_source_flag: Arc<AtomicU8>,
controller_vibration_pct: Arc<AtomicU8>,
controller_rumble_test: Arc<AtomicBool>,
gear_speed_limits: Arc<Mutex<GearSpeedLimits>>,
worker_handle: Option<JoinHandle<()>>,
}
@@ -315,6 +335,7 @@ impl FpvEngineController {
control_source_flag: Arc::new(AtomicU8::new(ControlSource::G29.as_u8())),
controller_vibration_pct: Arc::new(AtomicU8::new(100)),
controller_rumble_test: Arc::new(AtomicBool::new(false)),
gear_speed_limits: Arc::new(Mutex::new(GearSpeedLimits::default())),
worker_handle: None,
}
}
@@ -327,6 +348,7 @@ impl FpvEngineController {
control_source_flag: Arc::clone(&self.control_source_flag),
controller_vibration_pct: Arc::clone(&self.controller_vibration_pct),
controller_rumble_test: Arc::clone(&self.controller_rumble_test),
gear_speed_limits: Arc::clone(&self.gear_speed_limits),
monitor_ref: Arc::clone(&self.monitor),
optical_params: Arc::clone(&self.optical_params),
dvr_toggle_cmd: Arc::clone(&self.dvr_toggle_cmd),
@@ -391,6 +413,13 @@ impl FpvEngineController {
self.controller_vibration_pct
.store(cfg.controller_vibration.min(100), Ordering::Relaxed);
self.controller_rumble_test.store(false, Ordering::Relaxed);
*self.gear_speed_limits.lock() = GearSpeedLimits {
forward_min: cfg.gaz_avant_min,
forward_max: [cfg.gear_1_max, cfg.gear_2_max, cfg.gear_3_max],
reverse_min: cfg.gaz_arriere_min,
reverse_max: cfg.gear_reverse_max,
}
.sanitized();
*self.optical_params.lock() = LiveOpticalParams {
camera_fov_deg: cfg.camera_fov_deg,
@@ -448,6 +477,7 @@ impl FpvEngineController {
let control_source_clone = Arc::clone(&self.control_source_flag);
let controller_vib_clone = Arc::clone(&self.controller_vibration_pct);
let controller_test_clone = Arc::clone(&self.controller_rumble_test);
let gear_limits_clone = Arc::clone(&self.gear_speed_limits);
let handle = thread::Builder::new()
.name("fpv-engine-worker".into())
@@ -469,6 +499,7 @@ impl FpvEngineController {
control_source_clone,
controller_vib_clone,
controller_test_clone,
gear_limits_clone,
);
})
.expect("Impossible de créer le thread fpv-engine-worker");
@@ -520,10 +551,20 @@ fn sync_telemetry_receiver(
if !telem_slot.should_retry() {
return;
}
let mut allowed_peers = Vec::new();
if let Ok(ip) = cfg.radxa_vrx_ip.trim().parse::<std::net::IpAddr>() {
allowed_peers.push(ip);
}
if let Ok(ip) = cfg.nomad_ip.trim().parse::<std::net::IpAddr>() {
if !allowed_peers.contains(&ip) {
allowed_peers.push(ip);
}
}
match TelemetryReceiver::start_with_state(
&cfg.usb_bind_ip,
cfg.telemetry_udp_port,
Arc::clone(shared_telem_state),
allowed_peers,
) {
Ok(rx) => {
monitor.lock().telemetry_status = SubsystemStatus::Running(format!(
@@ -799,6 +840,7 @@ fn run_engine_worker(
control_source_flag: Arc<AtomicU8>,
controller_vibration_pct: Arc<AtomicU8>,
controller_rumble_test: Arc<AtomicBool>,
gear_speed_limits: Arc<Mutex<GearSpeedLimits>>,
) {
let mut active_dvr: Option<Arc<DvrRecorder>> = None;
log::info!(
@@ -852,11 +894,18 @@ fn run_engine_worker(
// 3b. Démarrage optionnel Passerelle Unifiée UDP G29 + Télémétrie CRSF
let g29_rx_opt = if cfg.g29_enabled {
let allowed_g29_peers: Vec<std::net::IpAddr> = cfg
.radxa_vrx_ip
.trim()
.parse::<std::net::IpAddr>()
.into_iter()
.collect();
match G29BridgeReceiver::start(
&cfg.usb_bind_ip,
cfg.g29_udp_port,
control_for_g29,
Some(Arc::clone(&shared_telem_state)),
allowed_g29_peers,
) {
Ok(rx) => {
sync_g29_status(&cfg, Some(&rx), &monitor);
@@ -892,6 +941,7 @@ fn run_engine_worker(
Arc::clone(&control_source_flag),
Arc::clone(&controller_vibration_pct),
Arc::clone(&controller_rumble_test),
Arc::clone(&gear_speed_limits),
control_for_ctrl,
g29_rx_opt.as_ref().map(|rx| rx.state()),
Some(Arc::clone(&shared_telem_state)),
@@ -1395,6 +1445,7 @@ fn try_run_openxr_session(
if standby_tick % 2 == 0 || last_frame_id % 2 == 0 {
sync_video_status(cfg, video_rx_opt, monitor);
let preview_arc = Arc::new(composited_rgba.clone());
let mut mon = monitor.lock();
if fps_timer.elapsed() >= Duration::from_secs(1) {
if has_video_stream {
@@ -1421,7 +1472,7 @@ fn try_run_openxr_session(
mon.latest_telemetry = telem_snapshot;
mon.preview_width = cfg.video_width;
mon.preview_height = cfg.video_height;
mon.preview_rgba.clone_from(&composited_rgba);
mon.preview_rgba = preview_arc;
mon.preview_frame_seq = mon.preview_frame_seq.wrapping_add(1);
}
@@ -1721,6 +1772,7 @@ fn run_desktop_fallback_loop(
}
sync_video_status(cfg, video_rx_opt, monitor);
let preview_arc = Arc::new(composited_rgba.clone());
{
let mut mon = monitor.lock();
if fps_timer.elapsed() >= Duration::from_secs(1) {
@@ -1748,7 +1800,7 @@ fn run_desktop_fallback_loop(
mon.latest_telemetry = telem_snapshot;
mon.preview_width = cfg.video_width;
mon.preview_height = cfg.video_height;
mon.preview_rgba.clone_from(&composited_rgba);
mon.preview_rgba = preview_arc;
mon.preview_frame_seq = mon.preview_frame_seq.wrapping_add(1);
}
+44 -2
View File
@@ -155,11 +155,16 @@ impl G29BridgeReceiver {
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 {}", addr);
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);
@@ -170,8 +175,19 @@ impl G29BridgeReceiver {
.name("g29-udp-rx".into())
.spawn(move || {
let mut buf = [0u8; 512];
let mut last_reject_log = Instant::now() - Duration::from_secs(10);
while !stop_clone.load(Ordering::Acquire) {
if let Ok((len, _src)) = socket.recv_from(&mut buf) {
if let Ok((len, src)) = socket.recv_from(&mut buf) {
if !Self::is_peer_allowed(src.ip(), &allowed_peers) {
if last_reject_log.elapsed() >= Duration::from_secs(5) {
log::warn!(
"[G29 Bridge] Paquet UDP rejeté depuis IP non autorisée : {}",
src
);
last_reject_log = Instant::now();
}
continue;
}
if let Ok(text) = std::str::from_utf8(&buf[..len]) {
for line in text.lines() {
Self::process_line(
@@ -213,6 +229,10 @@ impl G29BridgeReceiver {
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)
}
@@ -553,4 +573,26 @@ mod tests {
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)),
&[]
));
}
}
+99 -1
View File
@@ -1,5 +1,6 @@
use crate::config::AppConfig;
use crate::controller::ControlSource;
use crate::controller::{ControlSource, GearSpeedLimits};
use crate::nomad_elrs::{CRSF_CHANNEL_MAX, CRSF_CHANNEL_MID, CRSF_CHANNEL_MIN};
use crate::dome_projection::ProjectionMode;
use crate::dvr::{DvrContainer, DvrMode};
use crate::engine::{EngineControlHandle, FpvEngineController, LiveOpticalParams, RuntimeMonitor, SubsystemStatus};
@@ -1043,6 +1044,103 @@ impl eframe::App for SteamFrameGuiApp {
ui.end_row();
});
ui.add_space(6.0);
ui.label(
RichText::new("Vitesses CRSF (Volant G29 + Steam Controller)")
.strong(),
);
let mut gears_changed = false;
egui::Grid::new("ctrl_gears_grid")
.num_columns(2)
.spacing([8.0, 6.0])
.show(ui, |ui| {
ui.label("Seuil Gaz Avant (Min) :");
gears_changed |= ui
.add(egui::Slider::new(
&mut self.cfg.gaz_avant_min,
CRSF_CHANNEL_MID..=CRSF_CHANNEL_MAX,
))
.changed();
ui.end_row();
ui.label("1ère Vitesse (Manœuvre) :");
gears_changed |= ui
.add(egui::Slider::new(
&mut self.cfg.gear_1_max,
self.cfg.gaz_avant_min..=CRSF_CHANNEL_MAX,
))
.changed();
ui.end_row();
ui.label("2ème Vitesse (Normale) :");
gears_changed |= ui
.add(egui::Slider::new(
&mut self.cfg.gear_2_max,
self.cfg.gaz_avant_min..=CRSF_CHANNEL_MAX,
))
.changed();
ui.end_row();
ui.label("3ème Vitesse (Rapide) :");
gears_changed |= ui
.add(egui::Slider::new(
&mut self.cfg.gear_3_max,
self.cfg.gaz_avant_min..=CRSF_CHANNEL_MAX,
))
.changed();
ui.end_row();
ui.label("Seuil Gaz Arrière (Min) :");
gears_changed |= ui
.add(egui::Slider::new(
&mut self.cfg.gaz_arriere_min,
CRSF_CHANNEL_MIN..=CRSF_CHANNEL_MID,
))
.changed();
ui.end_row();
ui.label("Plafond Marche Arrière (R) :");
gears_changed |= ui
.add(egui::Slider::new(
&mut self.cfg.gear_reverse_max,
CRSF_CHANNEL_MIN..=self.cfg.gaz_arriere_min,
))
.changed();
ui.end_row();
});
if ui.button("↺ Vitesses par défaut").clicked() {
let def = GearSpeedLimits::default();
self.cfg.gaz_avant_min = def.forward_min;
self.cfg.gear_1_max = def.forward_max[0];
self.cfg.gear_2_max = def.forward_max[1];
self.cfg.gear_3_max = def.forward_max[2];
self.cfg.gaz_arriere_min = def.reverse_min;
self.cfg.gear_reverse_max = def.reverse_max;
gears_changed = true;
}
if gears_changed {
let sanitized = GearSpeedLimits {
forward_min: self.cfg.gaz_avant_min,
forward_max: [
self.cfg.gear_1_max,
self.cfg.gear_2_max,
self.cfg.gear_3_max,
],
reverse_min: self.cfg.gaz_arriere_min,
reverse_max: self.cfg.gear_reverse_max,
}
.sanitized();
self.cfg.gaz_avant_min = sanitized.forward_min;
self.cfg.gear_1_max = sanitized.forward_max[0];
self.cfg.gear_2_max = sanitized.forward_max[1];
self.cfg.gear_3_max = sanitized.forward_max[2];
self.cfg.gaz_arriere_min = sanitized.reverse_min;
self.cfg.gear_reverse_max = sanitized.reverse_max;
self.controls.set_gear_speed_limits(sanitized);
}
ui.add_space(6.0);
egui::Frame::group(ui.style())
.fill(Color32::from_rgb(16, 20, 28))
+242 -10
View File
@@ -1,5 +1,5 @@
use crate::config::AppConfig;
use crate::controller::{ControlSource, SteamControllerState};
use crate::controller::{ControlSource, GearSpeedLimits, SteamControllerState};
use crate::dome_projection::ProjectionMode;
use crate::dvr::{DvrContainer, DvrMode};
use crate::engine::{
@@ -230,9 +230,10 @@ impl SteamFrameGpuiApp {
}
self.latest_pose = mon.latest_head_pose;
self.latest_telem = mon.latest_telemetry.clone();
if self.latest_g29.packets_received != mon.latest_g29.packets_received
|| self.latest_g29.connected != mon.latest_g29.connected
if self.latest_g29.connected != mon.latest_g29.connected
|| self.latest_g29.last_button != mon.latest_g29.last_button
|| (self.active_tab == ActiveTab::Settings
&& self.latest_g29.packets_received != mon.latest_g29.packets_received)
{
changed = true;
}
@@ -257,14 +258,14 @@ impl SteamFrameGpuiApp {
}
self.latest_controller = mon.latest_controller.clone();
// Ne cloner et décoder la trame QUE si l'onglet Cockpit est actif !
let frame_data: Option<(u32, u32, Vec<u8>)> = if self.active_tab == ActiveTab::Cockpit
// Ne cloner que le pointeur Arc sous verrou ; la copie/conversion BGRA se fait hors verrou !
let frame_data: Option<(u32, u32, Arc<Vec<u8>>)> = if self.active_tab == ActiveTab::Cockpit
&& mon.preview_frame_seq != self.last_frame_seq
&& !mon.preview_rgba.is_empty()
&& mon.preview_width > 0
&& mon.preview_height > 0
{
Some((mon.preview_width, mon.preview_height, mon.preview_rgba.clone()))
Some((mon.preview_width, mon.preview_height, Arc::clone(&mon.preview_rgba)))
} else {
None
};
@@ -273,7 +274,8 @@ impl SteamFrameGpuiApp {
}; // Verrou `engine_monitor` immédiatement libéré !
// 2. Conversion BGRA et allocation GPU hors du verrou monitor
if let Some((w, h, mut raw_buf)) = new_frame_data {
if let Some((w, h, raw_arc)) = new_frame_data {
let mut raw_buf = (*raw_arc).clone();
for pixel in raw_buf.chunks_exact_mut(4) {
pixel.swap(0, 2);
}
@@ -632,6 +634,8 @@ impl Render for SteamFrameGpuiApp {
.flex()
.flex_col()
.flex_1()
.min_h_0()
.min_w_0()
.overflow_hidden()
.child(match self.active_tab {
ActiveTab::Cockpit => self.render_cockpit_view(cx).into_any_element(),
@@ -651,6 +655,7 @@ impl SteamFrameGpuiApp {
div()
.flex()
.flex_row()
.flex_wrap()
.justify_between()
.items_center()
.bg(rgb(COLOR_SURFACE_CARD))
@@ -664,6 +669,7 @@ impl SteamFrameGpuiApp {
.child(
div()
.flex()
.flex_wrap()
.items_center()
.gap_2p5()
.child(
@@ -681,6 +687,7 @@ impl SteamFrameGpuiApp {
.child(
div()
.flex()
.flex_wrap()
.items_center()
.gap_1()
.bg(rgb(COLOR_SURFACE_ELEVATED))
@@ -705,6 +712,7 @@ impl SteamFrameGpuiApp {
.child(
div()
.flex()
.flex_wrap()
.items_center()
.gap_2()
.child(
@@ -907,6 +915,8 @@ impl SteamFrameGpuiApp {
.flex()
.flex_col()
.size_full()
.min_h_0()
.min_w_0()
.relative()
.bg(rgb(0x030508))
.border_1()
@@ -915,9 +925,20 @@ impl SteamFrameGpuiApp {
.overflow_hidden()
.items_center()
.justify_center()
// 2.1 Flux Vidéo
// 2.1 Flux Vidéo (cadrage proportionnel intégral sans rognage)
.child(if let Some(ref img_src) = self.current_render_image {
div().size_full().child(img(img_src.clone()).size_full())
div()
.flex()
.items_center()
.justify_center()
.size_full()
.min_h_0()
.min_w_0()
.child(
img(img_src.clone())
.size_full()
.object_fit(gpui::ObjectFit::Contain),
)
} else {
div()
.flex()
@@ -940,6 +961,8 @@ impl SteamFrameGpuiApp {
.child(
div()
.flex()
.flex_wrap()
.justify_center()
.gap_2()
.pt_2()
.child(
@@ -1132,6 +1155,8 @@ impl SteamFrameGpuiApp {
.flex()
.flex_col()
.size_full()
.min_h_0()
.min_w_0()
.id("settings_view_scroll")
.overflow_y_scroll()
.bg(rgb(COLOR_SURFACE_CARD))
@@ -1144,8 +1169,10 @@ impl SteamFrameGpuiApp {
.child(
div()
.flex()
.flex_wrap()
.justify_between()
.items_center()
.gap_2()
.border_b_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.pb_3()
@@ -1206,6 +1233,7 @@ impl SteamFrameGpuiApp {
"Mode Acquisition Vidéo",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_mode_rndis",
@@ -1231,6 +1259,7 @@ impl SteamFrameGpuiApp {
"Canal 5.8 GHz (RTL8812EU)",
div()
.flex()
.flex_wrap()
.gap_1p5()
.child(self.render_channel_button(149, 5745, cx))
.child(self.render_channel_button(153, 5765, cx))
@@ -1242,6 +1271,7 @@ impl SteamFrameGpuiApp {
"Codec Décodage",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_codec_h264",
@@ -1266,6 +1296,7 @@ impl SteamFrameGpuiApp {
.child(
div()
.flex()
.flex_wrap()
.gap_2()
.pt_2()
.child(
@@ -1373,6 +1404,7 @@ impl SteamFrameGpuiApp {
"Cible Réseau (clic pour éditer)",
div()
.flex()
.flex_wrap()
.items_center()
.gap_1()
.child(
@@ -1536,6 +1568,7 @@ impl SteamFrameGpuiApp {
.child(
div()
.flex()
.flex_wrap()
.gap_2()
.pt_1()
.child(
@@ -1594,6 +1627,7 @@ impl SteamFrameGpuiApp {
.child(
div()
.flex()
.flex_wrap()
.gap_2()
.pt_1()
.child(
@@ -1715,6 +1749,7 @@ impl SteamFrameGpuiApp {
"Sens Direction Steam Controller",
div()
.flex()
.flex_wrap()
.items_center()
.gap_2()
.child(self.render_selectable_pill(
@@ -1868,6 +1903,91 @@ impl SteamFrameGpuiApp {
.child("📳 Tester Vibrations"),
),
))
.child(self.render_setting_row(
"Réglage des Vitesses CRSF (G29 + Steam Controller)",
div()
.flex()
.flex_col()
.gap_2()
.p_2p5()
.rounded_md()
.bg(rgb(COLOR_BG_DARK))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.child(self.render_gear_stepper_row(
"av_min",
"Seuil Gaz Avant (Min)",
self.cfg.gaz_avant_min,
COLOR_TEXT_MAIN,
|cfg, d| cfg.gaz_avant_min = cfg.gaz_avant_min.saturating_add_signed(d),
cx,
))
.child(self.render_gear_stepper_row(
"g1",
"1ère Vitesse (Manœuvre)",
self.cfg.gear_1_max,
COLOR_CYAN,
|cfg, d| cfg.gear_1_max = cfg.gear_1_max.saturating_add_signed(d),
cx,
))
.child(self.render_gear_stepper_row(
"g2",
"2ème Vitesse (Normale)",
self.cfg.gear_2_max,
COLOR_GREEN,
|cfg, d| cfg.gear_2_max = cfg.gear_2_max.saturating_add_signed(d),
cx,
))
.child(self.render_gear_stepper_row(
"g3",
"3ème Vitesse (Rapide)",
self.cfg.gear_3_max,
COLOR_ORANGE,
|cfg, d| cfg.gear_3_max = cfg.gear_3_max.saturating_add_signed(d),
cx,
))
.child(self.render_gear_stepper_row(
"ar_min",
"Seuil Gaz Arrière (Min)",
self.cfg.gaz_arriere_min,
COLOR_TEXT_MAIN,
|cfg, d| cfg.gaz_arriere_min = cfg.gaz_arriere_min.saturating_add_signed(d),
cx,
))
.child(self.render_gear_stepper_row(
"ar_max",
"Plafond Marche Arrière (R)",
self.cfg.gear_reverse_max,
COLOR_RED,
|cfg, d| cfg.gear_reverse_max = cfg.gear_reverse_max.saturating_add_signed(d),
cx,
))
.child(
div()
.flex()
.justify_end()
.pt_1()
.child(
div()
.id("btn_gears_reset_default")
.px_2p5()
.py_1()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(rgb(COLOR_TEXT_MAIN))
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
this.reset_gear_speed_limits();
cx.notify();
}))
.child("↺ Valeurs par défaut (1065 / 1100-1150-1220 / 905-800)"),
),
),
))
.child(self.render_controller_monitor(cx))
.child(
div()
@@ -1894,6 +2014,7 @@ impl SteamFrameGpuiApp {
"Affichage Casque VR (OpenXR)",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_vr_on",
@@ -1919,6 +2040,7 @@ impl SteamFrameGpuiApp {
"Mode de Projection VR",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_proj_dome",
@@ -2004,6 +2126,7 @@ impl SteamFrameGpuiApp {
"État Télémétrie & OSD",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_telem_on",
@@ -2047,6 +2170,7 @@ impl SteamFrameGpuiApp {
"Format Conteneur",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_dvr_mkv",
@@ -2082,6 +2206,7 @@ impl SteamFrameGpuiApp {
"Mode Enregistrement",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_dvr_copy",
@@ -2167,8 +2292,9 @@ impl SteamFrameGpuiApp {
div()
.flex()
.flex_col()
.min_w(px(380.0))
.min_w(px(300.0))
.flex_1()
.overflow_hidden()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
@@ -2242,6 +2368,7 @@ impl SteamFrameGpuiApp {
div()
.flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_2()
@@ -2266,6 +2393,107 @@ impl SteamFrameGpuiApp {
)
}
fn apply_gear_speed_limits(&mut self) {
let sanitized = GearSpeedLimits {
forward_min: self.cfg.gaz_avant_min,
forward_max: [
self.cfg.gear_1_max,
self.cfg.gear_2_max,
self.cfg.gear_3_max,
],
reverse_min: self.cfg.gaz_arriere_min,
reverse_max: self.cfg.gear_reverse_max,
}
.sanitized();
self.cfg.gaz_avant_min = sanitized.forward_min;
self.cfg.gear_1_max = sanitized.forward_max[0];
self.cfg.gear_2_max = sanitized.forward_max[1];
self.cfg.gear_3_max = sanitized.forward_max[2];
self.cfg.gaz_arriere_min = sanitized.reverse_min;
self.cfg.gear_reverse_max = sanitized.reverse_max;
self.controls.set_gear_speed_limits(sanitized);
}
fn reset_gear_speed_limits(&mut self) {
let def = GearSpeedLimits::default();
self.cfg.gaz_avant_min = def.forward_min;
self.cfg.gear_1_max = def.forward_max[0];
self.cfg.gear_2_max = def.forward_max[1];
self.cfg.gear_3_max = def.forward_max[2];
self.cfg.gaz_arriere_min = def.reverse_min;
self.cfg.gear_reverse_max = def.reverse_max;
self.controls.set_gear_speed_limits(def);
}
fn render_gear_stepper_row(
&self,
id_prefix: &'static str,
label: &'static str,
value: u16,
accent_color: u32,
mutator: fn(&mut AppConfig, i16),
cx: &mut Context<Self>,
) -> impl IntoElement {
let step_btn = |suffix: &'static str, txt: &'static str, delta: i16| {
let btn_id = gpui::SharedString::from(format!("btn_gear_{}_{}", id_prefix, suffix));
div()
.id(btn_id)
.px_2()
.py_0p5()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.cursor_pointer()
.on_click(cx.listener(move |this, _, _, cx| {
mutator(&mut this.cfg, delta);
this.apply_gear_speed_limits();
cx.notify();
}))
.child(txt)
};
div()
.flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_2()
.child(
div()
.text_xs()
.text_color(rgb(COLOR_TEXT_MAIN))
.child(label),
)
.child(
div()
.flex()
.items_center()
.gap_1p5()
.child(step_btn("m10", "−10", -10))
.child(step_btn("m5", "−5", -5))
.child(
div()
.w(px(56.0))
.py_0p5()
.rounded_md()
.bg(rgb(COLOR_SURFACE_CARD))
.border_1()
.border_color(rgb(accent_color))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.text_color(rgb(accent_color))
.flex()
.justify_center()
.child(format!("{}", value)),
)
.child(step_btn("p5", "+5", 5))
.child(step_btn("p10", "+10", 10)),
)
}
fn render_setting_row(&self, label: &str, control: impl IntoElement) -> impl IntoElement {
div()
.flex()
@@ -2373,6 +2601,8 @@ impl SteamFrameGpuiApp {
.flex()
.flex_col()
.size_full()
.min_h_0()
.min_w_0()
.id("telemetry_view_scroll")
.overflow_y_scroll()
.bg(rgb(COLOR_SURFACE_CARD))
@@ -2775,6 +3005,8 @@ impl SteamFrameGpuiApp {
.flex()
.flex_col()
.flex_1()
.min_h_0()
.min_w_0()
.id("logs_scroll_tab")
.overflow_y_scroll()
.px_2()
+12 -5
View File
@@ -272,8 +272,14 @@ impl NomadHeadTracker {
(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 {
format!("$HT,{},{},{}\n", pan, tilt, roll)
Self::append_nmea_crc8(&format!("$HT,{},{},{}", pan, tilt, roll))
}
pub fn encode_mspv2_ptr(pan: u16, tilt: u16, roll: u16) -> [u8; 15] {
@@ -494,9 +500,10 @@ mod tests {
#[test]
fn test_g29_bridge_ht_format() {
assert_eq!(NomadProtocol::from_str("g29"), NomadProtocol::G29Bridge);
assert_eq!(
NomadHeadTracker::encode_g29_ht(992, 1200, 800),
"$HT,992,1200,800\n"
);
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);
}
}
+25 -4
View File
@@ -149,13 +149,19 @@ pub struct TelemetryReceiver {
impl TelemetryReceiver {
#[allow(dead_code)]
pub fn start(bind_ip: &str, port: u16) -> Result<Self> {
Self::start_with_state(bind_ip, port, Arc::new(Mutex::new(TelemetryState::default())))
Self::start_with_state(
bind_ip,
port,
Arc::new(Mutex::new(TelemetryState::default())),
Vec::new(),
)
}
pub fn start_with_state(
bind_ip: &str,
port: u16,
state: Arc<Mutex<TelemetryState>>,
allowed_peers: Vec<std::net::IpAddr>,
) -> Result<Self> {
let addr = format!("{}:{}", bind_ip, port);
let socket = UdpSocket::bind(&addr).map_err(|e| {
@@ -168,8 +174,9 @@ impl TelemetryReceiver {
})?;
socket.set_read_timeout(Some(Duration::from_millis(100)))?;
log::info!(
"[Télémétrie OSD] Récepteur MAVLink / CRSF en écoute sur UDP {}",
addr
"[Télémétrie OSD] Récepteur MAVLink / CRSF en écoute sur UDP {} (pairs autorisés: {:?})",
addr,
allowed_peers
);
let state_clone = Arc::clone(&state);
@@ -180,8 +187,22 @@ impl TelemetryReceiver {
.name("telemetry-udp-rx".into())
.spawn(move || {
let mut buf = [0u8; 1024];
let mut last_reject_log = Instant::now() - Duration::from_secs(10);
while !stop_clone.load(Ordering::Acquire) {
if let Ok((len, _src)) = socket.recv_from(&mut buf) {
if let Ok((len, src)) = socket.recv_from(&mut buf) {
if !src.ip().is_loopback()
&& !allowed_peers.is_empty()
&& !allowed_peers.contains(&src.ip())
{
if last_reject_log.elapsed() >= Duration::from_secs(5) {
log::warn!(
"[Télémétrie OSD] Paquet UDP rejeté depuis IP non autorisée : {}",
src
);
last_reject_log = Instant::now();
}
continue;
}
Self::parse_datagram(&buf[..len], &state_clone);
}
}
+11 -2
View File
@@ -28,6 +28,9 @@ pub struct VulkanXrContext {
pub height: u32,
}
// SAFETY: VulkanXrContext ne partage aucun accès mutable concurrent (pas de `Sync`) ;
// le transfert entre threads est sûr tant que le contexte est utilisé exclusivement
// depuis le thread de rendu OpenXR propriétaire via `&mut self`.
unsafe impl Send for VulkanXrContext {}
impl VulkanXrContext {
@@ -66,7 +69,10 @@ impl VulkanXrContext {
xr_instance
.create_vulkan_instance(
system,
std::mem::transmute(vk_entry.static_fn().get_instance_proc_addr),
// SAFETY: vkGetInstanceProcAddr d'ash a exactement l'ABI C PFN_vkGetInstanceProcAddr attendue par openxr.
std::mem::transmute::<vk::PFN_vkGetInstanceProcAddr, _>(
vk_entry.static_fn().get_instance_proc_addr,
),
&vk_instance_create_info as *const _ as *const _,
)
.context("Échec de xrCreateVulkanInstanceKHR")?
@@ -116,7 +122,10 @@ impl VulkanXrContext {
xr_instance
.create_vulkan_device(
system,
std::mem::transmute(vk_entry.static_fn().get_instance_proc_addr),
// SAFETY: vkGetInstanceProcAddr d'ash a exactement l'ABI C PFN_vkGetInstanceProcAddr attendue par openxr.
std::mem::transmute::<vk::PFN_vkGetInstanceProcAddr, _>(
vk_entry.static_fn().get_instance_proc_addr,
),
phys_device.as_raw() as _,
&device_create_info as *const _ as *const _,
)