Skip to main content

spodes_rs/transport/
mod.rs

1//! Transport layer for the DLMS/COSEM communication profiles.
2//!
3//! The layer is split into two independent concerns:
4//!
5//! * [`crate::transport::PhysicalTransport`] — a bidirectional byte channel abstracting the
6//!   concrete medium (serial line, TCP connection, UDP socket). It is provided
7//!   by the user of the library.
8//! * [`crate::transport::DataLinkLayer`] — a framing sub-layer that carries xDLMS APDUs over a
9//!   physical transport. Two implementations are provided (added in later
10//!   commits): an HDLC layer usable over any medium, and a wrapper layer for
11//!   TCP/UDP only.
12//!
13//! Because the framing sub-layers are generic over the physical transport, the
14//! same HDLC implementation works over a serial line and over TCP, while the
15//! wrapper sub-layer is bounded on [`crate::transport::NetworkTransport`] so it can only be built
16//! over TCP/UDP.
17
18use std::collections::VecDeque;
19use std::io;
20use std::time::Duration;
21
22pub mod hdlc;
23pub mod wrapper;
24
25/// A bidirectional byte channel abstracting the physical medium.
26///
27/// Framing sub-layers (HDLC, wrapper) are built on top of this trait, so they
28/// are independent of whether the underlying medium is a serial line, a TCP
29/// connection or a UDP socket.
30pub trait PhysicalTransport {
31    /// Sends all of `data` over the medium.
32    fn send(&mut self, data: &[u8]) -> io::Result<()>;
33
34    /// Receives bytes into `buf`, returning the number of bytes read. A return
35    /// value of 0 indicates end of stream.
36    fn receive(&mut self, buf: &mut [u8]) -> io::Result<usize>;
37
38    /// Sets the maximum time a subsequent [`receive`](Self::receive) call may
39    /// block before returning an [`io::ErrorKind::TimedOut`] (or
40    /// [`io::ErrorKind::WouldBlock`]) error. `None` waits indefinitely (the
41    /// default behaviour, and what every `receive` implementation must do
42    /// when this method is never called).
43    ///
44    /// Used by [`crate::transport::hdlc::HdlcLayer`] to enforce the IEC 62056-46
45    /// inter-octet and inactivity timeouts. The default implementation is a
46    /// no-op that returns `Ok(())`: a transport that ignores this request
47    /// (i.e. keeps blocking indefinitely) makes those timeouts inactive but
48    /// otherwise behaves exactly as before this method existed — mirrors
49    /// [`std::net::TcpStream::set_read_timeout`], which most network
50    /// transports can delegate to directly.
51    fn set_read_timeout(&mut self, timeout: Option<Duration>) -> io::Result<()> {
52        let _ = timeout;
53        Ok(())
54    }
55}
56
57/// Marker trait for network transports (TCP/UDP).
58///
59/// The wrapper sub-layer is defined only over TCP/UDP, so it is bounded on this
60/// trait. HDLC works over any [`crate::transport::PhysicalTransport`] (serial or network) and does
61/// not require it.
62pub trait NetworkTransport: PhysicalTransport {}
63
64/// A data link / framing sub-layer that carries xDLMS APDUs.
65///
66/// Implemented by the HDLC and wrapper sub-layers.
67pub trait DataLinkLayer {
68    /// Frames and sends one APDU.
69    fn send_apdu(&mut self, apdu: &[u8]) -> io::Result<()>;
70
71    /// Receives and de-frames one APDU.
72    fn receive_apdu(&mut self) -> io::Result<Vec<u8>>;
73
74    /// Client SAP learned from the data-link peer address, when known.
75    fn client_sap(&self) -> Option<u8> {
76        None
77    }
78}
79
80/// An in-memory loopback transport, primarily for tests: bytes written with
81/// [`PhysicalTransport::send`] are read back by [`PhysicalTransport::receive`].
82///
83/// It implements [`crate::transport::NetworkTransport`], so it can back either framing sub-layer.
84#[derive(Debug, Default)]
85pub struct MemoryTransport {
86    buffer: VecDeque<u8>,
87}
88
89impl MemoryTransport {
90    /// Creates an empty transport.
91    pub fn new() -> Self {
92        MemoryTransport { buffer: VecDeque::new() }
93    }
94
95    /// Number of bytes currently buffered (sent but not yet received).
96    pub fn buffered(&self) -> usize {
97        self.buffer.len()
98    }
99
100    /// Feeds raw bytes to be returned by subsequent `receive` calls.
101    pub fn feed(&mut self, data: &[u8]) {
102        self.buffer.extend(data.iter().copied());
103    }
104}
105
106impl PhysicalTransport for MemoryTransport {
107    fn send(&mut self, data: &[u8]) -> io::Result<()> {
108        self.buffer.extend(data.iter().copied());
109        Ok(())
110    }
111
112    fn receive(&mut self, buf: &mut [u8]) -> io::Result<usize> {
113        let n = buf.len().min(self.buffer.len());
114        for slot in buf.iter_mut().take(n) {
115            *slot = self.buffer.pop_front().unwrap();
116        }
117        Ok(n)
118    }
119}
120
121impl NetworkTransport for MemoryTransport {}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn memory_transport_round_trips_bytes() {
129        let mut t = MemoryTransport::new();
130        t.send(&[1, 2, 3, 4]).unwrap();
131        assert_eq!(t.buffered(), 4);
132        let mut buf = [0u8; 2];
133        assert_eq!(t.receive(&mut buf).unwrap(), 2);
134        assert_eq!(buf, [1, 2]);
135        assert_eq!(t.receive(&mut buf).unwrap(), 2);
136        assert_eq!(buf, [3, 4]);
137        // Empty now.
138        assert_eq!(t.receive(&mut buf).unwrap(), 0);
139    }
140}