esp_hal/twai/filter.rs
1//! Two-wire Automotive Interface (TWAI) Filters
2//!
3//! ## Overview
4//!
5//! The TWAI controller contains a hardware acceptance filter which can be used
6//! to filter messages of a particular ID. A node that filters out a message
7//! does not receive the message, but will still acknowledge it. Acceptance
8//! filters can make a node more efficient by filtering out messages sent over
9//! the bus that are irrelevant to the node.
10//!
11//! ## Configuration
12//!
13//! The acceptance filters are configured using two 32-bit values known as the
14//! acceptance code and the acceptance mask.
15
16use super::{ExtendedId, StandardId};
17
18#[derive(Debug, PartialEq, Eq)]
19/// Represents the type of filtering to be applied to incoming TWAI frames.
20pub enum FilterType {
21 /// Uses the acceptance code and mask to define a single filter, which
22 /// allows for the first two data bytes of a standard frame to be filtered,
23 /// or the entirety of an extended frame's 29-bit ID.
24 Single,
25 /// Uses the acceptance code and mask to define two separate filters
26 /// allowing for increased flexibility of ID's to accept, but does not allow
27 /// for all 29-bits of an extended ID to be filtered.
28 Dual,
29}
30
31/// Interface for interacting with Acceptance Filters.
32///
33/// The Acceptance Filter is a programmable message filtering unit that allows
34/// the TWAI controller to accept or reject a received message based on the
35/// message’s ID field.
36///
37/// Only accepted messages will be stored in the Receive FIFO.
38///
39/// The Acceptance Filter’s registers can be programmed to specify a single
40/// filter, or two separate filters (dual filter mode).
41pub trait Filter {
42 /// The type of the filter.
43 const FILTER_TYPE: FilterType;
44 /// Returns filter type.
45 fn filter_type(&self) -> FilterType {
46 Self::FILTER_TYPE
47 }
48
49 /// Get the register level representation of the filter.
50 fn to_registers(&self) -> [u8; 8];
51}
52
53/// A type representing the bitmask used to filter incoming TWAI frames.
54pub type BitFilter<const N: usize> = [u8; N];
55
56// Convert a byte from a bytestring into a bit inside a given code and mask.
57macro_rules! set_bit_from_byte {
58 ($code:expr, $mask:expr, $byte:expr, $shift:expr) => {
59 match $byte {
60 b'0' => {
61 // Code bit is already zero, no need to set it.
62 $mask |= 1 << $shift;
63 }
64 b'1' => {
65 $code |= 1 << $shift;
66 $mask |= 1 << $shift;
67 }
68 b'x' => {}
69 _ => ::core::panic!("BitFilter bits must be either '1', '0' or 'x'."),
70 }
71 };
72}
73
74// Convert a code and mask to the byte array needed at a register level.
75//
76// On the input mask, set bits (1) mean we care about the exact value of the
77// corresponding bit in the code, reset bits (0) mean the bit could be any
78// value.
79const fn code_mask_to_register_array(code: u32, mask: u32) -> [u8; 8] {
80 // Convert the filter code and mask into the full byte array needed for the
81 // registers.
82 let [code_3, code_2, code_1, code_0] = code.to_be_bytes();
83
84 // At a register level, set bits in the mask mean we don't care about the value
85 // of that bit. Therefore, we invert the mask.
86 // https://www.espressif.com/sites/default/files/documentation/esp32-c3_technical_reference_manual_en.pdf#subsubsection.29.4.6
87 let [mask_3, mask_2, mask_1, mask_0] = (!mask).to_be_bytes();
88
89 [
90 code_3, code_2, code_1, code_0, mask_3, mask_2, mask_1, mask_0,
91 ]
92}
93
94/// A filter that matches against a single 11 bit id, the RTR bit, and the first
95/// two bytes of the payload.
96///
97/// Warning: This is not a perfect filter. Extended IDs that match the bit
98/// layout of this filter will also be accepted.
99pub struct SingleStandardFilter {
100 /// The register representation of the filter.
101 raw: [u8; 8],
102}
103
104impl SingleStandardFilter {
105 /// Create a new filter that matches against a single 11-bit standard id.
106 /// The filter can match against the packet's id, RTR bit, and first two
107 /// bytes of the payload.
108 ///
109 /// Example matching only even IDs, allowing any rtr value and any payload
110 /// data:
111 /// ```rust, no_run
112 #[doc = crate::before_snippet!()]
113 /// # use esp_hal::twai::filter::SingleStandardFilter;
114 /// const FILTER: SingleStandardFilter =
115 /// SingleStandardFilter::new(
116 /// b"xxxxxxxxxx0",
117 /// b"x",
118 /// [b"xxxxxxxx", b"xxxxxxxx"]
119 /// );
120 /// # Ok(())
121 /// # }
122 /// ```
123 pub const fn new(id: &BitFilter<11>, rtr: &BitFilter<1>, payload: [&BitFilter<8>; 2]) -> Self {
124 // The bit values we desire to match against. This determines whether we want a
125 // set bit (1) or a reset bit (0).
126 let mut acceptance_code: u32 = 0;
127 // The acceptance mask, set bits (1) mean we care about the exact value of the
128 // corresponding bit in the code, reset bits (0) mean the bit could be any
129 // value.
130 let mut acceptance_mask: u32 = 0;
131
132 // Convert the id filter into the code and mask bits.
133 {
134 let mut idx = 0;
135 while idx < 11 {
136 let shift = 31 - idx;
137 set_bit_from_byte!(acceptance_code, acceptance_mask, id[idx], shift);
138 idx += 1;
139 }
140 }
141 // Convert the RTR bit filter into the code and mask bits.
142 {
143 let shift = 20;
144 set_bit_from_byte!(acceptance_code, acceptance_mask, rtr[0], shift);
145 }
146 // Convert the payload byte filter into the code and mask bits.
147 {
148 let mut payload_index = 0;
149 while payload_index < 2 {
150 let mut idx = 0;
151 while idx < 8 {
152 let shift = 15 - (8 * payload_index) - idx;
153 set_bit_from_byte!(
154 acceptance_code,
155 acceptance_mask,
156 payload[payload_index][idx],
157 shift
158 );
159 idx += 1;
160 }
161 payload_index += 1;
162 }
163 }
164
165 Self {
166 raw: code_mask_to_register_array(acceptance_code, acceptance_mask),
167 }
168 }
169
170 /// The masks indicate which bits of the code the filter should match
171 /// against. Set bits in the mask indicate that the corresponding bit in
172 /// the code should match.
173 ///
174 ///
175 /// # Examples
176 ///
177 /// A filter that matches every standard id that is even, is not an rtr
178 /// frame, with any bytes for the first two payload bytes.
179 /// ```rust, ignore
180 /// let filter = twai::filter::SingleStandardFilter::new_from_code_mask(
181 /// StandardId::new(0x000)?,
182 /// StandardId::new(0x001)?,
183 /// false,
184 /// true,
185 /// [0x00, 0x00],
186 /// [0x00, 0x00],
187 /// );
188 /// ```
189 pub fn new_from_code_mask(
190 id_code: StandardId,
191 id_mask: StandardId,
192 rtr_code: bool,
193 rtr_mask: bool,
194 payload_code: [u8; 2],
195 payload_mask: [u8; 2],
196 ) -> Self {
197 // The bit values we desire to match against. This determines whether we want a
198 // set bit (1) or a reset bit (0).
199 let mut acceptance_code: u32 = 0;
200 // The acceptance mask, set bits (1) mean we care about the exact value of the
201 // corresponding bit in the code, reset bits (0) mean the bit could be any
202 // value.
203 let mut acceptance_mask: u32 = 0;
204
205 // Pack the id into the full layout.
206 acceptance_code |= (id_code.as_raw() as u32) << 21;
207 acceptance_mask |= (id_mask.as_raw() as u32) << 21;
208
209 // Pack the RTR bit into the full layout.
210 acceptance_code |= (rtr_code as u32) << 20;
211 acceptance_mask |= (rtr_mask as u32) << 20;
212
213 // Pack the payload bytes into the full layout.
214 acceptance_code |= ((payload_code[0] as u32) << 8) | (payload_code[1] as u32);
215 acceptance_mask |= ((payload_mask[0] as u32) << 8) | (payload_mask[1] as u32);
216
217 Self {
218 raw: code_mask_to_register_array(acceptance_code, acceptance_mask),
219 }
220 }
221}
222
223impl Filter for SingleStandardFilter {
224 const FILTER_TYPE: FilterType = FilterType::Single;
225 fn to_registers(&self) -> [u8; 8] {
226 self.raw
227 }
228}
229
230/// Warning: This is not a perfect filter. Standard IDs that match the bit
231/// layout of this filter will also be accepted.
232pub struct SingleExtendedFilter {
233 raw: [u8; 8],
234}
235
236impl SingleExtendedFilter {
237 /// Create a filter that matches against a single 29-bit extended id.
238 ///
239 /// The filter can match against the packet's id and the RTR bit.
240 ///
241 /// # Examples
242 /// A filter matching any odd extended IDs, with any rtr value.
243 /// ```rust, ignore
244 /// const FILTER: twai::filter::SingleExtendedFilter =
245 /// twai::filter::SingleExtendedFilter::new(b"xxxxxxxxxxxxxxxxxxxxxxxxxxxx1", b"x");
246 /// ```
247 pub const fn new(id: &BitFilter<29>, rtr: &BitFilter<1>) -> Self {
248 // The bit values we desire to match against. This determines whether we want a
249 // set bit (1) or a reset bit (0).
250 let mut acceptance_code: u32 = 0;
251 // The acceptance mask, set bits (1) mean we care about the exact value of the
252 // corresponding bit in the code, reset bits (0) mean the bit could be any
253 // value.
254 let mut acceptance_mask: u32 = 0;
255
256 // Convert the id filter into the code and mask bits.
257 {
258 let mut idx = 0;
259 while idx < 29 {
260 let shift = 31 - idx;
261 set_bit_from_byte!(acceptance_code, acceptance_mask, id[idx], shift);
262 idx += 1;
263 }
264 }
265 // Convert the RTR bit filter into the code and mask bits.
266 {
267 let shift = 2;
268 set_bit_from_byte!(acceptance_code, acceptance_mask, rtr[0], shift);
269 }
270
271 Self {
272 raw: code_mask_to_register_array(acceptance_code, acceptance_mask),
273 }
274 }
275 /// The masks indicate which bits of the code the filter should match
276 /// against. Set bits in the mask indicate that the corresponding bit in
277 /// the code should match.
278 pub fn new_from_code_mask(
279 id_code: ExtendedId,
280 id_mask: ExtendedId,
281 rtr_code: bool,
282 rtr_mask: bool,
283 ) -> Self {
284 // The bit values we desire to match against. This determines whether we want a
285 // set bit (1) or a reset bit (0).
286 let mut acceptance_code: u32 = 0;
287 // The acceptance mask, set bits (1) mean we care about the exact value of the
288 // corresponding bit in the code, reset bits (0) mean the bit could be any
289 // value.
290 let mut acceptance_mask: u32 = 0;
291
292 // Pack the id into the full layout.
293 acceptance_code |= id_code.as_raw() << 3;
294 acceptance_mask |= id_mask.as_raw() << 3;
295
296 // Pack the RTR bit into the full layout.
297 acceptance_code |= (rtr_code as u32) << 2;
298 acceptance_mask |= (rtr_mask as u32) << 2;
299
300 Self {
301 raw: code_mask_to_register_array(acceptance_code, acceptance_mask),
302 }
303 }
304}
305
306impl Filter for SingleExtendedFilter {
307 const FILTER_TYPE: FilterType = FilterType::Single;
308 fn to_registers(&self) -> [u8; 8] {
309 self.raw
310 }
311}
312
313/// A filter that matches against two standard 11-bit standard IDs.
314///
315/// The first filter part can match a packet's id, RTR bit, and the first byte
316/// of the payload. The second filter part can match a packet's id and RTR bit.
317///
318/// Warning: This is not a perfect filter. Extended IDs that match the bit
319/// layout of this filter will also be accepted.
320pub struct DualStandardFilter {
321 raw: [u8; 8],
322}
323
324impl DualStandardFilter {
325 /// Create a filter that matches against two standard 11-bit standard IDs.
326 ///
327 /// The first filter part can match a packet's id, RTR bit, and the first
328 /// byte of the payload. The second filter part can match a packet's id
329 /// and RTR bit.
330 ///
331 /// # Examples
332 /// A filter that matches any standard id that ends with a 00 or a 11, with
333 /// any RTR, and with any payload on the first filter.
334 /// ```rust, ignore
335 /// const FILTER: twai::filter::DualStandardFilter = twai::filter::DualStandardFilter::new(
336 /// b"xxxxxxxxx00",
337 /// b"x",
338 /// b"xxxxxxxx",
339 /// b"xxxxxxxxx11",
340 /// b"x",
341 /// );
342 /// ```
343 pub const fn new(
344 first_id: &BitFilter<11>,
345 first_rtr: &BitFilter<1>,
346 first_payload: &BitFilter<8>,
347 second_id: &BitFilter<11>,
348 second_rtr: &BitFilter<1>,
349 ) -> Self {
350 // The bit values we desire to match against. This determines whether we want a
351 // set bit (1) or a reset bit (0).
352 let mut acceptance_code: u32 = 0;
353 // The acceptance mask, set bits (1) mean we care about the exact value of the
354 // corresponding bit in the code, reset bits (0) mean the bit could be any
355 // value.
356 let mut acceptance_mask: u32 = 0;
357
358 // Convert the first id filter into the code and mask bits.
359 {
360 let mut idx = 0;
361 while idx < 11 {
362 let shift = 31 - idx;
363 set_bit_from_byte!(acceptance_code, acceptance_mask, first_id[idx], shift);
364 idx += 1;
365 }
366 }
367 // Convert the first RTR bit filter into the code and mask bits.
368 {
369 let shift = 20;
370 set_bit_from_byte!(acceptance_code, acceptance_mask, first_rtr[0], shift);
371 }
372 // Convert the first payload byte filter into the code and mask bits.
373 {
374 let mut idx = 0;
375 while idx < 4 {
376 let shift = 19 - idx;
377 set_bit_from_byte!(acceptance_code, acceptance_mask, first_payload[idx], shift);
378 idx += 1;
379 }
380 while idx < 8 {
381 let shift = 3 + 4 - idx;
382 set_bit_from_byte!(acceptance_code, acceptance_mask, first_payload[idx], shift);
383 idx += 1;
384 }
385 }
386 // Convert the second id filter into the code and mask bits.
387 {
388 let mut idx = 0;
389 while idx < 11 {
390 let shift = 15 - idx;
391 set_bit_from_byte!(acceptance_code, acceptance_mask, second_id[idx], shift);
392 idx += 1;
393 }
394 }
395 // Convert the second RTR bit filter into the code and mask bits.
396 {
397 let shift = 4;
398 set_bit_from_byte!(acceptance_code, acceptance_mask, second_rtr[0], shift);
399 }
400
401 Self {
402 raw: code_mask_to_register_array(acceptance_code, acceptance_mask),
403 }
404 }
405 /// The masks indicate which bits of the code the filter should match
406 /// against. Set bits in the mask indicate that the corresponding bit in
407 /// the code should match.
408 #[allow(clippy::too_many_arguments)]
409 pub fn new_from_code_mask(
410 first_id_code: StandardId,
411 first_id_mask: StandardId,
412 first_rtr_code: bool,
413 first_rtr_mask: bool,
414 first_payload_code: u8,
415 first_payload_mask: u8,
416 second_id_code: StandardId,
417 second_id_mask: StandardId,
418 second_rtr_code: bool,
419 second_rtr_mask: bool,
420 ) -> Self {
421 // The bit values we desire to match against. This determines whether we want a
422 // set bit (1) or a reset bit (0).
423 let mut acceptance_code: u32 = 0;
424 // The acceptance mask, set bits (1) mean we care about the exact value of the
425 // corresponding bit in the code, reset bits (0) mean the bit could be any
426 // value.
427 let mut acceptance_mask: u32 = 0;
428
429 // Pack the first id into the full layout.
430 acceptance_code |= (first_id_code.as_raw() as u32) << 21;
431 acceptance_mask |= (first_id_mask.as_raw() as u32) << 21;
432
433 // Pack the RTR bit into the full layout.
434 acceptance_code |= (first_rtr_code as u32) << 20;
435 acceptance_mask |= (first_rtr_mask as u32) << 20;
436
437 // Pack the first payload into the full layout.
438 acceptance_code |= ((first_payload_code & 0xF0) as u32) << 12;
439 acceptance_mask |= ((first_payload_mask & 0xF0) as u32) << 12;
440 acceptance_code |= (first_payload_code & 0x0F) as u32;
441 acceptance_mask |= (first_payload_mask & 0x0F) as u32;
442
443 // Pack the second id into the full layout.
444 acceptance_code |= (second_id_code.as_raw() as u32) << 5;
445 acceptance_mask |= (second_id_mask.as_raw() as u32) << 5;
446
447 // Pack the second RTR bit into the full layout.
448 acceptance_code |= (second_rtr_code as u32) << 4;
449 acceptance_mask |= (second_rtr_mask as u32) << 4;
450
451 Self {
452 raw: code_mask_to_register_array(acceptance_code, acceptance_mask),
453 }
454 }
455}
456
457impl Filter for DualStandardFilter {
458 const FILTER_TYPE: FilterType = FilterType::Dual;
459 fn to_registers(&self) -> [u8; 8] {
460 self.raw
461 }
462}
463
464/// Warning: This is not a perfect filter. Standard IDs that match the bit
465/// layout of this filter will also be accepted.
466///
467/// NOTE: The dual extended id acceptance filters can only match "the first 16
468/// bits of the 29-bit ID".
469pub struct DualExtendedFilter {
470 raw: [u8; 8],
471}
472
473impl DualExtendedFilter {
474 /// Create a filter that matches the first 16 bits of two 29-bit extended
475 /// IDs.
476 ///
477 /// # Examples
478 /// A filter that matches IDs with 4 bits either set or reset in the higher
479 /// part of the id. For example this id matches: 0x000f000f, 0x000f000a,
480 /// 0x0000000a, 0x0000000b.
481 /// But it does not match: 0x000a000a
482 /// ```rust, ignore
483 /// const FILTER: twai::filter::DualExtendedFilter =
484 /// twai::filter::DualExtendedFilter::new([b"xxxxxxxxx0000xxx", b"xxxxxxxxx1111xxx"]);
485 /// ```
486 pub const fn new(ids: [&BitFilter<16>; 2]) -> Self {
487 // The bit values we desire to match against. This determines whether we want a
488 // set bit (1) or a reset bit (0).
489 let mut acceptance_code: u32 = 0;
490 // The acceptance mask, set bits (1) mean we care about the exact value of the
491 // corresponding bit in the code, reset bits (0) mean the bit could be any
492 // value.
493 let mut acceptance_mask: u32 = 0;
494
495 // Convert the id filters into the code and mask bits.
496 {
497 let mut filter_idx = 0;
498 while filter_idx < 2 {
499 let mut idx = 0;
500 while idx < 16 {
501 let shift = 31 - (filter_idx * 16) - idx;
502 set_bit_from_byte!(
503 acceptance_code,
504 acceptance_mask,
505 ids[filter_idx][idx],
506 shift
507 );
508 idx += 1;
509 }
510 filter_idx += 1;
511 }
512 }
513
514 Self {
515 raw: code_mask_to_register_array(acceptance_code, acceptance_mask),
516 }
517 }
518 /// Create a new filter matching the first 16 bits of two 29-bit IDs.
519 ///
520 /// The masks indicate which bits of the code the filter should match
521 /// against. Set bits in the mask indicate that the corresponding bit in
522 /// the code should match.
523 pub fn new_from_code_mask(ids_code: [u16; 2], ids_mask: [u16; 2]) -> Self {
524 // The bit values we desire to match against. This determines whether we want a
525 // set bit (1) or a reset bit (0).
526 let mut acceptance_code: u32 = 0;
527 // The acceptance mask, set bits (1) mean we care about the exact value of the
528 // corresponding bit in the code, reset bits (0) mean the bit could be any
529 // value.
530 let mut acceptance_mask: u32 = 0;
531
532 // Pack the first partial id into the full layout.
533 acceptance_code |= (ids_code[0] as u32) << 16;
534 acceptance_mask |= (ids_mask[0] as u32) << 16;
535
536 // Pack the second partial id into the full layout.
537 acceptance_code |= ids_code[1] as u32;
538 acceptance_mask |= ids_mask[1] as u32;
539
540 Self {
541 raw: code_mask_to_register_array(acceptance_code, acceptance_mask),
542 }
543 }
544}
545
546impl Filter for DualExtendedFilter {
547 const FILTER_TYPE: FilterType = FilterType::Dual;
548 fn to_registers(&self) -> [u8; 8] {
549 self.raw
550 }
551}