Skip to main content

spodes_rs/classes/
register_monitor.rs

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