Skip to main content

spodes_rs/service/
notification.rs

1//! Unsolicited notification services (IEC 62056-5-3): the server-initiated
2//! EVENT-NOTIFICATION and DATA-NOTIFICATION APDUs.
3//!
4//! Both are unconfirmed: the server pushes them to the client without a prior
5//! request. EVENT-NOTIFICATION (`[194]`, tag 0xC2) reports a single attribute
6//! change; DATA-NOTIFICATION (`[15]`, tag 0x0F) carries an arbitrary push body
7//! (see the Push setup class, IC 40).
8
9use crate::types::CosemDataType;
10
11use super::{push_length, read_length, tag, AttributeDescriptor, ServiceError};
12
13/// An EVENT-NOTIFICATION-REQUEST APDU: an unsolicited report that one attribute
14/// of one object has taken a new value.
15#[derive(Debug, Clone, PartialEq)]
16pub struct EventNotificationRequest {
17    /// Optional event time, as a date-time octet-string.
18    pub time: Option<Vec<u8>>,
19    /// The attribute that changed.
20    pub attribute: AttributeDescriptor,
21    /// The new attribute value.
22    pub value: CosemDataType,
23}
24
25impl EventNotificationRequest {
26    /// Encodes the APDU.
27    pub fn encode(&self) -> Result<Vec<u8>, ServiceError> {
28        let mut buf = vec![tag::EVENT_NOTIFICATION_REQUEST];
29        match &self.time {
30            None => buf.push(0x00),
31            Some(t) => {
32                buf.push(0x01);
33                push_length(t.len(), &mut buf);
34                buf.extend_from_slice(t);
35            }
36        }
37        self.attribute.encode(&mut buf);
38        self.value.serialize_ber(&mut buf)?;
39        Ok(buf)
40    }
41
42    /// Decodes the APDU.
43    pub fn decode(bytes: &[u8]) -> Result<EventNotificationRequest, ServiceError> {
44        if bytes.first() != Some(&tag::EVENT_NOTIFICATION_REQUEST) {
45            return Err(ServiceError::UnexpectedTag(*bytes.first().unwrap_or(&0)));
46        }
47        let (time, mut pos) = match bytes.get(1) {
48            Some(0x00) => (None, 2),
49            Some(0x01) => {
50                let (len, header) = read_length(&bytes[2..])?;
51                let start = 2 + header;
52                let t = bytes.get(start..start + len).ok_or(ServiceError::Truncated)?.to_vec();
53                (Some(t), start + len)
54            }
55            Some(&other) => return Err(ServiceError::UnexpectedType(other)),
56            None => return Err(ServiceError::Truncated),
57        };
58        let (attribute, n) = AttributeDescriptor::decode(&bytes[pos..])?;
59        pos += n;
60        let (value, _) = CosemDataType::deserialize_ber(&bytes[pos..])?;
61        Ok(EventNotificationRequest { time, attribute, value })
62    }
63}
64
65/// A DATA-NOTIFICATION APDU: an unsolicited push carrying an arbitrary body.
66#[derive(Debug, Clone, PartialEq)]
67pub struct DataNotification {
68    /// Long-Invoke-Id-And-Priority (32-bit): identifies this push invocation.
69    pub long_invoke_id_and_priority: u32,
70    /// Date-time octet-string; empty (zero length) when not transmitted.
71    pub date_time: Vec<u8>,
72    /// The notification body (the push data).
73    pub notification_body: CosemDataType,
74}
75
76impl DataNotification {
77    /// Encodes the APDU.
78    pub fn encode(&self) -> Result<Vec<u8>, ServiceError> {
79        let mut buf = vec![tag::DATA_NOTIFICATION];
80        buf.extend_from_slice(&self.long_invoke_id_and_priority.to_be_bytes());
81        push_length(self.date_time.len(), &mut buf);
82        buf.extend_from_slice(&self.date_time);
83        self.notification_body.serialize_ber(&mut buf)?;
84        Ok(buf)
85    }
86
87    /// Decodes the APDU.
88    pub fn decode(bytes: &[u8]) -> Result<DataNotification, ServiceError> {
89        if bytes.first() != Some(&tag::DATA_NOTIFICATION) {
90            return Err(ServiceError::UnexpectedTag(*bytes.first().unwrap_or(&0)));
91        }
92        let b = bytes.get(1..5).ok_or(ServiceError::Truncated)?;
93        let long_invoke_id_and_priority = u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
94        let (len, header) = read_length(&bytes[5..])?;
95        let start = 5 + header;
96        let date_time = bytes.get(start..start + len).ok_or(ServiceError::Truncated)?.to_vec();
97        let (notification_body, _) = CosemDataType::deserialize_ber(&bytes[start + len..])?;
98        Ok(DataNotification { long_invoke_id_and_priority, date_time, notification_body })
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use crate::obis::ObisCode;
106
107    #[test]
108    fn event_notification_without_time_round_trips() {
109        let ev = EventNotificationRequest {
110            time: None,
111            attribute: AttributeDescriptor::new(1, ObisCode::new(0, 0, 96, 11, 0, 255), 2),
112            value: CosemDataType::LongUnsigned(0x0007),
113        };
114        let bytes = ev.encode().unwrap();
115        // C2 00 <attr 9> <12 0007>.
116        assert_eq!(bytes[..2], [0xC2, 0x00]);
117        assert_eq!(bytes[11..], [0x12, 0x00, 0x07]);
118        assert_eq!(EventNotificationRequest::decode(&bytes).unwrap(), ev);
119    }
120
121    #[test]
122    fn event_notification_with_time_round_trips() {
123        let ev = EventNotificationRequest {
124            time: Some(vec![0x07, 0xE6, 0x07, 0x04, 0x06, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
125            attribute: AttributeDescriptor::new(8, ObisCode::new(0, 0, 1, 0, 0, 255), 2),
126            value: CosemDataType::Unsigned(1),
127        };
128        let bytes = ev.encode().unwrap();
129        assert_eq!(bytes[..2], [0xC2, 0x01]);
130        assert_eq!(EventNotificationRequest::decode(&bytes).unwrap(), ev);
131    }
132
133    #[test]
134    fn data_notification_round_trips() {
135        let dn = DataNotification {
136            long_invoke_id_and_priority: 0x0000_0001,
137            date_time: Vec::new(),
138            notification_body: CosemDataType::Structure(vec![
139                CosemDataType::LongUnsigned(0x1234),
140                CosemDataType::Unsigned(9),
141            ]),
142        };
143        let bytes = dn.encode().unwrap();
144        // 0F 00000001 00 <02 02 <12 1234> <11 09>>.
145        assert_eq!(bytes[..6], [0x0F, 0x00, 0x00, 0x00, 0x01, 0x00]);
146        assert_eq!(DataNotification::decode(&bytes).unwrap(), dn);
147    }
148}