Premier commit
Cette révision appartient à :
révision
aee5ad5442
118 fichiers modifiés
+16226
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,7 @@
|
||||
[target.thumbv7em-none-eabihf]
|
||||
rustflags = [
|
||||
"-C", "link-arg=-Tlink.x",
|
||||
]
|
||||
|
||||
[build]
|
||||
target = "thumbv7em-none-eabihf"
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bare-metal"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3"
|
||||
dependencies = [
|
||||
"rustc_version",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitfield"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719"
|
||||
|
||||
[[package]]
|
||||
name = "cortex-m"
|
||||
version = "0.7.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "844b9697e922c99847eed515c6eb6d101e7ce62ff556fcaec243798291427ee8"
|
||||
dependencies = [
|
||||
"bare-metal",
|
||||
"bitfield",
|
||||
"cortex-m-macros",
|
||||
"critical-section",
|
||||
"embedded-hal 0.2.7",
|
||||
"embedded-hal 1.0.0",
|
||||
"volatile-register",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cortex-m-macros"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6d1922be58519ad40368fc4ca595a2cefa51a7abf947be3b0c90586dc7dbd0e2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cortex-m-rt"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c439b23bf18154d8a634543caf1ee73cceb723f2902f7ea243634159a00fd47"
|
||||
dependencies = [
|
||||
"cortex-m-rt-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cortex-m-rt-macros"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "061a75f3e7f3f01d649668d68e02d0ef92c7041a9c97b8fe6bc354ddbf40822d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "critical-section"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"
|
||||
|
||||
[[package]]
|
||||
name = "embedded-hal"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35949884794ad573cf46071e41c9b60efb0cb311e3ca01f7af807af1debc66ff"
|
||||
dependencies = [
|
||||
"nb 0.1.3",
|
||||
"void",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "embedded-hal"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "361a90feb7004eca4019fb28352a9465666b24f840f5c3cddf0ff13920590b89"
|
||||
|
||||
[[package]]
|
||||
name = "nb"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "801d31da0513b6ec5214e9bf433a77966320625a37860f910be265be6e18d06f"
|
||||
dependencies = [
|
||||
"nb 1.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nb"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d5439c4ad607c3c23abf66de8c8bf57ba8adcd1f129e699851a6e43935d339d"
|
||||
|
||||
[[package]]
|
||||
name = "os_relais"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"cortex-m",
|
||||
"cortex-m-rt",
|
||||
"panic-halt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "panic-halt"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "de96540e0ebde571dc55c73d60ef407c653844e6f9a1e2fdbd40c07b9252d812"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"
|
||||
dependencies = [
|
||||
"semver-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver-parser"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vcell"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77439c1b53d2303b20d9459b1ade71a83c716e3f9c34f3228c00e6f185d6c002"
|
||||
|
||||
[[package]]
|
||||
name = "void"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
|
||||
|
||||
[[package]]
|
||||
name = "volatile-register"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "de437e2a6208b014ab52972a27e59b33fa2920d3e00fe05026167a1c509d19cc"
|
||||
dependencies = [
|
||||
"vcell",
|
||||
]
|
||||
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
name = "os_relais"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
authors = ["Gastinel.Weather.169 Team"]
|
||||
description = "Bare-metal no_std firmware for STM32L476RGT6 weather relay node"
|
||||
|
||||
[lib]
|
||||
name = "os_relais"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "os_relais"
|
||||
path = "src/main.rs"
|
||||
test = false
|
||||
bench = false
|
||||
|
||||
[dependencies]
|
||||
cortex-m = { version = "0.7.7", features = ["critical-section-single-core"] }
|
||||
cortex-m-rt = "0.7.3"
|
||||
panic-halt = "0.2.0"
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
lto = false
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
@@ -0,0 +1,21 @@
|
||||
use std::env;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
// Put `memory.x` in our output directory and ensure it's
|
||||
// on the linker search path.
|
||||
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
|
||||
File::create(out.join("memory.x"))
|
||||
.unwrap()
|
||||
.write_all(include_bytes!("memory.x"))
|
||||
.unwrap();
|
||||
println!("cargo:rustc-link-search={}", out.display());
|
||||
|
||||
// By default, Cargo will re-run a build script whenever
|
||||
// any file in the project changes. By specifying `memory.x`
|
||||
// here, we ensure the build script is only re-run when
|
||||
// `memory.x` is changed.
|
||||
println!("cargo:rerun-if-changed=memory.x");
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/* Linker script STM32L476RGT6 optimisé pour la rétention Stop 2 */
|
||||
MEMORY
|
||||
{
|
||||
/* Mémoire Flash programme (1020 Ko) */
|
||||
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1020K
|
||||
|
||||
/* Pages Flash réservées pour la persistance Ping-Pong A/B (2 x 2 Ko) */
|
||||
FLASH_STORAGE_A (r) : ORIGIN = 0x080FE000, LENGTH = 2K
|
||||
FLASH_STORAGE_B (r) : ORIGIN = 0x080FF000, LENGTH = 2K
|
||||
|
||||
/* SRAM2 (32 Ko) : Conservée sous tension en mode Stop 2 (PWR_CR1.RRS = 1) */
|
||||
/* Héberge la pile MSP, les segments .data et .bss ainsi que l'EventQueue */
|
||||
RAM (rwx) : ORIGIN = 0x10000000, LENGTH = 32K
|
||||
|
||||
/* SRAM1 (96 Ko) : Non conservée en Stop 2 - réservée pour buffers volatils */
|
||||
SRAM1 (rwx) : ORIGIN = 0x20000000, LENGTH = 96K
|
||||
}
|
||||
|
||||
/* Positionnement de la pile au sommet de la SRAM2 */
|
||||
_stack_start = ORIGIN(RAM) + LENGTH(RAM);
|
||||
@@ -0,0 +1,145 @@
|
||||
//! Agrégation glissante des mesures météorologiques (min, max, moyennes, augets pluie)
|
||||
|
||||
use crate::protocol::davis::{DavisMeasurement, DavisPayload};
|
||||
|
||||
/// Agrégateur de mesures météorologiques en mémoire vive (SRAM2)
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub struct WeatherAggregator {
|
||||
wind_speed_sum: u32,
|
||||
wind_samples_count: u16,
|
||||
max_gust_mph: u8,
|
||||
last_wind_dir_deg: u16,
|
||||
last_temp_centi_c: i16,
|
||||
last_humidity_pct: u8,
|
||||
total_rain_tips: u16,
|
||||
has_valid_temp: bool,
|
||||
has_valid_hum: bool,
|
||||
}
|
||||
|
||||
impl WeatherAggregator {
|
||||
/// Crée un agrégateur réinitialisé
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
wind_speed_sum: 0,
|
||||
wind_samples_count: 0,
|
||||
max_gust_mph: 0,
|
||||
last_wind_dir_deg: 0,
|
||||
last_temp_centi_c: 0,
|
||||
last_humidity_pct: 0,
|
||||
total_rain_tips: 0,
|
||||
has_valid_temp: false,
|
||||
has_valid_hum: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Intègre une nouvelle mesure reçue de l'ISS Davis
|
||||
pub fn update(&mut self, m: &DavisMeasurement) {
|
||||
// Mise à jour continue du vent instantané
|
||||
self.wind_speed_sum = self.wind_speed_sum.saturating_add(m.wind_speed_mph as u32);
|
||||
self.wind_samples_count = self.wind_samples_count.saturating_add(1);
|
||||
self.last_wind_dir_deg = m.wind_direction_deg;
|
||||
|
||||
if m.wind_speed_mph > self.max_gust_mph {
|
||||
self.max_gust_mph = m.wind_speed_mph;
|
||||
}
|
||||
|
||||
match m.payload {
|
||||
DavisPayload::WindGust { gust_speed_mph } => {
|
||||
if gust_speed_mph > self.max_gust_mph {
|
||||
self.max_gust_mph = gust_speed_mph;
|
||||
}
|
||||
}
|
||||
DavisPayload::Temperature { temp_centi_celsius } => {
|
||||
self.last_temp_centi_c = temp_centi_celsius;
|
||||
self.has_valid_temp = true;
|
||||
}
|
||||
DavisPayload::Humidity { relative_humidity_pct } => {
|
||||
self.last_humidity_pct = relative_humidity_pct;
|
||||
self.has_valid_hum = true;
|
||||
}
|
||||
DavisPayload::Rain { tip_count } => {
|
||||
self.total_rain_tips = tip_count;
|
||||
}
|
||||
DavisPayload::SolarRadiation { .. } => {}
|
||||
DavisPayload::UvIndex { .. } => {}
|
||||
DavisPayload::Unknown { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calcule la vitesse moyenne du vent sur l'intervalle en dixièmes de km/h (1 mph ≈ 1.60934 km/h)
|
||||
pub fn average_wind_deci_kmh(&self) -> u16 {
|
||||
if self.wind_samples_count == 0 {
|
||||
return 0;
|
||||
}
|
||||
let avg_mph = (self.wind_speed_sum as f32) / (self.wind_samples_count as f32);
|
||||
(avg_mph * 16.0934) as u16
|
||||
}
|
||||
|
||||
/// Calcule la rafale maximale du vent en dixièmes de km/h
|
||||
pub fn max_gust_deci_kmh(&self) -> u16 {
|
||||
((self.max_gust_mph as f32) * 16.0934) as u16
|
||||
}
|
||||
|
||||
pub fn last_wind_dir_deg(&self) -> u16 {
|
||||
self.last_wind_dir_deg
|
||||
}
|
||||
|
||||
pub fn last_temp_centi_c(&self) -> i16 {
|
||||
self.last_temp_centi_c
|
||||
}
|
||||
|
||||
pub fn last_humidity_pct(&self) -> u8 {
|
||||
self.last_humidity_pct
|
||||
}
|
||||
|
||||
pub fn total_rain_tips(&self) -> u16 {
|
||||
self.total_rain_tips
|
||||
}
|
||||
|
||||
/// Réinitialise les accumulateurs glissants après une transmission 169 MHz réussie
|
||||
pub fn reset_window(&mut self) {
|
||||
self.wind_speed_sum = 0;
|
||||
self.wind_samples_count = 0;
|
||||
self.max_gust_mph = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_aggregator_wind_averaging_and_reset() {
|
||||
let mut agg = WeatherAggregator::new();
|
||||
assert_eq!(agg.average_wind_deci_kmh(), 0);
|
||||
|
||||
let m1 = DavisMeasurement {
|
||||
station_id: 0,
|
||||
battery_low: false,
|
||||
wind_speed_mph: 10,
|
||||
wind_direction_deg: 90,
|
||||
payload: DavisPayload::WindGust { gust_speed_mph: 15 },
|
||||
};
|
||||
let m2 = DavisMeasurement {
|
||||
station_id: 0,
|
||||
battery_low: false,
|
||||
wind_speed_mph: 20,
|
||||
wind_direction_deg: 180,
|
||||
payload: DavisPayload::WindGust { gust_speed_mph: 25 },
|
||||
};
|
||||
|
||||
agg.update(&m1);
|
||||
agg.update(&m2);
|
||||
|
||||
// Moyenne = 15 mph ≈ 241 deci-km/h (24.1 km/h)
|
||||
assert_eq!(agg.average_wind_deci_kmh(), 241);
|
||||
// Rafale max = 25 mph ≈ 402 deci-km/h (40.2 km/h)
|
||||
assert_eq!(agg.max_gust_deci_kmh(), 402);
|
||||
assert_eq!(agg.last_wind_dir_deg(), 180);
|
||||
|
||||
agg.reset_window();
|
||||
assert_eq!(agg.average_wind_deci_kmh(), 0);
|
||||
assert_eq!(agg.max_gust_deci_kmh(), 0);
|
||||
assert_eq!(agg.last_wind_dir_deg(), 180); // Conservé
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//! Couche applicative haute (Machine d'États FSM, Agrégation météo)
|
||||
|
||||
pub mod aggregator;
|
||||
pub mod state_machine;
|
||||
|
||||
pub use aggregator::WeatherAggregator;
|
||||
pub use state_machine::{RelayAction, RelayState, RelayStateMachine};
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Machine d'États Principale du Relais (FSM Applicative)
|
||||
//!
|
||||
//! Orchestre les cycles d'écoute Davis 868 MHz, de transmission 169 MHz,
|
||||
//! d'écoute descendante et de veille profonde Stop 2 sans dépendance matérielle.
|
||||
|
||||
use crate::events::SystemEvent;
|
||||
|
||||
/// États opérationnels de la machine d'états principale
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum RelayState {
|
||||
Boot,
|
||||
Init,
|
||||
DavisScan,
|
||||
SystemIdleSleep,
|
||||
DavisSync,
|
||||
DavisProcess,
|
||||
Transmission169,
|
||||
DownlinkListen,
|
||||
CommandProcessing,
|
||||
ErrorSafeMode,
|
||||
}
|
||||
|
||||
/// Actions ordonnées par la FSM en réaction aux événements
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum RelayAction {
|
||||
StartHardwareInit,
|
||||
StartDavisScan,
|
||||
EnterStop2Sleep,
|
||||
PrepareDavisSyncWindow,
|
||||
DecodeAndAggregateDavis,
|
||||
StartRadio169Transmission,
|
||||
OpenDownlinkListenWindow,
|
||||
ProcessIncomingCommand,
|
||||
ApplySafeModeFallback,
|
||||
None,
|
||||
}
|
||||
|
||||
/// Machine d'états principale du relais
|
||||
pub struct RelayStateMachine {
|
||||
current_state: RelayState,
|
||||
missed_davis_packets: u8,
|
||||
consecutive_transmissions: u32,
|
||||
}
|
||||
|
||||
impl RelayStateMachine {
|
||||
/// Initialise la machine d'états dans l'état initial BOOT
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
current_state: RelayState::Boot,
|
||||
missed_davis_packets: 0,
|
||||
consecutive_transmissions: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// État courant de la FSM
|
||||
#[inline(always)]
|
||||
pub fn current_state(&self) -> RelayState {
|
||||
self.current_state
|
||||
}
|
||||
|
||||
/// Nombre de paquets Davis consécutifs manqués
|
||||
#[inline(always)]
|
||||
pub fn missed_davis_packets(&self) -> u8 {
|
||||
self.missed_davis_packets
|
||||
}
|
||||
|
||||
/// Force l'état de la machine (utilisé lors du démarrage / tests)
|
||||
pub fn set_state(&mut self, state: RelayState) {
|
||||
self.current_state = state;
|
||||
}
|
||||
|
||||
/// Traite un événement entrant et opère la transition d'état
|
||||
pub fn process_event(&mut self, event: SystemEvent) -> (RelayState, RelayAction) {
|
||||
let (next_state, action) = match (self.current_state, event) {
|
||||
(RelayState::Boot, _) => (RelayState::Init, RelayAction::StartHardwareInit),
|
||||
|
||||
(RelayState::Init, _) => (RelayState::DavisScan, RelayAction::StartDavisScan),
|
||||
|
||||
(RelayState::DavisScan, SystemEvent::DavisPacketReady) => {
|
||||
self.missed_davis_packets = 0;
|
||||
(RelayState::SystemIdleSleep, RelayAction::EnterStop2Sleep)
|
||||
}
|
||||
(RelayState::DavisScan, SystemEvent::DavisListenTimeout) => {
|
||||
(RelayState::ErrorSafeMode, RelayAction::ApplySafeModeFallback)
|
||||
}
|
||||
|
||||
(RelayState::SystemIdleSleep, SystemEvent::RtcDavisTick) => {
|
||||
(RelayState::DavisSync, RelayAction::PrepareDavisSyncWindow)
|
||||
}
|
||||
(RelayState::SystemIdleSleep, SystemEvent::RtcTransmitTick) => {
|
||||
(
|
||||
RelayState::Transmission169,
|
||||
RelayAction::StartRadio169Transmission,
|
||||
)
|
||||
}
|
||||
|
||||
(RelayState::DavisSync, SystemEvent::DavisPacketReady) => {
|
||||
self.missed_davis_packets = 0;
|
||||
(RelayState::DavisProcess, RelayAction::DecodeAndAggregateDavis)
|
||||
}
|
||||
(RelayState::DavisSync, SystemEvent::DavisListenTimeout) => {
|
||||
self.missed_davis_packets = self.missed_davis_packets.saturating_add(1);
|
||||
(RelayState::DavisProcess, RelayAction::DecodeAndAggregateDavis)
|
||||
}
|
||||
|
||||
(RelayState::DavisProcess, _) => {
|
||||
if self.missed_davis_packets > 10 {
|
||||
// Perte prolongée de synchronisation -> retour en scan à froid
|
||||
(RelayState::DavisScan, RelayAction::StartDavisScan)
|
||||
} else {
|
||||
(RelayState::SystemIdleSleep, RelayAction::EnterStop2Sleep)
|
||||
}
|
||||
}
|
||||
|
||||
(RelayState::Transmission169, SystemEvent::Radio169AuxReady) => {
|
||||
self.consecutive_transmissions = self.consecutive_transmissions.saturating_add(1);
|
||||
(
|
||||
RelayState::DownlinkListen,
|
||||
RelayAction::OpenDownlinkListenWindow,
|
||||
)
|
||||
}
|
||||
|
||||
(RelayState::DownlinkListen, SystemEvent::Radio169RxByte(_)) => (
|
||||
RelayState::CommandProcessing,
|
||||
RelayAction::ProcessIncomingCommand,
|
||||
),
|
||||
(RelayState::DownlinkListen, SystemEvent::Radio169ListenEnd) => {
|
||||
(RelayState::SystemIdleSleep, RelayAction::EnterStop2Sleep)
|
||||
}
|
||||
|
||||
(RelayState::CommandProcessing, _) => {
|
||||
(RelayState::SystemIdleSleep, RelayAction::EnterStop2Sleep)
|
||||
}
|
||||
|
||||
(RelayState::ErrorSafeMode, _) => {
|
||||
(RelayState::SystemIdleSleep, RelayAction::EnterStop2Sleep)
|
||||
}
|
||||
|
||||
// Événements hors contexte -> maintien de l'état
|
||||
(state, _) => (state, RelayAction::None),
|
||||
};
|
||||
|
||||
self.current_state = next_state;
|
||||
(next_state, action)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_fsm_nominal_davis_cycle() {
|
||||
let mut fsm = RelayStateMachine::new();
|
||||
assert_eq!(fsm.current_state(), RelayState::Boot);
|
||||
|
||||
// Boot -> Init
|
||||
let (s, a) = fsm.process_event(SystemEvent::WatchdogKick);
|
||||
assert_eq!(s, RelayState::Init);
|
||||
assert_eq!(a, RelayAction::StartHardwareInit);
|
||||
|
||||
// Init -> DavisScan
|
||||
let (s, a) = fsm.process_event(SystemEvent::WatchdogKick);
|
||||
assert_eq!(s, RelayState::DavisScan);
|
||||
assert_eq!(a, RelayAction::StartDavisScan);
|
||||
|
||||
// Capture du 1er paquet en scan -> Sleep
|
||||
let (s, a) = fsm.process_event(SystemEvent::DavisPacketReady);
|
||||
assert_eq!(s, RelayState::SystemIdleSleep);
|
||||
assert_eq!(a, RelayAction::EnterStop2Sleep);
|
||||
|
||||
// Réveil RTC Davis -> DavisSync
|
||||
let (s, a) = fsm.process_event(SystemEvent::RtcDavisTick);
|
||||
assert_eq!(s, RelayState::DavisSync);
|
||||
assert_eq!(a, RelayAction::PrepareDavisSyncWindow);
|
||||
|
||||
// Paquet reçu en sync -> DavisProcess
|
||||
let (s, a) = fsm.process_event(SystemEvent::DavisPacketReady);
|
||||
assert_eq!(s, RelayState::DavisProcess);
|
||||
assert_eq!(a, RelayAction::DecodeAndAggregateDavis);
|
||||
|
||||
// Fin de traitement -> Retour Sleep
|
||||
let (s, a) = fsm.process_event(SystemEvent::WatchdogKick);
|
||||
assert_eq!(s, RelayState::SystemIdleSleep);
|
||||
assert_eq!(a, RelayAction::EnterStop2Sleep);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fsm_transmission_169_and_downlink() {
|
||||
let mut fsm = RelayStateMachine::new();
|
||||
fsm.set_state(RelayState::SystemIdleSleep);
|
||||
|
||||
// Réveil RTC Schedule -> Transmission 169
|
||||
let (s, a) = fsm.process_event(SystemEvent::RtcTransmitTick);
|
||||
assert_eq!(s, RelayState::Transmission169);
|
||||
assert_eq!(a, RelayAction::StartRadio169Transmission);
|
||||
|
||||
// AUX Ready -> Écoute descendante
|
||||
let (s, a) = fsm.process_event(SystemEvent::Radio169AuxReady);
|
||||
assert_eq!(s, RelayState::DownlinkListen);
|
||||
assert_eq!(a, RelayAction::OpenDownlinkListenWindow);
|
||||
|
||||
// Fin de fenêtre sans ordre -> Sommeil
|
||||
let (s, a) = fsm.process_event(SystemEvent::Radio169ListenEnd);
|
||||
assert_eq!(s, RelayState::SystemIdleSleep);
|
||||
assert_eq!(a, RelayAction::EnterStop2Sleep);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Primitives de contrôle et barrières CPU Cortex-M4F
|
||||
|
||||
/// Exécute une barrière de synchronisation des données (Data Synchronization Barrier).
|
||||
#[inline(always)]
|
||||
pub fn dsb() {
|
||||
#[cfg(target_arch = "arm")]
|
||||
cortex_m::asm::dsb();
|
||||
}
|
||||
|
||||
/// Exécute une barrière de synchronisation des instructions (Instruction Synchronization Barrier).
|
||||
#[inline(always)]
|
||||
pub fn isb() {
|
||||
#[cfg(target_arch = "arm")]
|
||||
cortex_m::asm::isb();
|
||||
}
|
||||
|
||||
/// Place le cœur en attente d'interruption (Wait For Interrupt).
|
||||
#[inline(always)]
|
||||
pub fn wfi() {
|
||||
#[cfg(target_arch = "arm")]
|
||||
cortex_m::asm::wfi();
|
||||
}
|
||||
|
||||
/// Place le cœur en attente d'événement (Wait For Event).
|
||||
#[inline(always)]
|
||||
pub fn wfe() {
|
||||
#[cfg(target_arch = "arm")]
|
||||
cortex_m::asm::wfe();
|
||||
}
|
||||
|
||||
/// Exécute un bloc de code en section critique (interruptions masquées).
|
||||
#[inline(always)]
|
||||
pub fn critical_section<F, R>(f: F) -> R
|
||||
where
|
||||
F: FnOnce(&cortex_m::interrupt::CriticalSection) -> R,
|
||||
{
|
||||
#[cfg(target_arch = "arm")]
|
||||
{
|
||||
cortex_m::interrupt::free(f)
|
||||
}
|
||||
#[cfg(not(target_arch = "arm"))]
|
||||
{
|
||||
// Dummy critical section token for host tests
|
||||
struct DummyCs;
|
||||
let cs = unsafe { core::mem::transmute::<&DummyCs, &cortex_m::interrupt::CriticalSection>(&DummyCs) };
|
||||
f(cs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Abstractions d'architecture CPU Cortex-M4F
|
||||
|
||||
pub mod barrier;
|
||||
|
||||
pub use barrier::{critical_section, dsb, isb, wfe, wfi};
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Module d'initialisation matérielle précoce au démarrage (Boot)
|
||||
//!
|
||||
//! Ce module configure les registres bas niveau du Cortex-M4F et du STM32L4
|
||||
//! immédiatement après la sortie du `Reset_Handler` de `cortex-m-rt`.
|
||||
|
||||
/// Cause identifiée du dernier reset matériel
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum ResetReason {
|
||||
PowerOnReset = 0x01,
|
||||
BrownOutReset = 0x02,
|
||||
PinReset = 0x03,
|
||||
IndependentWatchdog = 0x04,
|
||||
WindowWatchdog = 0x05,
|
||||
SoftwareReset = 0x06,
|
||||
LowPowerReset = 0x07,
|
||||
Unknown = 0x00,
|
||||
}
|
||||
|
||||
/// Initialisation du coprocesseur FPU et de l'empilement paresseux (Lazy Stacking).
|
||||
///
|
||||
/// Active CP10 et CP11 dans le registre CPACR (Cortex-M4F) et s'assure que
|
||||
/// `FPCCR.LSPEN` est armé afin de ne pas pénaliser la latence des ISRs courtes.
|
||||
pub fn init_fpu() {
|
||||
#[cfg(target_arch = "arm")]
|
||||
unsafe {
|
||||
// CPACR est à l'adresse 0xE000ED88
|
||||
const CPACR: *mut u32 = 0xE000_ED88 as *mut u32;
|
||||
// Bits 20..23 = 0b1111 (Full Access CP10 & CP11)
|
||||
let val = core::ptr::read_volatile(CPACR);
|
||||
core::ptr::write_volatile(CPACR, val | (0xF << 20));
|
||||
|
||||
// FPCCR est à l'adresse 0xE000EF34
|
||||
const FPCCR: *mut u32 = 0xE000_EF34 as *mut u32;
|
||||
// Bit 30 = LSPEN (Lazy Stacking Enable)
|
||||
let fpccr_val = core::ptr::read_volatile(FPCCR);
|
||||
core::ptr::write_volatile(FPCCR, fpccr_val | (1 << 30));
|
||||
|
||||
cortex_m::asm::dsb();
|
||||
cortex_m::asm::isb();
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyse et acquitte les drapeaux de reset dans RCC_CSR.
|
||||
pub fn capture_and_clear_reset_reason() -> ResetReason {
|
||||
#[cfg(target_arch = "arm")]
|
||||
unsafe {
|
||||
// RCC_CSR sur STM32L476 est à 0x40021094
|
||||
const RCC_CSR: *mut u32 = 0x4002_1094 as *mut u32;
|
||||
let csr = core::ptr::read_volatile(RCC_CSR);
|
||||
|
||||
let reason = if csr & (1 << 31) != 0 {
|
||||
ResetReason::LowPowerReset
|
||||
} else if csr & (1 << 29) != 0 {
|
||||
ResetReason::IndependentWatchdog
|
||||
} else if csr & (1 << 30) != 0 {
|
||||
ResetReason::WindowWatchdog
|
||||
} else if csr & (1 << 28) != 0 {
|
||||
ResetReason::SoftwareReset
|
||||
} else if csr & (1 << 27) != 0 {
|
||||
ResetReason::BrownOutReset
|
||||
} else if csr & (1 << 26) != 0 {
|
||||
ResetReason::PinReset
|
||||
} else {
|
||||
ResetReason::PowerOnReset
|
||||
};
|
||||
|
||||
// RMVF (bit 23) : efface les drapeaux de reset
|
||||
core::ptr::write_volatile(RCC_CSR, csr | (1 << 23));
|
||||
|
||||
reason
|
||||
}
|
||||
#[cfg(not(target_arch = "arm"))]
|
||||
{
|
||||
ResetReason::PowerOnReset
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Driver pour transceiver CC1101 (868 MHz - Interception Davis)
|
||||
|
||||
use crate::hal::spi::SpiError;
|
||||
|
||||
/// Erreurs possibles du driver CC1101
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Cc1101Error {
|
||||
Spi(SpiError),
|
||||
ChipNotResponding,
|
||||
InvalidChannel(u8),
|
||||
FifoOverflow,
|
||||
CrcError,
|
||||
}
|
||||
|
||||
impl From<SpiError> for Cc1101Error {
|
||||
fn from(err: SpiError) -> Self {
|
||||
Cc1101Error::Spi(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Contrat d'interface du récepteur radio 868 MHz Davis
|
||||
pub trait Radio868Receiver {
|
||||
type Error;
|
||||
|
||||
/// Initialise les registres RF du CC1101 pour la démodulation FSK 19.2 kbps
|
||||
fn init(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
/// Sélectionne le canal FHSS Davis (0..4 pour l'Europe : 868.0 à 868.5 MHz)
|
||||
fn set_channel(&mut self, channel: u8) -> Result<(), Self::Error>;
|
||||
|
||||
/// Passe le CC1101 en mode écoute active (RX)
|
||||
fn start_listening(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
/// Récupère un paquet brut de 14 octets depuis la FIFO
|
||||
fn read_packet(&mut self, buf: &mut [u8; 16]) -> Result<Option<u8>, Self::Error>;
|
||||
|
||||
/// Place le CC1101 en mode veille profonde (Power Down / Sleep)
|
||||
fn sleep(&mut self) -> Result<(), Self::Error>;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Driver pour module EBYTE E32-170T30D-V2.0 (Liaison VHF 169 MHz)
|
||||
|
||||
use crate::hal::uart::UartError;
|
||||
|
||||
/// Modes de fonctionnement du modem E32
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum E32Mode {
|
||||
/// Mode 0 : Transmission et réception transparentes (M0=0, M1=0)
|
||||
Mode0Normal,
|
||||
/// Mode 1 : Wake-up émetteur (M0=1, M1=0)
|
||||
Mode1WakeUp,
|
||||
/// Mode 2 : Économie d'énergie récepteur (M0=0, M1=1)
|
||||
Mode2PowerSaving,
|
||||
/// Mode 3 : Veille / Mode configuration (M0=1, M1=1)
|
||||
Mode3Sleep,
|
||||
}
|
||||
|
||||
/// Erreurs possibles du driver E32-170T30D
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum E32Error {
|
||||
Uart(UartError),
|
||||
TimeoutAux,
|
||||
ModuleBusy,
|
||||
InvalidParameter,
|
||||
}
|
||||
|
||||
impl From<UartError> for E32Error {
|
||||
fn from(err: UartError) -> Self {
|
||||
E32Error::Uart(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Contrat d'interface du transceiver 169 MHz EBYTE
|
||||
pub trait Radio169Transceiver {
|
||||
type Error;
|
||||
|
||||
/// Initialise le module, configure le débit et vérifie le signal AUX
|
||||
fn init(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
/// Émet une trame montante sérialisée sur 169 MHz (+27 dBm ERP max)
|
||||
fn send_payload(&mut self, payload: &[u8]) -> Result<(), Self::Error>;
|
||||
|
||||
/// Bascule en mode écoute descendante après émission (Mode 0)
|
||||
fn start_downlink_window(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
/// Scrute la réception de commandes descendantes pendant la fenêtre d'écoute
|
||||
fn poll_downlink(&mut self, buf: &mut [u8]) -> Result<Option<usize>, Self::Error>;
|
||||
|
||||
/// Bascule le module en veille ultra-basse consommation (Mode 3 Sleep)
|
||||
fn sleep(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
/// Indique si la broche d'état AUX est à l'état haut (Module prêt / Idle)
|
||||
fn is_aux_ready(&self) -> bool;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Drivers pour composants et modules externes
|
||||
|
||||
pub mod cc1101;
|
||||
pub mod e32_170t30d;
|
||||
pub mod pwr_switch;
|
||||
|
||||
pub use cc1101::{Cc1101Error, Radio868Receiver};
|
||||
pub use e32_170t30d::{E32Error, E32Mode, Radio169Transceiver};
|
||||
pub use pwr_switch::{PowerSwitchController, PowerSwitchError};
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Driver pour interrupteurs d'alimentation commandables (Load Switches)
|
||||
|
||||
/// Erreurs possibles du driver d'alimentation des périphériques
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum PowerSwitchError {
|
||||
PinError,
|
||||
ThermalFault,
|
||||
}
|
||||
|
||||
/// Contrat de coupure matérielle de puissance pour éliminer les courants de fuite
|
||||
pub trait PowerSwitchController {
|
||||
type Error;
|
||||
|
||||
/// Active ou coupe la ligne d'alimentation du récepteur CC1101 (868 MHz)
|
||||
fn set_cc1101_power(&mut self, on: bool) -> Result<(), Self::Error>;
|
||||
|
||||
/// Active ou coupe la ligne d'alimentation du modem EBYTE E32 (169 MHz)
|
||||
fn set_e32_power(&mut self, on: bool) -> Result<(), Self::Error>;
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
//! File d'événements circulaire statique déterministe (StaticEventQueue)
|
||||
//!
|
||||
//! Conçue pour une exécution sans allocation dynamique (`no_std`), avec zéro tas (heap),
|
||||
//! manipulable sous section critique courte (`cortex_m::interrupt::free`) entre les ISRs
|
||||
//! et la boucle principale.
|
||||
|
||||
/// Descripteurs d'événements du système météo
|
||||
#[repr(u8)]
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum SystemEvent {
|
||||
/// Réveil périodique RTC pour capture d'un tir Davis (~2.5s)
|
||||
RtcDavisTick,
|
||||
/// Réveil RTC pour transmission montante planifiée 169 MHz
|
||||
RtcTransmitTick,
|
||||
/// Front d'interruption EXTI GDO0 (trame Davis prête dans la FIFO du CC1101)
|
||||
DavisPacketReady,
|
||||
/// Échéance du timer d'écoute Davis (12-20 ms) sans réception de sync word
|
||||
DavisListenTimeout,
|
||||
/// Signal AUX du module EBYTE E32 passé à l'état haut (prêt / fin d'émission RF)
|
||||
Radio169AuxReady,
|
||||
/// Réception d'un octet descendant sur l'interface UART du module 169 MHz
|
||||
Radio169RxByte(u8),
|
||||
/// Échéance de la fenêtre d'écoute descendante 169 MHz (1.0 s)
|
||||
Radio169ListenEnd,
|
||||
/// Alerte de seuil bas de tension batterie mesurée par l'ADC ou PVD
|
||||
BatteryVoltageAlert,
|
||||
/// Signal périodique de rafraîchissement du chien de garde (IWDG)
|
||||
WatchdogKick,
|
||||
}
|
||||
|
||||
/// Tampon circulaire statique borné et déterministe pour `SystemEvent`.
|
||||
pub struct StaticEventQueue<const CAP: usize> {
|
||||
buffer: [SystemEvent; CAP],
|
||||
head: usize,
|
||||
tail: usize,
|
||||
count: usize,
|
||||
overflow_count: u32,
|
||||
}
|
||||
|
||||
impl<const CAP: usize> StaticEventQueue<CAP> {
|
||||
/// Crée une nouvelle file d'événements statique vide.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
buffer: [SystemEvent::RtcDavisTick; CAP],
|
||||
head: 0,
|
||||
tail: 0,
|
||||
count: 0,
|
||||
overflow_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tente d'insérer un événement dans la file (typiquement appelé depuis une ISR courte).
|
||||
///
|
||||
/// Retourne `true` si l'événement a été inséré, ou `false` si la file est saturée.
|
||||
/// En cas de saturation, le compteur d'overflow est incrémenté de façon saturante.
|
||||
pub fn push(&mut self, event: SystemEvent) -> bool {
|
||||
if self.count >= CAP {
|
||||
self.overflow_count = self.overflow_count.saturating_add(1);
|
||||
return false;
|
||||
}
|
||||
self.buffer[self.head] = event;
|
||||
self.head = (self.head + 1) % CAP;
|
||||
self.count += 1;
|
||||
true
|
||||
}
|
||||
|
||||
/// Dépile le plus ancien événement disponible dans la file (appelé depuis la boucle principale).
|
||||
pub fn pop(&mut self) -> Option<SystemEvent> {
|
||||
if self.count == 0 {
|
||||
return None;
|
||||
}
|
||||
let event = self.buffer[self.tail];
|
||||
self.tail = (self.tail + 1) % CAP;
|
||||
self.count -= 1;
|
||||
Some(event)
|
||||
}
|
||||
|
||||
/// Indique si la file est vide.
|
||||
#[inline(always)]
|
||||
pub const fn is_empty(&self) -> bool {
|
||||
self.count == 0
|
||||
}
|
||||
|
||||
/// Indique si la file est saturée.
|
||||
#[inline(always)]
|
||||
pub const fn is_full(&self) -> bool {
|
||||
self.count == CAP
|
||||
}
|
||||
|
||||
/// Nombre d'événements actuellement en attente.
|
||||
#[inline(always)]
|
||||
pub const fn len(&self) -> usize {
|
||||
self.count
|
||||
}
|
||||
|
||||
/// Capacité maximale de la file.
|
||||
#[inline(always)]
|
||||
pub const fn capacity(&self) -> usize {
|
||||
CAP
|
||||
}
|
||||
|
||||
/// Nombre d'événements perdus par saturation depuis l'initialisation.
|
||||
#[inline(always)]
|
||||
pub const fn overflow_count(&self) -> u32 {
|
||||
self.overflow_count
|
||||
}
|
||||
|
||||
/// Vide la file d'événements.
|
||||
pub fn clear(&mut self) {
|
||||
self.head = 0;
|
||||
self.tail = 0;
|
||||
self.count = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_event_queue_fifo_order() {
|
||||
let mut queue = StaticEventQueue::<4>::new();
|
||||
assert!(queue.is_empty());
|
||||
assert_eq!(queue.len(), 0);
|
||||
|
||||
assert!(queue.push(SystemEvent::RtcDavisTick));
|
||||
assert!(queue.push(SystemEvent::Radio169RxByte(0x42)));
|
||||
assert!(queue.push(SystemEvent::WatchdogKick));
|
||||
|
||||
assert_eq!(queue.len(), 3);
|
||||
assert!(!queue.is_empty());
|
||||
assert!(!queue.is_full());
|
||||
|
||||
assert_eq!(queue.pop(), Some(SystemEvent::RtcDavisTick));
|
||||
assert_eq!(queue.pop(), Some(SystemEvent::Radio169RxByte(0x42)));
|
||||
assert_eq!(queue.pop(), Some(SystemEvent::WatchdogKick));
|
||||
assert_eq!(queue.pop(), None);
|
||||
assert!(queue.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_event_queue_saturation_and_overflow() {
|
||||
let mut queue = StaticEventQueue::<2>::new();
|
||||
|
||||
assert!(queue.push(SystemEvent::RtcDavisTick));
|
||||
assert!(queue.push(SystemEvent::DavisPacketReady));
|
||||
assert!(queue.is_full());
|
||||
|
||||
// Doit échouer et incrémenter overflow_count
|
||||
assert!(!queue.push(SystemEvent::BatteryVoltageAlert));
|
||||
assert_eq!(queue.overflow_count(), 1);
|
||||
|
||||
assert!(!queue.push(SystemEvent::RtcTransmitTick));
|
||||
assert_eq!(queue.overflow_count(), 2);
|
||||
|
||||
assert_eq!(queue.pop(), Some(SystemEvent::RtcDavisTick));
|
||||
assert_eq!(queue.len(), 1);
|
||||
|
||||
// Insertion à nouveau possible
|
||||
assert!(queue.push(SystemEvent::BatteryVoltageAlert));
|
||||
assert_eq!(queue.pop(), Some(SystemEvent::DavisPacketReady));
|
||||
assert_eq!(queue.pop(), Some(SystemEvent::BatteryVoltageAlert));
|
||||
assert_eq!(queue.pop(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_event_queue_wraparound() {
|
||||
let mut queue = StaticEventQueue::<3>::new();
|
||||
|
||||
for i in 0..10 {
|
||||
assert!(queue.push(SystemEvent::Radio169RxByte(i as u8)));
|
||||
assert_eq!(queue.pop(), Some(SystemEvent::Radio169RxByte(i as u8)));
|
||||
}
|
||||
assert!(queue.is_empty());
|
||||
assert_eq!(queue.overflow_count(), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Gestion des événements système et files de synchronisation
|
||||
|
||||
pub mod event_queue;
|
||||
|
||||
pub use event_queue::{StaticEventQueue, SystemEvent};
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Abstraction matérielle de l'ADC (Conversion Analogique-Numérique)
|
||||
|
||||
/// Erreurs possibles du convertisseur ADC
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum AdcError {
|
||||
ConversionTimeout,
|
||||
CalibrationFailed,
|
||||
ChannelNotConfigured,
|
||||
}
|
||||
|
||||
/// Trait d'accès aux mesures de télémétrie interne du microcontrôleur
|
||||
pub trait AdcController {
|
||||
type Error;
|
||||
|
||||
/// Mesure la tension d'alimentation / batterie en millivolts
|
||||
fn read_vbat_mv(&mut self) -> Result<u16, Self::Error>;
|
||||
|
||||
/// Mesure la température interne de la jonction silicium en dixièmes de degré Celsius
|
||||
fn read_internal_temp_deci_celsius(&mut self) -> Result<i16, Self::Error>;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! Abstraction matérielle de la mémoire Flash interne (STM32L476)
|
||||
//!
|
||||
//! Pages de 2 Ko (2048 octets), programmation par mots doubles (64 bits).
|
||||
|
||||
/// Taille d'une page Flash sur STM32L4
|
||||
pub const FLASH_PAGE_SIZE: usize = 2048;
|
||||
|
||||
/// Erreurs Flash matérielles
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum FlashError {
|
||||
UnlockFailed,
|
||||
EraseError,
|
||||
ProgrammingError,
|
||||
AlignmentError,
|
||||
AddressOutOfBounds,
|
||||
WriteProtected,
|
||||
Timeout,
|
||||
}
|
||||
|
||||
/// Trait d'accès bas niveau à la mémoire Flash
|
||||
pub trait FlashDriver {
|
||||
type Error;
|
||||
|
||||
/// Déverrouille les registres de contrôle de la Flash
|
||||
fn unlock(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
/// Verrouille les registres de contrôle de la Flash
|
||||
fn lock(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
/// Efface une page de 2 Ko à l'adresse spécifiée (doit être alignée sur 2 Ko)
|
||||
fn erase_page(&mut self, page_base_addr: u32) -> Result<(), Self::Error>;
|
||||
|
||||
/// Écrit un mot double de 64 bits à une adresse alignée sur 8 octets
|
||||
fn write_double_word(&mut self, addr: u32, data: u64) -> Result<(), Self::Error>;
|
||||
|
||||
/// Lit un segment de mémoire Flash dans un buffer RAM
|
||||
fn read_bytes(&self, addr: u32, buf: &mut [u8]) -> Result<(), Self::Error>;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Abstraction matérielle des GPIOs et parking analogique basse consommation
|
||||
|
||||
/// Mode opérationnel d'une broche GPIO
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum PinMode {
|
||||
Input,
|
||||
Output,
|
||||
AlternateFunction(u8),
|
||||
Analog,
|
||||
}
|
||||
|
||||
/// Résistance de tirage d'une broche GPIO
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Pull {
|
||||
None,
|
||||
Up,
|
||||
Down,
|
||||
}
|
||||
|
||||
/// Vitesse de commutation d'une broche GPIO
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Speed {
|
||||
Low,
|
||||
Medium,
|
||||
High,
|
||||
VeryHigh,
|
||||
}
|
||||
|
||||
/// Identifiant de port GPIO
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GpioPort {
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
H,
|
||||
}
|
||||
|
||||
/// Descripteur d'une broche physique
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PinId {
|
||||
pub port: GpioPort,
|
||||
pub pin: u8, // 0..15
|
||||
}
|
||||
|
||||
/// Trait d'abstraction pour le contrôle d'une broche de sortie
|
||||
pub trait OutputPin {
|
||||
type Error;
|
||||
fn set_high(&mut self) -> Result<(), Self::Error>;
|
||||
fn set_low(&mut self) -> Result<(), Self::Error>;
|
||||
fn toggle(&mut self) -> Result<(), Self::Error>;
|
||||
}
|
||||
|
||||
/// Trait d'abstraction pour la lecture d'une broche d'entrée
|
||||
pub trait InputPin {
|
||||
type Error;
|
||||
fn is_high(&self) -> Result<bool, Self::Error>;
|
||||
fn is_low(&self) -> Result<bool, Self::Error>;
|
||||
}
|
||||
|
||||
/// Trait de configuration des broches GPIO
|
||||
pub trait GpioController {
|
||||
type Error;
|
||||
fn configure_pin(&mut self, pin: PinId, mode: PinMode, pull: Pull, speed: Speed) -> Result<(), Self::Error>;
|
||||
/// Reconfigure l'ensemble des broches non critiques en mode Analogique sans tirage
|
||||
/// pour éliminer les courants de fuite en veille Stop 2 (DEC-025).
|
||||
fn park_non_wake_pins(&mut self) -> Result<(), Self::Error>;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! Abstraction matérielle du Watchdog Indépendant (IWDG)
|
||||
|
||||
/// Trait de contrôle du Watchdog Indépendant
|
||||
pub trait WatchdogDriver {
|
||||
/// Démarre le watchdog avec un timeout en millisecondes
|
||||
fn start(&mut self, timeout_ms: u32);
|
||||
|
||||
/// Rafraîchit le compteur du watchdog (Kick / Feed)
|
||||
fn feed(&mut self);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Abstractions matérielles pures (Hardware Abstraction Layer)
|
||||
//!
|
||||
//! Couche d'accès aux périphériques sans logique métier, sans calcul météo,
|
||||
//! sans choix de politique horaire et sans protocole radio.
|
||||
|
||||
pub mod adc;
|
||||
pub mod flash;
|
||||
pub mod gpio;
|
||||
pub mod iwdg;
|
||||
pub mod pwr;
|
||||
pub mod rtc;
|
||||
pub mod spi;
|
||||
pub mod uart;
|
||||
|
||||
pub use adc::{AdcController, AdcError};
|
||||
pub use flash::{FlashDriver, FlashError, FLASH_PAGE_SIZE};
|
||||
pub use gpio::{GpioController, GpioPort, InputPin, OutputPin, PinId, PinMode, Pull, Speed};
|
||||
pub use iwdg::WatchdogDriver;
|
||||
pub use pwr::{LowPowerMode, PowerController};
|
||||
pub use rtc::{RtcController, RtcError, RtcTime};
|
||||
pub use spi::{SpiError, SpiMaster};
|
||||
pub use uart::{UartError, UartInterface};
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Abstraction matérielle de la gestion de l'énergie et des horloges (PWR / RCC)
|
||||
|
||||
/// Modes de basse consommation supportés par le microcontrôleur
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LowPowerMode {
|
||||
Sleep,
|
||||
LowPowerSleep,
|
||||
Stop0,
|
||||
Stop1,
|
||||
Stop2,
|
||||
Standby,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
/// Trait de contrôle de l'alimentation et des transitions de sommeil
|
||||
pub trait PowerController {
|
||||
type Error;
|
||||
|
||||
/// Prépare le microcontrôleur pour le mode Stop 2 avec rétention SRAM2 garantie
|
||||
fn prepare_stop2(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
/// Exécute la mise en sommeil effectif (DSB + ISB + WFI)
|
||||
fn enter_low_power(&mut self);
|
||||
|
||||
/// Restaure les horloges système après réveil (MSI 16 MHz sans PLL)
|
||||
fn restore_clocks_after_wakeup(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
/// Acquitte les drapeaux de réveil matériel
|
||||
fn clear_wakeup_flags(&mut self);
|
||||
}
|
||||
|
||||
/// Séquence matérielle directe de passage en Stop 2 pour STM32L476
|
||||
pub fn enter_stop2_hardware_sequence() {
|
||||
#[cfg(target_arch = "arm")]
|
||||
unsafe {
|
||||
// PWR_CR1 est à 0x40007000
|
||||
const PWR_CR1: *mut u32 = 0x4000_7000 as *mut u32;
|
||||
let mut cr1 = core::ptr::read_volatile(PWR_CR1);
|
||||
// Bit 9 = RRS (SRAM2 retention in Stop 2)
|
||||
cr1 |= 1 << 9;
|
||||
// Bits 2..0 = LPMS = 010 (Stop 2 mode)
|
||||
cr1 = (cr1 & !0x07) | 0x02;
|
||||
core::ptr::write_volatile(PWR_CR1, cr1);
|
||||
|
||||
// SCB_SCR est à 0xE000ED10
|
||||
const SCB_SCR: *mut u32 = 0xE000_ED10 as *mut u32;
|
||||
let scr = core::ptr::read_volatile(SCB_SCR);
|
||||
// Bit 2 = SLEEPDEEP
|
||||
core::ptr::write_volatile(SCB_SCR, scr | (1 << 2));
|
||||
|
||||
cortex_m::asm::dsb();
|
||||
cortex_m::asm::isb();
|
||||
cortex_m::asm::wfi();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Abstraction matérielle de l'Horloge Temps Réel (RTC) et registres de sauvegarde
|
||||
|
||||
/// Structure de temps UTC compacte
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RtcTime {
|
||||
pub hour: u8, // 0..23
|
||||
pub minute: u8, // 0..59
|
||||
pub second: u8, // 0..59
|
||||
}
|
||||
|
||||
impl RtcTime {
|
||||
/// Convertit l'heure en minute du jour (0..1439)
|
||||
#[inline(always)]
|
||||
pub const fn to_minutes_of_day(&self) -> u16 {
|
||||
(self.hour as u16) * 60 + (self.minute as u16)
|
||||
}
|
||||
}
|
||||
|
||||
/// Erreurs possibles lors des opérations RTC
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum RtcError {
|
||||
InitializationFailed,
|
||||
InvalidParameter,
|
||||
HardwareTimeout,
|
||||
}
|
||||
|
||||
/// Trait de contrôle de la RTC et des registres de sauvegarde
|
||||
pub trait RtcController {
|
||||
type Error;
|
||||
|
||||
/// Lit l'heure courante issue des registres RTC
|
||||
fn get_time(&self) -> Result<RtcTime, Self::Error>;
|
||||
|
||||
/// Définit l'heure courante (synchronisation depuis la station/serveur)
|
||||
fn set_time(&mut self, time: RtcTime) -> Result<(), Self::Error>;
|
||||
|
||||
/// Programme un réveil périodique via le Wakeup Timer (pour capture Davis)
|
||||
fn set_wakeup_timer_ticks(&mut self, ticks: u16) -> Result<(), Self::Error>;
|
||||
|
||||
/// Désactive le Wakeup Timer
|
||||
fn disable_wakeup_timer(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
/// Programme une alarme horaire (Alarme A pour la transmission 169 MHz)
|
||||
fn set_alarm_time(&mut self, hour: u8, minute: u8, second: u8) -> Result<(), Self::Error>;
|
||||
|
||||
/// Acquitte l'interruption d'alarme
|
||||
fn clear_alarm_flag(&mut self) -> Result<(), Self::Error>;
|
||||
|
||||
/// Lit l'un des 32 registres de sauvegarde (Backup Registers 0..31)
|
||||
fn read_backup_register(&self, index: u8) -> u32;
|
||||
|
||||
/// Écrit dans l'un des 32 registres de sauvegarde (préservés en Stop 2 et Vbat)
|
||||
fn write_backup_register(&mut self, index: u8, value: u32);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Abstraction matérielle du bus SPI (Master)
|
||||
|
||||
/// Erreurs possibles sur le bus SPI
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum SpiError {
|
||||
BusError,
|
||||
Overrun,
|
||||
ModeFault,
|
||||
CrcError,
|
||||
Timeout,
|
||||
}
|
||||
|
||||
/// Trait d'accès synchrone au bus SPI maître (ex: communication CC1101)
|
||||
pub trait SpiMaster {
|
||||
type Error;
|
||||
|
||||
/// Écrit un buffer sur le bus SPI sans lire la réponse
|
||||
fn write(&mut self, data: &[u8]) -> Result<(), Self::Error>;
|
||||
|
||||
/// Échange simultanément des octets en émission et réception (Full Duplex)
|
||||
fn transfer(&mut self, write_buf: &[u8], read_buf: &mut [u8]) -> Result<(), Self::Error>;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//! Abstraction matérielle de l'interface série asynchrone (UART/USART)
|
||||
|
||||
/// Erreurs possibles sur la liaison série UART
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum UartError {
|
||||
FramingError,
|
||||
NoiseError,
|
||||
Overrun,
|
||||
ParityError,
|
||||
Timeout,
|
||||
}
|
||||
|
||||
/// Trait d'accès à l'interface série (ex: modem EBYTE E32-170T30D)
|
||||
pub trait UartInterface {
|
||||
type Error;
|
||||
|
||||
/// Émet un buffer d'octets de manière bloquante ou DMA
|
||||
fn write_bytes(&mut self, data: &[u8]) -> Result<(), Self::Error>;
|
||||
|
||||
/// Lit un octet disponible sans blocage
|
||||
fn read_byte(&mut self) -> Result<Option<u8>, Self::Error>;
|
||||
|
||||
/// Vide et acquitte le buffer matériel de réception
|
||||
fn flush_rx(&mut self) -> Result<(), Self::Error>;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#![no_std]
|
||||
|
||||
//! # OS_relais - Firmware Bare-Metal Relais Météo 169 MHz (STM32L476RGT6)
|
||||
//!
|
||||
//! Couche logicielle propriétaire sans OS, sans RTOS et sans allocation dynamique (zéro heap),
|
||||
//! optimisée pour la rétention SRAM2 en mode Stop 2 et l'interception des trames Davis 868 MHz.
|
||||
|
||||
pub mod app;
|
||||
pub mod arch;
|
||||
pub mod boot;
|
||||
pub mod drivers;
|
||||
pub mod events;
|
||||
pub mod hal;
|
||||
pub mod protocol;
|
||||
pub mod services;
|
||||
@@ -0,0 +1,82 @@
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
|
||||
use cortex_m_rt::entry;
|
||||
use panic_halt as _;
|
||||
|
||||
use os_relais::app::{RelayAction, RelayStateMachine, WeatherAggregator};
|
||||
use os_relais::arch::barrier::wfi;
|
||||
use os_relais::boot::{capture_and_clear_reset_reason, init_fpu};
|
||||
use os_relais::events::{StaticEventQueue, SystemEvent};
|
||||
use os_relais::services::{
|
||||
PowerManager, SystemDiagnostics, TransmissionPolicyTable, WatchdogManager,
|
||||
};
|
||||
|
||||
/// Capacité de la file d'événements statique en SRAM2
|
||||
const EVENT_QUEUE_CAPACITY: usize = 16;
|
||||
|
||||
#[entry]
|
||||
fn main() -> ! {
|
||||
// 1. Initialisation matérielle précoce du CPU Cortex-M4F
|
||||
init_fpu();
|
||||
let reset_reason = capture_and_clear_reset_reason();
|
||||
|
||||
// 2. Allocation statique des gestionnaires en SRAM2 (0x10000000)
|
||||
let mut event_queue = StaticEventQueue::<EVENT_QUEUE_CAPACITY>::new();
|
||||
let mut fsm = RelayStateMachine::new();
|
||||
let mut aggregator = WeatherAggregator::new();
|
||||
let _power_mgr = PowerManager::new();
|
||||
let _watchdog_mgr = WatchdogManager::new(8000);
|
||||
let mut diag = SystemDiagnostics::new(reset_reason);
|
||||
let _policy = TransmissionPolicyTable::default_safe();
|
||||
|
||||
// Premier événement d'amorçage
|
||||
event_queue.push(SystemEvent::WatchdogKick);
|
||||
|
||||
// 3. Boucle événementielle principale
|
||||
loop {
|
||||
if let Some(event) = event_queue.pop() {
|
||||
let (_next_state, action) = fsm.process_event(event);
|
||||
|
||||
match action {
|
||||
RelayAction::StartHardwareInit => {
|
||||
// Initialisation des périphériques (clocks, GPIO, RTC, SPI, UART)
|
||||
event_queue.push(SystemEvent::WatchdogKick);
|
||||
}
|
||||
RelayAction::StartDavisScan => {
|
||||
// Démarrage de l'écoute continue CC1101 sur canal 0
|
||||
}
|
||||
RelayAction::PrepareDavisSyncWindow => {
|
||||
// Armement de la fenêtre d'écoute CC1101 (12-20 ms)
|
||||
}
|
||||
RelayAction::DecodeAndAggregateDavis => {
|
||||
// Décodage du paquet brut et mise à jour de l'agrégateur
|
||||
diag.record_davis_rx();
|
||||
}
|
||||
RelayAction::StartRadio169Transmission => {
|
||||
// Sérialisation télémétrie et émission UART E32 (+27 dBm ERP max)
|
||||
diag.record_169_tx();
|
||||
aggregator.reset_window();
|
||||
}
|
||||
RelayAction::OpenDownlinkListenWindow => {
|
||||
// Maintien écoute 169 MHz (1.0 s)
|
||||
}
|
||||
RelayAction::ProcessIncomingCommand => {
|
||||
// Application de la commande reçue
|
||||
diag.record_169_cmd();
|
||||
}
|
||||
RelayAction::ApplySafeModeFallback => {
|
||||
// Basculement sur politique de repli (600s)
|
||||
diag.record_davis_sync_loss();
|
||||
}
|
||||
RelayAction::EnterStop2Sleep => {
|
||||
// Entrée en mode Stop 2 avec réveil par RTC ou EXTI
|
||||
}
|
||||
RelayAction::None => {}
|
||||
}
|
||||
} else {
|
||||
// Aucun événement en attente : attente basse consommation
|
||||
wfi();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Traitement et validation des commandes descendantes 169 MHz depuis la station/serveur
|
||||
|
||||
use super::crc::crc32;
|
||||
|
||||
/// Magic identifiant les commandes descendantes
|
||||
pub const COMMAND_MAGIC: u16 = 0x4743; // 'G', 'C'
|
||||
|
||||
/// Catalogue des identifiants d'ordres descendants
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum CommandId {
|
||||
SetTransmissionPolicy = 0x10,
|
||||
ForceTransmission = 0x11,
|
||||
GetDiagnostics = 0x12,
|
||||
SystemReset = 0x13,
|
||||
SetRtcTime = 0x14,
|
||||
SetRadioParams = 0x15,
|
||||
}
|
||||
|
||||
/// Commande descendante décodée
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum DownlinkCommand {
|
||||
SetTransmissionPolicy {
|
||||
default_interval_s: u16,
|
||||
},
|
||||
ForceTransmission,
|
||||
GetDiagnostics,
|
||||
SystemReset,
|
||||
SetRtcTime {
|
||||
hour: u8,
|
||||
minute: u8,
|
||||
second: u8,
|
||||
},
|
||||
SetRadioParams {
|
||||
channel_index: u8,
|
||||
power_dbm: u8,
|
||||
},
|
||||
}
|
||||
|
||||
/// Erreurs de parsing de commande
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum CommandParseError {
|
||||
InvalidMagic,
|
||||
UnknownCommand(u8),
|
||||
PayloadLengthMismatch,
|
||||
CrcError,
|
||||
BufferTooShort,
|
||||
InvalidParameter,
|
||||
}
|
||||
|
||||
/// Décode une commande descendante reçue sur UART 169 MHz
|
||||
pub fn parse_downlink_command(raw: &[u8]) -> Result<(u32, DownlinkCommand), CommandParseError> {
|
||||
if raw.len() < 10 {
|
||||
return Err(CommandParseError::BufferTooShort);
|
||||
}
|
||||
|
||||
let magic = ((raw[0] as u16) << 8) | (raw[1] as u16);
|
||||
if magic != COMMAND_MAGIC {
|
||||
return Err(CommandParseError::InvalidMagic);
|
||||
}
|
||||
|
||||
let seq = u32::from_be_bytes([raw[2], raw[3], raw[4], raw[5]]);
|
||||
let cmd_code = raw[6];
|
||||
let payload_len = raw[7] as usize;
|
||||
|
||||
if raw.len() < 8 + payload_len + 4 {
|
||||
return Err(CommandParseError::PayloadLengthMismatch);
|
||||
}
|
||||
|
||||
let expected_crc = u32::from_be_bytes([
|
||||
raw[8 + payload_len],
|
||||
raw[8 + payload_len + 1],
|
||||
raw[8 + payload_len + 2],
|
||||
raw[8 + payload_len + 3],
|
||||
]);
|
||||
|
||||
let computed_crc = crc32(&raw[0..8 + payload_len]);
|
||||
if expected_crc != computed_crc {
|
||||
return Err(CommandParseError::CrcError);
|
||||
}
|
||||
|
||||
let payload = &raw[8..8 + payload_len];
|
||||
|
||||
let cmd = match cmd_code {
|
||||
0x10 => {
|
||||
if payload.len() < 2 {
|
||||
return Err(CommandParseError::PayloadLengthMismatch);
|
||||
}
|
||||
let default_interval_s = u16::from_be_bytes([payload[0], payload[1]]);
|
||||
DownlinkCommand::SetTransmissionPolicy { default_interval_s }
|
||||
}
|
||||
0x11 => DownlinkCommand::ForceTransmission,
|
||||
0x12 => DownlinkCommand::GetDiagnostics,
|
||||
0x13 => DownlinkCommand::SystemReset,
|
||||
0x14 => {
|
||||
if payload.len() < 3 {
|
||||
return Err(CommandParseError::PayloadLengthMismatch);
|
||||
}
|
||||
let hour = payload[0];
|
||||
let minute = payload[1];
|
||||
let second = payload[2];
|
||||
if hour > 23 || minute > 59 || second > 59 {
|
||||
return Err(CommandParseError::InvalidParameter);
|
||||
}
|
||||
DownlinkCommand::SetRtcTime { hour, minute, second }
|
||||
}
|
||||
0x15 => {
|
||||
if payload.len() < 2 {
|
||||
return Err(CommandParseError::PayloadLengthMismatch);
|
||||
}
|
||||
let channel_index = payload[0];
|
||||
let power_dbm = payload[1];
|
||||
if power_dbm > 27 {
|
||||
// Conformité ERP max (+27 dBm / 500 mW)
|
||||
return Err(CommandParseError::InvalidParameter);
|
||||
}
|
||||
DownlinkCommand::SetRadioParams {
|
||||
channel_index,
|
||||
power_dbm,
|
||||
}
|
||||
}
|
||||
other => return Err(CommandParseError::UnknownCommand(other)),
|
||||
};
|
||||
|
||||
Ok((seq, cmd))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_set_rtc_time_command() {
|
||||
let mut buf = [0u8; 15];
|
||||
buf[0] = (COMMAND_MAGIC >> 8) as u8;
|
||||
buf[1] = (COMMAND_MAGIC & 0xFF) as u8;
|
||||
buf[2..6].copy_from_slice(&105u32.to_be_bytes()); // Seq = 105
|
||||
buf[6] = 0x14; // SetRtcTime
|
||||
buf[7] = 3; // Payload len = 3
|
||||
buf[8] = 14; // 14h
|
||||
buf[9] = 30; // 30m
|
||||
buf[10] = 0; // 00s
|
||||
|
||||
let crc = crc32(&buf[0..11]);
|
||||
buf[11..15].copy_from_slice(&crc.to_be_bytes());
|
||||
|
||||
let (seq, cmd) = parse_downlink_command(&buf).unwrap();
|
||||
assert_eq!(seq, 105);
|
||||
assert_eq!(
|
||||
cmd,
|
||||
DownlinkCommand::SetRtcTime {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
second: 0
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Calculs d'intégrité et sommes de contrôle (CRC16 Davis, CRC16 CCITT, CRC32)
|
||||
//!
|
||||
//! Fonctions pures déterministes fonctionnant sans allocation dynamique.
|
||||
|
||||
/// Calcule le CRC-16 propre aux trames de l'ISS Davis Vantage Pro2.
|
||||
///
|
||||
/// Polynôme : 0x1021, Valeur initiale : 0x0000.
|
||||
pub fn crc16_davis(data: &[u8]) -> u16 {
|
||||
let mut crc: u16 = 0x0000;
|
||||
for &byte in data {
|
||||
let mut b = (byte as u16) << 8;
|
||||
for _ in 0..8 {
|
||||
if ((crc ^ b) & 0x8000) != 0 {
|
||||
crc = (crc << 1) ^ 0x1021;
|
||||
} else {
|
||||
crc <<= 1;
|
||||
}
|
||||
b <<= 1;
|
||||
}
|
||||
}
|
||||
crc
|
||||
}
|
||||
|
||||
/// Vérifie si une trame Davis brute (payload + 2 octets CRC) est intègre.
|
||||
pub fn is_davis_crc_valid(packet: &[u8]) -> bool {
|
||||
if packet.len() < 3 {
|
||||
return false;
|
||||
}
|
||||
crc16_davis(packet) == 0x0000
|
||||
}
|
||||
|
||||
/// Calcule le CRC-16 CCITT standard (XModem / Kermit / Table de politique).
|
||||
///
|
||||
/// Polynôme : 0x1021, Valeur initiale : 0xFFFF.
|
||||
pub fn crc16_ccitt(data: &[u8]) -> u16 {
|
||||
let mut crc: u16 = 0xFFFF;
|
||||
for &byte in data {
|
||||
crc ^= (byte as u16) << 8;
|
||||
for _ in 0..8 {
|
||||
if (crc & 0x8000) != 0 {
|
||||
crc = (crc << 1) ^ 0x1021;
|
||||
} else {
|
||||
crc <<= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
crc
|
||||
}
|
||||
|
||||
/// Calcule le CRC-32 IEEE 802.3 standard (utilisé pour Flash Ping-Pong et Télémétrie 169).
|
||||
///
|
||||
/// Polynôme réfléchi : 0xEDB88320, Valeur initiale : 0xFFFFFFFF, Inversion finale.
|
||||
pub fn crc32(data: &[u8]) -> u32 {
|
||||
let mut crc: u32 = 0xFFFF_FFFF;
|
||||
for &byte in data {
|
||||
crc ^= byte as u32;
|
||||
for _ in 0..8 {
|
||||
let mask = if (crc & 1) != 0 { 0xEDB8_8320 } else { 0 };
|
||||
crc = (crc >> 1) ^ mask;
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_crc16_davis_calculation_and_validation() {
|
||||
// Paquet simulé : 6 octets payload + 2 octets CRC Davis
|
||||
let payload = [0x50, 0x01, 0x2A, 0x00, 0x12, 0x34];
|
||||
let crc = crc16_davis(&payload);
|
||||
let crc_bytes = [(crc >> 8) as u8, (crc & 0xFF) as u8];
|
||||
|
||||
let mut full_packet = [0u8; 8];
|
||||
full_packet[..6].copy_from_slice(&payload);
|
||||
full_packet[6..8].copy_from_slice(&crc_bytes);
|
||||
|
||||
assert!(is_davis_crc_valid(&full_packet));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_crc16_ccitt() {
|
||||
let data = b"123456789";
|
||||
let crc = crc16_ccitt(data);
|
||||
// Le CRC-16/CCITT-FALSE de "123456789" est 0x29B1
|
||||
assert_eq!(crc, 0x29B1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_crc32_standard() {
|
||||
let data = b"123456789";
|
||||
let crc = crc32(data);
|
||||
// Le CRC-32 IEEE de "123456789" est 0xCBF43926
|
||||
assert_eq!(crc, 0xCBF4_3926);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Moteur algorithmique de décodage des trames Davis Vantage Pro2 ISS (868 MHz)
|
||||
//!
|
||||
//! Module pur sans dépendance matérielle, testable sur banc hôte.
|
||||
|
||||
use super::crc::is_davis_crc_valid;
|
||||
|
||||
/// Types de paquets transmis par l'ISS Davis
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum DavisPacketType {
|
||||
Temperature, // Type 0x8 (VP2P_TEMP)
|
||||
WindGust, // Type 0x9 (VP2P_WINDGUST)
|
||||
Humidity, // Type 0xA (VP2P_HUMIDITY)
|
||||
RainAccumulated, // Type 0xE (VP2P_RAIN)
|
||||
SolarRadiation, // Type 0x6 / 0x7 (VP2P_SOLAR)
|
||||
UvIndex, // Type 0x4 (VP2P_UV)
|
||||
RainSecs, // Type 0x5 (VP2P_RAINSECS)
|
||||
Unknown(u8),
|
||||
}
|
||||
|
||||
/// Mesure météorologique décodée issue d'une trame Davis
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub struct DavisMeasurement {
|
||||
pub station_id: u8,
|
||||
pub battery_low: bool,
|
||||
pub wind_speed_mph: u8,
|
||||
pub wind_direction_deg: u16,
|
||||
pub payload: DavisPayload,
|
||||
}
|
||||
|
||||
/// Charge utile spécifique au type de capteur
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub enum DavisPayload {
|
||||
Temperature { temp_centi_celsius: i16 },
|
||||
Humidity { relative_humidity_pct: u8 },
|
||||
Rain { tip_count: u16 },
|
||||
WindGust { gust_speed_mph: u8 },
|
||||
SolarRadiation { radiation_wm2: u16 },
|
||||
UvIndex { uv_index_deci: u8 },
|
||||
Unknown { raw_type: u8, data: [u8; 3] },
|
||||
}
|
||||
|
||||
/// Erreurs possibles lors du décodage d'un paquet Davis
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum DavisDecodeError {
|
||||
BufferTooShort,
|
||||
CrcInvalid,
|
||||
InvalidData,
|
||||
}
|
||||
|
||||
/// Décode un paquet brut reçu de l'ISS Davis (8 octets : 6 octets payload + 2 octets CRC)
|
||||
pub fn decode_davis_packet(raw: &[u8]) -> Result<DavisMeasurement, DavisDecodeError> {
|
||||
if raw.len() < 8 {
|
||||
return Err(DavisDecodeError::BufferTooShort);
|
||||
}
|
||||
|
||||
if !is_davis_crc_valid(&raw[0..8]) {
|
||||
return Err(DavisDecodeError::CrcInvalid);
|
||||
}
|
||||
|
||||
let byte0 = raw[0];
|
||||
let packet_type_nibble = (byte0 >> 4) & 0x0F;
|
||||
let battery_low = (byte0 & 0x08) != 0;
|
||||
let station_id = byte0 & 0x07;
|
||||
|
||||
let wind_speed_mph = raw[1];
|
||||
|
||||
// Direction du vent sur 8 bits normalisée à 0..359°
|
||||
let wind_direction_raw = raw[2] as u32;
|
||||
let wind_direction_deg = ((wind_direction_raw * 360) / 256) as u16 % 360;
|
||||
|
||||
let payload = match packet_type_nibble {
|
||||
0x8 => {
|
||||
// Température extérieure (Type 0x8 - VP2P_TEMP)
|
||||
// Format Davis : ((raw[3] << 8) | raw[4]) >> 4 en 1/10e °F (signé)
|
||||
let raw_temp_f_tenths = (((raw[3] as i16) << 8) | (raw[4] as i16)) >> 4;
|
||||
// Conversion en centièmes de °C : (T_F/10 - 32) * 5/9 * 100 = (T_F_tenths - 320) * 50 / 9
|
||||
let temp_centi_celsius = (((raw_temp_f_tenths as i32 - 320) * 50) / 9) as i16;
|
||||
DavisPayload::Temperature { temp_centi_celsius }
|
||||
}
|
||||
0x9 => {
|
||||
// Rafale de vent 10-minutes (Type 0x9 - VP2P_WINDGUST)
|
||||
let gust_speed_mph = raw[3];
|
||||
DavisPayload::WindGust { gust_speed_mph }
|
||||
}
|
||||
0xA => {
|
||||
// Humidité relative extérieure (Type 0xA - VP2P_HUMIDITY)
|
||||
// Format Davis : (((raw[4] >> 4) << 8) | raw[3]) / 10 en %
|
||||
let raw_hum = (((raw[4] as u16 >> 4) << 8) | (raw[3] as u16)) / 10;
|
||||
let relative_humidity_pct = if raw_hum > 100 { 100 } else { raw_hum as u8 };
|
||||
DavisPayload::Humidity { relative_humidity_pct }
|
||||
}
|
||||
0xE => {
|
||||
// Pluviosité : compteur cumulé d'augets (Type 0xE - VP2P_RAIN)
|
||||
let tip_count = (raw[3] as u16 & 0x7F) | (((raw[4] as u16) & 0x0F) << 7);
|
||||
DavisPayload::Rain { tip_count }
|
||||
}
|
||||
0x6 | 0x7 => {
|
||||
// Rayonnement solaire (Type 0x6 / 0x7 - VP2P_SOLAR)
|
||||
let raw_solar = (((raw[3] as u16) << 8) | (raw[4] as u16)) >> 6;
|
||||
DavisPayload::SolarRadiation { radiation_wm2: raw_solar }
|
||||
}
|
||||
0x4 => {
|
||||
// Indice UV (Type 0x4 - VP2P_UV)
|
||||
let raw_uv = (((raw[3] as u16) << 8) | (raw[4] as u16)) >> 6;
|
||||
DavisPayload::UvIndex { uv_index_deci: (raw_uv / 5) as u8 }
|
||||
}
|
||||
other => {
|
||||
let mut data = [0u8; 3];
|
||||
data.copy_from_slice(&raw[3..6]);
|
||||
DavisPayload::Unknown { raw_type: other, data }
|
||||
}
|
||||
};
|
||||
|
||||
Ok(DavisMeasurement {
|
||||
station_id,
|
||||
battery_low,
|
||||
wind_speed_mph,
|
||||
wind_direction_deg,
|
||||
payload,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_decode_davis_temp_packet() {
|
||||
// Vecteur 1 vérifié : Type 0x8 (Température), Station ID 0, Vent 10 mph, Dir 90° (0x40), Temp 0x3E9 (100.1 °F = 37.83 °C)
|
||||
let raw = [0x80, 0x0A, 0x40, 0x3E, 0x90, 0x00, 0x3A, 0x5D];
|
||||
let measurement = decode_davis_packet(&raw).expect("Doit décoder");
|
||||
|
||||
assert_eq!(measurement.station_id, 0);
|
||||
assert!(!measurement.battery_low);
|
||||
assert_eq!(measurement.wind_speed_mph, 10);
|
||||
assert_eq!(measurement.wind_direction_deg, 90);
|
||||
assert_eq!(
|
||||
measurement.payload,
|
||||
DavisPayload::Temperature { temp_centi_celsius: 3783 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decode_davis_rain_packet() {
|
||||
// Vecteur 2 vérifié : Type 0xE (Pluie), Station ID 0, Vent 0 mph, Dir 0°, Augets 21
|
||||
let raw = [0xE0, 0x00, 0x00, 0x15, 0x00, 0x00, 0x23, 0xAB];
|
||||
let measurement = decode_davis_packet(&raw).expect("Doit décoder");
|
||||
|
||||
assert_eq!(measurement.station_id, 0);
|
||||
assert_eq!(measurement.wind_speed_mph, 0);
|
||||
assert_eq!(measurement.payload, DavisPayload::Rain { tip_count: 21 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decode_davis_humidity_packet() {
|
||||
// Vecteur 3 vérifié : Type 0xA (Humidité), Station ID 0, Vent 5 mph, Dir 180° (0x80), Humidité 58.8% -> 58%
|
||||
let raw = [0xA0, 0x05, 0x80, 0x4C, 0x20, 0x00, 0x71, 0x6D];
|
||||
let measurement = decode_davis_packet(&raw).expect("Doit décoder");
|
||||
|
||||
assert_eq!(measurement.station_id, 0);
|
||||
assert_eq!(measurement.wind_speed_mph, 5);
|
||||
assert_eq!(measurement.wind_direction_deg, 180);
|
||||
assert_eq!(
|
||||
measurement.payload,
|
||||
DavisPayload::Humidity { relative_humidity_pct: 58 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decode_davis_crc_error() {
|
||||
let raw = [0x80, 15, 128, 25, 0x00, 0x00, 0xFF, 0xFF];
|
||||
let result = decode_davis_packet(&raw);
|
||||
assert_eq!(result, Err(DavisDecodeError::CrcInvalid));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
//! Protocoles de données indépendants du matériel (Davis, Télémétrie 169 MHz, Commandes)
|
||||
|
||||
pub mod command;
|
||||
pub mod crc;
|
||||
pub mod davis;
|
||||
pub mod telemetry;
|
||||
|
||||
pub use command::{parse_downlink_command, CommandId, CommandParseError, DownlinkCommand, COMMAND_MAGIC};
|
||||
pub use crc::{crc16_ccitt, crc16_davis, crc32, is_davis_crc_valid};
|
||||
pub use davis::{decode_davis_packet, DavisDecodeError, DavisMeasurement, DavisPacketType, DavisPayload};
|
||||
pub use telemetry::{MessageType, WeatherTelemetryPacket, TELEMETRY_MAGIC};
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Format binaire de la télémétrie montante 169 MHz vers la station
|
||||
//!
|
||||
//! Encodage compact sans allocation dynamique, protégé par CRC-32.
|
||||
|
||||
use super::crc::crc32;
|
||||
|
||||
/// Identifiant magique du protocole Gastinel Weather surcouche
|
||||
pub const TELEMETRY_MAGIC: u16 = 0x4757; // 'G', 'W'
|
||||
|
||||
/// Type de message télémétrique
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum MessageType {
|
||||
WeatherReport = 0x01,
|
||||
SystemDiagnostics = 0x02,
|
||||
AlarmNotification = 0x03,
|
||||
}
|
||||
|
||||
/// Structure de télémétrie météo compacte à transmettre sur 169 MHz
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WeatherTelemetryPacket {
|
||||
pub sequence_number: u32,
|
||||
pub timestamp_minutes: u16,
|
||||
pub wind_avg_deci_kmh: u16,
|
||||
pub wind_gust_deci_kmh: u16,
|
||||
pub wind_direction_deg: u16,
|
||||
pub temperature_centi_c: i16,
|
||||
pub humidity_pct: u8,
|
||||
pub rain_tips_accumulated: u16,
|
||||
pub vbat_mv: u16,
|
||||
pub die_temp_deci_c: i16,
|
||||
pub davis_rx_count: u16,
|
||||
pub davis_miss_count: u16,
|
||||
}
|
||||
|
||||
impl WeatherTelemetryPacket {
|
||||
/// Taille sérialisée du paquet (sans CRC) : 2 (magic) + 1 (type) + 26 (champs) = 29 octets (+ 4 octets CRC32 = 33 octets)
|
||||
pub const SERIALIZED_LEN: usize = 33;
|
||||
|
||||
/// Sérialise le paquet dans un buffer de 33 octets avec CRC32 en queue
|
||||
pub fn serialize(&self, out: &mut [u8; Self::SERIALIZED_LEN]) {
|
||||
out[0] = (TELEMETRY_MAGIC >> 8) as u8;
|
||||
out[1] = (TELEMETRY_MAGIC & 0xFF) as u8;
|
||||
out[2] = MessageType::WeatherReport as u8;
|
||||
|
||||
out[3..7].copy_from_slice(&self.sequence_number.to_be_bytes());
|
||||
out[7..9].copy_from_slice(&self.timestamp_minutes.to_be_bytes());
|
||||
out[9..11].copy_from_slice(&self.wind_avg_deci_kmh.to_be_bytes());
|
||||
out[11..13].copy_from_slice(&self.wind_gust_deci_kmh.to_be_bytes());
|
||||
out[13..15].copy_from_slice(&self.wind_direction_deg.to_be_bytes());
|
||||
out[15..17].copy_from_slice(&self.temperature_centi_c.to_be_bytes());
|
||||
out[17] = self.humidity_pct;
|
||||
out[18..20].copy_from_slice(&self.rain_tips_accumulated.to_be_bytes());
|
||||
out[20..22].copy_from_slice(&self.vbat_mv.to_be_bytes());
|
||||
out[22..24].copy_from_slice(&self.die_temp_deci_c.to_be_bytes());
|
||||
out[24..26].copy_from_slice(&self.davis_rx_count.to_be_bytes());
|
||||
out[26..28].copy_from_slice(&self.davis_miss_count.to_be_bytes());
|
||||
out[28] = 0x00; // Réservé / Padding
|
||||
|
||||
let crc = crc32(&out[0..29]);
|
||||
out[29..33].copy_from_slice(&crc.to_be_bytes());
|
||||
}
|
||||
|
||||
/// Désérialise et valide un buffer de télémétrie reçu
|
||||
pub fn deserialize(raw: &[u8; Self::SERIALIZED_LEN]) -> Option<Self> {
|
||||
let magic = ((raw[0] as u16) << 8) | (raw[1] as u16);
|
||||
if magic != TELEMETRY_MAGIC || raw[2] != (MessageType::WeatherReport as u8) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let expected_crc = u32::from_be_bytes([raw[29], raw[30], raw[31], raw[32]]);
|
||||
let computed_crc = crc32(&raw[0..29]);
|
||||
if expected_crc != computed_crc {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Self {
|
||||
sequence_number: u32::from_be_bytes([raw[3], raw[4], raw[5], raw[6]]),
|
||||
timestamp_minutes: u16::from_be_bytes([raw[7], raw[8]]),
|
||||
wind_avg_deci_kmh: u16::from_be_bytes([raw[9], raw[10]]),
|
||||
wind_gust_deci_kmh: u16::from_be_bytes([raw[11], raw[12]]),
|
||||
wind_direction_deg: u16::from_be_bytes([raw[13], raw[14]]),
|
||||
temperature_centi_c: i16::from_be_bytes([raw[15], raw[16]]),
|
||||
humidity_pct: raw[17],
|
||||
rain_tips_accumulated: u16::from_be_bytes([raw[18], raw[19]]),
|
||||
vbat_mv: u16::from_be_bytes([raw[20], raw[21]]),
|
||||
die_temp_deci_c: i16::from_be_bytes([raw[22], raw[23]]),
|
||||
davis_rx_count: u16::from_be_bytes([raw[24], raw[25]]),
|
||||
davis_miss_count: u16::from_be_bytes([raw[26], raw[27]]),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_telemetry_packet_roundtrip() {
|
||||
let packet = WeatherTelemetryPacket {
|
||||
sequence_number: 1420,
|
||||
timestamp_minutes: 720, // 12:00
|
||||
wind_avg_deci_kmh: 450, // 45.0 km/h
|
||||
wind_gust_deci_kmh: 680, // 68.0 km/h
|
||||
wind_direction_deg: 270,
|
||||
temperature_centi_c: -350, // -3.50 °C
|
||||
humidity_pct: 85,
|
||||
rain_tips_accumulated: 12,
|
||||
vbat_mv: 3620,
|
||||
die_temp_deci_c: -15,
|
||||
davis_rx_count: 50,
|
||||
davis_miss_count: 1,
|
||||
};
|
||||
|
||||
let mut buf = [0u8; WeatherTelemetryPacket::SERIALIZED_LEN];
|
||||
packet.serialize(&mut buf);
|
||||
|
||||
let decoded = WeatherTelemetryPacket::deserialize(&buf).expect("Doit décoder");
|
||||
assert_eq!(packet, decoded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_telemetry_packet_crc_rejection() {
|
||||
let packet = WeatherTelemetryPacket {
|
||||
sequence_number: 1,
|
||||
timestamp_minutes: 10,
|
||||
wind_avg_deci_kmh: 0,
|
||||
wind_gust_deci_kmh: 0,
|
||||
wind_direction_deg: 0,
|
||||
temperature_centi_c: 2000,
|
||||
humidity_pct: 50,
|
||||
rain_tips_accumulated: 0,
|
||||
vbat_mv: 3700,
|
||||
die_temp_deci_c: 220,
|
||||
davis_rx_count: 10,
|
||||
davis_miss_count: 0,
|
||||
};
|
||||
|
||||
let mut buf = [0u8; WeatherTelemetryPacket::SERIALIZED_LEN];
|
||||
packet.serialize(&mut buf);
|
||||
|
||||
// Corrompt un octet
|
||||
buf[5] ^= 0xFF;
|
||||
|
||||
assert_eq!(WeatherTelemetryPacket::deserialize(&buf), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Gestionnaire de Diagnostics et Métriques de Santé Système (DiagManager)
|
||||
|
||||
use crate::boot::ResetReason;
|
||||
|
||||
/// Structure de métriques et compteurs de santé système
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SystemDiagnostics {
|
||||
pub last_reset_reason: ResetReason,
|
||||
pub davis_packets_received: u32,
|
||||
pub davis_crc_errors: u32,
|
||||
pub davis_sync_losses: u16,
|
||||
pub radio169_transmissions: u32,
|
||||
pub radio169_rx_commands: u16,
|
||||
pub queue_overflows: u32,
|
||||
pub last_vbat_mv: u16,
|
||||
pub last_die_temp_deci_c: i16,
|
||||
}
|
||||
|
||||
impl SystemDiagnostics {
|
||||
pub const fn new(reset_reason: ResetReason) -> Self {
|
||||
Self {
|
||||
last_reset_reason: reset_reason,
|
||||
davis_packets_received: 0,
|
||||
davis_crc_errors: 0,
|
||||
davis_sync_losses: 0,
|
||||
radio169_transmissions: 0,
|
||||
radio169_rx_commands: 0,
|
||||
queue_overflows: 0,
|
||||
last_vbat_mv: 0,
|
||||
last_die_temp_deci_c: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record_davis_rx(&mut self) {
|
||||
self.davis_packets_received = self.davis_packets_received.saturating_add(1);
|
||||
}
|
||||
|
||||
pub fn record_davis_crc_error(&mut self) {
|
||||
self.davis_crc_errors = self.davis_crc_errors.saturating_add(1);
|
||||
}
|
||||
|
||||
pub fn record_davis_sync_loss(&mut self) {
|
||||
self.davis_sync_losses = self.davis_sync_losses.saturating_add(1);
|
||||
}
|
||||
|
||||
pub fn record_169_tx(&mut self) {
|
||||
self.radio169_transmissions = self.radio169_transmissions.saturating_add(1);
|
||||
}
|
||||
|
||||
pub fn record_169_cmd(&mut self) {
|
||||
self.radio169_rx_commands = self.radio169_rx_commands.saturating_add(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Services système d'orchestration (Power, Schedule, Storage, Watchdog, Diagnostics)
|
||||
|
||||
pub mod diag_manager;
|
||||
pub mod power_manager;
|
||||
pub mod schedule_manager;
|
||||
pub mod storage_manager;
|
||||
pub mod watchdog_manager;
|
||||
|
||||
pub use diag_manager::SystemDiagnostics;
|
||||
pub use power_manager::{PowerManager, PowerState};
|
||||
pub use schedule_manager::{
|
||||
TimeWindowRule, TransmissionPolicyTable, MAX_RULES, POLICY_MAGIC, SAFE_FALLBACK_INTERVAL_S,
|
||||
};
|
||||
pub use storage_manager::{
|
||||
arbitrate_slots, FlashSlotHeader, PersistentStorageManager, PingPongArbitration, SlotStatus,
|
||||
StorageSlot, COMMIT_MARK_ERASED, COMMIT_MARK_VALID, FLASH_SLOT_A_ADDR, FLASH_SLOT_B_ADDR,
|
||||
STORAGE_MAGIC,
|
||||
};
|
||||
pub use watchdog_manager::WatchdogManager;
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Gestionnaire d'Énergie et transitions de sommeil (PowerManager - Stop 2)
|
||||
//!
|
||||
//! Orchestre le parking analogique des broches, la coupure des Load Switches,
|
||||
//! la programmation du mode Stop 2 avec rétention SRAM2 et le réveil rapide sur MSI.
|
||||
|
||||
use crate::hal::gpio::GpioController;
|
||||
use crate::hal::pwr::enter_stop2_hardware_sequence;
|
||||
|
||||
/// État du cycle de gestion d'énergie
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum PowerState {
|
||||
Active,
|
||||
PreparingSleep,
|
||||
InStop2,
|
||||
WakingUp,
|
||||
}
|
||||
|
||||
/// Structure d'orchestration du PowerManager
|
||||
pub struct PowerManager {
|
||||
state: PowerState,
|
||||
total_wakeups: u32,
|
||||
}
|
||||
|
||||
impl PowerManager {
|
||||
/// Initialise le gestionnaire d'énergie
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
state: PowerState::Active,
|
||||
total_wakeups: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// État courant de la gestion d'énergie
|
||||
#[inline(always)]
|
||||
pub fn current_state(&self) -> PowerState {
|
||||
self.state
|
||||
}
|
||||
|
||||
/// Nombre total de réveils depuis l'initialisation
|
||||
#[inline(always)]
|
||||
pub fn total_wakeups(&self) -> u32 {
|
||||
self.total_wakeups
|
||||
}
|
||||
|
||||
/// Séquence formelle d'entrée en mode Stop 2 ultra-basse consommation
|
||||
///
|
||||
/// 1. Parking analogique des GPIOs non-réveil
|
||||
/// 2. Armement de la rétention SRAM2 (`PWR_CR1.RRS = 1`)
|
||||
/// 3. Barrières DSB / ISB et exécution de WFI
|
||||
pub fn enter_stop2<G: GpioController>(&mut self, gpio: &mut G) -> Result<(), G::Error> {
|
||||
self.state = PowerState::PreparingSleep;
|
||||
|
||||
// Parking des broches GPIO pour éliminer les fuites parasites (~1.2 µA visé)
|
||||
gpio.park_non_wake_pins()?;
|
||||
|
||||
self.state = PowerState::InStop2;
|
||||
|
||||
// Séquence matérielle Stop 2 avec rétention SRAM2 et WFI
|
||||
enter_stop2_hardware_sequence();
|
||||
|
||||
// Sortie de WFI (Réveil immédiat par EXTI ou RTC)
|
||||
self.state = PowerState::WakingUp;
|
||||
self.total_wakeups = self.total_wakeups.saturating_add(1);
|
||||
self.state = PowerState::Active;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::hal::gpio::{PinId, PinMode, Pull, Speed};
|
||||
|
||||
struct MockGpio {
|
||||
parked: bool,
|
||||
}
|
||||
|
||||
impl GpioController for MockGpio {
|
||||
type Error = ();
|
||||
fn configure_pin(
|
||||
&mut self,
|
||||
_pin: PinId,
|
||||
_mode: PinMode,
|
||||
_pull: Pull,
|
||||
_speed: Speed,
|
||||
) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
fn park_non_wake_pins(&mut self) -> Result<(), Self::Error> {
|
||||
self.parked = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_power_manager_lifecycle() {
|
||||
let mut pm = PowerManager::new();
|
||||
let mut gpio = MockGpio { parked: false };
|
||||
|
||||
assert_eq!(pm.current_state(), PowerState::Active);
|
||||
assert_eq!(pm.total_wakeups(), 0);
|
||||
|
||||
let res = pm.enter_stop2(&mut gpio);
|
||||
assert!(res.is_ok());
|
||||
assert!(gpio.parked);
|
||||
assert_eq!(pm.current_state(), PowerState::Active);
|
||||
assert_eq!(pm.total_wakeups(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Moteur de politiques horaires de transmission (ScheduleManager)
|
||||
//!
|
||||
//! Gère la table de configuration des plages de transmission VHF 169 MHz,
|
||||
//! évalue l'intervalle selon l'heure UTC courante (minutes du jour) et applique
|
||||
//! un repli de sécurité déterministe (600s / 10 min) en cas d'invalidité.
|
||||
|
||||
use crate::protocol::crc::crc16_ccitt;
|
||||
|
||||
/// Magic identifiant la table binaire de politique ("POLY")
|
||||
pub const POLICY_MAGIC: u32 = 0x504F4C59;
|
||||
|
||||
/// Intervalle de repli de sécurité par défaut (10 minutes)
|
||||
pub const SAFE_FALLBACK_INTERVAL_S: u16 = 600;
|
||||
|
||||
/// Nombre maximal de règles de plages horaires dans la table
|
||||
pub const MAX_RULES: usize = 4;
|
||||
|
||||
/// Règle de plage horaire compacte (8 octets)
|
||||
#[repr(C, packed)]
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TimeWindowRule {
|
||||
pub start_hour: u8, // 0..23
|
||||
pub start_minute: u8, // 0..59
|
||||
pub end_hour: u8, // 0..23
|
||||
pub end_minute: u8, // 0..59
|
||||
pub interval_seconds: u16, // Intervalle d'émission pendant la plage (ex: 60s)
|
||||
pub flags: u16, // Réservé / Drapeaux futurs
|
||||
}
|
||||
|
||||
impl TimeWindowRule {
|
||||
/// Crée une nouvelle règle de plage horaire
|
||||
pub const fn new(
|
||||
start_hour: u8,
|
||||
start_minute: u8,
|
||||
end_hour: u8,
|
||||
end_minute: u8,
|
||||
interval_seconds: u16,
|
||||
) -> Self {
|
||||
Self {
|
||||
start_hour,
|
||||
start_minute,
|
||||
end_hour,
|
||||
end_minute,
|
||||
interval_seconds,
|
||||
flags: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Indique si la règle est syntaxiquement valide
|
||||
pub fn is_valid(&self) -> bool {
|
||||
self.start_hour < 24
|
||||
&& self.start_minute < 60
|
||||
&& self.end_hour < 24
|
||||
&& self.end_minute < 60
|
||||
&& self.interval_seconds > 0
|
||||
}
|
||||
|
||||
/// Évalue si la minute courante du jour (0..1439) est incluse dans la plage
|
||||
pub fn matches_minute_of_day(&self, current_minute_of_day: u16) -> bool {
|
||||
let start = (self.start_hour as u16) * 60 + (self.start_minute as u16);
|
||||
let end = (self.end_hour as u16) * 60 + (self.end_minute as u16);
|
||||
|
||||
if start <= end {
|
||||
// Plage intra-journée classique (ex: 06:00 -> 08:00)
|
||||
current_minute_of_day >= start && current_minute_of_day < end
|
||||
} else {
|
||||
// Plage à cheval sur minuit (ex: 22:00 -> 04:00)
|
||||
current_minute_of_day >= start || current_minute_of_day < end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Table binaire complète de politique de transmission
|
||||
#[repr(C, packed)]
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TransmissionPolicyTable {
|
||||
pub magic: u32,
|
||||
pub version: u16,
|
||||
pub num_rules: u8,
|
||||
pub default_interval_s: u16,
|
||||
pub rules: [TimeWindowRule; MAX_RULES],
|
||||
pub checksum: u16, // CRC-16 CCITT
|
||||
}
|
||||
|
||||
impl TransmissionPolicyTable {
|
||||
/// Crée une table de politique par défaut avec repli 10 minutes
|
||||
pub const fn default_safe() -> Self {
|
||||
let dummy_rule = TimeWindowRule::new(0, 0, 0, 0, SAFE_FALLBACK_INTERVAL_S);
|
||||
Self {
|
||||
magic: POLICY_MAGIC,
|
||||
version: 1,
|
||||
num_rules: 0,
|
||||
default_interval_s: SAFE_FALLBACK_INTERVAL_S,
|
||||
rules: [dummy_rule; MAX_RULES],
|
||||
checksum: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Calcule et met à jour le checksum CRC-16 CCITT de la table
|
||||
pub fn update_checksum(&mut self) {
|
||||
let bytes = unsafe {
|
||||
let ptr = self as *const Self as *const u8;
|
||||
// Taille de la structure moins les 2 octets du champ checksum
|
||||
let len = core::mem::size_of::<Self>() - 2;
|
||||
core::slice::from_raw_parts(ptr, len)
|
||||
};
|
||||
self.checksum = crc16_ccitt(bytes);
|
||||
}
|
||||
|
||||
/// Vérifie la conformité totale de la table (magic, limites, checksum)
|
||||
pub fn is_valid(&self) -> bool {
|
||||
if self.magic != POLICY_MAGIC || self.num_rules > (MAX_RULES as u8) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if self.default_interval_s == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
for i in 0..(self.num_rules as usize) {
|
||||
if !self.rules[i].is_valid() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = unsafe {
|
||||
let ptr = self as *const Self as *const u8;
|
||||
let len = core::mem::size_of::<Self>() - 2;
|
||||
core::slice::from_raw_parts(ptr, len)
|
||||
};
|
||||
crc16_ccitt(bytes) == self.checksum
|
||||
}
|
||||
|
||||
/// Évalue l'intervalle de transmission actif pour une minute du jour donnée (0..1439).
|
||||
///
|
||||
/// Retourne l'intervalle en secondes de la première règle concordante,
|
||||
/// ou `default_interval_s` hors plages, ou `SAFE_FALLBACK_INTERVAL_S` si la table est corrompue.
|
||||
pub fn evaluate_interval(&self, minute_of_day: u16) -> u16 {
|
||||
if !self.is_valid() {
|
||||
return SAFE_FALLBACK_INTERVAL_S;
|
||||
}
|
||||
|
||||
let n = self.num_rules as usize;
|
||||
for i in 0..n {
|
||||
if self.rules[i].matches_minute_of_day(minute_of_day) {
|
||||
return self.rules[i].interval_seconds;
|
||||
}
|
||||
}
|
||||
|
||||
self.default_interval_s
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_time_window_intra_day() {
|
||||
let rule = TimeWindowRule::new(6, 0, 8, 0, 60); // 06:00 -> 08:00
|
||||
assert!(rule.is_valid());
|
||||
|
||||
assert!(!rule.matches_minute_of_day(5 * 60 + 59)); // 05:59 -> faux
|
||||
assert!(rule.matches_minute_of_day(6 * 60)); // 06:00 -> vrai
|
||||
assert!(rule.matches_minute_of_day(7 * 60 + 30)); // 07:30 -> vrai
|
||||
assert!(!rule.matches_minute_of_day(8 * 60)); // 08:00 -> faux
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_time_window_cross_midnight() {
|
||||
let rule = TimeWindowRule::new(22, 0, 4, 0, 120); // 22:00 -> 04:00
|
||||
assert!(rule.is_valid());
|
||||
|
||||
assert!(rule.matches_minute_of_day(22 * 60)); // 22:00 -> vrai
|
||||
assert!(rule.matches_minute_of_day(23 * 60 + 59)); // 23:59 -> vrai
|
||||
assert!(rule.matches_minute_of_day(0)); // 00:00 -> vrai
|
||||
assert!(rule.matches_minute_of_day(3 * 60 + 59)); // 03:59 -> vrai
|
||||
assert!(!rule.matches_minute_of_day(4 * 60)); // 04:00 -> faux
|
||||
assert!(!rule.matches_minute_of_day(12 * 60)); // 12:00 -> faux
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_policy_table_evaluation_and_fallback() {
|
||||
let mut table = TransmissionPolicyTable::default_safe();
|
||||
table.default_interval_s = 600;
|
||||
table.num_rules = 1;
|
||||
table.rules[0] = TimeWindowRule::new(6, 0, 8, 0, 60);
|
||||
table.update_checksum();
|
||||
|
||||
assert!(table.is_valid());
|
||||
|
||||
// À 07:00 -> 60s
|
||||
assert_eq!(table.evaluate_interval(7 * 60), 60);
|
||||
// À 12:00 -> 600s (default)
|
||||
assert_eq!(table.evaluate_interval(12 * 60), 600);
|
||||
|
||||
// Corrompre le checksum -> repli safe 600s
|
||||
table.checksum ^= 0xFFFF;
|
||||
assert!(!table.is_valid());
|
||||
assert_eq!(table.evaluate_interval(7 * 60), SAFE_FALLBACK_INTERVAL_S);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
//! Architecture de persistance Flash Ping-Pong A/B (StorageManager)
|
||||
//!
|
||||
//! Assure la sauvegarde sécurisée et atomique de la configuration et des états
|
||||
//! sur deux pages Flash indépendantes de 2 Ko (Pages 510 et 511), avec numéro
|
||||
//! de séquence monotone, contrôle CRC32 et mot double de validation (commit mark).
|
||||
|
||||
use crate::hal::flash::FLASH_PAGE_SIZE;
|
||||
|
||||
/// Magic identifiant l'en-tête de persistance Flash ("GWST")
|
||||
pub const STORAGE_MAGIC: u32 = 0x47575354;
|
||||
|
||||
/// Valeur du mot double de validation écrit en dernier pour valider une page
|
||||
pub const COMMIT_MARK_VALID: u64 = 0x55AA55AA_55AA55AA;
|
||||
|
||||
/// Valeur d'une cellule Flash effacée
|
||||
pub const COMMIT_MARK_ERASED: u64 = 0xFFFF_FFFF_FFFF_FFFF;
|
||||
|
||||
/// Adresses des deux pages Flash réservées (STM32L476 1 Mo)
|
||||
pub const FLASH_SLOT_A_ADDR: u32 = 0x080F_E000; // Page 510
|
||||
pub const FLASH_SLOT_B_ADDR: u32 = 0x080F_F000; // Page 511
|
||||
|
||||
/// En-tête structuré d'un slot de persistance Flash (Alignement 64 bits obligatoire - 24 octets)
|
||||
///
|
||||
/// Composé exactement de 3 mots doubles de 64 bits :
|
||||
/// - Mot 1 : `magic` (32b) + `sequence_number` (32b)
|
||||
/// - Mot 2 : `payload_len` (16b) + `payload_version` (16b) + `crc32` (32b)
|
||||
/// - Mot 3 : `commit_mark` (64b)
|
||||
#[repr(C, align(8))]
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FlashSlotHeader {
|
||||
pub magic: u32, // 0x47575354 ("GWST")
|
||||
pub sequence_number: u32, // Numéro de séquence strictement croissant
|
||||
pub payload_len: u16, // Taille de la charge utile en octets
|
||||
pub payload_version: u16, // Version du schéma
|
||||
pub crc32: u32, // CRC-32 IEEE du payload
|
||||
pub commit_mark: u64, // Mot double programmé en tout dernier
|
||||
}
|
||||
|
||||
impl FlashSlotHeader {
|
||||
/// Taille en octets du header Flash (24 octets = 3 mots de 64 bits)
|
||||
pub const SIZE: usize = core::mem::size_of::<Self>();
|
||||
|
||||
/// Crée un nouvel en-tête prêt pour l'écriture (non commité)
|
||||
pub const fn new_uncommitted(sequence_number: u32, payload_len: u16, payload_version: u16, crc32: u32) -> Self {
|
||||
Self {
|
||||
magic: STORAGE_MAGIC,
|
||||
sequence_number,
|
||||
payload_len,
|
||||
payload_version,
|
||||
crc32,
|
||||
commit_mark: COMMIT_MARK_ERASED,
|
||||
}
|
||||
}
|
||||
|
||||
/// Vérifie si l'en-tête est formellement valide et commité
|
||||
pub fn is_valid_committed(&self) -> bool {
|
||||
self.magic == STORAGE_MAGIC
|
||||
&& self.commit_mark == COMMIT_MARK_VALID
|
||||
&& (self.payload_len as usize) <= (FLASH_PAGE_SIZE - Self::SIZE)
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifiant de slot Ping-Pong
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum StorageSlot {
|
||||
SlotA,
|
||||
SlotB,
|
||||
}
|
||||
|
||||
impl StorageSlot {
|
||||
/// Retourne l'adresse physique Flash du début du slot
|
||||
pub const fn base_address(&self) -> u32 {
|
||||
match self {
|
||||
StorageSlot::SlotA => FLASH_SLOT_A_ADDR,
|
||||
StorageSlot::SlotB => FLASH_SLOT_B_ADDR,
|
||||
}
|
||||
}
|
||||
|
||||
/// Retourne le slot opposé
|
||||
pub const fn opposite(&self) -> Self {
|
||||
match self {
|
||||
StorageSlot::SlotA => StorageSlot::SlotB,
|
||||
StorageSlot::SlotB => StorageSlot::SlotA,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// État de santé d'un slot Flash
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SlotStatus {
|
||||
pub slot: StorageSlot,
|
||||
pub is_valid: bool,
|
||||
pub sequence_number: u32,
|
||||
pub payload_len: u16,
|
||||
}
|
||||
|
||||
/// Résultat de l'arbitrage Ping-Pong au démarrage
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PingPongArbitration {
|
||||
/// Slot actif contenant la configuration valide la plus récente
|
||||
pub active_slot: Option<StorageSlot>,
|
||||
/// Slot cible pour la prochaine écriture
|
||||
pub next_target_slot: StorageSlot,
|
||||
/// Prochain numéro de séquence à utiliser
|
||||
pub next_sequence_number: u32,
|
||||
}
|
||||
|
||||
/// Arbitre l'état des deux slots Flash pour déterminer le slot actif et le slot cible
|
||||
pub fn arbitrate_slots(status_a: SlotStatus, status_b: SlotStatus) -> PingPongArbitration {
|
||||
match (status_a.is_valid, status_b.is_valid) {
|
||||
(true, true) => {
|
||||
// Les deux slots sont valides : on choisit le plus récent selon sequence_number
|
||||
if status_a.sequence_number >= status_b.sequence_number {
|
||||
PingPongArbitration {
|
||||
active_slot: Some(StorageSlot::SlotA),
|
||||
next_target_slot: StorageSlot::SlotB,
|
||||
next_sequence_number: status_a.sequence_number.saturating_add(1),
|
||||
}
|
||||
} else {
|
||||
PingPongArbitration {
|
||||
active_slot: Some(StorageSlot::SlotB),
|
||||
next_target_slot: StorageSlot::SlotA,
|
||||
next_sequence_number: status_b.sequence_number.saturating_add(1),
|
||||
}
|
||||
}
|
||||
}
|
||||
(true, false) => PingPongArbitration {
|
||||
active_slot: Some(StorageSlot::SlotA),
|
||||
next_target_slot: StorageSlot::SlotB,
|
||||
next_sequence_number: status_a.sequence_number.saturating_add(1),
|
||||
},
|
||||
(false, true) => PingPongArbitration {
|
||||
active_slot: Some(StorageSlot::SlotB),
|
||||
next_target_slot: StorageSlot::SlotA,
|
||||
next_sequence_number: status_b.sequence_number.saturating_add(1),
|
||||
},
|
||||
(false, false) => PingPongArbitration {
|
||||
active_slot: None,
|
||||
next_target_slot: StorageSlot::SlotA,
|
||||
next_sequence_number: 1,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Contrat du gestionnaire de persistance
|
||||
pub trait PersistentStorageManager {
|
||||
type Error;
|
||||
|
||||
/// Initialise et inspecte les deux slots au démarrage
|
||||
fn init(&mut self) -> Result<PingPongArbitration, Self::Error>;
|
||||
|
||||
/// Charge la charge utile depuis le slot actif
|
||||
fn read_active_payload(&self, out: &mut [u8]) -> Result<usize, Self::Error>;
|
||||
|
||||
/// Sauvegarde une nouvelle charge utile de manière atomique sur le slot inactif
|
||||
fn write_payload(&mut self, payload: &[u8], version: u16) -> Result<(), Self::Error>;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_header_size_and_alignment() {
|
||||
assert_eq!(FlashSlotHeader::SIZE, 24);
|
||||
assert_eq!(core::mem::align_of::<FlashSlotHeader>(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_arbitrate_slots_both_valid() {
|
||||
let status_a = SlotStatus {
|
||||
slot: StorageSlot::SlotA,
|
||||
is_valid: true,
|
||||
sequence_number: 12,
|
||||
payload_len: 64,
|
||||
};
|
||||
let status_b = SlotStatus {
|
||||
slot: StorageSlot::SlotB,
|
||||
is_valid: true,
|
||||
sequence_number: 13,
|
||||
payload_len: 64,
|
||||
};
|
||||
|
||||
let arb = arbitrate_slots(status_a, status_b);
|
||||
assert_eq!(arb.active_slot, Some(StorageSlot::SlotB));
|
||||
assert_eq!(arb.next_target_slot, StorageSlot::SlotA);
|
||||
assert_eq!(arb.next_sequence_number, 14);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_arbitrate_slots_one_corrupted() {
|
||||
let status_a = SlotStatus {
|
||||
slot: StorageSlot::SlotA,
|
||||
is_valid: true,
|
||||
sequence_number: 5,
|
||||
payload_len: 64,
|
||||
};
|
||||
let status_b = SlotStatus {
|
||||
slot: StorageSlot::SlotB,
|
||||
is_valid: false, // Coupure pendant écriture
|
||||
sequence_number: 6,
|
||||
payload_len: 64,
|
||||
};
|
||||
|
||||
let arb = arbitrate_slots(status_a, status_b);
|
||||
assert_eq!(arb.active_slot, Some(StorageSlot::SlotA));
|
||||
assert_eq!(arb.next_target_slot, StorageSlot::SlotB);
|
||||
assert_eq!(arb.next_sequence_number, 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_arbitrate_slots_fresh_flash() {
|
||||
let status_a = SlotStatus {
|
||||
slot: StorageSlot::SlotA,
|
||||
is_valid: false,
|
||||
sequence_number: 0,
|
||||
payload_len: 0,
|
||||
};
|
||||
let status_b = SlotStatus {
|
||||
slot: StorageSlot::SlotB,
|
||||
is_valid: false,
|
||||
sequence_number: 0,
|
||||
payload_len: 0,
|
||||
};
|
||||
|
||||
let arb = arbitrate_slots(status_a, status_b);
|
||||
assert_eq!(arb.active_slot, None);
|
||||
assert_eq!(arb.next_target_slot, StorageSlot::SlotA);
|
||||
assert_eq!(arb.next_sequence_number, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Gestionnaire du Chien de Garde et intégrité système (WatchdogManager)
|
||||
|
||||
use crate::hal::iwdg::WatchdogDriver;
|
||||
|
||||
/// Gestionnaire d'orchestration de la surveillance watchdog
|
||||
pub struct WatchdogManager {
|
||||
timeout_ms: u32,
|
||||
kick_count: u32,
|
||||
}
|
||||
|
||||
impl WatchdogManager {
|
||||
/// Crée un nouveau gestionnaire de watchdog (défaut 8000 ms)
|
||||
pub const fn new(timeout_ms: u32) -> Self {
|
||||
Self {
|
||||
timeout_ms,
|
||||
kick_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Démarre le watchdog matériel
|
||||
pub fn start<W: WatchdogDriver>(&mut self, watchdog: &mut W) {
|
||||
watchdog.start(self.timeout_ms);
|
||||
}
|
||||
|
||||
/// Rafraîchit le watchdog matériel
|
||||
pub fn feed<W: WatchdogDriver>(&mut self, watchdog: &mut W) {
|
||||
watchdog.feed();
|
||||
self.kick_count = self.kick_count.saturating_add(1);
|
||||
}
|
||||
|
||||
/// Nombre total de rafraîchissements effectués
|
||||
#[inline(always)]
|
||||
pub fn kick_count(&self) -> u32 {
|
||||
self.kick_count
|
||||
}
|
||||
}
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur