Skip to main content

spodes_rs/classes/
utility_tables.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::{BerError, CosemDataType};
4use serde::{Deserialize, Serialize};
5use std::any::Any;
6
7/// Configuration structure used to build a [`UtilityTables`] object.
8#[derive(Clone, Serialize, Deserialize, Debug)]
9pub struct UtilityTablesConfig {
10    /// Attribute 1: the object's logical name (OBIS code).
11    pub logical_name: ObisCode,
12    /// Attribute 2: table identifier (per the referenced table standard).
13    pub table_id: u16,
14    /// Attribute 3: length of the table contents in octets.
15    pub length: u32,
16    /// Attribute 4: the encapsulated table contents.
17    pub buffer: Vec<u8>,
18}
19
20/// `Utility tables` interface class (class_id = 26, version = 0) per
21/// IEC 62056-6-2 ยง4.3.6. Encapsulates ANSI C12.19 (or other) table data as an
22/// octet-string.
23///
24/// This class defines no specific methods.
25#[derive(Clone, Serialize, Deserialize, Debug)]
26pub struct UtilityTables {
27    logical_name: ObisCode,
28    table_id: u16,
29    length: u32,
30    buffer: Vec<u8>,
31}
32
33impl UtilityTables {
34    /// Builds a new [`UtilityTables`] from its configuration.
35    pub fn new(config: UtilityTablesConfig) -> Self {
36        UtilityTables {
37            logical_name: config.logical_name,
38            table_id: config.table_id,
39            length: config.length,
40            buffer: config.buffer,
41        }
42    }
43}
44
45impl InterfaceClass for UtilityTables {
46    fn class_id(&self) -> u16 {
47        26
48    }
49
50    fn version(&self) -> u8 {
51        0
52    }
53
54    fn logical_name(&self) -> &ObisCode {
55        &self.logical_name
56    }
57
58    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
59        vec![
60            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
61            (2, CosemDataType::LongUnsigned(self.table_id)),
62            (3, CosemDataType::DoubleLongUnsigned(self.length)),
63            (4, CosemDataType::OctetString(self.buffer.clone())),
64        ]
65    }
66
67    fn methods(&self) -> Vec<(u8, String)> {
68        // The utility tables class defines no specific methods.
69        vec![]
70    }
71
72    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
73        let mut seq_buf = Vec::new();
74        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
75        for (_, attr) in self.attributes() {
76            attr.serialize_ber(&mut seq_buf)?;
77        }
78        buf.push(0x02); // structure [2]
79        write_length(1 + self.attributes().len(), buf);
80        buf.extend_from_slice(&seq_buf);
81        Ok(())
82    }
83
84    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
85        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
86        if !rest.is_empty() {
87            return Err(BerError::InvalidTag);
88        }
89        let CosemDataType::Structure(seq) = tlv else {
90            return Err(BerError::InvalidTag);
91        };
92        if seq.len() != 5 {
93            return Err(BerError::InvalidLength);
94        }
95        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
96            if class_id != self.class_id() {
97                return Err(BerError::InvalidValue);
98            }
99        } else {
100            return Err(BerError::InvalidTag);
101        }
102        if let CosemDataType::OctetString(obis) = &seq[1] {
103            if obis.len() == 6 {
104                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
105            } else {
106                return Err(BerError::InvalidLength);
107            }
108        } else {
109            return Err(BerError::InvalidTag);
110        }
111        self.table_id = match seq[2] {
112            CosemDataType::LongUnsigned(v) => v,
113            _ => return Err(BerError::InvalidTag),
114        };
115        self.length = match seq[3] {
116            CosemDataType::DoubleLongUnsigned(v) => v,
117            _ => return Err(BerError::InvalidTag),
118        };
119        self.buffer = match &seq[4] {
120            CosemDataType::OctetString(v) => v.clone(),
121            _ => return Err(BerError::InvalidTag),
122        };
123        Ok(())
124    }
125
126    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
127        Err(format!("Method {method_id} not supported for Utility tables (no specific methods)"))
128    }
129
130    fn as_any(&self) -> &dyn Any {
131        self
132    }
133}
134
135/// Writes a BER length octet (short or long form).
136#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
137fn write_length(length: usize, buf: &mut Vec<u8>) {
138    if length < 128 {
139        buf.push(length as u8);
140    } else {
141        let bytes = (length as u64).to_be_bytes();
142        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
143        let num_octets = 8 - first_non_zero;
144        buf.push(0x80 | num_octets as u8);
145        buf.extend_from_slice(&bytes[first_non_zero..]);
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    fn sample() -> UtilityTables {
154        UtilityTables::new(UtilityTablesConfig {
155            logical_name: ObisCode::new(0, 0, 65, 0, 0, 255),
156            table_id: 23,
157            length: 4,
158            buffer: vec![0xDE, 0xAD, 0xBE, 0xEF],
159        })
160    }
161
162    #[test]
163    fn class_id_and_attributes() {
164        let obj = sample();
165        assert_eq!(obj.class_id(), 26);
166        assert_eq!(obj.attributes().len(), 4);
167        assert!(obj.methods().is_empty());
168    }
169
170    #[test]
171    fn round_trip() {
172        let obj = sample();
173        let mut buf = Vec::new();
174        obj.serialize_ber(&mut buf).unwrap();
175        let mut decoded = UtilityTables::new(UtilityTablesConfig {
176            logical_name: ObisCode::new(0, 0, 0, 0, 0, 0),
177            table_id: 0,
178            length: 0,
179            buffer: vec![],
180        });
181        decoded.deserialize_ber(&buf).unwrap();
182        assert_eq!(decoded.attributes(), obj.attributes());
183    }
184}