Skip to content
Merged
6 changes: 4 additions & 2 deletions boards/esp/src/ble/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -966,15 +966,17 @@ 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,
))
.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,
Expand Down
132 changes: 60 additions & 72 deletions boards/esp/src/can.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -228,26 +232,29 @@ 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);
log::warn!(
"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();
}
Expand All @@ -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;
}
}
Expand All @@ -284,33 +291,55 @@ mod hardware {

type TwaiRxStats = crate::can::RxStats<EspTwaiError>;

/// 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
),
}
}
Expand Down Expand Up @@ -537,52 +566,31 @@ 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<E> {
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<E>,
}

#[cfg_attr(not(feature = "hardware"), allow(dead_code))]
impl<E> RxStats<E> {
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())
}
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions boards/esp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Loading