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,
398
399 nominal_timing: Timing,
403
404 fd_timing: Timing,
408
409 retransmit_limit: Option<u8>,
416
417 secondary_sample_point_offset: Option<u8>,
421
422 drop_request_frames: bool,
426
427 protocol_exception: bool,
431
432 no_transceiver: bool,
439}
440
441impl Default for Config {
442 fn default() -> Self {
443 Self {
446 mode: Mode::Normal,
447 clock_source: ClockSource::PllF80m,
448 nominal_timing: Timing {
449 baud_rate_prescaler: 10,
450 propagation_segment: 7,
451 phase_segment_1: 5,
452 phase_segment_2: 3,
453 sync_jump_width: 3,
454 },
455 fd_timing: Timing {
456 baud_rate_prescaler: 10,
457 propagation_segment: 1,
458 phase_segment_1: 1,
459 phase_segment_2: 1,
460 sync_jump_width: 1,
461 },
462 retransmit_limit: Some(3),
463 secondary_sample_point_offset: None,
464 drop_request_frames: false,
465 protocol_exception: false,
466 no_transceiver: false,
467 }
468 }
469}
470
471impl Config {
472 fn validate(&self) -> Result<(), ConfigError> {
473 if !self.nominal_timing.is_valid(&NOMINAL_TIMING_LIMITS) {
474 return Err(ConfigError::UnsupportedNominalTiming);
475 }
476 if !self.fd_timing.is_valid(&FD_TIMING_LIMITS) {
477 return Err(ConfigError::UnsupportedFdTiming);
478 }
479 if self
480 .retransmit_limit
481 .is_some_and(|limit| limit > MAX_RETRANSMIT_LIMIT)
482 {
483 return Err(ConfigError::UnsupportedRetransmitLimit);
484 }
485
486 if let Some(offset) = self.secondary_sample_point_offset {
487 let cycles = u32::from(offset) * u32::from(self.fd_timing.baud_rate_prescaler);
489
490 if cycles > u32::from(u8::MAX) {
492 return Err(ConfigError::UnsupportedSecondarySamplePoint);
493 }
494
495 let data_bit_cycles =
500 u32::from(self.fd_timing.baud_rate_prescaler) * self.fd_timing.total_quanta();
501 if cycles + MIN_TRANSMITTER_DELAY_CYCLES > data_bit_cycles * 4 {
502 return Err(ConfigError::UnsupportedSecondarySamplePoint);
503 }
504
505 if cycles <= MIN_TRANSMITTER_DELAY_CYCLES {
508 return Err(ConfigError::UnsupportedSecondarySamplePoint);
509 }
510 }
511
512 Ok(())
513 }
514}
515
516#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
526#[cfg_attr(feature = "defmt", derive(defmt::Format))]
527pub struct MaskFilterConfig {
528 id: u32,
529 mask: u32,
530 extended: bool,
531 formats: FrameFormats,
532}
533
534impl MaskFilterConfig {
535 pub fn standard(id: StandardId, mask: StandardId) -> Self {
537 Self {
538 id: id.as_raw() as u32,
539 mask: mask.as_raw() as u32,
540 extended: false,
541 formats: FrameFormats::Both,
542 }
543 }
544
545 pub fn extended(id: ExtendedId, mask: ExtendedId) -> Self {
547 Self {
548 id: id.as_raw(),
549 mask: mask.as_raw(),
550 extended: true,
551 formats: FrameFormats::Both,
552 }
553 }
554
555 pub fn with_formats(self, formats: FrameFormats) -> Self {
557 Self { formats, ..self }
558 }
559
560 fn kinds(&self) -> FrameKinds {
561 FrameKinds::new(self.extended, self.formats)
562 }
563}
564
565#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
573#[cfg_attr(feature = "defmt", derive(defmt::Format))]
574pub struct RangeFilterConfig {
575 low: u32,
576 high: u32,
577 extended: bool,
578 formats: FrameFormats,
579}
580
581impl RangeFilterConfig {
582 pub fn standard(low: StandardId, high: StandardId) -> Self {
584 Self {
585 low: low.as_raw() as u32,
586 high: high.as_raw() as u32,
587 extended: false,
588 formats: FrameFormats::Both,
589 }
590 }
591
592 pub fn extended(low: ExtendedId, high: ExtendedId) -> Self {
594 Self {
595 low: low.as_raw(),
596 high: high.as_raw(),
597 extended: true,
598 formats: FrameFormats::Both,
599 }
600 }
601
602 pub fn with_formats(self, formats: FrameFormats) -> Self {
604 Self { formats, ..self }
605 }
606
607 fn kinds(&self) -> FrameKinds {
608 FrameKinds::new(self.extended, self.formats)
609 }
610}
611
612#[derive(Clone, Copy)]
614pub struct Frame {
615 id: Id,
616 request: bool,
617 fd: bool,
618 bit_rate_switch: bool,
619 error_state_indicator: bool,
620 data: [u8; MAX_DATA_LEN],
621 len: usize,
623 requested_len: usize,
625 timestamp: u64,
626}
627
628impl Frame {
629 pub fn new(id: impl Into<Id>, payload: &[u8]) -> Result<Self, FrameError> {
635 if payload.len() > CLASSIC_MAX_DATA_LEN {
636 return Err(FrameError::PayloadTooLong);
637 }
638 Ok(Self::build(id.into(), false, false, payload))
639 }
640
641 pub fn new_request(id: impl Into<Id>, len: usize) -> Result<Self, FrameError> {
650 if len > CLASSIC_MAX_DATA_LEN {
651 return Err(FrameError::PayloadTooLong);
652 }
653 let mut frame = Self::build(id.into(), true, false, &[]);
654 frame.requested_len = len;
655 Ok(frame)
656 }
657
658 pub fn new_fd(id: impl Into<Id>, payload: &[u8]) -> Result<Self, FrameError> {
667 if payload.len() > MAX_DATA_LEN {
668 return Err(FrameError::PayloadTooLong);
669 }
670 Ok(Self::build(id.into(), false, true, payload))
671 }
672
673 pub fn with_bit_rate_switch(mut self, bit_rate_switch: bool) -> Self {
678 self.bit_rate_switch = bit_rate_switch && self.fd;
679 self
680 }
681
682 fn build(id: Id, request: bool, fd: bool, payload: &[u8]) -> Self {
683 let mut data = [0u8; MAX_DATA_LEN];
684 data[..payload.len()].copy_from_slice(payload);
685 Self {
686 id,
687 request,
688 fd,
689 bit_rate_switch: false,
690 error_state_indicator: false,
691 data,
692 len: payload.len(),
693 requested_len: 0,
694 timestamp: 0,
695 }
696 }
697
698 pub fn payload(&self) -> &[u8] {
700 &self.data[..self.len]
701 }
702
703 pub fn len(&self) -> usize {
705 self.len
706 }
707
708 pub fn is_empty(&self) -> bool {
710 self.len == 0
711 }
712
713 pub fn requested_len(&self) -> usize {
717 self.requested_len
718 }
719
720 pub fn dlc(&self) -> u8 {
725 if self.request {
726 len_to_dlc(self.requested_len as u8)
727 } else {
728 len_to_dlc(self.len as u8)
729 }
730 }
731
732 pub fn id(&self) -> Id {
734 self.id
735 }
736
737 pub fn is_extended(&self) -> bool {
739 matches!(self.id, Id::Extended(_))
740 }
741
742 pub fn is_request(&self) -> bool {
744 self.request
745 }
746
747 pub fn is_fd(&self) -> bool {
749 self.fd
750 }
751
752 pub fn is_bit_rate_switched(&self) -> bool {
754 self.bit_rate_switch
755 }
756
757 pub fn error_state_indicator(&self) -> bool {
759 self.error_state_indicator
760 }
761
762 pub fn timestamp(&self) -> u64 {
767 self.timestamp
768 }
769
770 fn to_buffer(self) -> FrameBuffer {
771 FrameBuffer::build(
772 FrameHeader {
773 id: self.id,
774 request: self.request,
775 fd: self.fd,
776 bit_rate_switch: self.bit_rate_switch,
777 dlc: self.dlc(),
778 },
779 self.payload(),
780 )
781 }
782
783 fn from_buffer(buffer: &FrameBuffer) -> Self {
784 let payload = buffer.data();
785 let mut data = [0u8; MAX_DATA_LEN];
786 data[..payload.len()].copy_from_slice(payload);
787 let request = buffer.is_request();
788 Self {
789 id: buffer.id(),
790 request,
791 fd: buffer.is_fd(),
792 bit_rate_switch: buffer.is_bit_rate_switched(),
793 error_state_indicator: buffer.error_state_indicator(),
794 data,
795 len: payload.len(),
796 requested_len: if request { buffer.requested_len() } else { 0 },
797 timestamp: buffer.timestamp(),
798 }
799 }
800
801 fn raw_id(&self) -> u32 {
802 match self.id {
803 Id::Standard(id) => u32::from(id.as_raw()),
804 Id::Extended(id) => id.as_raw(),
805 }
806 }
807}
808
809impl core::fmt::Debug for Frame {
810 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
811 f.debug_struct("Frame")
812 .field("id", &format_args!("{:#x}", self.raw_id()))
813 .field("extended", &self.is_extended())
814 .field("request", &self.request)
815 .field("fd", &self.fd)
816 .field("bit_rate_switch", &self.bit_rate_switch)
817 .field("error_state_indicator", &self.error_state_indicator)
818 .field("dlc", &self.dlc())
819 .field("len", &self.len)
820 .field("timestamp", &self.timestamp)
821 .field("data", &self.payload())
822 .finish()
823 }
824}
825
826#[cfg(feature = "defmt")]
827impl defmt::Format for Frame {
828 fn format(&self, f: defmt::Formatter<'_>) {
829 defmt::write!(
830 f,
831 "Frame {{ id: {=u32:#x}, extended: {}, request: {}, fd: {}, brs: {}, esi: {}, dlc: {=u8}, len: {=usize}, timestamp: {=u64}, data: {=[u8]:#x} }}",
832 self.raw_id(),
833 self.is_extended(),
834 self.request,
835 self.fd,
836 self.bit_rate_switch,
837 self.error_state_indicator,
838 self.dlc(),
839 self.len,
840 self.timestamp,
841 self.payload()
842 )
843 }
844}
845
846#[derive(Clone, Copy, Debug)]
857#[cfg_attr(feature = "defmt", derive(defmt::Format))]
858pub struct ClassicFrame(Frame);
859
860impl ClassicFrame {
861 pub fn into_frame(self) -> Frame {
863 self.0
864 }
865}
866
867impl core::ops::Deref for ClassicFrame {
868 type Target = Frame;
869
870 fn deref(&self) -> &Frame {
871 &self.0
872 }
873}
874
875impl TryFrom<Frame> for ClassicFrame {
876 type Error = FrameError;
877
878 fn try_from(frame: Frame) -> Result<Self, FrameError> {
882 if frame.fd {
883 return Err(FrameError::NotClassic);
884 }
885 Ok(Self(frame))
886 }
887}
888
889impl From<ClassicFrame> for Frame {
890 fn from(frame: ClassicFrame) -> Self {
891 frame.0
892 }
893}
894
895#[instability::unstable]
896impl embedded_can::Frame for ClassicFrame {
897 fn new(id: impl Into<Id>, data: &[u8]) -> Option<Self> {
898 Frame::new(id, data).ok().map(Self)
899 }
900
901 fn new_remote(id: impl Into<Id>, dlc: usize) -> Option<Self> {
902 Frame::new_request(id, dlc).ok().map(Self)
903 }
904
905 fn is_extended(&self) -> bool {
906 self.0.is_extended()
907 }
908
909 fn is_remote_frame(&self) -> bool {
910 self.0.request
911 }
912
913 fn id(&self) -> Id {
914 self.0.id
915 }
916
917 fn dlc(&self) -> usize {
918 if self.0.request {
921 self.0.requested_len
922 } else {
923 self.0.len
924 }
925 }
926
927 fn data(&self) -> &[u8] {
928 self.0.payload()
929 }
930}
931
932#[instability::unstable]
933impl From<BusErrorKind> for embedded_can::ErrorKind {
934 fn from(kind: BusErrorKind) -> Self {
935 match kind {
936 BusErrorKind::Bit => Self::Bit,
937 BusErrorKind::Crc => Self::Crc,
938 BusErrorKind::Form => Self::Form,
939 BusErrorKind::Ack => Self::Acknowledge,
940 BusErrorKind::Stuff => Self::Stuff,
941 BusErrorKind::Unknown(_) => Self::Other,
942 }
943 }
944}
945
946#[instability::unstable]
947impl embedded_can::Error for BusErrorKind {
948 fn kind(&self) -> embedded_can::ErrorKind {
949 (*self).into()
950 }
951}
952
953impl core::error::Error for BusErrorKind {}
954
955impl core::fmt::Display for BusErrorKind {
956 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
957 match self {
958 Self::Bit => f.write_str("The transmitted bit did not match the bit sampled back"),
959 Self::Crc => f.write_str("The CRC of the frame did not match"),
960 Self::Form => f.write_str("A fixed-form field held an illegal value"),
961 Self::Ack => f.write_str("No node acknowledged the frame"),
962 Self::Stuff => f.write_str("A stuffing rule was violated"),
963 Self::Unknown(code) => write!(f, "Unknown bus error code {code}"),
964 }
965 }
966}
967
968pub struct CanFd<'d, Dm: DriverMode = Blocking> {
970 bus: BusGuard,
973 config: Config,
974 _mode: PhantomData<Dm>,
975 filter_kinds: [FrameKinds; 4],
978 pins_bound: bool,
980 twai: AnyCanFd<'d>,
981 _function_clock: FunctionClockGuard,
982 _peripheral: PeripheralGuard,
983}
984
985impl<Dm: DriverMode> core::fmt::Debug for CanFd<'_, Dm> {
986 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
987 f.debug_struct("CanFd")
988 .field("twai", &self.twai)
989 .field("config", &self.config)
990 .field("started", &self.is_started())
991 .finish_non_exhaustive()
992 }
993}
994
995#[cfg(feature = "defmt")]
996impl<Dm: DriverMode> defmt::Format for CanFd<'_, Dm> {
997 fn format(&self, f: defmt::Formatter<'_>) {
998 defmt::write!(
999 f,
1000 "CanFd {{ twai: {:?}, config: {:?}, started: {} }}",
1001 self.twai,
1002 self.config,
1003 self.is_started()
1004 )
1005 }
1006}
1007
1008pub struct CanFdRx<'a, Dm: DriverMode> {
1013 driver: Driver,
1014 state: &'static asynch::State,
1015 _driver: PhantomData<&'a mut ()>,
1016 _mode: PhantomData<Dm>,
1017}
1018
1019pub struct CanFdTx<'a, Dm: DriverMode> {
1023 driver: Driver,
1024 state: &'static asynch::State,
1025 tx_buffers: u8,
1026 _driver: PhantomData<&'a mut ()>,
1027 _mode: PhantomData<Dm>,
1028}
1029
1030impl<Dm: DriverMode> core::fmt::Debug for CanFdRx<'_, Dm> {
1031 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1032 f.debug_struct("CanFdRx")
1033 .field("rx_frame_count", &self.rx_frame_count())
1034 .finish_non_exhaustive()
1035 }
1036}
1037
1038impl<Dm: DriverMode> core::fmt::Debug for CanFdTx<'_, Dm> {
1039 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1040 f.debug_struct("CanFdTx")
1041 .field("tx_buffers", &self.tx_buffers)
1042 .finish_non_exhaustive()
1043 }
1044}
1045
1046#[cfg(feature = "defmt")]
1047impl<Dm: DriverMode> defmt::Format for CanFdRx<'_, Dm> {
1048 fn format(&self, f: defmt::Formatter<'_>) {
1049 defmt::write!(
1050 f,
1051 "CanFdRx {{ rx_frame_count: {=u16} }}",
1052 self.rx_frame_count()
1053 )
1054 }
1055}
1056
1057#[cfg(feature = "defmt")]
1058impl<Dm: DriverMode> defmt::Format for CanFdTx<'_, Dm> {
1059 fn format(&self, f: defmt::Formatter<'_>) {
1060 defmt::write!(f, "CanFdTx {{ tx_buffers: {=u8} }}", self.tx_buffers)
1061 }
1062}
1063
1064impl<Dm: DriverMode> CanFdRx<'_, Dm> {
1065 pub fn rx_frame_count(&self) -> u16 {
1067 self.driver.rx_frame_count()
1068 }
1069
1070 pub fn receive(&mut self) -> Result<Frame, Error> {
1076 if self.driver.rx_frame_count() == 0 {
1077 return Err(Error::RxBufferEmpty);
1078 }
1079 Ok(Frame::from_buffer(&self.driver.read_rx_frame()))
1080 }
1081
1082 pub fn flush_rx(&mut self) {
1084 self.driver.flush_rx();
1085 }
1086
1087 pub fn rx_buffer_size_words(&self) -> u16 {
1089 self.driver.rx_buffer_size()
1090 }
1091
1092 pub fn rx_buffer_free_words(&self) -> u16 {
1094 self.driver.rx_free_words()
1095 }
1096
1097 pub fn rx_overrun(&self) -> bool {
1100 self.driver.rx_overrun()
1101 }
1102
1103 pub fn clear_rx_overrun(&mut self) {
1105 self.driver.clear_overrun();
1106 }
1107
1108 pub fn error_state(&self) -> ErrorState {
1110 self.driver.error_state()
1111 }
1112
1113 pub fn receive_error_count(&self) -> u16 {
1115 self.driver.rec()
1116 }
1117
1118 pub fn transmit_error_count(&self) -> u16 {
1120 self.driver.tec()
1121 }
1122}
1123
1124impl CanFdRx<'_, Async> {
1125 pub async fn receive_async(&mut self) -> Frame {
1132 core::future::poll_fn(|cx| {
1133 self.state.rx_waker.register(cx.waker());
1134 self.driver
1137 .enable_interrupts(CanFdInterrupt::RxNotEmpty.bit());
1138
1139 if self.driver.rx_frame_count() > 0 {
1140 self.driver
1141 .disable_interrupts(CanFdInterrupt::RxNotEmpty.bit());
1142 return core::task::Poll::Ready(());
1143 }
1144
1145 core::task::Poll::Pending
1146 })
1147 .await;
1148
1149 Frame::from_buffer(&self.driver.read_rx_frame())
1150 }
1151}
1152
1153impl<Dm: DriverMode> CanFdTx<'_, Dm> {
1154 pub fn tx_buffer_count(&self) -> u8 {
1156 self.tx_buffers
1157 }
1158
1159 pub fn transmit(&mut self, frame: &Frame) -> Result<u8, Error> {
1181 if !self.driver.is_enabled() {
1182 return Err(Error::ControllerStopped);
1183 }
1184
1185 let index = (0..self.tx_buffers)
1186 .find(|&i| self.driver.tx_buffer_state(i).is_writable())
1187 .ok_or(Error::NoFreeTxBuffer)?;
1188
1189 self.driver.write_tx_buffer(index, &frame.to_buffer());
1190 self.driver.set_tx_ready(index);
1191 Ok(index)
1192 }
1193
1194 pub fn tx_buffer_state(&self, index: u8) -> TxBufferState {
1199 if index >= self.tx_buffers {
1200 return TxBufferState::NotExist;
1201 }
1202 self.driver.tx_buffer_state(index)
1203 }
1204
1205 pub fn abort_transmit(&mut self, index: u8) {
1209 if index < self.tx_buffers {
1210 self.driver.set_tx_abort(index);
1211 }
1212 }
1213
1214 pub fn release_tx_buffer(&mut self, index: u8) {
1218 if index < self.tx_buffers {
1219 self.driver.set_tx_empty(index);
1220 }
1221 }
1222
1223 pub fn set_tx_priority(&mut self, index: u8, priority: u8) {
1234 if index < self.tx_buffers {
1235 self.driver
1236 .set_tx_priority(index, priority.min(MAX_TX_PRIORITY));
1237 }
1238 }
1239
1240 pub fn error_state(&self) -> ErrorState {
1246 self.driver.error_state()
1247 }
1248
1249 pub fn receive_error_count(&self) -> u16 {
1251 self.driver.rec()
1252 }
1253
1254 pub fn transmit_error_count(&self) -> u16 {
1256 self.driver.tec()
1257 }
1258
1259 pub fn request_bus_off_recovery(&mut self) {
1270 if self.driver.error_state() == ErrorState::BusOff {
1271 self.driver.request_bus_off_recovery();
1272 }
1273 }
1274}
1275
1276impl CanFdTx<'_, Async> {
1277 pub async fn transmit_async(&mut self, frame: &Frame) -> Result<(), Error> {
1294 let index = self.transmit(frame)?;
1295
1296 core::future::poll_fn(|cx| {
1297 self.state.tx_waker.register(cx.waker());
1298 self.driver.enable_interrupts(CanFdInterrupt::TxDone.bit());
1301
1302 let state = self.driver.tx_buffer_state(index);
1303 if !matches!(
1304 state,
1305 TxBufferState::Ready | TxBufferState::InProgress | TxBufferState::AbortInProgress
1306 ) {
1307 self.driver.disable_interrupts(CanFdInterrupt::TxDone.bit());
1308 }
1309
1310 match state {
1311 TxBufferState::Ready
1312 | TxBufferState::InProgress
1313 | TxBufferState::AbortInProgress => core::task::Poll::Pending,
1314 TxBufferState::Ok => core::task::Poll::Ready(Ok(())),
1315 TxBufferState::Failed => core::task::Poll::Ready(Err(Error::TransmitFailed)),
1316 TxBufferState::Aborted => core::task::Poll::Ready(Err(Error::TransmitAborted)),
1317 _ => core::task::Poll::Ready(Err(Error::NoFreeTxBuffer)),
1318 }
1319 })
1320 .await
1321 }
1322}
1323
1324struct BusGuard {
1327 driver: Driver,
1328 tx_buffers: u8,
1329 interrupt: Interrupt,
1330 abort_timeout: Duration,
1333 wake_lock: Option<WakeLock>,
1337}
1338
1339impl BusGuard {
1340 fn enable(&mut self) {
1341 self.driver.enable(true);
1342 if self.wake_lock.is_none() {
1343 self.wake_lock = Some(WakeLock::new());
1344 }
1345 }
1346
1347 fn disable(&mut self) {
1348 self.driver.enable(false);
1349 self.wake_lock = None;
1350 }
1351
1352 fn quiesce(&self) -> Result<(), Error> {
1355 for index in 0..self.tx_buffers {
1356 self.driver.set_tx_abort(index);
1357 }
1358
1359 let deadline = Instant::now() + self.abort_timeout;
1360 for index in 0..self.tx_buffers {
1361 while matches!(
1362 self.driver.tx_buffer_state(index),
1363 TxBufferState::Ready | TxBufferState::InProgress | TxBufferState::AbortInProgress
1364 ) {
1365 if Instant::now() > deadline {
1366 return Err(Error::AbortTimeout);
1367 }
1368 }
1369 }
1370
1371 Ok(())
1372 }
1373}
1374
1375impl Drop for BusGuard {
1376 fn drop(&mut self) {
1377 self.driver.disable_interrupts(u32::MAX);
1380 self.driver.clear_interrupts(u32::MAX);
1381 crate::interrupt::disable(Cpu::current(), self.interrupt);
1382
1383 let _ = self.quiesce();
1385 self.disable();
1386 }
1387}
1388
1389impl crate::private::Sealed for CanFd<'_, Blocking> {}
1390
1391#[instability::unstable]
1392impl crate::interrupt::InterruptConfigurable for CanFd<'_, Blocking> {
1393 fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
1394 self.bind_interrupt_handler(handler);
1395 }
1396}
1397
1398impl<'d> CanFd<'d, Blocking> {
1399 #[instability::unstable]
1405 pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
1406 self.bind_interrupt_handler(handler);
1407 }
1408
1409 pub fn listen(&mut self, interrupts: impl Into<EnumSet<CanFdInterrupt>>) {
1414 self.bus
1415 .driver
1416 .enable_interrupts(CanFdInterrupt::mask(interrupts.into()));
1417 }
1418
1419 pub fn unlisten(&mut self, interrupts: impl Into<EnumSet<CanFdInterrupt>>) {
1421 self.bus
1422 .driver
1423 .disable_interrupts(CanFdInterrupt::mask(interrupts.into()));
1424 }
1425
1426 pub fn interrupts(&self) -> EnumSet<CanFdInterrupt> {
1428 CanFdInterrupt::from_mask(self.bus.driver.interrupt_status())
1429 }
1430
1431 pub fn clear_interrupts(&mut self, interrupts: impl Into<EnumSet<CanFdInterrupt>>) {
1433 self.bus
1434 .driver
1435 .clear_interrupts(CanFdInterrupt::mask(interrupts.into()));
1436 }
1437
1438 pub fn new(twai: impl Instance + 'd, config: Config) -> Result<Self, ConfigError> {
1447 let twai = twai.degrade();
1448 let info = twai.info();
1449 let peripheral = PeripheralGuard::new(info.peripheral);
1450 let function_clock = FunctionClockGuard::new(info.clock_instance, config.clock_source);
1451
1452 let driver = Driver::new(info.register_block);
1453 driver.reset();
1454 let tx_buffers = driver.tx_buffer_count();
1455
1456 let abort_timeout = abort_timeout(
1457 &config.nominal_timing,
1458 &config.fd_timing,
1459 info.clock_instance.function_clock_frequency(),
1460 );
1461
1462 let mut this = Self {
1463 bus: BusGuard {
1464 driver,
1465 tx_buffers,
1466 abort_timeout,
1467 interrupt: info.interrupt,
1468 wake_lock: None,
1469 },
1470 config,
1471 filter_kinds: RESET_FILTER_KINDS,
1472 pins_bound: false,
1473 _mode: PhantomData,
1474 twai,
1475 _function_clock: function_clock,
1476 _peripheral: peripheral,
1477 };
1478 this.configure()?;
1479
1480 Ok(this)
1481 }
1482
1483 pub fn into_async(self) -> CanFd<'d, Async> {
1485 let mut this = CanFd {
1486 bus: self.bus,
1487 config: self.config,
1488 filter_kinds: self.filter_kinds,
1489 pins_bound: self.pins_bound,
1490 _mode: PhantomData,
1491 twai: self.twai,
1492 _function_clock: self._function_clock,
1493 _peripheral: self._peripheral,
1494 };
1495 let handler = this.twai.info().async_handler;
1496 this.bind_interrupt_handler(handler);
1497
1498 this
1499 }
1500}
1501
1502impl<'d> CanFd<'d, Async> {
1503 pub async fn receive_async(&mut self) -> Frame {
1510 self.rx_half().receive_async().await
1511 }
1512
1513 pub async fn transmit_async(&mut self, frame: &Frame) -> Result<(), Error> {
1530 self.tx_half().transmit_async(frame).await
1531 }
1532
1533 pub fn into_blocking(self) -> CanFd<'d, Blocking> {
1535 self.bus.driver.disable_interrupts(u32::MAX);
1536 crate::interrupt::disable(Cpu::current(), self.twai.info().interrupt);
1537
1538 CanFd {
1539 bus: self.bus,
1540 config: self.config,
1541 filter_kinds: self.filter_kinds,
1542 pins_bound: self.pins_bound,
1543 _mode: PhantomData,
1544 twai: self.twai,
1545 _function_clock: self._function_clock,
1546 _peripheral: self._peripheral,
1547 }
1548 }
1549}
1550
1551impl<'d, Dm: DriverMode> CanFd<'d, Dm> {
1552 fn bind_interrupt_handler(&mut self, handler: InterruptHandler) {
1553 let interrupt = self.twai.info().interrupt;
1554 crate::interrupt::disable(Cpu::current(), interrupt);
1555 self.bus.driver.disable_interrupts(u32::MAX);
1556 self.bus.driver.clear_interrupts(u32::MAX);
1557 crate::interrupt::bind_handler(interrupt, handler);
1558 crate::interrupt::enable(interrupt, handler.priority());
1559 }
1560
1561 pub fn with_rx(mut self, rx: impl PeripheralInput<'d>) -> Self {
1566 let rx = rx.into();
1567 rx.apply_input_config(&InputConfig::default().with_pull(self.pin_pull()));
1568 rx.set_input_enable(true);
1569 self.twai.info().rx_signal.connect_to(&rx);
1570 self.pins_bound = true;
1571
1572 self
1573 }
1574
1575 pub fn with_tx(mut self, tx: impl PeripheralOutput<'d>) -> Self {
1582 let tx = tx.into();
1583 let mut output = OutputConfig::default();
1584 if self.config.no_transceiver {
1585 output = output
1586 .with_drive_mode(DriveMode::OpenDrain)
1587 .with_pull(Pull::Up);
1588 }
1589 tx.apply_output_config(&output);
1590 tx.set_output_enable(true);
1591 self.twai.info().tx_signal.connect_to(&tx);
1592 self.pins_bound = true;
1593
1594 self
1595 }
1596
1597 fn pin_pull(&self) -> Pull {
1598 if self.config.no_transceiver {
1599 Pull::Up
1600 } else {
1601 Pull::None
1602 }
1603 }
1604
1605 pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
1620 config.validate()?;
1621
1622 if self.pins_bound && config.no_transceiver != self.config.no_transceiver {
1623 return Err(ConfigError::TransceiverModeLocked);
1624 }
1625
1626 if config.clock_source != self.config.clock_source {
1629 self.stop_timestamp_timer();
1630 }
1631
1632 let previous = self.config;
1635 self.config = *config;
1636 self.configure().inspect_err(|_| self.config = previous)
1637 }
1638
1639 pub fn config(&self) -> &Config {
1641 &self.config
1642 }
1643
1644 fn configure(&mut self) -> Result<(), ConfigError> {
1646 self.config.validate()?;
1647
1648 if self.bus.driver.is_enabled() {
1649 self.bus.quiesce().map_err(|_| ConfigError::BusBusy)?;
1650 }
1651
1652 self.bus.disable();
1654
1655 self._function_clock.set_source(self.config.clock_source);
1658
1659 let config = self.config;
1660 let (listen_only, self_test, loopback) = match config.mode {
1661 Mode::Normal => (false, false, false),
1662 Mode::ListenOnly => (true, false, false),
1663 Mode::SelfTest => (false, true, false),
1664 Mode::LoopbackSelfTest => (false, true, true),
1665 };
1666
1667 self.bus.driver.apply_mode_settings(&ll::ModeSettings {
1668 listen_only,
1669 self_test,
1670 loopback,
1671 fd_enabled: true,
1672 protocol_exception: config.protocol_exception,
1673 rx_auto_increment: true,
1674 filters_enabled: true,
1675 bus_off_tx_fail: true,
1676 drop_request_frames: config.drop_request_frames,
1677 time_triggered_tx: false,
1678 retransmit_limit: config.retransmit_limit,
1679 });
1680
1681 self.bus
1682 .driver
1683 .set_timestamp_point(TimestampPoint::EndOfFrame);
1684
1685 self.bus.driver.set_nominal_timing(&config.nominal_timing);
1686 self.bus.driver.set_fd_timing(&config.fd_timing);
1687
1688 self.bus.abort_timeout = abort_timeout(
1689 &config.nominal_timing,
1690 &config.fd_timing,
1691 self.function_clock_frequency(),
1692 );
1693
1694 match config.secondary_sample_point_offset {
1695 Some(offset) => self.bus.driver.set_secondary_sample_point(
1697 SspSource::MeasuredPlusOffset,
1698 offset.saturating_mul(config.fd_timing.baud_rate_prescaler),
1699 ),
1700 None => self
1701 .bus
1702 .driver
1703 .set_secondary_sample_point(SspSource::Disabled, 0),
1704 }
1705
1706 Ok(())
1707 }
1708
1709 pub fn start(&mut self) -> Result<(), Error> {
1719 let timeout = integration_timeout(
1720 &self.config.nominal_timing,
1721 &self.config.fd_timing,
1722 self.function_clock_frequency(),
1723 );
1724
1725 let was_enabled = self.bus.driver.is_enabled();
1726 self.bus.enable();
1727
1728 let deadline = Instant::now() + timeout;
1731 loop {
1732 if self.bus.driver.error_state() == ErrorState::Active {
1733 return Ok(());
1734 }
1735 if Instant::now() > deadline {
1736 if !was_enabled {
1737 self.bus.disable();
1738 }
1739 return Err(Error::BusIntegrationTimeout);
1740 }
1741 }
1742 }
1743
1744 pub fn stop(&mut self) -> Result<(), Error> {
1759 self.bus.quiesce()?;
1760 self.bus.disable();
1761 Ok(())
1762 }
1763
1764 pub fn is_started(&self) -> bool {
1769 self.bus.driver.is_enabled()
1770 }
1771
1772 pub fn identity(&self) -> Identity {
1774 let (major, minor) = self.bus.driver.version();
1775 Identity {
1776 device_id: self.bus.driver.device_id(),
1777 version_major: major,
1778 version_minor: minor,
1779 }
1780 }
1781
1782 pub fn function_clock_frequency(&self) -> u32 {
1784 self.twai.info().clock_instance.function_clock_frequency()
1785 }
1786
1787 pub fn split(&mut self) -> (CanFdRx<'_, Dm>, CanFdTx<'_, Dm>) {
1798 let (info, state) = self.twai.parts();
1799 (
1800 CanFdRx {
1801 driver: Driver::new(info.register_block),
1802 state,
1803 _driver: PhantomData,
1804 _mode: PhantomData,
1805 },
1806 CanFdTx {
1807 driver: Driver::new(info.register_block),
1808 state,
1809 tx_buffers: self.bus.tx_buffers,
1810 _driver: PhantomData,
1811 _mode: PhantomData,
1812 },
1813 )
1814 }
1815
1816 fn rx_half(&mut self) -> CanFdRx<'_, Dm> {
1817 self.split().0
1818 }
1819
1820 fn tx_half(&mut self) -> CanFdTx<'_, Dm> {
1821 self.split().1
1822 }
1823
1824 pub fn tx_buffer_count(&self) -> u8 {
1826 self.bus.tx_buffers
1827 }
1828
1829 pub fn transmit(&mut self, frame: &Frame) -> Result<u8, Error> {
1841 self.tx_half().transmit(frame)
1842 }
1843
1844 pub fn tx_buffer_state(&self, index: u8) -> TxBufferState {
1849 if index >= self.bus.tx_buffers {
1850 return TxBufferState::NotExist;
1851 }
1852 self.bus.driver.tx_buffer_state(index)
1853 }
1854
1855 pub fn abort_transmit(&mut self, index: u8) {
1861 if index < self.bus.tx_buffers {
1862 self.bus.driver.set_tx_abort(index);
1863 }
1864 }
1865
1866 pub fn release_tx_buffer(&mut self, index: u8) {
1870 if index < self.bus.tx_buffers {
1871 self.bus.driver.set_tx_empty(index);
1872 }
1873 }
1874
1875 pub fn set_tx_priority(&mut self, index: u8, priority: u8) {
1880 self.tx_half().set_tx_priority(index, priority);
1881 }
1882
1883 pub fn rx_frame_count(&self) -> u16 {
1885 self.bus.driver.rx_frame_count()
1886 }
1887
1888 pub fn receive(&mut self) -> Result<Frame, Error> {
1894 self.rx_half().receive()
1895 }
1896
1897 pub fn flush_rx(&mut self) {
1899 self.bus.driver.flush_rx();
1900 }
1901
1902 pub fn rx_buffer_size_words(&self) -> u16 {
1904 self.bus.driver.rx_buffer_size()
1905 }
1906
1907 pub fn rx_buffer_free_words(&self) -> u16 {
1909 self.bus.driver.rx_free_words()
1910 }
1911
1912 pub fn rx_overrun(&self) -> bool {
1915 self.bus.driver.rx_overrun()
1916 }
1917
1918 pub fn clear_rx_overrun(&mut self) {
1920 self.bus.driver.clear_overrun();
1921 }
1922
1923 pub fn error_state(&self) -> ErrorState {
1930 self.bus.driver.error_state()
1931 }
1932
1933 pub fn error_warning(&self) -> bool {
1937 self.bus.driver.error_warning()
1938 }
1939
1940 pub fn receive_error_count(&self) -> u16 {
1942 self.bus.driver.rec()
1943 }
1944
1945 pub fn transmit_error_count(&self) -> u16 {
1947 self.bus.driver.tec()
1948 }
1949
1950 pub fn request_bus_off_recovery(&mut self) {
1953 self.tx_half().request_bus_off_recovery();
1954 }
1955
1956 pub fn set_error_warning_limit(&mut self, limit: u8) -> Result<(), Error> {
1965 if self.bus.driver.is_enabled() {
1966 return Err(Error::ControllerRunning);
1967 }
1968 self.bus.driver.enable_test_mode(true);
1969 self.bus.driver.set_error_warning_limit(limit);
1970 self.bus.driver.enable_test_mode(false);
1971 Ok(())
1972 }
1973
1974 pub fn reset_traffic_counters(&mut self) {
1976 self.bus.driver.reset_traffic_counters();
1977 }
1978
1979 pub fn rx_traffic_count(&self) -> u32 {
1982 self.bus.driver.rx_traffic_counter()
1983 }
1984
1985 pub fn tx_traffic_count(&self) -> u32 {
1988 self.bus.driver.tx_traffic_counter()
1989 }
1990
1991 pub fn set_mask_filter(&mut self, filter: MaskFilter, config: &MaskFilterConfig) {
1997 self.bus
1998 .driver
1999 .set_mask_filter(filter, config.extended, config.id, config.mask);
2000 self.filter_kinds[Self::mask_filter_index(filter)] = config.kinds();
2001 self.apply_filter_kinds();
2002 }
2003
2004 pub fn disable_mask_filter(&mut self, filter: MaskFilter) {
2006 self.filter_kinds[Self::mask_filter_index(filter)] = FrameKinds::NONE;
2007 self.apply_filter_kinds();
2008 }
2009
2010 pub fn set_range_filter(&mut self, config: &RangeFilterConfig) {
2012 self.bus
2013 .driver
2014 .set_range_filter(config.extended, config.low, config.high);
2015 self.filter_kinds[RANGE_FILTER_INDEX] = config.kinds();
2016 self.apply_filter_kinds();
2017 }
2018
2019 pub fn disable_range_filter(&mut self) {
2021 self.filter_kinds[RANGE_FILTER_INDEX] = FrameKinds::NONE;
2022 self.apply_filter_kinds();
2023 }
2024
2025 pub fn accept_all(&mut self) {
2030 self.bus.driver.set_mask_filter(MaskFilter::A, false, 0, 0);
2033 self.filter_kinds = RESET_FILTER_KINDS;
2034 self.apply_filter_kinds();
2035 }
2036
2037 fn mask_filter_index(filter: MaskFilter) -> usize {
2038 match filter {
2039 MaskFilter::A => 0,
2040 MaskFilter::B => 1,
2041 MaskFilter::C => 2,
2042 }
2043 }
2044
2045 fn apply_filter_kinds(&mut self) {
2046 let [a, b, c, range] = self.filter_kinds;
2047 self.bus.driver.set_filter_kinds(a, b, c, range);
2048 }
2049
2050 pub fn error_capture(&self) -> ErrorCapture {
2055 self.bus.driver.error_capture()
2056 }
2057
2058 pub fn retransmit_count(&self) -> u8 {
2061 self.bus.driver.retransmit_count()
2062 }
2063
2064 pub fn nominal_error_count(&self) -> u16 {
2066 self.bus.driver.nominal_error_count()
2067 }
2068
2069 pub fn fd_error_count(&self) -> u16 {
2072 self.bus.driver.fd_error_count()
2073 }
2074
2075 pub fn transmitter_delay(&self) -> u8 {
2083 self.bus.driver.transmitter_delay()
2084 }
2085
2086 pub fn start_timestamp_timer(&mut self, resolution_hz: u32) -> Result<u32, ConfigError> {
2100 let clock = self.function_clock_frequency();
2101 if resolution_hz == 0 || resolution_hz > clock {
2102 return Err(ConfigError::UnsupportedTimestampResolution);
2103 }
2104
2105 let divider = clock / resolution_hz;
2106 let divider =
2107 u16::try_from(divider).map_err(|_| ConfigError::UnsupportedTimestampResolution)?;
2108
2109 self.bus.driver.timer_enable(false);
2110 self.bus.driver.timer_enable_config_clock(true);
2111
2112 self.bus.driver.timer_set_divider(divider);
2113 self.bus.driver.timer_count_up(true);
2114 self.bus.driver.timer_set_free_running();
2115 self.bus.driver.timer_enable(true);
2116 self.bus.driver.timer_clear();
2117
2118 let cycles = u64::from(PRESCALER_PERIOD) + 2 * u64::from(divider);
2124 let deadline = Instant::now()
2125 + Duration::from_micros(cycles * 1_000_000 / u64::from(clock))
2126 + Duration::from_millis(1);
2127 while self.bus.driver.timer_count() == 0 {
2128 if Instant::now() > deadline {
2129 return Err(ConfigError::TimestampTimerStalled);
2130 }
2131 }
2132
2133 Ok(clock / u32::from(divider))
2134 }
2135
2136 pub fn stop_timestamp_timer(&mut self) {
2138 self.bus.driver.timer_enable(false);
2139 self.bus.driver.timer_enable_config_clock(false);
2140 }
2141
2142 pub fn timestamp(&self) -> u64 {
2144 self.bus.driver.timer_count()
2145 }
2146
2147 pub fn timestamp_bit_width(&self) -> u8 {
2149 self.bus.driver.timer_bit_width()
2150 }
2151}
2152
2153crate::any_peripheral! {
2154 pub peripheral AnyCanFd<'d> {
2156 Twai0(crate::peripherals::TWAI0<'d>),
2157 Twai1(crate::peripherals::TWAI1<'d>),
2158 }
2159}
2160
2161#[doc(hidden)]
2163#[non_exhaustive]
2164pub struct Info {
2165 pub register_block: *const crate::pac::twai0::RegisterBlock,
2166 pub peripheral: Peripheral,
2167 pub clock_instance: TwaiInstance,
2168 pub interrupt: Interrupt,
2169 pub async_handler: InterruptHandler,
2170 pub rx_signal: InputSignal,
2171 pub tx_signal: OutputSignal,
2172}
2173
2174unsafe impl Sync for Info {}
2175
2176pub trait Instance: crate::private::Sealed + any::Degrade {
2178 #[doc(hidden)]
2180 fn parts(&self) -> (&'static Info, &'static asynch::State);
2181
2182 #[doc(hidden)]
2184 #[inline(always)]
2185 fn info(&self) -> &'static Info {
2186 self.parts().0
2187 }
2188
2189 #[doc(hidden)]
2191 #[inline(always)]
2192 fn state(&self) -> &'static asynch::State {
2193 self.parts().1
2194 }
2195}
2196
2197for_each_canfd! {
2198 ($instance:ident, $sys:ident, $rx:ident, $tx:ident) => {
2199 impl Instance for crate::peripherals::$instance<'_> {
2200 fn parts(&self) -> (&'static Info, &'static asynch::State) {
2201 #[crate::handler]
2202 fn irq_handler() {
2203 asynch::handle(&INFO, &STATE);
2204 }
2205
2206 static STATE: asynch::State = asynch::State::new();
2207
2208 static INFO: Info = Info {
2209 register_block: crate::peripherals::$instance::ptr(),
2210 peripheral: Peripheral::$sys,
2211 clock_instance: TwaiInstance::$sys,
2212 interrupt: Interrupt::$instance,
2213 async_handler: irq_handler,
2214 rx_signal: InputSignal::$rx,
2215 tx_signal: OutputSignal::$tx,
2216 };
2217
2218 (&INFO, &STATE)
2219 }
2220 }
2221 };
2222}
2223
2224impl Instance for AnyCanFd<'_> {
2225 #[inline]
2226 fn parts(&self) -> (&'static Info, &'static asynch::State) {
2227 any::delegate!(self, twai => { twai.parts() })
2228 }
2229}
2230
2231const RANGE_FILTER_INDEX: usize = 3;
2233
2234const RESET_FILTER_KINDS: [FrameKinds; 4] = [
2237 FrameKinds::ALL,
2238 FrameKinds::NONE,
2239 FrameKinds::NONE,
2240 FrameKinds::NONE,
2241];
2242
2243const PRESCALER_PERIOD: u32 = 1 << 16;
2246
2247const MIN_TRANSMITTER_DELAY_CYCLES: u32 = 2;
2250
2251const INTEGRATION_TIMEOUT_BITS: u64 = 2048;
2254
2255const INTEGRATION_TIMEOUT_FLOOR: Duration = Duration::from_millis(50);
2258
2259const ABORT_TIMEOUT_BITS: u64 = 1024;
2262
2263fn abort_timeout(nominal: &Timing, fd: &Timing, function_clock_hz: u32) -> Duration {
2269 bit_times(
2271 slowest_cycles_per_bit(nominal, fd),
2272 ABORT_TIMEOUT_BITS,
2273 function_clock_hz,
2274 ) + Duration::from_millis(1)
2275}
2276
2277fn integration_timeout(nominal: &Timing, fd: &Timing, function_clock_hz: u32) -> Duration {
2279 let derived = bit_times(
2280 slowest_cycles_per_bit(nominal, fd),
2281 INTEGRATION_TIMEOUT_BITS,
2282 function_clock_hz,
2283 );
2284
2285 if derived < INTEGRATION_TIMEOUT_FLOOR {
2286 INTEGRATION_TIMEOUT_FLOOR
2287 } else {
2288 derived
2289 }
2290}
2291
2292fn slowest_cycles_per_bit(nominal: &Timing, fd: &Timing) -> u64 {
2294 let cycles_per_bit =
2295 |timing: &Timing| u64::from(timing.baud_rate_prescaler) * u64::from(timing.total_quanta());
2296 cycles_per_bit(nominal).max(cycles_per_bit(fd))
2297}
2298
2299fn bit_times(cycles_per_bit: u64, bits: u64, function_clock_hz: u32) -> Duration {
2301 let micros = cycles_per_bit
2303 .saturating_mul(bits)
2304 .saturating_mul(1_000_000)
2305 / u64::from(function_clock_hz).max(1);
2306
2307 Duration::from_micros(micros)
2308}
2309
2310struct FunctionClockGuard {
2311 instance: TwaiInstance,
2312}
2313
2314impl FunctionClockGuard {
2315 fn new(instance: TwaiInstance, clock_source: ClockSource) -> Self {
2316 ClockTree::with(|clocks| {
2317 instance.configure_function_clock(clocks, clock_source);
2319 instance.request_function_clock(clocks);
2320 });
2321 Self { instance }
2322 }
2323
2324 fn set_source(&self, clock_source: ClockSource) {
2325 ClockTree::with(|clocks| {
2326 self.instance.configure_function_clock(clocks, clock_source);
2327 });
2328 }
2329}
2330
2331impl Drop for FunctionClockGuard {
2332 fn drop(&mut self) {
2333 ClockTree::with(|clocks| self.instance.release_function_clock(clocks));
2334 }
2335}