Skip to main content

spodes_rs/spodus/
collect.rs

1//! Downstream meter polling and aggregation (СТО 34.01-5.1-013-2023, §10).
2//!
3//! The ИВКЭ, acting as a DLMS client to the meters, reads their attributes and
4//! stores the results in its aggregation cache so they can be served upstream
5//! without re-polling.
6
7use crate::obis::ObisCode;
8use crate::service::get::{GetDataResult, GetResponse};
9use crate::session::ClientSession;
10use crate::transport::DataLinkLayer;
11
12use super::meter::MeterRegistry;
13
14/// A meter attribute to poll: `(class_id, logical_name, attribute_id)`.
15pub type AttributeRef = (u16, ObisCode, i8);
16
17/// Polls `attributes` of a meter over its downstream `session` and stores the
18/// successfully read values in the registry's aggregation cache. Returns the
19/// number of attributes read successfully.
20pub fn poll_meter<L: DataLinkLayer>(
21    session: &mut ClientSession<L>,
22    registry: &mut MeterRegistry,
23    meter_id: &[u8],
24    attributes: &[AttributeRef],
25) -> usize {
26    let mut read = 0;
27    for (class_id, obis, attribute) in attributes {
28        if let Ok(GetResponse::Normal { result: GetDataResult::Data(value), .. }) =
29            session.get(*class_id, obis.clone(), *attribute)
30        {
31            // Attribute ids are always <128 in practice (i8-valued on the wire).
32            #[allow(clippy::cast_sign_loss)]
33            let attribute_id = *attribute as u8;
34            registry.store(meter_id, obis.clone(), attribute_id, value);
35            read += 1;
36        }
37    }
38    read
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44    use crate::classes::data::Data;
45    use crate::server::RequestDispatcher;
46    use crate::spodus::meter::MeterDescriptor;
47    use crate::types::CosemDataType;
48    use std::io;
49
50    /// A loopback link that dispatches each request to a local "meter" server.
51    struct LocalLink {
52        server: RequestDispatcher,
53        pending: Option<Vec<u8>>,
54    }
55
56    impl DataLinkLayer for LocalLink {
57        fn send_apdu(&mut self, apdu: &[u8]) -> io::Result<()> {
58            self.pending = Some(self.server.dispatch(apdu).expect("dispatch"));
59            Ok(())
60        }
61        fn receive_apdu(&mut self) -> io::Result<Vec<u8>> {
62            Ok(self.pending.take().expect("a response"))
63        }
64    }
65
66    #[test]
67    fn poll_meter_updates_aggregation_cache() {
68        // The downstream "meter" exposes an energy register.
69        let energy = ObisCode::new(1, 0, 1, 8, 0, 255);
70        let mut meter_server = RequestDispatcher::new();
71        meter_server.add(Box::new(Data::new(energy.clone(), CosemDataType::DoubleLongUnsigned(123_456))));
72        let mut session = ClientSession::new(LocalLink { server: meter_server, pending: None });
73
74        let mut registry = MeterRegistry::new();
75        registry.add(MeterDescriptor { meter_id: b"SIT12260004".to_vec(), ..Default::default() });
76
77        let read = poll_meter(&mut session, &mut registry, b"SIT12260004", &[(1, energy.clone(), 2)]);
78        assert_eq!(read, 1);
79        assert_eq!(registry.cached(b"SIT12260004", &energy, 2), Some(&CosemDataType::DoubleLongUnsigned(123_456)));
80    }
81}