Skip to main content

esp_hal/canfd/
mod.rs

1//! # Controller Area Network Flexible Data-Rate (CAN FD)
2//!
3//! ## Overview
4//!
5//! The CAN FD controller is a CTU CAN FD core. It is a different peripheral
6//! from the classic two-wire automotive interface (TWAI) controller. It
7//! supports classic CAN 2.0 frames and CAN FD frames. A CAN FD frame carries up
8//! to 64 bytes of payload and can switch to a faster bit rate for its data
9//! phase.
10//!
11//! The peripheral needs an external transceiver to drive a real bus.
12#![doc = concat!("[ESP-IDF documentation](https://docs.espressif.com/projects/esp-idf/en/latest/", chip!(), "/api-reference/peripherals/twai.html)")]
13//! ## Configuration
14//!
15//! [`Config`] selects the bus participation [`Mode`], the function
16//! [`ClockSource`], and the bit [`Timing`] of the arbitration and data phases.
17//! The controller stays off the bus until [`CanFd::start`] is called, so the
18//! pins can be assigned first.
19//!
20//! Received frames pass through three mask filters and one range filter; see
21//! [`MaskFilterConfig`] and [`RangeFilterConfig`]. Each filter matches either
22//! standard or extended identifiers, and accepts classic CAN frames, CAN FD
23//! frames or both, as set by [`FrameFormats`].
24//!
25//! ## Usage
26//!
27//! [`CanFd::into_async`] converts the driver into an async driver. Received
28//! frames stay in the hardware RX buffer until they are read, so
29//! [`CanFd::receive_async`] is cancel-safe and the driver needs no software
30//! frame queue.
31//!
32//! Identifiers are the [`embedded_can`] types. [`ClassicFrame`] implements
33//! [`embedded_can::Frame`] and [`BusErrorKind`] implements
34//! [`embedded_can::Error`], for code written against those traits.
35//!
36//! ## Examples
37//!
38//! ### Sending a CAN FD frame
39//!
40//! ```rust, no_run
41#![doc = crate::before_snippet!()]
42//! use esp_hal::canfd::{CanFd, Config, Frame, StandardId};
43//!
44//! let mut canfd = CanFd::new(peripherals.TWAI0, Config::default())?
45//!     .with_rx(peripherals.GPIO9)
46//!     .with_tx(peripherals.GPIO8);
47//! canfd.start()?;
48//!
49//! // A 64-byte frame, sent with the data phase at the FD bit rate.
50//! let id = StandardId::new(0x123).unwrap();
51//! let frame = Frame::new_fd(id, &[0xAA; 64])?.with_bit_rate_switch(true);
52//! canfd.transmit(&frame)?;
53//! # Ok(())
54//! # }
55//! ```
56//! 
57//! ### Receiving a range of identifiers
58//!
59//! Filter A accepts every frame out of reset. Configure it to accept only
60//! CAN FD frames with the standard identifiers 0x120–0x12F.
61//! ```rust, no_run
62#![doc = crate::before_snippet!()]
63//! use esp_hal::canfd::{
64//!     CanFd,
65//!     Config,
66//!     FrameFormats,
67//!     MaskFilter,
68//!     MaskFilterConfig,
69//!     StandardId,
70//! };
71//!
72//! let mut canfd = CanFd::new(peripherals.TWAI0, Config::default())?
73//!     .with_rx(peripherals.GPIO9)
74//!     .with_tx(peripherals.GPIO8);
75//!
76//! let id = StandardId::new(0x120).unwrap();
77//! let mask = StandardId::new(0x7F0).unwrap();
78//! canfd.set_mask_filter(
79//!     MaskFilter::A,
80//!     &MaskFilterConfig::standard(id, mask).with_formats(FrameFormats::Fd),
81//! );
82//! canfd.start()?;
83//! # Ok(())
84//! # }
85//! ```
86//! 
87//! ## Implementation State
88//!
89//! - Time-triggered transmission is not exposed.
90//! - TX buffer backup mode and RAM parity protection are not exposed.
91//!
92//! "TRM" in this module means the ESP32-C5 TRM v1.1, chapter 38.
93#![doc = crate::trm_markdown_link!("#canfd")]
94
95use core::marker::PhantomData;
96
97pub use embedded_can::{ExtendedId, Id, StandardId};
98use enumset::{EnumSet, EnumSetType};
99
100use crate::{
101    Async,
102    Blocking,
103    DriverMode,
104    clock::ll::{ClockTree, TwaiInstance},
105    gpio::{
106        DriveMode,
107        InputConfig,
108        InputSignal,
109        OutputConfig,
110        OutputSignal,
111        Pull,
112        interconnect::{PeripheralInput, PeripheralOutput},
113    },
114    interrupt::InterruptHandler,
115    peripherals::Interrupt,
116    rtc_cntl::WakeLock,
117    system::{Cpu, Peripheral, PeripheralGuard},
118    time::{Duration, Instant},
119};
120
121mod asynch;
122mod ll;
123
124pub use ll::{
125    BusErrorKind,
126    ErrorCapture,
127    ErrorPosition,
128    ErrorState,
129    FD_TIMING_LIMITS,
130    FrameFormats,
131    MAX_RETRANSMIT_LIMIT,
132    MAX_TX_PRIORITY,
133    MaskFilter,
134    NOMINAL_TIMING_LIMITS,
135    Timing,
136    TimingLimits,
137    TxBufferState,
138};
139use ll::{
140    CLASSIC_MAX_DATA_LEN,
141    Driver,
142    FrameBuffer,
143    FrameHeader,
144    FrameKinds,
145    MAX_DATA_LEN,
146    SspSource,
147    TimestampPoint,
148    len_to_dlc,
149};
150
151/// Clock source for the CAN FD peripheral.
152pub use crate::soc::clocks::TwaiFunctionClockConfig as ClockSource;
153
154/// The device ID every CTU CAN FD core reports.
155const CTU_CAN_FD_DEVICE_ID: u16 = 0xCAFD;
156
157/// An interrupt source of the controller (TRM 38.4).
158#[derive(Debug, EnumSetType)]
159#[cfg_attr(feature = "defmt", derive(defmt::Format))]
160pub enum CanFdInterrupt {
161    /// A frame was received.
162    RxFrame,
163    /// A frame was transmitted.
164    TxFrame,
165    /// The error warning limit was reached.
166    ErrorWarning,
167    /// The RX buffer overran.
168    DataOverrun,
169    /// The fault confinement state changed.
170    FaultStateChanged,
171    /// Arbitration was lost.
172    ArbitrationLost,
173    /// A bus error was detected.
174    BusError,
175    /// An overload frame was seen.
176    Overload,
177    /// The RX buffer is full.
178    RxFull,
179    /// A frame switched to the data bit rate, on either side of the transfer.
180    BitRateShifted,
181    /// The RX buffer is no longer empty.
182    RxNotEmpty,
183    /// A TX buffer finished, successfully or not.
184    TxDone,
185}
186
187impl CanFdInterrupt {
188    const fn bit(self) -> u32 {
189        1 << match self {
190            Self::RxFrame => 0,
191            Self::TxFrame => 1,
192            Self::ErrorWarning => 2,
193            Self::DataOverrun => 3,
194            Self::FaultStateChanged => 4,
195            Self::ArbitrationLost => 5,
196            Self::BusError => 6,
197            Self::Overload => 7,
198            Self::RxFull => 8,
199            Self::BitRateShifted => 9,
200            Self::RxNotEmpty => 10,
201            Self::TxDone => 11,
202        }
203    }
204
205    fn mask(set: EnumSet<Self>) -> u32 {
206        set.iter().fold(0, |acc, source| acc | source.bit())
207    }
208
209    fn from_mask(bits: u32) -> EnumSet<Self> {
210        EnumSet::all()
211            .iter()
212            .filter(|source: &Self| bits & source.bit() != 0)
213            .collect()
214    }
215}
216
217/// Identity of a CAN FD controller, read out of the hardware.
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
219#[cfg_attr(feature = "defmt", derive(defmt::Format))]
220pub struct Identity {
221    /// Device ID. Reads `0xCAFD` on a working core.
222    pub device_id: u16,
223    /// IP core major version.
224    pub version_major: u8,
225    /// IP core minor version.
226    pub version_minor: u8,
227}
228
229impl Identity {
230    /// Returns whether the device ID is the one a CTU CAN FD core reports.
231    pub fn is_ctu_can_fd(&self) -> bool {
232        self.device_id == CTU_CAN_FD_DEVICE_ID
233    }
234}
235
236/// How the controller participates on the bus.
237#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
238#[cfg_attr(feature = "defmt", derive(defmt::Format))]
239pub enum Mode {
240    /// Transmits and receives normally.
241    #[default]
242    Normal,
243    /// Receives only, never driving a dominant bit (TRM 38.3.12.4).
244    ListenOnly,
245    /// Treats a frame as transmitted even without an ACK (TRM 38.3.12.2).
246    ///
247    /// Needed to transmit as the only node on a bus.
248    SelfTest,
249    /// Routes transmitted frames back into the RX buffer (TRM 38.3.12.1).
250    ///
251    /// Also enables self test, because loopback alone still requires an ACK.
252    LoopbackSelfTest,
253}
254
255/// Errors that can occur when the configuration is applied.
256#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
257#[cfg_attr(feature = "defmt", derive(defmt::Format))]
258#[non_exhaustive]
259pub enum ConfigError {
260    /// The nominal bit timing is outside the limits of the hardware.
261    UnsupportedNominalTiming,
262    /// The data phase bit timing is outside the limits of the hardware.
263    UnsupportedFdTiming,
264    /// The timestamp resolution cannot be reached from the function clock.
265    UnsupportedTimestampResolution,
266    /// The timestamp counter did not start ticking.
267    TimestampTimerStalled,
268    /// The retransmission limit is larger than [`MAX_RETRANSMIT_LIMIT`].
269    UnsupportedRetransmitLimit,
270    /// The secondary sample point cannot be placed where it was asked for.
271    ///
272    /// The final position must stay inside four data bit times and inside the
273    /// eight-bit offset field (TRM 38.3.7.3).
274    UnsupportedSecondarySamplePoint,
275    /// A transmission was still in flight and did not settle, so the
276    /// configuration was not applied.
277    BusBusy,
278    /// The transceiver setting cannot change after a pin is assigned, because
279    /// it decides how that pin is driven.
280    TransceiverModeLocked,
281}
282
283impl core::error::Error for ConfigError {}
284
285impl core::fmt::Display for ConfigError {
286    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
287        let message = match self {
288            Self::UnsupportedNominalTiming => {
289                "The nominal bit timing is outside the hardware limits"
290            }
291            Self::UnsupportedFdTiming => "The data phase bit timing is outside the hardware limits",
292            Self::UnsupportedTimestampResolution => {
293                "The timestamp resolution cannot be reached from the function clock"
294            }
295            Self::TimestampTimerStalled => "The timestamp counter did not start ticking",
296            Self::UnsupportedRetransmitLimit => {
297                "The retransmission limit is larger than the hardware field can hold"
298            }
299            Self::UnsupportedSecondarySamplePoint => {
300                "The secondary sample point cannot be placed where it was asked for"
301            }
302            Self::BusBusy => "A transmission was still in flight and did not settle",
303            Self::TransceiverModeLocked => {
304                "Whether a transceiver is in the way cannot be changed once a pin is assigned"
305            }
306        };
307        f.write_str(message)
308    }
309}
310
311/// Errors that can occur while the driver operates.
312#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
313#[cfg_attr(feature = "defmt", derive(defmt::Format))]
314#[non_exhaustive]
315pub enum Error {
316    /// Every TX buffer holds a frame that is not yet finished.
317    NoFreeTxBuffer,
318    /// The RX buffer holds no complete frame.
319    RxBufferEmpty,
320    /// The controller did not become error-active in time.
321    ///
322    /// The bus must be idle-recessive for 11 bit times before the controller
323    /// can join it.
324    BusIntegrationTimeout,
325    /// The controller gave up on the frame after its retransmission limit.
326    TransmitFailed,
327    /// The transmission was aborted.
328    TransmitAborted,
329    /// The operation needs the controller to be off the bus first.
330    ControllerRunning,
331    /// The operation needs the controller to be on the bus; see
332    /// [`CanFd::start`].
333    ControllerStopped,
334    /// A transmission did not settle in time after being aborted.
335    AbortTimeout,
336}
337
338impl core::error::Error for Error {}
339
340impl core::fmt::Display for Error {
341    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
342        let message = match self {
343            Self::NoFreeTxBuffer => "Every TX buffer holds a frame that is not yet finished",
344            Self::RxBufferEmpty => "The RX buffer holds no complete frame",
345            Self::BusIntegrationTimeout => "The controller did not become error-active in time",
346            Self::TransmitFailed => "The controller gave up on the frame",
347            Self::TransmitAborted => "The transmission was aborted",
348            Self::ControllerRunning => "The operation needs the controller to be off the bus",
349            Self::ControllerStopped => "The operation needs the controller to be on the bus",
350            Self::AbortTimeout => "A transmission did not settle in time after being aborted",
351        };
352        f.write_str(message)
353    }
354}
355
356/// Errors that can occur when a frame is created.
357#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
358#[cfg_attr(feature = "defmt", derive(defmt::Format))]
359#[non_exhaustive]
360pub enum FrameError {
361    /// The payload is longer than the frame format can carry.
362    ///
363    /// Classic CAN frames carry up to 8 bytes, CAN FD frames up to 64.
364    PayloadTooLong,
365    /// The frame is a CAN FD frame, which a [`ClassicFrame`] cannot hold.
366    NotClassic,
367}
368
369impl core::error::Error for FrameError {}
370
371impl core::fmt::Display for FrameError {
372    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
373        let message = match self {
374            Self::PayloadTooLong => "The payload is longer than the frame format can carry",
375            Self::NotClassic => "The frame is a CAN FD frame",
376        };
377        f.write_str(message)
378    }
379}
380
381/// CAN FD driver configuration.
382#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, procmacros::BuilderLite)]
383#[cfg_attr(feature = "defmt", derive(defmt::Format))]
384#[non_exhaustive]
385pub struct Config {
386    /// Bus participation mode.
387    ///
388    /// Default value: [`Mode::Normal`].
389    mode: Mode,
390
391    /// Function clock source.
392    ///
393    /// The TRM recommends [`ClockSource::Xtal`] up to 5 Mbit/s and
394    /// [`ClockSource::PllF80m`] above that.
395    ///
396    /// Default value: [`ClockSource::PllF80m`].
397    clock_source: ClockSource,
398
399    /// Bit timing of the arbitration phase.
400    ///
401    /// Default value: 500 kbit/s from an 80 MHz function clock.
402    nominal_timing: Timing,
403
404    /// Bit timing of the data phase, used by bit-rate-switched frames.
405    ///
406    /// Default value: 2 Mbit/s from an 80 MHz function clock.
407    fd_timing: Timing,
408
409    /// Number of retransmission attempts, or `None` to retry forever.
410    ///
411    /// The first attempt is not a retransmission. The hardware holds at most
412    /// [`MAX_RETRANSMIT_LIMIT`].
413    ///
414    /// Default value: `Some(3)`.
415    retransmit_limit: Option<u8>,
416
417    /// Secondary sample point offset in time quanta, or `None` to disable it.
418    ///
419    /// Default value: `None`.
420    secondary_sample_point_offset: Option<u8>,
421
422    /// Whether received request frames are dropped instead of stored.
423    ///
424    /// Default value: `false`.
425    drop_request_frames: bool,
426
427    /// Whether protocol exception handling is enabled.
428    ///
429    /// Default value: `false`.
430    protocol_exception: bool,
431
432    /// Whether the TX pin is driven open-drain with a pull-up.
433    ///
434    /// Lets two nodes be wired together directly, without transceivers. Binding
435    /// the RX and TX signals to the same pin then forms a single-node bus.
436    ///
437    /// Default value: `false`.
438    no_transceiver: bool,
439}
440
441impl Default for Config {
442    fn default() -> Self {
443        // 500 kbit/s nominal and 2 Mbit/s data from 80 MHz, sampling at 81.2%
444        // and 75%.
445        Self {
446            mode: Mode::Normal,
447            clock_source: ClockSource::PllF80m,
448            nominal_timing: Timing {
449                baud_rate_prescaler: 10,
450                propagation_segment: 7,
451                phase_segment_1: 5,
452                phase_segment_2: 3,
453                sync_jump_width: 3,
454            },
455            fd_timing: Timing {
456                baud_rate_prescaler: 10,
457                propagation_segment: 1,
458                phase_segment_1: 1,
459                phase_segment_2: 1,
460                sync_jump_width: 1,
461            },
462            retransmit_limit: Some(3),
463            secondary_sample_point_offset: None,
464            drop_request_frames: false,
465            protocol_exception: false,
466            no_transceiver: false,
467        }
468    }
469}
470
471impl Config {
472    fn validate(&self) -> Result<(), ConfigError> {
473        if !self.nominal_timing.is_valid(&NOMINAL_TIMING_LIMITS) {
474            return Err(ConfigError::UnsupportedNominalTiming);
475        }
476        if !self.fd_timing.is_valid(&FD_TIMING_LIMITS) {
477            return Err(ConfigError::UnsupportedFdTiming);
478        }
479        if self
480            .retransmit_limit
481            .is_some_and(|limit| limit > MAX_RETRANSMIT_LIMIT)
482        {
483            return Err(ConfigError::UnsupportedRetransmitLimit);
484        }
485
486        if let Some(offset) = self.secondary_sample_point_offset {
487            // The hardware counts the offset in function clock periods.
488            let cycles = u32::from(offset) * u32::from(self.fd_timing.baud_rate_prescaler);
489
490            // The field is eight bits; the hardware would saturate silently.
491            if cycles > u32::from(u8::MAX) {
492                return Err(ConfigError::UnsupportedSecondarySamplePoint);
493            }
494
495            // TRM 38.3.7.3 limits the final position, offset plus measured
496            // delay, to four data bit times. The core adds at least two cycles
497            // of delay on its own, so an offset that only fits with zero delay
498            // cannot fit in practice.
499            let data_bit_cycles =
500                u32::from(self.fd_timing.baud_rate_prescaler) * self.fd_timing.total_quanta();
501            if cycles + MIN_TRANSMITTER_DELAY_CYCLES > data_bit_cycles * 4 {
502                return Err(ConfigError::UnsupportedSecondarySamplePoint);
503            }
504
505            // Below three cycles the core flags bit errors against its own
506            // output.
507            if cycles <= MIN_TRANSMITTER_DELAY_CYCLES {
508                return Err(ConfigError::UnsupportedSecondarySamplePoint);
509            }
510        }
511
512        Ok(())
513    }
514}
515
516/// Configuration of one mask filter; see [`CanFd::set_mask_filter`].
517///
518/// A frame is accepted when its identifier has the filter's format and matches
519/// the filter's identifier in every bit set in the mask. A mask of
520/// [`StandardId::MAX`] or [`ExtendedId::MAX`] compares every bit, and a mask of
521/// zero accepts every identifier of the format.
522///
523/// The filter accepts classic CAN and CAN FD frames by default; see
524/// [`MaskFilterConfig::with_formats`].
525#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
526#[cfg_attr(feature = "defmt", derive(defmt::Format))]
527pub struct MaskFilterConfig {
528    id: u32,
529    mask: u32,
530    extended: bool,
531    formats: FrameFormats,
532}
533
534impl MaskFilterConfig {
535    /// Matches standard identifiers against `id`, in the bits set in `mask`.
536    pub fn standard(id: StandardId, mask: StandardId) -> Self {
537        Self {
538            id: id.as_raw() as u32,
539            mask: mask.as_raw() as u32,
540            extended: false,
541            formats: FrameFormats::Both,
542        }
543    }
544
545    /// Matches extended identifiers against `id`, in the bits set in `mask`.
546    pub fn extended(id: ExtendedId, mask: ExtendedId) -> Self {
547        Self {
548            id: id.as_raw(),
549            mask: mask.as_raw(),
550            extended: true,
551            formats: FrameFormats::Both,
552        }
553    }
554
555    /// Sets which frame formats the filter accepts.
556    pub fn with_formats(self, formats: FrameFormats) -> Self {
557        Self { formats, ..self }
558    }
559
560    fn kinds(&self) -> FrameKinds {
561        FrameKinds::new(self.extended, self.formats)
562    }
563}
564
565/// Configuration of the range filter; see [`CanFd::set_range_filter`].
566///
567/// A frame is accepted when its identifier has the filter's format and lies in
568/// `low..=high`. A `low` above `high` is an empty range, which accepts nothing.
569///
570/// The filter accepts classic CAN and CAN FD frames by default; see
571/// [`RangeFilterConfig::with_formats`].
572#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
573#[cfg_attr(feature = "defmt", derive(defmt::Format))]
574pub struct RangeFilterConfig {
575    low: u32,
576    high: u32,
577    extended: bool,
578    formats: FrameFormats,
579}
580
581impl RangeFilterConfig {
582    /// Matches standard identifiers in `low..=high`.
583    pub fn standard(low: StandardId, high: StandardId) -> Self {
584        Self {
585            low: low.as_raw() as u32,
586            high: high.as_raw() as u32,
587            extended: false,
588            formats: FrameFormats::Both,
589        }
590    }
591
592    /// Matches extended identifiers in `low..=high`.
593    pub fn extended(low: ExtendedId, high: ExtendedId) -> Self {
594        Self {
595            low: low.as_raw(),
596            high: high.as_raw(),
597            extended: true,
598            formats: FrameFormats::Both,
599        }
600    }
601
602    /// Sets which frame formats the filter accepts.
603    pub fn with_formats(self, formats: FrameFormats) -> Self {
604        Self { formats, ..self }
605    }
606
607    fn kinds(&self) -> FrameKinds {
608        FrameKinds::new(self.extended, self.formats)
609    }
610}
611
612/// A CAN FD frame.
613#[derive(Clone, Copy)]
614pub struct Frame {
615    id: Id,
616    request: bool,
617    fd: bool,
618    bit_rate_switch: bool,
619    error_state_indicator: bool,
620    data: [u8; MAX_DATA_LEN],
621    /// Bytes carried. Always zero for a request frame.
622    len: usize,
623    /// Bytes a request frame asks for. Zero for a data frame.
624    requested_len: usize,
625    timestamp: u64,
626}
627
628impl Frame {
629    /// Creates a new classic CAN data frame.
630    ///
631    /// # Errors
632    ///
633    /// [`FrameError::PayloadTooLong`] when `payload` is longer than 8 bytes.
634    pub fn new(id: impl Into<Id>, payload: &[u8]) -> Result<Self, FrameError> {
635        if payload.len() > CLASSIC_MAX_DATA_LEN {
636            return Err(FrameError::PayloadTooLong);
637        }
638        Ok(Self::build(id.into(), false, false, payload))
639    }
640
641    /// Creates a new classic CAN request frame.
642    ///
643    /// A request frame carries no payload. `len` is the payload length that the
644    /// frame asks for.
645    ///
646    /// # Errors
647    ///
648    /// [`FrameError::PayloadTooLong`] when `len` is greater than 8.
649    pub fn new_request(id: impl Into<Id>, len: usize) -> Result<Self, FrameError> {
650        if len > CLASSIC_MAX_DATA_LEN {
651            return Err(FrameError::PayloadTooLong);
652        }
653        let mut frame = Self::build(id.into(), true, false, &[]);
654        frame.requested_len = len;
655        Ok(frame)
656    }
657
658    /// Creates a new CAN FD data frame.
659    ///
660    /// The data phase uses the nominal bit rate unless
661    /// [`Frame::with_bit_rate_switch`] is set.
662    ///
663    /// # Errors
664    ///
665    /// [`FrameError::PayloadTooLong`] when `payload` is longer than 64 bytes.
666    pub fn new_fd(id: impl Into<Id>, payload: &[u8]) -> Result<Self, FrameError> {
667        if payload.len() > MAX_DATA_LEN {
668            return Err(FrameError::PayloadTooLong);
669        }
670        Ok(Self::build(id.into(), false, true, payload))
671    }
672
673    /// Sets whether the data phase is sent at the FD bit rate.
674    ///
675    /// Only a CAN FD frame can switch bit rate; the setting is ignored on a
676    /// classic frame.
677    pub fn with_bit_rate_switch(mut self, bit_rate_switch: bool) -> Self {
678        self.bit_rate_switch = bit_rate_switch && self.fd;
679        self
680    }
681
682    fn build(id: Id, request: bool, fd: bool, payload: &[u8]) -> Self {
683        let mut data = [0u8; MAX_DATA_LEN];
684        data[..payload.len()].copy_from_slice(payload);
685        Self {
686            id,
687            request,
688            fd,
689            bit_rate_switch: false,
690            error_state_indicator: false,
691            data,
692            len: payload.len(),
693            requested_len: 0,
694            timestamp: 0,
695        }
696    }
697
698    /// Returns the payload the frame carries.
699    pub fn payload(&self) -> &[u8] {
700        &self.data[..self.len]
701    }
702
703    /// Returns the payload length in bytes.
704    pub fn len(&self) -> usize {
705        self.len
706    }
707
708    /// Returns whether the frame carries no payload.
709    pub fn is_empty(&self) -> bool {
710        self.len == 0
711    }
712
713    /// Returns the payload length a request frame asks for, in bytes.
714    ///
715    /// Zero for a data frame, whose length is [`Frame::len`].
716    pub fn requested_len(&self) -> usize {
717        self.requested_len
718    }
719
720    /// Returns the data length code the frame is sent with.
721    ///
722    /// A payload length that no code expresses is padded up to the next one,
723    /// so a received copy of the frame can be longer than [`Frame::len`].
724    pub fn dlc(&self) -> u8 {
725        if self.request {
726            len_to_dlc(self.requested_len as u8)
727        } else {
728            len_to_dlc(self.len as u8)
729        }
730    }
731
732    /// Returns the arbitration identifier.
733    pub fn id(&self) -> Id {
734        self.id
735    }
736
737    /// Returns whether the identifier is a 29-bit extended one.
738    pub fn is_extended(&self) -> bool {
739        matches!(self.id, Id::Extended(_))
740    }
741
742    /// Returns whether this is a request frame, which carries no payload.
743    pub fn is_request(&self) -> bool {
744        self.request
745    }
746
747    /// Returns whether the frame uses the CAN FD format.
748    pub fn is_fd(&self) -> bool {
749        self.fd
750    }
751
752    /// Returns whether the data phase uses the FD bit rate.
753    pub fn is_bit_rate_switched(&self) -> bool {
754        self.bit_rate_switch
755    }
756
757    /// Returns the error state indicator of the transmitting node.
758    pub fn error_state_indicator(&self) -> bool {
759        self.error_state_indicator
760    }
761
762    /// Returns the timestamp captured when the frame was received.
763    ///
764    /// Zero for a frame that was not received; see
765    /// [`CanFd::start_timestamp_timer`].
766    pub fn timestamp(&self) -> u64 {
767        self.timestamp
768    }
769
770    fn to_buffer(self) -> FrameBuffer {
771        FrameBuffer::build(
772            FrameHeader {
773                id: self.id,
774                request: self.request,
775                fd: self.fd,
776                bit_rate_switch: self.bit_rate_switch,
777                dlc: self.dlc(),
778            },
779            self.payload(),
780        )
781    }
782
783    fn from_buffer(buffer: &FrameBuffer) -> Self {
784        let payload = buffer.data();
785        let mut data = [0u8; MAX_DATA_LEN];
786        data[..payload.len()].copy_from_slice(payload);
787        let request = buffer.is_request();
788        Self {
789            id: buffer.id(),
790            request,
791            fd: buffer.is_fd(),
792            bit_rate_switch: buffer.is_bit_rate_switched(),
793            error_state_indicator: buffer.error_state_indicator(),
794            data,
795            len: payload.len(),
796            requested_len: if request { buffer.requested_len() } else { 0 },
797            timestamp: buffer.timestamp(),
798        }
799    }
800
801    fn raw_id(&self) -> u32 {
802        match self.id {
803            Id::Standard(id) => u32::from(id.as_raw()),
804            Id::Extended(id) => id.as_raw(),
805        }
806    }
807}
808
809impl core::fmt::Debug for Frame {
810    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
811        f.debug_struct("Frame")
812            .field("id", &format_args!("{:#x}", self.raw_id()))
813            .field("extended", &self.is_extended())
814            .field("request", &self.request)
815            .field("fd", &self.fd)
816            .field("bit_rate_switch", &self.bit_rate_switch)
817            .field("error_state_indicator", &self.error_state_indicator)
818            .field("dlc", &self.dlc())
819            .field("len", &self.len)
820            .field("timestamp", &self.timestamp)
821            .field("data", &self.payload())
822            .finish()
823    }
824}
825
826#[cfg(feature = "defmt")]
827impl defmt::Format for Frame {
828    fn format(&self, f: defmt::Formatter<'_>) {
829        defmt::write!(
830            f,
831            "Frame {{ id: {=u32:#x}, extended: {}, request: {}, fd: {}, brs: {}, esi: {}, dlc: {=u8}, len: {=usize}, timestamp: {=u64}, data: {=[u8]:#x} }}",
832            self.raw_id(),
833            self.is_extended(),
834            self.request,
835            self.fd,
836            self.bit_rate_switch,
837            self.error_state_indicator,
838            self.dlc(),
839            self.len,
840            self.timestamp,
841            self.payload()
842        )
843    }
844}
845
846/// A frame that is known to be classic CAN, for code written against
847/// `embedded-can`.
848///
849/// [`embedded_can::Frame`] promises at most 8 bytes of data, which a [`Frame`]
850/// cannot keep: a 64-byte FD frame is a `Frame` too. The trait is therefore
851/// implemented on this type, which the trait constructors build directly and
852/// which `TryFrom<Frame>` refuses to make from an FD frame.
853///
854/// The type dereferences to the [`Frame`] it wraps and converts back into one
855/// for [`CanFd::transmit`].
856#[derive(Clone, Copy, Debug)]
857#[cfg_attr(feature = "defmt", derive(defmt::Format))]
858pub struct ClassicFrame(Frame);
859
860impl ClassicFrame {
861    /// Returns the frame this wraps.
862    pub fn into_frame(self) -> Frame {
863        self.0
864    }
865}
866
867impl core::ops::Deref for ClassicFrame {
868    type Target = Frame;
869
870    fn deref(&self) -> &Frame {
871        &self.0
872    }
873}
874
875impl TryFrom<Frame> for ClassicFrame {
876    type Error = FrameError;
877
878    /// # Errors
879    ///
880    /// [`FrameError::NotClassic`] when the frame uses the CAN FD format.
881    fn try_from(frame: Frame) -> Result<Self, FrameError> {
882        if frame.fd {
883            return Err(FrameError::NotClassic);
884        }
885        Ok(Self(frame))
886    }
887}
888
889impl From<ClassicFrame> for Frame {
890    fn from(frame: ClassicFrame) -> Self {
891        frame.0
892    }
893}
894
895#[instability::unstable]
896impl embedded_can::Frame for ClassicFrame {
897    fn new(id: impl Into<Id>, data: &[u8]) -> Option<Self> {
898        Frame::new(id, data).ok().map(Self)
899    }
900
901    fn new_remote(id: impl Into<Id>, dlc: usize) -> Option<Self> {
902        Frame::new_request(id, dlc).ok().map(Self)
903    }
904
905    fn is_extended(&self) -> bool {
906        self.0.is_extended()
907    }
908
909    fn is_remote_frame(&self) -> bool {
910        self.0.request
911    }
912
913    fn id(&self) -> Id {
914        self.0.id
915    }
916
917    fn dlc(&self) -> usize {
918        // The trait defines this as the payload length of a data frame and the
919        // requested length of a remote frame.
920        if self.0.request {
921            self.0.requested_len
922        } else {
923            self.0.len
924        }
925    }
926
927    fn data(&self) -> &[u8] {
928        self.0.payload()
929    }
930}
931
932#[instability::unstable]
933impl From<BusErrorKind> for embedded_can::ErrorKind {
934    fn from(kind: BusErrorKind) -> Self {
935        match kind {
936            BusErrorKind::Bit => Self::Bit,
937            BusErrorKind::Crc => Self::Crc,
938            BusErrorKind::Form => Self::Form,
939            BusErrorKind::Ack => Self::Acknowledge,
940            BusErrorKind::Stuff => Self::Stuff,
941            BusErrorKind::Unknown(_) => Self::Other,
942        }
943    }
944}
945
946#[instability::unstable]
947impl embedded_can::Error for BusErrorKind {
948    fn kind(&self) -> embedded_can::ErrorKind {
949        (*self).into()
950    }
951}
952
953impl core::error::Error for BusErrorKind {}
954
955impl core::fmt::Display for BusErrorKind {
956    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
957        match self {
958            Self::Bit => f.write_str("The transmitted bit did not match the bit sampled back"),
959            Self::Crc => f.write_str("The CRC of the frame did not match"),
960            Self::Form => f.write_str("A fixed-form field held an illegal value"),
961            Self::Ack => f.write_str("No node acknowledged the frame"),
962            Self::Stuff => f.write_str("A stuffing rule was violated"),
963            Self::Unknown(code) => write!(f, "Unknown bus error code {code}"),
964        }
965    }
966}
967
968/// A CAN FD controller.
969pub struct CanFd<'d, Dm: DriverMode = Blocking> {
970    // Drop order matters: the controller leaves the bus before its clocks are
971    // released, and the function clock goes before the register clock.
972    bus: BusGuard,
973    config: Config,
974    _mode: PhantomData<Dm>,
975    /// Accepted frame kinds for filters A, B, C and the range filter. They
976    /// share one register.
977    filter_kinds: [FrameKinds; 4],
978    /// Whether a pin has been assigned, which commits `no_transceiver`.
979    pins_bound: bool,
980    twai: AnyCanFd<'d>,
981    _function_clock: FunctionClockGuard,
982    _peripheral: PeripheralGuard,
983}
984
985impl<Dm: DriverMode> core::fmt::Debug for CanFd<'_, Dm> {
986    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
987        f.debug_struct("CanFd")
988            .field("twai", &self.twai)
989            .field("config", &self.config)
990            .field("started", &self.is_started())
991            .finish_non_exhaustive()
992    }
993}
994
995#[cfg(feature = "defmt")]
996impl<Dm: DriverMode> defmt::Format for CanFd<'_, Dm> {
997    fn format(&self, f: defmt::Formatter<'_>) {
998        defmt::write!(
999            f,
1000            "CanFd {{ twai: {:?}, config: {:?}, started: {} }}",
1001            self.twai,
1002            self.config,
1003            self.is_started()
1004        )
1005    }
1006}
1007
1008/// Receiving half of a split controller.
1009///
1010/// Borrows the driver, which keeps the configuration and the teardown. See
1011/// [`CanFd::split`].
1012pub struct CanFdRx<'a, Dm: DriverMode> {
1013    driver: Driver,
1014    state: &'static asynch::State,
1015    _driver: PhantomData<&'a mut ()>,
1016    _mode: PhantomData<Dm>,
1017}
1018
1019/// Transmitting half of a split controller.
1020///
1021/// See [`CanFd::split`].
1022pub struct CanFdTx<'a, Dm: DriverMode> {
1023    driver: Driver,
1024    state: &'static asynch::State,
1025    tx_buffers: u8,
1026    _driver: PhantomData<&'a mut ()>,
1027    _mode: PhantomData<Dm>,
1028}
1029
1030impl<Dm: DriverMode> core::fmt::Debug for CanFdRx<'_, Dm> {
1031    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1032        f.debug_struct("CanFdRx")
1033            .field("rx_frame_count", &self.rx_frame_count())
1034            .finish_non_exhaustive()
1035    }
1036}
1037
1038impl<Dm: DriverMode> core::fmt::Debug for CanFdTx<'_, Dm> {
1039    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1040        f.debug_struct("CanFdTx")
1041            .field("tx_buffers", &self.tx_buffers)
1042            .finish_non_exhaustive()
1043    }
1044}
1045
1046#[cfg(feature = "defmt")]
1047impl<Dm: DriverMode> defmt::Format for CanFdRx<'_, Dm> {
1048    fn format(&self, f: defmt::Formatter<'_>) {
1049        defmt::write!(
1050            f,
1051            "CanFdRx {{ rx_frame_count: {=u16} }}",
1052            self.rx_frame_count()
1053        )
1054    }
1055}
1056
1057#[cfg(feature = "defmt")]
1058impl<Dm: DriverMode> defmt::Format for CanFdTx<'_, Dm> {
1059    fn format(&self, f: defmt::Formatter<'_>) {
1060        defmt::write!(f, "CanFdTx {{ tx_buffers: {=u8} }}", self.tx_buffers)
1061    }
1062}
1063
1064impl<Dm: DriverMode> CanFdRx<'_, Dm> {
1065    /// Returns the number of complete frames waiting in the RX buffer.
1066    pub fn rx_frame_count(&self) -> u16 {
1067        self.driver.rx_frame_count()
1068    }
1069
1070    /// Reads one frame from the RX buffer.
1071    ///
1072    /// # Errors
1073    ///
1074    /// [`Error::RxBufferEmpty`] when no complete frame is waiting.
1075    pub fn receive(&mut self) -> Result<Frame, Error> {
1076        if self.driver.rx_frame_count() == 0 {
1077            return Err(Error::RxBufferEmpty);
1078        }
1079        Ok(Frame::from_buffer(&self.driver.read_rx_frame()))
1080    }
1081
1082    /// Discards everything in the RX buffer.
1083    pub fn flush_rx(&mut self) {
1084        self.driver.flush_rx();
1085    }
1086
1087    /// Returns the size of the RX buffer in 32-bit words.
1088    pub fn rx_buffer_size_words(&self) -> u16 {
1089        self.driver.rx_buffer_size()
1090    }
1091
1092    /// Returns the free space in the RX buffer in 32-bit words.
1093    pub fn rx_buffer_free_words(&self) -> u16 {
1094        self.driver.rx_free_words()
1095    }
1096
1097    /// Returns whether the RX buffer has overrun and dropped a frame
1098    /// (TRM 38.3.9.4).
1099    pub fn rx_overrun(&self) -> bool {
1100        self.driver.rx_overrun()
1101    }
1102
1103    /// Clears the RX buffer overrun flag.
1104    pub fn clear_rx_overrun(&mut self) {
1105        self.driver.clear_overrun();
1106    }
1107
1108    /// Returns the current fault confinement state; see [`CanFd::error_state`].
1109    pub fn error_state(&self) -> ErrorState {
1110        self.driver.error_state()
1111    }
1112
1113    /// Returns the receive error counter.
1114    pub fn receive_error_count(&self) -> u16 {
1115        self.driver.rec()
1116    }
1117
1118    /// Returns the transmit error counter.
1119    pub fn transmit_error_count(&self) -> u16 {
1120        self.driver.tec()
1121    }
1122}
1123
1124impl CanFdRx<'_, Async> {
1125    /// Waits until a frame is received, then reads it.
1126    ///
1127    /// # Cancellation Safety
1128    ///
1129    /// This future is cancel-safe. A frame stays in the hardware RX buffer
1130    /// until it is read, so dropping the future loses nothing.
1131    pub async fn receive_async(&mut self) -> Frame {
1132        core::future::poll_fn(|cx| {
1133            self.state.rx_waker.register(cx.waker());
1134            // Armed before the check, so a frame arriving in between still
1135            // raises the interrupt.
1136            self.driver
1137                .enable_interrupts(CanFdInterrupt::RxNotEmpty.bit());
1138
1139            if self.driver.rx_frame_count() > 0 {
1140                self.driver
1141                    .disable_interrupts(CanFdInterrupt::RxNotEmpty.bit());
1142                return core::task::Poll::Ready(());
1143            }
1144
1145            core::task::Poll::Pending
1146        })
1147        .await;
1148
1149        Frame::from_buffer(&self.driver.read_rx_frame())
1150    }
1151}
1152
1153impl<Dm: DriverMode> CanFdTx<'_, Dm> {
1154    /// Returns the number of TX buffers the hardware provides.
1155    pub fn tx_buffer_count(&self) -> u8 {
1156        self.tx_buffers
1157    }
1158
1159    /// Queues a frame in the first free TX buffer and arms it.
1160    ///
1161    /// Returns the index of the buffer used. Up to [`CanFdTx::tx_buffer_count`]
1162    /// frames can be queued at once.
1163    ///
1164    /// The hardware picks the next frame to send among the armed buffers by
1165    /// priority, and among equal priorities by the lower buffer index; see
1166    /// [`CanFdTx::set_tx_priority`]. The order in which frames were queued
1167    /// plays no part in that choice. With equal priorities a frame queued into
1168    /// a buffer that a finished frame freed up is sent before frames still
1169    /// waiting in higher-numbered buffers. To keep frames in the order they
1170    /// were queued, wait for each buffer to leave [`TxBufferState::Ready`]
1171    /// before queueing the next frame, or give later frames lower priorities.
1172    ///
1173    /// # Errors
1174    ///
1175    /// [`Error::ControllerStopped`] when the controller is not on the bus. A
1176    /// stopped controller ignores the command that arms a buffer, so the frame
1177    /// would be lost.
1178    ///
1179    /// [`Error::NoFreeTxBuffer`] when every TX buffer is occupied.
1180    pub fn transmit(&mut self, frame: &Frame) -> Result<u8, Error> {
1181        if !self.driver.is_enabled() {
1182            return Err(Error::ControllerStopped);
1183        }
1184
1185        let index = (0..self.tx_buffers)
1186            .find(|&i| self.driver.tx_buffer_state(i).is_writable())
1187            .ok_or(Error::NoFreeTxBuffer)?;
1188
1189        self.driver.write_tx_buffer(index, &frame.to_buffer());
1190        self.driver.set_tx_ready(index);
1191        Ok(index)
1192    }
1193
1194    /// Returns the state of one TX buffer.
1195    ///
1196    /// Returns [`TxBufferState::NotExist`] for an index the hardware does not
1197    /// have.
1198    pub fn tx_buffer_state(&self, index: u8) -> TxBufferState {
1199        if index >= self.tx_buffers {
1200            return TxBufferState::NotExist;
1201        }
1202        self.driver.tx_buffer_state(index)
1203    }
1204
1205    /// Requests that a queued transmission be aborted.
1206    ///
1207    /// Does nothing for an index the hardware does not have.
1208    pub fn abort_transmit(&mut self, index: u8) {
1209        if index < self.tx_buffers {
1210            self.driver.set_tx_abort(index);
1211        }
1212    }
1213
1214    /// Returns a TX buffer to the empty state, releasing it for reuse.
1215    ///
1216    /// Does nothing for an index the hardware does not have.
1217    pub fn release_tx_buffer(&mut self, index: u8) {
1218        if index < self.tx_buffers {
1219            self.driver.set_tx_empty(index);
1220        }
1221    }
1222
1223    /// Sets a TX buffer's arbitration priority.
1224    ///
1225    /// Higher values win. Equal priorities are resolved in favor of the lower
1226    /// buffer index (TRM 38.3.8.1). A value above [`MAX_TX_PRIORITY`] counts as
1227    /// that maximum. Does nothing for an index the hardware does not have.
1228    ///
1229    /// The priority belongs to the buffer, not to the frame in it, and all
1230    /// buffers start out equal. Set it before arming the buffer with
1231    /// [`CanFdTx::transmit`], or right after, while the frame is still
1232    /// [`TxBufferState::Ready`].
1233    pub fn set_tx_priority(&mut self, index: u8, priority: u8) {
1234        if index < self.tx_buffers {
1235            self.driver
1236                .set_tx_priority(index, priority.min(MAX_TX_PRIORITY));
1237        }
1238    }
1239
1240    /// Returns the current fault confinement state; see [`CanFd::error_state`].
1241    ///
1242    /// On bus-off every armed TX buffer fails, so a transmission that ends in
1243    /// [`Error::TransmitFailed`] can be told apart from an exhausted
1244    /// retransmission limit here.
1245    pub fn error_state(&self) -> ErrorState {
1246        self.driver.error_state()
1247    }
1248
1249    /// Returns the receive error counter.
1250    pub fn receive_error_count(&self) -> u16 {
1251        self.driver.rec()
1252    }
1253
1254    /// Returns the transmit error counter.
1255    pub fn transmit_error_count(&self) -> u16 {
1256        self.driver.tec()
1257    }
1258
1259    /// Requests that a bus-off controller rejoin the bus.
1260    ///
1261    /// Does nothing unless the controller is bus-off. Rejoining takes 128
1262    /// occurrences of 11 recessive bits, as ISO 11898-1 requires. Leaving the
1263    /// bus with [`CanFd::stop`] and joining it again with [`CanFd::start`] also
1264    /// clears the bus-off state, after ordinary integration.
1265    ///
1266    /// The state is checked here because the hardware remembers a request made
1267    /// while error-active and then rejoins on its own the next time it goes
1268    /// bus-off (measured on an ESP32-C5; TRM register 38.3 says otherwise).
1269    pub fn request_bus_off_recovery(&mut self) {
1270        if self.driver.error_state() == ErrorState::BusOff {
1271            self.driver.request_bus_off_recovery();
1272        }
1273    }
1274}
1275
1276impl CanFdTx<'_, Async> {
1277    /// Queues a frame and waits until the hardware finishes with it.
1278    ///
1279    /// # Errors
1280    ///
1281    /// [`Error::ControllerStopped`] when the controller is not on the bus, and
1282    /// [`Error::NoFreeTxBuffer`] when every TX buffer is occupied; see
1283    /// [`CanFdTx::transmit`].
1284    ///
1285    /// [`Error::TransmitFailed`] when the controller gave up on the frame.
1286    ///
1287    /// [`Error::TransmitAborted`] when the transmission was aborted.
1288    ///
1289    /// # Cancellation Safety
1290    ///
1291    /// This future is not cancel-safe. Dropping it leaves the frame queued, and
1292    /// the hardware may still transmit it.
1293    pub async fn transmit_async(&mut self, frame: &Frame) -> Result<(), Error> {
1294        let index = self.transmit(frame)?;
1295
1296        core::future::poll_fn(|cx| {
1297            self.state.tx_waker.register(cx.waker());
1298            // Armed before the check, so a transmission finishing in between
1299            // still raises the interrupt.
1300            self.driver.enable_interrupts(CanFdInterrupt::TxDone.bit());
1301
1302            let state = self.driver.tx_buffer_state(index);
1303            if !matches!(
1304                state,
1305                TxBufferState::Ready | TxBufferState::InProgress | TxBufferState::AbortInProgress
1306            ) {
1307                self.driver.disable_interrupts(CanFdInterrupt::TxDone.bit());
1308            }
1309
1310            match state {
1311                TxBufferState::Ready
1312                | TxBufferState::InProgress
1313                | TxBufferState::AbortInProgress => core::task::Poll::Pending,
1314                TxBufferState::Ok => core::task::Poll::Ready(Ok(())),
1315                TxBufferState::Failed => core::task::Poll::Ready(Err(Error::TransmitFailed)),
1316                TxBufferState::Aborted => core::task::Poll::Ready(Err(Error::TransmitAborted)),
1317                _ => core::task::Poll::Ready(Err(Error::NoFreeTxBuffer)),
1318            }
1319        })
1320        .await
1321    }
1322}
1323
1324/// Owns the controller's participation in the bus, so that a dropped driver
1325/// leaves the bus cleanly instead of cutting a frame short.
1326struct BusGuard {
1327    driver: Driver,
1328    tx_buffers: u8,
1329    interrupt: Interrupt,
1330    /// How long a frame in flight is given to finish at the configured bit
1331    /// rate.
1332    abort_timeout: Duration,
1333    /// Held while the controller is on the bus: light sleep gates the function
1334    /// clock, and a frame keeps going after the future that queued it is
1335    /// dropped.
1336    wake_lock: Option<WakeLock>,
1337}
1338
1339impl BusGuard {
1340    fn enable(&mut self) {
1341        self.driver.enable(true);
1342        if self.wake_lock.is_none() {
1343            self.wake_lock = Some(WakeLock::new());
1344        }
1345    }
1346
1347    fn disable(&mut self) {
1348        self.driver.enable(false);
1349        self.wake_lock = None;
1350    }
1351
1352    /// Aborts anything queued and waits for the wire to be free (TRM 38.3.6
1353    /// step 1).
1354    fn quiesce(&self) -> Result<(), Error> {
1355        for index in 0..self.tx_buffers {
1356            self.driver.set_tx_abort(index);
1357        }
1358
1359        let deadline = Instant::now() + self.abort_timeout;
1360        for index in 0..self.tx_buffers {
1361            while matches!(
1362                self.driver.tx_buffer_state(index),
1363                TxBufferState::Ready | TxBufferState::InProgress | TxBufferState::AbortInProgress
1364            ) {
1365                if Instant::now() > deadline {
1366                    return Err(Error::AbortTimeout);
1367                }
1368            }
1369        }
1370
1371        Ok(())
1372    }
1373}
1374
1375impl Drop for BusGuard {
1376    fn drop(&mut self) {
1377        // An interrupt source left armed keeps the request line asserted after
1378        // the clocks are gone, and the handler could no longer retire it.
1379        self.driver.disable_interrupts(u32::MAX);
1380        self.driver.clear_interrupts(u32::MAX);
1381        crate::interrupt::disable(Cpu::current(), self.interrupt);
1382
1383        // Best effort: a wedged transmission must not hang teardown.
1384        let _ = self.quiesce();
1385        self.disable();
1386    }
1387}
1388
1389impl crate::private::Sealed for CanFd<'_, Blocking> {}
1390
1391#[instability::unstable]
1392impl crate::interrupt::InterruptConfigurable for CanFd<'_, Blocking> {
1393    fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
1394        self.bind_interrupt_handler(handler);
1395    }
1396}
1397
1398impl<'d> CanFd<'d, Blocking> {
1399    /// Registers an interrupt handler for this controller.
1400    ///
1401    /// Replaces any previously registered handler. The handler runs for the
1402    /// sources enabled with [`CanFd::listen`]. It must clear them with
1403    /// [`CanFd::clear_interrupts`], or it runs again as soon as it returns.
1404    #[instability::unstable]
1405    pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
1406        self.bind_interrupt_handler(handler);
1407    }
1408
1409    /// Enables the given interrupt sources.
1410    ///
1411    /// Without a handler from [`CanFd::set_interrupt_handler`] this only makes
1412    /// [`CanFd::interrupts`] record what happened.
1413    pub fn listen(&mut self, interrupts: impl Into<EnumSet<CanFdInterrupt>>) {
1414        self.bus
1415            .driver
1416            .enable_interrupts(CanFdInterrupt::mask(interrupts.into()));
1417    }
1418
1419    /// Disables the given interrupt sources.
1420    pub fn unlisten(&mut self, interrupts: impl Into<EnumSet<CanFdInterrupt>>) {
1421        self.bus
1422            .driver
1423            .disable_interrupts(CanFdInterrupt::mask(interrupts.into()));
1424    }
1425
1426    /// Returns the interrupt sources that are currently asserted.
1427    pub fn interrupts(&self) -> EnumSet<CanFdInterrupt> {
1428        CanFdInterrupt::from_mask(self.bus.driver.interrupt_status())
1429    }
1430
1431    /// Clears the given interrupt sources.
1432    pub fn clear_interrupts(&mut self, interrupts: impl Into<EnumSet<CanFdInterrupt>>) {
1433        self.bus
1434            .driver
1435            .clear_interrupts(CanFdInterrupt::mask(interrupts.into()));
1436    }
1437
1438    /// Creates a new CAN FD driver in [`Blocking`] mode.
1439    ///
1440    /// The controller is configured but stays off the bus. Assign the pins with
1441    /// [`CanFd::with_rx`] and [`CanFd::with_tx`], then call [`CanFd::start`].
1442    ///
1443    /// # Errors
1444    ///
1445    /// [`ConfigError`] when the configuration does not fit the hardware.
1446    pub fn new(twai: impl Instance + 'd, config: Config) -> Result<Self, ConfigError> {
1447        let twai = twai.degrade();
1448        let info = twai.info();
1449        let peripheral = PeripheralGuard::new(info.peripheral);
1450        let function_clock = FunctionClockGuard::new(info.clock_instance, config.clock_source);
1451
1452        let driver = Driver::new(info.register_block);
1453        driver.reset();
1454        let tx_buffers = driver.tx_buffer_count();
1455
1456        let abort_timeout = abort_timeout(
1457            &config.nominal_timing,
1458            &config.fd_timing,
1459            info.clock_instance.function_clock_frequency(),
1460        );
1461
1462        let mut this = Self {
1463            bus: BusGuard {
1464                driver,
1465                tx_buffers,
1466                abort_timeout,
1467                interrupt: info.interrupt,
1468                wake_lock: None,
1469            },
1470            config,
1471            filter_kinds: RESET_FILTER_KINDS,
1472            pins_bound: false,
1473            _mode: PhantomData,
1474            twai,
1475            _function_clock: function_clock,
1476            _peripheral: peripheral,
1477        };
1478        this.configure()?;
1479
1480        Ok(this)
1481    }
1482
1483    /// Converts the driver into an async driver.
1484    pub fn into_async(self) -> CanFd<'d, Async> {
1485        let mut this = CanFd {
1486            bus: self.bus,
1487            config: self.config,
1488            filter_kinds: self.filter_kinds,
1489            pins_bound: self.pins_bound,
1490            _mode: PhantomData,
1491            twai: self.twai,
1492            _function_clock: self._function_clock,
1493            _peripheral: self._peripheral,
1494        };
1495        let handler = this.twai.info().async_handler;
1496        this.bind_interrupt_handler(handler);
1497
1498        this
1499    }
1500}
1501
1502impl<'d> CanFd<'d, Async> {
1503    /// Waits until a frame is received, then reads it.
1504    ///
1505    /// # Cancellation Safety
1506    ///
1507    /// This future is cancel-safe. A frame stays in the hardware RX buffer
1508    /// until it is read, so dropping the future loses nothing.
1509    pub async fn receive_async(&mut self) -> Frame {
1510        self.rx_half().receive_async().await
1511    }
1512
1513    /// Queues a frame and waits until the hardware finishes with it.
1514    ///
1515    /// # Errors
1516    ///
1517    /// [`Error::ControllerStopped`] when the controller is not on the bus, and
1518    /// [`Error::NoFreeTxBuffer`] when every TX buffer is occupied; see
1519    /// [`CanFdTx::transmit`].
1520    ///
1521    /// [`Error::TransmitFailed`] when the controller gave up on the frame.
1522    ///
1523    /// [`Error::TransmitAborted`] when the transmission was aborted.
1524    ///
1525    /// # Cancellation Safety
1526    ///
1527    /// This future is not cancel-safe. Dropping it leaves the frame queued, and
1528    /// the hardware may still transmit it.
1529    pub async fn transmit_async(&mut self, frame: &Frame) -> Result<(), Error> {
1530        self.tx_half().transmit_async(frame).await
1531    }
1532
1533    /// Converts the driver back into a blocking driver.
1534    pub fn into_blocking(self) -> CanFd<'d, Blocking> {
1535        self.bus.driver.disable_interrupts(u32::MAX);
1536        crate::interrupt::disable(Cpu::current(), self.twai.info().interrupt);
1537
1538        CanFd {
1539            bus: self.bus,
1540            config: self.config,
1541            filter_kinds: self.filter_kinds,
1542            pins_bound: self.pins_bound,
1543            _mode: PhantomData,
1544            twai: self.twai,
1545            _function_clock: self._function_clock,
1546            _peripheral: self._peripheral,
1547        }
1548    }
1549}
1550
1551impl<'d, Dm: DriverMode> CanFd<'d, Dm> {
1552    fn bind_interrupt_handler(&mut self, handler: InterruptHandler) {
1553        let interrupt = self.twai.info().interrupt;
1554        crate::interrupt::disable(Cpu::current(), interrupt);
1555        self.bus.driver.disable_interrupts(u32::MAX);
1556        self.bus.driver.clear_interrupts(u32::MAX);
1557        crate::interrupt::bind_handler(interrupt, handler);
1558        crate::interrupt::enable(interrupt, handler.priority());
1559    }
1560
1561    /// Assigns the RX pin.
1562    ///
1563    /// The pin is driven according to [`Config::with_no_transceiver`]. That
1564    /// setting is committed to the hardware here and cannot change afterwards.
1565    pub fn with_rx(mut self, rx: impl PeripheralInput<'d>) -> Self {
1566        let rx = rx.into();
1567        rx.apply_input_config(&InputConfig::default().with_pull(self.pin_pull()));
1568        rx.set_input_enable(true);
1569        self.twai.info().rx_signal.connect_to(&rx);
1570        self.pins_bound = true;
1571
1572        self
1573    }
1574
1575    /// Assigns the TX pin.
1576    ///
1577    /// With [`Config::with_no_transceiver`] set, the pin is driven open-drain
1578    /// with a pull-up. Assigning the same pin to [`CanFd::with_rx`] then forms
1579    /// a single-node bus that needs no external wiring. That setting is
1580    /// committed to the hardware here and cannot change afterwards.
1581    pub fn with_tx(mut self, tx: impl PeripheralOutput<'d>) -> Self {
1582        let tx = tx.into();
1583        let mut output = OutputConfig::default();
1584        if self.config.no_transceiver {
1585            output = output
1586                .with_drive_mode(DriveMode::OpenDrain)
1587                .with_pull(Pull::Up);
1588        }
1589        tx.apply_output_config(&output);
1590        tx.set_output_enable(true);
1591        self.twai.info().tx_signal.connect_to(&tx);
1592        self.pins_bound = true;
1593
1594        self
1595    }
1596
1597    fn pin_pull(&self) -> Pull {
1598        if self.config.no_transceiver {
1599            Pull::Up
1600        } else {
1601            Pull::None
1602        }
1603    }
1604
1605    /// Applies a new configuration.
1606    ///
1607    /// The controller leaves the bus while the configuration is applied. A
1608    /// running driver must be started again with [`CanFd::start`] afterwards.
1609    /// A change of clock source also stops a running timestamp counter,
1610    /// because its resolution is derived from that clock. Start it again with
1611    /// [`CanFd::start_timestamp_timer`] and use the resolution that it returns.
1612    ///
1613    /// # Errors
1614    ///
1615    /// [`ConfigError`] when the configuration does not fit the hardware.
1616    ///
1617    /// [`ConfigError::TransceiverModeLocked`] when the configuration changes
1618    /// [`Config::with_no_transceiver`] after a pin has been assigned.
1619    pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
1620        config.validate()?;
1621
1622        if self.pins_bound && config.no_transceiver != self.config.no_transceiver {
1623            return Err(ConfigError::TransceiverModeLocked);
1624        }
1625
1626        // The prescaler divides the function clock, so a new source would
1627        // silently rescale a running counter.
1628        if config.clock_source != self.config.clock_source {
1629            self.stop_timestamp_timer();
1630        }
1631
1632        // `configure` refuses before writing anything, so `config()` keeps
1633        // describing the hardware.
1634        let previous = self.config;
1635        self.config = *config;
1636        self.configure().inspect_err(|_| self.config = previous)
1637    }
1638
1639    /// Returns the current configuration.
1640    pub fn config(&self) -> &Config {
1641        &self.config
1642    }
1643
1644    /// Writes the stored configuration to the hardware, leaving the bus.
1645    fn configure(&mut self) -> Result<(), ConfigError> {
1646        self.config.validate()?;
1647
1648        if self.bus.driver.is_enabled() {
1649            self.bus.quiesce().map_err(|_| ConfigError::BusBusy)?;
1650        }
1651
1652        // Mode bits can only be changed while the controller is disabled.
1653        self.bus.disable();
1654
1655        // The timing below is expressed in periods of the function clock
1656        // (TRM 38.3.1), so the mux is switched first.
1657        self._function_clock.set_source(self.config.clock_source);
1658
1659        let config = self.config;
1660        let (listen_only, self_test, loopback) = match config.mode {
1661            Mode::Normal => (false, false, false),
1662            Mode::ListenOnly => (true, false, false),
1663            Mode::SelfTest => (false, true, false),
1664            Mode::LoopbackSelfTest => (false, true, true),
1665        };
1666
1667        self.bus.driver.apply_mode_settings(&ll::ModeSettings {
1668            listen_only,
1669            self_test,
1670            loopback,
1671            fd_enabled: true,
1672            protocol_exception: config.protocol_exception,
1673            rx_auto_increment: true,
1674            filters_enabled: true,
1675            bus_off_tx_fail: true,
1676            drop_request_frames: config.drop_request_frames,
1677            time_triggered_tx: false,
1678            retransmit_limit: config.retransmit_limit,
1679        });
1680
1681        self.bus
1682            .driver
1683            .set_timestamp_point(TimestampPoint::EndOfFrame);
1684
1685        self.bus.driver.set_nominal_timing(&config.nominal_timing);
1686        self.bus.driver.set_fd_timing(&config.fd_timing);
1687
1688        self.bus.abort_timeout = abort_timeout(
1689            &config.nominal_timing,
1690            &config.fd_timing,
1691            self.function_clock_frequency(),
1692        );
1693
1694        match config.secondary_sample_point_offset {
1695            // The hardware counts the offset in function clock cycles.
1696            Some(offset) => self.bus.driver.set_secondary_sample_point(
1697                SspSource::MeasuredPlusOffset,
1698                offset.saturating_mul(config.fd_timing.baud_rate_prescaler),
1699            ),
1700            None => self
1701                .bus
1702                .driver
1703                .set_secondary_sample_point(SspSource::Disabled, 0),
1704        }
1705
1706        Ok(())
1707    }
1708
1709    /// Joins the bus and waits for the controller to become error-active.
1710    ///
1711    /// Follows the initialization sequence in TRM 38.3.5.
1712    ///
1713    /// # Errors
1714    ///
1715    /// [`Error::BusIntegrationTimeout`] when the bus does not go idle-recessive
1716    /// long enough for the controller to join it. The controller stays off the
1717    /// bus in that case, unless it was on the bus before the call.
1718    pub fn start(&mut self) -> Result<(), Error> {
1719        let timeout = integration_timeout(
1720            &self.config.nominal_timing,
1721            &self.config.fd_timing,
1722            self.function_clock_frequency(),
1723        );
1724
1725        let was_enabled = self.bus.driver.is_enabled();
1726        self.bus.enable();
1727
1728        // Integration finishes when the controller becomes error-active, after
1729        // 11 consecutive recessive bits.
1730        let deadline = Instant::now() + timeout;
1731        loop {
1732            if self.bus.driver.error_state() == ErrorState::Active {
1733                return Ok(());
1734            }
1735            if Instant::now() > deadline {
1736                if !was_enabled {
1737                    self.bus.disable();
1738                }
1739                return Err(Error::BusIntegrationTimeout);
1740            }
1741        }
1742    }
1743
1744    /// Leaves the bus, following the de-initialization sequence in TRM 38.3.6.
1745    ///
1746    /// Every TX buffer returns to the empty state without its memory being
1747    /// cleared, and the RX buffer is flushed.
1748    ///
1749    /// While the controller is on the bus, the driver holds a [`WakeLock`],
1750    /// because Light-sleep mode gates the function clock. Leaving the bus
1751    /// releases the lock. A running timestamp counter does not advance during
1752    /// sleep.
1753    ///
1754    /// # Errors
1755    ///
1756    /// [`Error::AbortTimeout`] when a transmission does not settle. The
1757    /// controller stays on the bus in that case.
1758    pub fn stop(&mut self) -> Result<(), Error> {
1759        self.bus.quiesce()?;
1760        self.bus.disable();
1761        Ok(())
1762    }
1763
1764    /// Returns whether the controller is on the bus.
1765    ///
1766    /// This is true between a successful [`CanFd::start`] and the next
1767    /// [`CanFd::stop`] or [`CanFd::apply_config`].
1768    pub fn is_started(&self) -> bool {
1769        self.bus.driver.is_enabled()
1770    }
1771
1772    /// Returns the identity of the core.
1773    pub fn identity(&self) -> Identity {
1774        let (major, minor) = self.bus.driver.version();
1775        Identity {
1776            device_id: self.bus.driver.device_id(),
1777            version_major: major,
1778            version_minor: minor,
1779        }
1780    }
1781
1782    /// Returns the frequency of the controller's function clock, in Hz.
1783    pub fn function_clock_frequency(&self) -> u32 {
1784        self.twai.info().clock_instance.function_clock_frequency()
1785    }
1786
1787    /// Splits the controller into a receiving and a transmitting half.
1788    ///
1789    /// The two halves can be used at the same time, for example to wait for a
1790    /// frame while a transmission is in flight. They arm different interrupt
1791    /// sources, so neither disturbs the other.
1792    ///
1793    /// The halves borrow the driver, which keeps the configuration and the
1794    /// teardown: everything that reconfigures the controller or takes it off
1795    /// the bus stays on [`CanFd`] and is unavailable while a half is alive. For
1796    /// two independent tasks, split a driver that lives in a `static`.
1797    pub fn split(&mut self) -> (CanFdRx<'_, Dm>, CanFdTx<'_, Dm>) {
1798        let (info, state) = self.twai.parts();
1799        (
1800            CanFdRx {
1801                driver: Driver::new(info.register_block),
1802                state,
1803                _driver: PhantomData,
1804                _mode: PhantomData,
1805            },
1806            CanFdTx {
1807                driver: Driver::new(info.register_block),
1808                state,
1809                tx_buffers: self.bus.tx_buffers,
1810                _driver: PhantomData,
1811                _mode: PhantomData,
1812            },
1813        )
1814    }
1815
1816    fn rx_half(&mut self) -> CanFdRx<'_, Dm> {
1817        self.split().0
1818    }
1819
1820    fn tx_half(&mut self) -> CanFdTx<'_, Dm> {
1821        self.split().1
1822    }
1823
1824    /// Returns the number of TX buffers the hardware provides.
1825    pub fn tx_buffer_count(&self) -> u8 {
1826        self.bus.tx_buffers
1827    }
1828
1829    /// Queues a frame in the first free TX buffer and arms it.
1830    ///
1831    /// Returns the index of the buffer used. The hardware chooses the order in
1832    /// which armed buffers are sent, not the order in which they were queued;
1833    /// see [`CanFdTx::transmit`].
1834    ///
1835    /// # Errors
1836    ///
1837    /// [`Error::ControllerStopped`] when the controller is not on the bus, and
1838    /// [`Error::NoFreeTxBuffer`] when every TX buffer is occupied; see
1839    /// [`CanFdTx::transmit`].
1840    pub fn transmit(&mut self, frame: &Frame) -> Result<u8, Error> {
1841        self.tx_half().transmit(frame)
1842    }
1843
1844    /// Returns the state of one TX buffer.
1845    ///
1846    /// Returns [`TxBufferState::NotExist`] for an index the hardware does not
1847    /// have.
1848    pub fn tx_buffer_state(&self, index: u8) -> TxBufferState {
1849        if index >= self.bus.tx_buffers {
1850            return TxBufferState::NotExist;
1851        }
1852        self.bus.driver.tx_buffer_state(index)
1853    }
1854
1855    /// Requests that a queued transmission be aborted.
1856    ///
1857    /// The buffer moves to "aborted", or to "abort in progress" if the frame is
1858    /// already on the wire. Does nothing for an index the hardware does not
1859    /// have.
1860    pub fn abort_transmit(&mut self, index: u8) {
1861        if index < self.bus.tx_buffers {
1862            self.bus.driver.set_tx_abort(index);
1863        }
1864    }
1865
1866    /// Returns a TX buffer to the empty state, releasing it for reuse.
1867    ///
1868    /// Does nothing for an index the hardware does not have.
1869    pub fn release_tx_buffer(&mut self, index: u8) {
1870        if index < self.bus.tx_buffers {
1871            self.bus.driver.set_tx_empty(index);
1872        }
1873    }
1874
1875    /// Sets a TX buffer's arbitration priority.
1876    ///
1877    /// Higher values win, and a value above [`MAX_TX_PRIORITY`] counts as that
1878    /// maximum; see [`CanFdTx::set_tx_priority`].
1879    pub fn set_tx_priority(&mut self, index: u8, priority: u8) {
1880        self.tx_half().set_tx_priority(index, priority);
1881    }
1882
1883    /// Returns the number of complete frames waiting in the RX buffer.
1884    pub fn rx_frame_count(&self) -> u16 {
1885        self.bus.driver.rx_frame_count()
1886    }
1887
1888    /// Reads one frame from the RX buffer.
1889    ///
1890    /// # Errors
1891    ///
1892    /// [`Error::RxBufferEmpty`] when no complete frame is waiting.
1893    pub fn receive(&mut self) -> Result<Frame, Error> {
1894        self.rx_half().receive()
1895    }
1896
1897    /// Discards everything in the RX buffer.
1898    pub fn flush_rx(&mut self) {
1899        self.bus.driver.flush_rx();
1900    }
1901
1902    /// Returns the size of the RX buffer in 32-bit words.
1903    pub fn rx_buffer_size_words(&self) -> u16 {
1904        self.bus.driver.rx_buffer_size()
1905    }
1906
1907    /// Returns the free space in the RX buffer in 32-bit words.
1908    pub fn rx_buffer_free_words(&self) -> u16 {
1909        self.bus.driver.rx_free_words()
1910    }
1911
1912    /// Returns whether the RX buffer has overrun and dropped a frame
1913    /// (TRM 38.3.9.4).
1914    pub fn rx_overrun(&self) -> bool {
1915        self.bus.driver.rx_overrun()
1916    }
1917
1918    /// Clears the RX buffer overrun flag.
1919    pub fn clear_rx_overrun(&mut self) {
1920        self.bus.driver.clear_overrun();
1921    }
1922
1923    /// Returns the current fault confinement state.
1924    ///
1925    /// Returns [`ErrorState::BusOff`] while the controller is off the bus, both
1926    /// before the first [`CanFd::start`] and after [`CanFd::stop`]; that is how
1927    /// the hardware reports a disabled controller. [`CanFd::is_started`] tells
1928    /// the two apart.
1929    pub fn error_state(&self) -> ErrorState {
1930        self.bus.driver.error_state()
1931    }
1932
1933    /// Returns whether an error counter has reached the error warning limit.
1934    ///
1935    /// A node at the limit is still [`ErrorState::Active`] (TRM 38.3.10).
1936    pub fn error_warning(&self) -> bool {
1937        self.bus.driver.error_warning()
1938    }
1939
1940    /// Returns the receive error counter.
1941    pub fn receive_error_count(&self) -> u16 {
1942        self.bus.driver.rec()
1943    }
1944
1945    /// Returns the transmit error counter.
1946    pub fn transmit_error_count(&self) -> u16 {
1947        self.bus.driver.tec()
1948    }
1949
1950    /// Requests that a bus-off controller rejoin the bus; see
1951    /// [`CanFdTx::request_bus_off_recovery`].
1952    pub fn request_bus_off_recovery(&mut self) {
1953        self.tx_half().request_bus_off_recovery();
1954    }
1955
1956    /// Sets the error warning limit, which defaults to 96.
1957    ///
1958    /// The hardware only accepts the write in test mode (TRM 38.3.10), which
1959    /// is entered for the write and left again.
1960    ///
1961    /// # Errors
1962    ///
1963    /// [`Error::ControllerRunning`] when the controller is still on the bus.
1964    pub fn set_error_warning_limit(&mut self, limit: u8) -> Result<(), Error> {
1965        if self.bus.driver.is_enabled() {
1966            return Err(Error::ControllerRunning);
1967        }
1968        self.bus.driver.enable_test_mode(true);
1969        self.bus.driver.set_error_warning_limit(limit);
1970        self.bus.driver.enable_test_mode(false);
1971        Ok(())
1972    }
1973
1974    /// Resets the received and transmitted frame counters.
1975    pub fn reset_traffic_counters(&mut self) {
1976        self.bus.driver.reset_traffic_counters();
1977    }
1978
1979    /// Returns the number of frames received since the traffic counters were
1980    /// last reset.
1981    pub fn rx_traffic_count(&self) -> u32 {
1982        self.bus.driver.rx_traffic_counter()
1983    }
1984
1985    /// Returns the number of frames transmitted since the traffic counters
1986    /// were last reset.
1987    pub fn tx_traffic_count(&self) -> u32 {
1988        self.bus.driver.tx_traffic_counter()
1989    }
1990
1991    /// Configures one mask filter and enables it.
1992    ///
1993    /// A frame reaches the RX buffer if it passes at least one enabled filter
1994    /// (TRM 38.3.9.8). Out of reset, filter A accepts every frame; see
1995    /// [`CanFd::accept_all`].
1996    pub fn set_mask_filter(&mut self, filter: MaskFilter, config: &MaskFilterConfig) {
1997        self.bus
1998            .driver
1999            .set_mask_filter(filter, config.extended, config.id, config.mask);
2000        self.filter_kinds[Self::mask_filter_index(filter)] = config.kinds();
2001        self.apply_filter_kinds();
2002    }
2003
2004    /// Disables one mask filter.
2005    pub fn disable_mask_filter(&mut self, filter: MaskFilter) {
2006        self.filter_kinds[Self::mask_filter_index(filter)] = FrameKinds::NONE;
2007        self.apply_filter_kinds();
2008    }
2009
2010    /// Configures the range filter and enables it.
2011    pub fn set_range_filter(&mut self, config: &RangeFilterConfig) {
2012        self.bus
2013            .driver
2014            .set_range_filter(config.extended, config.low, config.high);
2015        self.filter_kinds[RANGE_FILTER_INDEX] = config.kinds();
2016        self.apply_filter_kinds();
2017    }
2018
2019    /// Disables the range filter.
2020    pub fn disable_range_filter(&mut self) {
2021        self.filter_kinds[RANGE_FILTER_INDEX] = FrameKinds::NONE;
2022        self.apply_filter_kinds();
2023    }
2024
2025    /// Accepts every frame, by giving filter A a zero mask and disabling the rest.
2026    ///
2027    /// This is the one filter setting that matches standard and extended
2028    /// identifiers at once.
2029    pub fn accept_all(&mut self) {
2030        // A zero mask passes any identifier word, so the format only decides
2031        // how the zeros are shifted.
2032        self.bus.driver.set_mask_filter(MaskFilter::A, false, 0, 0);
2033        self.filter_kinds = RESET_FILTER_KINDS;
2034        self.apply_filter_kinds();
2035    }
2036
2037    fn mask_filter_index(filter: MaskFilter) -> usize {
2038        match filter {
2039            MaskFilter::A => 0,
2040            MaskFilter::B => 1,
2041            MaskFilter::C => 2,
2042        }
2043    }
2044
2045    fn apply_filter_kinds(&mut self) {
2046        let [a, b, c, range] = self.filter_kinds;
2047        self.bus.driver.set_filter_kinds(a, b, c, range);
2048    }
2049
2050    /// Returns details of the last bus error the core captured.
2051    ///
2052    /// Only meaningful after the core has reported a bus error; see
2053    /// [`ErrorCapture`].
2054    pub fn error_capture(&self) -> ErrorCapture {
2055        self.bus.driver.error_capture()
2056    }
2057
2058    /// Returns the number of retransmission attempts made for the frame
2059    /// currently being sent.
2060    pub fn retransmit_count(&self) -> u8 {
2061        self.bus.driver.retransmit_count()
2062    }
2063
2064    /// Returns the number of errors detected at the nominal bit rate.
2065    pub fn nominal_error_count(&self) -> u16 {
2066        self.bus.driver.nominal_error_count()
2067    }
2068
2069    /// Returns the number of errors detected at the data bit rate, in the data
2070    /// phase of bit-rate-switched frames.
2071    pub fn fd_error_count(&self) -> u16 {
2072        self.bus.driver.fd_error_count()
2073    }
2074
2075    /// Returns the transmitter delay the core measured, in function clock
2076    /// periods.
2077    ///
2078    /// The core measures the delay during every FD frame it sends
2079    /// (TRM 38.3.7.2), so the value reads zero until the first one. The
2080    /// secondary sample point sits at this delay plus the configured offset,
2081    /// and the four-bit-time limit of TRM 38.3.7.3 applies to that sum.
2082    pub fn transmitter_delay(&self) -> u8 {
2083        self.bus.driver.transmitter_delay()
2084    }
2085
2086    /// Starts the timestamp counter from zero, at the requested resolution.
2087    ///
2088    /// Received frames are stamped at the sixth bit of their end-of-frame
2089    /// field, which is when a frame becomes valid. The achievable resolution is
2090    /// the function clock divided by an integer, so the returned value is the
2091    /// resolution actually programmed, in Hz.
2092    ///
2093    /// # Errors
2094    ///
2095    /// [`ConfigError::UnsupportedTimestampResolution`] when the resolution
2096    /// cannot be reached from the function clock.
2097    ///
2098    /// [`ConfigError::TimestampTimerStalled`] when the counter does not start.
2099    pub fn start_timestamp_timer(&mut self, resolution_hz: u32) -> Result<u32, ConfigError> {
2100        let clock = self.function_clock_frequency();
2101        if resolution_hz == 0 || resolution_hz > clock {
2102            return Err(ConfigError::UnsupportedTimestampResolution);
2103        }
2104
2105        let divider = clock / resolution_hz;
2106        let divider =
2107            u16::try_from(divider).map_err(|_| ConfigError::UnsupportedTimestampResolution)?;
2108
2109        self.bus.driver.timer_enable(false);
2110        self.bus.driver.timer_enable_config_clock(true);
2111
2112        self.bus.driver.timer_set_divider(divider);
2113        self.bus.driver.timer_count_up(true);
2114        self.bus.driver.timer_set_free_running();
2115        self.bus.driver.timer_enable(true);
2116        self.bus.driver.timer_clear();
2117
2118        // The prescaler keeps its phase across a reprogram and compares
2119        // against the divider instead of reloading, so a divider below the
2120        // phase it holds is missed until the 16-bit prescaler wraps. Measured
2121        // on an ESP32-C5; nothing resets that phase. Wait it out rather than
2122        // hand back a counter that stands still for up to 819 us.
2123        let cycles = u64::from(PRESCALER_PERIOD) + 2 * u64::from(divider);
2124        let deadline = Instant::now()
2125            + Duration::from_micros(cycles * 1_000_000 / u64::from(clock))
2126            + Duration::from_millis(1);
2127        while self.bus.driver.timer_count() == 0 {
2128            if Instant::now() > deadline {
2129                return Err(ConfigError::TimestampTimerStalled);
2130            }
2131        }
2132
2133        Ok(clock / u32::from(divider))
2134    }
2135
2136    /// Stops the timestamp counter.
2137    pub fn stop_timestamp_timer(&mut self) {
2138        self.bus.driver.timer_enable(false);
2139        self.bus.driver.timer_enable_config_clock(false);
2140    }
2141
2142    /// Returns the current value of the timestamp counter.
2143    pub fn timestamp(&self) -> u64 {
2144        self.bus.driver.timer_count()
2145    }
2146
2147    /// Returns the width of the timestamp counter in bits.
2148    pub fn timestamp_bit_width(&self) -> u8 {
2149        self.bus.driver.timer_bit_width()
2150    }
2151}
2152
2153crate::any_peripheral! {
2154    /// Any CAN FD peripheral.
2155    pub peripheral AnyCanFd<'d> {
2156        Twai0(crate::peripherals::TWAI0<'d>),
2157        Twai1(crate::peripherals::TWAI1<'d>),
2158    }
2159}
2160
2161/// Peripheral data describing one CAN FD controller.
2162#[doc(hidden)]
2163#[non_exhaustive]
2164pub struct Info {
2165    pub register_block: *const crate::pac::twai0::RegisterBlock,
2166    pub peripheral: Peripheral,
2167    pub clock_instance: TwaiInstance,
2168    pub interrupt: Interrupt,
2169    pub async_handler: InterruptHandler,
2170    pub rx_signal: InputSignal,
2171    pub tx_signal: OutputSignal,
2172}
2173
2174unsafe impl Sync for Info {}
2175
2176/// A peripheral singleton compatible with the CAN FD driver.
2177pub trait Instance: crate::private::Sealed + any::Degrade {
2178    /// Returns the peripheral data and state describing this controller.
2179    #[doc(hidden)]
2180    fn parts(&self) -> (&'static Info, &'static asynch::State);
2181
2182    /// Returns the peripheral data describing this controller.
2183    #[doc(hidden)]
2184    #[inline(always)]
2185    fn info(&self) -> &'static Info {
2186        self.parts().0
2187    }
2188
2189    /// Returns the peripheral state of this controller.
2190    #[doc(hidden)]
2191    #[inline(always)]
2192    fn state(&self) -> &'static asynch::State {
2193        self.parts().1
2194    }
2195}
2196
2197for_each_canfd! {
2198    ($instance:ident, $sys:ident, $rx:ident, $tx:ident) => {
2199        impl Instance for crate::peripherals::$instance<'_> {
2200            fn parts(&self) -> (&'static Info, &'static asynch::State) {
2201                #[crate::handler]
2202                fn irq_handler() {
2203                    asynch::handle(&INFO, &STATE);
2204                }
2205
2206                static STATE: asynch::State = asynch::State::new();
2207
2208                static INFO: Info = Info {
2209                    register_block: crate::peripherals::$instance::ptr(),
2210                    peripheral: Peripheral::$sys,
2211                    clock_instance: TwaiInstance::$sys,
2212                    interrupt: Interrupt::$instance,
2213                    async_handler: irq_handler,
2214                    rx_signal: InputSignal::$rx,
2215                    tx_signal: OutputSignal::$tx,
2216                };
2217
2218                (&INFO, &STATE)
2219            }
2220        }
2221    };
2222}
2223
2224impl Instance for AnyCanFd<'_> {
2225    #[inline]
2226    fn parts(&self) -> (&'static Info, &'static asynch::State) {
2227        any::delegate!(self, twai => { twai.parts() })
2228    }
2229}
2230
2231/// Index of the range filter in `CanFd::filter_kinds`.
2232const RANGE_FILTER_INDEX: usize = 3;
2233
2234/// The reset value of `CanFd::filter_kinds`: filter A accepts everything, the
2235/// rest are off.
2236const RESET_FILTER_KINDS: [FrameKinds; 4] = [
2237    FrameKinds::ALL,
2238    FrameKinds::NONE,
2239    FrameKinds::NONE,
2240    FrameKinds::NONE,
2241];
2242
2243/// Function clock periods the timestamp prescaler takes to wrap, measured on
2244/// an ESP32-C5.
2245const PRESCALER_PERIOD: u32 = 1 << 16;
2246
2247/// Transmitter delay the core adds on its own, in function clock periods
2248/// (TRM 38.3.7.3).
2249const MIN_TRANSMITTER_DELAY_CYCLES: u32 = 2;
2250
2251/// Bit times allowed for joining the bus: a frame already in flight (under 800
2252/// bit times at most), then the 11 recessive bits of integration.
2253const INTEGRATION_TIMEOUT_BITS: u64 = 2048;
2254
2255/// Shortest wait for bus integration, so the bound at megabit rates is not
2256/// about the speed of the polling loop.
2257const INTEGRATION_TIMEOUT_FLOOR: Duration = Duration::from_millis(50);
2258
2259/// Bit times allowed for a transmission to settle: an abort only takes effect
2260/// once the frame in flight has finished.
2261const ABORT_TIMEOUT_BITS: u64 = 1024;
2262
2263/// How long a transmission may take to finish or abort while leaving the bus.
2264///
2265/// Derived from the slower of the two phases: a bit rate switched frame
2266/// spends its data field at the FD timing, and nothing requires that to be the
2267/// faster one.
2268fn abort_timeout(nominal: &Timing, fd: &Timing, function_clock_hz: u32) -> Duration {
2269    // The added millisecond covers the polling loop at fast bit rates.
2270    bit_times(
2271        slowest_cycles_per_bit(nominal, fd),
2272        ABORT_TIMEOUT_BITS,
2273        function_clock_hz,
2274    ) + Duration::from_millis(1)
2275}
2276
2277/// How long the controller may take to join the bus.
2278fn integration_timeout(nominal: &Timing, fd: &Timing, function_clock_hz: u32) -> Duration {
2279    let derived = bit_times(
2280        slowest_cycles_per_bit(nominal, fd),
2281        INTEGRATION_TIMEOUT_BITS,
2282        function_clock_hz,
2283    );
2284
2285    if derived < INTEGRATION_TIMEOUT_FLOOR {
2286        INTEGRATION_TIMEOUT_FLOOR
2287    } else {
2288        derived
2289    }
2290}
2291
2292/// Function clock periods one bit takes in the slower of the two phases.
2293fn slowest_cycles_per_bit(nominal: &Timing, fd: &Timing) -> u64 {
2294    let cycles_per_bit =
2295        |timing: &Timing| u64::from(timing.baud_rate_prescaler) * u64::from(timing.total_quanta());
2296    cycles_per_bit(nominal).max(cycles_per_bit(fd))
2297}
2298
2299/// How long `bits` bit times last, given the clock periods one bit takes.
2300fn bit_times(cycles_per_bit: u64, bits: u64, function_clock_hz: u32) -> Duration {
2301    // Scaled before dividing: a bit at 2 Mbit/s is half a microsecond.
2302    let micros = cycles_per_bit
2303        .saturating_mul(bits)
2304        .saturating_mul(1_000_000)
2305        / u64::from(function_clock_hz).max(1);
2306
2307    Duration::from_micros(micros)
2308}
2309
2310struct FunctionClockGuard {
2311    instance: TwaiInstance,
2312}
2313
2314impl FunctionClockGuard {
2315    fn new(instance: TwaiInstance, clock_source: ClockSource) -> Self {
2316        ClockTree::with(|clocks| {
2317            // The mux must be configured before the clock is requested.
2318            instance.configure_function_clock(clocks, clock_source);
2319            instance.request_function_clock(clocks);
2320        });
2321        Self { instance }
2322    }
2323
2324    fn set_source(&self, clock_source: ClockSource) {
2325        ClockTree::with(|clocks| {
2326            self.instance.configure_function_clock(clocks, clock_source);
2327        });
2328    }
2329}
2330
2331impl Drop for FunctionClockGuard {
2332    fn drop(&mut self) {
2333        ClockTree::with(|clocks| self.instance.release_function_clock(clocks));
2334    }
2335}