Skip to main content

spodes_rs/classes/
clock.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::DateTime;
4use crate::types::{BerError, CosemDataType};
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7
8/// Configuration used to build a `Clock` object.
9#[derive(Clone, Serialize, Deserialize, Debug)]
10pub struct ClockConfig {
11    /// Attribute 1: the object's logical name (OBIS code).
12    pub logical_name: ObisCode,
13    /// Attribute 2: the current date and time (date-time, 12 octets).
14    pub time: DateTime,
15    /// Attribute 3: deviation of local time from GMT, in minutes (long).
16    pub time_zone: i16,
17    /// Attribute 4: clock status flags (unsigned bit-string).
18    pub status: u8,
19    /// Attribute 5: date and time at which daylight saving begins (date-time).
20    pub daylight_savings_begin: DateTime,
21    /// Attribute 6: date and time at which daylight saving ends (date-time).
22    pub daylight_savings_end: DateTime,
23    /// Attribute 7: daylight-saving offset added to `time`, in minutes (integer).
24    pub daylight_savings_deviation: i8,
25    /// Attribute 8: whether daylight saving is applied (boolean).
26    pub daylight_savings_enabled: bool,
27    /// Attribute 9: the underlying clock base / source (enum).
28    pub clock_base: u8,
29}
30
31/// The `Clock` interface class (class_id = 8) managing time and date
32/// per IEC 62056-6-2.
33///
34/// Attributes (IEC 62056-6-2, Table 15):
35/// - attr 1: logical_name (octet-string) — OBIS code
36/// - attr 2: time (date-time) — current date and time
37/// - attr 3: time_zone (long) — deviation from GMT in minutes
38/// - attr 4: status (bit-string) — clock status flags
39/// - attr 5: daylight_savings_begin (date-time)
40/// - attr 6: daylight_savings_end (date-time)
41/// - attr 7: daylight_savings_deviation (integer) — offset in minutes
42/// - attr 8: daylight_savings_enabled (boolean)
43/// - attr 9: clock_base (enum) — clock source
44#[derive(Clone, Serialize, Deserialize, Debug)]
45pub struct Clock {
46    logical_name: ObisCode,
47    time: DateTime,
48    time_zone: i16,
49    status: u8,
50    daylight_savings_begin: DateTime,
51    daylight_savings_end: DateTime,
52    daylight_savings_deviation: i8,
53    daylight_savings_enabled: bool,
54    clock_base: u8,
55}
56
57impl Clock {
58    /// Creates a new `Clock` object from its configuration.
59    ///
60    /// # Arguments
61    /// * `config` - The configuration used to build the object.
62    ///
63    /// # Returns
64    /// A new `Clock`.
65    pub fn new(config: ClockConfig) -> Self {
66        Clock {
67            logical_name: config.logical_name,
68            time: config.time,
69            time_zone: config.time_zone,
70            status: config.status,
71            daylight_savings_begin: config.daylight_savings_begin,
72            daylight_savings_end: config.daylight_savings_end,
73            daylight_savings_deviation: config.daylight_savings_deviation,
74            daylight_savings_enabled: config.daylight_savings_enabled,
75            clock_base: config.clock_base,
76        }
77    }
78
79    /// Returns the time attribute (attr 2).
80    pub fn time(&self) -> &DateTime {
81        &self.time
82    }
83
84    /// Returns the time_zone attribute (attr 3).
85    pub fn time_zone(&self) -> i16 {
86        self.time_zone
87    }
88
89    /// Returns the status attribute (attr 4).
90    pub fn status(&self) -> u8 {
91        self.status
92    }
93
94    /// Returns the clock_base attribute (attr 9).
95    pub fn clock_base(&self) -> u8 {
96        self.clock_base
97    }
98
99    /// Adjusts the time to the nearest quarter hour (minute 0, 15, 30 or 45).
100    fn adjust_to_quarter(&mut self) -> CosemDataType {
101        let minutes = u32::from(self.time.0[6]);
102        let new_minutes: u8 = if minutes < 8 {
103            0
104        } else if minutes < 23 {
105            15
106        } else if minutes < 37 {
107            30
108        } else {
109            45
110        };
111        self.time.0[6] = new_minutes;
112        self.time.0[7] = 0;
113        self.time.0[8] = 0;
114        CosemDataType::Null
115    }
116
117    /// Adjusts the time to the measuring period (stub — C++ parity).
118    fn adjust_to_measuring_period(&mut self) -> CosemDataType {
119        CosemDataType::Null
120    }
121
122    /// Adjusts the time to the nearest minute.
123    fn adjust_to_minute(&mut self) -> CosemDataType {
124        self.time.0[7] = 0;
125        self.time.0[8] = 0;
126        CosemDataType::Null
127    }
128
129    /// Sets a preset time.
130    fn adjust_to_preset_time(&mut self, params: Option<CosemDataType>) -> Result<CosemDataType, String> {
131        if let Some(CosemDataType::DateTime(dt) | CosemDataType::OctetString(dt)) = params {
132            if dt.len() == 12 {
133                let mut buf = [0u8; 12];
134                buf.copy_from_slice(&dt);
135                self.time = DateTime(buf);
136                return Ok(CosemDataType::Null);
137            }
138        }
139        Err("Invalid DateTime parameter".to_string())
140    }
141
142    /// Preset-time adjustment (stub).
143    fn preset_adjusting_time() -> CosemDataType {
144        CosemDataType::Null
145    }
146
147    /// Shifts the clock by a relative offset in seconds (Blue Book method 6).
148    /// Parameter is ignored for success/failure — C++ returns null without applying.
149    fn shift_time(_params: Option<CosemDataType>) -> CosemDataType {
150        CosemDataType::Null
151    }
152}
153
154impl InterfaceClass for Clock {
155    fn class_id(&self) -> u16 {
156        8
157    }
158
159    fn version(&self) -> u8 {
160        0
161    }
162
163    fn logical_name(&self) -> &ObisCode {
164        &self.logical_name
165    }
166
167    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
168        // Blue Book date-time attributes are carried as octet-string (tag 0x09),
169        // matching `osp_val_cosem_datetime` / common client expectations — not tag 0x19.
170        vec![
171            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
172            (2, CosemDataType::OctetString(self.time.0.to_vec())),
173            (3, CosemDataType::Long(self.time_zone)),
174            (4, CosemDataType::Unsigned(self.status)),
175            (5, CosemDataType::OctetString(self.daylight_savings_begin.0.to_vec())),
176            (6, CosemDataType::OctetString(self.daylight_savings_end.0.to_vec())),
177            (7, CosemDataType::Integer(self.daylight_savings_deviation)),
178            (8, CosemDataType::Boolean(self.daylight_savings_enabled)),
179            (9, CosemDataType::Enum(self.clock_base)),
180        ]
181    }
182
183    fn methods(&self) -> Vec<(u8, String)> {
184        vec![
185            (1, "adjust_to_quarter".to_string()),
186            (2, "adjust_to_measuring_period".to_string()),
187            (3, "adjust_to_minute".to_string()),
188            (4, "adjust_to_preset_time".to_string()),
189            (5, "preset_adjusting_time".to_string()),
190            (6, "shift_time".to_string()),
191        ]
192    }
193
194    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
195        let mut seq_buf = Vec::new();
196        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
197        for (_, attr) in self.attributes() {
198            attr.serialize_ber(&mut seq_buf)?;
199        }
200        buf.push(0x02); // structure [2]
201        write_length(1 + self.attributes().len(), buf); // length = element count
202        buf.extend_from_slice(&seq_buf);
203        Ok(())
204    }
205
206    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
207        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
208        if !rest.is_empty() {
209            return Err(BerError::InvalidTag);
210        }
211        if let CosemDataType::Structure(seq) = tlv {
212            if seq.len() == 10 {
213                if let CosemDataType::LongUnsigned(class_id) = seq[0] {
214                    if class_id != self.class_id() {
215                        return Err(BerError::InvalidValue);
216                    }
217                } else {
218                    return Err(BerError::InvalidTag);
219                }
220                if let CosemDataType::OctetString(obis) = &seq[1] {
221                    if obis.len() == 6 {
222                        self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
223                    } else {
224                        return Err(BerError::InvalidLength);
225                    }
226                } else {
227                    return Err(BerError::InvalidTag);
228                }
229                // Parse typed attributes from CosemDataType
230                self.time = DateTime::try_from(&seq[2]).map_err(|_| BerError::InvalidValue)?;
231                self.time_zone = match &seq[3] {
232                    CosemDataType::Long(v) => *v,
233                    _ => return Err(BerError::InvalidTag),
234                };
235                self.status = match &seq[4] {
236                    CosemDataType::Unsigned(v) => *v,
237                    _ => return Err(BerError::InvalidTag),
238                };
239                self.daylight_savings_begin = DateTime::try_from(&seq[5]).map_err(|_| BerError::InvalidValue)?;
240                self.daylight_savings_end = DateTime::try_from(&seq[6]).map_err(|_| BerError::InvalidValue)?;
241                self.daylight_savings_deviation = match &seq[7] {
242                    CosemDataType::Integer(v) => *v,
243                    _ => return Err(BerError::InvalidTag),
244                };
245                self.daylight_savings_enabled = match &seq[8] {
246                    CosemDataType::Boolean(v) => *v,
247                    _ => return Err(BerError::InvalidTag),
248                };
249                self.clock_base = match &seq[9] {
250                    CosemDataType::Enum(v) => *v,
251                    _ => return Err(BerError::InvalidTag),
252                };
253                return Ok(());
254            }
255            return Err(BerError::InvalidLength);
256        }
257        Err(BerError::InvalidTag)
258    }
259
260    fn set_attribute(&mut self, attribute_id: u8, value: CosemDataType) -> Result<(), String> {
261        match attribute_id {
262            2 => {
263                self.time = DateTime::try_from(&value)?;
264                Ok(())
265            }
266            3 => match value {
267                CosemDataType::Long(v) => {
268                    self.time_zone = v;
269                    Ok(())
270                }
271                _ => Err("time_zone must be long".into()),
272            },
273            // Attr 4 (status) is read-only in the ACL mask.
274            5 => {
275                self.daylight_savings_begin = DateTime::try_from(&value)?;
276                Ok(())
277            }
278            6 => {
279                self.daylight_savings_end = DateTime::try_from(&value)?;
280                Ok(())
281            }
282            7 => match value {
283                CosemDataType::Integer(v) => {
284                    self.daylight_savings_deviation = v;
285                    Ok(())
286                }
287                _ => Err("daylight_savings_deviation must be integer".into()),
288            },
289            8 => match value {
290                CosemDataType::Boolean(v) => {
291                    self.daylight_savings_enabled = v;
292                    Ok(())
293                }
294                _ => Err("daylight_savings_enabled must be boolean".into()),
295            },
296            // Attr 9 (clock_base) is read-only.
297            _ => Err(format!("Clock attribute {attribute_id} is not writable")),
298        }
299    }
300
301    fn invoke_method(&mut self, method_id: u8, params: Option<CosemDataType>) -> Result<CosemDataType, String> {
302        match method_id {
303            1 => Ok(self.adjust_to_quarter()),
304            2 => Ok(self.adjust_to_measuring_period()),
305            3 => Ok(self.adjust_to_minute()),
306            4 => self.adjust_to_preset_time(params),
307            5 => Ok(Self::preset_adjusting_time()),
308            6 => Ok(Self::shift_time(params)),
309            _ => Err(format!("Method {method_id} not supported for Clock class")),
310        }
311    }
312
313    fn as_any(&self) -> &dyn Any {
314        self
315    }
316}
317
318/// Writes a length in BER (short or long form).
319#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
320fn write_length(length: usize, buf: &mut Vec<u8>) {
321    if length < 128 {
322        buf.push(length as u8);
323    } else {
324        let bytes = (length as u64).to_be_bytes();
325        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
326        let num_octets = 8 - first_non_zero;
327        buf.push(0x80 | num_octets as u8);
328        buf.extend_from_slice(&bytes[first_non_zero..]);
329    }
330}