Skip to main content

spodes_rs/classes/
push_setup.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::{
4    CaptureObjectDefinition, CommunicationWindow, ConfirmationParameters, DateTime, PushProtectionParameter,
5    SendDestinationAndMethod,
6};
7use crate::types::{BerError, CosemDataType};
8use serde::{Deserialize, Serialize};
9use std::any::Any;
10
11/// One outbound push, assembled by
12/// [`RequestDispatcher::build_push_delivery_request`](crate::server::RequestDispatcher::build_push_delivery_request):
13/// the destination and transport from attribute 3, the push client SAP and
14/// the encoded DataNotification body. The host owns the actual transmission.
15#[derive(Debug, Clone, PartialEq)]
16pub struct PushDeliveryRequest {
17    /// Destination address (from `send_destination_and_method`).
18    pub destination: Vec<u8>,
19    /// Transport service identifier (from `send_destination_and_method`).
20    pub transport_service: u8,
21    /// The push client SAP (attribute 9).
22    pub client_sap: i8,
23    /// The encoded DataNotification APDU carrying the push object values.
24    pub body: Vec<u8>,
25}
26
27/// Configuration structure used to build a [`PushSetup`] object.
28#[derive(Clone, Serialize, Deserialize, Debug)]
29pub struct PushSetupConfig {
30    /// Attribute 1: the object's logical name (OBIS code).
31    pub logical_name: ObisCode,
32    /// Class version: 0, 1 or 2. Selects which attributes and methods are exposed.
33    pub version: u8,
34    /// Attribute 2: array of `cosem_object_instance_id` entries to be pushed.
35    pub push_object_list: Vec<CaptureObjectDefinition>,
36    /// Attribute 3: `send_destination_and_method` structure.
37    pub send_destination_and_method: SendDestinationAndMethod,
38    /// Attribute 4: array of communication windows.
39    pub communication_window: Vec<CommunicationWindow>,
40    /// Attribute 5: randomisation start interval, in seconds.
41    pub randomisation_start_interval: u16,
42    /// Attribute 6: number of retries.
43    pub number_of_retries: u8,
44    /// Attribute 7 (version 2): `repetition_delay` structure.
45    pub repetition_delay: CosemDataType,
46    /// Attribute 8: reference to the communication port setup object.
47    pub port_reference: Vec<u8>,
48    /// Attribute 9: push client SAP.
49    pub push_client_sap: i8,
50    /// Attribute 10: array of push protection parameters.
51    pub push_protection_parameters: Vec<PushProtectionParameter>,
52    /// Attribute 11: push operation method (enum).
53    pub push_operation_method: u8,
54    /// Attribute 12: `confirmation_parameters` structure.
55    pub confirmation_parameters: ConfirmationParameters,
56    /// Attribute 13: date-time of the last successful confirmation.
57    pub last_confirmation_date_time: DateTime,
58}
59
60/// `Push setup` interface class (class_id = 40) per IEC 62056-6-2 §4.4.8. Holds
61/// the configuration of the server's unsolicited (push) output.
62///
63/// All three versions are supported:
64/// * version 0 — attributes 1..7, method `push`;
65/// * version 1 — attributes 1..10, method `push`;
66/// * version 2 — attributes 1..13, methods `push` and `reset`.
67///
68/// In versions 0 and 1 attribute 7 (`repetition_delay`) is a `long-unsigned`;
69/// in version 2 it is a structure. The `push` ACTION only validates that the
70/// object is triggerable; assembling and sending the actual DataNotification
71/// is done by [`RequestDispatcher::build_push_delivery_request`](crate::server::RequestDispatcher::build_push_delivery_request),
72/// which has access to the live object registry that this class does not
73/// hold.
74#[derive(Clone, Serialize, Deserialize, Debug)]
75pub struct PushSetup {
76    version: u8,
77    logical_name: ObisCode,
78    push_object_list: Vec<CaptureObjectDefinition>,
79    send_destination_and_method: SendDestinationAndMethod,
80    communication_window: Vec<CommunicationWindow>,
81    randomisation_start_interval: u16,
82    number_of_retries: u8,
83    repetition_delay: CosemDataType,
84    port_reference: Vec<u8>,
85    push_client_sap: i8,
86    push_protection_parameters: Vec<PushProtectionParameter>,
87    push_operation_method: u8,
88    confirmation_parameters: ConfirmationParameters,
89    last_confirmation_date_time: DateTime,
90}
91
92impl PushSetup {
93    /// Builds a new [`PushSetup`] from its configuration.
94    pub fn new(config: PushSetupConfig) -> Self {
95        PushSetup {
96            version: config.version,
97            logical_name: config.logical_name,
98            push_object_list: config.push_object_list,
99            send_destination_and_method: config.send_destination_and_method,
100            communication_window: config.communication_window,
101            randomisation_start_interval: config.randomisation_start_interval,
102            number_of_retries: config.number_of_retries,
103            repetition_delay: config.repetition_delay,
104            port_reference: config.port_reference,
105            push_client_sap: config.push_client_sap,
106            push_protection_parameters: config.push_protection_parameters,
107            push_operation_method: config.push_operation_method,
108            confirmation_parameters: config.confirmation_parameters,
109            last_confirmation_date_time: config.last_confirmation_date_time,
110        }
111    }
112
113    /// Method 1: `push` — triggers sending the push object list to the
114    /// destination (IEC 62056-6-2 §4.4.8.3.1). Building the notification body
115    /// requires reading the live values of the referenced objects, which this
116    /// class does not hold; use
117    /// [`RequestDispatcher::build_push_delivery_request`](crate::server::RequestDispatcher::build_push_delivery_request)
118    /// against the object registry to actually assemble and send the push. The
119    /// ACTION itself only validates that the object is triggerable.
120    fn push() -> CosemDataType {
121        CosemDataType::Null
122    }
123
124    /// Method 2: `reset` — resets the push confirmation state by clearing
125    /// `last_confirmation_date_time`.
126    fn reset(&mut self) -> CosemDataType {
127        self.last_confirmation_date_time = DateTime::from_ymdhms(1900, 1, 1, 0, 0, 0);
128        CosemDataType::Null
129    }
130
131    /// Returns the push object list (attribute 2): the objects and attribute
132    /// indices to read when assembling a push.
133    pub fn push_object_list(&self) -> &[CaptureObjectDefinition] {
134        &self.push_object_list
135    }
136
137    /// Returns the send-destination-and-method (attribute 3).
138    pub fn send_destination_and_method(&self) -> &SendDestinationAndMethod {
139        &self.send_destination_and_method
140    }
141
142    /// Returns the push client SAP (attribute 9, 0 in versions without it).
143    pub fn push_client_sap(&self) -> i8 {
144        self.push_client_sap
145    }
146}
147
148impl InterfaceClass for PushSetup {
149    fn class_id(&self) -> u16 {
150        40
151    }
152
153    fn version(&self) -> u8 {
154        self.version
155    }
156
157    fn logical_name(&self) -> &ObisCode {
158        &self.logical_name
159    }
160
161    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
162        // Attributes 1..7 are common to all versions.
163        let mut attrs = vec![
164            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
165            (2, CosemDataType::Array(self.push_object_list.iter().map(|o| CosemDataType::from(o.clone())).collect())),
166            (3, CosemDataType::from(self.send_destination_and_method.clone())),
167            (
168                4,
169                CosemDataType::Array(
170                    self.communication_window.iter().map(|cw| CosemDataType::from(cw.clone())).collect(),
171                ),
172            ),
173            (5, CosemDataType::LongUnsigned(self.randomisation_start_interval)),
174            (6, CosemDataType::Unsigned(self.number_of_retries)),
175            (7, self.repetition_delay.clone()),
176        ];
177        // Attributes 8..10 were added in version 1.
178        if self.version >= 1 {
179            attrs.push((8, CosemDataType::OctetString(self.port_reference.clone())));
180            attrs.push((9, CosemDataType::Integer(self.push_client_sap)));
181            attrs.push((
182                10,
183                CosemDataType::Array(
184                    self.push_protection_parameters.iter().map(|p| CosemDataType::from(p.clone())).collect(),
185                ),
186            ));
187        }
188        // Attributes 11..13 were added in version 2.
189        if self.version >= 2 {
190            attrs.push((11, CosemDataType::Enum(self.push_operation_method)));
191            attrs.push((12, CosemDataType::from(self.confirmation_parameters.clone())));
192            attrs.push((13, CosemDataType::from(self.last_confirmation_date_time.clone())));
193        }
194        attrs
195    }
196
197    fn methods(&self) -> Vec<(u8, String)> {
198        // `reset` was added in version 2.
199        if self.version >= 2 {
200            vec![(1, "push".to_string()), (2, "reset".to_string())]
201        } else {
202            vec![(1, "push".to_string())]
203        }
204    }
205
206    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
207        let mut seq_buf = Vec::new();
208        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
209        for (_, attr) in self.attributes() {
210            attr.serialize_ber(&mut seq_buf)?;
211        }
212        buf.push(0x02); // structure [2]
213        write_length(1 + self.attributes().len(), buf); // length = element count
214        buf.extend_from_slice(&seq_buf);
215        Ok(())
216    }
217
218    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
219        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
220        if !rest.is_empty() {
221            return Err(BerError::InvalidTag);
222        }
223        let CosemDataType::Structure(seq) = tlv else {
224            return Err(BerError::InvalidTag);
225        };
226        // The element count (class_id + attributes) identifies the version:
227        // 8 → v0, 11 → v1, 14 → v2.
228        self.version = match seq.len() {
229            8 => 0,
230            11 => 1,
231            14 => 2,
232            _ => return Err(BerError::InvalidLength),
233        };
234        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
235            if class_id != self.class_id() {
236                return Err(BerError::InvalidValue);
237            }
238        } else {
239            return Err(BerError::InvalidTag);
240        }
241        if let CosemDataType::OctetString(obis) = &seq[1] {
242            if obis.len() == 6 {
243                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
244            } else {
245                return Err(BerError::InvalidLength);
246            }
247        } else {
248            return Err(BerError::InvalidTag);
249        }
250        self.push_object_list = match &seq[2] {
251            CosemDataType::Array(list) => list
252                .iter()
253                .map(CaptureObjectDefinition::try_from)
254                .collect::<Result<Vec<_>, _>>()
255                .map_err(|_| BerError::InvalidValue)?,
256            _ => return Err(BerError::InvalidTag),
257        };
258        self.send_destination_and_method =
259            SendDestinationAndMethod::try_from(&seq[3]).map_err(|_| BerError::InvalidValue)?;
260        self.communication_window = match &seq[4] {
261            CosemDataType::Array(list) => list
262                .iter()
263                .map(CommunicationWindow::try_from)
264                .collect::<Result<Vec<_>, _>>()
265                .map_err(|_| BerError::InvalidValue)?,
266            _ => return Err(BerError::InvalidTag),
267        };
268        self.randomisation_start_interval = match seq[5] {
269            CosemDataType::LongUnsigned(v) => v,
270            _ => return Err(BerError::InvalidTag),
271        };
272        self.number_of_retries = match seq[6] {
273            CosemDataType::Unsigned(v) => v,
274            _ => return Err(BerError::InvalidTag),
275        };
276        self.repetition_delay = seq[7].clone();
277        if self.version >= 1 {
278            self.port_reference = match &seq[8] {
279                CosemDataType::OctetString(v) => v.clone(),
280                _ => return Err(BerError::InvalidTag),
281            };
282            self.push_client_sap = match seq[9] {
283                CosemDataType::Integer(v) => v,
284                _ => return Err(BerError::InvalidTag),
285            };
286            self.push_protection_parameters = match &seq[10] {
287                CosemDataType::Array(list) => list
288                    .iter()
289                    .map(PushProtectionParameter::try_from)
290                    .collect::<Result<Vec<_>, _>>()
291                    .map_err(|_| BerError::InvalidValue)?,
292                _ => return Err(BerError::InvalidTag),
293            };
294        }
295        if self.version >= 2 {
296            self.push_operation_method = match seq[11] {
297                CosemDataType::Enum(v) => v,
298                _ => return Err(BerError::InvalidTag),
299            };
300            self.confirmation_parameters =
301                ConfirmationParameters::try_from(&seq[12]).map_err(|_| BerError::InvalidValue)?;
302            self.last_confirmation_date_time = DateTime::try_from(&seq[13]).map_err(|_| BerError::InvalidValue)?;
303        }
304        Ok(())
305    }
306
307    fn set_attribute(&mut self, attribute_id: u8, value: CosemDataType) -> Result<(), String> {
308        match attribute_id {
309            2 => match value {
310                CosemDataType::Array(list) => {
311                    self.push_object_list =
312                        list.iter().map(CaptureObjectDefinition::try_from).collect::<Result<Vec<_>, _>>()?;
313                    Ok(())
314                }
315                _ => Err("push_object_list must be array".to_string()),
316            },
317            3 => {
318                self.send_destination_and_method = SendDestinationAndMethod::try_from(&value)?;
319                Ok(())
320            }
321            4 => match value {
322                CosemDataType::Array(list) => {
323                    self.communication_window =
324                        list.iter().map(CommunicationWindow::try_from).collect::<Result<Vec<_>, _>>()?;
325                    Ok(())
326                }
327                _ => Err("communication_window must be array".to_string()),
328            },
329            5 => match value {
330                CosemDataType::LongUnsigned(v) => {
331                    self.randomisation_start_interval = v;
332                    Ok(())
333                }
334                _ => Err("randomisation_start_interval must be long-unsigned".to_string()),
335            },
336            6 => match value {
337                CosemDataType::Unsigned(v) => {
338                    self.number_of_retries = v;
339                    Ok(())
340                }
341                _ => Err("number_of_retries must be unsigned".to_string()),
342            },
343            7 => {
344                self.repetition_delay = value;
345                Ok(())
346            }
347            8 if self.version >= 1 => match value {
348                CosemDataType::OctetString(v) => {
349                    self.port_reference = v;
350                    Ok(())
351                }
352                _ => Err("port_reference must be octet-string".to_string()),
353            },
354            _ => Err(format!("Attribute {} not writable for PushSetup", attribute_id)),
355        }
356    }
357
358    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
359        match method_id {
360            1 => Ok(Self::push()),
361            2 if self.version >= 2 => Ok(self.reset()),
362            _ => Err(format!("Method {} not supported for Push setup version {}", method_id, self.version)),
363        }
364    }
365
366    fn as_any(&self) -> &dyn Any {
367        self
368    }
369}
370
371/// Writes a BER length octet (short or long form).
372#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
373fn write_length(length: usize, buf: &mut Vec<u8>) {
374    if length < 128 {
375        buf.push(length as u8);
376    } else {
377        let bytes = (length as u64).to_be_bytes();
378        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
379        let num_octets = 8 - first_non_zero;
380        buf.push(0x80 | num_octets as u8);
381        buf.extend_from_slice(&bytes[first_non_zero..]);
382    }
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    fn sample_versioned(version: u8) -> PushSetup {
390        PushSetup::new(PushSetupConfig {
391            version,
392            logical_name: ObisCode::new(0, 0, 25, 9, 0, 255),
393            push_object_list: vec![CaptureObjectDefinition::new(8, ObisCode::new(0, 0, 1, 0, 0, 255), 2, 0)],
394            send_destination_and_method: SendDestinationAndMethod {
395                transport_service: 0,
396                destination: b"192.168.0.1:4059".to_vec(),
397                message: 0,
398            },
399            communication_window: vec![],
400            randomisation_start_interval: 0,
401            number_of_retries: 3,
402            repetition_delay: CosemDataType::Structure(vec![
403                CosemDataType::LongUnsigned(30),
404                CosemDataType::LongUnsigned(240),
405                CosemDataType::LongUnsigned(0),
406            ]),
407            port_reference: vec![0, 0, 25, 0, 0, 255],
408            push_client_sap: 1,
409            push_protection_parameters: vec![],
410            push_operation_method: 0,
411            confirmation_parameters: ConfirmationParameters { data: vec![] },
412            last_confirmation_date_time: DateTime::new([0u8; 12]),
413        })
414    }
415
416    #[test]
417    fn attribute_and_method_counts_per_version() {
418        let expected = [(0u8, 7usize, 1usize), (1, 10, 1), (2, 13, 2)];
419        for (version, attr_count, method_count) in expected {
420            let obj = sample_versioned(version);
421            assert_eq!(obj.class_id(), 40);
422            assert_eq!(obj.version(), version);
423            assert_eq!(obj.attributes().len(), attr_count, "attrs for v{version}");
424            assert_eq!(obj.methods().len(), method_count, "methods for v{version}");
425        }
426    }
427
428    #[test]
429    fn round_trip_all_versions() {
430        for version in 0..=2u8 {
431            let obj = sample_versioned(version);
432            let mut buf = Vec::new();
433            obj.serialize_ber(&mut buf).unwrap();
434            let mut decoded = sample_versioned(0);
435            decoded.deserialize_ber(&buf).unwrap();
436            assert_eq!(decoded.version(), version);
437            assert_eq!(decoded.attributes(), obj.attributes());
438        }
439    }
440
441    #[test]
442    fn reset_clears_confirmation() {
443        let mut obj = sample_versioned(2);
444        obj.last_confirmation_date_time = DateTime::new([0x07; 12]);
445        obj.invoke_method(2, None).unwrap();
446        assert_eq!(obj.attributes()[12].1, CosemDataType::from(DateTime::from_ymdhms(1900, 1, 1, 0, 0, 0)));
447        // `reset` is not available in versions 0 and 1.
448        let mut v1 = sample_versioned(1);
449        assert!(v1.invoke_method(2, None).is_err());
450    }
451}