diff --git a/lib-bms-protocol/src/types.rs b/lib-bms-protocol/src/types.rs index b25775f..4d99e50 100644 --- a/lib-bms-protocol/src/types.rs +++ b/lib-bms-protocol/src/types.rs @@ -44,6 +44,12 @@ //! errors random errors in the transmission have a probabilty of 2**-6 = 0.015625 of matching the original messages CRC code. //! Meaning the chance of errors going undetected is <2%. +const U26_VALUE_MASK: u32 = 0xFFFFFFc0; +const U26_MAX_VALUE: u32 = 0x03FFFFFF; + +pub enum U26Error { + Overflow +} #[derive(Debug)] /// this type is used for storing data on memory devices the concern here is mostly protecting against memory corruption @@ -56,6 +62,24 @@ /// | 26 bits u26 value | 5 hemming bits | 1 unused extrabit | pub struct Stored_U26(u32); +impl From for u32 { + fn from(value: Stored_U26) -> Self { + value.0 & U26_VALUE_MASK >> 6 + } +} + +impl TryFrom for Stored_U26 { + type Error = U26Error; + + fn try_from(value: u32) -> Result { + if value > U26_MAX_VALUE { + Err(U26Error::Overflow) + } else { + todo!() + } + } +} + #[derive(Debug)] /// this type is used for transmitting data, the concern here is protection against transmission errors which most likely occur /// as burst errors effecting multiple bits, hemming codes would be a waist of space here so instead a 6 bit crc code is used @@ -64,6 +88,24 @@ pub struct Stored_U26(u32); /// | 26 bits u26 value | 6 bits crc value | pub struct Transit_U26(u32); +impl From for u32 { + fn from(value: Transit_U26) -> Self { + value.0 & U26_VALUE_MASK >> 6 + } +} + +impl TryFrom for Transit_U26 { + type Error = U26Error; + + fn try_from(value: u32) -> Result { + if value > U26_MAX_VALUE { + Err(U26Error::Overflow) + } else { + todo!() + } + } +} + // only calc hemming code for the first 24 data bits including the 5 hemming bits // pos | | p1 | p2 | p3 | p4 | p5 | // 00001 | p1 | o | | | | | @@ -182,7 +224,6 @@ fn calc_hemming(data_bits: u32) -> u8 { 0x00 | (p1 as u8) << 0 | (p2 as u8) << 1 | (p3 as u8) << 2 | (p4 as u8) << 3 | (p5 as u8) << 5 } - #[cfg(test)] mod base_type_tests { use super::calc_hemming;