use crate::protocol::{EncodedFrame, FrameId, FramePayload, FrameRef};
use embedded_can::{Frame, Id, StandardId};
impl EncodedFrame {
pub fn to_embedded_can<F: Frame>(&self) -> Option<F> {
let id = StandardId::new(self.id())?;
if self.is_remote() {
F::new_remote(id, usize::from(self.dlc()))
} else {
F::new(id, self.data())
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InvalidFrameLength;
impl core::fmt::Display for InvalidFrameLength {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("invalid Classic CAN frame length")
}
}
impl core::error::Error for InvalidFrameLength {}
impl<'a> FrameRef<'a> {
pub fn from_classic_embedded_can<F: Frame>(frame: &'a F) -> Result<Self, InvalidFrameLength> {
let dlc = frame.dlc();
if dlc > 8 {
return Err(InvalidFrameLength);
}
let payload = if frame.is_remote_frame() {
FramePayload::Remote { dlc: dlc as u8 }
} else {
FramePayload::Data(frame.data().get(..dlc).ok_or(InvalidFrameLength)?)
};
Ok(Self {
id: frame.id().into(),
payload,
})
}
}
impl From<Id> for FrameId {
fn from(id: Id) -> Self {
match id {
Id::Standard(id) => Self::Standard(id.as_raw()),
Id::Extended(id) => Self::Extended(id.as_raw()),
}
}
}