use super::{Display, ParseError};
use crate::frame::Frame;
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Aux([u8; 4]);
impl Aux {
pub const fn raw(self) -> [u8; 4] {
self.0
}
pub const fn raw_volts(self) -> u8 {
self.0[2]
}
pub fn volts(self) -> f32 {
f32::from(self.raw_volts()) / 100.0
}
}
impl std::fmt::Display for Aux {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("{}({:.2})", stringify!(Self), self.volts()))
}
}
impl TryFrom<Frame> for Aux {
type Error = ParseError;
fn try_from(frame: Frame) -> Result<Self, Self::Error> {
const ID: u32 = 0x2c2;
const LEN: usize = 4;
if frame.id() != ID {
return Err(ParseError::Id { frame });
}
let data: [u8; LEN] = match frame.data().try_into() {
Ok(data) => data,
Err(_) => {
return Err(ParseError::Len {
frame: frame.into(),
expected: LEN,
})
}
};
Ok(Aux(data))
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(PartialEq, Debug, Display, Clone)]
#[repr(align(8))]
pub enum Battery {
Aux(Aux),
}
impl TryFrom<Frame> for Battery {
type Error = ParseError;
fn try_from(frame: Frame) -> Result<Self, Self::Error> {
match frame.id() {
0x2c2 => Ok(Battery::Aux(frame.try_into()?)),
_ => Err(ParseError::Id { frame }),
}
}
}