Skip to main content

smgw_lmn/simulator/
meter.rs

1use super::{
2    ENERGY, ID, MEASURED, PROFILE, Protocol, STATUS, sml, std,
3    tcp::{CLIENT_SAP, Link, MAX_APDU, METER_SAP, READ_ONLY, SESSION_LIMIT, Timed},
4};
5use crate::dlms::{
6    ClockRange,
7    clock::utc_clock,
8    protocol::{
9        axdr::{Data, DateTime, Unit},
10        codec::{self, Encode, Writer},
11        cosem::{AttributeAccess, CaptureObject},
12        obis::Obis,
13        security::RustCryptoProvider,
14        server::{ObjectStore, Server, ServerConfig, ServerState, StoreResult},
15        xdlms::{DataAccessResult, SelectiveAccess},
16    },
17};
18use core::cell::RefCell;
19use std::{io, net::TcpStream, time::Instant};
20
21const COLUMNS: [CaptureObject; 4] = [
22    STATUS,
23    CaptureObject::new(3, ENERGY, 2, 0),
24    CaptureObject::clock(),
25    MEASURED,
26];
27
28/// Choose which source records the simulated meter reports.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum History {
31    /// Only the opening register has been observed.
32    Opening,
33    /// The middle quarter-hour is missing.
34    Gap,
35    /// All three slots contain the original readings.
36    Filled,
37    /// The middle slot conflicts with its previously reported energy reading.
38    Revised,
39}
40
41/// One day of quarter-hour observations, including the latest register.
42pub type VirtualMeter = mme::Meter<'static, 96>;
43
44impl History {
45    /// Build a reproducible starting state, including a conflicting replay for gateway tests.
46    pub fn meter(self) -> VirtualMeter {
47        let mut meter = VirtualMeter::new(ID, 0, 12_340).unwrap();
48        if self != Self::Opening {
49            let middle = 15 + u32::from(self == Self::Revised);
50            if self != Self::Gap {
51                meter.advance(900, middle).unwrap();
52            }
53            meter
54                .advance(1800, 12_370 - meter.current().import_dwh)
55                .unwrap();
56        }
57        meter
58    }
59}
60
61/// Read-only object store for the commissioned simulation profile.
62pub struct Meter<'a> {
63    history: &'a RefCell<VirtualMeter>,
64    on_profile_read: Option<&'a dyn Fn()>,
65}
66
67impl<'a> Meter<'a> {
68    /// Project the caller's current import register and history.
69    pub fn new(history: &'a RefCell<VirtualMeter>) -> Self {
70        Self {
71            history,
72            on_profile_read: None,
73        }
74    }
75}
76
77// Accept the fixture's inclusive, whole-row clock ranges.
78fn clock_range(selection: Option<SelectiveAccess<'_>>) -> StoreResult<ClockRange> {
79    let invalid = DataAccessResult::ScopeOfAccessViolated;
80    let range = selection
81        .filter(|s| s.selector == 1)
82        .and_then(|s| s.parameters.as_structure())
83        .filter(|s| s.len() == 4)
84        .ok_or(invalid)?;
85    let field = |i| range.get(i).map_err(|_| invalid);
86    if CaptureObject::from_data(&field(0)?).map_err(|_| invalid)? != CaptureObject::clock()
87        || !field(3)?.as_array().is_some_and(|a| a.is_empty())
88    {
89        return Err(invalid);
90    }
91    let time = |i| {
92        let Data::OctetString(bytes) = field(i)? else {
93            return Err(invalid);
94        };
95        Ok(DateTime::from_bytes(bytes.try_into().map_err(|_| invalid)?))
96    };
97    ClockRange::new(time(1)?, time(2)?).map_err(|_| invalid)
98}
99
100impl Meter<'_> {
101    fn buffer(
102        &self,
103        selection: Option<SelectiveAccess<'_>>,
104        w: &mut dyn Writer,
105    ) -> StoreResult<()> {
106        let range = clock_range(selection)?;
107        if let Some(notify) = self.on_profile_read {
108            notify();
109        }
110        let history = self.history.borrow();
111        let rows = history.readings().filter(|r| range.contains(r.utc));
112        let encode = || -> codec::Result<()> {
113            w.write_u8(1)?; // A-XDR array
114            w.write_length(rows.clone().count())?;
115            for reading in rows {
116                w.write_bytes(&[2, 4])?; // structure in capture-object order
117                Data::Unsigned(1).encode(w)?;
118                Data::DoubleLongUnsigned(reading.import_dwh).encode(w)?;
119                // The simulator observes a scheduled reading two seconds after its grid time.
120                for offset in [0, 2] {
121                    let time = reading
122                        .utc
123                        .checked_add(offset)
124                        .and_then(|utc| utc_clock(utc).ok())
125                        .ok_or(codec::Error::new(codec::ErrorKind::InvalidValue, 0))?;
126                    Data::OctetString(&time.to_bytes()).encode(w)?;
127                }
128            }
129            Ok(())
130        };
131        encode().map_err(|_| DataAccessResult::OtherReason)
132    }
133}
134
135impl ObjectStore for Meter<'_> {
136    fn get_attribute(
137        &self,
138        class: u16,
139        name: Obis,
140        attr: i8,
141        selection: Option<SelectiveAccess<'_>>,
142        w: &mut dyn Writer,
143    ) -> StoreResult<()> {
144        if (class, name, attr) == (7, PROFILE, 2) {
145            return self.buffer(selection, w);
146        }
147        if selection.is_some() {
148            return Err(DataAccessResult::ScopeOfAccessViolated);
149        }
150        let encoded = match (class, name, attr) {
151            (7, PROFILE, 3) => w
152                .write_bytes(&[1, 4])
153                .and_then(|()| COLUMNS.iter().try_for_each(|column| column.encode(w))),
154            (7, PROFILE, 4) => Data::DoubleLongUnsigned(900).encode(w),
155            (3, ENERGY, 2) => {
156                Data::DoubleLongUnsigned(self.history.borrow().current().import_dwh).encode(w)
157            }
158            (3, ENERGY, 3) => w.write_bytes(&[2, 2, 0x0f, 0xff, 0x16, Unit::WATT_HOUR.0]),
159            _ => return Err(DataAccessResult::ObjectUndefined),
160        };
161        encoded.map_err(|_| DataAccessResult::OtherReason)
162    }
163
164    fn attribute_access(&self, class: u16, name: Obis, attr: i8) -> AttributeAccess {
165        match (class, name, attr) {
166            (7, PROFILE, 2..=4) | (3, ENERGY, 2..=3) => AttributeAccess::READ,
167            _ => AttributeAccess::empty(),
168        }
169    }
170}
171
172/// Serve one loopback session for up to four seconds: a public-client DLMS association
173/// or one SML request. The caller owns the listener. The callback observes a selected
174/// profile read and receives the session deadline.
175pub fn serve_meter(
176    socket: TcpStream,
177    protocol: Protocol,
178    history: VirtualMeter,
179    on_profile_read: impl Fn(Instant),
180) -> io::Result<()> {
181    let deadline = Instant::now() + SESSION_LIMIT;
182    if history.id() != ID {
183        return Err(io::Error::new(
184            io::ErrorKind::InvalidInput,
185            "unexpected commissioned meter identity",
186        ));
187    }
188    if protocol == Protocol::Sml {
189        let mut stream = Timed::new(socket, deadline)?;
190        sml::meter::serve(&mut stream, &history, || on_profile_read(deadline))?;
191        return stream.shutdown();
192    }
193    let mut link = Link::new(socket, deadline, METER_SAP, CLIENT_SAP)?;
194    let notify = || on_profile_read(deadline);
195    let history = RefCell::new(history);
196    let meter = Meter {
197        history: &history,
198        on_profile_read: Some(&notify),
199    };
200    let mut server = Server::<_, RustCryptoProvider>::new(
201        ServerConfig {
202            conformance: READ_ONLY,
203            max_pdu_size: MAX_APDU as u16,
204            ..ServerConfig::default()
205        },
206        meter,
207        RustCryptoProvider::default(),
208    );
209    let mut request = [0; MAX_APDU];
210    let mut reply = [0; MAX_APDU];
211    while server.state() != ServerState::Closed {
212        let len = link.recv_apdu(&mut request)?;
213        let n = server
214            .handle(&request[..len], &mut reply)
215            .map_err(io::Error::other)?;
216        if n > 0 {
217            link.send_apdu(&reply[..n])?;
218        }
219    }
220    Ok(())
221}