1#, "/api-reference/peripherals/twai.html)")]
13#![doc = crate::before_snippet!()]
42#![doc = crate::before_snippet!()]
63#![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
151pub use crate::soc::clocks::TwaiFunctionClockConfig as ClockSource;
153
154const CTU_CAN_FD_DEVICE_ID: u16 = 0xCAFD;
156
157#[derive(Debug, EnumSetType)]
159#[cfg_attr(feature = "defmt", derive(defmt::Format))]
160pub enum CanFdInterrupt {
161 RxFrame,
163 TxFrame,
165 ErrorWarning,
167 DataOverrun,
169 FaultStateChanged,
171 ArbitrationLost,
173 BusError,
175 Overload,
177 RxFull,
179 BitRateShifted,
181 RxNotEmpty,
183 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
219#[cfg_attr(feature = "defmt", derive(defmt::Format))]
220pub struct Identity {
221 pub device_id: u16,
223 pub version_major: u8,
225 pub version_minor: u8,
227}
228
229impl Identity {
230 pub fn is_ctu_can_fd(&self) -> bool {
232 self.device_id == CTU_CAN_FD_DEVICE_ID
233 }
234}
235
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
238#[cfg_attr(feature = "defmt", derive(defmt::Format))]
239pub enum Mode {
240 #[default]
242 Normal,
243 ListenOnly,
245 SelfTest,
249 LoopbackSelfTest,
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
257#[cfg_attr(feature = "defmt", derive(defmt::Format))]
258#[non_exhaustive]
259pub enum ConfigError {
260 UnsupportedNominalTiming,
262 UnsupportedFdTiming,
264 UnsupportedTimestampResolution,
266 TimestampTimerStalled,
268 UnsupportedRetransmitLimit,
270 UnsupportedSecondarySamplePoint,
275 BusBusy,
278 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
313#[cfg_attr(feature = "defmt", derive(defmt::Format))]
314#[non_exhaustive]
315pub enum Error {
316 NoFreeTxBuffer,
318 RxBufferEmpty,
320 BusIntegrationTimeout,
325 TransmitFailed,
327 TransmitAborted,
329 ControllerRunning,
331 ControllerStopped,
334 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
358#[cfg_attr(feature = "defmt", derive(defmt::Format))]
359#[non_exhaustive]
360pub enum FrameError {
361 PayloadTooLong,
365 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, procmacros::BuilderLite)]
383#[cfg_attr(feature = "defmt", derive(defmt::Format))]
384#[non_exhaustive]
385pub struct Config {
386 mode: Mode,
390
391 clock_source: ClockSource,
399
400 nominal_timing: Timing,
404
405 fd_timing: Timing,
409
410 retransmit_limit: Option<u8>,
417
418 secondary_sample_point_offset: Option<u8>,
422
423 drop_request_frames: bool,
427
428 protocol_exception: bool,
432
433 no_transceiver: bool,
440}
441
442impl Default for Config {
443 fn default() -> Self {
444 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 let cycles = u32::from(offset) * u32::from(self.fd_timing.baud_rate_prescaler);
494
495 if cycles > u32::from(u8::MAX) {
497 return Err(ConfigError::UnsupportedSecondarySamplePoint);
498 }
499
500 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 if cycles <= MIN_TRANSMITTER_DELAY_CYCLES {
513 return Err(ConfigError::UnsupportedSecondarySamplePoint);
514 }
515 }
516
517 Ok(())
518 }
519}
520
521#[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 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 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 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#[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 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 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 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#[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 len: usize,
628 requested_len: usize,
630 timestamp: u64,
631}
632
633impl Frame {
634 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 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 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 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 pub fn payload(&self) -> &[u8] {
705 &self.data[..self.len]
706 }
707
708 pub fn len(&self) -> usize {
710 self.len
711 }
712
713 pub fn is_empty(&self) -> bool {
715 self.len == 0
716 }
717
718 pub fn requested_len(&self) -> usize {
722 self.requested_len
723 }
724
725 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 pub fn id(&self) -> Id {
739 self.id
740 }
741
742 pub fn is_extended(&self) -> bool {
744 matches!(self.id, Id::Extended(_))
745 }
746
747 pub fn is_request(&self) -> bool {
749 self.request
750 }
751
752 pub fn is_fd(&self) -> bool {
754 self.fd
755 }
756
757 pub fn is_bit_rate_switched(&self) -> bool {
759 self.bit_rate_switch
760 }
761
762 pub fn error_state_indicator(&self) -> bool {
764 self.error_state_indicator
765 }
766
767 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#[derive(Clone, Copy, Debug)]
862#[cfg_attr(feature = "defmt", derive(defmt::Format))]
863pub struct ClassicFrame(Frame);
864
865impl ClassicFrame {
866 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 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 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
973pub struct CanFd<'d, Dm: DriverMode = Blocking> {
975 bus: BusGuard,
978 config: Config,
979 _mode: PhantomData<Dm>,
980 filter_kinds: [FrameKinds; 4],
983 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
1013pub struct CanFdRx<'a, Dm: DriverMode> {
1018 driver: Driver,
1019 state: &'static asynch::State,
1020 _driver: PhantomData<&'a mut ()>,
1021 _mode: PhantomData<Dm>,
1022}
1023
1024pub 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 pub fn rx_frame_count(&self) -> u16 {
1072 self.driver.rx_frame_count()
1073 }
1074
1075 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 pub fn flush_rx(&mut self) {
1089 self.driver.flush_rx();
1090 }
1091
1092 pub fn rx_buffer_size_words(&self) -> u16 {
1094 self.driver.rx_buffer_size()
1095 }
1096
1097 pub fn rx_buffer_free_words(&self) -> u16 {
1099 self.driver.rx_free_words()
1100 }
1101
1102 pub fn rx_overrun(&self) -> bool {
1105 self.driver.rx_overrun()
1106 }
1107
1108 pub fn clear_rx_overrun(&mut self) {
1110 self.driver.clear_overrun();
1111 }
1112
1113 pub fn error_state(&self) -> ErrorState {
1115 self.driver.error_state()
1116 }
1117
1118 pub fn receive_error_count(&self) -> u16 {
1120 self.driver.rec()
1121 }
1122
1123 pub fn transmit_error_count(&self) -> u16 {
1125 self.driver.tec()
1126 }
1127}
1128
1129impl CanFdRx<'_, Async> {
1130 pub async fn receive_async(&mut self) -> Frame {
1137 core::future::poll_fn(|cx| {
1138 self.state.rx_waker.register(cx.waker());
1139 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 pub fn tx_buffer_count(&self) -> u8 {
1161 self.tx_buffers
1162 }
1163
1164 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 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 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 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 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 pub fn error_state(&self) -> ErrorState {
1251 self.driver.error_state()
1252 }
1253
1254 pub fn receive_error_count(&self) -> u16 {
1256 self.driver.rec()
1257 }
1258
1259 pub fn transmit_error_count(&self) -> u16 {
1261 self.driver.tec()
1262 }
1263
1264 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 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 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
1329struct BusGuard {
1332 driver: Driver,
1333 tx_buffers: u8,
1334 interrupt: Interrupt,
1335 abort_timeout: Duration,
1338 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 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 self.driver.disable_interrupts(u32::MAX);
1385 self.driver.clear_interrupts(u32::MAX);
1386 crate::interrupt::disable(Cpu::current(), self.interrupt);
1387
1388 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 #[instability::unstable]
1410 pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
1411 self.bind_interrupt_handler(handler);
1412 }
1413
1414 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 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 pub fn interrupts(&self) -> EnumSet<CanFdInterrupt> {
1433 CanFdInterrupt::from_mask(self.bus.driver.interrupt_status())
1434 }
1435
1436 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 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 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 pub async fn receive_async(&mut self) -> Frame {
1515 self.rx_half().receive_async().await
1516 }
1517
1518 pub async fn transmit_async(&mut self, frame: &Frame) -> Result<(), Error> {
1535 self.tx_half().transmit_async(frame).await
1536 }
1537
1538 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 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 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 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 if config.clock_source != self.config.clock_source {
1634 self.stop_timestamp_timer();
1635 }
1636
1637 let previous = self.config;
1640 self.config = *config;
1641 self.configure().inspect_err(|_| self.config = previous)
1642 }
1643
1644 pub fn config(&self) -> &Config {
1646 &self.config
1647 }
1648
1649 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 self.bus.disable();
1659
1660 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 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 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 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 pub fn stop(&mut self) -> Result<(), Error> {
1764 self.bus.quiesce()?;
1765 self.bus.disable();
1766 Ok(())
1767 }
1768
1769 pub fn is_started(&self) -> bool {
1774 self.bus.driver.is_enabled()
1775 }
1776
1777 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 pub fn function_clock_frequency(&self) -> u32 {
1789 self.twai.info().clock_instance.function_clock_frequency()
1790 }
1791
1792 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 pub fn tx_buffer_count(&self) -> u8 {
1831 self.bus.tx_buffers
1832 }
1833
1834 pub fn transmit(&mut self, frame: &Frame) -> Result<u8, Error> {
1846 self.tx_half().transmit(frame)
1847 }
1848
1849 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 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 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 pub fn set_tx_priority(&mut self, index: u8, priority: u8) {
1885 self.tx_half().set_tx_priority(index, priority);
1886 }
1887
1888 pub fn rx_frame_count(&self) -> u16 {
1890 self.bus.driver.rx_frame_count()
1891 }
1892
1893 pub fn receive(&mut self) -> Result<Frame, Error> {
1899 self.rx_half().receive()
1900 }
1901
1902 pub fn flush_rx(&mut self) {
1904 self.bus.driver.flush_rx();
1905 }
1906
1907 pub fn rx_buffer_size_words(&self) -> u16 {
1909 self.bus.driver.rx_buffer_size()
1910 }
1911
1912 pub fn rx_buffer_free_words(&self) -> u16 {
1914 self.bus.driver.rx_free_words()
1915 }
1916
1917 pub fn rx_overrun(&self) -> bool {
1920 self.bus.driver.rx_overrun()
1921 }
1922
1923 pub fn clear_rx_overrun(&mut self) {
1925 self.bus.driver.clear_overrun();
1926 }
1927
1928 pub fn error_state(&self) -> ErrorState {
1935 self.bus.driver.error_state()
1936 }
1937
1938 pub fn error_warning(&self) -> bool {
1942 self.bus.driver.error_warning()
1943 }
1944
1945 pub fn receive_error_count(&self) -> u16 {
1947 self.bus.driver.rec()
1948 }
1949
1950 pub fn transmit_error_count(&self) -> u16 {
1952 self.bus.driver.tec()
1953 }
1954
1955 pub fn request_bus_off_recovery(&mut self) {
1958 self.tx_half().request_bus_off_recovery();
1959 }
1960
1961 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 pub fn reset_traffic_counters(&mut self) {
1981 self.bus.driver.reset_traffic_counters();
1982 }
1983
1984 pub fn rx_traffic_count(&self) -> u32 {
1987 self.bus.driver.rx_traffic_counter()
1988 }
1989
1990 pub fn tx_traffic_count(&self) -> u32 {
1993 self.bus.driver.tx_traffic_counter()
1994 }
1995
1996 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 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 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 pub fn disable_range_filter(&mut self) {
2026 self.filter_kinds[RANGE_FILTER_INDEX] = FrameKinds::NONE;
2027 self.apply_filter_kinds();
2028 }
2029
2030 pub fn accept_all(&mut self) {
2035 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 pub fn error_capture(&self) -> ErrorCapture {
2060 self.bus.driver.error_capture()
2061 }
2062
2063 pub fn retransmit_count(&self) -> u8 {
2066 self.bus.driver.retransmit_count()
2067 }
2068
2069 pub fn nominal_error_count(&self) -> u16 {
2071 self.bus.driver.nominal_error_count()
2072 }
2073
2074 pub fn fd_error_count(&self) -> u16 {
2077 self.bus.driver.fd_error_count()
2078 }
2079
2080 pub fn transmitter_delay(&self) -> u8 {
2088 self.bus.driver.transmitter_delay()
2089 }
2090
2091 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 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 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 pub fn timestamp(&self) -> u64 {
2149 self.bus.driver.timer_count()
2150 }
2151
2152 pub fn timestamp_bit_width(&self) -> u8 {
2154 self.bus.driver.timer_bit_width()
2155 }
2156}
2157
2158crate::any_peripheral! {
2159 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#[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
2182pub trait Instance: crate::private::Sealed + any::Degrade {
2184 #[doc(hidden)]
2186 fn parts(&self) -> (&'static Info, &'static asynch::State);
2187
2188 #[doc(hidden)]
2190 #[inline(always)]
2191 fn info(&self) -> &'static Info {
2192 self.parts().0
2193 }
2194
2195 #[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
2237const RANGE_FILTER_INDEX: usize = 3;
2239
2240const RESET_FILTER_KINDS: [FrameKinds; 4] = [
2243 FrameKinds::ALL,
2244 FrameKinds::NONE,
2245 FrameKinds::NONE,
2246 FrameKinds::NONE,
2247];
2248
2249const PRESCALER_PERIOD: u32 = 1 << 16;
2252
2253const MIN_TRANSMITTER_DELAY_CYCLES: u32 = 2;
2256
2257const INTEGRATION_TIMEOUT_BITS: u64 = 2048;
2260
2261const INTEGRATION_TIMEOUT_FLOOR: Duration = Duration::from_millis(50);
2264
2265const ABORT_TIMEOUT_BITS: u64 = 1024;
2268
2269fn abort_timeout(nominal: &Timing, fd: &Timing, function_clock_hz: u32) -> Duration {
2275 bit_times(
2277 slowest_cycles_per_bit(nominal, fd),
2278 ABORT_TIMEOUT_BITS,
2279 function_clock_hz,
2280 ) + Duration::from_millis(1)
2281}
2282
2283fn 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
2298fn 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
2305fn bit_times(cycles_per_bit: u64, bits: u64, function_clock_hz: u32) -> Duration {
2307 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 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}