Skip to main content

spodes_rs/classes/
limiter.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::{EmergencyProfile, LimiterAction, ValueDefinition};
4use crate::types::{BerError, CosemDataType};
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7
8/// Configuration structure used to build a [`Limiter`] object.
9#[derive(Clone, Serialize, Deserialize, Debug)]
10pub struct LimiterConfig {
11    /// Attribute 1: the object's logical name (OBIS code).
12    pub logical_name: ObisCode,
13    /// Attribute 2: `value_definition` structure { class_id, logical_name, attribute_index }.
14    pub monitored_value: ValueDefinition,
15    /// Attribute 3: active threshold (same type as the monitored attribute).
16    pub threshold_active: CosemDataType,
17    /// Attribute 4: threshold used during normal operation.
18    pub threshold_normal: CosemDataType,
19    /// Attribute 5: threshold used while an emergency profile is active.
20    pub threshold_emergency: CosemDataType,
21    /// Attribute 6: minimal over-threshold duration in seconds.
22    pub min_over_threshold_duration: u32,
23    /// Attribute 7: minimal under-threshold duration in seconds.
24    pub min_under_threshold_duration: u32,
25    /// Attribute 8: `emergency_profile` structure { id, activation_time, duration }.
26    pub emergency_profile: EmergencyProfile,
27    /// Attribute 9: array of emergency profile group ids.
28    pub emergency_profile_group_id_list: Vec<u16>,
29    /// Attribute 10: whether an emergency profile is currently active.
30    pub emergency_profile_active: bool,
31    /// Attribute 11: `action` structure of over/under-threshold scripts.
32    pub actions: LimiterAction,
33}
34
35/// `Limiter` interface class (class_id = 71, version = 0) per IEC 62056-6-2
36/// §4.5.9. Monitors a value attribute of another object and triggers actions
37/// when it crosses the active threshold for at least the minimal duration.
38///
39/// This class defines no specific methods.
40#[derive(Clone, Serialize, Deserialize, Debug)]
41pub struct Limiter {
42    logical_name: ObisCode,
43    monitored_value: ValueDefinition,
44    threshold_active: CosemDataType,
45    threshold_normal: CosemDataType,
46    threshold_emergency: CosemDataType,
47    min_over_threshold_duration: u32,
48    min_under_threshold_duration: u32,
49    emergency_profile: EmergencyProfile,
50    emergency_profile_group_id_list: Vec<u16>,
51    emergency_profile_active: bool,
52    actions: LimiterAction,
53}
54
55impl Limiter {
56    /// Builds a new [`Limiter`] from its configuration.
57    pub fn new(config: LimiterConfig) -> Self {
58        Limiter {
59            logical_name: config.logical_name,
60            monitored_value: config.monitored_value,
61            threshold_active: config.threshold_active,
62            threshold_normal: config.threshold_normal,
63            threshold_emergency: config.threshold_emergency,
64            min_over_threshold_duration: config.min_over_threshold_duration,
65            min_under_threshold_duration: config.min_under_threshold_duration,
66            emergency_profile: config.emergency_profile,
67            emergency_profile_group_id_list: config.emergency_profile_group_id_list,
68            emergency_profile_active: config.emergency_profile_active,
69            actions: config.actions,
70        }
71    }
72}
73
74impl InterfaceClass for Limiter {
75    fn class_id(&self) -> u16 {
76        71
77    }
78
79    fn version(&self) -> u8 {
80        0
81    }
82
83    fn logical_name(&self) -> &ObisCode {
84        &self.logical_name
85    }
86
87    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
88        vec![
89            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
90            (2, CosemDataType::from(self.monitored_value.clone())),
91            (3, self.threshold_active.clone()),
92            (4, self.threshold_normal.clone()),
93            (5, self.threshold_emergency.clone()),
94            (6, CosemDataType::DoubleLongUnsigned(self.min_over_threshold_duration)),
95            (7, CosemDataType::DoubleLongUnsigned(self.min_under_threshold_duration)),
96            (8, CosemDataType::from(self.emergency_profile.clone())),
97            (
98                9,
99                CosemDataType::Array(
100                    self.emergency_profile_group_id_list.iter().map(|id| CosemDataType::LongUnsigned(*id)).collect(),
101                ),
102            ),
103            (10, CosemDataType::Boolean(self.emergency_profile_active)),
104            (11, CosemDataType::from(self.actions.clone())),
105        ]
106    }
107
108    fn methods(&self) -> Vec<(u8, String)> {
109        // The Limiter class defines no specific methods.
110        vec![]
111    }
112
113    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
114        let mut seq_buf = Vec::new();
115        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
116        for (_, attr) in self.attributes() {
117            attr.serialize_ber(&mut seq_buf)?;
118        }
119        buf.push(0x02); // structure [2]
120        write_length(1 + self.attributes().len(), buf); // length = element count
121        buf.extend_from_slice(&seq_buf);
122        Ok(())
123    }
124
125    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
126        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
127        if !rest.is_empty() {
128            return Err(BerError::InvalidTag);
129        }
130        let CosemDataType::Structure(seq) = tlv else {
131            return Err(BerError::InvalidTag);
132        };
133        // class_id + 11 attributes.
134        if seq.len() != 12 {
135            return Err(BerError::InvalidLength);
136        }
137        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
138            if class_id != self.class_id() {
139                return Err(BerError::InvalidValue);
140            }
141        } else {
142            return Err(BerError::InvalidTag);
143        }
144        if let CosemDataType::OctetString(obis) = &seq[1] {
145            if obis.len() == 6 {
146                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
147            } else {
148                return Err(BerError::InvalidLength);
149            }
150        } else {
151            return Err(BerError::InvalidTag);
152        }
153        self.monitored_value = ValueDefinition::try_from(&seq[2]).map_err(|_| BerError::InvalidValue)?;
154        self.threshold_active = seq[3].clone();
155        self.threshold_normal = seq[4].clone();
156        self.threshold_emergency = seq[5].clone();
157        self.min_over_threshold_duration = match seq[6] {
158            CosemDataType::DoubleLongUnsigned(v) => v,
159            _ => return Err(BerError::InvalidTag),
160        };
161        self.min_under_threshold_duration = match seq[7] {
162            CosemDataType::DoubleLongUnsigned(v) => v,
163            _ => return Err(BerError::InvalidTag),
164        };
165        self.emergency_profile = EmergencyProfile::try_from(&seq[8]).map_err(|_| BerError::InvalidValue)?;
166        self.emergency_profile_group_id_list = match &seq[9] {
167            CosemDataType::Array(list) => list
168                .iter()
169                .map(|e| match e {
170                    CosemDataType::LongUnsigned(v) => Ok(*v),
171                    _ => Err(BerError::InvalidTag),
172                })
173                .collect::<Result<Vec<_>, _>>()?,
174            _ => return Err(BerError::InvalidTag),
175        };
176        self.emergency_profile_active = match seq[10] {
177            CosemDataType::Boolean(v) => v,
178            _ => return Err(BerError::InvalidTag),
179        };
180        self.actions = LimiterAction::try_from(&seq[11]).map_err(|_| BerError::InvalidValue)?;
181        Ok(())
182    }
183
184    fn set_attribute(&mut self, attribute_id: u8, value: CosemDataType) -> Result<(), String> {
185        match attribute_id {
186            2 => {
187                self.monitored_value = ValueDefinition::try_from(&value)?;
188                Ok(())
189            }
190            3 => {
191                self.threshold_active = value;
192                Ok(())
193            }
194            4 => {
195                self.threshold_normal = value;
196                Ok(())
197            }
198            5 => {
199                self.threshold_emergency = value;
200                Ok(())
201            }
202            6 => match value {
203                CosemDataType::DoubleLongUnsigned(v) => {
204                    self.min_over_threshold_duration = v;
205                    Ok(())
206                }
207                _ => Err("min_over_threshold_duration must be double-long-unsigned".into()),
208            },
209            7 => match value {
210                CosemDataType::DoubleLongUnsigned(v) => {
211                    self.min_under_threshold_duration = v;
212                    Ok(())
213                }
214                _ => Err("min_under_threshold_duration must be double-long-unsigned".into()),
215            },
216            8 => {
217                self.emergency_profile = EmergencyProfile::try_from(&value)?;
218                Ok(())
219            }
220            9 => {
221                let CosemDataType::Array(list) = value else {
222                    return Err("emergency_profile_group_id_list must be array".into());
223                };
224                self.emergency_profile_group_id_list = list
225                    .iter()
226                    .map(|e| match e {
227                        CosemDataType::LongUnsigned(v) => Ok(*v),
228                        _ => Err("group id must be long-unsigned".into()),
229                    })
230                    .collect::<Result<Vec<_>, String>>()?;
231                Ok(())
232            }
233            10 => match value {
234                CosemDataType::Boolean(v) => {
235                    self.emergency_profile_active = v;
236                    Ok(())
237                }
238                _ => Err("emergency_profile_active must be boolean".into()),
239            },
240            11 => {
241                self.actions = LimiterAction::try_from(&value)?;
242                Ok(())
243            }
244            _ => Err(format!("Limiter attribute {attribute_id} is not writable")),
245        }
246    }
247
248    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
249        Err(format!("Method {method_id} not supported for Limiter (no specific methods)"))
250    }
251
252    fn as_any(&self) -> &dyn Any {
253        self
254    }
255}
256
257/// Writes a BER length octet (short or long form).
258#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
259fn write_length(length: usize, buf: &mut Vec<u8>) {
260    if length < 128 {
261        buf.push(length as u8);
262    } else {
263        let bytes = (length as u64).to_be_bytes();
264        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
265        let num_octets = 8 - first_non_zero;
266        buf.push(0x80 | num_octets as u8);
267        buf.extend_from_slice(&bytes[first_non_zero..]);
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    fn sample() -> Limiter {
276        use crate::types::attrs::ActionItem;
277        Limiter::new(LimiterConfig {
278            logical_name: ObisCode::new(0, 0, 17, 0, 0, 255),
279            monitored_value: ValueDefinition {
280                class_id: 3,
281                logical_name: ObisCode::new(1, 0, 1, 7, 0, 255),
282                attribute_index: 2,
283            },
284            threshold_active: CosemDataType::LongUnsigned(5000),
285            threshold_normal: CosemDataType::LongUnsigned(5000),
286            threshold_emergency: CosemDataType::LongUnsigned(8000),
287            min_over_threshold_duration: 60,
288            min_under_threshold_duration: 120,
289            emergency_profile: EmergencyProfile {
290                emergency_profile_id: 1,
291                emergency_activation_time: vec![0; 12],
292                emergency_duration: 3600,
293            },
294            emergency_profile_group_id_list: vec![1],
295            emergency_profile_active: false,
296            actions: LimiterAction {
297                action_over_threshold: ActionItem {
298                    script_logical_name: ObisCode::new(0, 0, 10, 0, 1, 255),
299                    script_selector: 1,
300                },
301                action_under_threshold: ActionItem {
302                    script_logical_name: ObisCode::new(0, 0, 10, 0, 1, 255),
303                    script_selector: 2,
304                },
305            },
306        })
307    }
308
309    #[test]
310    fn class_id_and_attributes() {
311        let obj = sample();
312        assert_eq!(obj.class_id(), 71);
313        assert_eq!(obj.version(), 0);
314        assert_eq!(obj.attributes().len(), 11);
315        assert!(obj.methods().is_empty());
316    }
317
318    #[test]
319    fn round_trip() {
320        let obj = sample();
321        let mut buf = Vec::new();
322        obj.serialize_ber(&mut buf).unwrap();
323        let mut decoded = Limiter::new(LimiterConfig {
324            logical_name: ObisCode::new(0, 0, 0, 0, 0, 0),
325            monitored_value: ValueDefinition {
326                class_id: 0,
327                logical_name: ObisCode::new(0, 0, 0, 0, 0, 0),
328                attribute_index: 0,
329            },
330            threshold_active: CosemDataType::Null,
331            threshold_normal: CosemDataType::Null,
332            threshold_emergency: CosemDataType::Null,
333            min_over_threshold_duration: 0,
334            min_under_threshold_duration: 0,
335            emergency_profile: EmergencyProfile {
336                emergency_profile_id: 0,
337                emergency_activation_time: vec![],
338                emergency_duration: 0,
339            },
340            emergency_profile_group_id_list: vec![],
341            emergency_profile_active: true,
342            actions: LimiterAction {
343                action_over_threshold: crate::types::attrs::ActionItem {
344                    script_logical_name: ObisCode::new(0, 0, 0, 0, 0, 0),
345                    script_selector: 0,
346                },
347                action_under_threshold: crate::types::attrs::ActionItem {
348                    script_logical_name: ObisCode::new(0, 0, 0, 0, 0, 0),
349                    script_selector: 0,
350                },
351            },
352        });
353        decoded.deserialize_ber(&buf).unwrap();
354        assert_eq!(decoded.attributes(), obj.attributes());
355    }
356
357    #[test]
358    fn no_methods_supported() {
359        let mut obj = sample();
360        assert!(obj.invoke_method(1, None).is_err());
361    }
362}