Skip to main content

spodes_rs/spodus/
discovered.rs

1//! Discovered-meters list (СТО 34.01-5.1-013-2023, §10.5, `0.0.94.7.131.255`).
2//!
3//! The ИВКЭ keeps a reference list of the meters it has found on its channels,
4//! exposed as a `ProfileGeneric` (IC 7, v1) whose buffer rows follow the Table-6
5//! column layout: `meter_id`, `meter_model`, `channel_id`, `address`,
6//! first-contact time and last-contact time.
7
8use std::sync::Arc;
9
10use crate::classes::data::Data;
11use crate::classes::profile_generic::{ProfileGeneric, ProfileGenericConfig};
12use crate::interface::InterfaceClass;
13use crate::obis::ObisCode;
14use crate::types::attrs::SortMethod;
15use crate::types::CosemDataType;
16
17use super::obis;
18
19/// One entry of the discovered-meters list (§10.5, Table 6).
20#[derive(Clone, Debug, Default)]
21pub struct DiscoveredMeter {
22    /// `meter_id` — meter identifier.
23    pub meter_id: Vec<u8>,
24    /// `meter_model` — meter model.
25    pub meter_model: Vec<u8>,
26    /// `channel_id` — communication channel.
27    pub channel_id: u8,
28    /// `address` — address within the channel.
29    pub address: u16,
30    /// First-contact time, as date-time octets.
31    pub first_seen: Vec<u8>,
32    /// Last-contact time, as date-time octets.
33    pub last_seen: Vec<u8>,
34}
35
36impl DiscoveredMeter {
37    /// The Table-6 buffer row for this meter.
38    fn to_entry(&self) -> CosemDataType {
39        CosemDataType::Structure(vec![
40            CosemDataType::OctetString(self.meter_id.clone()),
41            CosemDataType::OctetString(self.meter_model.clone()),
42            CosemDataType::Unsigned(self.channel_id),
43            CosemDataType::LongUnsigned(self.address),
44            CosemDataType::DateTime(self.first_seen.clone()),
45            CosemDataType::DateTime(self.last_seen.clone()),
46        ])
47    }
48}
49
50/// The discovered-meters list (§10.5).
51#[derive(Clone, Debug, Default)]
52pub struct DiscoveredMeters {
53    records: Vec<DiscoveredMeter>,
54}
55
56impl DiscoveredMeters {
57    /// Creates an empty list.
58    pub fn new() -> Self {
59        Self::default()
60    }
61
62    /// Appends a discovered meter.
63    pub fn record(&mut self, meter: DiscoveredMeter) {
64        self.records.push(meter);
65    }
66
67    /// Number of recorded meters.
68    pub fn len(&self) -> usize {
69        self.records.len()
70    }
71
72    /// Whether the list is empty.
73    pub fn is_empty(&self) -> bool {
74        self.records.is_empty()
75    }
76
77    /// The Table-6 columns as capture-object markers (Data at `…131.0..5`, attr 2).
78    fn columns() -> Vec<(Arc<dyn InterfaceClass + Send + Sync>, u8)> {
79        (0u8..6)
80            .map(|i| {
81                let obj: Arc<dyn InterfaceClass + Send + Sync> =
82                    Arc::new(Data::new(ObisCode::new(0, 0, 94, 7, 131, i), CosemDataType::Null));
83                (obj, 2u8)
84            })
85            .collect()
86    }
87
88    /// Builds the COSEM `ProfileGeneric` (IC 7, v1) object for this list.
89    pub fn build(&self) -> ProfileGeneric {
90        let buffer: Vec<CosemDataType> = self.records.iter().map(DiscoveredMeter::to_entry).collect();
91        // An in-memory buffer never approaches u32::MAX entries.
92        #[allow(clippy::cast_possible_truncation)]
93        let entries_in_use = buffer.len() as u32;
94        ProfileGeneric::new(ProfileGenericConfig {
95            logical_name: obis::discovered_meters(),
96            version: 1,
97            buffer,
98            capture_objects: Self::columns(),
99            capture_period: 0,
100            sort_method: SortMethod::Fifo,
101            sort_object: None,
102            entries_in_use,
103            profile_entries: 0,
104        })
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    #[test]
113    fn discovered_meters_builds_profile_generic() {
114        let mut list = DiscoveredMeters::new();
115        list.record(DiscoveredMeter {
116            meter_id: b"MTR-0001".to_vec(),
117            meter_model: b"SiT".to_vec(),
118            channel_id: 1,
119            address: 0x0010,
120            first_seen: vec![0x07, 0xE6, 0x07, 0x04],
121            last_seen: vec![0x07, 0xE6, 0x07, 0x05],
122        });
123        assert_eq!(list.len(), 1);
124
125        let profile = list.build();
126        assert_eq!(profile.class_id(), 7);
127        assert_eq!(profile.version(), 1);
128        assert_eq!(profile.logical_name(), &obis::discovered_meters());
129
130        let attrs = profile.attributes();
131        // Attribute 2: the buffer — one row with the six typed columns.
132        let CosemDataType::Array(rows) = &attrs[1].1 else { panic!("buffer is an array") };
133        assert_eq!(rows.len(), 1);
134        let CosemDataType::Structure(cols) = &rows[0] else { panic!("row is a structure") };
135        assert_eq!(cols.len(), 6);
136        assert_eq!(cols[0], CosemDataType::OctetString(b"MTR-0001".to_vec()));
137        assert_eq!(cols[2], CosemDataType::Unsigned(1));
138        assert_eq!(cols[3], CosemDataType::LongUnsigned(0x0010));
139
140        // Attribute 3: six capture-object definitions.
141        let CosemDataType::Array(caps) = &attrs[2].1 else { panic!("capture objects is an array") };
142        assert_eq!(caps.len(), 6);
143    }
144}