use super::{Display, Frame, ParseError};
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(PartialEq, Debug, Display, Copy, Clone)]
pub struct ParkingLights(u8);
impl ParkingLights {
#[inline]
pub const fn are_on(self) -> bool {
self.0 == 1
}
#[inline]
pub const fn are_off(self) -> bool {
!self.are_on()
}
}
impl TryFrom<Frame> for ParkingLights {
type Error = ParseError;
fn try_from(frame: Frame) -> Result<Self, Self::Error> {
const ID: u32 = 0x2fa;
const LEN: usize = 8;
if frame.id() != ID {
return Err(ParseError::Id { frame });
}
let data: [u8; 8] = match frame.data().try_into() {
Ok(data) => data,
Err(_) => {
return Err(ParseError::Len {
frame,
expected: LEN,
})
}
};
if data[1] == 0 || data[1] == 1 {
Ok(Self(data[1]))
} else {
Err(ParseError::Data {
frame,
detail: format!(
"`ParkingLights` value ({}) at index 1 was neither 0 nor 1",
data[1]
),
})
}
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(PartialEq, Debug, Display, Copy, Clone)]
pub struct Dimmer(u8);
impl Dimmer {
const MIN: u8 = 0;
const MAX: u8 = 255;
const RANGE: u8 = Self::MAX - Self::MIN;
#[inline]
pub fn percent(self) -> f32 {
f32::from(self.0 - Self::MIN) / f32::from(Self::RANGE)
}
#[inline]
pub const fn is_min(self) -> bool {
self.0 == Self::MIN
}
#[inline]
pub const fn is_max(self) -> bool {
self.0 == Self::MAX
}
}
impl TryFrom<Frame> for Dimmer {
type Error = ParseError;
fn try_from(frame: Frame) -> Result<Self, Self::Error> {
const ID: u32 = 0x2fa;
const LEN: usize = 8;
if frame.id() != ID {
return Err(ParseError::Id { frame });
}
let data: [u8; 8] = match frame.data().try_into() {
Ok(data) => data,
Err(_) => {
return Err(ParseError::Len {
frame,
expected: LEN,
})
}
};
if data[2] >= Self::MIN && data[2] <= Self::MAX {
Ok(Self(data[2]))
} else {
Err(ParseError::Data {
frame,
detail: format!("`Dimmer` value ({}) at index 2 was outside of accepted range.", data[2]),
})
}
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(PartialEq, Debug, Display, Clone)]
#[repr(align(8))]
pub enum Lights {
HazardsOnOff,
ParkingLights(ParkingLights),
Dimmer(Dimmer),
}