diff --git a/boards/esp/src/ble/transport.rs b/boards/esp/src/ble/transport.rs index f99c34e..68aa524 100644 --- a/boards/esp/src/ble/transport.rs +++ b/boards/esp/src/ble/transport.rs @@ -966,8 +966,9 @@ mod hardware { // so give it the current state now instead of at the next update. // Not at once: a notification sent right as the CCCD write is // accepted is lost before the app's notification stream is - // listening (seen on Android). The CAN access state follows through - // BLE_TX_CHANNEL, and is repeated every few seconds anyway. + // listening (seen on Android). The CAN access state, command + // availability and bus health follow through BLE_TX_CHANNEL, and are + // repeated every few seconds anyway. Either3::Third(()) => { embassy_time::Timer::after(embassy_time::Duration::from_millis( SUBSCRIBE_RESEND_DELAY_MS, @@ -975,6 +976,7 @@ mod hardware { .await; core_interface::resend_can_access_state(); core_interface::resend_command_availability(); + core_interface::resend_can_bus_health(); match core_interface::latest_ble_state() { Some(msg) => msg, None => continue, diff --git a/boards/esp/src/can.rs b/boards/esp/src/can.rs index 2dcce01..a94196d 100644 --- a/boards/esp/src/can.rs +++ b/boards/esp/src/can.rs @@ -209,6 +209,10 @@ mod hardware { loop { if core_interface::is_can_bus_listen_only(bus_id) != listen_only { + // End the window under the mode it ran in, so the app sees the new + // mode at once instead of at the end of the window. + end_rx_window(bus_id, listen_only, stats, *next_report); + *next_report = Instant::now() + RX_STATS_INTERVAL; return; } @@ -228,14 +232,14 @@ mod hardware { }; core_interface::log_can_frame(&core_frame); let matched = core_interface::passes_filter(&core_frame, filters); - stats.record_frame(matched); + stats.counts.record_frame(matched); // The vehicle doesn't see frames while SavvyCAN has the buses. if matched && !core_interface::is_can_logging() { CAN_RX_CHANNEL.sender().send(core_frame).await; } } Either4::First(Err(EspTwaiError::BusOff)) => { - stats.record_bus_off(); + stats.counts.record_bus_off(); // A bus fault relocks every bus: the vehicle has to validate the car // again before it can transmit. core_interface::set_can_read_only(true); @@ -243,11 +247,14 @@ mod hardware { "CAN bus {}: TWAI bus-off, buses relocked, restarting controller in 1s", bus_id ); + // Report the bus-off now rather than at the end of the window. + end_rx_window(bus_id, listen_only, stats, *next_report); + *next_report = Instant::now() + RX_STATS_INTERVAL; Timer::after(Duration::from_secs(1)).await; return; } Either4::First(Err(EspTwaiError::EmbeddedHAL(twai::ErrorKind::Overrun))) => { - stats.record_overrun(); + stats.counts.record_overrun(); log::warn!("CAN bus {}: TWAI RX overrun, frames dropped", bus_id); twai.clear_receive_fifo(); } @@ -259,7 +266,7 @@ mod hardware { // The flag is re-checked at the top of the loop. Either4::Third(_) => {} Either4::Fourth(()) => { - log_rx_stats(bus_id, listen_only, &stats.take()); + end_rx_window(bus_id, listen_only, stats, *next_report); *next_report = Instant::now() + RX_STATS_INTERVAL; } } @@ -284,33 +291,55 @@ mod hardware { type TwaiRxStats = crate::can::RxStats; - /// Logs one RX stats window. A silent bus logs zeros, so "no data" is visible on the + /// Ends one RX stats window: logs it, and reports it for the bus health the app shows. + /// Called every [`RX_STATS_INTERVAL`], and early on a mode change or a bus-off, so the + /// log line can cover less than the interval. `next_report` is when the window was due + /// to end: it started one [`RX_STATS_INTERVAL`] before that. + fn end_rx_window( + bus_id: u8, + listen_only: bool, + stats: &mut TwaiRxStats, + next_report: embassy_time::Instant, + ) { + let window = stats.take(); + let started = next_report - RX_STATS_INTERVAL; + let window_ms = embassy_time::Instant::now() + .saturating_duration_since(started) + .as_millis(); + log_rx_stats(bus_id, listen_only, &window, window_ms); + core_interface::report_can_bus_window(bus_id, &window.counts, window_ms, Some(listen_only)); + } + + /// Logs one RX stats window, `window_ms` long (to a tenth of a second: a mode change or + /// a bus-off ends it early). A silent bus logs zeros, so "no data" is visible on the /// serial console; errors without frames usually mean a wrong bitrate or wiring. - fn log_rx_stats(bus_id: u8, listen_only: bool, stats: &TwaiRxStats) { + fn log_rx_stats(bus_id: u8, listen_only: bool, stats: &TwaiRxStats, window_ms: u64) { let mode = if listen_only { "listen-only" } else { "normal" }; - let secs = RX_STATS_INTERVAL.as_secs(); + let (secs, tenths) = (window_ms / 1000, window_ms % 1000 / 100); match stats.last_error { Some(e) => log::info!( - "CAN bus {} ({}), last {}s: {} frames, {} matched filters, {} RX errors (last: {:?}), {} overruns, {} bus-offs", + "CAN bus {} ({}), last {}.{}s: {} frames, {} matched filters, {} RX errors (last: {:?}), {} overruns, {} bus-offs", bus_id, mode, secs, - stats.received, - stats.matched, - stats.errors, + tenths, + stats.counts.received, + stats.counts.matched, + stats.counts.errors, e, - stats.overruns, - stats.bus_offs + stats.counts.overruns, + stats.counts.bus_offs ), None => log::info!( - "CAN bus {} ({}), last {}s: {} frames, {} matched filters, 0 RX errors, {} overruns, {} bus-offs", + "CAN bus {} ({}), last {}.{}s: {} frames, {} matched filters, 0 RX errors, {} overruns, {} bus-offs", bus_id, mode, secs, - stats.received, - stats.matched, - stats.overruns, - stats.bus_offs + tenths, + stats.counts.received, + stats.counts.matched, + stats.counts.overruns, + stats.counts.bus_offs ), } } @@ -537,16 +566,14 @@ mod hardware { #[cfg(feature = "hardware")] pub use hardware::*; -/// RX counters behind the periodic CAN health log. `take` returns them and starts a fresh -/// window, so each log line covers one reporting interval. `E` is the driver's error type. +/// RX counters behind the periodic CAN health log and the bus health sent to the app +/// (`core_interface::report_can_bus_window`), plus the last RX error for the log. `take` +/// returns them and starts a fresh window, so each report covers one interval. `E` is the +/// driver's error type. #[cfg_attr(not(feature = "hardware"), allow(dead_code))] #[derive(Debug, PartialEq)] pub(crate) struct RxStats { - pub received: u32, - pub matched: u32, - pub errors: u32, - pub overruns: u32, - pub bus_offs: u32, + pub counts: core_interface::CanRxCounts, pub last_error: Option, } @@ -554,35 +581,16 @@ pub(crate) struct RxStats { impl RxStats { pub const fn new() -> Self { Self { - received: 0, - matched: 0, - errors: 0, - overruns: 0, - bus_offs: 0, + counts: core_interface::CanRxCounts::new(), last_error: None, } } - pub fn record_frame(&mut self, matched: bool) { - self.received = self.received.saturating_add(1); - if matched { - self.matched = self.matched.saturating_add(1); - } - } - pub fn record_error(&mut self, error: E) { - self.errors = self.errors.saturating_add(1); + self.counts.record_error(); self.last_error = Some(error); } - pub fn record_overrun(&mut self) { - self.overruns = self.overruns.saturating_add(1); - } - - pub fn record_bus_off(&mut self) { - self.bus_offs = self.bus_offs.saturating_add(1); - } - pub fn take(&mut self) -> Self { core::mem::replace(self, Self::new()) } @@ -745,46 +753,26 @@ mod tests { } #[test] - fn rx_stats_count_frames_and_errors() { + fn rx_stats_count_errors_and_keep_the_last() { let mut stats = RxStats::<&str>::new(); - stats.record_frame(true); - stats.record_frame(false); + stats.counts.record_frame(true); stats.record_error("bit"); stats.record_error("stuff"); - stats.record_overrun(); - stats.record_bus_off(); - assert_eq!( - stats, - RxStats { - received: 2, - matched: 1, - errors: 2, - overruns: 1, - bus_offs: 1, - last_error: Some("stuff"), - } - ); + assert_eq!(stats.counts.errors, 2); + assert_eq!(stats.last_error, Some("stuff")); } #[test] fn rx_stats_take_starts_a_new_window() { let mut stats = RxStats::<&str>::new(); - stats.record_frame(true); + stats.counts.record_frame(true); stats.record_error("bit"); let report = stats.take(); - assert_eq!(report.received, 1); + assert_eq!(report.counts.received, 1); assert_eq!(report.last_error, Some("bit")); assert_eq!(stats, RxStats::new()); } - #[test] - fn rx_stats_saturate_instead_of_wrapping() { - let mut stats = RxStats::<&str>::new(); - stats.received = u32::MAX; - stats.record_frame(false); - assert_eq!(stats.received, u32::MAX); - } - /// Minimal stand-in for a driver's frame type. struct TestFrame { id: Id, diff --git a/boards/esp/src/lib.rs b/boards/esp/src/lib.rs index b9353bd..eff6fb6 100644 --- a/boards/esp/src/lib.rs +++ b/boards/esp/src/lib.rs @@ -60,6 +60,7 @@ mod hardware { spawner.spawn(core_interface::publish_state_task().unwrap()); spawner.spawn(core_interface::publish_can_access_task().unwrap()); spawner.spawn(core_interface::publish_command_availability_task().unwrap()); + spawner.spawn(core_interface::publish_can_bus_health_task().unwrap()); spawner.spawn(system_command_task().unwrap()); core_interface::set_random_source(fill_random); } diff --git a/boards/pc/src/can.rs b/boards/pc/src/can.rs index 3f48daf..4cdebb8 100644 --- a/boards/pc/src/can.rs +++ b/boards/pc/src/can.rs @@ -1,9 +1,9 @@ #[cfg(target_os = "linux")] mod linux_can { use core_interface::{CAN_RX_CHANNEL, CanFilter, CanFrame}; - use embassy_time::{Duration, Timer}; + use embassy_time::{Duration, Instant, Timer}; use embedded_can::{Frame as EmbeddedFrame, Id}; - use socketcan::{CanSocket, Socket}; + use socketcan::{CanError, CanSocket, Socket, SocketOptions}; use std::io::ErrorKind; /// Converts a received `socketcan::CanDataFrame` into a `core_interface::CanFrame`, @@ -38,6 +38,25 @@ mod linux_can { } } + /// How often each bus reports its RX counters for the bus health the app shows. + const RX_STATS_INTERVAL: Duration = Duration::from_secs(5); + + /// Counts one SocketCAN error frame: a bus-off, a receive buffer overflow, or else a + /// receive error. + pub(crate) fn record_error_frame(counts: &mut core_interface::CanRxCounts, error: &CanError) { + use socketcan::ErrorCause; + use socketcan::errors::ControllerProblems; + if error.causes().any(|c| matches!(c, ErrorCause::BusOff)) { + counts.record_bus_off(); + } else if error.causes().any(|c| { + matches!(c, ErrorCause::Controller(p) if p.contains(ControllerProblems::RX_OVERFLOW)) + }) { + counts.record_overrun(); + } else { + counts.record_error(); + } + } + /// Opens a SocketCAN socket on `interface` and runs a bidirectional CAN loop /// for bus number `bus_id`. Up to 4 concurrent instances are supported (`pool_size`). /// @@ -45,6 +64,8 @@ mod linux_can { /// received frames against `filters` and forwards matches to `CAN_RX_CHANNEL`. /// - TX: After each RX poll, drains this bus's `CAN_TX_CHANNELS` entry and writes /// the frames to the socket. + /// - Health: counts frames and error frames, and reports them every 5 s for the bus + /// health the app shows (`core_interface::report_can_bus_window`). /// /// If the interface cannot be opened (e.g. it does not exist), the task logs a /// warning and retries every 5 seconds so the rest of the system keeps running. @@ -84,24 +105,49 @@ mod linux_can { return; }; + // Error frames feed the bus health. A virtual (vcan) bus never sends any. + if let Err(e) = socket.set_error_filter_accept_all() { + log::warn!( + "CAN bus {}: no error frames from '{}': {}", + bus_id, + interface, + e + ); + } + let mut counts = core_interface::CanRxCounts::new(); + let mut next_report = Instant::now() + RX_STATS_INTERVAL; + loop { Timer::after(Duration::from_millis(1)).await; + if Instant::now() >= next_report { + // The window started one interval before it was due. + let window_ms = Instant::now() + .saturating_duration_since(next_report - RX_STATS_INTERVAL) + .as_millis(); + // SocketCAN has no listen-only mode here: read-only drops TX in software. + core_interface::report_can_bus_window(bus_id, &counts.take(), window_ms, None); + next_report = Instant::now() + RX_STATS_INTERVAL; + } + // RX: drain all available frames from the kernel rx buffer loop { match socket.read_frame() { Ok(socketcan::CanFrame::Data(f)) => { let core_frame = socketcan_to_core_frame(&f, bus_id); core_interface::log_can_frame(&core_frame); + let matched = core_interface::passes_filter(&core_frame, filters); + counts.record_frame(matched); // The vehicle doesn't see frames while SavvyCAN has the buses. - if core_interface::passes_filter(&core_frame, filters) - && !core_interface::is_can_logging() - { + if matched && !core_interface::is_can_logging() { CAN_RX_CHANNEL.sender().send(core_frame).await; } } - // Remote frames and error frames are ignored - Ok(_) => {} + Ok(socketcan::CanFrame::Error(f)) => { + record_error_frame(&mut counts, &f.into_error()); + } + // Remote frames are ignored + Ok(socketcan::CanFrame::Remote(_)) => {} Err(ref e) if e.kind() == ErrorKind::WouldBlock => break, Err(_) => break, } @@ -126,6 +172,25 @@ mod linux_can { #[cfg(test)] mod tests { use super::*; + + fn counted(error: CanError) -> core_interface::CanRxCounts { + let mut counts = core_interface::CanRxCounts::new(); + record_error_frame(&mut counts, &error); + counts + } + + #[test] + fn error_frames_are_counted_by_cause() { + use socketcan::ErrorCause; + use socketcan::errors::ControllerProblems; + assert_eq!(counted(CanError::new(ErrorCause::BusOff)).bus_offs, 1); + let overflow = ErrorCause::Controller(ControllerProblems::RX_OVERFLOW); + assert_eq!(counted(CanError::new(overflow)).overruns, 1); + let both = CanError::from_multiple(overflow, [ErrorCause::BusOff]); + assert_eq!(counted(both.clone()).bus_offs, 1); + assert_eq!(counted(both).overruns, 0); + assert_eq!(counted(CanError::new(ErrorCause::NoAck)).errors, 1); + } use embedded_can::{ExtendedId, StandardId}; fn sc_std_frame(raw_id: u16, data: &[u8]) -> socketcan::CanDataFrame { @@ -249,7 +314,7 @@ pub use linux_can::socket_can_task; #[cfg(not(target_os = "linux"))] mod dummy_can { use core_interface::CanFilter; - use embassy_time::{Duration, Timer}; + use embassy_time::{Duration, Instant, Timer}; #[embassy_executor::task(pool_size = 4)] pub async fn socket_can_task( diff --git a/boards/pc/src/lib.rs b/boards/pc/src/lib.rs index a920cef..4ebaf33 100644 --- a/boards/pc/src/lib.rs +++ b/boards/pc/src/lib.rs @@ -21,6 +21,7 @@ pub fn start(spawner: &embassy_executor::Spawner) { spawner.spawn(core_interface::publish_state_task().unwrap()); spawner.spawn(core_interface::publish_can_access_task().unwrap()); spawner.spawn(core_interface::publish_command_availability_task().unwrap()); + spawner.spawn(core_interface::publish_can_bus_health_task().unwrap()); spawner.spawn(can_rw_approval_store_task().unwrap()); spawner.spawn(phone_validations_store_task().unwrap()); core_interface::set_random_source(fill_random); diff --git a/contracts b/contracts index 36bedc2..1faf470 160000 --- a/contracts +++ b/contracts @@ -1 +1 @@ -Subproject commit 36bedc221243f775514609f0212f7c9ea597904a +Subproject commit 1faf470ab2490fdb73bd65da092798396a26bef8 diff --git a/core-interface/src/can_health.rs b/core-interface/src/can_health.rs new file mode 100644 index 0000000..2598edb --- /dev/null +++ b/core-interface/src/can_health.rs @@ -0,0 +1,341 @@ +//! CAN bus health, reported to the app over BLE (`SystemState.can_bus_health`). +//! +//! Each board CAN driver counts what it receives over a short window ([`CanRxCounts`]) +//! and hands the window to [`report_can_bus_window`] when it ends. This module keeps +//! running totals per bus, judges each window ([`can_bus_status`]) and publishes the +//! result with [`publish_can_bus_health_task`]. Boards never build protos; vehicles +//! never see any of it. + +use core::cell::RefCell; + +use embassy_sync::blocking_mutex::Mutex; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::signal::Signal; +use embassy_time::{Duration, Instant, Timer}; + +use crate::channels::MAX_CAN_BUSES; +use crate::proto; + +/// RX counters over one window of a bus driver. Saturating, never wrapping. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CanRxCounts { + /// Frames received. + pub received: u32, + /// Frames the vehicle's filters accepted. + pub matched: u32, + /// Receive errors (bit, stuff, form, CRC, acknowledge...). + pub errors: u32, + /// Receive queue overflows (frames dropped). + pub overruns: u32, + /// Times the controller went bus-off. + pub bus_offs: u32, +} + +impl CanRxCounts { + pub const fn new() -> Self { + Self { + received: 0, + matched: 0, + errors: 0, + overruns: 0, + bus_offs: 0, + } + } + + pub fn record_frame(&mut self, matched: bool) { + self.received = self.received.saturating_add(1); + if matched { + self.matched = self.matched.saturating_add(1); + } + } + + pub fn record_error(&mut self) { + self.errors = self.errors.saturating_add(1); + } + + pub fn record_overrun(&mut self) { + self.overruns = self.overruns.saturating_add(1); + } + + pub fn record_bus_off(&mut self) { + self.bus_offs = self.bus_offs.saturating_add(1); + } + + /// Returns the counters and starts a new window. + pub fn take(&mut self) -> Self { + core::mem::take(self) + } + + fn add(&mut self, other: &Self) { + self.received = self.received.saturating_add(other.received); + self.matched = self.matched.saturating_add(other.matched); + self.errors = self.errors.saturating_add(other.errors); + self.overruns = self.overruns.saturating_add(other.overruns); + self.bus_offs = self.bus_offs.saturating_add(other.bus_offs); + } +} + +/// Judges one window of a bus. A bus-off outranks everything; errors with no frame at +/// all usually mean a wrong bitrate, a CAN FD bus or a wiring fault. +pub fn can_bus_status(window: &CanRxCounts) -> proto::CanBusStatus { + use proto::CanBusStatus as S; + if window.bus_offs > 0 { + S::BusOff + } else if window.received == 0 && window.errors > 0 { + S::NoValidFrames + } else if window.errors > 0 || window.overruns > 0 { + S::Degraded + } else if window.received == 0 { + S::Silent + } else { + S::Ok + } +} + +/// Frames per second over a window of `window_ms`, rounded down and saturating. None for +/// an empty window, whose rate means nothing. +pub fn frames_per_second(window: &CanRxCounts, window_ms: u64) -> Option { + if window_ms == 0 { + return None; + } + let rate = u64::from(window.received) * 1000 / window_ms; + Some(u32::try_from(rate).unwrap_or(u32::MAX)) +} + +/// What is known about one bus: totals since boot and the last window's verdict and +/// rate. Only the error totals are sent: a frame total would saturate on a busy bus. +#[derive(Debug, Clone, Copy, PartialEq)] +struct BusHealth { + totals: CanRxCounts, + status: proto::CanBusStatus, + listen_only: Option, + frames_per_second: Option, +} + +impl BusHealth { + fn to_proto(self) -> proto::CanBusHealth { + proto::CanBusHealth { + status: Some(self.status as i32), + listen_only: self.listen_only, + frames_per_second: self.frames_per_second, + rx_errors: Some(self.totals.errors), + overruns: Some(self.totals.overruns), + bus_offs: Some(self.totals.bus_offs), + } + } +} + +type Buses = [Option; MAX_CAN_BUSES]; + +static BUSES: Mutex> = + Mutex::new(RefCell::new([None; MAX_CAN_BUSES])); + +/// Wakes the publisher when a bus reports, or when the app subscribes. +static CAN_HEALTH_CHANGED: Signal = Signal::new(); + +/// Records the end of one RX window of `bus_id`, `window_ms` long. Called by board CAN +/// drivers, every few seconds and right after a bus-off. `listen_only` is whether the +/// controller ran in hardware listen-only mode, or `None` for a driver that has no such +/// mode. Never blocks. Ignores a bus id beyond [`MAX_CAN_BUSES`]. +pub fn report_can_bus_window( + bus_id: u8, + window: &CanRxCounts, + window_ms: u64, + listen_only: Option, +) { + let reported = BUSES.lock(|buses| { + let mut buses = buses.borrow_mut(); + let Some(slot) = buses.get_mut(bus_id as usize) else { + return false; + }; + let mut totals = slot.map(|bus| bus.totals).unwrap_or_default(); + totals.add(window); + *slot = Some(BusHealth { + totals, + status: can_bus_status(window), + listen_only, + frames_per_second: frames_per_second(window, window_ms), + }); + true + }); + if reported { + CAN_HEALTH_CHANGED.signal(()); + } +} + +/// The health of every bus that has reported, by bus id. +pub fn can_bus_health() -> alloc::collections::BTreeMap { + BUSES.lock(|buses| { + buses + .borrow() + .iter() + .enumerate() + .filter_map(|(id, bus)| Some((id as u32, bus.as_ref()?.to_proto()))) + .collect() + }) +} + +/// A state update carrying only [`can_bus_health`]. +pub fn can_bus_health_state_update(timestamp_ms: u64) -> proto::DeviceToApp { + proto::DeviceToApp { + timestamp_ms, + platform_id: crate::platform_id(), + payload: Some(proto::device_to_app::Payload::StateUpdate( + proto::StateUpdate { + system_state: Some(proto::SystemState { + can_bus_health: can_bus_health(), + ..Default::default() + }), + vehicle_state: None, + }, + )), + } +} + +/// How often the bus health is sent at most while no bus changes status, and at least +/// while nothing changes at all (a message sent as the app subscribes can be lost). +/// Matches the boards' RX report window, so the counters reach the app about as often +/// as they are reported. +pub const CAN_BUS_HEALTH_REPEAT_MS: u64 = 5_000; + +/// The statuses last queued for the app (per bus: status and listen-only), and when. +type Summary = [Option<(proto::CanBusStatus, Option)>; MAX_CAN_BUSES]; + +static LAST_PUBLISHED: Mutex>> = + Mutex::new(RefCell::new(None)); + +fn summary() -> Summary { + BUSES.lock(|buses| { + buses + .borrow() + .map(|bus| bus.map(|b| (b.status, b.listen_only))) + }) +} + +/// Queues [`can_bus_health_state_update`] on BLE when a bus changed status (or appeared) +/// since the last one queued, or when that was [`CAN_BUS_HEALTH_REPEAT_MS`] or more ago. +/// Counters alone don't make it due sooner, so a busy bus doesn't flood the link. +/// Nothing is sent before a bus has reported. `try_send`: never blocks; a full queue or a +/// link that is down leaves it unsent, to retry on the next call. Returns whether a +/// message was queued. +pub fn publish_can_bus_health(timestamp_ms: u64) -> bool { + let summary = summary(); + if summary.iter().all(Option::is_none) { + return false; + } + let due = LAST_PUBLISHED.lock(|last| match last.borrow().as_ref() { + Some((sent, sent_at)) => { + *sent != summary || timestamp_ms.saturating_sub(*sent_at) >= CAN_BUS_HEALTH_REPEAT_MS + } + None => true, + }); + if !due { + return false; + } + let msg = can_bus_health_state_update(timestamp_ms); + if !crate::routing::try_send_to(crate::types::Transport::Ble, msg) { + return false; + } + LAST_PUBLISHED.lock(|last| *last.borrow_mut() = Some((summary, timestamp_ms))); + true +} + +/// Sends the bus health again even if unchanged, e.g. when the app subscribes. +pub fn resend_can_bus_health() { + LAST_PUBLISHED.lock(|last| *last.borrow_mut() = None); + CAN_HEALTH_CHANGED.signal(()); +} + +/// Forgets every bus and what was published, for tests. +pub fn reset_can_bus_health_for_tests() { + BUSES.lock(|buses| *buses.borrow_mut() = [None; MAX_CAN_BUSES]); + LAST_PUBLISHED.lock(|last| *last.borrow_mut() = None); +} + +/// Publishes the bus health over BLE when a bus reports, and checks once a second, which +/// sends the periodic repeat and retries a send that found the queue full. +#[embassy_executor::task] +pub async fn publish_can_bus_health_task() { + loop { + publish_can_bus_health(Instant::now().as_millis()); + let _ = embassy_futures::select::select( + CAN_HEALTH_CHANGED.wait(), + Timer::after(Duration::from_secs(1)), + ) + .await; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use proto::CanBusStatus as S; + + fn counts(received: u32, errors: u32, overruns: u32, bus_offs: u32) -> CanRxCounts { + CanRxCounts { + received, + matched: received, + errors, + overruns, + bus_offs, + } + } + + #[test] + fn status_of_a_window() { + assert_eq!(can_bus_status(&counts(0, 0, 0, 0)), S::Silent); + assert_eq!(can_bus_status(&counts(10, 0, 0, 0)), S::Ok); + assert_eq!(can_bus_status(&counts(10, 1, 0, 0)), S::Degraded); + assert_eq!(can_bus_status(&counts(10, 0, 1, 0)), S::Degraded); + assert_eq!(can_bus_status(&counts(0, 5, 0, 0)), S::NoValidFrames); + assert_eq!(can_bus_status(&counts(10, 5, 1, 1)), S::BusOff); + assert_eq!(can_bus_status(&counts(0, 0, 0, 1)), S::BusOff); + } + + #[test] + fn counts_record_and_take() { + let mut c = CanRxCounts::new(); + c.record_frame(true); + c.record_frame(false); + c.record_error(); + c.record_overrun(); + c.record_bus_off(); + assert_eq!(c.take(), counts(2, 1, 1, 1).with_matched(1)); + assert_eq!(c, CanRxCounts::new()); + } + + #[test] + fn frames_per_second_of_a_window() { + assert_eq!( + frames_per_second(&counts(10_800, 0, 0, 0), 5_000), + Some(2_160) + ); + assert_eq!(frames_per_second(&counts(7, 0, 0, 0), 2_000), Some(3)); + assert_eq!(frames_per_second(&counts(0, 0, 0, 0), 5_000), Some(0)); + assert_eq!(frames_per_second(&counts(10, 0, 0, 0), 0), None); + assert_eq!( + frames_per_second(&counts(u32::MAX, 0, 0, 0), 1), + Some(u32::MAX) + ); + } + + #[test] + fn counts_saturate_instead_of_wrapping() { + let mut c = CanRxCounts { + received: u32::MAX, + ..CanRxCounts::new() + }; + c.record_frame(false); + assert_eq!(c.received, u32::MAX); + let mut total = c; + total.add(&c); + assert_eq!(total.received, u32::MAX); + } + + impl CanRxCounts { + fn with_matched(mut self, matched: u32) -> Self { + self.matched = matched; + self + } + } +} diff --git a/core-interface/src/lib.rs b/core-interface/src/lib.rs index 2f1bdb0..8c84c78 100644 --- a/core-interface/src/lib.rs +++ b/core-interface/src/lib.rs @@ -8,6 +8,7 @@ pub mod proto { mod availability; mod can; mod can_access; +mod can_health; mod can_log; mod can_probe; mod can_tx; @@ -112,6 +113,13 @@ pub use can_access::{ set_can_dev_write_unlocked, try_take_can_read_write_approval_to_store, }; +// CAN bus health (RX counters reported by the board drivers, published over BLE) +pub use can_health::{ + CAN_BUS_HEALTH_REPEAT_MS, CanRxCounts, can_bus_health, can_bus_health_state_update, + can_bus_status, frames_per_second, publish_can_bus_health, publish_can_bus_health_task, + report_can_bus_window, resend_can_bus_health, reset_can_bus_health_for_tests, +}; + // CAN logging (SavvyCAN / GVRET) pub use can_log::{ CAN_LOG_CHANNEL, CanLogFrame, CanLogSession, GvretCommand, GvretParser, SessionEnd, diff --git a/core-interface/tests/can_health.rs b/core-interface/tests/can_health.rs new file mode 100644 index 0000000..57c972a --- /dev/null +++ b/core-interface/tests/can_health.rs @@ -0,0 +1,164 @@ +use core_interface::{ + BLE_TX_CHANNEL, CAN_BUS_HEALTH_REPEAT_MS, CanRxCounts, MAX_CAN_BUSES, init, proto, + publish_can_bus_health, report_can_bus_window, resend_can_bus_health, + reset_can_bus_health_for_tests, +}; +use proto::CanBusStatus as S; +use std::collections::BTreeMap; + +fn boot() { + init(0xDEAD_BEEF); + reset_can_bus_health_for_tests(); + core_interface::set_link_up(core_interface::Transport::Ble, true); + while BLE_TX_CHANNEL.try_receive().is_ok() {} +} + +fn frames(received: u32) -> CanRxCounts { + CanRxCounts { + received, + matched: received / 2, + ..CanRxCounts::new() + } +} + +fn sent() -> Option> { + match BLE_TX_CHANNEL.try_receive().ok()?.payload { + Some(proto::device_to_app::Payload::StateUpdate(update)) => { + assert!(update.vehicle_state.is_none()); + Some(update.system_state?.can_bus_health) + } + other => panic!("unexpected message {other:?}"), + } +} + +fn status(health: &proto::CanBusHealth) -> S { + S::try_from(health.status.unwrap()).unwrap() +} + +#[test] +fn nothing_is_published_before_a_bus_reports() { + boot(); + assert!(!publish_can_bus_health(0)); + assert!(BLE_TX_CHANNEL.try_receive().is_err()); +} + +#[test] +fn a_report_is_published_with_totals_since_boot() { + boot(); + report_can_bus_window(0, &frames(10), 5_000, Some(true)); + report_can_bus_window(0, &frames(4), 2_000, Some(true)); + let mut faulty = CanRxCounts::new(); + faulty.record_error(); + faulty.record_error(); + report_can_bus_window(1, &faulty, 5_000, None); + report_can_bus_window(1, &faulty, 5_000, None); + + assert!(publish_can_bus_health(1_000)); + let health = sent().unwrap(); + assert_eq!(health.len(), 2); + + let bus0 = &health[&0]; + assert_eq!(status(bus0), S::Ok); + assert_eq!(bus0.listen_only, Some(true)); + assert_eq!(bus0.rx_errors, Some(0)); + assert_eq!(bus0.overruns, Some(0)); + assert_eq!(bus0.bus_offs, Some(0)); + // The rate is the last window's (4 frames in 2 s), not the totals'. + assert_eq!(bus0.frames_per_second, Some(2)); + + let bus1 = &health[&1]; + assert_eq!(status(bus1), S::NoValidFrames); + assert_eq!(bus1.listen_only, None); + assert_eq!(bus1.rx_errors, Some(4)); +} + +#[test] +fn the_status_follows_the_last_window_only() { + boot(); + let mut bus_off = frames(3); + bus_off.record_bus_off(); + report_can_bus_window(0, &bus_off, 5_000, Some(false)); + report_can_bus_window(0, &CanRxCounts::new(), 5_000, Some(false)); + assert!(publish_can_bus_health(0)); + let bus0 = sent().unwrap()[&0]; + assert_eq!(status(&bus0), S::Silent); + assert_eq!(bus0.bus_offs, Some(1)); + assert_eq!(bus0.frames_per_second, Some(0)); +} + +#[test] +fn a_status_change_is_published_at_once_and_counters_only_after_the_repeat() { + boot(); + report_can_bus_window(0, &frames(10), 5_000, Some(true)); + assert!(publish_can_bus_health(1_000)); + sent().unwrap(); + + // Same status, new counters: held until the repeat interval. + report_can_bus_window(0, &frames(20), 5_000, Some(true)); + assert!(!publish_can_bus_health(2_000)); + assert!(BLE_TX_CHANNEL.try_receive().is_err()); + assert!(publish_can_bus_health(1_000 + CAN_BUS_HEALTH_REPEAT_MS)); + assert_eq!(sent().unwrap()[&0].frames_per_second, Some(4)); + + // A new status goes out at once. + let now = 1_000 + CAN_BUS_HEALTH_REPEAT_MS + 100; + report_can_bus_window(0, &CanRxCounts::new(), 5_000, Some(true)); + assert!(publish_can_bus_health(now)); + assert_eq!(status(&sent().unwrap()[&0]), S::Silent); + + // So does a change of mode, and a bus that appears. + report_can_bus_window(0, &CanRxCounts::new(), 5_000, Some(false)); + assert!(publish_can_bus_health(now + 1)); + sent().unwrap(); + report_can_bus_window(1, &CanRxCounts::new(), 5_000, Some(false)); + assert!(publish_can_bus_health(now + 2)); + assert_eq!(sent().unwrap().len(), 2); +} + +#[test] +fn resend_publishes_again_even_if_unchanged() { + boot(); + report_can_bus_window(0, &frames(1), 5_000, Some(true)); + assert!(publish_can_bus_health(1_000)); + sent().unwrap(); + assert!(!publish_can_bus_health(1_100)); + resend_can_bus_health(); + assert!(publish_can_bus_health(1_100)); + assert!(sent().is_some()); +} + +#[test] +fn nothing_is_queued_while_ble_is_down_and_it_is_retried() { + boot(); + report_can_bus_window(0, &frames(1), 5_000, Some(true)); + core_interface::set_link_up(core_interface::Transport::Ble, false); + assert!(!publish_can_bus_health(1_000)); + core_interface::set_link_up(core_interface::Transport::Ble, true); + assert!(publish_can_bus_health(1_001)); + assert!(sent().is_some()); +} + +#[test] +fn a_bus_id_beyond_the_limit_is_ignored() { + boot(); + report_can_bus_window(MAX_CAN_BUSES as u8, &frames(1), 5_000, Some(true)); + assert!(!publish_can_bus_health(0)); +} + +#[test] +fn a_full_state_update_fits_a_ble_message() { + use prost::Message; + boot(); + let worst = CanRxCounts { + received: u32::MAX, + matched: u32::MAX, + errors: u32::MAX, + overruns: u32::MAX, + bus_offs: u32::MAX, + }; + for bus in 0..MAX_CAN_BUSES as u8 { + report_can_bus_window(bus, &worst, 1, Some(false)); + } + let msg = core_interface::can_bus_health_state_update(u64::MAX); + assert!(msg.encoded_len() <= core_interface::ble::BLE_MAX_MESSAGE_BYTES); +} diff --git a/docs/architecture.md b/docs/architecture.md index 189723f..acff0b5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -11,7 +11,7 @@ The intermediary between transport layers (BLE/MQTT) and vehicle logic. Knows no * Defines 12 static `Channel`s as the inter-crate contract (see [Channels](#channels)). * Defines shared types: `Transport`, `InboundCommand`, `VehicleStatePayload`, `CanLogFrame`. -* Defines 6 pure-logic `#[embassy_executor::task]` functions: `process_ble_commands_task`, `process_mqtt_commands_task`, `route_responses_task`, `publish_state_task`, `publish_can_access_task`, `publish_command_availability_task`. +* Defines pure-logic `#[embassy_executor::task]` functions: `process_ble_commands_task`, `process_mqtt_commands_task`, `route_responses_task`, `publish_state_task`, `publish_can_access_task`, `publish_command_availability_task`, `publish_can_bus_health_task`. * Exposes `pub fn passes_filter()`, `pub fn is_can_read_only()`, `pub fn set_can_read_only(bool)`, the CAN read-write policy (car identity, owner approval, dev lock; see [CAN](can.md#read-write-policy)), the CAN TX classes (`CanTxFrame`, `CommandAuthorization`; see [CAN](can.md#tx-classes)), phone trust and validation sessions (see [BLE](ble.md#phone-trust)), and the SavvyCAN logging API (`is_can_logging`, `log_can_frame`, `run_can_log_session`). * Has 4 inner async helpers (`handle_ble_message`, `handle_mqtt_message`, `route_single_response`, `publish_single_state`) extracted from the task loops so they can be unit-tested without running an executor. * **`publish_single_state` is intentionally non-blocking:** state updates don't go through the TX queues. Each transport has a single-value slot (`BLE_STATE_TX`, `MQTT_STATE_TX`, embassy `Signal`s) that the newest update overwrites. This guarantees `publish_state_task` never stalls, keeping `VEHICLE_STATE_CHANNEL` always drainable and preventing a deadlock cascade through `state_update_task` and command-handler tasks, and a state update can never push a command response out of a queue. diff --git a/docs/ble.md b/docs/ble.md index a7f0688..0f4ac31 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -57,7 +57,7 @@ Both RX and TX GATT characteristics declare `permissions(encrypted)` in the `#[c Encryption is checked via a per-connection `tx_auth: AtomicBool` (initialized `false`). On each retry while `tx_auth` is `false`, `ble_tx_notify_task` calls `conn.raw().security_level()` — if the result is `Encrypted`, it sets `tx_auth = true` (cached for all subsequent messages) and sends immediately. This single check covers both the first-pair path (encryption established during `PairingComplete`) and the reconnect path (re-encryption via stored LTK, which never fires `PairingComplete` on iOS). `gatt_event_task` does not touch `tx_auth`. ## State on subscribe -trouble-host's `notify` sends nothing to a peer that hasn't enabled notifications (and still returns `Ok`), and the app subscribes only after the link is encrypted, so the first state update after connecting would otherwise be lost. `publish_single_state` keeps the last BLE state message in `core_interface::latest_ble_state()` (unlike `BLE_STATE_TX`, it isn't emptied when sent). When the app writes the TX characteristic's CCCD with notifications enabled, `gatt_event_task` signals `ble_tx_notify_task`, which sends that cached state (full state, original timestamp) through the normal path, `SUBSCRIBE_RESEND_DELAY_MS` (500 ms) later: a notification sent right as the CCCD write is accepted was lost on Android, before the app's notification stream was listening. It is still held until the link is encrypted. Nothing is sent if the vehicle hasn't published a state since boot. The CAN access state (`SystemState.can_access`, sent with the connected phone's `SystemState.phone_access`, see [Phone trust](#phone-trust)) and the command availability (`SystemState.command_availability`) are sent again too (`resend_can_access_state()`, `resend_command_availability()`), and both are repeated every few seconds anyway (see [CAN](can.md#read-write-policy) and [Vehicle commands](commands.md#command-availability)). A message the app was already subscribed for may arrive twice; state updates are idempotent. +trouble-host's `notify` sends nothing to a peer that hasn't enabled notifications (and still returns `Ok`), and the app subscribes only after the link is encrypted, so the first state update after connecting would otherwise be lost. `publish_single_state` keeps the last BLE state message in `core_interface::latest_ble_state()` (unlike `BLE_STATE_TX`, it isn't emptied when sent). When the app writes the TX characteristic's CCCD with notifications enabled, `gatt_event_task` signals `ble_tx_notify_task`, which sends that cached state (full state, original timestamp) through the normal path, `SUBSCRIBE_RESEND_DELAY_MS` (500 ms) later: a notification sent right as the CCCD write is accepted was lost on Android, before the app's notification stream was listening. It is still held until the link is encrypted. Nothing is sent if the vehicle hasn't published a state since boot. The CAN access state (`SystemState.can_access`, sent with the connected phone's `SystemState.phone_access`, see [Phone trust](#phone-trust)) the command availability (`SystemState.command_availability`) and the CAN bus health (`SystemState.can_bus_health`) are sent again too (`resend_can_access_state()`, `resend_command_availability()`, `resend_can_bus_health()`), and all three are repeated every few seconds anyway (see [CAN](can.md#read-write-policy), [Vehicle commands](commands.md#command-availability) and [Bus health](can.md#bus-health)). A message the app was already subscribed for may arrive twice; state updates are idempotent. ## MQTT client ID The access state update also carries `SystemState.mqtt_client_id`, the `network.mqtt.client_id` this device's topics are built from, and it is unset in a build without MQTT. The app can't know it otherwise, and needs it to use this device's topics. So give each device its own `client_id`. diff --git a/docs/can.md b/docs/can.md index 21563e7..b549ec5 100644 --- a/docs/can.md +++ b/docs/can.md @@ -35,7 +35,7 @@ Hardware filters are set to accept-all where driver constraints apply (TWAI on E * RX is interrupt-driven (esp-hal ISR → 32-frame queue), which keeps frames from being lost on single-core chips while WiFi/BLE are busy. * The session loop sleeps until a frame arrives, a TX frame is queued for this bus, the read-only flag changes, or the next RX stats report is due. TX waits are bounded to 100 ms, RX overruns clear the FIFO, and bus-off rebuilds the controller after 1 s. A bus-off also relocks every bus (`set_can_read_only(true)`), so the vehicle has to unlock again (see [Read-write policy](#read-write-policy)). -* Every 5 s each TWAI bus logs one `info` line with the frames received, how many matched the vehicle filters, RX errors (with the last error kind), overruns and bus-offs since the previous line. A silent bus logs zeros, so the serial console shows whether the car is sending anything. RX errors with no frames usually mean a wrong bitrate, a CAN FD bus or a wiring fault. MCP2515 buses don't have this log yet. +* Every 5 s each TWAI bus logs one `info` line with the frames received, how many matched the vehicle filters, RX errors (with the last error kind), overruns and bus-offs since the previous line. A silent bus logs zeros, so the serial console shows whether the car is sending anything. RX errors with no frames usually mean a wrong bitrate, a CAN FD bus or a wiring fault, but TWAI doesn't count RX errors yet (see [Bus health](#bus-health)). The same window is reported for the app, and a bus-off or a switch between listen-only and normal mode ends the window early, so the app sees it at once (the window is reported under the mode it ran in, and the line gives its real length, e.g. `last 0.2s`). MCP2515 buses don't have this log or the bus health yet. * The blocking `nb` path was dropped because esp-hal's blocking `receive()` never releases the FIFO after an overrun, so RX stays dead permanently. ### MCP2515 (SPI) @@ -44,6 +44,25 @@ Hardware filters are set to accept-all where driver constraints apply (TWAI on E ## PC driver `socket_can_task` (pool of 4) opens a non-blocking `SocketCAN` socket per bus and polls it every 1 ms via Embassy timer. Outbound frames are drained from this bus's `CAN_TX_CHANNELS` entry after each RX sweep. If the interface cannot be opened (e.g. `vcan0` does not exist), the task logs a warning and retries every 5 seconds — it does **not** panic, so MQTT, BLE, and the simulated state heartbeat continue running normally. +## Bus health + +The app shows each bus's health from `SystemState.can_bus_health`, a map from bus id to `CanBusHealth`. Board drivers count what they receive in a `core_interface::CanRxCounts` and hand each window to `report_can_bus_window(bus_id, &counts, window_ms, listen_only)` when it ends (every 5 s, and at once after a bus-off or, on TWAI, a mode switch), with how long it lasted. `can_health.rs` adds it to the bus's totals since boot and judges the window (`can_bus_status`): + +| Status | Window | +|---|---| +| `BUS_OFF` | the controller went bus-off | +| `NO_VALID_FRAMES` | RX errors and no frame: usually a wrong bitrate, a CAN FD bus or wiring | +| `DEGRADED` | frames, with RX errors or overruns | +| `SILENT` | nothing at all: the car is asleep, or the bus isn't connected | +| `OK` | frames, no errors | + +The error counters sent (`rx_errors`, `overruns`, `bus_offs`) are totals since boot (saturating), so a lost update loses nothing; the status and `frames_per_second` (frames received over the window's length, rounded down) are about the last window only. Frames are sent as a rate rather than a total: on a busy bus (about 2,000 frames/s on E-GMP M-CAN) a `u32` total would saturate after a few weeks of the bus being awake. The serial log still shows the frame counts of each window. `listen_only` is whether the controller ran in hardware listen-only mode, and unset for a driver without one (SocketCAN on the PC board, which drops TX in software instead). + +It is BLE only (MQTT carries basic state only), in a `StateUpdate` of its own sent by `publish_can_bus_health_task`: at once when a bus changes status or mode, or first reports; otherwise every `CAN_BUS_HEALTH_REPEAT_MS` (5 s), with the new counters; and again when the app subscribes. A bus whose driver doesn't report (MCP2515 so far) is absent from the map. + +* **ESP TWAI:** the counters behind the 5 s RX log (see [TWAI](#twai-built-in)). RX errors always read 0: esp-hal's `receive_async` only returns frames, bus-offs and overruns, and drops bus errors (bit, stuff, form, CRC, ACK); the error counters don't help either, because REC is held at 128 in listen-only mode (an errata workaround). So a TWAI bus never reads `NO_VALID_FRAMES`, or `DEGRADED` from RX errors: a wrong bitrate on a busy bus reads `SILENT` (seen in an E-GMP car). Tracked in [#117](https://github.com/OpenCarControls/firmware/issues/117). +* **PC (SocketCAN):** frames, plus error frames (the socket accepts all of them): a bus-off, a receive buffer overflow (counted as an overrun), or else an RX error. A `vcan` bus never sends error frames, so it only reads `OK` or `SILENT`. + ## xtask CAN codegen In `xtask_builder.rs` per board: