Skip to main content

dlms_cosem_kit/xdlms/
notify.rs

1//! Push: the notification services.
2
3use 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/// A date-time carried as an octet string that may be empty.
9///
10/// The notification services do not use the A-XDR `OPTIONAL` flag for their timestamp:
11/// they send a zero-length octet string when there is none. A decoder that assumes
12/// twelve bytes reads the notification body as a date.
13#[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/// An unsolicited value sent by the server — the push service.
43///
44/// This is what a meter's customer interface emits: a `DataNotification` whose body is
45/// a structure of the objects listed in its push setup. It is usually the only APDU a
46/// listener ever sees, and it is usually ciphered.
47#[derive(Debug, Clone, Copy, PartialEq)]
48pub struct DataNotification<'a> {
49    /// Identifies the notification; the confirmed variant expects it echoed back.
50    pub long_invoke_id: LongInvokeId,
51    /// When the values were captured, if the meter said.
52    pub date_time: OptionalDateTime,
53    /// The values.
54    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/// An unsolicited attribute value, named by its descriptor.
76#[derive(Debug, Clone, Copy, PartialEq)]
77pub struct EventNotification<'a> {
78    /// When it happened, if the meter said.
79    pub time: Option<DateTime>,
80    /// Which attribute changed.
81    pub descriptor: AttributeDescriptor,
82    /// Its value.
83    pub value: Data<'a>,
84}
85
86/// A date-time wrapped so it encodes as a length-prefixed octet string.
87#[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}