dlms_cosem_kit/xdlms/
notify.rs1use crate::axdr::{Data, DateTime};
4use crate::codec::{Decode, Encode, ErrorKind, Reader, Result, Writer};
5
6use super::descriptor::{AttributeDescriptor, LongInvokeId, decode_optional, encode_optional};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub struct OptionalDateTime(pub Option<DateTime>);
15
16impl Encode for OptionalDateTime {
17 fn encode(&self, w: &mut dyn Writer) -> Result<()> {
18 match self.0 {
19 None => w.write_length(0),
20 Some(dt) => w.write_length_prefixed(&dt.to_bytes()),
21 }
22 }
23
24 fn encoded_len(&self) -> usize {
25 if self.0.is_some() { 13 } else { 1 }
26 }
27}
28
29impl<'a> Decode<'a> for OptionalDateTime {
30 fn decode(r: &mut Reader<'a>) -> Result<Self> {
31 let bytes = r.length_prefixed()?;
32 match bytes.len() {
33 0 => Ok(Self(None)),
34 12 => Ok(Self(Some(DateTime::from_bytes(
35 bytes.try_into().map_err(|_| r.err(ErrorKind::InvalidLength))?,
36 )))),
37 _ => Err(r.err(ErrorKind::InvalidLength)),
38 }
39 }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq)]
48pub struct DataNotification<'a> {
49 pub long_invoke_id: LongInvokeId,
51 pub date_time: OptionalDateTime,
53 pub body: Data<'a>,
55}
56
57impl Encode for DataNotification<'_> {
58 fn encode(&self, w: &mut dyn Writer) -> Result<()> {
59 w.write_u32(self.long_invoke_id.0)?;
60 self.date_time.encode(w)?;
61 self.body.encode(w)
62 }
63}
64
65impl<'a> Decode<'a> for DataNotification<'a> {
66 fn decode(r: &mut Reader<'a>) -> Result<Self> {
67 Ok(Self {
68 long_invoke_id: LongInvokeId(r.u32()?),
69 date_time: OptionalDateTime::decode(r)?,
70 body: Data::decode(r)?,
71 })
72 }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq)]
77pub struct EventNotification<'a> {
78 pub time: Option<DateTime>,
80 pub descriptor: AttributeDescriptor,
82 pub value: Data<'a>,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88struct DateTimeOctets(DateTime);
89
90impl Encode for DateTimeOctets {
91 fn encode(&self, w: &mut dyn Writer) -> Result<()> {
92 w.write_length_prefixed(&self.0.to_bytes())
93 }
94}
95
96impl<'a> Decode<'a> for DateTimeOctets {
97 fn decode(r: &mut Reader<'a>) -> Result<Self> {
98 let bytes = r.length_prefixed()?;
99 let arr: [u8; 12] = bytes.try_into().map_err(|_| r.err(ErrorKind::InvalidLength))?;
100 Ok(Self(DateTime::from_bytes(arr)))
101 }
102}
103
104impl Encode for EventNotification<'_> {
105 fn encode(&self, w: &mut dyn Writer) -> Result<()> {
106 encode_optional(w, self.time.map(DateTimeOctets).as_ref())?;
107 self.descriptor.encode(w)?;
108 self.value.encode(w)
109 }
110}
111
112impl<'a> Decode<'a> for EventNotification<'a> {
113 fn decode(r: &mut Reader<'a>) -> Result<Self> {
114 let time = decode_optional::<DateTimeOctets>(r)?.map(|d| d.0);
115 Ok(Self { time, descriptor: AttributeDescriptor::decode(r)?, value: Data::decode(r)? })
116 }
117}