knx_rust/dpt/
mod.rs

1mod float_16;
2mod unsigned_8;
3
4pub use crate::dpt::float_16::{*};
5pub use crate::dpt::unsigned_8::{*};
6
7use std::fmt::{Display, Formatter};
8use byteorder::{BigEndian, ByteOrder};
9use crate::knxnet::KnxNetIpError;
10
11
12pub trait DPT{
13    fn encode(&self, buf: &mut Vec<u8>);
14    fn decode(&mut self, buf: &[u8]) -> Result<(), KnxNetIpError> where Self: Sized;
15    fn bit_len(&self) -> u16;
16    fn unit(&self) -> &str {""}
17}
18
19impl DPT for Vec<u8> {
20    fn encode(&self, buf: &mut Vec<u8>) {
21        buf.extend(self)
22    }
23
24    fn decode(&mut self,buf: &[u8]) -> Result<(), KnxNetIpError> {
25        self.clear();
26        if buf.len() > 1 {
27            self.extend_from_slice(&buf[1..]);
28        } else if buf.len() == 1{
29            self.push(buf[0] & 0x3F)
30        }
31        Ok(())
32    }
33
34    fn bit_len(&self) -> u16 {
35        8 * self.len() as u16
36    }
37}
38
39impl DPT for bool {
40    fn encode(&self, buf: &mut Vec<u8>) {
41        buf.push(*self as u8)
42    }
43
44    fn decode(&mut self,buf: &[u8]) -> Result<(), KnxNetIpError> {
45        if buf.len() < 1 {
46            return Err(KnxNetIpError::MessageTooShort(buf.len()))
47        }
48        *self = buf[0] & 0x1 > 0;
49        return Ok(())
50    }
51
52    fn bit_len(&self) -> u16 {
53        1
54    }
55}
56
57impl DPT for () {
58    fn encode(&self, buf: &mut Vec<u8>) {
59    }
60
61    fn decode(&mut self,buf: &[u8]) -> Result<(), KnxNetIpError> where Self: Sized {
62        Ok(())
63    }
64
65    fn bit_len(&self) -> u16 {
66        return 0
67    }
68}
69
70impl DPT for u16 {
71    fn encode(&self, buf: &mut Vec<u8>) {
72        buf.extend_from_slice(&self.to_be_bytes());
73    }
74
75    fn decode(&mut self, buf: &[u8]) -> Result<(), KnxNetIpError> where Self: Sized {
76        if buf.len() < 2 {
77            return Err(KnxNetIpError::MessageTooShort(buf.len()))
78        }
79        *self = BigEndian::read_u16(&buf[0..2]);
80        Ok(())
81    }
82
83    fn bit_len(&self) -> u16 {
84        16
85    }
86}
87
88
89