Skip to main content

ch32_hal/can/
can.rs

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
16/// Receive interrupt handler.
17pub 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); // Disable FIFO 0 message pending interrupt
28            });
29        });
30    }
31}
32
33/// Transmit interrupt handler.
34pub 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/// Can config
49///
50/// Without the `embassy` feature, waits have no timeout and may block
51/// indefinitely if the peripheral does not make progress.
52#[non_exhaustive]
53#[derive(Copy, Clone)]
54pub struct Config {
55    /// Timeout. Without the `embassy` feature, waits have no deadline.
56    #[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            // Disable interrupt if the future is canceled
102            T::regs().intenr().modify(|w| {
103                w.set_fmpie0(false); // Disable FIFO 0 message pending interrupt
104            })
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                // No messages available, wait for a new message
113                regs.0.intenr().modify(|w| {
114                    w.set_fmpie0(true); // Enable FIFO 0 message pending interrupt
115                });
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            // Disable interrupt if the future is canceled
130            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                // Mailbox available
139                self.last_mailbox_used = mailbox_num;
140                Poll::Ready(Ok(()))
141            } else {
142                // No mailbox available, wait for one to become free
143                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    /// Puts a frame in the transmit buffer to be sent on the bus.
169    ///
170    /// If the transmit buffer is full, this function will block until a mailbox becomes available or the timeout is reached.
171    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    /// Blocks until a frame was received or an error occurred.
187    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    /// Puts a frame in the transmit buffer to be sent on the bus.
213    ///
214    /// If the transmit buffer is full, this function will try to replace a pending
215    /// lower priority frame and return the frame that was replaced.
216    /// Returns `Err(WouldBlock)` if the transmit buffer is full and no frame can be
217    /// replaced.
218    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        // Success in readying packet for transmit. No packets can be replaced in the
228        // transmit buffer so return None in accordance with embedded-can.
229        Ok(None)
230    }
231
232    /// Try to read the next message from the queue.
233    /// If there are no messages, an error is returned.
234    pub fn try_recv(&self) -> nb::Result<CanFrame, CanError> {
235        let regs = Registers::new::<T>();
236
237        //check pending messages
238        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    /// Assumes AFIO & PORTB clocks have been enabled by HAL.
248    ///
249    /// CAN_RX is mapped to PB8, and CAN_TX is mapped to PB9.
250    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(); // Enable CAN peripheral
268
269        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        // //here should remap functionality be added
281        // T::remap(0b10);
282
283        unsafe {
284            use crate::interrupt::typelevel::Interrupt;
285            T::ReceiveInterrupt::enable();
286            T::TransmitInterrupt::enable();
287        };
288
289        Registers::new::<T>().enter_init_mode(); // CAN enter initialization mode
290
291        // Configure bit timing parameters and CAN operating mode
292        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(); // Exit CAN initialization mode
299
300        Ok(this)
301    }
302
303    /// Each filter bank consists of 2 32-bit registers CAN_FxR0 and CAN_FxR1
304    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)); // Enable filter init mode
309
310        can.fscfgr()
311            .modify(|w| w.set_fsc(filter.bank, filter.bit_mode.val_bool())); // Set filter scale config (32bit or 16bit mode)
312
313        can.fr(filter.fr_id_value_reg())
314            .write_value(crate::pac::can::regs::Fr(filter.id_value)); // Set filter's id value to match/mask
315
316        can.fr(filter.fr_id_mask_reg())
317            .write_value(crate::pac::can::regs::Fr(filter.id_mask)); // Set filter's id bits to mask
318
319        can.fmcfgr().modify(|w| w.set_fbm(filter.bank, filter.mode.val_bool())); // Set new filter's operating mode
320
321        can.fafifor()
322            .modify(|w| w.set_ffa(filter.bank, fifo.val_bool())); // Associate CAN's FIFO to new filter
323
324        can.fwr().modify(|w| w.set_fact(filter.bank, true)); // Activate new filter
325
326        can.fctlr().modify(|w| w.set_finit(false)); // Exit filter init mode
327    }
328
329    /// Retrieves status of the last frame transmission
330    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    /// Receives a CAN frame from the hardware. Caller must make sure that a frame is available
339    /// in the FIFO before calling this method.
340    fn receive_inner(&self) -> Result<CanFrame, CanError> {
341        let regs = Registers::new::<T>();
342        let fifo = self.fifo.val();
343
344        // A DLC of 9 to 15 is valid in classic CAN and carries 8 data bytes.
345        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            //set the data was read
362            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
376/// These trait methods are only usable within the embedded_can context.
377/// Under normal use of the [Can] instance,
378impl<'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    /// Puts a frame in the transmit buffer to be sent on the bus.
386    ///
387    /// If the transmit buffer is full, this function will try to replace a pending
388    /// lower priority frame and return the frame that was replaced.
389    /// Returns `Err(WouldBlock)` if the transmit buffer is full and no frame can be
390    /// replaced.
391    fn transmit(&mut self, frame: &Self::Frame) -> nb::Result<Option<Self::Frame>, Self::Error> {
392        Can::nb_transmit(self, frame)
393    }
394
395    /// Returns a received frame if available.
396    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    /// Puts a frame in the transmit buffer. Blocks until space is available in
409    /// the transmit buffer.
410    fn transmit(&mut self, frame: &Self::Frame) -> Result<(), Self::Error> {
411        Can::blocking_transmit(self, frame)
412    }
413
414    /// Blocks until a frame was received or an error occured.
415    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    // Either `0b00`, `0b10` or `b11` on CAN1. `0` or `1` on CAN2.
438    // fn remap(rm: u8) -> ();
439
440    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            // FIXME: CH32L1 supports CANFD, and is compatible with the CAN peripheral.
455            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);