Skip to main content

spodes_rs/classes/
parameter_monitor.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::ValueDefinition;
4use crate::types::{BerError, CosemDataType};
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7
8/// Configuration structure used to build a [`ParameterMonitor`] object.
9#[derive(Clone, Serialize, Deserialize, Debug)]
10pub struct ParameterMonitorConfig {
11    /// Attribute 1: the object's logical name (OBIS code).
12    pub logical_name: ObisCode,
13    /// Attribute 2: `value_definition` of the monitored attribute.
14    pub monitored_value: ValueDefinition,
15    /// Attribute 3: thresholds structure applied to the monitored value.
16    pub thresholds: CosemDataType,
17    /// Attribute 4: array of recorded monitoring events.
18    pub events: Vec<CosemDataType>,
19    /// Attribute 5: minimal duration (seconds) before an event is recorded.
20    pub minimal_duration: u32,
21}
22
23/// `Parameter monitor` interface class (class_id = 65, version = 0) per
24/// IEC 62056-6-2 §4.5.10. Monitors an attribute of a referenced object against
25/// the thresholds and records crossing events.
26///
27/// This class defines no specific methods.
28#[derive(Clone, Serialize, Deserialize, Debug)]
29pub struct ParameterMonitor {
30    logical_name: ObisCode,
31    monitored_value: ValueDefinition,
32    thresholds: CosemDataType,
33    events: Vec<CosemDataType>,
34    minimal_duration: u32,
35}
36
37impl ParameterMonitor {
38    /// Builds a new [`ParameterMonitor`] from its configuration.
39    pub fn new(config: ParameterMonitorConfig) -> Self {
40        ParameterMonitor {
41            logical_name: config.logical_name,
42            monitored_value: config.monitored_value,
43            thresholds: config.thresholds,
44            events: config.events,
45            minimal_duration: config.minimal_duration,
46        }
47    }
48
49    /// Records a monitoring event (host-driven).
50    pub fn record_event(&mut self, event: CosemDataType) {
51        self.events.push(event);
52    }
53
54    /// Returns the recorded events (attribute 4).
55    pub fn events(&self) -> &[CosemDataType] {
56        &self.events
57    }
58}
59
60impl InterfaceClass for ParameterMonitor {
61    fn class_id(&self) -> u16 {
62        65
63    }
64
65    fn version(&self) -> u8 {
66        0
67    }
68
69    fn logical_name(&self) -> &ObisCode {
70        &self.logical_name
71    }
72
73    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
74        vec![
75            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
76            (2, self.monitored_value.clone().into()),
77            (3, self.thresholds.clone()),
78            (4, CosemDataType::Array(self.events.clone())),
79            (5, CosemDataType::DoubleLongUnsigned(self.minimal_duration)),
80        ]
81    }
82
83    fn methods(&self) -> Vec<(u8, String)> {
84        // The parameter monitor class defines no specific methods.
85        vec![]
86    }
87
88    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
89        let mut seq_buf = Vec::new();
90        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
91        for (_, attr) in self.attributes() {
92            attr.serialize_ber(&mut seq_buf)?;
93        }
94        buf.push(0x02); // structure [2]
95        write_length(1 + self.attributes().len(), buf);
96        buf.extend_from_slice(&seq_buf);
97        Ok(())
98    }
99
100    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
101        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
102        if !rest.is_empty() {
103            return Err(BerError::InvalidTag);
104        }
105        let CosemDataType::Structure(seq) = tlv else {
106            return Err(BerError::InvalidTag);
107        };
108        if seq.len() != 6 {
109            return Err(BerError::InvalidLength);
110        }
111        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
112            if class_id != self.class_id() {
113                return Err(BerError::InvalidValue);
114            }
115        } else {
116            return Err(BerError::InvalidTag);
117        }
118        if let CosemDataType::OctetString(obis) = &seq[1] {
119            if obis.len() == 6 {
120                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
121            } else {
122                return Err(BerError::InvalidLength);
123            }
124        } else {
125            return Err(BerError::InvalidTag);
126        }
127        self.monitored_value = ValueDefinition::try_from(&seq[2]).map_err(|_| BerError::InvalidValue)?;
128        self.thresholds = seq[3].clone();
129        self.events = match &seq[4] {
130            CosemDataType::Array(v) => v.clone(),
131            _ => return Err(BerError::InvalidTag),
132        };
133        self.minimal_duration = match seq[5] {
134            CosemDataType::DoubleLongUnsigned(v) => v,
135            _ => return Err(BerError::InvalidTag),
136        };
137        Ok(())
138    }
139
140    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
141        Err(format!("Method {method_id} not supported for Parameter monitor (no specific methods)"))
142    }
143
144    fn as_any(&self) -> &dyn Any {
145        self
146    }
147}
148
149/// Writes a BER length octet (short or long form).
150#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
151fn write_length(length: usize, buf: &mut Vec<u8>) {
152    if length < 128 {
153        buf.push(length as u8);
154    } else {
155        let bytes = (length as u64).to_be_bytes();
156        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
157        let num_octets = 8 - first_non_zero;
158        buf.push(0x80 | num_octets as u8);
159        buf.extend_from_slice(&bytes[first_non_zero..]);
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    fn sample() -> ParameterMonitor {
168        ParameterMonitor::new(ParameterMonitorConfig {
169            logical_name: ObisCode::new(0, 0, 16, 2, 0, 255),
170            monitored_value: ValueDefinition {
171                class_id: 3,
172                logical_name: ObisCode::new(1, 0, 12, 7, 0, 255),
173                attribute_index: 2,
174            },
175            thresholds: CosemDataType::Structure(vec![
176                CosemDataType::DoubleLongUnsigned(207_000),
177                CosemDataType::DoubleLongUnsigned(253_000),
178            ]),
179            events: vec![],
180            minimal_duration: 60,
181        })
182    }
183
184    #[test]
185    fn class_id_and_attributes() {
186        let obj = sample();
187        assert_eq!(obj.class_id(), 65);
188        assert_eq!(obj.attributes().len(), 5);
189        assert!(obj.methods().is_empty());
190    }
191
192    #[test]
193    fn round_trip() {
194        let mut obj = sample();
195        obj.record_event(CosemDataType::Structure(vec![
196            CosemDataType::Unsigned(1),
197            CosemDataType::DoubleLongUnsigned(260_000),
198        ]));
199        let mut buf = Vec::new();
200        obj.serialize_ber(&mut buf).unwrap();
201        let mut decoded = sample();
202        decoded.deserialize_ber(&buf).unwrap();
203        assert_eq!(decoded.attributes(), obj.attributes());
204        assert_eq!(decoded.events().len(), 1);
205    }
206}