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