Skip to content

Commit

Permalink
Added CAN ID wrapper for creating headers conveniently
Browse files Browse the repository at this point in the history
  • Loading branch information
Max Guichard committed Nov 21, 2024
1 parent 050d3d1 commit 110a948
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
8 changes: 8 additions & 0 deletions embassy-stm32/src/can/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ pub enum FrameCreateError {
InvalidCanId,
}

/// Id Create Errors
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum IdCreateError {
/// ID was out of range for 11/28 bit identifier
OutOfRange
}

/// Error returned by `try_read`
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
Expand Down
32 changes: 31 additions & 1 deletion embassy-stm32/src/can/frame.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Definition for CAN Frames
use bit_field::BitField;

use crate::can::enums::FrameCreateError;
use crate::can::enums::{FrameCreateError, IdCreateError};

/// Calculate proper timestamp when available.
#[cfg(feature = "time")]
Expand All @@ -19,6 +19,35 @@ pub struct Header {
flags: u8,
}

/// Convenience wrapper for embedded_can::Id
#[derive(Debug, Copy, Clone)]
pub struct Id (
// Wrapped ID
embedded_can::Id
);

impl TryFrom<u16> for Id {
type Error = IdCreateError;

fn try_from(raw_id: u16) -> Result<Self, Self::Error> {
let standard_id = embedded_can::StandardId::new(raw_id).ok_or(IdCreateError::OutOfRange)?;
Ok (Id { 0: standard_id.into() })
}
}

impl TryFrom<u32> for Id {
type Error = IdCreateError;

fn try_from(raw_id: u32) -> Result<Self, Self::Error> {
let extended_id = embedded_can::ExtendedId::new(raw_id).ok_or(IdCreateError::OutOfRange)?;
Ok (Id { 0: extended_id.into() })
}
}

impl From<Id> for embedded_can::Id {
fn from(id: Id) -> Self { id.0 }
}

#[cfg(feature = "defmt")]
impl defmt::Format for Header {
fn format(&self, fmt: defmt::Formatter<'_>) {
Expand Down Expand Up @@ -352,6 +381,7 @@ impl FdFrame {
}

/// Create new extended frame
/// BRS is set to false by default
pub fn new_extended(raw_id: u32, raw_data: &[u8]) -> Result<Self, FrameCreateError> {
if let Some(id) = embedded_can::ExtendedId::new(raw_id) {
Self::new(Header::new(id.into(), raw_data.len() as u8, false), raw_data)
Expand Down

0 comments on commit 110a948

Please sign in to comment.