aboutsummaryrefslogtreecommitdiff
path: root/embassy-stm32/src/can/fd
diff options
context:
space:
mode:
authorDario Nieuwenhuis <[email protected]>2024-02-23 01:45:10 +0100
committerGitHub <[email protected]>2024-02-23 01:45:10 +0100
commita6a5d9913cda2ecfe89b63fa0bcf7afaebc2dac0 (patch)
tree14124a6f34d351a979cb110a0ce566b588f5d272 /embassy-stm32/src/can/fd
parent5b7e2d88265b5633fa53047961598fbc38bffed0 (diff)
parent2855bb69680a42a721fe88168657ea1e634e8766 (diff)
Merge branch 'main' into stm32l0-reset-rtc
Diffstat (limited to 'embassy-stm32/src/can/fd')
-rw-r--r--embassy-stm32/src/can/fd/config.rs438
-rw-r--r--embassy-stm32/src/can/fd/filter.rs379
-rw-r--r--embassy-stm32/src/can/fd/message_ram/common.rs134
-rw-r--r--embassy-stm32/src/can/fd/message_ram/enums.rs233
-rw-r--r--embassy-stm32/src/can/fd/message_ram/extended_filter.rs136
-rw-r--r--embassy-stm32/src/can/fd/message_ram/generic.rs168
-rw-r--r--embassy-stm32/src/can/fd/message_ram/mod.rs170
-rw-r--r--embassy-stm32/src/can/fd/message_ram/rxfifo_element.rs122
-rw-r--r--embassy-stm32/src/can/fd/message_ram/standard_filter.rs136
-rw-r--r--embassy-stm32/src/can/fd/message_ram/txbuffer_element.rs433
-rw-r--r--embassy-stm32/src/can/fd/message_ram/txevent_element.rs138
-rw-r--r--embassy-stm32/src/can/fd/mod.rs6
-rw-r--r--embassy-stm32/src/can/fd/peripheral.rs828
13 files changed, 3321 insertions, 0 deletions
diff --git a/embassy-stm32/src/can/fd/config.rs b/embassy-stm32/src/can/fd/config.rs
new file mode 100644
index 000000000..38b409121
--- /dev/null
+++ b/embassy-stm32/src/can/fd/config.rs
@@ -0,0 +1,438 @@
1//! Configuration for FDCAN Module
2//! Note: This file is copied and modified from fdcan crate by Richard Meadows
3
4use core::num::{NonZeroU16, NonZeroU8};
5
6/// Configures the bit timings.
7///
8/// You can use <http://www.bittiming.can-wiki.info/> to calculate the `btr` parameter. Enter
9/// parameters as follows:
10///
11/// - *Clock Rate*: The input clock speed to the CAN peripheral (*not* the CPU clock speed).
12/// This is the clock rate of the peripheral bus the CAN peripheral is attached to (eg. APB1).
13/// - *Sample Point*: Should normally be left at the default value of 87.5%.
14/// - *SJW*: Should normally be left at the default value of 1.
15///
16/// Then copy the `CAN_BUS_TIME` register value from the table and pass it as the `btr`
17/// parameter to this method.
18#[derive(Clone, Copy, Debug)]
19pub struct NominalBitTiming {
20 /// Value by which the oscillator frequency is divided for generating the bit time quanta. The bit
21 /// time is built up from a multiple of this quanta. Valid values are 1 to 512.
22 pub prescaler: NonZeroU16,
23 /// Valid values are 1 to 128.
24 pub seg1: NonZeroU8,
25 /// Valid values are 1 to 255.
26 pub seg2: NonZeroU8,
27 /// Valid values are 1 to 128.
28 pub sync_jump_width: NonZeroU8,
29}
30impl NominalBitTiming {
31 #[inline]
32 pub(crate) fn nbrp(&self) -> u16 {
33 u16::from(self.prescaler) & 0x1FF
34 }
35 #[inline]
36 pub(crate) fn ntseg1(&self) -> u8 {
37 u8::from(self.seg1)
38 }
39 #[inline]
40 pub(crate) fn ntseg2(&self) -> u8 {
41 u8::from(self.seg2) & 0x7F
42 }
43 #[inline]
44 pub(crate) fn nsjw(&self) -> u8 {
45 u8::from(self.sync_jump_width) & 0x7F
46 }
47}
48
49impl Default for NominalBitTiming {
50 #[inline]
51 fn default() -> Self {
52 // Kernel Clock 8MHz, Bit rate: 500kbit/s. Corresponds to a NBTP
53 // register value of 0x0600_0A03
54 Self {
55 prescaler: NonZeroU16::new(1).unwrap(),
56 seg1: NonZeroU8::new(11).unwrap(),
57 seg2: NonZeroU8::new(4).unwrap(),
58 sync_jump_width: NonZeroU8::new(4).unwrap(),
59 }
60 }
61}
62
63/// Configures the data bit timings for the FdCan Variable Bitrates.
64/// This is not used when frame_transmit is set to anything other than AllowFdCanAndBRS.
65#[derive(Clone, Copy, Debug)]
66pub struct DataBitTiming {
67 /// Tranceiver Delay Compensation
68 pub transceiver_delay_compensation: bool,
69 /// The value by which the oscillator frequency is divided to generate the bit time quanta. The bit
70 /// time is built up from a multiple of this quanta. Valid values for the Baud Rate Prescaler are 1
71 /// to 31.
72 pub prescaler: NonZeroU16,
73 /// Valid values are 1 to 31.
74 pub seg1: NonZeroU8,
75 /// Valid values are 1 to 15.
76 pub seg2: NonZeroU8,
77 /// Must always be smaller than DTSEG2, valid values are 1 to 15.
78 pub sync_jump_width: NonZeroU8,
79}
80impl DataBitTiming {
81 // #[inline]
82 // fn tdc(&self) -> u8 {
83 // let tsd = self.transceiver_delay_compensation as u8;
84 // //TODO: stm32g4 does not export the TDC field
85 // todo!()
86 // }
87 #[inline]
88 pub(crate) fn dbrp(&self) -> u8 {
89 (u16::from(self.prescaler) & 0x001F) as u8
90 }
91 #[inline]
92 pub(crate) fn dtseg1(&self) -> u8 {
93 u8::from(self.seg1) & 0x1F
94 }
95 #[inline]
96 pub(crate) fn dtseg2(&self) -> u8 {
97 u8::from(self.seg2) & 0x0F
98 }
99 #[inline]
100 pub(crate) fn dsjw(&self) -> u8 {
101 u8::from(self.sync_jump_width) & 0x0F
102 }
103}
104
105impl Default for DataBitTiming {
106 #[inline]
107 fn default() -> Self {
108 // Kernel Clock 8MHz, Bit rate: 500kbit/s. Corresponds to a DBTP
109 // register value of 0x0000_0A33
110 Self {
111 transceiver_delay_compensation: false,
112 prescaler: NonZeroU16::new(1).unwrap(),
113 seg1: NonZeroU8::new(11).unwrap(),
114 seg2: NonZeroU8::new(4).unwrap(),
115 sync_jump_width: NonZeroU8::new(4).unwrap(),
116 }
117 }
118}
119
120/// Configures which modes to use
121/// Individual headers can contain a desire to be send via FdCan
122/// or use Bit rate switching. But if this general setting does not allow
123/// that, only classic CAN is used instead.
124#[derive(Clone, Copy, Debug)]
125pub enum FrameTransmissionConfig {
126 /// Only allow Classic CAN message Frames
127 ClassicCanOnly,
128 /// Allow (non-brs) FdCAN Message Frames
129 AllowFdCan,
130 /// Allow FdCAN Message Frames and allow Bit Rate Switching
131 AllowFdCanAndBRS,
132}
133
134///
135#[derive(Clone, Copy, Debug)]
136pub enum ClockDivider {
137 /// Divide by 1
138 _1 = 0b0000,
139 /// Divide by 2
140 _2 = 0b0001,
141 /// Divide by 4
142 _4 = 0b0010,
143 /// Divide by 6
144 _6 = 0b0011,
145 /// Divide by 8
146 _8 = 0b0100,
147 /// Divide by 10
148 _10 = 0b0101,
149 /// Divide by 12
150 _12 = 0b0110,
151 /// Divide by 14
152 _14 = 0b0111,
153 /// Divide by 16
154 _16 = 0b1000,
155 /// Divide by 18
156 _18 = 0b1001,
157 /// Divide by 20
158 _20 = 0b1010,
159 /// Divide by 22
160 _22 = 0b1011,
161 /// Divide by 24
162 _24 = 0b1100,
163 /// Divide by 26
164 _26 = 0b1101,
165 /// Divide by 28
166 _28 = 0b1110,
167 /// Divide by 30
168 _30 = 0b1111,
169}
170
171/// Prescaler of the Timestamp counter
172#[derive(Clone, Copy, Debug)]
173pub enum TimestampPrescaler {
174 /// 1
175 _1 = 1,
176 /// 2
177 _2 = 2,
178 /// 3
179 _3 = 3,
180 /// 4
181 _4 = 4,
182 /// 5
183 _5 = 5,
184 /// 6
185 _6 = 6,
186 /// 7
187 _7 = 7,
188 /// 8
189 _8 = 8,
190 /// 9
191 _9 = 9,
192 /// 10
193 _10 = 10,
194 /// 11
195 _11 = 11,
196 /// 12
197 _12 = 12,
198 /// 13
199 _13 = 13,
200 /// 14
201 _14 = 14,
202 /// 15
203 _15 = 15,
204 /// 16
205 _16 = 16,
206}
207
208/// Selects the source of the Timestamp counter
209#[derive(Clone, Copy, Debug)]
210pub enum TimestampSource {
211 /// The Timestamp counter is disabled
212 None,
213 /// Using the FdCan input clock as the Timstamp counter's source,
214 /// and using a specific prescaler
215 Prescaler(TimestampPrescaler),
216 /// Using TIM3 as a source
217 FromTIM3,
218}
219
220/// How to handle frames in the global filter
221#[derive(Clone, Copy, Debug)]
222pub enum NonMatchingFilter {
223 /// Frames will go to Fifo0 when they do no match any specific filter
224 IntoRxFifo0 = 0b00,
225 /// Frames will go to Fifo1 when they do no match any specific filter
226 IntoRxFifo1 = 0b01,
227 /// Frames will be rejected when they do not match any specific filter
228 Reject = 0b11,
229}
230
231/// How to handle frames which do not match a specific filter
232#[derive(Clone, Copy, Debug)]
233pub struct GlobalFilter {
234 /// How to handle non-matching standard frames
235 pub handle_standard_frames: NonMatchingFilter,
236
237 /// How to handle non-matching extended frames
238 pub handle_extended_frames: NonMatchingFilter,
239
240 /// How to handle remote standard frames
241 pub reject_remote_standard_frames: bool,
242
243 /// How to handle remote extended frames
244 pub reject_remote_extended_frames: bool,
245}
246impl GlobalFilter {
247 /// Reject all non-matching and remote frames
248 pub const fn reject_all() -> Self {
249 Self {
250 handle_standard_frames: NonMatchingFilter::Reject,
251 handle_extended_frames: NonMatchingFilter::Reject,
252 reject_remote_standard_frames: true,
253 reject_remote_extended_frames: true,
254 }
255 }
256
257 /// How to handle non-matching standard frames
258 pub const fn set_handle_standard_frames(mut self, filter: NonMatchingFilter) -> Self {
259 self.handle_standard_frames = filter;
260 self
261 }
262 /// How to handle non-matching exteded frames
263 pub const fn set_handle_extended_frames(mut self, filter: NonMatchingFilter) -> Self {
264 self.handle_extended_frames = filter;
265 self
266 }
267 /// How to handle remote standard frames
268 pub const fn set_reject_remote_standard_frames(mut self, filter: bool) -> Self {
269 self.reject_remote_standard_frames = filter;
270 self
271 }
272 /// How to handle remote extended frames
273 pub const fn set_reject_remote_extended_frames(mut self, filter: bool) -> Self {
274 self.reject_remote_extended_frames = filter;
275 self
276 }
277}
278impl Default for GlobalFilter {
279 #[inline]
280 fn default() -> Self {
281 Self {
282 handle_standard_frames: NonMatchingFilter::IntoRxFifo0,
283 handle_extended_frames: NonMatchingFilter::IntoRxFifo0,
284 reject_remote_standard_frames: false,
285 reject_remote_extended_frames: false,
286 }
287 }
288}
289
290/// FdCan Config Struct
291#[derive(Clone, Copy, Debug)]
292pub struct FdCanConfig {
293 /// Nominal Bit Timings
294 pub nbtr: NominalBitTiming,
295 /// (Variable) Data Bit Timings
296 pub dbtr: DataBitTiming,
297 /// Enables or disables automatic retransmission of messages
298 ///
299 /// If this is enabled, the CAN peripheral will automatically try to retransmit each frame
300 /// util it can be sent. Otherwise, it will try only once to send each frame.
301 ///
302 /// Automatic retransmission is enabled by default.
303 pub automatic_retransmit: bool,
304 /// Enabled or disables the pausing between transmissions
305 ///
306 /// This feature looses up burst transmissions coming from a single node and it protects against
307 /// "babbling idiot" scenarios where the application program erroneously requests too many
308 /// transmissions.
309 pub transmit_pause: bool,
310 /// Enabled or disables the pausing between transmissions
311 ///
312 /// This feature looses up burst transmissions coming from a single node and it protects against
313 /// "babbling idiot" scenarios where the application program erroneously requests too many
314 /// transmissions.
315 pub frame_transmit: FrameTransmissionConfig,
316 /// Non Isoe Mode
317 /// If this is set, the FDCAN uses the CAN FD frame format as specified by the Bosch CAN
318 /// FD Specification V1.0.
319 pub non_iso_mode: bool,
320 /// Edge Filtering: Two consecutive dominant tq required to detect an edge for hard synchronization
321 pub edge_filtering: bool,
322 /// Enables protocol exception handling
323 pub protocol_exception_handling: bool,
324 /// Sets the general clock divider for this FdCAN instance
325 pub clock_divider: ClockDivider,
326 /// Sets the timestamp source
327 pub timestamp_source: TimestampSource,
328 /// Configures the Global Filter
329 pub global_filter: GlobalFilter,
330}
331
332impl FdCanConfig {
333 /// Configures the bit timings.
334 #[inline]
335 pub const fn set_nominal_bit_timing(mut self, btr: NominalBitTiming) -> Self {
336 self.nbtr = btr;
337 self
338 }
339
340 /// Configures the bit timings.
341 #[inline]
342 pub const fn set_data_bit_timing(mut self, btr: DataBitTiming) -> Self {
343 self.dbtr = btr;
344 self
345 }
346
347 /// Enables or disables automatic retransmission of messages
348 ///
349 /// If this is enabled, the CAN peripheral will automatically try to retransmit each frame
350 /// util it can be sent. Otherwise, it will try only once to send each frame.
351 ///
352 /// Automatic retransmission is enabled by default.
353 #[inline]
354 pub const fn set_automatic_retransmit(mut self, enabled: bool) -> Self {
355 self.automatic_retransmit = enabled;
356 self
357 }
358
359 /// Enabled or disables the pausing between transmissions
360 ///
361 /// This feature looses up burst transmissions coming from a single node and it protects against
362 /// "babbling idiot" scenarios where the application program erroneously requests too many
363 /// transmissions.
364 #[inline]
365 pub const fn set_transmit_pause(mut self, enabled: bool) -> Self {
366 self.transmit_pause = enabled;
367 self
368 }
369
370 /// If this is set, the FDCAN uses the CAN FD frame format as specified by the Bosch CAN
371 /// FD Specification V1.0.
372 #[inline]
373 pub const fn set_non_iso_mode(mut self, enabled: bool) -> Self {
374 self.non_iso_mode = enabled;
375 self
376 }
377
378 /// Two consecutive dominant tq required to detect an edge for hard synchronization
379 #[inline]
380 pub const fn set_edge_filtering(mut self, enabled: bool) -> Self {
381 self.edge_filtering = enabled;
382 self
383 }
384
385 /// Sets the allowed transmission types for messages.
386 #[inline]
387 pub const fn set_frame_transmit(mut self, fts: FrameTransmissionConfig) -> Self {
388 self.frame_transmit = fts;
389 self
390 }
391
392 /// Enables protocol exception handling
393 #[inline]
394 pub const fn set_protocol_exception_handling(mut self, peh: bool) -> Self {
395 self.protocol_exception_handling = peh;
396 self
397 }
398
399 /// Sets the general clock divider for this FdCAN instance
400 #[inline]
401 pub const fn set_clock_divider(mut self, div: ClockDivider) -> Self {
402 self.clock_divider = div;
403 self
404 }
405
406 /// Sets the timestamp source
407 #[inline]
408 pub const fn set_timestamp_source(mut self, tss: TimestampSource) -> Self {
409 self.timestamp_source = tss;
410 self
411 }
412
413 /// Sets the global filter settings
414 #[inline]
415 pub const fn set_global_filter(mut self, filter: GlobalFilter) -> Self {
416 self.global_filter = filter;
417 self
418 }
419}
420
421impl Default for FdCanConfig {
422 #[inline]
423 fn default() -> Self {
424 Self {
425 nbtr: NominalBitTiming::default(),
426 dbtr: DataBitTiming::default(),
427 automatic_retransmit: true,
428 transmit_pause: false,
429 frame_transmit: FrameTransmissionConfig::ClassicCanOnly,
430 non_iso_mode: false,
431 edge_filtering: false,
432 protocol_exception_handling: true,
433 clock_divider: ClockDivider::_1,
434 timestamp_source: TimestampSource::None,
435 global_filter: GlobalFilter::default(),
436 }
437 }
438}
diff --git a/embassy-stm32/src/can/fd/filter.rs b/embassy-stm32/src/can/fd/filter.rs
new file mode 100644
index 000000000..3e2129e6e
--- /dev/null
+++ b/embassy-stm32/src/can/fd/filter.rs
@@ -0,0 +1,379 @@
1//! Definition of Filter structs for FDCAN Module
2//! Note: This file is copied and modified from fdcan crate by Richard Meadows
3
4use embedded_can::{ExtendedId, StandardId};
5
6use crate::can::fd::message_ram;
7pub use crate::can::fd::message_ram::{EXTENDED_FILTER_MAX, STANDARD_FILTER_MAX};
8
9/// A Standard Filter
10pub type StandardFilter = Filter<StandardId, u16>;
11/// An Extended Filter
12pub type ExtendedFilter = Filter<ExtendedId, u32>;
13
14impl Default for StandardFilter {
15 fn default() -> Self {
16 StandardFilter::disable()
17 }
18}
19impl Default for ExtendedFilter {
20 fn default() -> Self {
21 ExtendedFilter::disable()
22 }
23}
24
25impl StandardFilter {
26 /// Accept all messages in FIFO 0
27 pub fn accept_all_into_fifo0() -> StandardFilter {
28 StandardFilter {
29 filter: FilterType::BitMask { filter: 0x0, mask: 0x0 },
30 action: Action::StoreInFifo0,
31 }
32 }
33
34 /// Accept all messages in FIFO 1
35 pub fn accept_all_into_fifo1() -> StandardFilter {
36 StandardFilter {
37 filter: FilterType::BitMask { filter: 0x0, mask: 0x0 },
38 action: Action::StoreInFifo1,
39 }
40 }
41
42 /// Reject all messages
43 pub fn reject_all() -> StandardFilter {
44 StandardFilter {
45 filter: FilterType::BitMask { filter: 0x0, mask: 0x0 },
46 action: Action::Reject,
47 }
48 }
49
50 /// Disable the filter
51 pub fn disable() -> StandardFilter {
52 StandardFilter {
53 filter: FilterType::Disabled,
54 action: Action::Disable,
55 }
56 }
57}
58
59impl ExtendedFilter {
60 /// Accept all messages in FIFO 0
61 pub fn accept_all_into_fifo0() -> ExtendedFilter {
62 ExtendedFilter {
63 filter: FilterType::BitMask { filter: 0x0, mask: 0x0 },
64 action: Action::StoreInFifo0,
65 }
66 }
67
68 /// Accept all messages in FIFO 1
69 pub fn accept_all_into_fifo1() -> ExtendedFilter {
70 ExtendedFilter {
71 filter: FilterType::BitMask { filter: 0x0, mask: 0x0 },
72 action: Action::StoreInFifo1,
73 }
74 }
75
76 /// Reject all messages
77 pub fn reject_all() -> ExtendedFilter {
78 ExtendedFilter {
79 filter: FilterType::BitMask { filter: 0x0, mask: 0x0 },
80 action: Action::Reject,
81 }
82 }
83
84 /// Disable the filter
85 pub fn disable() -> ExtendedFilter {
86 ExtendedFilter {
87 filter: FilterType::Disabled,
88 action: Action::Disable,
89 }
90 }
91}
92
93/// Filter Type
94#[derive(Clone, Copy, Debug)]
95pub enum FilterType<ID, UNIT>
96where
97 ID: Copy + Clone + core::fmt::Debug,
98 UNIT: Copy + Clone + core::fmt::Debug,
99{
100 /// Match with a range between two messages
101 Range {
102 /// First Id of the range
103 from: ID,
104 /// Last Id of the range
105 to: ID,
106 },
107 /// Match with a bitmask
108 BitMask {
109 /// Filter of the bitmask
110 filter: UNIT,
111 /// Mask of the bitmask
112 mask: UNIT,
113 },
114 /// Match with a single ID
115 DedicatedSingle(ID),
116 /// Match with one of two ID's
117 DedicatedDual(ID, ID),
118 /// Filter is disabled
119 Disabled,
120}
121impl<ID, UNIT> From<FilterType<ID, UNIT>> for message_ram::enums::FilterType
122where
123 ID: Copy + Clone + core::fmt::Debug,
124 UNIT: Copy + Clone + core::fmt::Debug,
125{
126 fn from(f: FilterType<ID, UNIT>) -> Self {
127 match f {
128 FilterType::Range { to: _, from: _ } => Self::RangeFilter,
129 FilterType::BitMask { filter: _, mask: _ } => Self::ClassicFilter,
130 FilterType::DedicatedSingle(_) => Self::DualIdFilter,
131 FilterType::DedicatedDual(_, _) => Self::DualIdFilter,
132 FilterType::Disabled => Self::FilterDisabled,
133 }
134 }
135}
136
137/// Filter Action
138#[derive(Clone, Copy, Debug)]
139pub enum Action {
140 /// No Action
141 Disable = 0b000,
142 /// Store an matching message in FIFO 0
143 StoreInFifo0 = 0b001,
144 /// Store an matching message in FIFO 1
145 StoreInFifo1 = 0b010,
146 /// Reject an matching message
147 Reject = 0b011,
148 /// Flag a matching message (But not store?!?)
149 FlagHighPrio = 0b100,
150 /// Flag a matching message as a High Priority message and store it in FIFO 0
151 FlagHighPrioAndStoreInFifo0 = 0b101,
152 /// Flag a matching message as a High Priority message and store it in FIFO 1
153 FlagHighPrioAndStoreInFifo1 = 0b110,
154}
155impl From<Action> for message_ram::enums::FilterElementConfig {
156 fn from(a: Action) -> Self {
157 match a {
158 Action::Disable => Self::DisableFilterElement,
159 Action::StoreInFifo0 => Self::StoreInFifo0,
160 Action::StoreInFifo1 => Self::StoreInFifo1,
161 Action::Reject => Self::Reject,
162 Action::FlagHighPrio => Self::SetPriority,
163 Action::FlagHighPrioAndStoreInFifo0 => Self::SetPriorityAndStoreInFifo0,
164 Action::FlagHighPrioAndStoreInFifo1 => Self::SetPriorityAndStoreInFifo1,
165 }
166 }
167}
168
169/// Filter
170#[derive(Clone, Copy, Debug)]
171pub struct Filter<ID, UNIT>
172where
173 ID: Copy + Clone + core::fmt::Debug,
174 UNIT: Copy + Clone + core::fmt::Debug,
175{
176 /// How to match an incoming message
177 pub filter: FilterType<ID, UNIT>,
178 /// What to do with a matching message
179 pub action: Action,
180}
181
182/// Standard Filter Slot
183#[derive(Debug, Copy, Clone, Eq, PartialEq)]
184pub enum StandardFilterSlot {
185 /// 0
186 _0 = 0,
187 /// 1
188 _1 = 1,
189 /// 2
190 _2 = 2,
191 /// 3
192 _3 = 3,
193 /// 4
194 _4 = 4,
195 /// 5
196 _5 = 5,
197 /// 6
198 _6 = 6,
199 /// 7
200 _7 = 7,
201 /// 8
202 _8 = 8,
203 /// 9
204 _9 = 9,
205 /// 10
206 _10 = 10,
207 /// 11
208 _11 = 11,
209 /// 12
210 _12 = 12,
211 /// 13
212 _13 = 13,
213 /// 14
214 _14 = 14,
215 /// 15
216 _15 = 15,
217 /// 16
218 _16 = 16,
219 /// 17
220 _17 = 17,
221 /// 18
222 _18 = 18,
223 /// 19
224 _19 = 19,
225 /// 20
226 _20 = 20,
227 /// 21
228 _21 = 21,
229 /// 22
230 _22 = 22,
231 /// 23
232 _23 = 23,
233 /// 24
234 _24 = 24,
235 /// 25
236 _25 = 25,
237 /// 26
238 _26 = 26,
239 /// 27
240 _27 = 27,
241}
242impl From<u8> for StandardFilterSlot {
243 fn from(u: u8) -> Self {
244 match u {
245 0 => StandardFilterSlot::_0,
246 1 => StandardFilterSlot::_1,
247 2 => StandardFilterSlot::_2,
248 3 => StandardFilterSlot::_3,
249 4 => StandardFilterSlot::_4,
250 5 => StandardFilterSlot::_5,
251 6 => StandardFilterSlot::_6,
252 7 => StandardFilterSlot::_7,
253 8 => StandardFilterSlot::_8,
254 9 => StandardFilterSlot::_9,
255 10 => StandardFilterSlot::_10,
256 11 => StandardFilterSlot::_11,
257 12 => StandardFilterSlot::_12,
258 13 => StandardFilterSlot::_13,
259 14 => StandardFilterSlot::_14,
260 15 => StandardFilterSlot::_15,
261 16 => StandardFilterSlot::_16,
262 17 => StandardFilterSlot::_17,
263 18 => StandardFilterSlot::_18,
264 19 => StandardFilterSlot::_19,
265 20 => StandardFilterSlot::_20,
266 21 => StandardFilterSlot::_21,
267 22 => StandardFilterSlot::_22,
268 23 => StandardFilterSlot::_23,
269 24 => StandardFilterSlot::_24,
270 25 => StandardFilterSlot::_25,
271 26 => StandardFilterSlot::_26,
272 27 => StandardFilterSlot::_27,
273 _ => panic!("Standard Filter Slot Too High!"),
274 }
275 }
276}
277
278/// Extended Filter Slot
279#[derive(Debug, Copy, Clone, Eq, PartialEq)]
280pub enum ExtendedFilterSlot {
281 /// 0
282 _0 = 0,
283 /// 1
284 _1 = 1,
285 /// 2
286 _2 = 2,
287 /// 3
288 _3 = 3,
289 /// 4
290 _4 = 4,
291 /// 5
292 _5 = 5,
293 /// 6
294 _6 = 6,
295 /// 7
296 _7 = 7,
297}
298impl From<u8> for ExtendedFilterSlot {
299 fn from(u: u8) -> Self {
300 match u {
301 0 => ExtendedFilterSlot::_0,
302 1 => ExtendedFilterSlot::_1,
303 2 => ExtendedFilterSlot::_2,
304 3 => ExtendedFilterSlot::_3,
305 4 => ExtendedFilterSlot::_4,
306 5 => ExtendedFilterSlot::_5,
307 6 => ExtendedFilterSlot::_6,
308 7 => ExtendedFilterSlot::_7,
309 _ => panic!("Extended Filter Slot Too High!"), // Should be unreachable
310 }
311 }
312}
313
314/// Enum over both Standard and Extended Filter ID's
315#[derive(Debug, Copy, Clone, Eq, PartialEq)]
316pub enum FilterId {
317 /// Standard Filter Slots
318 Standard(StandardFilterSlot),
319 /// Extended Filter Slots
320 Extended(ExtendedFilterSlot),
321}
322
323pub(crate) trait ActivateFilter<ID, UNIT>
324where
325 ID: Copy + Clone + core::fmt::Debug,
326 UNIT: Copy + Clone + core::fmt::Debug,
327{
328 fn activate(&mut self, f: Filter<ID, UNIT>);
329 // fn read(&self) -> Filter<ID, UNIT>;
330}
331
332impl ActivateFilter<StandardId, u16> for message_ram::StandardFilter {
333 fn activate(&mut self, f: Filter<StandardId, u16>) {
334 let sft = f.filter.into();
335
336 let (sfid1, sfid2) = match f.filter {
337 FilterType::Range { to, from } => (to.as_raw(), from.as_raw()),
338 FilterType::DedicatedSingle(id) => (id.as_raw(), id.as_raw()),
339 FilterType::DedicatedDual(id1, id2) => (id1.as_raw(), id2.as_raw()),
340 FilterType::BitMask { filter, mask } => (filter, mask),
341 FilterType::Disabled => (0x0, 0x0),
342 };
343 let sfec = f.action.into();
344 self.write(|w| {
345 unsafe { w.sfid1().bits(sfid1).sfid2().bits(sfid2) }
346 .sft()
347 .set_filter_type(sft)
348 .sfec()
349 .set_filter_element_config(sfec)
350 });
351 }
352 // fn read(&self) -> Filter<StandardId, u16> {
353 // todo!()
354 // }
355}
356impl ActivateFilter<ExtendedId, u32> for message_ram::ExtendedFilter {
357 fn activate(&mut self, f: Filter<ExtendedId, u32>) {
358 let eft = f.filter.into();
359
360 let (efid1, efid2) = match f.filter {
361 FilterType::Range { to, from } => (to.as_raw(), from.as_raw()),
362 FilterType::DedicatedSingle(id) => (id.as_raw(), id.as_raw()),
363 FilterType::DedicatedDual(id1, id2) => (id1.as_raw(), id2.as_raw()),
364 FilterType::BitMask { filter, mask } => (filter, mask),
365 FilterType::Disabled => (0x0, 0x0),
366 };
367 let efec = f.action.into();
368 self.write(|w| {
369 unsafe { w.efid1().bits(efid1).efid2().bits(efid2) }
370 .eft()
371 .set_filter_type(eft)
372 .efec()
373 .set_filter_element_config(efec)
374 });
375 }
376 // fn read(&self) -> Filter<ExtendedId, u32> {
377 // todo!()
378 // }
379}
diff --git a/embassy-stm32/src/can/fd/message_ram/common.rs b/embassy-stm32/src/can/fd/message_ram/common.rs
new file mode 100644
index 000000000..108c1a428
--- /dev/null
+++ b/embassy-stm32/src/can/fd/message_ram/common.rs
@@ -0,0 +1,134 @@
1// Note: This file is copied and modified from fdcan crate by Richard Meadows
2#![allow(non_camel_case_types)]
3#![allow(non_snake_case)]
4#![allow(unused)]
5
6use super::enums::{
7 BitRateSwitching, ErrorStateIndicator, FilterElementConfig, FilterType, FrameFormat, IdType,
8 RemoteTransmissionRequest,
9};
10use super::generic;
11
12#[doc = "Reader of field `ID`"]
13pub type ID_R = generic::R<u32, u32>;
14
15#[doc = "Reader of field `RTR`"]
16pub type RTR_R = generic::R<bool, RemoteTransmissionRequest>;
17impl RTR_R {
18 pub fn rtr(&self) -> RemoteTransmissionRequest {
19 match self.bits {
20 false => RemoteTransmissionRequest::TransmitDataFrame,
21 true => RemoteTransmissionRequest::TransmitRemoteFrame,
22 }
23 }
24 pub fn is_transmit_remote_frame(&self) -> bool {
25 *self == RemoteTransmissionRequest::TransmitRemoteFrame
26 }
27 pub fn is_transmit_data_frame(&self) -> bool {
28 *self == RemoteTransmissionRequest::TransmitDataFrame
29 }
30}
31
32#[doc = "Reader of field `XTD`"]
33pub type XTD_R = generic::R<bool, IdType>;
34impl XTD_R {
35 pub fn id_type(&self) -> IdType {
36 match self.bits() {
37 false => IdType::StandardId,
38 true => IdType::ExtendedId,
39 }
40 }
41 pub fn is_standard_id(&self) -> bool {
42 *self == IdType::StandardId
43 }
44 pub fn is_exteded_id(&self) -> bool {
45 *self == IdType::ExtendedId
46 }
47}
48
49#[doc = "Reader of field `ESI`"]
50pub type ESI_R = generic::R<bool, ErrorStateIndicator>;
51impl ESI_R {
52 pub fn error_state(&self) -> ErrorStateIndicator {
53 match self.bits() {
54 false => ErrorStateIndicator::ErrorActive,
55 true => ErrorStateIndicator::ErrorPassive,
56 }
57 }
58 pub fn is_error_active(&self) -> bool {
59 *self == ErrorStateIndicator::ErrorActive
60 }
61 pub fn is_error_passive(&self) -> bool {
62 *self == ErrorStateIndicator::ErrorPassive
63 }
64}
65
66#[doc = "Reader of field `DLC`"]
67pub type DLC_R = generic::R<u8, u8>;
68
69#[doc = "Reader of field `BRS`"]
70pub type BRS_R = generic::R<bool, BitRateSwitching>;
71impl BRS_R {
72 pub fn bit_rate_switching(&self) -> BitRateSwitching {
73 match self.bits() {
74 true => BitRateSwitching::WithBRS,
75 false => BitRateSwitching::WithoutBRS,
76 }
77 }
78 pub fn is_with_brs(&self) -> bool {
79 *self == BitRateSwitching::WithBRS
80 }
81 pub fn is_without_brs(&self) -> bool {
82 *self == BitRateSwitching::WithoutBRS
83 }
84}
85
86#[doc = "Reader of field `FDF`"]
87pub type FDF_R = generic::R<bool, FrameFormat>;
88impl FDF_R {
89 pub fn frame_format(&self) -> FrameFormat {
90 match self.bits() {
91 false => FrameFormat::Classic,
92 true => FrameFormat::Fdcan,
93 }
94 }
95 pub fn is_classic_format(&self) -> bool {
96 *self == FrameFormat::Classic
97 }
98 pub fn is_fdcan_format(&self) -> bool {
99 *self == FrameFormat::Fdcan
100 }
101}
102
103#[doc = "Reader of field `(X|S)FT`"]
104pub type ESFT_R = generic::R<u8, FilterType>;
105impl ESFT_R {
106 #[doc = r"Gets the Filtertype"]
107 #[inline(always)]
108 pub fn to_filter_type(&self) -> FilterType {
109 match self.bits() {
110 0b00 => FilterType::RangeFilter,
111 0b01 => FilterType::DualIdFilter,
112 0b10 => FilterType::ClassicFilter,
113 0b11 => FilterType::FilterDisabled,
114 _ => unreachable!(),
115 }
116 }
117}
118
119#[doc = "Reader of field `(E|S)FEC`"]
120pub type ESFEC_R = generic::R<u8, FilterElementConfig>;
121impl ESFEC_R {
122 pub fn to_filter_element_config(&self) -> FilterElementConfig {
123 match self.bits() {
124 0b000 => FilterElementConfig::DisableFilterElement,
125 0b001 => FilterElementConfig::StoreInFifo0,
126 0b010 => FilterElementConfig::StoreInFifo1,
127 0b011 => FilterElementConfig::Reject,
128 0b100 => FilterElementConfig::SetPriority,
129 0b101 => FilterElementConfig::SetPriorityAndStoreInFifo0,
130 0b110 => FilterElementConfig::SetPriorityAndStoreInFifo1,
131 _ => unimplemented!(),
132 }
133 }
134}
diff --git a/embassy-stm32/src/can/fd/message_ram/enums.rs b/embassy-stm32/src/can/fd/message_ram/enums.rs
new file mode 100644
index 000000000..0ec5e0f34
--- /dev/null
+++ b/embassy-stm32/src/can/fd/message_ram/enums.rs
@@ -0,0 +1,233 @@
1// Note: This file is copied and modified from fdcan crate by Richard Meadows
2
3/// Datalength is the message length generalised over
4/// the Standard (Classic) and FDCAN message types
5
6#[derive(Clone, Copy, Debug, PartialEq)]
7pub enum DataLength {
8 Classic(u8),
9 Fdcan(u8),
10}
11impl DataLength {
12 /// Creates a DataLength type
13 ///
14 /// Uses the byte length and Type of frame as input
15 pub fn new(len: u8, ff: FrameFormat) -> DataLength {
16 match ff {
17 FrameFormat::Classic => match len {
18 0..=8 => DataLength::Classic(len),
19 _ => panic!("DataLength > 8"),
20 },
21 FrameFormat::Fdcan => match len {
22 0..=64 => DataLength::Fdcan(len),
23 _ => panic!("DataLength > 64"),
24 },
25 }
26 }
27 /// Specialised function to create classic frames
28 pub fn new_classic(len: u8) -> DataLength {
29 Self::new(len, FrameFormat::Classic)
30 }
31 /// Specialised function to create FDCAN frames
32 pub fn new_fdcan(len: u8) -> DataLength {
33 Self::new(len, FrameFormat::Fdcan)
34 }
35
36 /// returns the length in bytes
37 pub fn len(&self) -> u8 {
38 match self {
39 DataLength::Classic(l) | DataLength::Fdcan(l) => *l,
40 }
41 }
42
43 pub(crate) fn dlc(&self) -> u8 {
44 match self {
45 DataLength::Classic(l) => *l,
46 // See RM0433 Rev 7 Table 475. DLC coding
47 DataLength::Fdcan(l) => match l {
48 0..=8 => *l,
49 9..=12 => 9,
50 13..=16 => 10,
51 17..=20 => 11,
52 21..=24 => 12,
53 25..=32 => 13,
54 33..=48 => 14,
55 49..=64 => 15,
56 _ => panic!("DataLength > 64"),
57 },
58 }
59 }
60}
61impl From<DataLength> for FrameFormat {
62 fn from(dl: DataLength) -> FrameFormat {
63 match dl {
64 DataLength::Classic(_) => FrameFormat::Classic,
65 DataLength::Fdcan(_) => FrameFormat::Fdcan,
66 }
67 }
68}
69
70/// Wheter or not to generate an Tx Event
71#[derive(Clone, Copy, Debug, PartialEq)]
72pub enum Event {
73 /// Do not generate an Tx Event
74 NoEvent,
75 /// Generate an Tx Event with a specified ID
76 Event(u8),
77}
78
79impl From<Event> for EventControl {
80 fn from(e: Event) -> Self {
81 match e {
82 Event::NoEvent => EventControl::DoNotStore,
83 Event::Event(_) => EventControl::Store,
84 }
85 }
86}
87
88impl From<Option<u8>> for Event {
89 fn from(mm: Option<u8>) -> Self {
90 match mm {
91 None => Event::NoEvent,
92 Some(mm) => Event::Event(mm),
93 }
94 }
95}
96
97impl From<Event> for Option<u8> {
98 fn from(e: Event) -> Option<u8> {
99 match e {
100 Event::NoEvent => None,
101 Event::Event(mm) => Some(mm),
102 }
103 }
104}
105
106/// TODO
107#[derive(Clone, Copy, Debug, PartialEq)]
108pub enum ErrorStateIndicator {
109 /// TODO
110 ErrorActive = 0,
111 /// TODO
112 ErrorPassive = 1,
113}
114impl From<ErrorStateIndicator> for bool {
115 #[inline(always)]
116 fn from(e: ErrorStateIndicator) -> Self {
117 e as u8 != 0
118 }
119}
120
121/// Type of frame, standard (classic) or FdCAN
122#[derive(Clone, Copy, Debug, PartialEq)]
123pub enum FrameFormat {
124 Classic = 0,
125 Fdcan = 1,
126}
127impl From<FrameFormat> for bool {
128 #[inline(always)]
129 fn from(e: FrameFormat) -> Self {
130 e as u8 != 0
131 }
132}
133
134/// Type of Id, Standard or Extended
135#[derive(Clone, Copy, Debug, PartialEq)]
136pub enum IdType {
137 /// Standard ID
138 StandardId = 0,
139 /// Extended ID
140 ExtendedId = 1,
141}
142impl From<IdType> for bool {
143 #[inline(always)]
144 fn from(e: IdType) -> Self {
145 e as u8 != 0
146 }
147}
148
149/// Whether the frame contains data or requests data
150#[derive(Clone, Copy, Debug, PartialEq)]
151pub enum RemoteTransmissionRequest {
152 /// Frame contains data
153 TransmitDataFrame = 0,
154 /// frame does not contain data
155 TransmitRemoteFrame = 1,
156}
157impl From<RemoteTransmissionRequest> for bool {
158 #[inline(always)]
159 fn from(e: RemoteTransmissionRequest) -> Self {
160 e as u8 != 0
161 }
162}
163
164/// Whether BitRateSwitching should be or was enabled
165#[derive(Clone, Copy, Debug, PartialEq)]
166pub enum BitRateSwitching {
167 /// disable bit rate switching
168 WithoutBRS = 0,
169 /// enable bit rate switching
170 WithBRS = 1,
171}
172impl From<BitRateSwitching> for bool {
173 #[inline(always)]
174 fn from(e: BitRateSwitching) -> Self {
175 e as u8 != 0
176 }
177}
178
179/// Whether to store transmit Events
180#[derive(Clone, Copy, Debug, PartialEq)]
181pub enum EventControl {
182 /// do not store an tx event
183 DoNotStore,
184 /// store transmit events
185 Store,
186}
187impl From<EventControl> for bool {
188 #[inline(always)]
189 fn from(e: EventControl) -> Self {
190 e as u8 != 0
191 }
192}
193
194/// If an received message matched any filters
195#[derive(Clone, Copy, Debug, PartialEq)]
196pub enum FilterFrameMatch {
197 /// This did match filter <id>
198 DidMatch(u8),
199 /// This received frame did not match any specific filters
200 DidNotMatch,
201}
202
203/// Type of filter to be used
204#[derive(Clone, Copy, Debug, PartialEq)]
205pub enum FilterType {
206 /// Filter uses the range between two id's
207 RangeFilter = 0b00,
208 /// The filter matches on two specific id's (or one ID checked twice)
209 DualIdFilter = 0b01,
210 /// Filter is using a bitmask
211 ClassicFilter = 0b10,
212 /// Filter is disabled
213 FilterDisabled = 0b11,
214}
215
216#[derive(Clone, Copy, Debug, PartialEq)]
217pub enum FilterElementConfig {
218 /// Filter is disabled
219 DisableFilterElement = 0b000,
220 /// Store a matching message in FIFO 0
221 StoreInFifo0 = 0b001,
222 /// Store a matching message in FIFO 1
223 StoreInFifo1 = 0b010,
224 /// Reject a matching message
225 Reject = 0b011,
226 /// Flag that a priority message has been received, *But do note store!*??
227 SetPriority = 0b100,
228 /// Flag and store message in FIFO 0
229 SetPriorityAndStoreInFifo0 = 0b101,
230 /// Flag and store message in FIFO 1
231 SetPriorityAndStoreInFifo1 = 0b110,
232 //_Unused = 0b111,
233}
diff --git a/embassy-stm32/src/can/fd/message_ram/extended_filter.rs b/embassy-stm32/src/can/fd/message_ram/extended_filter.rs
new file mode 100644
index 000000000..453e9056e
--- /dev/null
+++ b/embassy-stm32/src/can/fd/message_ram/extended_filter.rs
@@ -0,0 +1,136 @@
1// Note: This file is copied and modified from fdcan crate by Richard Meadows
2
3#![allow(non_camel_case_types)]
4#![allow(non_snake_case)]
5#![allow(unused)]
6
7use super::common::{ESFEC_R, ESFT_R};
8use super::enums::{FilterElementConfig, FilterType};
9use super::generic;
10
11#[doc = "Reader of register ExtendedFilter"]
12pub(crate) type R = generic::R<super::ExtendedFilterType, super::ExtendedFilter>;
13#[doc = "Writer for register ExtendedFilter"]
14pub(crate) type W = generic::W<super::ExtendedFilterType, super::ExtendedFilter>;
15#[doc = "Register ExtendedFilter `reset()`'s"]
16impl generic::ResetValue for super::ExtendedFilter {
17 type Type = super::ExtendedFilterType;
18 #[inline(always)]
19 fn reset_value() -> Self::Type {
20 // Sets filter element to Disabled
21 [0x0, 0x0]
22 }
23}
24
25#[doc = "Reader of field `EFID2`"]
26pub(crate) type EFID2_R = generic::R<u32, u32>;
27#[doc = "Write proxy for field `EFID2`"]
28pub(crate) struct EFID2_W<'a> {
29 w: &'a mut W,
30}
31impl<'a> EFID2_W<'a> {
32 #[doc = r"Writes raw bits to the field"]
33 #[inline(always)]
34 pub unsafe fn bits(self, value: u32) -> &'a mut W {
35 self.w.bits[1] = (self.w.bits[1] & !(0x1FFFFFFF)) | ((value as u32) & 0x1FFFFFFF);
36 self.w
37 }
38}
39
40#[doc = "Reader of field `EFID1`"]
41pub(crate) type EFID1_R = generic::R<u32, u32>;
42#[doc = "Write proxy for field `EFID1`"]
43pub(crate) struct EFID1_W<'a> {
44 w: &'a mut W,
45}
46impl<'a> EFID1_W<'a> {
47 #[doc = r"Writes raw bits to the field"]
48 #[inline(always)]
49 pub unsafe fn bits(self, value: u32) -> &'a mut W {
50 self.w.bits[0] = (self.w.bits[0] & !(0x1FFFFFFF)) | ((value as u32) & 0x1FFFFFFF);
51 self.w
52 }
53}
54
55#[doc = "Write proxy for field `EFEC`"]
56pub(crate) struct EFEC_W<'a> {
57 w: &'a mut W,
58}
59impl<'a> EFEC_W<'a> {
60 #[doc = r"Writes raw bits to the field"]
61 #[inline(always)]
62 pub unsafe fn bits(self, value: u8) -> &'a mut W {
63 self.w.bits[0] = (self.w.bits[0] & !(0x07 << 29)) | (((value as u32) & 0x07) << 29);
64 self.w
65 }
66 #[doc = r"Sets the field according to FilterElementConfig"]
67 #[inline(always)]
68 pub fn set_filter_element_config(self, fec: FilterElementConfig) -> &'a mut W {
69 //SAFETY: FilterElementConfig only be valid options
70 unsafe { self.bits(fec as u8) }
71 }
72}
73
74#[doc = "Write proxy for field `EFT`"]
75pub(crate) struct EFT_W<'a> {
76 w: &'a mut W,
77}
78impl<'a> EFT_W<'a> {
79 #[doc = r"Sets the field according the FilterType"]
80 #[inline(always)]
81 pub fn set_filter_type(self, filter: FilterType) -> &'a mut W {
82 //SAFETY: FilterType only be valid options
83 unsafe { self.bits(filter as u8) }
84 }
85 #[doc = r"Writes raw bits to the field"]
86 #[inline(always)]
87 pub unsafe fn bits(self, value: u8) -> &'a mut W {
88 self.w.bits[1] = (self.w.bits[1] & !(0x03 << 30)) | (((value as u32) & 0x03) << 30);
89 self.w
90 }
91}
92
93impl R {
94 #[doc = "Byte 0 - Bits 0:28 - EFID1"]
95 #[inline(always)]
96 pub fn sfid1(&self) -> EFID1_R {
97 EFID1_R::new(((self.bits[0]) & 0x1FFFFFFF) as u32)
98 }
99 #[doc = "Byte 0 - Bits 29:31 - EFEC"]
100 #[inline(always)]
101 pub fn efec(&self) -> ESFEC_R {
102 ESFEC_R::new(((self.bits[0] >> 29) & 0x07) as u8)
103 }
104 #[doc = "Byte 1 - Bits 0:28 - EFID2"]
105 #[inline(always)]
106 pub fn sfid2(&self) -> EFID2_R {
107 EFID2_R::new(((self.bits[1]) & 0x1FFFFFFF) as u32)
108 }
109 #[doc = "Byte 1 - Bits 30:31 - EFT"]
110 #[inline(always)]
111 pub fn eft(&self) -> ESFT_R {
112 ESFT_R::new(((self.bits[1] >> 30) & 0x03) as u8)
113 }
114}
115impl W {
116 #[doc = "Byte 0 - Bits 0:28 - EFID1"]
117 #[inline(always)]
118 pub fn efid1(&mut self) -> EFID1_W {
119 EFID1_W { w: self }
120 }
121 #[doc = "Byte 0 - Bits 29:31 - EFEC"]
122 #[inline(always)]
123 pub fn efec(&mut self) -> EFEC_W {
124 EFEC_W { w: self }
125 }
126 #[doc = "Byte 1 - Bits 0:28 - EFID2"]
127 #[inline(always)]
128 pub fn efid2(&mut self) -> EFID2_W {
129 EFID2_W { w: self }
130 }
131 #[doc = "Byte 1 - Bits 30:31 - EFT"]
132 #[inline(always)]
133 pub fn eft(&mut self) -> EFT_W {
134 EFT_W { w: self }
135 }
136}
diff --git a/embassy-stm32/src/can/fd/message_ram/generic.rs b/embassy-stm32/src/can/fd/message_ram/generic.rs
new file mode 100644
index 000000000..1a5e121b4
--- /dev/null
+++ b/embassy-stm32/src/can/fd/message_ram/generic.rs
@@ -0,0 +1,168 @@
1// Note: This file is copied and modified from fdcan crate by Richard Meadows
2
3use core::marker;
4
5///This trait shows that register has `read` method
6///
7///Registers marked with `Writable` can be also `modify`'ed
8pub trait Readable {}
9
10///This trait shows that register has `write`, `write_with_zero` and `reset` method
11///
12///Registers marked with `Readable` can be also `modify`'ed
13pub trait Writable {}
14
15///Reset value of the register
16///
17///This value is initial value for `write` method.
18///It can be also directly writed to register by `reset` method.
19pub trait ResetValue {
20 ///Register size
21 type Type;
22 ///Reset value of the register
23 fn reset_value() -> Self::Type;
24}
25
26///This structure provides volatile access to register
27pub struct Reg<U, REG> {
28 register: vcell::VolatileCell<U>,
29 _marker: marker::PhantomData<REG>,
30}
31
32unsafe impl<U: Send, REG> Send for Reg<U, REG> {}
33
34impl<U, REG> Reg<U, REG>
35where
36 Self: Readable,
37 U: Copy,
38{
39 ///Reads the contents of `Readable` register
40 ///
41 ///You can read the contents of a register in such way:
42 ///```ignore
43 ///let bits = periph.reg.read().bits();
44 ///```
45 ///or get the content of a particular field of a register.
46 ///```ignore
47 ///let reader = periph.reg.read();
48 ///let bits = reader.field1().bits();
49 ///let flag = reader.field2().bit_is_set();
50 ///```
51 #[inline(always)]
52 pub fn read(&self) -> R<U, Self> {
53 R {
54 bits: self.register.get(),
55 _reg: marker::PhantomData,
56 }
57 }
58}
59
60impl<U, REG> Reg<U, REG>
61where
62 Self: ResetValue<Type = U> + Writable,
63 U: Copy,
64{
65 ///Writes the reset value to `Writable` register
66 ///
67 ///Resets the register to its initial state
68 #[inline(always)]
69 pub fn reset(&self) {
70 self.register.set(Self::reset_value())
71 }
72}
73
74impl<U, REG> Reg<U, REG>
75where
76 Self: ResetValue<Type = U> + Writable,
77 U: Copy,
78{
79 ///Writes bits to `Writable` register
80 ///
81 ///You can write raw bits into a register:
82 ///```ignore
83 ///periph.reg.write(|w| unsafe { w.bits(rawbits) });
84 ///```
85 ///or write only the fields you need:
86 ///```ignore
87 ///periph.reg.write(|w| w
88 /// .field1().bits(newfield1bits)
89 /// .field2().set_bit()
90 /// .field3().variant(VARIANT)
91 ///);
92 ///```
93 ///Other fields will have reset value.
94 #[inline(always)]
95 pub fn write<F>(&self, f: F)
96 where
97 F: FnOnce(&mut W<U, Self>) -> &mut W<U, Self>,
98 {
99 self.register.set(
100 f(&mut W {
101 bits: Self::reset_value(),
102 _reg: marker::PhantomData,
103 })
104 .bits,
105 );
106 }
107}
108
109///Register/field reader
110///
111///Result of the [`read`](Reg::read) method of a register.
112///Also it can be used in the [`modify`](Reg::read) method
113pub struct R<U, T> {
114 pub(crate) bits: U,
115 _reg: marker::PhantomData<T>,
116}
117
118impl<U, T> R<U, T>
119where
120 U: Copy,
121{
122 ///Create new instance of reader
123 #[inline(always)]
124 pub(crate) fn new(bits: U) -> Self {
125 Self {
126 bits,
127 _reg: marker::PhantomData,
128 }
129 }
130 ///Read raw bits from register/field
131 #[inline(always)]
132 pub fn bits(&self) -> U {
133 self.bits
134 }
135}
136
137impl<U, T, FI> PartialEq<FI> for R<U, T>
138where
139 U: PartialEq,
140 FI: Copy + Into<U>,
141{
142 #[inline(always)]
143 fn eq(&self, other: &FI) -> bool {
144 self.bits.eq(&(*other).into())
145 }
146}
147
148impl<FI> R<bool, FI> {
149 ///Value of the field as raw bits
150 #[inline(always)]
151 pub fn bit(&self) -> bool {
152 self.bits
153 }
154 ///Returns `true` if the bit is clear (0)
155 #[inline(always)]
156 pub fn bit_is_clear(&self) -> bool {
157 !self.bit()
158 }
159}
160
161///Register writer
162///
163///Used as an argument to the closures in the [`write`](Reg::write) and [`modify`](Reg::modify) methods of the register
164pub struct W<U, REG> {
165 ///Writable bits
166 pub(crate) bits: U,
167 _reg: marker::PhantomData<REG>,
168}
diff --git a/embassy-stm32/src/can/fd/message_ram/mod.rs b/embassy-stm32/src/can/fd/message_ram/mod.rs
new file mode 100644
index 000000000..830edf3bb
--- /dev/null
+++ b/embassy-stm32/src/can/fd/message_ram/mod.rs
@@ -0,0 +1,170 @@
1// Note: This file is copied and modified from fdcan crate by Richard Meadows
2
3use volatile_register::RW;
4
5pub(crate) mod common;
6pub(crate) mod enums;
7pub(crate) mod generic;
8
9/// Number of Receive Fifos configured by this module
10pub const RX_FIFOS_MAX: u8 = 2;
11/// Number of Receive Messages per RxFifo configured by this module
12pub const RX_FIFO_MAX: u8 = 3;
13/// Number of Transmit Messages configured by this module
14pub const TX_FIFO_MAX: u8 = 3;
15/// Number of Transmit Events configured by this module
16pub const TX_EVENT_MAX: u8 = 3;
17/// Number of Standard Filters configured by this module
18pub const STANDARD_FILTER_MAX: u8 = 28;
19/// Number of Extended Filters configured by this module
20pub const EXTENDED_FILTER_MAX: u8 = 8;
21
22/// MessageRam Overlay
23#[repr(C)]
24pub struct RegisterBlock {
25 pub(crate) filters: Filters,
26 pub(crate) receive: [Receive; RX_FIFOS_MAX as usize],
27 pub(crate) transmit: Transmit,
28}
29impl RegisterBlock {
30 pub fn reset(&mut self) {
31 self.filters.reset();
32 self.receive[0].reset();
33 self.receive[1].reset();
34 self.transmit.reset();
35 }
36}
37
38#[repr(C)]
39pub(crate) struct Filters {
40 pub(crate) flssa: [StandardFilter; STANDARD_FILTER_MAX as usize],
41 pub(crate) flesa: [ExtendedFilter; EXTENDED_FILTER_MAX as usize],
42}
43impl Filters {
44 pub fn reset(&mut self) {
45 for sf in &mut self.flssa {
46 sf.reset();
47 }
48 for ef in &mut self.flesa {
49 ef.reset();
50 }
51 }
52}
53
54#[repr(C)]
55pub(crate) struct Receive {
56 pub(crate) fxsa: [RxFifoElement; RX_FIFO_MAX as usize],
57}
58impl Receive {
59 pub fn reset(&mut self) {
60 for fe in &mut self.fxsa {
61 fe.reset();
62 }
63 }
64}
65
66#[repr(C)]
67pub(crate) struct Transmit {
68 pub(crate) efsa: [TxEventElement; TX_EVENT_MAX as usize],
69 pub(crate) tbsa: [TxBufferElement; TX_FIFO_MAX as usize],
70}
71impl Transmit {
72 pub fn reset(&mut self) {
73 for ee in &mut self.efsa {
74 ee.reset();
75 }
76 for be in &mut self.tbsa {
77 be.reset();
78 }
79 }
80}
81
82pub(crate) mod standard_filter;
83pub(crate) type StandardFilterType = u32;
84pub(crate) type StandardFilter = generic::Reg<StandardFilterType, _StandardFilter>;
85pub(crate) struct _StandardFilter;
86impl generic::Readable for StandardFilter {}
87impl generic::Writable for StandardFilter {}
88
89pub(crate) mod extended_filter;
90pub(crate) type ExtendedFilterType = [u32; 2];
91pub(crate) type ExtendedFilter = generic::Reg<ExtendedFilterType, _ExtendedFilter>;
92pub(crate) struct _ExtendedFilter;
93impl generic::Readable for ExtendedFilter {}
94impl generic::Writable for ExtendedFilter {}
95
96pub(crate) mod txevent_element;
97pub(crate) type TxEventElementType = [u32; 2];
98pub(crate) type TxEventElement = generic::Reg<TxEventElementType, _TxEventElement>;
99pub(crate) struct _TxEventElement;
100impl generic::Readable for TxEventElement {}
101impl generic::Writable for TxEventElement {}
102
103pub(crate) mod rxfifo_element;
104#[repr(C)]
105pub(crate) struct RxFifoElement {
106 pub(crate) header: RxFifoElementHeader,
107 pub(crate) data: [RW<u32>; 16],
108}
109impl RxFifoElement {
110 pub(crate) fn reset(&mut self) {
111 self.header.reset();
112 for byte in self.data.iter_mut() {
113 unsafe { byte.write(0) };
114 }
115 }
116}
117pub(crate) type RxFifoElementHeaderType = [u32; 2];
118pub(crate) type RxFifoElementHeader = generic::Reg<RxFifoElementHeaderType, _RxFifoElement>;
119pub(crate) struct _RxFifoElement;
120impl generic::Readable for RxFifoElementHeader {}
121impl generic::Writable for RxFifoElementHeader {}
122
123pub(crate) mod txbuffer_element;
124#[repr(C)]
125pub(crate) struct TxBufferElement {
126 pub(crate) header: TxBufferElementHeader,
127 pub(crate) data: [RW<u32>; 16],
128}
129impl TxBufferElement {
130 pub(crate) fn reset(&mut self) {
131 self.header.reset();
132 for byte in self.data.iter_mut() {
133 unsafe { byte.write(0) };
134 }
135 }
136}
137pub(crate) type TxBufferElementHeader = generic::Reg<TxBufferElementHeaderType, _TxBufferElement>;
138pub(crate) type TxBufferElementHeaderType = [u32; 2];
139pub(crate) struct _TxBufferElement;
140impl generic::Readable for TxBufferElementHeader {}
141impl generic::Writable for TxBufferElementHeader {}
142
143/// FdCan Message RAM instance.
144///
145/// # Safety
146///
147/// It is only safe to implement this trait, when:
148///
149/// * The implementing type has ownership of the Message RAM, preventing any
150/// other accesses to the register block.
151/// * `MSG_RAM` is a pointer to the Message RAM block and can be safely accessed
152/// for as long as ownership or a borrow of the implementing type is present.
153pub unsafe trait Instance {
154 const MSG_RAM: *mut RegisterBlock;
155 fn msg_ram(&self) -> &RegisterBlock {
156 unsafe { &*Self::MSG_RAM }
157 }
158 fn msg_ram_mut(&mut self) -> &mut RegisterBlock {
159 unsafe { &mut *Self::MSG_RAM }
160 }
161}
162
163// Ensure the RegisterBlock is the same size as on pg 1957 of RM0440.
164static_assertions::assert_eq_size!(Filters, [u32; 28 + 16]);
165static_assertions::assert_eq_size!(Receive, [u32; 54]);
166static_assertions::assert_eq_size!(Transmit, [u32; 6 + 54]);
167static_assertions::assert_eq_size!(
168 RegisterBlock,
169 [u32; 28 /*Standard Filters*/ +16 /*Extended Filters*/ +54 /*RxFifo0*/ +54 /*RxFifo1*/ +6 /*TxEvent*/ +54 /*TxFifo */]
170);
diff --git a/embassy-stm32/src/can/fd/message_ram/rxfifo_element.rs b/embassy-stm32/src/can/fd/message_ram/rxfifo_element.rs
new file mode 100644
index 000000000..48fc3a091
--- /dev/null
+++ b/embassy-stm32/src/can/fd/message_ram/rxfifo_element.rs
@@ -0,0 +1,122 @@
1// Note: This file is copied and modified from fdcan crate by Richard Meadows
2
3#![allow(non_camel_case_types)]
4#![allow(non_snake_case)]
5#![allow(unused)]
6
7use super::common::{BRS_R, DLC_R, ESI_R, FDF_R, ID_R, RTR_R, XTD_R};
8use super::enums::{DataLength, FilterFrameMatch, FrameFormat};
9use super::generic;
10
11#[doc = "Reader of register RxFifoElement"]
12pub(crate) type R = generic::R<super::RxFifoElementHeaderType, super::RxFifoElementHeader>;
13// #[doc = "Writer for register ExtendedFilter"]
14// pub(crate) type W = generic::W<super::RxFifoElementHeaderType, super::RxFifoElementHeader>;
15#[doc = "Register ExtendedFilter `reset()`'s"]
16impl generic::ResetValue for super::RxFifoElementHeader {
17 type Type = super::RxFifoElementHeaderType;
18 #[inline(always)]
19 fn reset_value() -> Self::Type {
20 [0x0, 0x0]
21 }
22}
23
24#[doc = "Reader of field `RXTS`"]
25pub(crate) type RXTS_R = generic::R<u16, u16>;
26
27#[doc = "Reader of field `FIDX`"]
28pub(crate) type FIDX_R = generic::R<u8, u8>;
29
30pub(crate) struct _ANMF;
31#[doc = "Reader of field `ANMF`"]
32pub(crate) type ANMF_R = generic::R<bool, _ANMF>;
33impl ANMF_R {
34 pub fn is_matching_frame(&self) -> bool {
35 self.bit_is_clear()
36 }
37}
38
39impl R {
40 #[doc = "Byte 0 - Bits 0:28 - ID"]
41 #[inline(always)]
42 pub fn id(&self) -> ID_R {
43 ID_R::new(((self.bits[0]) & 0x1FFFFFFF) as u32)
44 }
45 #[doc = "Byte 0 - Bit 29 - RTR"]
46 #[inline(always)]
47 pub fn rtr(&self) -> RTR_R {
48 RTR_R::new(((self.bits[0] >> 29) & 0x01) != 0)
49 }
50 #[doc = "Byte 0 - Bit 30 - XTD"]
51 #[inline(always)]
52 pub fn xtd(&self) -> XTD_R {
53 XTD_R::new(((self.bits[0] >> 30) & 0x01) != 0)
54 }
55 #[doc = "Byte 0 - Bit 30 - ESI"]
56 #[inline(always)]
57 pub fn esi(&self) -> ESI_R {
58 ESI_R::new(((self.bits[0] >> 31) & 0x01) != 0)
59 }
60 #[doc = "Byte 1 - Bits 0:15 - RXTS"]
61 #[inline(always)]
62 pub fn txts(&self) -> RXTS_R {
63 RXTS_R::new(((self.bits[1]) & 0xFFFF) as u16)
64 }
65 #[doc = "Byte 1 - Bits 16:19 - DLC"]
66 #[inline(always)]
67 pub fn dlc(&self) -> DLC_R {
68 DLC_R::new(((self.bits[1] >> 16) & 0x0F) as u8)
69 }
70 #[doc = "Byte 1 - Bits 20 - BRS"]
71 #[inline(always)]
72 pub fn brs(&self) -> BRS_R {
73 BRS_R::new(((self.bits[1] >> 20) & 0x01) != 0)
74 }
75 #[doc = "Byte 1 - Bits 20 - FDF"]
76 #[inline(always)]
77 pub fn fdf(&self) -> FDF_R {
78 FDF_R::new(((self.bits[1] >> 21) & 0x01) != 0)
79 }
80 #[doc = "Byte 1 - Bits 24:30 - FIDX"]
81 #[inline(always)]
82 pub fn fidx(&self) -> FIDX_R {
83 FIDX_R::new(((self.bits[1] >> 24) & 0xFF) as u8)
84 }
85 #[doc = "Byte 1 - Bits 31 - ANMF"]
86 #[inline(always)]
87 pub fn anmf(&self) -> ANMF_R {
88 ANMF_R::new(((self.bits[1] >> 31) & 0x01) != 0)
89 }
90 pub fn to_data_length(&self) -> DataLength {
91 let dlc = self.dlc().bits();
92 let ff = self.fdf().frame_format();
93 let len = if ff == FrameFormat::Fdcan {
94 // See RM0433 Rev 7 Table 475. DLC coding
95 match dlc {
96 0..=8 => dlc,
97 9 => 12,
98 10 => 16,
99 11 => 20,
100 12 => 24,
101 13 => 32,
102 14 => 48,
103 15 => 64,
104 _ => panic!("DLC > 15"),
105 }
106 } else {
107 match dlc {
108 0..=8 => dlc,
109 9..=15 => 8,
110 _ => panic!("DLC > 15"),
111 }
112 };
113 DataLength::new(len, ff)
114 }
115 pub fn to_filter_match(&self) -> FilterFrameMatch {
116 if self.anmf().is_matching_frame() {
117 FilterFrameMatch::DidMatch(self.fidx().bits())
118 } else {
119 FilterFrameMatch::DidNotMatch
120 }
121 }
122}
diff --git a/embassy-stm32/src/can/fd/message_ram/standard_filter.rs b/embassy-stm32/src/can/fd/message_ram/standard_filter.rs
new file mode 100644
index 000000000..3a3bbcf12
--- /dev/null
+++ b/embassy-stm32/src/can/fd/message_ram/standard_filter.rs
@@ -0,0 +1,136 @@
1// Note: This file is copied and modified from fdcan crate by Richard Meadows
2
3#![allow(non_camel_case_types)]
4#![allow(non_snake_case)]
5#![allow(unused)]
6
7use super::common::{ESFEC_R, ESFT_R};
8use super::enums::{FilterElementConfig, FilterType};
9use super::generic;
10
11#[doc = "Reader of register StandardFilter"]
12pub(crate) type R = generic::R<super::StandardFilterType, super::StandardFilter>;
13#[doc = "Writer for register StandardFilter"]
14pub(crate) type W = generic::W<super::StandardFilterType, super::StandardFilter>;
15#[doc = "Register StandardFilter `reset()`'s with value 0xC0000"]
16impl generic::ResetValue for super::StandardFilter {
17 type Type = super::StandardFilterType;
18 #[inline(always)]
19 fn reset_value() -> Self::Type {
20 // Sets filter element to Disabled
21 0xC000
22 }
23}
24
25#[doc = "Reader of field `SFID2`"]
26pub(crate) type SFID2_R = generic::R<u16, u16>;
27#[doc = "Write proxy for field `SFID2`"]
28pub(crate) struct SFID2_W<'a> {
29 w: &'a mut W,
30}
31impl<'a> SFID2_W<'a> {
32 #[doc = r"Writes raw bits to the field"]
33 #[inline(always)]
34 pub unsafe fn bits(self, value: u16) -> &'a mut W {
35 self.w.bits = (self.w.bits & !(0x07ff)) | ((value as u32) & 0x07ff);
36 self.w
37 }
38}
39
40#[doc = "Reader of field `SFID1`"]
41pub(crate) type SFID1_R = generic::R<u16, u16>;
42#[doc = "Write proxy for field `SFID1`"]
43pub(crate) struct SFID1_W<'a> {
44 w: &'a mut W,
45}
46impl<'a> SFID1_W<'a> {
47 #[doc = r"Writes raw bits to the field"]
48 #[inline(always)]
49 pub unsafe fn bits(self, value: u16) -> &'a mut W {
50 self.w.bits = (self.w.bits & !(0x07ff << 16)) | (((value as u32) & 0x07ff) << 16);
51 self.w
52 }
53}
54
55#[doc = "Write proxy for field `SFEC`"]
56pub(crate) struct SFEC_W<'a> {
57 w: &'a mut W,
58}
59impl<'a> SFEC_W<'a> {
60 #[doc = r"Writes raw bits to the field"]
61 #[inline(always)]
62 pub unsafe fn bits(self, value: u8) -> &'a mut W {
63 self.w.bits = (self.w.bits & !(0x07 << 27)) | (((value as u32) & 0x07) << 27);
64 self.w
65 }
66 #[doc = r"Sets the field according to FilterElementConfig"]
67 #[inline(always)]
68 pub fn set_filter_element_config(self, fec: FilterElementConfig) -> &'a mut W {
69 //SAFETY: FilterElementConfig only be valid options
70 unsafe { self.bits(fec as u8) }
71 }
72}
73
74#[doc = "Write proxy for field `SFT`"]
75pub(crate) struct SFT_W<'a> {
76 w: &'a mut W,
77}
78impl<'a> SFT_W<'a> {
79 #[doc = r"Sets the field according the FilterType"]
80 #[inline(always)]
81 pub fn set_filter_type(self, filter: FilterType) -> &'a mut W {
82 //SAFETY: FilterType only be valid options
83 unsafe { self.bits(filter as u8) }
84 }
85 #[doc = r"Writes raw bits to the field"]
86 #[inline(always)]
87 pub unsafe fn bits(self, value: u8) -> &'a mut W {
88 self.w.bits = (self.w.bits & !(0x03 << 30)) | (((value as u32) & 0x03) << 30);
89 self.w
90 }
91}
92
93impl R {
94 #[doc = "Bits 0:10 - SFID2"]
95 #[inline(always)]
96 pub fn sfid2(&self) -> SFID2_R {
97 SFID2_R::new((self.bits & 0x07ff) as u16)
98 }
99 #[doc = "Bits 16:26 - SFID1"]
100 #[inline(always)]
101 pub fn sfid1(&self) -> SFID1_R {
102 SFID1_R::new(((self.bits >> 16) & 0x07ff) as u16)
103 }
104 #[doc = "Bits 27:29 - SFEC"]
105 #[inline(always)]
106 pub fn sfec(&self) -> ESFEC_R {
107 ESFEC_R::new(((self.bits >> 27) & 0x07) as u8)
108 }
109 #[doc = "Bits 30:31 - SFT"]
110 #[inline(always)]
111 pub fn sft(&self) -> ESFT_R {
112 ESFT_R::new(((self.bits >> 30) & 0x03) as u8)
113 }
114}
115impl W {
116 #[doc = "Bits 0:10 - SFID2"]
117 #[inline(always)]
118 pub fn sfid2(&mut self) -> SFID2_W {
119 SFID2_W { w: self }
120 }
121 #[doc = "Bits 16:26 - SFID1"]
122 #[inline(always)]
123 pub fn sfid1(&mut self) -> SFID1_W {
124 SFID1_W { w: self }
125 }
126 #[doc = "Bits 27:29 - SFEC"]
127 #[inline(always)]
128 pub fn sfec(&mut self) -> SFEC_W {
129 SFEC_W { w: self }
130 }
131 #[doc = "Bits 30:31 - SFT"]
132 #[inline(always)]
133 pub fn sft(&mut self) -> SFT_W {
134 SFT_W { w: self }
135 }
136}
diff --git a/embassy-stm32/src/can/fd/message_ram/txbuffer_element.rs b/embassy-stm32/src/can/fd/message_ram/txbuffer_element.rs
new file mode 100644
index 000000000..455406a1c
--- /dev/null
+++ b/embassy-stm32/src/can/fd/message_ram/txbuffer_element.rs
@@ -0,0 +1,433 @@
1// Note: This file is copied and modified from fdcan crate by Richard Meadows
2
3#![allow(non_camel_case_types)]
4#![allow(non_snake_case)]
5#![allow(unused)]
6
7use super::common::{BRS_R, DLC_R, ESI_R, FDF_R, ID_R, RTR_R, XTD_R};
8use super::enums::{
9 BitRateSwitching, DataLength, ErrorStateIndicator, Event, EventControl, FrameFormat, IdType,
10 RemoteTransmissionRequest,
11};
12use super::generic;
13
14#[doc = "Reader of register TxBufferElement"]
15pub(crate) type R = generic::R<super::TxBufferElementHeaderType, super::TxBufferElementHeader>;
16#[doc = "Writer for register TxBufferElement"]
17pub(crate) type W = generic::W<super::TxBufferElementHeaderType, super::TxBufferElementHeader>;
18impl generic::ResetValue for super::TxBufferElementHeader {
19 type Type = super::TxBufferElementHeaderType;
20
21 #[allow(dead_code)]
22 #[inline(always)]
23 fn reset_value() -> Self::Type {
24 [0; 2]
25 }
26}
27
28#[doc = "Write proxy for field `ESI`"]
29pub(crate) struct ESI_W<'a> {
30 w: &'a mut W,
31}
32impl<'a> ESI_W<'a> {
33 #[doc = r"Writes `variant` to the field"]
34 #[inline(always)]
35 #[allow(dead_code)]
36 pub fn set_error_indicator(self, esi: ErrorStateIndicator) -> &'a mut W {
37 self.bit(esi as u8 != 0)
38 }
39
40 #[doc = r"Sets the field bit"]
41 #[inline(always)]
42 #[allow(dead_code)]
43 pub fn set_bit(self) -> &'a mut W {
44 self.bit(true)
45 }
46 #[doc = r"Clears the field bit"]
47 #[inline(always)]
48 #[allow(dead_code)]
49 pub fn clear_bit(self) -> &'a mut W {
50 self.bit(false)
51 }
52 #[doc = r"Writes raw bits to the field"]
53 #[inline(always)]
54 #[allow(dead_code)]
55 pub fn bit(self, value: bool) -> &'a mut W {
56 self.w.bits[0] = (self.w.bits[0] & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
57 self.w
58 }
59}
60
61#[doc = "Write proxy for field `XTD`"]
62pub(crate) struct XTD_W<'a> {
63 w: &'a mut W,
64}
65impl<'a> XTD_W<'a> {
66 #[doc = r"Writes `variant` to the field"]
67 #[inline(always)]
68 #[allow(dead_code)]
69 pub fn set_id_type(self, idt: IdType) -> &'a mut W {
70 self.bit(idt as u8 != 0)
71 }
72
73 #[doc = r"Sets the field bit"]
74 #[inline(always)]
75 #[allow(dead_code)]
76 pub fn set_bit(self) -> &'a mut W {
77 self.bit(true)
78 }
79 #[doc = r"Clears the field bit"]
80 #[inline(always)]
81 #[allow(dead_code)]
82 pub fn clear_bit(self) -> &'a mut W {
83 self.bit(false)
84 }
85 #[doc = r"Writes raw bits to the field"]
86 #[inline(always)]
87 #[allow(dead_code)]
88 pub fn bit(self, value: bool) -> &'a mut W {
89 self.w.bits[0] = (self.w.bits[0] & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
90 self.w
91 }
92}
93
94#[doc = "Write proxy for field `RTR`"]
95pub(crate) struct RTR_W<'a> {
96 w: &'a mut W,
97}
98impl<'a> RTR_W<'a> {
99 #[doc = r"Writes `variant` to the field"]
100 #[inline(always)]
101 #[allow(dead_code)]
102 pub fn set_rtr(self, rtr: RemoteTransmissionRequest) -> &'a mut W {
103 self.bit(rtr as u8 != 0)
104 }
105
106 #[doc = r"Sets the field bit"]
107 #[inline(always)]
108 #[allow(dead_code)]
109 pub fn set_bit(self) -> &'a mut W {
110 self.bit(true)
111 }
112 #[doc = r"Clears the field bit"]
113 #[inline(always)]
114 #[allow(dead_code)]
115 pub fn clear_bit(self) -> &'a mut W {
116 self.bit(false)
117 }
118 #[doc = r"Writes raw bits to the field"]
119 #[inline(always)]
120 #[allow(dead_code)]
121 pub fn bit(self, value: bool) -> &'a mut W {
122 self.w.bits[0] = (self.w.bits[0] & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
123 self.w
124 }
125}
126
127#[doc = "Write proxy for field `ID`"]
128pub(crate) struct ID_W<'a> {
129 w: &'a mut W,
130}
131impl<'a> ID_W<'a> {
132 #[doc = r"Writes raw bits to the field"]
133 #[inline(always)]
134 #[allow(dead_code)]
135 pub unsafe fn bits(self, value: u32) -> &'a mut W {
136 self.w.bits[0] = (self.w.bits[0] & !(0x1FFFFFFF)) | ((value as u32) & 0x1FFFFFFF);
137 self.w
138 }
139}
140
141#[doc = "Write proxy for field `DLC`"]
142pub(crate) struct DLC_W<'a> {
143 w: &'a mut W,
144}
145impl<'a> DLC_W<'a> {
146 #[doc = r"Writes raw bits to the field"]
147 #[inline(always)]
148 #[allow(dead_code)]
149 pub unsafe fn bits(self, value: u8) -> &'a mut W {
150 self.w.bits[1] = (self.w.bits[1] & !(0x0F << 16)) | (((value as u32) & 0x0F) << 16);
151 self.w
152 }
153}
154
155#[doc = "Write proxy for field `BRS`"]
156pub(crate) struct BRS_W<'a> {
157 w: &'a mut W,
158}
159impl<'a> BRS_W<'a> {
160 #[doc = r"Writes `variant` to the field"]
161 #[inline(always)]
162 #[allow(dead_code)]
163 pub fn set_brs(self, brs: BitRateSwitching) -> &'a mut W {
164 self.bit(brs as u8 != 0)
165 }
166
167 #[doc = r"Sets the field bit"]
168 #[inline(always)]
169 #[allow(dead_code)]
170 pub fn set_bit(self) -> &'a mut W {
171 self.bit(true)
172 }
173 #[doc = r"Clears the field bit"]
174 #[inline(always)]
175 #[allow(dead_code)]
176 pub fn clear_bit(self) -> &'a mut W {
177 self.bit(false)
178 }
179 #[doc = r"Writes raw bits to the field"]
180 #[inline(always)]
181 #[allow(dead_code)]
182 pub fn bit(self, value: bool) -> &'a mut W {
183 self.w.bits[1] = (self.w.bits[1] & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
184 self.w
185 }
186}
187
188#[doc = "Write proxy for field `FDF`"]
189pub(crate) struct FDF_W<'a> {
190 w: &'a mut W,
191}
192impl<'a> FDF_W<'a> {
193 #[doc = r"Writes `variant` to the field"]
194 #[inline(always)]
195 #[allow(dead_code)]
196 pub fn set_format(self, fdf: FrameFormat) -> &'a mut W {
197 self.bit(fdf as u8 != 0)
198 }
199
200 #[doc = r"Sets the field bit"]
201 #[inline(always)]
202 #[allow(dead_code)]
203 pub fn set_bit(self) -> &'a mut W {
204 self.bit(true)
205 }
206 #[doc = r"Clears the field bit"]
207 #[inline(always)]
208 #[allow(dead_code)]
209 pub fn clear_bit(self) -> &'a mut W {
210 self.bit(false)
211 }
212 #[doc = r"Writes raw bits to the field"]
213 #[inline(always)]
214 #[allow(dead_code)]
215 pub fn bit(self, value: bool) -> &'a mut W {
216 self.w.bits[1] = (self.w.bits[1] & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
217 self.w
218 }
219}
220
221#[doc = "Reader of field `EFC`"]
222pub(crate) type EFC_R = generic::R<bool, EventControl>;
223impl EFC_R {
224 pub fn to_event_control(&self) -> EventControl {
225 match self.bit() {
226 false => EventControl::DoNotStore,
227 true => EventControl::Store,
228 }
229 }
230}
231#[doc = "Write proxy for field `EFC`"]
232pub(crate) struct EFC_W<'a> {
233 w: &'a mut W,
234}
235impl<'a> EFC_W<'a> {
236 #[doc = r"Writes `variant` to the field"]
237 #[inline(always)]
238 #[allow(dead_code)]
239 pub fn set_event_control(self, efc: EventControl) -> &'a mut W {
240 self.bit(match efc {
241 EventControl::DoNotStore => false,
242 EventControl::Store => true,
243 })
244 }
245
246 #[doc = r"Sets the field bit"]
247 #[inline(always)]
248 #[allow(dead_code)]
249 pub fn set_bit(self) -> &'a mut W {
250 self.bit(true)
251 }
252 #[doc = r"Clears the field bit"]
253 #[inline(always)]
254 #[allow(dead_code)]
255 pub fn clear_bit(self) -> &'a mut W {
256 self.bit(false)
257 }
258 #[doc = r"Writes raw bits to the field"]
259 #[inline(always)]
260 #[allow(dead_code)]
261 pub fn bit(self, value: bool) -> &'a mut W {
262 self.w.bits[1] = (self.w.bits[1] & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
263 self.w
264 }
265}
266
267struct Marker(u8);
268impl From<Event> for Marker {
269 fn from(e: Event) -> Marker {
270 match e {
271 Event::NoEvent => Marker(0),
272 Event::Event(mm) => Marker(mm),
273 }
274 }
275}
276
277#[doc = "Reader of field `MM`"]
278pub(crate) type MM_R = generic::R<u8, u8>;
279#[doc = "Write proxy for field `MM`"]
280pub(crate) struct MM_W<'a> {
281 w: &'a mut W,
282}
283impl<'a> MM_W<'a> {
284 #[doc = r"Writes raw bits to the field"]
285 #[inline(always)]
286 pub unsafe fn bits(self, value: u8) -> &'a mut W {
287 self.w.bits[1] = (self.w.bits[1] & !(0x7F << 24)) | (((value as u32) & 0x7F) << 24);
288 self.w
289 }
290
291 fn set_message_marker(self, mm: Marker) -> &'a mut W {
292 unsafe { self.bits(mm.0) }
293 }
294}
295
296impl R {
297 #[doc = "Byte 0 - Bits 0:28 - ID"]
298 #[inline(always)]
299 pub fn id(&self) -> ID_R {
300 ID_R::new(((self.bits[0]) & 0x1FFFFFFF) as u32)
301 }
302 #[doc = "Byte 0 - Bit 29 - RTR"]
303 #[inline(always)]
304 pub fn rtr(&self) -> RTR_R {
305 RTR_R::new(((self.bits[0] >> 29) & 0x01) != 0)
306 }
307 #[doc = "Byte 0 - Bit 30 - XTD"]
308 #[inline(always)]
309 pub fn xtd(&self) -> XTD_R {
310 XTD_R::new(((self.bits[0] >> 30) & 0x01) != 0)
311 }
312 #[doc = "Byte 0 - Bit 30 - ESI"]
313 #[inline(always)]
314 pub fn esi(&self) -> ESI_R {
315 ESI_R::new(((self.bits[0] >> 31) & 0x01) != 0)
316 }
317 #[doc = "Byte 1 - Bits 16:19 - DLC"]
318 #[inline(always)]
319 pub fn dlc(&self) -> DLC_R {
320 DLC_R::new(((self.bits[1] >> 16) & 0x0F) as u8)
321 }
322 #[doc = "Byte 1 - Bits 20 - BRS"]
323 #[inline(always)]
324 pub fn brs(&self) -> BRS_R {
325 BRS_R::new(((self.bits[1] >> 20) & 0x01) != 0)
326 }
327 #[doc = "Byte 1 - Bits 20 - FDF"]
328 #[inline(always)]
329 pub fn fdf(&self) -> FDF_R {
330 FDF_R::new(((self.bits[1] >> 21) & 0x01) != 0)
331 }
332 #[doc = "Byte 1 - Bits 23 - EFC"]
333 #[inline(always)]
334 pub fn efc(&self) -> EFC_R {
335 EFC_R::new(((self.bits[1] >> 23) & 0x01) != 0)
336 }
337 #[doc = "Byte 1 - Bits 24:31 - MM"]
338 #[inline(always)]
339 pub fn mm(&self) -> MM_R {
340 MM_R::new(((self.bits[1] >> 24) & 0xFF) as u8)
341 }
342 pub fn to_data_length(&self) -> DataLength {
343 let dlc = self.dlc().bits();
344 let ff = self.fdf().frame_format();
345 let len = if ff == FrameFormat::Fdcan {
346 // See RM0433 Rev 7 Table 475. DLC coding
347 match dlc {
348 0..=8 => dlc,
349 9 => 12,
350 10 => 16,
351 11 => 20,
352 12 => 24,
353 13 => 32,
354 14 => 48,
355 15 => 64,
356 _ => panic!("DLC > 15"),
357 }
358 } else {
359 match dlc {
360 0..=8 => dlc,
361 9..=15 => 8,
362 _ => panic!("DLC > 15"),
363 }
364 };
365 DataLength::new(len, ff)
366 }
367 pub fn to_event(&self) -> Event {
368 let mm = self.mm().bits();
369 let efc = self.efc().to_event_control();
370 match efc {
371 EventControl::DoNotStore => Event::NoEvent,
372 EventControl::Store => Event::Event(mm),
373 }
374 }
375}
376impl W {
377 #[doc = "Byte 0 - Bits 0:28 - ID"]
378 #[inline(always)]
379 pub fn id(&mut self) -> ID_W {
380 ID_W { w: self }
381 }
382 #[doc = "Byte 0 - Bit 29 - RTR"]
383 #[inline(always)]
384 pub fn rtr(&mut self) -> RTR_W {
385 RTR_W { w: self }
386 }
387 #[doc = "Byte 0 - Bit 30 - XTD"]
388 #[inline(always)]
389 pub fn xtd(&mut self) -> XTD_W {
390 XTD_W { w: self }
391 }
392 #[doc = "Byte 0 - Bit 31 - ESI"]
393 #[inline(always)]
394 pub fn esi(&mut self) -> ESI_W {
395 ESI_W { w: self }
396 }
397 #[doc = "Byte 1 - Bit 16:19 - DLC"]
398 #[inline(always)]
399 pub fn dlc(&mut self) -> DLC_W {
400 DLC_W { w: self }
401 }
402 #[doc = "Byte 1 - Bit 20 - BRS"]
403 #[inline(always)]
404 pub fn brs(&mut self) -> BRS_W {
405 BRS_W { w: self }
406 }
407 #[doc = "Byte 1 - Bit 21 - FDF"]
408 #[inline(always)]
409 pub fn fdf(&mut self) -> FDF_W {
410 FDF_W { w: self }
411 }
412 #[doc = "Byte 1 - Bit 23 - EFC"]
413 #[inline(always)]
414 pub fn efc(&mut self) -> EFC_W {
415 EFC_W { w: self }
416 }
417 #[doc = "Byte 1 - Bit 24:31 - MM"]
418 #[inline(always)]
419 pub fn mm(&mut self) -> MM_W {
420 MM_W { w: self }
421 }
422 #[doc = "Convenience function for setting the data length and frame format"]
423 #[inline(always)]
424 pub fn set_len(&mut self, dl: impl Into<DataLength>) -> &mut Self {
425 let dl: DataLength = dl.into();
426 self.fdf().set_format(dl.into());
427 unsafe { self.dlc().bits(dl.dlc()) }
428 }
429 pub fn set_event(&mut self, event: Event) -> &mut Self {
430 self.mm().set_message_marker(event.into());
431 self.efc().set_event_control(event.into())
432 }
433}
diff --git a/embassy-stm32/src/can/fd/message_ram/txevent_element.rs b/embassy-stm32/src/can/fd/message_ram/txevent_element.rs
new file mode 100644
index 000000000..817a4449f
--- /dev/null
+++ b/embassy-stm32/src/can/fd/message_ram/txevent_element.rs
@@ -0,0 +1,138 @@
1// Note: This file is copied and modified from fdcan crate by Richard Meadows
2
3#![allow(non_camel_case_types)]
4#![allow(non_snake_case)]
5#![allow(unused)]
6
7use super::common::{BRS_R, DLC_R, ESI_R, RTR_R, XTD_R};
8use super::generic;
9
10#[doc = "Reader of register TxEventElement"]
11pub(crate) type R = generic::R<super::TxEventElementType, super::TxEventElement>;
12// #[doc = "Writer for register TxEventElement"]
13// pub(crate) type W = generic::W<super::TxEventElementType, super::TxEventElement>;
14#[doc = "Register TxEventElement `reset()`'s"]
15impl generic::ResetValue for super::TxEventElement {
16 type Type = super::TxEventElementType;
17 #[inline(always)]
18 fn reset_value() -> Self::Type {
19 [0, 0]
20 }
21}
22
23#[doc = "Reader of field `ID`"]
24pub(crate) type ID_R = generic::R<u32, u32>;
25
26#[doc = "Reader of field `TXTS`"]
27pub(crate) type TXTS_R = generic::R<u16, u16>;
28
29#[derive(Clone, Copy, Debug, PartialEq)]
30pub(crate) enum DataLengthFormat {
31 StandardLength = 0,
32 FDCANLength = 1,
33}
34impl From<DataLengthFormat> for bool {
35 #[inline(always)]
36 fn from(dlf: DataLengthFormat) -> Self {
37 dlf as u8 != 0
38 }
39}
40
41#[doc = "Reader of field `EDL`"]
42pub(crate) type EDL_R = generic::R<bool, DataLengthFormat>;
43impl EDL_R {
44 pub fn data_length_format(&self) -> DataLengthFormat {
45 match self.bits() {
46 false => DataLengthFormat::StandardLength,
47 true => DataLengthFormat::FDCANLength,
48 }
49 }
50 pub fn is_standard_length(&self) -> bool {
51 *self == DataLengthFormat::StandardLength
52 }
53 pub fn is_fdcan_length(&self) -> bool {
54 *self == DataLengthFormat::FDCANLength
55 }
56}
57
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub(crate) enum EventType {
60 //_Reserved = 0b00,
61 TxEvent = 0b01,
62 TxDespiteAbort = 0b10,
63 //_Reserved = 0b10,
64}
65
66#[doc = "Reader of field `EFC`"]
67pub(crate) type EFC_R = generic::R<u8, EventType>;
68impl EFC_R {
69 pub fn event_type(&self) -> EventType {
70 match self.bits() {
71 0b01 => EventType::TxEvent,
72 0b10 => EventType::TxDespiteAbort,
73 _ => unimplemented!(),
74 }
75 }
76 pub fn is_tx_event(&self) -> bool {
77 self.event_type() == EventType::TxEvent
78 }
79 pub fn is_despite_abort(&self) -> bool {
80 self.event_type() == EventType::TxDespiteAbort
81 }
82}
83
84#[doc = "Reader of field `MM`"]
85pub(crate) type MM_R = generic::R<u8, u8>;
86
87impl R {
88 #[doc = "Byte 0 - Bits 0:28 - ID"]
89 #[inline(always)]
90 pub fn id(&self) -> ID_R {
91 ID_R::new(((self.bits[0]) & 0x1FFFFFFF) as u32)
92 }
93 #[doc = "Byte 0 - Bit 29 - RTR"]
94 #[inline(always)]
95 pub fn rtr(&self) -> RTR_R {
96 RTR_R::new(((self.bits[0] >> 29) & 0x01) != 0)
97 }
98 #[doc = "Byte 0 - Bit 30 - XTD"]
99 #[inline(always)]
100 pub fn xtd(&self) -> XTD_R {
101 XTD_R::new(((self.bits[0] >> 30) & 0x01) != 0)
102 }
103 #[doc = "Byte 0 - Bit 30 - ESI"]
104 #[inline(always)]
105 pub fn esi(&self) -> ESI_R {
106 ESI_R::new(((self.bits[0] >> 31) & 0x01) != 0)
107 }
108 #[doc = "Byte 1 - Bits 0:15 - TXTS"]
109 #[inline(always)]
110 pub fn txts(&self) -> TXTS_R {
111 TXTS_R::new(((self.bits[1]) & 0xFFFF) as u16)
112 }
113 #[doc = "Byte 1 - Bits 16:19 - DLC"]
114 #[inline(always)]
115 pub fn dlc(&self) -> DLC_R {
116 DLC_R::new(((self.bits[1] >> 16) & 0x0F) as u8)
117 }
118 #[doc = "Byte 1 - Bits 20 - BRS"]
119 #[inline(always)]
120 pub fn brs(&self) -> BRS_R {
121 BRS_R::new(((self.bits[1] >> 20) & 0x01) != 0)
122 }
123 #[doc = "Byte 1 - Bits 21 - EDL"]
124 #[inline(always)]
125 pub fn edl(&self) -> EDL_R {
126 EDL_R::new(((self.bits[1] >> 21) & 0x01) != 0)
127 }
128 #[doc = "Byte 1 - Bits 22:23 - EFC"]
129 #[inline(always)]
130 pub fn efc(&self) -> EFC_R {
131 EFC_R::new(((self.bits[1] >> 22) & 0x03) as u8)
132 }
133 #[doc = "Byte 1 - Bits 24:31 - MM"]
134 #[inline(always)]
135 pub fn mm(&self) -> MM_R {
136 MM_R::new(((self.bits[1] >> 24) & 0xFF) as u8)
137 }
138}
diff --git a/embassy-stm32/src/can/fd/mod.rs b/embassy-stm32/src/can/fd/mod.rs
new file mode 100644
index 000000000..271ca0b3c
--- /dev/null
+++ b/embassy-stm32/src/can/fd/mod.rs
@@ -0,0 +1,6 @@
1//! Module containing that which is specific to fdcan hardware variant
2
3pub mod config;
4pub mod filter;
5pub(crate) mod message_ram;
6pub(crate) mod peripheral;
diff --git a/embassy-stm32/src/can/fd/peripheral.rs b/embassy-stm32/src/can/fd/peripheral.rs
new file mode 100644
index 000000000..0771d6fbb
--- /dev/null
+++ b/embassy-stm32/src/can/fd/peripheral.rs
@@ -0,0 +1,828 @@
1// Note: This file is copied and modified from fdcan crate by Richard Meadows
2
3use core::convert::Infallible;
4use core::slice;
5
6use cfg_if::cfg_if;
7
8use crate::can::enums::*;
9use crate::can::fd::config::*;
10use crate::can::fd::message_ram::enums::*;
11use crate::can::fd::message_ram::{RegisterBlock, RxFifoElement, TxBufferElement};
12use crate::can::frame::*;
13
14/// Loopback Mode
15#[derive(Clone, Copy, Debug)]
16enum LoopbackMode {
17 None,
18 Internal,
19 External,
20}
21
22pub struct Registers {
23 pub regs: &'static crate::pac::can::Fdcan,
24 pub msgram: &'static crate::pac::fdcanram::Fdcanram,
25}
26
27impl Registers {
28 fn tx_buffer_element(&self, bufidx: usize) -> &mut TxBufferElement {
29 &mut self.msg_ram_mut().transmit.tbsa[bufidx]
30 }
31 pub fn msg_ram_mut(&self) -> &mut RegisterBlock {
32 let ptr = self.msgram.as_ptr() as *mut RegisterBlock;
33 unsafe { &mut (*ptr) }
34 }
35
36 fn rx_fifo_element(&self, fifonr: usize, bufnum: usize) -> &mut RxFifoElement {
37 &mut self.msg_ram_mut().receive[fifonr].fxsa[bufnum]
38 }
39
40 pub fn read_classic(&self, fifonr: usize) -> Option<(ClassicFrame, u16)> {
41 // Fill level - do we have a msg?
42 if self.regs.rxfs(fifonr).read().ffl() < 1 {
43 return None;
44 }
45
46 let read_idx = self.regs.rxfs(fifonr).read().fgi();
47 let mailbox = self.rx_fifo_element(fifonr, read_idx as usize);
48
49 let mut buffer: [u8; 8] = [0; 8];
50 let maybe_header = extract_frame(mailbox, &mut buffer);
51
52 // Clear FIFO, reduces count and increments read buf
53 self.regs.rxfa(fifonr).modify(|w| w.set_fai(read_idx));
54
55 match maybe_header {
56 Some((header, ts)) => {
57 let data = ClassicData::new(&buffer[0..header.len() as usize]);
58 Some((ClassicFrame::new(header, data.unwrap()), ts))
59 }
60 None => None,
61 }
62 }
63
64 pub fn read_fd(&self, fifonr: usize) -> Option<(FdFrame, u16)> {
65 // Fill level - do we have a msg?
66 if self.regs.rxfs(fifonr).read().ffl() < 1 {
67 return None;
68 }
69
70 let read_idx = self.regs.rxfs(fifonr).read().fgi();
71 let mailbox = self.rx_fifo_element(fifonr, read_idx as usize);
72
73 let mut buffer: [u8; 64] = [0; 64];
74 let maybe_header = extract_frame(mailbox, &mut buffer);
75
76 // Clear FIFO, reduces count and increments read buf
77 self.regs.rxfa(fifonr).modify(|w| w.set_fai(read_idx));
78
79 match maybe_header {
80 Some((header, ts)) => {
81 let data = FdData::new(&buffer[0..header.len() as usize]);
82 Some((FdFrame::new(header, data.unwrap()), ts))
83 }
84 None => None,
85 }
86 }
87
88 pub fn put_tx_frame(&self, bufidx: usize, header: &Header, buffer: &[u8]) {
89 // Fill level - do we have a msg?
90 //if self.regs.rxfs(fifonr).read().ffl() < 1 { return None; }
91
92 //let read_idx = self.regs.rxfs(fifonr).read().fgi();
93
94 let mailbox = self.tx_buffer_element(bufidx);
95
96 mailbox.reset();
97 put_tx_header(mailbox, header);
98 put_tx_data(mailbox, &buffer[..header.len() as usize]);
99
100 // Set <idx as Mailbox> as ready to transmit
101 self.regs.txbar().modify(|w| w.set_ar(bufidx, true));
102 }
103
104 fn reg_to_error(value: u8) -> Option<BusError> {
105 match value {
106 //0b000 => None,
107 0b001 => Some(BusError::Stuff),
108 0b010 => Some(BusError::Form),
109 0b011 => Some(BusError::Acknowledge),
110 0b100 => Some(BusError::BitRecessive),
111 0b101 => Some(BusError::BitDominant),
112 0b110 => Some(BusError::Crc),
113 //0b111 => Some(BusError::NoError),
114 _ => None,
115 }
116 }
117
118 pub fn curr_error(&self) -> Option<BusError> {
119 let err = { self.regs.psr().read() };
120 if err.bo() {
121 return Some(BusError::BusOff);
122 } else if err.ep() {
123 return Some(BusError::BusPassive);
124 } else if err.ew() {
125 return Some(BusError::BusWarning);
126 } else {
127 cfg_if! {
128 if #[cfg(stm32h7)] {
129 let lec = err.lec();
130 } else {
131 let lec = err.lec().to_bits();
132 }
133 }
134 if let Some(err) = Self::reg_to_error(lec) {
135 return Some(err);
136 }
137 }
138 None
139 }
140 /// Returns if the tx queue is able to accept new messages without having to cancel an existing one
141 #[inline]
142 pub fn tx_queue_is_full(&self) -> bool {
143 self.regs.txfqs().read().tfqf()
144 }
145
146 #[inline]
147 pub fn has_pending_frame(&self, idx: usize) -> bool {
148 self.regs.txbrp().read().trp(idx)
149 }
150
151 /// Returns `Ok` when the mailbox is free or if it contains pending frame with a
152 /// lower priority (higher ID) than the identifier `id`.
153 #[inline]
154 pub fn is_available(&self, bufidx: usize, id: &embedded_can::Id) -> bool {
155 if self.has_pending_frame(bufidx) {
156 let mailbox = self.tx_buffer_element(bufidx);
157
158 let header_reg = mailbox.header.read();
159 let old_id = make_id(header_reg.id().bits(), header_reg.xtd().bits());
160
161 *id > old_id
162 } else {
163 true
164 }
165 }
166
167 /// Attempts to abort the sending of a frame that is pending in a mailbox.
168 ///
169 /// If there is no frame in the provided mailbox, or its transmission succeeds before it can be
170 /// aborted, this function has no effect and returns `false`.
171 ///
172 /// If there is a frame in the provided mailbox, and it is canceled successfully, this function
173 /// returns `true`.
174 #[inline]
175 pub fn abort(&self, bufidx: usize) -> bool {
176 let can = self.regs;
177
178 // Check if there is a request pending to abort
179 if self.has_pending_frame(bufidx) {
180 // Abort Request
181 can.txbcr().write(|w| w.set_cr(bufidx, true));
182
183 // Wait for the abort request to be finished.
184 loop {
185 if can.txbcf().read().cf(bufidx) {
186 // Return false when a transmission has occured
187 break can.txbto().read().to(bufidx) == false;
188 }
189 }
190 } else {
191 false
192 }
193 }
194
195 #[inline]
196 //fn abort_pending_mailbox<PTX, R>(&mut self, idx: Mailbox, pending: PTX) -> Option<R>
197 pub fn abort_pending_mailbox(&self, bufidx: usize) -> Option<ClassicFrame>
198//where
199 // PTX: FnOnce(Mailbox, TxFrameHeader, &[u32]) -> R,
200 {
201 if self.abort(bufidx) {
202 let mailbox = self.tx_buffer_element(bufidx);
203
204 let header_reg = mailbox.header.read();
205 let id = make_id(header_reg.id().bits(), header_reg.xtd().bits());
206
207 let len = match header_reg.to_data_length() {
208 DataLength::Fdcan(len) => len,
209 DataLength::Classic(len) => len,
210 };
211 if len as usize > ClassicFrame::MAX_DATA_LEN {
212 return None;
213 }
214
215 //let tx_ram = self.tx_msg_ram();
216 let mut data = [0u8; 64];
217 data_from_tx_buffer(&mut data, mailbox, len as usize);
218
219 let cd = ClassicData::new(&data).unwrap();
220 Some(ClassicFrame::new(Header::new(id, len, header_reg.rtr().bit()), cd))
221 } else {
222 // Abort request failed because the frame was already sent (or being sent) on
223 // the bus. All mailboxes are now free. This can happen for small prescaler
224 // values (e.g. 1MBit/s bit timing with a source clock of 8MHz) or when an ISR
225 // has preempted the execution.
226 None
227 }
228 }
229
230 #[inline]
231 //fn abort_pending_mailbox<PTX, R>(&mut self, idx: Mailbox, pending: PTX) -> Option<R>
232 pub fn abort_pending_fd_mailbox(&self, bufidx: usize) -> Option<FdFrame>
233//where
234 // PTX: FnOnce(Mailbox, TxFrameHeader, &[u32]) -> R,
235 {
236 if self.abort(bufidx) {
237 let mailbox = self.tx_buffer_element(bufidx);
238
239 let header_reg = mailbox.header.read();
240 let id = make_id(header_reg.id().bits(), header_reg.xtd().bits());
241
242 let len = match header_reg.to_data_length() {
243 DataLength::Fdcan(len) => len,
244 DataLength::Classic(len) => len,
245 };
246 if len as usize > FdFrame::MAX_DATA_LEN {
247 return None;
248 }
249
250 //let tx_ram = self.tx_msg_ram();
251 let mut data = [0u8; 64];
252 data_from_tx_buffer(&mut data, mailbox, len as usize);
253
254 let cd = FdData::new(&data).unwrap();
255
256 let header = if header_reg.fdf().frame_format() == FrameFormat::Fdcan {
257 Header::new_fd(id, len, header_reg.rtr().bit(), header_reg.brs().bit())
258 } else {
259 Header::new(id, len, header_reg.rtr().bit())
260 };
261
262 Some(FdFrame::new(header, cd))
263 } else {
264 // Abort request failed because the frame was already sent (or being sent) on
265 // the bus. All mailboxes are now free. This can happen for small prescaler
266 // values (e.g. 1MBit/s bit timing with a source clock of 8MHz) or when an ISR
267 // has preempted the execution.
268 None
269 }
270 }
271
272 /// As Transmit, but if there is a pending frame, `pending` will be called so that the frame can
273 /// be preserved.
274 //pub fn transmit_preserve<PTX, P>(
275 pub fn write_classic(&self, frame: &ClassicFrame) -> nb::Result<Option<ClassicFrame>, Infallible> {
276 let queue_is_full = self.tx_queue_is_full();
277
278 let id = frame.header().id();
279
280 // If the queue is full,
281 // Discard the first slot with a lower priority message
282 let (idx, pending_frame) = if queue_is_full {
283 if self.is_available(0, id) {
284 (0, self.abort_pending_mailbox(0))
285 } else if self.is_available(1, id) {
286 (1, self.abort_pending_mailbox(1))
287 } else if self.is_available(2, id) {
288 (2, self.abort_pending_mailbox(2))
289 } else {
290 // For now we bail when there is no lower priority slot available
291 // Can this lead to priority inversion?
292 return Err(nb::Error::WouldBlock);
293 }
294 } else {
295 // Read the Write Pointer
296 let idx = self.regs.txfqs().read().tfqpi();
297
298 (idx, None)
299 };
300
301 self.put_tx_frame(idx as usize, frame.header(), frame.data());
302
303 Ok(pending_frame)
304 }
305
306 /// As Transmit, but if there is a pending frame, `pending` will be called so that the frame can
307 /// be preserved.
308 //pub fn transmit_preserve<PTX, P>(
309 pub fn write_fd(&self, frame: &FdFrame) -> nb::Result<Option<FdFrame>, Infallible> {
310 let queue_is_full = self.tx_queue_is_full();
311
312 let id = frame.header().id();
313
314 // If the queue is full,
315 // Discard the first slot with a lower priority message
316 let (idx, pending_frame) = if queue_is_full {
317 if self.is_available(0, id) {
318 (0, self.abort_pending_fd_mailbox(0))
319 } else if self.is_available(1, id) {
320 (1, self.abort_pending_fd_mailbox(1))
321 } else if self.is_available(2, id) {
322 (2, self.abort_pending_fd_mailbox(2))
323 } else {
324 // For now we bail when there is no lower priority slot available
325 // Can this lead to priority inversion?
326 return Err(nb::Error::WouldBlock);
327 }
328 } else {
329 // Read the Write Pointer
330 let idx = self.regs.txfqs().read().tfqpi();
331
332 (idx, None)
333 };
334
335 self.put_tx_frame(idx as usize, frame.header(), frame.data());
336
337 Ok(pending_frame)
338 }
339
340 #[inline]
341 fn reset_msg_ram(&mut self) {
342 self.msg_ram_mut().reset();
343 }
344
345 #[inline]
346 fn enter_init_mode(&mut self) {
347 self.regs.cccr().modify(|w| w.set_init(true));
348 while false == self.regs.cccr().read().init() {}
349 self.regs.cccr().modify(|w| w.set_cce(true));
350 }
351
352 /// Enables or disables loopback mode: Internally connects the TX and RX
353 /// signals together.
354 #[inline]
355 fn set_loopback_mode(&mut self, mode: LoopbackMode) {
356 let (test, mon, lbck) = match mode {
357 LoopbackMode::None => (false, false, false),
358 LoopbackMode::Internal => (true, true, true),
359 LoopbackMode::External => (true, false, true),
360 };
361
362 self.set_test_mode(test);
363 self.set_bus_monitoring_mode(mon);
364
365 self.regs.test().modify(|w| w.set_lbck(lbck));
366 }
367
368 /// Enables or disables silent mode: Disconnects the TX signal from the pin.
369 #[inline]
370 fn set_bus_monitoring_mode(&mut self, enabled: bool) {
371 self.regs.cccr().modify(|w| w.set_mon(enabled));
372 }
373
374 #[inline]
375 fn set_restricted_operations(&mut self, enabled: bool) {
376 self.regs.cccr().modify(|w| w.set_asm(enabled));
377 }
378
379 #[inline]
380 fn set_normal_operations(&mut self, _enabled: bool) {
381 self.set_loopback_mode(LoopbackMode::None);
382 }
383
384 #[inline]
385 fn set_test_mode(&mut self, enabled: bool) {
386 self.regs.cccr().modify(|w| w.set_test(enabled));
387 }
388
389 #[inline]
390 fn set_power_down_mode(&mut self, enabled: bool) {
391 self.regs.cccr().modify(|w| w.set_csr(enabled));
392 while self.regs.cccr().read().csa() != enabled {}
393 }
394
395 /// Moves out of PoweredDownMode and into ConfigMode
396 #[inline]
397 pub fn into_config_mode(mut self, _config: FdCanConfig) {
398 self.set_power_down_mode(false);
399 self.enter_init_mode();
400
401 self.reset_msg_ram();
402
403 // check the FDCAN core matches our expections
404 assert!(
405 self.regs.crel().read().rel() == 3,
406 "Expected FDCAN core major release 3"
407 );
408 assert!(
409 self.regs.endn().read().etv() == 0x87654321_u32,
410 "Error reading endianness test value from FDCAN core"
411 );
412
413 // Framework specific settings are set here
414
415 // set TxBuffer to Queue Mode
416 self.regs.txbc().write(|w| w.set_tfqm(true));
417
418 // set standard filters list size to 28
419 // set extended filters list size to 8
420 // REQUIRED: we use the memory map as if these settings are set
421 // instead of re-calculating them.
422 #[cfg(not(stm32h7))]
423 {
424 self.regs.rxgfc().modify(|w| {
425 w.set_lss(crate::can::fd::message_ram::STANDARD_FILTER_MAX);
426 w.set_lse(crate::can::fd::message_ram::EXTENDED_FILTER_MAX);
427 });
428 }
429 #[cfg(stm32h7)]
430 {
431 self.regs
432 .sidfc()
433 .modify(|w| w.set_lss(crate::can::fd::message_ram::STANDARD_FILTER_MAX));
434 self.regs
435 .xidfc()
436 .modify(|w| w.set_lse(crate::can::fd::message_ram::EXTENDED_FILTER_MAX));
437 }
438
439 /*
440 for fid in 0..crate::can::message_ram::STANDARD_FILTER_MAX {
441 self.set_standard_filter((fid as u8).into(), StandardFilter::disable());
442 }
443 for fid in 0..Ecrate::can::message_ram::XTENDED_FILTER_MAX {
444 self.set_extended_filter(fid.into(), ExtendedFilter::disable());
445 }
446 */
447 }
448
449 /// Disables the CAN interface and returns back the raw peripheral it was created from.
450 #[inline]
451 pub fn free(mut self) {
452 //self.disable_interrupts(Interrupts::all());
453
454 //TODO check this!
455 self.enter_init_mode();
456 self.set_power_down_mode(true);
457 //self.control.instance
458 }
459
460 /// Applies the settings of a new FdCanConfig See [`FdCanConfig`]
461 #[inline]
462 pub fn apply_config(&mut self, config: FdCanConfig) {
463 self.set_data_bit_timing(config.dbtr);
464 self.set_nominal_bit_timing(config.nbtr);
465 self.set_automatic_retransmit(config.automatic_retransmit);
466 self.set_transmit_pause(config.transmit_pause);
467 self.set_frame_transmit(config.frame_transmit);
468 //self.set_interrupt_line_config(config.interrupt_line_config);
469 self.set_non_iso_mode(config.non_iso_mode);
470 self.set_edge_filtering(config.edge_filtering);
471 self.set_protocol_exception_handling(config.protocol_exception_handling);
472 self.set_global_filter(config.global_filter);
473 }
474
475 #[inline]
476 fn leave_init_mode(&mut self, config: FdCanConfig) {
477 self.apply_config(config);
478
479 self.regs.cccr().modify(|w| w.set_cce(false));
480 self.regs.cccr().modify(|w| w.set_init(false));
481 while self.regs.cccr().read().init() == true {}
482 }
483
484 /// Moves out of ConfigMode and into specified mode
485 #[inline]
486 pub fn into_mode(mut self, config: FdCanConfig, mode: crate::can::_version::FdcanOperatingMode) {
487 match mode {
488 crate::can::FdcanOperatingMode::InternalLoopbackMode => self.set_loopback_mode(LoopbackMode::Internal),
489 crate::can::FdcanOperatingMode::ExternalLoopbackMode => self.set_loopback_mode(LoopbackMode::External),
490 crate::can::FdcanOperatingMode::NormalOperationMode => self.set_normal_operations(true),
491 crate::can::FdcanOperatingMode::RestrictedOperationMode => self.set_restricted_operations(true),
492 crate::can::FdcanOperatingMode::BusMonitoringMode => self.set_bus_monitoring_mode(true),
493 }
494 self.leave_init_mode(config);
495 }
496
497 /// Moves out of ConfigMode and into InternalLoopbackMode
498 #[inline]
499 pub fn into_internal_loopback(mut self, config: FdCanConfig) {
500 self.set_loopback_mode(LoopbackMode::Internal);
501 self.leave_init_mode(config);
502 }
503
504 /// Moves out of ConfigMode and into ExternalLoopbackMode
505 #[inline]
506 pub fn into_external_loopback(mut self, config: FdCanConfig) {
507 self.set_loopback_mode(LoopbackMode::External);
508 self.leave_init_mode(config);
509 }
510
511 /// Moves out of ConfigMode and into RestrictedOperationMode
512 #[inline]
513 pub fn into_restricted(mut self, config: FdCanConfig) {
514 self.set_restricted_operations(true);
515 self.leave_init_mode(config);
516 }
517
518 /// Moves out of ConfigMode and into NormalOperationMode
519 #[inline]
520 pub fn into_normal(mut self, config: FdCanConfig) {
521 self.set_normal_operations(true);
522 self.leave_init_mode(config);
523 }
524
525 /// Moves out of ConfigMode and into BusMonitoringMode
526 #[inline]
527 pub fn into_bus_monitoring(mut self, config: FdCanConfig) {
528 self.set_bus_monitoring_mode(true);
529 self.leave_init_mode(config);
530 }
531
532 /// Moves out of ConfigMode and into Testmode
533 #[inline]
534 pub fn into_test_mode(mut self, config: FdCanConfig) {
535 self.set_test_mode(true);
536 self.leave_init_mode(config);
537 }
538
539 /// Moves out of ConfigMode and into PoweredDownmode
540 #[inline]
541 pub fn into_powered_down(mut self, config: FdCanConfig) {
542 self.set_power_down_mode(true);
543 self.leave_init_mode(config);
544 }
545
546 /// Configures the bit timings.
547 ///
548 /// You can use <http://www.bittiming.can-wiki.info/> to calculate the `btr` parameter. Enter
549 /// parameters as follows:
550 ///
551 /// - *Clock Rate*: The input clock speed to the CAN peripheral (*not* the CPU clock speed).
552 /// This is the clock rate of the peripheral bus the CAN peripheral is attached to (eg. APB1).
553 /// - *Sample Point*: Should normally be left at the default value of 87.5%.
554 /// - *SJW*: Should normally be left at the default value of 1.
555 ///
556 /// Then copy the `CAN_BUS_TIME` register value from the table and pass it as the `btr`
557 /// parameter to this method.
558 #[inline]
559 pub fn set_nominal_bit_timing(&mut self, btr: NominalBitTiming) {
560 //self.control.config.nbtr = btr;
561
562 self.regs.nbtp().write(|w| {
563 w.set_nbrp(btr.nbrp() - 1);
564 w.set_ntseg1(btr.ntseg1() - 1);
565 w.set_ntseg2(btr.ntseg2() - 1);
566 w.set_nsjw(btr.nsjw() - 1);
567 });
568 }
569
570 /// Configures the data bit timings for the FdCan Variable Bitrates.
571 /// This is not used when frame_transmit is set to anything other than AllowFdCanAndBRS.
572 #[inline]
573 pub fn set_data_bit_timing(&mut self, btr: DataBitTiming) {
574 //self.control.config.dbtr = btr;
575
576 self.regs.dbtp().write(|w| {
577 w.set_dbrp(btr.dbrp() - 1);
578 w.set_dtseg1(btr.dtseg1() - 1);
579 w.set_dtseg2(btr.dtseg2() - 1);
580 w.set_dsjw(btr.dsjw() - 1);
581 });
582 }
583
584 /// Enables or disables automatic retransmission of messages
585 ///
586 /// If this is enabled, the CAN peripheral will automatically try to retransmit each frame
587 /// util it can be sent. Otherwise, it will try only once to send each frame.
588 ///
589 /// Automatic retransmission is enabled by default.
590 #[inline]
591 pub fn set_automatic_retransmit(&mut self, enabled: bool) {
592 self.regs.cccr().modify(|w| w.set_dar(!enabled));
593 //self.control.config.automatic_retransmit = enabled;
594 }
595
596 /// Configures the transmit pause feature. See
597 /// [`FdCanConfig::set_transmit_pause`]
598 #[inline]
599 pub fn set_transmit_pause(&mut self, enabled: bool) {
600 self.regs.cccr().modify(|w| w.set_txp(!enabled));
601 //self.control.config.transmit_pause = enabled;
602 }
603
604 /// Configures non-iso mode. See [`FdCanConfig::set_non_iso_mode`]
605 #[inline]
606 pub fn set_non_iso_mode(&mut self, enabled: bool) {
607 self.regs.cccr().modify(|w| w.set_niso(enabled));
608 //self.control.config.non_iso_mode = enabled;
609 }
610
611 /// Configures edge filtering. See [`FdCanConfig::set_edge_filtering`]
612 #[inline]
613 pub fn set_edge_filtering(&mut self, enabled: bool) {
614 self.regs.cccr().modify(|w| w.set_efbi(enabled));
615 //self.control.config.edge_filtering = enabled;
616 }
617
618 /// Configures frame transmission mode. See
619 /// [`FdCanConfig::set_frame_transmit`]
620 #[inline]
621 pub fn set_frame_transmit(&mut self, fts: FrameTransmissionConfig) {
622 let (fdoe, brse) = match fts {
623 FrameTransmissionConfig::ClassicCanOnly => (false, false),
624 FrameTransmissionConfig::AllowFdCan => (true, false),
625 FrameTransmissionConfig::AllowFdCanAndBRS => (true, true),
626 };
627
628 self.regs.cccr().modify(|w| {
629 w.set_fdoe(fdoe);
630 #[cfg(stm32h7)]
631 w.set_bse(brse);
632 #[cfg(not(stm32h7))]
633 w.set_brse(brse);
634 });
635
636 //self.control.config.frame_transmit = fts;
637 }
638
639 /// Sets the protocol exception handling on/off
640 #[inline]
641 pub fn set_protocol_exception_handling(&mut self, enabled: bool) {
642 self.regs.cccr().modify(|w| w.set_pxhd(!enabled));
643
644 //self.control.config.protocol_exception_handling = enabled;
645 }
646
647 /// Configures and resets the timestamp counter
648 #[inline]
649 pub fn set_timestamp_counter_source(&mut self, select: TimestampSource) {
650 #[cfg(stm32h7)]
651 let (tcp, tss) = match select {
652 TimestampSource::None => (0, 0),
653 TimestampSource::Prescaler(p) => (p as u8, 1),
654 TimestampSource::FromTIM3 => (0, 2),
655 };
656
657 #[cfg(not(stm32h7))]
658 let (tcp, tss) = match select {
659 TimestampSource::None => (0, stm32_metapac::can::vals::Tss::ZERO),
660 TimestampSource::Prescaler(p) => (p as u8, stm32_metapac::can::vals::Tss::INCREMENT),
661 TimestampSource::FromTIM3 => (0, stm32_metapac::can::vals::Tss::EXTERNAL),
662 };
663
664 self.regs.tscc().write(|w| {
665 w.set_tcp(tcp);
666 w.set_tss(tss);
667 });
668
669 //self.control.config.timestamp_source = select;
670 }
671
672 #[cfg(not(stm32h7))]
673 /// Configures the global filter settings
674 #[inline]
675 pub fn set_global_filter(&mut self, filter: GlobalFilter) {
676 let anfs = match filter.handle_standard_frames {
677 crate::can::fd::config::NonMatchingFilter::IntoRxFifo0 => stm32_metapac::can::vals::Anfs::ACCEPT_FIFO_0,
678 crate::can::fd::config::NonMatchingFilter::IntoRxFifo1 => stm32_metapac::can::vals::Anfs::ACCEPT_FIFO_1,
679 crate::can::fd::config::NonMatchingFilter::Reject => stm32_metapac::can::vals::Anfs::REJECT,
680 };
681 let anfe = match filter.handle_extended_frames {
682 crate::can::fd::config::NonMatchingFilter::IntoRxFifo0 => stm32_metapac::can::vals::Anfe::ACCEPT_FIFO_0,
683 crate::can::fd::config::NonMatchingFilter::IntoRxFifo1 => stm32_metapac::can::vals::Anfe::ACCEPT_FIFO_1,
684 crate::can::fd::config::NonMatchingFilter::Reject => stm32_metapac::can::vals::Anfe::REJECT,
685 };
686
687 self.regs.rxgfc().modify(|w| {
688 w.set_anfs(anfs);
689 w.set_anfe(anfe);
690 w.set_rrfs(filter.reject_remote_standard_frames);
691 w.set_rrfe(filter.reject_remote_extended_frames);
692 });
693 }
694
695 #[cfg(stm32h7)]
696 /// Configures the global filter settings
697 #[inline]
698 pub fn set_global_filter(&mut self, filter: GlobalFilter) {
699 let anfs = match filter.handle_standard_frames {
700 crate::can::fd::config::NonMatchingFilter::IntoRxFifo0 => 0,
701 crate::can::fd::config::NonMatchingFilter::IntoRxFifo1 => 1,
702 crate::can::fd::config::NonMatchingFilter::Reject => 2,
703 };
704
705 let anfe = match filter.handle_extended_frames {
706 crate::can::fd::config::NonMatchingFilter::IntoRxFifo0 => 0,
707 crate::can::fd::config::NonMatchingFilter::IntoRxFifo1 => 1,
708 crate::can::fd::config::NonMatchingFilter::Reject => 2,
709 };
710
711 self.regs.gfc().modify(|w| {
712 w.set_anfs(anfs);
713 w.set_anfe(anfe);
714 w.set_rrfs(filter.reject_remote_standard_frames);
715 w.set_rrfe(filter.reject_remote_extended_frames);
716 });
717 }
718}
719
720fn make_id(id: u32, extended: bool) -> embedded_can::Id {
721 if extended {
722 embedded_can::Id::from(unsafe { embedded_can::ExtendedId::new_unchecked(id & 0x1FFFFFFF) })
723 } else {
724 embedded_can::Id::from(unsafe { embedded_can::StandardId::new_unchecked((id & 0x000007FF) as u16) })
725 }
726}
727
728fn put_tx_header(mailbox: &mut TxBufferElement, header: &Header) {
729 let (id, id_type) = match header.id() {
730 embedded_can::Id::Standard(id) => (id.as_raw() as u32, IdType::StandardId),
731 embedded_can::Id::Extended(id) => (id.as_raw() as u32, IdType::ExtendedId),
732 };
733
734 // Use FDCAN only for DLC > 8. FDCAN users can revise this if required.
735 let frame_format = if header.len() > 8 || header.fdcan() {
736 FrameFormat::Fdcan
737 } else {
738 FrameFormat::Classic
739 };
740 let brs = header.len() > 8 || header.bit_rate_switching();
741
742 mailbox.header.write(|w| {
743 unsafe { w.id().bits(id) }
744 .rtr()
745 .bit(header.len() == 0 && header.rtr())
746 .xtd()
747 .set_id_type(id_type)
748 .set_len(DataLength::new(header.len(), frame_format))
749 .set_event(Event::NoEvent)
750 .fdf()
751 .set_format(frame_format)
752 .brs()
753 .bit(brs)
754 //esi.set_error_indicator(//TODO//)
755 });
756}
757
758fn put_tx_data(mailbox: &mut TxBufferElement, buffer: &[u8]) {
759 let mut lbuffer = [0_u32; 16];
760 let len = buffer.len();
761 let data = unsafe { slice::from_raw_parts_mut(lbuffer.as_mut_ptr() as *mut u8, len) };
762 data[..len].copy_from_slice(&buffer[..len]);
763 let data_len = ((len) + 3) / 4;
764 for (register, byte) in mailbox.data.iter_mut().zip(lbuffer[..data_len].iter()) {
765 unsafe { register.write(*byte) };
766 }
767}
768
769fn data_from_fifo(buffer: &mut [u8], mailbox: &RxFifoElement, len: usize) {
770 for (i, register) in mailbox.data.iter().enumerate() {
771 let register_value = register.read();
772 let register_bytes = unsafe { slice::from_raw_parts(&register_value as *const u32 as *const u8, 4) };
773 let num_bytes = (len) - i * 4;
774 if num_bytes <= 4 {
775 buffer[i * 4..i * 4 + num_bytes].copy_from_slice(&register_bytes[..num_bytes]);
776 break;
777 }
778 buffer[i * 4..(i + 1) * 4].copy_from_slice(register_bytes);
779 }
780}
781
782fn data_from_tx_buffer(buffer: &mut [u8], mailbox: &TxBufferElement, len: usize) {
783 for (i, register) in mailbox.data.iter().enumerate() {
784 let register_value = register.read();
785 let register_bytes = unsafe { slice::from_raw_parts(&register_value as *const u32 as *const u8, 4) };
786 let num_bytes = (len) - i * 4;
787 if num_bytes <= 4 {
788 buffer[i * 4..i * 4 + num_bytes].copy_from_slice(&register_bytes[..num_bytes]);
789 break;
790 }
791 buffer[i * 4..(i + 1) * 4].copy_from_slice(register_bytes);
792 }
793}
794
795impl From<&RxFifoElement> for ClassicFrame {
796 fn from(mailbox: &RxFifoElement) -> Self {
797 let header_reg = mailbox.header.read();
798
799 let id = make_id(header_reg.id().bits(), header_reg.xtd().bits());
800 let dlc = header_reg.to_data_length().len();
801 let len = dlc as usize;
802
803 let mut buffer: [u8; 64] = [0; 64];
804 data_from_fifo(&mut buffer, mailbox, len);
805 let data = ClassicData::new(&buffer[0..len]);
806 let header = Header::new(id, dlc, header_reg.rtr().bits());
807 ClassicFrame::new(header, data.unwrap())
808 }
809}
810
811fn extract_frame(mailbox: &RxFifoElement, buffer: &mut [u8]) -> Option<(Header, u16)> {
812 let header_reg = mailbox.header.read();
813
814 let id = make_id(header_reg.id().bits(), header_reg.xtd().bits());
815 let dlc = header_reg.to_data_length().len();
816 let len = dlc as usize;
817 let timestamp = header_reg.txts().bits;
818 if len > buffer.len() {
819 return None;
820 }
821 data_from_fifo(buffer, mailbox, len);
822 let header = if header_reg.fdf().bits {
823 Header::new_fd(id, dlc, header_reg.rtr().bits(), header_reg.brs().bits())
824 } else {
825 Header::new(id, dlc, header_reg.rtr().bits())
826 };
827 Some((header, timestamp))
828}