Skip to main content

spodes_rs/classes/
single_action_schedule.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::{ExecutedScript, ExecutionTime};
4use crate::types::{BerError, CosemDataType};
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7
8/// Configuration structure used to build a [`SingleActionSchedule`] object.
9#[derive(Clone, Serialize, Deserialize, Debug)]
10pub struct SingleActionScheduleConfig {
11    /// Attribute 1: the object's logical name (OBIS code).
12    pub logical_name: ObisCode,
13    /// Attribute 2: `script` structure { script_logical_name, script_selector }.
14    pub executed_script: ExecutedScript,
15    /// Attribute 3: schedule type (enum 1..6, defines date/time wildcard handling).
16    pub schedule_type: u8,
17    /// Attribute 4: array of `execution_time` structures { time, date }.
18    pub execution_time: Vec<ExecutionTime>,
19}
20
21/// `Single action schedule` interface class (class_id = 22, version = 0) per
22/// IEC 62056-6-2 §4.5.7. Schedules the execution of a single script at the
23/// configured times.
24///
25/// This class defines no specific methods.
26#[derive(Clone, Serialize, Deserialize, Debug)]
27pub struct SingleActionSchedule {
28    logical_name: ObisCode,
29    executed_script: ExecutedScript,
30    schedule_type: u8,
31    execution_time: Vec<ExecutionTime>,
32}
33
34impl SingleActionSchedule {
35    /// Builds a new [`SingleActionSchedule`] from its configuration.
36    pub fn new(config: SingleActionScheduleConfig) -> Self {
37        SingleActionSchedule {
38            logical_name: config.logical_name,
39            executed_script: config.executed_script,
40            schedule_type: config.schedule_type,
41            execution_time: config.execution_time,
42        }
43    }
44}
45
46impl InterfaceClass for SingleActionSchedule {
47    fn class_id(&self) -> u16 {
48        22
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::from(self.executed_script.clone())),
63            (3, CosemDataType::Enum(self.schedule_type)),
64            (4, CosemDataType::Array(self.execution_time.iter().cloned().map(CosemDataType::from).collect())),
65        ]
66    }
67
68    fn methods(&self) -> Vec<(u8, String)> {
69        // The Single action schedule 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.executed_script = ExecutedScript::try_from(&seq[2]).map_err(|_| BerError::InvalidTag)?;
114        self.schedule_type = match seq[3] {
115            CosemDataType::Enum(v) => v,
116            _ => return Err(BerError::InvalidTag),
117        };
118        self.execution_time = match &seq[4] {
119            CosemDataType::Array(list) => list
120                .iter()
121                .map(ExecutionTime::try_from)
122                .collect::<Result<Vec<_>, _>>()
123                .map_err(|_| BerError::InvalidValue)?,
124            _ => return Err(BerError::InvalidTag),
125        };
126        Ok(())
127    }
128
129    fn set_attribute(&mut self, attribute_id: u8, value: CosemDataType) -> Result<(), String> {
130        match attribute_id {
131            2 => {
132                self.executed_script = ExecutedScript::try_from(&value)?;
133                Ok(())
134            }
135            3 => match value {
136                CosemDataType::Enum(v) => {
137                    self.schedule_type = v;
138                    Ok(())
139                }
140                _ => Err("schedule_type must be enum".into()),
141            },
142            4 => {
143                let CosemDataType::Array(list) = value else {
144                    return Err("execution_time must be array".into());
145                };
146                self.execution_time = list.iter().map(ExecutionTime::try_from).collect::<Result<Vec<_>, _>>()?;
147                Ok(())
148            }
149            _ => Err(format!("SingleActionSchedule attribute {attribute_id} is not writable")),
150        }
151    }
152
153    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
154        Err(format!("Method {method_id} not supported for Single action schedule (no specific methods)"))
155    }
156
157    fn as_any(&self) -> &dyn Any {
158        self
159    }
160}
161
162/// Writes a BER length octet (short or long form).
163#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
164fn write_length(length: usize, buf: &mut Vec<u8>) {
165    if length < 128 {
166        buf.push(length as u8);
167    } else {
168        let bytes = (length as u64).to_be_bytes();
169        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
170        let num_octets = 8 - first_non_zero;
171        buf.push(0x80 | num_octets as u8);
172        buf.extend_from_slice(&bytes[first_non_zero..]);
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    fn sample() -> SingleActionSchedule {
181        SingleActionSchedule::new(SingleActionScheduleConfig {
182            logical_name: ObisCode::new(0, 0, 15, 0, 0, 255),
183            executed_script: ExecutedScript {
184                script_logical_name: ObisCode::new(0, 0, 10, 0, 100, 255),
185                script_selector: 1,
186            },
187            schedule_type: 1,
188            execution_time: vec![ExecutionTime {
189                time: vec![0x00, 0x00, 0x00, 0xFF],
190                date: vec![0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
191            }],
192        })
193    }
194
195    #[test]
196    fn class_id_and_attributes() {
197        let obj = sample();
198        assert_eq!(obj.class_id(), 22);
199        assert_eq!(obj.version(), 0);
200        assert_eq!(obj.attributes().len(), 4);
201        assert!(obj.methods().is_empty());
202    }
203
204    #[test]
205    fn round_trip() {
206        let obj = sample();
207        let mut buf = Vec::new();
208        obj.serialize_ber(&mut buf).unwrap();
209        let mut decoded = sample();
210        decoded.schedule_type = 0;
211        decoded.deserialize_ber(&buf).unwrap();
212        assert_eq!(decoded.attributes(), obj.attributes());
213    }
214}