Skip to main content

spodes_rs/classes/
special_days_table.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::SpecialDayEntry;
4use crate::types::{BerError, CosemDataType};
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7
8/// Configuration used to build a `SpecialDaysTable` object.
9#[derive(Clone, Serialize, Deserialize, Debug)]
10pub struct SpecialDaysTableConfig {
11    /// Attribute 1: the object's logical name (OBIS code).
12    pub logical_name: ObisCode,
13    /// Attribute 2: array of `special_day` entries { index, date, day_id }.
14    pub entries: Vec<SpecialDayEntry>,
15}
16
17/// The `SpecialDaysTable` interface class (class_id = 11, version = 0) managing a
18/// list of special days, per IEC 62056-6-2:2019.
19#[derive(Clone, Serialize, Deserialize, Debug)]
20pub struct SpecialDaysTable {
21    logical_name: ObisCode,
22    entries: Vec<SpecialDayEntry>,
23}
24
25impl SpecialDaysTable {
26    /// Builds a new [`SpecialDaysTable`] from its configuration.
27    pub fn new(config: SpecialDaysTableConfig) -> Self {
28        SpecialDaysTable { logical_name: config.logical_name, entries: config.entries }
29    }
30
31    fn insert(&mut self, data: &CosemDataType) -> Result<CosemDataType, String> {
32        let entry = SpecialDayEntry::try_from(data)?;
33        if entry.specialday_date.len() != 12 {
34            return Err("Invalid DateTime length".to_string());
35        }
36        self.entries.push(entry);
37        Ok(CosemDataType::Null)
38    }
39
40    fn delete(&mut self, data: &CosemDataType) -> Result<CosemDataType, String> {
41        let entry = SpecialDayEntry::try_from(data)?;
42        self.entries.retain(|e| e.index != entry.index);
43        Ok(CosemDataType::Null)
44    }
45}
46
47impl InterfaceClass for SpecialDaysTable {
48    fn class_id(&self) -> u16 {
49        11
50    }
51
52    fn version(&self) -> u8 {
53        0
54    }
55
56    fn logical_name(&self) -> &ObisCode {
57        &self.logical_name
58    }
59
60    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
61        vec![
62            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
63            (2, CosemDataType::Array(self.entries.iter().cloned().map(Into::into).collect())),
64        ]
65    }
66
67    fn methods(&self) -> Vec<(u8, String)> {
68        vec![(1, "insert".to_string()), (2, "delete".to_string())]
69    }
70
71    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
72        let mut seq_buf = Vec::new();
73        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
74        for (_, attr) in self.attributes() {
75            attr.serialize_ber(&mut seq_buf)?;
76        }
77        buf.push(0x02); // structure [2]
78        write_length(1 + self.attributes().len(), buf); // length = element count
79        buf.extend_from_slice(&seq_buf);
80        Ok(())
81    }
82
83    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
84        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
85        if !rest.is_empty() {
86            return Err(BerError::InvalidTag);
87        }
88        let CosemDataType::Structure(seq) = tlv else {
89            return Err(BerError::InvalidTag);
90        };
91        if seq.len() == 3 {
92            if let CosemDataType::LongUnsigned(class_id) = seq[0] {
93                if class_id != self.class_id() {
94                    return Err(BerError::InvalidValue);
95                }
96            } else {
97                return Err(BerError::InvalidTag);
98            }
99            if let CosemDataType::OctetString(obis) = &seq[1] {
100                if obis.len() == 6 {
101                    self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
102                } else {
103                    return Err(BerError::InvalidLength);
104                }
105            } else {
106                return Err(BerError::InvalidTag);
107            }
108            if let CosemDataType::Array(entries) = &seq[2] {
109                let mut parsed = Vec::new();
110                for entry in entries {
111                    let special_entry = SpecialDayEntry::try_from(entry).map_err(|_| BerError::InvalidValue)?;
112                    if special_entry.specialday_date.len() != 12 {
113                        return Err(BerError::InvalidLength);
114                    }
115                    parsed.push(special_entry);
116                }
117                self.entries = parsed;
118            } else {
119                return Err(BerError::InvalidTag);
120            }
121            Ok(())
122        } else {
123            Err(BerError::InvalidLength)
124        }
125    }
126
127    fn set_attribute(&mut self, attribute_id: u8, value: CosemDataType) -> Result<(), String> {
128        match attribute_id {
129            2 => {
130                let CosemDataType::Array(entries) = value else {
131                    return Err("entries must be array".into());
132                };
133                self.entries = entries.iter().map(SpecialDayEntry::try_from).collect::<Result<Vec<_>, _>>()?;
134                Ok(())
135            }
136            _ => Err(format!("SpecialDaysTable attribute {attribute_id} is not writable")),
137        }
138    }
139
140    fn invoke_method(&mut self, method_id: u8, params: Option<CosemDataType>) -> Result<CosemDataType, String> {
141        match method_id {
142            1 => self.insert(&params.ok_or("Missing parameter for insert method")?),
143            2 => self.delete(&params.ok_or("Missing parameter for delete method")?),
144            _ => Err(format!("Method {method_id} not supported for SpecialDaysTable")),
145        }
146    }
147
148    fn as_any(&self) -> &dyn Any {
149        self
150    }
151}
152
153/// Writes a BER/A-XDR length octet (short or long form).
154#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
155fn write_length(length: usize, buf: &mut Vec<u8>) {
156    if length < 128 {
157        buf.push(length as u8);
158    } else {
159        let bytes = (length as u64).to_be_bytes();
160        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
161        let num_octets = 8 - first_non_zero;
162        buf.push(0x80 | num_octets as u8);
163        buf.extend_from_slice(&bytes[first_non_zero..]);
164    }
165}