diff --git a/embassy-stm32/src/can/enums.rs b/embassy-stm32/src/can/enums.rs index a5cca424db..69dcc6b412 100644 --- a/embassy-stm32/src/can/enums.rs +++ b/embassy-stm32/src/can/enums.rs @@ -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))] diff --git a/embassy-stm32/src/can/frame.rs b/embassy-stm32/src/can/frame.rs index d2d1f7aa6d..3497bae5f2 100644 --- a/embassy-stm32/src/can/frame.rs +++ b/embassy-stm32/src/can/frame.rs @@ -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")] @@ -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 for Id { + type Error = IdCreateError; + + fn try_from(raw_id: u16) -> Result { + let standard_id = embedded_can::StandardId::new(raw_id).ok_or(IdCreateError::OutOfRange)?; + Ok (Id { 0: standard_id.into() }) + } +} + +impl TryFrom for Id { + type Error = IdCreateError; + + fn try_from(raw_id: u32) -> Result { + let extended_id = embedded_can::ExtendedId::new(raw_id).ok_or(IdCreateError::OutOfRange)?; + Ok (Id { 0: extended_id.into() }) + } +} + +impl From 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<'_>) { @@ -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 { if let Some(id) = embedded_can::ExtendedId::new(raw_id) { Self::new(Header::new(id.into(), raw_data.len() as u8, false), raw_data)