Skip to main content

smgw_lmn/dlms/
blocking.rs

1extern crate std;
2
3use super::{AttributeReader, protocol};
4use core::{fmt, num::NonZeroUsize};
5use protocol::{
6    axdr::Data,
7    client::{Client, ClientError, Transport},
8    security::CryptoProvider,
9    xdlms::{AttributeDescriptor, SelectiveAccess},
10};
11use std::io;
12
13/// Failure of one blocking attribute read.
14#[derive(Debug)]
15pub enum BlockingReadError {
16    /// The complete GET exchange exceeded its incoming APDU byte budget.
17    /// Establish a fresh association before retrying.
18    ResponseBudgetExceeded { limit: usize },
19    /// An earlier exchange interrupted this association.
20    ReconnectRequired,
21    /// The upstream client or its transport returned an error. An explicit
22    /// meter refusal or exception leaves the association usable.
23    Client(ClientError),
24}
25
26impl BlockingReadError {
27    /// Whether to discard this association before issuing another request.
28    pub fn requires_reconnect(&self) -> bool {
29        !matches!(
30            self,
31            Self::Client(
32                ClientError::Refused(_)
33                    | ClientError::Exception(_)
34                    | ClientError::ResponseTooLarge {
35                        reconnect_required: false,
36                        ..
37                    }
38            )
39        )
40    }
41}
42
43impl fmt::Display for BlockingReadError {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        match self {
46            Self::ResponseBudgetExceeded { limit } => {
47                write!(
48                    f,
49                    "DLMS GET exceeded the {limit}-byte response budget; reconnect"
50                )
51            }
52            Self::ReconnectRequired => f.write_str("establish a fresh DLMS association"),
53            Self::Client(error) => error.fmt(f),
54        }
55    }
56}
57
58impl core::error::Error for BlockingReadError {
59    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
60        match self {
61            Self::Client(error) => Some(error),
62            _ => None,
63        }
64    }
65}
66
67#[derive(Clone, Copy)]
68enum Exchange {
69    Idle,
70    Reading { remaining: usize },
71    Exceeded,
72    Unusable,
73}
74
75/// A blocking DLMS transport with a cumulative receive budget for each
76/// [`BlockingReader`] GET. Wrap the transport before calling [`Client::connect`].
77///
78/// Charge each received APDU, including its headers and block-transfer exchanges.
79/// Only APDUs within the budget reach the upstream client. The transport can read
80/// one further APDU into the driver's frame buffer to determine its length.
81/// Association setup and ordinary release take place outside the GET budget.
82/// Configure deadlines and lower-layer framing limits on the underlying transport.
83pub struct BudgetedTransport<T> {
84    inner: T,
85    limit: NonZeroUsize,
86    exchange: Exchange,
87}
88
89impl<T> BudgetedTransport<T> {
90    /// Set the maximum number of incoming APDU bytes per attribute GET.
91    pub fn new(inner: T, max_response_bytes: NonZeroUsize) -> Self {
92        Self {
93            inner,
94            limit: max_response_bytes,
95            exchange: Exchange::Idle,
96        }
97    }
98
99    /// Recover the underlying transport, for example after a successful release.
100    pub fn into_inner(self) -> T {
101        self.inner
102    }
103
104    fn begin_get(&mut self) -> Result<(), BlockingReadError> {
105        if !matches!(self.exchange, Exchange::Idle) {
106            self.exchange = Exchange::Unusable;
107            return Err(BlockingReadError::ReconnectRequired);
108        }
109        self.exchange = Exchange::Reading {
110            remaining: self.limit.get(),
111        };
112        Ok(())
113    }
114
115    fn finish_get<V>(&mut self, result: Result<V, ClientError>) -> Result<V, BlockingReadError> {
116        if matches!(self.exchange, Exchange::Exceeded) {
117            self.exchange = Exchange::Unusable;
118            return Err(BlockingReadError::ResponseBudgetExceeded {
119                limit: self.limit.get(),
120            });
121        }
122        // A complete value or explicit refusal ends the exchange. Other errors can
123        // leave a block or its acknowledgement outstanding on the association.
124        let result = result.map_err(BlockingReadError::Client);
125        self.exchange = if result
126            .as_ref()
127            .is_err_and(BlockingReadError::requires_reconnect)
128        {
129            Exchange::Unusable
130        } else {
131            Exchange::Idle
132        };
133        result
134    }
135
136    fn exceed(&mut self) -> io::Error {
137        self.exchange = Exchange::Exceeded;
138        io::Error::other("DLMS GET response budget exceeded")
139    }
140
141    fn start_io(&mut self) -> io::Result<Exchange> {
142        match self.exchange {
143            Exchange::Reading { remaining: 0 } | Exchange::Exceeded => Err(self.exceed()),
144            Exchange::Unusable => Err(io::Error::new(
145                io::ErrorKind::NotConnected,
146                "establish a fresh DLMS association",
147            )),
148            // Restore the exchange only after a successful I/O call. A transport
149            // error or unwinding panic leaves the association unusable.
150            _ => Ok(core::mem::replace(&mut self.exchange, Exchange::Unusable)),
151        }
152    }
153}
154
155impl<T: Transport> Transport for BudgetedTransport<T> {
156    fn send(&mut self, apdu: &[u8]) -> io::Result<()> {
157        let exchange = self.start_io()?;
158        self.inner.send(apdu)?;
159        self.exchange = exchange;
160        Ok(())
161    }
162
163    fn recv(&mut self, buf: &mut [u8]) -> io::Result<usize> {
164        let exchange = self.start_io()?;
165        let len = self.inner.recv(buf)?;
166        if len == 0 || len > buf.len() {
167            return Err(io::Error::new(
168                io::ErrorKind::InvalidData,
169                "invalid DLMS transport response length",
170            ));
171        }
172        self.exchange = match exchange {
173            Exchange::Reading { remaining } => Exchange::Reading {
174                remaining: remaining.checked_sub(len).ok_or_else(|| self.exceed())?,
175            },
176            other => other,
177        };
178        Ok(len)
179    }
180
181    fn close(&mut self) -> io::Result<()> {
182        self.exchange = Exchange::Unusable;
183        self.inner.close()
184    }
185}
186
187/// Read attributes through an established client over [`BudgetedTransport`].
188/// The host authenticates the meter and sets transport deadlines. Scratch must
189/// fit the complete encoded A-XDR value, which the result borrows directly.
190/// On a capacity error use [`BlockingReadError::requires_reconnect`] before retrying.
191///
192/// ```
193/// use core::num::NonZeroUsize;
194/// use smgw_lmn::dlms::{self, BlockingReadError, BlockingReader, BudgetedTransport, ClockRange, Counts, ReadError, Source};
195/// use smgw_core::taf15;
196/// use dlms::protocol::{client::{Client, ClientConfig, ClientError, Transport}, security::CryptoProvider};
197///
198/// fn connect<T: Transport, P: CryptoProvider>(
199///     transport: T, config: ClientConfig, provider: P, wire_budget: NonZeroUsize,
200/// ) -> Result<Client<BudgetedTransport<T>, P>, ClientError> {
201///     Client::connect(BudgetedTransport::new(transport, wire_budget), config, provider)
202/// }
203///
204/// fn backfill<T: Transport, P: CryptoProvider, const FRAME: usize, const SLOTS: usize>(
205///     client: &mut Client<BudgetedTransport<T>, P, FRAME>,
206///     authenticated_meter_id: &str,
207///     source: &Source<'_>,
208///     destination: &mut taf15::Profile<'_, SLOTS>,
209///     range: ClockRange,
210///     scratch: &mut [u8],
211/// ) -> Result<Counts, ReadError<BlockingReadError>> {
212///     let mut reader = BlockingReader::new(authenticated_meter_id, client, scratch);
213///     dlms::read_profile(&mut reader, source, range, destination)
214/// }
215/// ```
216pub struct BlockingReader<'a, T, P, const N: usize = 1024> {
217    meter_id: &'a str,
218    client: &'a mut Client<BudgetedTransport<T>, P, N>,
219    scratch: &'a mut [u8],
220}
221
222impl<'a, T, P, const N: usize> BlockingReader<'a, T, P, N> {
223    /// Bind the identity established by the host to its associated client.
224    pub fn new(
225        meter_id: &'a str,
226        client: &'a mut Client<BudgetedTransport<T>, P, N>,
227        scratch: &'a mut [u8],
228    ) -> Self {
229        Self {
230            meter_id,
231            client,
232            scratch,
233        }
234    }
235}
236
237impl<T: Transport, P: CryptoProvider, const N: usize> AttributeReader
238    for BlockingReader<'_, T, P, N>
239{
240    type Error = BlockingReadError;
241
242    fn meter_id(&self) -> &str {
243        self.meter_id
244    }
245
246    fn get(
247        &mut self,
248        attribute: AttributeDescriptor,
249        selection: Option<SelectiveAccess<'_>>,
250    ) -> Result<Data<'_>, BlockingReadError> {
251        self.client.transport_mut().begin_get()?;
252        let response = self.client.get_into(attribute, selection, self.scratch);
253        self.client.transport_mut().finish_get(response)
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    struct Link {
262        reported: usize,
263        sends: usize,
264        recvs: usize,
265        closed: bool,
266    }
267
268    impl Transport for Link {
269        fn send(&mut self, _: &[u8]) -> io::Result<()> {
270            self.sends += 1;
271            Ok(())
272        }
273
274        fn recv(&mut self, _: &mut [u8]) -> io::Result<usize> {
275            self.recvs += 1;
276            Ok(self.reported)
277        }
278
279        fn close(&mut self) -> io::Result<()> {
280            self.closed = true;
281            Ok(())
282        }
283    }
284
285    fn transport(reported: usize) -> BudgetedTransport<Link> {
286        let inner = Link {
287            reported,
288            sends: 0,
289            recvs: 0,
290            closed: false,
291        };
292        BudgetedTransport::new(inner, NonZeroUsize::new(4).unwrap())
293    }
294
295    #[test]
296    fn exhausted_credit_stops_the_next_block_request_before_send() {
297        let mut link = transport(4);
298        link.begin_get().unwrap();
299        link.send(&[1]).unwrap();
300        assert_eq!(link.recv(&mut [0; 8]).unwrap(), 4);
301        let error = link.send(&[2]).unwrap_err();
302        assert!(matches!(
303            link.finish_get::<()>(Err(error.into())),
304            Err(BlockingReadError::ResponseBudgetExceeded { limit: 4 })
305        ));
306        assert!(matches!(
307            link.begin_get(),
308            Err(BlockingReadError::ReconnectRequired)
309        ));
310        assert!(link.recv(&mut [0; 8]).is_err());
311        assert!(link.send(&[1]).is_err());
312        assert_eq!((link.inner.sends, link.inner.recvs), (1, 1));
313        link.close().unwrap();
314        assert!(link.into_inner().closed);
315    }
316
317    #[test]
318    fn invalid_lengths_interrupt_the_association() {
319        for reported in [0, 5] {
320            let mut link = transport(reported);
321            link.begin_get().unwrap();
322            let error = link.recv(&mut [0; 4]).unwrap_err();
323            assert_eq!(error.kind(), io::ErrorKind::InvalidData);
324            assert!(matches!(
325                link.finish_get::<()>(Err(error.into())),
326                Err(BlockingReadError::Client(ClientError::Io(_)))
327            ));
328            assert!(matches!(
329                link.begin_get(),
330                Err(BlockingReadError::ReconnectRequired)
331            ));
332            assert!(link.send(&[1]).is_err());
333            assert_eq!((link.inner.sends, link.inner.recvs), (0, 1));
334        }
335    }
336}