Skip to main content

spodes_rs/classes/
profile_generic.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::{CaptureObjectDefinition, Choice, SortMethod};
4use crate::types::{BerError, CosemDataType};
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7use std::fmt;
8use std::sync::Arc;
9
10/// Configuration structure used to build a `ProfileGeneric` object.
11#[derive(Clone, Serialize, Deserialize)]
12pub struct ProfileGenericConfig {
13    /// Attribute 1: the object's logical name (OBIS code).
14    pub logical_name: ObisCode,
15    /// Class version: 0 or 1. Version 0 additionally exposes the
16    /// `get_buffer_by_range` and `get_buffer_by_index` methods.
17    pub version: u8,
18    /// Attribute 2: the captured data buffer (array of entry structures).
19    pub buffer: Vec<Choice>,
20    /// Attribute 3: the objects captured into each buffer entry, paired with the
21    /// captured attribute index.
22    #[serde(skip)]
23    pub capture_objects: Vec<(Arc<dyn InterfaceClass + Send + Sync>, u8)>,
24    /// Attribute 4: the capturing period, in seconds (0 = event-driven).
25    pub capture_period: u32,
26    /// Attribute 5: sort method (1 = FIFO, 2 = LIFO, 3 = largest, 4 = smallest).
27    pub sort_method: SortMethod,
28    /// Attribute 6: `capture_object_definition` used as the sort key.
29    pub sort_object: Option<CaptureObjectDefinition>,
30    /// Attribute 7: number of entries currently stored in the buffer.
31    pub entries_in_use: u32,
32    /// Attribute 8: maximum number of entries the buffer can hold.
33    pub profile_entries: u32,
34}
35
36impl fmt::Debug for ProfileGenericConfig {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.debug_struct("ProfileGenericConfig")
39            .field("logical_name", &self.logical_name)
40            .field("buffer", &self.buffer)
41            .field("capture_objects", &format_args!("Vec<...> (len={})", self.capture_objects.len()))
42            .field("capture_period", &self.capture_period)
43            .field("sort_method", &self.sort_method)
44            .field("sort_object", &self.sort_object)
45            .field("entries_in_use", &self.entries_in_use)
46            .field("profile_entries", &self.profile_entries)
47            .finish()
48    }
49}
50
51/// `ProfileGeneric` interface class (class_id = 7, version = 1) for storing data
52/// profiles such as load profiles or event logs, per IEC 62056-6-2 §4.3.6 in the
53/// `spodes-rs` library.
54///
55/// Supports capturing data from the specified objects and their attributes.
56#[derive(Clone, Serialize, Deserialize)]
57pub struct ProfileGeneric {
58    version: u8,
59    logical_name: ObisCode,
60    buffer: Vec<Choice>,
61    #[serde(skip)]
62    capture_objects: Vec<(Arc<dyn InterfaceClass + Send + Sync>, u8)>,
63    /// When set via SET, overrides the Arc-based capture_objects for GET.
64    #[serde(skip)]
65    capture_objects_value: Option<CosemDataType>,
66    capture_period: u32,
67    sort_method: SortMethod,
68    sort_object: Option<CaptureObjectDefinition>,
69    entries_in_use: u32,
70    profile_entries: u32,
71}
72
73impl fmt::Debug for ProfileGeneric {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.debug_struct("ProfileGeneric")
76            .field("logical_name", &self.logical_name)
77            .field("buffer", &self.buffer)
78            .field("capture_objects", &format_args!("Vec<...> (len={})", self.capture_objects.len()))
79            .field("capture_period", &self.capture_period)
80            .field("sort_method", &self.sort_method)
81            .field("sort_object", &self.sort_object)
82            .field("entries_in_use", &self.entries_in_use)
83            .field("profile_entries", &self.profile_entries)
84            .finish()
85    }
86}
87
88impl ProfileGeneric {
89    /// Builds a new `ProfileGeneric` object from its configuration.
90    ///
91    /// # Arguments
92    /// * `config` - Configuration used to build the object.
93    ///
94    /// # Returns
95    /// A new `ProfileGeneric` structure.
96    pub fn new(config: ProfileGenericConfig) -> Self {
97        ProfileGeneric {
98            version: config.version,
99            logical_name: config.logical_name,
100            buffer: config.buffer,
101            capture_objects: config.capture_objects,
102            capture_objects_value: None,
103            capture_period: config.capture_period,
104            sort_method: config.sort_method,
105            sort_object: config.sort_object,
106            entries_in_use: config.entries_in_use,
107            profile_entries: config.profile_entries,
108        }
109    }
110
111    /// Resets the profile buffer, clearing all entries.
112    ///
113    /// # Returns
114    /// * `Ok(CosemDataType::Null)` - If the reset succeeded.
115    /// * `Err(String)` - If an error occurred.
116    fn reset(&mut self) -> CosemDataType {
117        self.buffer.clear();
118        self.entries_in_use = 0;
119        CosemDataType::Null
120    }
121
122    /// Captures a new entry into the profile buffer, reading the attribute values
123    /// from the objects listed in `capture_objects`.
124    ///
125    /// An entry holds only the values of the captured objects (a timestamp, if
126    /// needed, is provided by a `Clock` object included in `capture_objects`). For
127    /// an unsorted profile the buffer behaves as a FIFO: when full, the oldest
128    /// entry is evicted (IEC 62056-6-2, §5.2.1.2.5).
129    ///
130    /// # Returns
131    /// * `Ok(CosemDataType::Null)` - If the capture succeeded.
132    /// * `Err(String)` - If a captured object's attribute is not found.
133    fn capture(&mut self) -> Result<CosemDataType, String> {
134        let mut captured_values = Vec::new();
135
136        for (obj, attr_id) in &self.capture_objects {
137            let attributes = obj.attributes();
138            if let Some((_, value)) = attributes.iter().find(|(id, _)| *id == *attr_id) {
139                captured_values.push(value.clone());
140            } else {
141                return Err(format!("Attribute {attr_id} not found in object"));
142            }
143        }
144
145        let new_entry = CosemDataType::Structure(captured_values);
146
147        // When the buffer is full, evict the oldest entry (FIFO).
148        if self.profile_entries > 0 && self.entries_in_use >= self.profile_entries && !self.buffer.is_empty() {
149            self.buffer.remove(0);
150            self.entries_in_use -= 1;
151        }
152
153        self.buffer.push(new_entry);
154        self.entries_in_use += 1;
155
156        Ok(CosemDataType::Null)
157    }
158
159    /// Method 3 (version 0 only): `get_buffer_by_range` — returns the buffer
160    /// entries whose sort value falls within a range (IEC 62056-6-2 §5.2.1.2.3).
161    ///
162    /// Full range filtering requires evaluating the sort object of each entry;
163    /// that ordering logic is not modelled here, so this returns the whole
164    /// buffer as a best effort.
165    fn get_buffer_by_range(&self, _params: Option<CosemDataType>) -> CosemDataType {
166        CosemDataType::Array(self.buffer.clone())
167    }
168
169    /// Method 4 (version 0 only): `get_buffer_by_index` — returns the buffer
170    /// entries in the 1-based inclusive range `[from_entry, to_entry]`
171    /// (IEC 62056-6-2 §5.2.1.2.4).
172    ///
173    /// The parameter is `structure { from_entry: double-long-unsigned,
174    /// to_entry: double-long-unsigned, .. }`; when it is absent, the whole
175    /// buffer is returned.
176    fn get_buffer_by_index(&self, params: Option<CosemDataType>) -> Result<CosemDataType, String> {
177        let (from_entry, to_entry) = match params {
178            Some(CosemDataType::Structure(fields)) if fields.len() >= 2 => {
179                let from = as_u32(&fields[0]).ok_or("from_entry must be an unsigned integer")?;
180                let to = as_u32(&fields[1]).ok_or("to_entry must be an unsigned integer")?;
181                (from, to)
182            }
183            None => return Ok(CosemDataType::Array(self.buffer.clone())),
184            _ => return Err("Expected structure { from_entry, to_entry, .. }".to_string()),
185        };
186        if from_entry == 0 || to_entry < from_entry {
187            return Err("Invalid entry range (1-based, from ≤ to)".to_string());
188        }
189        let start = (from_entry - 1) as usize;
190        let end = (to_entry as usize).min(self.buffer.len());
191        let slice = if start < end { self.buffer[start..end].to_vec() } else { Vec::new() };
192        Ok(CosemDataType::Array(slice))
193    }
194}
195
196/// Reads a non-negative COSEM integer as `u32` (used for entry indices).
197fn as_u32(value: &CosemDataType) -> Option<u32> {
198    match value {
199        CosemDataType::DoubleLongUnsigned(v) => Some(*v),
200        CosemDataType::LongUnsigned(v) => Some(u32::from(*v)),
201        CosemDataType::Unsigned(v) => Some(u32::from(*v)),
202        _ => None,
203    }
204}
205
206impl InterfaceClass for ProfileGeneric {
207    fn class_id(&self) -> u16 {
208        7
209    }
210
211    fn version(&self) -> u8 {
212        // Both versions share the same attributes. In version 0 the buffer can
213        // also be read via the get_buffer_by_range/index methods; in version 1
214        // (required by СТО 34.01-5.1-006-2023, Table 7.1) those are reserved and
215        // buffer access uses selective GET instead.
216        self.version
217    }
218
219    fn logical_name(&self) -> &ObisCode {
220        &self.logical_name
221    }
222
223    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
224        let capture_objects = self.capture_objects_value.clone().unwrap_or_else(|| {
225            CosemDataType::Array(
226                self.capture_objects
227                    .iter()
228                    .map(|(obj, attr_id)| {
229                        // Attribute ids are always <128 in practice (i8-valued on the wire).
230                        #[allow(clippy::cast_possible_wrap)]
231                        let attr_id = *attr_id as i8;
232                        CosemDataType::Structure(vec![
233                            CosemDataType::LongUnsigned(obj.class_id()),
234                            CosemDataType::OctetString(obj.logical_name().to_bytes()),
235                            CosemDataType::Integer(attr_id), // attribute_index (integer)
236                            CosemDataType::LongUnsigned(0),  // data_index (long-unsigned, default 0)
237                        ])
238                    })
239                    .collect(),
240            )
241        });
242
243        vec![
244            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
245            (2, CosemDataType::Array(self.buffer.clone())),
246            (3, capture_objects),
247            (4, CosemDataType::DoubleLongUnsigned(self.capture_period)),
248            (5, CosemDataType::Unsigned(self.sort_method as u8)),
249            (6, self.sort_object.as_ref().map(|c| c.clone().into()).unwrap_or(CosemDataType::Null)),
250            (7, CosemDataType::DoubleLongUnsigned(self.entries_in_use)),
251            (8, CosemDataType::DoubleLongUnsigned(self.profile_entries)),
252        ]
253    }
254
255    fn methods(&self) -> Vec<(u8, String)> {
256        // Version 0 additionally exposes the buffer-reading methods 3 and 4.
257        if self.version == 0 {
258            vec![
259                (1, "reset".to_string()),
260                (2, "capture".to_string()),
261                (3, "get_buffer_by_range".to_string()),
262                (4, "get_buffer_by_index".to_string()),
263            ]
264        } else {
265            vec![(1, "reset".to_string()), (2, "capture".to_string())]
266        }
267    }
268
269    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
270        let mut seq_buf = Vec::new();
271        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
272        for (_, attr) in self.attributes() {
273            attr.serialize_ber(&mut seq_buf)?;
274        }
275        buf.push(0x02); // structure [2]
276        write_length(1 + self.attributes().len(), buf); // length = element count
277        buf.extend_from_slice(&seq_buf);
278        Ok(())
279    }
280
281    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
282        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
283        if !rest.is_empty() {
284            return Err(BerError::InvalidTag);
285        }
286        if let CosemDataType::Structure(seq) = tlv {
287            if seq.len() == 9 {
288                if let CosemDataType::LongUnsigned(class_id) = seq[0] {
289                    if class_id != self.class_id() {
290                        return Err(BerError::InvalidValue);
291                    }
292                } else {
293                    return Err(BerError::InvalidTag);
294                }
295                if let CosemDataType::OctetString(obis) = &seq[1] {
296                    if obis.len() == 6 {
297                        self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
298                    } else {
299                        return Err(BerError::InvalidLength);
300                    }
301                } else {
302                    return Err(BerError::InvalidTag);
303                }
304                if let CosemDataType::Array(buffer) = &seq[2] {
305                    self.buffer.clone_from(buffer);
306                } else {
307                    return Err(BerError::InvalidTag);
308                }
309                if let CosemDataType::Array(_) = &seq[3] {
310                    // capture_objects are deserialized separately, if needed
311                } else {
312                    return Err(BerError::InvalidTag);
313                }
314                if let CosemDataType::DoubleLongUnsigned(capture_period) = seq[4] {
315                    self.capture_period = capture_period;
316                } else {
317                    return Err(BerError::InvalidTag);
318                }
319                if let CosemDataType::Unsigned(sort_method) = seq[5] {
320                    self.sort_method = SortMethod::from_u8(sort_method).unwrap_or(SortMethod::Fifo);
321                } else {
322                    return Err(BerError::InvalidTag);
323                }
324                self.sort_object = CaptureObjectDefinition::try_from(&seq[6]).ok();
325                if let CosemDataType::DoubleLongUnsigned(entries_in_use) = seq[7] {
326                    self.entries_in_use = entries_in_use;
327                } else {
328                    return Err(BerError::InvalidTag);
329                }
330                if let CosemDataType::DoubleLongUnsigned(profile_entries) = seq[8] {
331                    self.profile_entries = profile_entries;
332                } else {
333                    return Err(BerError::InvalidTag);
334                }
335                return Ok(());
336            }
337            return Err(BerError::InvalidLength);
338        }
339        Err(BerError::InvalidTag)
340    }
341
342    fn set_attribute(&mut self, attribute_id: u8, value: CosemDataType) -> Result<(), String> {
343        match attribute_id {
344            3 => {
345                let CosemDataType::Array(ref list) = value else {
346                    return Err("capture_objects must be array".into());
347                };
348                for item in list {
349                    let _ = CaptureObjectDefinition::try_from(item)?;
350                }
351                self.capture_objects_value = Some(value);
352                Ok(())
353            }
354            4 => match value {
355                CosemDataType::DoubleLongUnsigned(v) => {
356                    self.capture_period = v;
357                    Ok(())
358                }
359                _ => Err("capture_period must be double-long-unsigned".into()),
360            },
361            5 => match value {
362                CosemDataType::Unsigned(v) => {
363                    self.sort_method = SortMethod::from_u8(v).unwrap_or(SortMethod::Fifo);
364                    Ok(())
365                }
366                _ => Err("sort_method must be unsigned".into()),
367            },
368            8 => match value {
369                CosemDataType::DoubleLongUnsigned(v) => {
370                    self.profile_entries = v;
371                    Ok(())
372                }
373                _ => Err("profile_entries must be double-long-unsigned".into()),
374            },
375            _ => Err(format!("ProfileGeneric attribute {attribute_id} is not writable")),
376        }
377    }
378
379    fn invoke_method(&mut self, method_id: u8, params: Option<CosemDataType>) -> Result<CosemDataType, String> {
380        match method_id {
381            1 => Ok(self.reset()),
382            2 => self.capture(),
383            // Methods 3 and 4 exist only in version 0.
384            3 if self.version == 0 => Ok(self.get_buffer_by_range(params)),
385            4 if self.version == 0 => self.get_buffer_by_index(params),
386            _ => Err(format!("Method {} not supported for ProfileGeneric version {}", method_id, self.version)),
387        }
388    }
389
390    fn as_any(&self) -> &dyn Any {
391        self
392    }
393}
394
395/// Writes a BER length octet (short or long form).
396#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
397fn write_length(length: usize, buf: &mut Vec<u8>) {
398    if length < 128 {
399        buf.push(length as u8);
400    } else {
401        let bytes = (length as u64).to_be_bytes();
402        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
403        let num_octets = 8 - first_non_zero;
404        buf.push(0x80 | num_octets as u8);
405        buf.extend_from_slice(&bytes[first_non_zero..]);
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412    use crate::interface::InterfaceClass;
413
414    fn versioned_profile(version: u8, profile_entries: u32) -> ProfileGeneric {
415        ProfileGeneric::new(ProfileGenericConfig {
416            logical_name: ObisCode::new(1, 0, 99, 1, 0, 255),
417            version,
418            buffer: vec![],
419            capture_objects: vec![],
420            capture_period: 0,
421            sort_method: SortMethod::Fifo,
422            sort_object: None,
423            entries_in_use: 0,
424            profile_entries,
425        })
426    }
427
428    fn empty_profile(profile_entries: u32) -> ProfileGeneric {
429        versioned_profile(1, profile_entries)
430    }
431
432    /// When the buffer is full, an unsorted profile evicts the oldest entry
433    /// (FIFO) instead of returning an error.
434    #[test]
435    fn capture_evicts_oldest_when_full() {
436        let mut p = empty_profile(2);
437        for _ in 0..3 {
438            p.invoke_method(2, None).expect("capture failed");
439        }
440        // Buffer and counter never exceed the capacity.
441        assert_eq!(p.attributes()[6].1, CosemDataType::DoubleLongUnsigned(2)); // entries_in_use
442        if let CosemDataType::Array(buf) = &p.attributes()[1].1 {
443            assert_eq!(buf.len(), 2);
444        } else {
445            panic!("buffer must be an array");
446        }
447    }
448
449    #[test]
450    fn reset_clears_buffer() {
451        let mut p = empty_profile(4);
452        p.invoke_method(2, None).unwrap();
453        p.invoke_method(1, None).unwrap(); // reset
454        assert_eq!(p.attributes()[6].1, CosemDataType::DoubleLongUnsigned(0));
455    }
456
457    #[test]
458    fn method_set_depends_on_version() {
459        // Version 0 exposes the two extra buffer-reading methods.
460        assert_eq!(versioned_profile(0, 4).methods().len(), 4);
461        assert_eq!(versioned_profile(1, 4).methods().len(), 2);
462        // Method 4 is available only in version 0.
463        assert!(versioned_profile(1, 4).invoke_method(4, None).is_err());
464    }
465
466    #[test]
467    fn get_buffer_by_index_slices_entries() {
468        let mut p = versioned_profile(0, 10);
469        for _ in 0..5 {
470            p.invoke_method(2, None).unwrap();
471        }
472        // Entries 2..=4 (1-based, inclusive) → 3 entries.
473        let params =
474            CosemDataType::Structure(vec![CosemDataType::DoubleLongUnsigned(2), CosemDataType::DoubleLongUnsigned(4)]);
475        let result = p.invoke_method(4, Some(params)).unwrap();
476        if let CosemDataType::Array(entries) = result {
477            assert_eq!(entries.len(), 3);
478        } else {
479            panic!("get_buffer_by_index must return an array");
480        }
481    }
482}