Skip to main content

spodes_rs/classes/
compact_data.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::{BerError, CosemDataType};
4use serde::{Deserialize, Serialize};
5use std::any::Any;
6use std::fmt;
7use std::sync::Arc;
8
9/// Values of the `capture_method` attribute (IEC 62056-6-2 §4.3.8).
10pub mod capture_method {
11    /// Method 2 `capture` stores all values (invoked explicitly).
12    pub const INVOKE: u8 = 0;
13    /// The values are captured implicitly on read of the compact buffer.
14    pub const IMPLICIT: u8 = 1;
15}
16
17/// Configuration structure used to build a [`CompactData`] object.
18#[derive(Clone, Serialize, Deserialize)]
19pub struct CompactDataConfig {
20    /// Attribute 1: the object's logical name (OBIS code).
21    pub logical_name: ObisCode,
22    /// Attribute 2: the compact buffer (octet-string of concatenated values).
23    pub compact_buffer: Vec<u8>,
24    /// Attribute 3: the objects captured into the buffer, paired with the
25    /// captured attribute index.
26    #[serde(skip)]
27    pub capture_objects: Vec<(Arc<dyn InterfaceClass + Send + Sync>, u8)>,
28    /// Attribute 4: identifier of the template describing the buffer contents.
29    pub template_id: u8,
30    /// Attribute 5: template description (octet-string of type tags).
31    pub template_description: Vec<u8>,
32    /// Attribute 6: capture method (see [`capture_method`]).
33    pub capture_method: u8,
34}
35
36impl fmt::Debug for CompactDataConfig {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.debug_struct("CompactDataConfig")
39            .field("logical_name", &self.logical_name)
40            .field("compact_buffer", &self.compact_buffer)
41            .field("capture_objects", &format_args!("Vec<...> (len={})", self.capture_objects.len()))
42            .field("template_id", &self.template_id)
43            .field("template_description", &self.template_description)
44            .field("capture_method", &self.capture_method)
45            .finish()
46    }
47}
48
49/// `Compact data` interface class (class_id = 62, version = 0) per
50/// IEC 62056-6-2 §4.3.8. Holds the values of the capture objects in a compact
51/// (contents-only) encoding described by the template.
52#[derive(Clone, Serialize, Deserialize)]
53pub struct CompactData {
54    logical_name: ObisCode,
55    compact_buffer: Vec<u8>,
56    #[serde(skip)]
57    capture_objects: Vec<(Arc<dyn InterfaceClass + Send + Sync>, u8)>,
58    template_id: u8,
59    template_description: Vec<u8>,
60    capture_method: u8,
61}
62
63impl fmt::Debug for CompactData {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.debug_struct("CompactData")
66            .field("logical_name", &self.logical_name)
67            .field("compact_buffer", &self.compact_buffer)
68            .field("capture_objects", &format_args!("Vec<...> (len={})", self.capture_objects.len()))
69            .field("template_id", &self.template_id)
70            .field("template_description", &self.template_description)
71            .field("capture_method", &self.capture_method)
72            .finish()
73    }
74}
75
76impl CompactData {
77    /// Builds a new [`CompactData`] from its configuration.
78    pub fn new(config: CompactDataConfig) -> Self {
79        CompactData {
80            logical_name: config.logical_name,
81            compact_buffer: config.compact_buffer,
82            capture_objects: config.capture_objects,
83            template_id: config.template_id,
84            template_description: config.template_description,
85            capture_method: config.capture_method,
86        }
87    }
88
89    /// Method 1: `reset` — clears the compact buffer.
90    fn reset(&mut self) -> CosemDataType {
91        self.compact_buffer.clear();
92        CosemDataType::Null
93    }
94
95    /// Method 2: `capture` — reads every capture object's attribute and stores
96    /// the serialized values (full TLV encoding, one after another) into the
97    /// compact buffer.
98    fn capture(&mut self) -> Result<CosemDataType, String> {
99        if self.capture_objects.is_empty() {
100            return Err("No capture objects configured".to_string());
101        }
102        let mut buffer = Vec::new();
103        for (obj, attr_id) in &self.capture_objects {
104            let value = obj
105                .attributes()
106                .into_iter()
107                .find(|(id, _)| id == attr_id)
108                .map(|(_, v)| v)
109                .ok_or_else(|| format!("Capture object has no attribute {attr_id}"))?;
110            value.serialize_ber(&mut buffer).map_err(|e| format!("Capture serialization failed: {e:?}"))?;
111        }
112        self.compact_buffer = buffer;
113        Ok(CosemDataType::Null)
114    }
115
116    /// Returns the compact buffer (attribute 2).
117    pub fn compact_buffer(&self) -> &[u8] {
118        &self.compact_buffer
119    }
120}
121
122impl InterfaceClass for CompactData {
123    fn class_id(&self) -> u16 {
124        62
125    }
126
127    fn version(&self) -> u8 {
128        0
129    }
130
131    fn logical_name(&self) -> &ObisCode {
132        &self.logical_name
133    }
134
135    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
136        let capture_objects = CosemDataType::Array(
137            self.capture_objects
138                .iter()
139                .map(|(obj, attr_id)| {
140                    // Attribute ids are always <128 in practice (i8-valued on the wire).
141                    #[allow(clippy::cast_possible_wrap)]
142                    let attr_id = *attr_id as i8;
143                    CosemDataType::Structure(vec![
144                        CosemDataType::LongUnsigned(obj.class_id()),
145                        CosemDataType::OctetString(obj.logical_name().to_bytes()),
146                        CosemDataType::Integer(attr_id), // attribute_index (integer)
147                        CosemDataType::LongUnsigned(0),  // data_index (long-unsigned, default 0)
148                    ])
149                })
150                .collect(),
151        );
152        vec![
153            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
154            (2, CosemDataType::OctetString(self.compact_buffer.clone())),
155            (3, capture_objects),
156            (4, CosemDataType::Unsigned(self.template_id)),
157            (5, CosemDataType::OctetString(self.template_description.clone())),
158            (6, CosemDataType::Enum(self.capture_method)),
159        ]
160    }
161
162    fn methods(&self) -> Vec<(u8, String)> {
163        vec![(1, "reset".to_string()), (2, "capture".to_string())]
164    }
165
166    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
167        let mut seq_buf = Vec::new();
168        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
169        CosemDataType::OctetString(self.logical_name.to_bytes()).serialize_ber(&mut seq_buf)?;
170        CosemDataType::OctetString(self.compact_buffer.clone()).serialize_ber(&mut seq_buf)?;
171        CosemDataType::Unsigned(self.template_id).serialize_ber(&mut seq_buf)?;
172        CosemDataType::OctetString(self.template_description.clone()).serialize_ber(&mut seq_buf)?;
173        CosemDataType::Enum(self.capture_method).serialize_ber(&mut seq_buf)?;
174        buf.push(0x02); // structure [2]
175        write_length(6, buf);
176        buf.extend_from_slice(&seq_buf);
177        Ok(())
178    }
179
180    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
181        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
182        if !rest.is_empty() {
183            return Err(BerError::InvalidTag);
184        }
185        let CosemDataType::Structure(seq) = tlv else {
186            return Err(BerError::InvalidTag);
187        };
188        if seq.len() != 6 {
189            return Err(BerError::InvalidLength);
190        }
191        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
192            if class_id != self.class_id() {
193                return Err(BerError::InvalidValue);
194            }
195        } else {
196            return Err(BerError::InvalidTag);
197        }
198        if let CosemDataType::OctetString(obis) = &seq[1] {
199            if obis.len() == 6 {
200                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
201            } else {
202                return Err(BerError::InvalidLength);
203            }
204        } else {
205            return Err(BerError::InvalidTag);
206        }
207        self.compact_buffer = match &seq[2] {
208            CosemDataType::OctetString(v) => v.clone(),
209            _ => return Err(BerError::InvalidTag),
210        };
211        self.template_id = match seq[3] {
212            CosemDataType::Unsigned(v) => v,
213            _ => return Err(BerError::InvalidTag),
214        };
215        self.template_description = match &seq[4] {
216            CosemDataType::OctetString(v) => v.clone(),
217            _ => return Err(BerError::InvalidTag),
218        };
219        self.capture_method = match seq[5] {
220            CosemDataType::Enum(v) => v,
221            _ => return Err(BerError::InvalidTag),
222        };
223        Ok(())
224    }
225
226    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
227        match method_id {
228            1 => Ok(self.reset()),
229            2 => self.capture(),
230            _ => Err(format!("Method {method_id} not supported for Compact data class")),
231        }
232    }
233
234    fn as_any(&self) -> &dyn Any {
235        self
236    }
237}
238
239/// Writes a BER length octet (short or long form).
240#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
241fn write_length(length: usize, buf: &mut Vec<u8>) {
242    if length < 128 {
243        buf.push(length as u8);
244    } else {
245        let bytes = (length as u64).to_be_bytes();
246        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
247        let num_octets = 8 - first_non_zero;
248        buf.push(0x80 | num_octets as u8);
249        buf.extend_from_slice(&bytes[first_non_zero..]);
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256    use crate::classes::data::Data;
257
258    fn sample() -> CompactData {
259        CompactData::new(CompactDataConfig {
260            logical_name: ObisCode::new(0, 0, 66, 0, 1, 255),
261            compact_buffer: vec![],
262            capture_objects: vec![(
263                Arc::new(Data::new(ObisCode::new(0, 0, 96, 1, 0, 255), CosemDataType::LongUnsigned(0x1234))),
264                2,
265            )],
266            template_id: 1,
267            template_description: vec![0x12],
268            capture_method: capture_method::INVOKE,
269        })
270    }
271
272    #[test]
273    fn class_id_attributes_and_methods() {
274        let obj = sample();
275        assert_eq!(obj.class_id(), 62);
276        assert_eq!(obj.attributes().len(), 6);
277        assert_eq!(obj.methods().len(), 2);
278    }
279
280    #[test]
281    fn capture_fills_and_reset_clears_buffer() {
282        let mut obj = sample();
283        obj.invoke_method(2, None).unwrap();
284        // long-unsigned 0x1234 → 12 12 34.
285        assert_eq!(obj.compact_buffer(), &[0x12, 0x12, 0x34]);
286        obj.invoke_method(1, None).unwrap();
287        assert!(obj.compact_buffer().is_empty());
288    }
289
290    #[test]
291    fn round_trip() {
292        let mut obj = sample();
293        obj.invoke_method(2, None).unwrap();
294        let mut buf = Vec::new();
295        obj.serialize_ber(&mut buf).unwrap();
296        let mut decoded = sample();
297        decoded.deserialize_ber(&buf).unwrap();
298        assert_eq!(decoded.compact_buffer(), obj.compact_buffer());
299        assert_eq!(decoded.attributes()[4], obj.attributes()[4]);
300    }
301}