1use core::future::poll_fn;
2use core::marker::PhantomData;
3use core::task::Poll;
4
5use embassy_sync::waitqueue::AtomicWaker;
6
7use super::enums::*;
8use super::filter::{BitMode, FilterMode};
9use super::{CanFilter, CanFrame};
10use crate::can::registers::Registers;
11use crate::can::util;
12use crate::internal::drop::OnDrop;
13use crate::mode::{Async, Blocking, Mode, NonBlocking};
14use crate::{interrupt, pac, peripherals, Peri, RccPeripheral, RemapPeripheral, Timeout};
15
16pub struct ReceiveInterruptHandler<T: Instance> {
18 _phantom: PhantomData<T>,
19}
20
21impl<T: Instance> interrupt::typelevel::Handler<T::ReceiveInterrupt> for ReceiveInterruptHandler<T> {
22 unsafe fn on_interrupt() {
23 let regs = &T::regs();
24 T::state().rx_waker.wake();
25 critical_section::with(|_| {
26 regs.intenr().modify(|w| {
27 w.set_fmpie0(false); });
29 });
30 }
31}
32
33pub struct TransmitInterruptHandler<T: Instance> {
35 _phantom: PhantomData<T>,
36}
37
38impl<T: Instance> interrupt::typelevel::Handler<T::TransmitInterrupt> for TransmitInterruptHandler<T> {
39 unsafe fn on_interrupt() {
40 let regs = Registers::new::<T>();
41 T::state().tx_waker.wake();
42 critical_section::with(|_| {
43 regs.enable_transmit_empty_interrupt(false);
44 });
45 }
46}
47
48#[non_exhaustive]
53#[derive(Copy, Clone)]
54pub struct Config {
55 #[cfg(feature = "embassy")]
57 pub timeout: embassy_time::Duration,
58}
59
60impl Default for Config {
61 fn default() -> Self {
62 Self {
63 #[cfg(feature = "embassy")]
64 timeout: embassy_time::Duration::from_millis(1000),
65 }
66 }
67}
68
69pub struct Can<'d, T: Instance, M: Mode> {
70 _peri: Peri<'d, T>,
71 fifo: CanFifo,
72 last_mailbox_used: usize,
73 #[cfg(feature = "embassy")]
74 timeout: embassy_time::Duration,
75 _phantom: PhantomData<(&'d mut T, M)>,
76}
77
78#[derive(Debug)]
79pub enum CanInitError {
80 InvalidTimings,
81}
82
83impl<'d, T: Instance> Can<'d, T, Async> {
84 pub fn new_async<const REMAP: u8>(
85 peri: Peri<'d, T>,
86 rx: Peri<'d, impl RxPin<T, REMAP>>,
87 tx: Peri<'d, impl TxPin<T, REMAP>>,
88 _irq: impl interrupt::typelevel::Binding<T::ReceiveInterrupt, ReceiveInterruptHandler<T>>
89 + interrupt::typelevel::Binding<T::TransmitInterrupt, TransmitInterruptHandler<T>>
90 + 'd,
91 fifo: CanFifo,
92 mode: CanMode,
93 bitrate: u32,
94 config: Config,
95 ) -> Result<Self, CanInitError> {
96 Self::new_inner(peri, rx, tx, fifo, mode, bitrate, config)
97 }
98
99 pub async fn receive(&self) -> Result<CanFrame, CanError> {
100 let on_drop = OnDrop::new(|| {
101 T::regs().intenr().modify(|w| {
103 w.set_fmpie0(false); })
105 });
106 poll_fn(|cx| {
107 T::state().rx_waker.register(cx.waker());
108
109 let regs = Registers::new::<T>();
110
111 if regs.pending_messages(self.fifo) == 0 {
112 regs.0.intenr().modify(|w| {
114 w.set_fmpie0(true); });
116 Poll::Pending
117 } else {
118 Poll::Ready(Ok(()))
119 }
120 })
121 .await?;
122 drop(on_drop);
123
124 self.receive_inner()
125 }
126
127 pub async fn transmit(&mut self, frame: &CanFrame) -> Result<(), CanError> {
128 let on_drop = OnDrop::new(|| {
129 Registers::new::<T>().enable_transmit_empty_interrupt(false);
131 });
132 poll_fn(|cx| {
133 T::state().tx_waker.register(cx.waker());
134
135 let regs = Registers::new::<T>();
136
137 if let Some(mailbox_num) = regs.find_free_mailbox() {
138 self.last_mailbox_used = mailbox_num;
140 Poll::Ready(Ok(()))
141 } else {
142 regs.enable_transmit_empty_interrupt(true);
144 Poll::Pending
145 }
146 })
147 .await?;
148 drop(on_drop);
149
150 Registers::new::<T>().write_frame_mailbox(self.last_mailbox_used, frame);
151 Ok(())
152 }
153}
154
155impl<'d, T: Instance> Can<'d, T, Blocking> {
156 pub fn new_blocking<const REMAP: u8>(
157 peri: Peri<'d, T>,
158 rx: Peri<'d, impl RxPin<T, REMAP>>,
159 tx: Peri<'d, impl TxPin<T, REMAP>>,
160 fifo: CanFifo,
161 mode: CanMode,
162 bitrate: u32,
163 config: Config,
164 ) -> Result<Self, CanInitError> {
165 Self::new_inner(peri, rx, tx, fifo, mode, bitrate, config)
166 }
167
168 fn blocking_transmit(&mut self, frame: &CanFrame) -> Result<(), CanError> {
172 let regs = Registers::new::<T>();
173 let timeout = self.timeout();
174
175 let mailbox_num = loop {
176 if let Some(mailbox_num) = regs.find_free_mailbox() {
177 break mailbox_num;
178 };
179 timeout.check().ok_or(CanError::Timeout)?;
180 };
181 regs.write_frame_mailbox(mailbox_num, frame);
182 self.last_mailbox_used = mailbox_num;
183 Ok(())
184 }
185
186 fn blocking_recv(&self) -> Result<CanFrame, CanError> {
188 let timeout = self.timeout();
189
190 while Registers::new::<T>().pending_messages(self.fifo) == 0 {
191 timeout.check().ok_or(CanError::Timeout)?;
192 }
193
194 let frame = self.receive_inner()?;
195 Ok(frame)
196 }
197}
198
199impl<'d, T: Instance> Can<'d, T, NonBlocking> {
200 pub fn new_nb<const REMAP: u8>(
201 peri: Peri<'d, T>,
202 rx: Peri<'d, impl RxPin<T, REMAP>>,
203 tx: Peri<'d, impl TxPin<T, REMAP>>,
204 fifo: CanFifo,
205 mode: CanMode,
206 bitrate: u32,
207 config: Config,
208 ) -> Result<Self, CanInitError> {
209 Self::new_inner(peri, rx, tx, fifo, mode, bitrate, config)
210 }
211
212 fn nb_transmit(&mut self, frame: &CanFrame) -> nb::Result<Option<CanFrame>, CanError> {
219 let mailbox_num = match Registers::new::<T>().find_free_mailbox() {
220 Some(n) => n,
221 None => return Err(nb::Error::WouldBlock),
222 };
223
224 Registers::new::<T>().write_frame_mailbox(mailbox_num, frame);
225 self.last_mailbox_used = mailbox_num;
226
227 Ok(None)
230 }
231
232 pub fn try_recv(&self) -> nb::Result<CanFrame, CanError> {
235 let regs = Registers::new::<T>();
236
237 if regs.pending_messages(self.fifo) == 0 {
239 return Err(nb::Error::WouldBlock);
240 }
241
242 self.receive_inner().map_err(nb::Error::Other)
243 }
244}
245
246impl<'d, T: Instance, M: Mode> Can<'d, T, M> {
247 fn new_inner<const REMAP: u8>(
251 peri: Peri<'d, T>,
252 rx: Peri<'d, impl RxPin<T, REMAP>>,
253 tx: Peri<'d, impl TxPin<T, REMAP>>,
254 fifo: CanFifo,
255 mode: CanMode,
256 bitrate: u32,
257 config: Config,
258 ) -> Result<Self, CanInitError> {
259 let this = Self {
260 _peri: peri,
261 fifo,
262 last_mailbox_used: usize::MAX,
263 #[cfg(feature = "embassy")]
264 timeout: config.timeout,
265 _phantom: PhantomData,
266 };
267 T::enable_and_reset(); rx.set_mode_cnf(
270 pac::gpio::vals::Mode::INPUT,
271 pac::gpio::vals::Cnf::PULL_IN__AF_PUSH_PULL_OUT,
272 );
273
274 tx.set_mode_cnf(
275 pac::gpio::vals::Mode::OUTPUT_50MHZ,
276 pac::gpio::vals::Cnf::PULL_IN__AF_PUSH_PULL_OUT,
277 );
278 T::set_remap(REMAP);
279
280 unsafe {
284 use crate::interrupt::typelevel::Interrupt;
285 T::ReceiveInterrupt::enable();
286 T::TransmitInterrupt::enable();
287 };
288
289 Registers::new::<T>().enter_init_mode(); let Some(bit_timings) = util::calc_can_timings(T::frequency().0, bitrate) else {
293 return Err(CanInitError::InvalidTimings);
294 };
295
296 Registers::new::<T>().set_bit_timing_and_mode(bit_timings, mode);
297
298 Registers::new::<T>().leave_init_mode(); Ok(this)
301 }
302
303 pub fn add_filter<BIT: BitMode, MODE: FilterMode>(&self, filter: CanFilter<BIT, MODE>) {
305 let can = T::regs();
306 let fifo = &self.fifo;
307
308 can.fctlr().modify(|w| w.set_finit(true)); can.fscfgr()
311 .modify(|w| w.set_fsc(filter.bank, filter.bit_mode.val_bool())); can.fr(filter.fr_id_value_reg())
314 .write_value(crate::pac::can::regs::Fr(filter.id_value)); can.fr(filter.fr_id_mask_reg())
317 .write_value(crate::pac::can::regs::Fr(filter.id_mask)); can.fmcfgr().modify(|w| w.set_fbm(filter.bank, filter.mode.val_bool())); can.fafifor()
322 .modify(|w| w.set_ffa(filter.bank, fifo.val_bool())); can.fwr().modify(|w| w.set_fact(filter.bank, true)); can.fctlr().modify(|w| w.set_finit(false)); }
328
329 pub fn transmit_status(&self) -> TxStatus {
331 if self.last_mailbox_used > 2 {
332 return TxStatus::OtherError;
333 }
334
335 Registers::new::<T>().transmit_status(self.last_mailbox_used)
336 }
337
338 fn receive_inner(&self) -> Result<CanFrame, CanError> {
341 let regs = Registers::new::<T>();
342 let fifo = self.fifo.val();
343
344 let dlc = (regs.0.rxmdtr(fifo).read().dlc() as usize).min(8);
346 let rxmir = regs.0.rxmir(fifo).read();
347
348 let id = if rxmir.ide() {
349 let raw_id = ((rxmir.stid() as u32) << 18) | rxmir.exid();
350 embedded_can::Id::from(unsafe { embedded_can::ExtendedId::new_unchecked(raw_id & 0x1FFFFFFF) })
351 } else {
352 embedded_can::Id::Standard(embedded_can::StandardId::new(rxmir.stid()).unwrap())
353 };
354
355 let frame_data_unordered: u64 =
356 ((regs.0.rxmdhr(fifo).read().0 as u64) << 32) | regs.0.rxmdlr(fifo).read().0 as u64;
357
358 let frame = CanFrame::new_from_data_registers(id, frame_data_unordered, dlc);
359
360 regs.0.rfifo(fifo).write(|w| {
361 w.set_rfom(true);
363 });
364
365 Ok(frame)
366 }
367
368 fn timeout(&self) -> Timeout {
369 Timeout {
370 #[cfg(feature = "embassy")]
371 deadline: embassy_time::Instant::now() + self.timeout,
372 }
373 }
374}
375
376impl<'d, T> embedded_can::nb::Can for Can<'d, T, NonBlocking>
379where
380 T: Instance,
381{
382 type Frame = CanFrame;
383 type Error = CanError;
384
385 fn transmit(&mut self, frame: &Self::Frame) -> nb::Result<Option<Self::Frame>, Self::Error> {
392 Can::nb_transmit(self, frame)
393 }
394
395 fn receive(&mut self) -> nb::Result<Self::Frame, Self::Error> {
397 Can::try_recv(self)
398 }
399}
400
401impl<'d, T> embedded_can::blocking::Can for Can<'d, T, Blocking>
402where
403 T: Instance,
404{
405 type Frame = CanFrame;
406 type Error = CanError;
407
408 fn transmit(&mut self, frame: &Self::Frame) -> Result<(), Self::Error> {
411 Can::blocking_transmit(self, frame)
412 }
413
414 fn receive(&mut self) -> Result<Self::Frame, Self::Error> {
416 Can::blocking_recv(self)
417 }
418}
419
420struct State {
421 #[allow(unused)]
422 rx_waker: AtomicWaker,
423 tx_waker: AtomicWaker,
424}
425
426impl State {
427 const fn new() -> Self {
428 Self {
429 rx_waker: AtomicWaker::new(),
430 tx_waker: AtomicWaker::new(),
431 }
432 }
433}
434
435pub trait SealedInstance: RccPeripheral + RemapPeripheral {
436 fn regs() -> pac::can::Can;
437 fn state() -> &'static State;
441}
442
443pub trait Instance: SealedInstance + embassy_hal_internal::PeripheralType + 'static {
444 type ReceiveInterrupt: crate::interrupt::typelevel::Interrupt;
445 type TransmitInterrupt: crate::interrupt::typelevel::Interrupt;
446}
447
448pin_trait!(RxPin, Instance);
449pin_trait!(TxPin, Instance);
450
451foreach_peripheral!(
452 (can, $inst:ident) => {
453 impl SealedInstance for peripherals::$inst {
454 fn regs() -> crate::pac::can::Can {
456 #[cfg(ch32l1)]
457 return unsafe { crate::pac::can::Can::from_ptr(crate::pac::$inst.as_ptr()) };
458 #[cfg(not(ch32l1))]
459 return crate::pac::$inst;
460 }
461
462 fn state() -> &'static State {
463 static STATE: State = State::new();
464 &STATE
465 }
466 }
467
468 impl Instance for peripherals::$inst {
469 type ReceiveInterrupt = crate::_generated::peripheral_interrupts::$inst::RX0;
470 type TransmitInterrupt = crate::_generated::peripheral_interrupts::$inst::TX;
471 }
472 };
473);