Skip to main content

spodes_rs/spodus/
node.rs

1//! The ИВКЭ concentrator node (СТО 34.01-5.1-013-2023, §10).
2//!
3//! [`Concentrator`] holds the ИВКЭ information model — nameplate, meter registry,
4//! discovered-meters list, access policies and journals — and assembles the
5//! upstream [`RequestDispatcher`] that serves the head-end (ИВК) with the
6//! mandatory COSEM object catalogue.
7
8use crate::classes::association_ln::AuthenticationMechanism;
9use crate::interface::InterfaceClass;
10use crate::obis::ObisCode;
11use crate::server::RequestDispatcher;
12use crate::types::CosemDataType;
13
14use super::access_policy::AccessPolicies;
15use super::catalog;
16use super::channels::ChannelList;
17use super::discovered::DiscoveredMeters;
18use super::journals::{EventJournal, ExchangeStatusJournal};
19use super::meter::MeterRegistry;
20use super::misc;
21use super::nameplate::Nameplate;
22use super::obis;
23use super::profile_filter::ProfileDataFilter;
24use super::proxy::DirectChannelTable;
25use super::push::EventMessages;
26use super::records::{CorrectionJournal, IncomingEventsTable, NumericJournal};
27use super::status::MeterStatusTable;
28use super::table_manager::TableManager;
29use super::tasks::ExchangeTasks;
30
31/// A СПОДУС concentrator (ИВКЭ): the meter aggregation model plus the upstream
32/// server it exposes to the head-end. Its [`dispatcher`](Concentrator::dispatcher)
33/// serves the full mandatory COSEM object catalogue of Appendix A.
34#[derive(Clone, Debug, Default)]
35pub struct Concentrator {
36    /// Passport data (§10.14).
37    pub nameplate: Nameplate,
38    /// Configured meters and their aggregated values (§10.2).
39    pub meters: MeterRegistry,
40    /// ИВКЭ channel list (§10.4).
41    pub channels: ChannelList,
42    /// Discovered-meters list (§10.5).
43    pub discovered: DiscoveredMeters,
44    /// Meter access policies (§10.6).
45    pub access_policies: AccessPolicies,
46    /// Meter data-exchange task list (§10.7).
47    pub exchange_tasks: ExchangeTasks,
48    /// Direct-channel (pass-through) table (§10.3).
49    pub direct_channels: DirectChannelTable,
50    /// Meter status table (§10.8).
51    pub meter_status: MeterStatusTable,
52    /// Data-exchange-status journal (§10.9).
53    pub exchange_journal: ExchangeStatusJournal,
54    /// Object-correction journal (§10.10).
55    pub correction_journal: CorrectionJournal,
56    /// Numeric meter journal (§10.11).
57    pub numeric_journal: NumericJournal,
58    /// Incoming push-events table (§8.5.10).
59    pub incoming_events: IncomingEventsTable,
60    /// ИВКЭ event journals (§10.13).
61    pub event_journals: Vec<EventJournal>,
62    /// Aggregated event push-messages (§8.5.11).
63    pub events: EventMessages,
64    /// Time-difference-with-meters delta (`0.0.94.7.141.255`).
65    pub time_delta: u8,
66    /// Discrete-inputs state bitmask (`0.0.96.3.1.255`).
67    pub discrete_inputs: u16,
68    /// Server system-title, used by the Security-setup objects.
69    pub server_system_title: Vec<u8>,
70}
71
72impl Concentrator {
73    /// Creates an empty concentrator.
74    pub fn new() -> Self {
75        Self::default()
76    }
77
78    /// Assembles the upstream [`RequestDispatcher`] populated with the full
79    /// ИВКЭ object catalogue (Appendix A).
80    pub fn dispatcher(&self) -> RequestDispatcher {
81        let mut d = RequestDispatcher::new();
82
83        // Passport data (§10.14) and its reference profile.
84        for object in self.nameplate.objects() {
85            d.add(Box::new(object));
86        }
87        d.add(Box::new(self.nameplate.profile()));
88
89        // Meter-interaction objects (§10.2..§10.11, §8.5.10).
90        d.add(Box::new(self.meters.build_meter_list()));
91        d.add(Box::new(self.direct_channels.build()));
92        d.add(Box::new(self.channels.build()));
93        d.add(Box::new(self.discovered.build()));
94        d.add(Box::new(self.access_policies.build()));
95        d.add(Box::new(self.exchange_tasks.build()));
96        d.add(Box::new(self.meter_status.build()));
97        d.add(Box::new(self.exchange_journal.build()));
98        d.add(Box::new(self.correction_journal.build()));
99        d.add(Box::new(self.numeric_journal.build()));
100        d.add(Box::new(self.incoming_events.build()));
101
102        // ИВКЭ event journals (§10.13) and single-value objects.
103        for journal in &self.event_journals {
104            d.add(Box::new(journal.build()));
105        }
106        d.add(Box::new(misc::time_delta(self.time_delta)));
107        d.add(Box::new(misc::discrete_inputs(self.discrete_inputs)));
108
109        // Notifications (§8.5).
110        d.add(Box::new(self.events.build()));
111
112        // Group-operation classes (§7): a Table manager over the meter list and
113        // a Profile data filter over the numeric journal.
114        let mut table_manager = TableManager::new(obis::meter_list(), 0);
115        if let CosemDataType::Array(rows) = self.meters.build_meter_list().attributes()[1].1.clone() {
116            table_manager.set_rows(rows);
117        }
118        d.add(Box::new(table_manager));
119        d.add(Box::new(ProfileDataFilter::new(obis::numeric_meter_journal(), vec![])));
120
121        // Standard catalogue objects (Appendix A): Clock, SAP assignment,
122        // Security setup and Association LN for the connection types.
123        d.add(Box::new(catalog::clock()));
124        d.add(Box::new(catalog::sap_assignment(vec![])));
125        let st = &self.server_system_title;
126        for (e, policy) in [(0u8, 0u8), (1, 3), (2, 3)] {
127            d.add(Box::new(catalog::security_setup(ObisCode::new(0, 0, 43, 0, e, 255), policy, vec![], st.clone())));
128        }
129        let associations = [
130            (0u8, AuthenticationMechanism::None, 0u8),
131            (1, AuthenticationMechanism::None, 0),
132            (2, AuthenticationMechanism::Lls, 1),
133            (3, AuthenticationMechanism::HlsGmac, 2),
134            (4, AuthenticationMechanism::None, 0),
135        ];
136        for (e, mechanism, security) in associations {
137            d.add(Box::new(catalog::association(
138                ObisCode::new(0, 0, 40, 0, e, 255),
139                mechanism,
140                ObisCode::new(0, 0, 43, 0, security, 255),
141            )));
142        }
143        d
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150    use crate::obis::ObisCode;
151    use crate::service::get::{GetDataResult, GetRequest, GetResponse};
152    use crate::service::{invoke_id_and_priority, AttributeDescriptor};
153    use crate::spodus::meter::MeterDescriptor;
154    use crate::spodus::obis;
155    use crate::types::CosemDataType;
156
157    fn get(dispatcher: &mut RequestDispatcher, class_id: u16, instance: ObisCode, attr: i8) -> GetResponse {
158        let request = GetRequest::Normal {
159            invoke_id_and_priority: invoke_id_and_priority(1, true, true),
160            attribute: AttributeDescriptor::new(class_id, instance, attr),
161            access_selection: None,
162        };
163        GetResponse::decode(&dispatcher.dispatch(&request.encode().unwrap()).unwrap()).unwrap()
164    }
165
166    #[test]
167    fn concentrator_serves_nameplate_and_meter_list() {
168        let mut node = Concentrator::new();
169        node.nameplate.serial_number = "IVKE-0001".to_string();
170        node.meters.add(MeterDescriptor {
171            meter_id: b"SIT12260004".to_vec(),
172            meter_model: b"SiT".to_vec(),
173            channels: vec![],
174        });
175        let mut dispatcher = node.dispatcher();
176
177        // The head-end reads the ИВКЭ serial number (0.0.96.1.0.255, Data attr 2).
178        let response = get(&mut dispatcher, 1, obis::serial_number(), 2);
179        assert_eq!(
180            response,
181            GetResponse::Normal {
182                invoke_id_and_priority: 0xC1,
183                result: GetDataResult::Data(CosemDataType::OctetString(b"IVKE-0001".to_vec())),
184            }
185        );
186
187        // And the meter list (0.0.94.7.128.255, Data attr 2) with one meter.
188        let response = get(&mut dispatcher, 1, obis::meter_list(), 2);
189        let GetResponse::Normal { result: GetDataResult::Data(CosemDataType::Array(rows)), .. } = response else {
190            panic!("expected an array of meters");
191        };
192        assert_eq!(rows.len(), 1);
193    }
194}