Skip to main content

spodes_rs/spodus/
journals.rs

1//! ИВКЭ journals (СТО 34.01-5.1-013-2023, §10.9 and §10.13).
2//!
3//! * The **data-exchange-status journal** (§10.9, `0.0.94.7.135.255`) records the
4//!   outcome of the read/write tasks the ИВКЭ runs against a meter.
5//! * The **event journals** (§10.13) log the ИВКЭ's own events; their structure
6//!   and codes follow ГОСТ Р 58940-2020 (timestamp + event code).
7//!
8//! Both are `ProfileGeneric` (IC 7, v1) objects; the typed models here build the
9//! buffer and the capture-object column schema.
10
11use std::sync::Arc;
12
13use crate::classes::data::Data;
14use crate::classes::profile_generic::{ProfileGeneric, ProfileGenericConfig};
15use crate::interface::InterfaceClass;
16use crate::obis::ObisCode;
17use crate::types::attrs::SortMethod;
18use crate::types::CosemDataType;
19
20use super::obis;
21
22/// `status` values of an exchange-status record (§10.9, Table 8, column 4).
23pub mod exchange_status {
24    /// Task completed successfully.
25    pub const DONE: u8 = 0;
26    /// Waiting to start.
27    pub const WAITING: u8 = 1;
28    /// Access denied.
29    pub const ACCESS_DENIED: u8 = 2;
30    /// Not supported.
31    pub const NOT_SUPPORTED: u8 = 3;
32    /// Partially completed.
33    pub const PARTIAL: u8 = 4;
34    /// Meter not found.
35    pub const NOT_FOUND: u8 = 5;
36    /// No response.
37    pub const NO_RESPONSE: u8 = 6;
38    /// Bad link.
39    pub const BAD_LINK: u8 = 7;
40}
41
42/// A helper building a capture-object column marker (`Data` at `code`, attr 2).
43fn column(code: ObisCode) -> (Arc<dyn InterfaceClass + Send + Sync>, u8) {
44    (Arc::new(Data::new(code, CosemDataType::Null)), 2u8)
45}
46
47/// One data-exchange-status record (§10.9, Table 8).
48#[derive(Clone, Debug, Default)]
49pub struct ExchangeRecord {
50    /// `task_id` — task identifier.
51    pub task_id: u32,
52    /// Meter unique identifier.
53    pub meter_uid: Vec<u8>,
54    /// Task start time, as date-time octets.
55    pub start: Vec<u8>,
56    /// Task status (see [`exchange_status`]).
57    pub status: u8,
58    /// Task end time, as date-time octets.
59    pub end: Vec<u8>,
60    /// Number of attempts.
61    pub attempts: u8,
62}
63
64impl ExchangeRecord {
65    fn to_entry(&self) -> CosemDataType {
66        // task_id is practically always <=u16::MAX (a concentrator won't
67        // schedule 65536+ tasks); the wire field is long-unsigned regardless
68        // of the wider in-memory type.
69        #[allow(clippy::cast_possible_truncation)]
70        let task_id = self.task_id as u16;
71        CosemDataType::Structure(vec![
72            CosemDataType::LongUnsigned(task_id),
73            CosemDataType::OctetString(self.meter_uid.clone()),
74            CosemDataType::DateTime(self.start.clone()),
75            CosemDataType::Unsigned(self.status),
76            CosemDataType::DateTime(self.end.clone()),
77            CosemDataType::Unsigned(self.attempts),
78        ])
79    }
80}
81
82/// The data-exchange-status journal (§10.9, `0.0.94.7.135.255`).
83#[derive(Clone, Debug, Default)]
84pub struct ExchangeStatusJournal {
85    records: Vec<ExchangeRecord>,
86}
87
88impl ExchangeStatusJournal {
89    /// Creates an empty journal.
90    pub fn new() -> Self {
91        Self::default()
92    }
93
94    /// Appends an exchange-status record.
95    pub fn append(&mut self, record: ExchangeRecord) {
96        self.records.push(record);
97    }
98
99    /// The Table-8 columns as capture-object markers.
100    fn columns() -> Vec<(Arc<dyn InterfaceClass + Send + Sync>, u8)> {
101        vec![
102            column(ObisCode::new(0, 0, 94, 7, 135, 1)),  // task_id
103            column(ObisCode::new(0, 0, 94, 7, 128, 10)), // meter uid
104            column(ObisCode::new(0, 0, 94, 7, 135, 2)),  // start
105            column(ObisCode::new(0, 0, 94, 7, 135, 3)),  // status
106            column(ObisCode::new(0, 0, 94, 7, 135, 4)),  // end
107            column(ObisCode::new(0, 0, 94, 7, 135, 5)),  // attempts
108        ]
109    }
110
111    /// Builds the COSEM `ProfileGeneric` (IC 7, v1) journal object.
112    pub fn build(&self) -> ProfileGeneric {
113        let buffer: Vec<CosemDataType> = self.records.iter().map(ExchangeRecord::to_entry).collect();
114        // An in-memory buffer never approaches u32::MAX entries.
115        #[allow(clippy::cast_possible_truncation)]
116        let entries_in_use = buffer.len() as u32;
117        ProfileGeneric::new(ProfileGenericConfig {
118            logical_name: obis::exchange_status_journal(),
119            version: 1,
120            buffer,
121            capture_objects: Self::columns(),
122            capture_period: 0,
123            sort_method: SortMethod::Fifo,
124            sort_object: None,
125            entries_in_use,
126            profile_entries: 0,
127        })
128    }
129}
130
131/// An ИВКЭ event journal (§10.13), following ГОСТ Р 58940-2020: each entry is a
132/// timestamp and an event code, captured by a Clock and an event register.
133#[derive(Clone, Debug)]
134pub struct EventJournal {
135    logical_name: ObisCode,
136    entries: Vec<(Vec<u8>, u16)>,
137}
138
139impl EventJournal {
140    /// Creates an empty event journal with the given OBIS (one of the §10.13
141    /// codes, e.g. [`obis::access_control_log`]).
142    pub fn new(logical_name: ObisCode) -> Self {
143        EventJournal { logical_name, entries: Vec::new() }
144    }
145
146    /// Logs an event: `timestamp` (date-time octets) and its code.
147    pub fn log(&mut self, timestamp: Vec<u8>, code: u16) {
148        self.entries.push((timestamp, code));
149    }
150
151    /// Builds the COSEM `ProfileGeneric` (IC 7, v1) journal object.
152    pub fn build(&self) -> ProfileGeneric {
153        let buffer: Vec<CosemDataType> = self
154            .entries
155            .iter()
156            .map(|(ts, code)| {
157                CosemDataType::Structure(vec![CosemDataType::DateTime(ts.clone()), CosemDataType::LongUnsigned(*code)])
158            })
159            .collect();
160        // An in-memory buffer never approaches u32::MAX entries.
161        #[allow(clippy::cast_possible_truncation)]
162        let entries_in_use = buffer.len() as u32;
163        let columns = vec![
164            column(ObisCode::new(0, 0, 1, 0, 0, 255)), // Clock timestamp
165            column(self.logical_name.clone()),         // event code register
166        ];
167        ProfileGeneric::new(ProfileGenericConfig {
168            logical_name: self.logical_name.clone(),
169            version: 1,
170            buffer,
171            capture_objects: columns,
172            capture_period: 0,
173            sort_method: SortMethod::Fifo,
174            sort_object: None,
175            entries_in_use,
176            profile_entries: 0,
177        })
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn exchange_status_journal_builds_profile() {
187        let mut journal = ExchangeStatusJournal::new();
188        journal.append(ExchangeRecord {
189            task_id: 7,
190            meter_uid: b"SIT12260004".to_vec(),
191            start: vec![0x07, 0xE6, 0x07, 0x04],
192            status: exchange_status::DONE,
193            end: vec![0x07, 0xE6, 0x07, 0x04],
194            attempts: 1,
195        });
196        let profile = journal.build();
197        assert_eq!(profile.class_id(), 7);
198        assert_eq!(profile.logical_name(), &obis::exchange_status_journal());
199
200        let attrs = profile.attributes();
201        let CosemDataType::Array(rows) = &attrs[1].1 else { panic!("buffer array") };
202        let CosemDataType::Structure(cols) = &rows[0] else { panic!("row structure") };
203        assert_eq!(cols.len(), 6);
204        assert_eq!(cols[0], CosemDataType::LongUnsigned(7));
205        assert_eq!(cols[3], CosemDataType::Unsigned(exchange_status::DONE));
206        // Six capture columns.
207        let CosemDataType::Array(caps) = &attrs[2].1 else { panic!("capture array") };
208        assert_eq!(caps.len(), 6);
209    }
210
211    #[test]
212    fn event_journal_logs_events() {
213        let mut journal = EventJournal::new(obis::access_control_log());
214        journal.log(vec![0x07, 0xE6, 0x07, 0x04], 0x0011);
215        let profile = journal.build();
216        assert_eq!(profile.logical_name(), &obis::access_control_log());
217
218        let attrs = profile.attributes();
219        let CosemDataType::Array(rows) = &attrs[1].1 else { panic!("buffer array") };
220        let CosemDataType::Structure(cols) = &rows[0] else { panic!("row structure") };
221        assert_eq!(cols.len(), 2);
222        assert_eq!(cols[1], CosemDataType::LongUnsigned(0x0011));
223        // Two capture columns: clock + event register.
224        let CosemDataType::Array(caps) = &attrs[2].1 else { panic!("capture array") };
225        assert_eq!(caps.len(), 2);
226    }
227}