Skip to main content

fennec_modbus/contrib/
types.rs

1use bytes::{Buf, BufMut};
2
3use crate::{
4    Error,
5    protocol::codec::{BitSize, Decode, Encode},
6};
7
8// TODO: make endianness a type parameter.
9macro_rules! impl_new_type {
10    ($target:ident => $inner:ty) => {
11        impl BitSize for $target<$inner> {
12            const N_BITS: u16 = <$inner as BitSize>::N_BITS;
13            const N_BYTES: u8 = <$inner as BitSize>::N_BYTES;
14            const N_WORDS: u16 = <$inner as BitSize>::N_WORDS;
15        }
16
17        impl Decode for $target<$inner> {
18            fn decode_from(buf: &mut impl Buf) -> Result<Self, Error> {
19                <$inner>::decode_from(buf).map(Self)
20            }
21        }
22
23        impl Encode for $target<$inner> {
24            fn encode_to(&self, buf: &mut impl BufMut) {
25                self.0.encode_to(buf);
26            }
27        }
28    };
29}
30
31#[derive(Copy, Clone, Debug, Eq, PartialEq)]
32pub struct Percentage<T>(pub T);
33
34impl_new_type!(Percentage => u16);
35
36/// [Decawatt][1]-hours, 1 daWh is equal to 10 [Wh][2].
37///
38/// [1]: https://en.wiktionary.org/wiki/decawatt
39/// [2]: https://en.wiktionary.org/wiki/watt-hour
40#[derive(Copy, Clone, Debug, Eq, PartialEq)]
41pub struct DecawattHours<T>(pub T);
42
43impl_new_type!(DecawattHours => u16);
44impl_new_type!(DecawattHours => u32);
45
46#[derive(Copy, Clone, Debug, Eq, PartialEq)]
47pub struct Watts<T>(pub T);
48
49impl_new_type!(Watts => u16);
50impl_new_type!(Watts => i32);