Skip to main content

spodes_rs/classes/
activity_calendar.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::{DayProfile, SeasonProfile, WeekProfile};
4use crate::types::{BerError, CosemDataType};
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7
8/// Configuration structure used to build an [`ActivityCalendar`] object.
9#[derive(Clone, Serialize, Deserialize, Debug)]
10pub struct ActivityCalendarConfig {
11    /// Attribute 1: the object's logical name (OBIS code).
12    pub logical_name: ObisCode,
13    /// Attribute 2: name of the active calendar.
14    pub calendar_name_active: Vec<u8>,
15    /// Attribute 3: active season profile (array of `season` structures).
16    pub season_profile_active: Vec<SeasonProfile>,
17    /// Attribute 4: active week profile table (array).
18    pub week_profile_table_active: Vec<WeekProfile>,
19    /// Attribute 5: active day profile table (array).
20    pub day_profile_table_active: Vec<DayProfile>,
21    /// Attribute 6: name of the passive calendar.
22    pub calendar_name_passive: Vec<u8>,
23    /// Attribute 7: passive season profile (array).
24    pub season_profile_passive: Vec<SeasonProfile>,
25    /// Attribute 8: passive week profile table (array).
26    pub week_profile_table_passive: Vec<WeekProfile>,
27    /// Attribute 9: passive day profile table (array).
28    pub day_profile_table_passive: Vec<DayProfile>,
29    /// Attribute 10: date-time at which the passive calendar becomes active.
30    pub activate_passive_calendar_time: Vec<u8>,
31}
32
33/// `Activity calendar` interface class (class_id = 20, version = 0) per
34/// IEC 62056-6-2 §4.5.5. Defines the tariff schedule as an active calendar and a
35/// passive calendar that replaces it when activated.
36#[derive(Clone, Serialize, Deserialize, Debug)]
37pub struct ActivityCalendar {
38    logical_name: ObisCode,
39    calendar_name_active: Vec<u8>,
40    season_profile_active: Vec<SeasonProfile>,
41    week_profile_table_active: Vec<WeekProfile>,
42    day_profile_table_active: Vec<DayProfile>,
43    calendar_name_passive: Vec<u8>,
44    season_profile_passive: Vec<SeasonProfile>,
45    week_profile_table_passive: Vec<WeekProfile>,
46    day_profile_table_passive: Vec<DayProfile>,
47    activate_passive_calendar_time: Vec<u8>,
48}
49
50impl ActivityCalendar {
51    /// Builds a new [`ActivityCalendar`] from its configuration.
52    pub fn new(config: ActivityCalendarConfig) -> Self {
53        ActivityCalendar {
54            logical_name: config.logical_name,
55            calendar_name_active: config.calendar_name_active,
56            season_profile_active: config.season_profile_active,
57            week_profile_table_active: config.week_profile_table_active,
58            day_profile_table_active: config.day_profile_table_active,
59            calendar_name_passive: config.calendar_name_passive,
60            season_profile_passive: config.season_profile_passive,
61            week_profile_table_passive: config.week_profile_table_passive,
62            day_profile_table_passive: config.day_profile_table_passive,
63            activate_passive_calendar_time: config.activate_passive_calendar_time,
64        }
65    }
66
67    /// Method 1: `activate_passive_calendar` — copies the passive calendar over
68    /// the active one, making it effective immediately (IEC 62056-6-2 §4.5.5.3).
69    fn activate_passive_calendar(&mut self) -> CosemDataType {
70        self.calendar_name_active = self.calendar_name_passive.clone();
71        self.season_profile_active = self.season_profile_passive.clone();
72        self.week_profile_table_active = self.week_profile_table_passive.clone();
73        self.day_profile_table_active = self.day_profile_table_passive.clone();
74        CosemDataType::Null
75    }
76}
77
78impl InterfaceClass for ActivityCalendar {
79    fn class_id(&self) -> u16 {
80        20
81    }
82
83    fn version(&self) -> u8 {
84        0
85    }
86
87    fn logical_name(&self) -> &ObisCode {
88        &self.logical_name
89    }
90
91    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
92        vec![
93            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
94            (2, CosemDataType::OctetString(self.calendar_name_active.clone())),
95            (3, CosemDataType::Array(self.season_profile_active.iter().map(|s| s.clone().into()).collect())),
96            (4, CosemDataType::Array(self.week_profile_table_active.iter().map(|w| w.clone().into()).collect())),
97            (5, CosemDataType::Array(self.day_profile_table_active.iter().map(|d| d.clone().into()).collect())),
98            (6, CosemDataType::OctetString(self.calendar_name_passive.clone())),
99            (7, CosemDataType::Array(self.season_profile_passive.iter().map(|s| s.clone().into()).collect())),
100            (8, CosemDataType::Array(self.week_profile_table_passive.iter().map(|w| w.clone().into()).collect())),
101            (9, CosemDataType::Array(self.day_profile_table_passive.iter().map(|d| d.clone().into()).collect())),
102            (10, CosemDataType::OctetString(self.activate_passive_calendar_time.clone())),
103        ]
104    }
105
106    fn methods(&self) -> Vec<(u8, String)> {
107        vec![(1, "activate_passive_calendar".to_string())]
108    }
109
110    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
111        let mut seq_buf = Vec::new();
112        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
113        for (_, attr) in self.attributes() {
114            attr.serialize_ber(&mut seq_buf)?;
115        }
116        buf.push(0x02); // structure [2]
117        write_length(1 + self.attributes().len(), buf); // length = element count
118        buf.extend_from_slice(&seq_buf);
119        Ok(())
120    }
121
122    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
123        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
124        if !rest.is_empty() {
125            return Err(BerError::InvalidTag);
126        }
127        let CosemDataType::Structure(seq) = tlv else {
128            return Err(BerError::InvalidTag);
129        };
130        // class_id + 10 attributes.
131        if seq.len() != 11 {
132            return Err(BerError::InvalidLength);
133        }
134        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
135            if class_id != self.class_id() {
136                return Err(BerError::InvalidValue);
137            }
138        } else {
139            return Err(BerError::InvalidTag);
140        }
141        if let CosemDataType::OctetString(obis) = &seq[1] {
142            if obis.len() == 6 {
143                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
144            } else {
145                return Err(BerError::InvalidLength);
146            }
147        } else {
148            return Err(BerError::InvalidTag);
149        }
150        self.calendar_name_active = take_octet_string(&seq[2])?;
151        self.season_profile_active = take_typed_array(&seq[3])?;
152        self.week_profile_table_active = take_typed_array(&seq[4])?;
153        self.day_profile_table_active = take_typed_array(&seq[5])?;
154        self.calendar_name_passive = take_octet_string(&seq[6])?;
155        self.season_profile_passive = take_typed_array(&seq[7])?;
156        self.week_profile_table_passive = take_typed_array(&seq[8])?;
157        self.day_profile_table_passive = take_typed_array(&seq[9])?;
158        self.activate_passive_calendar_time = take_octet_string(&seq[10])?;
159        Ok(())
160    }
161
162    fn set_attribute(&mut self, attribute_id: u8, value: CosemDataType) -> Result<(), String> {
163        match attribute_id {
164            2 => {
165                self.calendar_name_active = take_octet_string(&value).map_err(|e| format!("{e:?}"))?;
166                Ok(())
167            }
168            3 => {
169                self.season_profile_active = take_typed_array(&value).map_err(|e| format!("{e:?}"))?;
170                Ok(())
171            }
172            4 => {
173                self.week_profile_table_active = take_typed_array(&value).map_err(|e| format!("{e:?}"))?;
174                Ok(())
175            }
176            5 => {
177                self.day_profile_table_active = take_typed_array(&value).map_err(|e| format!("{e:?}"))?;
178                Ok(())
179            }
180            6 => {
181                self.calendar_name_passive = take_octet_string(&value).map_err(|e| format!("{e:?}"))?;
182                Ok(())
183            }
184            7 => {
185                self.season_profile_passive = take_typed_array(&value).map_err(|e| format!("{e:?}"))?;
186                Ok(())
187            }
188            8 => {
189                self.week_profile_table_passive = take_typed_array(&value).map_err(|e| format!("{e:?}"))?;
190                Ok(())
191            }
192            9 => {
193                self.day_profile_table_passive = take_typed_array(&value).map_err(|e| format!("{e:?}"))?;
194                Ok(())
195            }
196            10 => {
197                self.activate_passive_calendar_time = take_octet_string(&value).map_err(|e| format!("{e:?}"))?;
198                Ok(())
199            }
200            _ => Err(format!("ActivityCalendar attribute {attribute_id} is not writable")),
201        }
202    }
203
204    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
205        match method_id {
206            1 => Ok(self.activate_passive_calendar()),
207            _ => Err(format!("Method {method_id} not supported for Activity calendar")),
208        }
209    }
210
211    fn as_any(&self) -> &dyn Any {
212        self
213    }
214}
215
216fn take_octet_string(value: &CosemDataType) -> Result<Vec<u8>, BerError> {
217    match value {
218        CosemDataType::OctetString(bytes) => Ok(bytes.clone()),
219        _ => Err(BerError::InvalidTag),
220    }
221}
222
223fn take_typed_array<T: for<'a> TryFrom<&'a CosemDataType, Error = String>>(
224    value: &CosemDataType,
225) -> Result<Vec<T>, BerError> {
226    match value {
227        CosemDataType::Array(list) => {
228            list.iter().map(|item| T::try_from(item).map_err(|_| BerError::InvalidTag)).collect()
229        }
230        _ => Err(BerError::InvalidTag),
231    }
232}
233
234/// Writes a BER length octet (short or long form).
235#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
236fn write_length(length: usize, buf: &mut Vec<u8>) {
237    if length < 128 {
238        buf.push(length as u8);
239    } else {
240        let bytes = (length as u64).to_be_bytes();
241        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
242        let num_octets = 8 - first_non_zero;
243        buf.push(0x80 | num_octets as u8);
244        buf.extend_from_slice(&bytes[first_non_zero..]);
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    fn sample() -> ActivityCalendar {
253        ActivityCalendar::new(ActivityCalendarConfig {
254            logical_name: ObisCode::new(0, 0, 13, 0, 0, 255),
255            calendar_name_active: b"ACT".to_vec(),
256            season_profile_active: vec![SeasonProfile {
257                season_profile_name: b"summer".to_vec(),
258                season_start: vec![1, 1],
259                week_name: b"w1".to_vec(),
260            }],
261            week_profile_table_active: vec![],
262            day_profile_table_active: vec![],
263            calendar_name_passive: b"PAS".to_vec(),
264            season_profile_passive: vec![SeasonProfile {
265                season_profile_name: b"winter".to_vec(),
266                season_start: vec![7, 1],
267                week_name: b"w2".to_vec(),
268            }],
269            week_profile_table_passive: vec![],
270            day_profile_table_passive: vec![],
271            activate_passive_calendar_time: vec![0; 12],
272        })
273    }
274
275    #[test]
276    fn class_id_and_attributes() {
277        let obj = sample();
278        assert_eq!(obj.class_id(), 20);
279        assert_eq!(obj.version(), 0);
280        assert_eq!(obj.attributes().len(), 10);
281        assert_eq!(obj.methods().len(), 1);
282    }
283
284    #[test]
285    fn round_trip() {
286        let obj = sample();
287        let mut buf = Vec::new();
288        obj.serialize_ber(&mut buf).unwrap();
289        let mut decoded = sample();
290        decoded.calendar_name_active = vec![];
291        decoded.deserialize_ber(&buf).unwrap();
292        assert_eq!(decoded.attributes(), obj.attributes());
293    }
294
295    #[test]
296    fn activate_copies_passive_over_active() {
297        let mut obj = sample();
298        obj.invoke_method(1, None).unwrap();
299        assert_eq!(obj.attributes()[1].1, CosemDataType::OctetString(b"PAS".to_vec()));
300        let expected_passive: CosemDataType = SeasonProfile {
301            season_profile_name: b"winter".to_vec(),
302            season_start: vec![7, 1],
303            week_name: b"w2".to_vec(),
304        }
305        .into();
306        assert_eq!(obj.attributes()[2].1, CosemDataType::Array(vec![expected_passive]));
307    }
308}