Skip to main content

spodes_rs/classes/
script_table.rs

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