Skip to main content

mbus_kit/
serial.rs

1//! A blocking wired master over a real port (feature `std`): the sans-I/O state machines
2//! of [`master`](crate::master), driven over anything that is `Read + Write`.
3//!
4//! That is a serial device of an M-Bus level converter (opened at 8E1 with a **short read
5//! timeout**, e.g. 10 ms, by any serial crate or `stty`), a `TcpStream` to an Ethernet
6//! M-Bus gateway, or a test double. The driver writes each request, reads until the state
7//! machine has a complete frame or the response timeout has passed, removes a converter's
8//! echo of the request, and keeps collecting while bytes still arrive (a long frame at
9//! 2400 Bd takes more than a second).
10//!
11//! ```no_run
12//! # fn open() -> std::net::TcpStream { unimplemented!() }
13//! use mbus_kit::master::{Baud, Target};
14//! use mbus_kit::serial::Bus;
15//!
16//! let mut bus = Bus::new(open(), Baud::B2400);
17//! for telegram in bus.readout(Target::Primary(1))? {
18//!     for record in telegram.application()?.records().into_iter().flatten() {
19//!         println!("{}", record?);
20//!     }
21//! }
22//! # Ok::<(), mbus_kit::serial::Error>(())
23//! ```
24//!
25//! The port must not block forever on a read: give it a read timeout, or reads that
26//! return `TimedOut`, `WouldBlock` or `Ok(0)` when nothing arrived.
27
28extern crate std;
29
30use std::fmt;
31use std::io::{self, ErrorKind, Read, Write};
32use std::time::{Duration, Instant};
33use std::vec::Vec;
34
35use crate::app::{Address, Application};
36use crate::master::{Baud, Event, Outcome, Readout, Request, Search, SecondaryAddress, Target};
37use crate::wired::Frame;
38
39/// What can go wrong on a real bus.
40#[derive(Debug)]
41pub enum Error {
42    /// The port failed.
43    Io(io::Error),
44    /// The readout ended before the meter's data did: `outcome` says why (the meter does
45    /// not answer, the telegram limit, an undecodable telegram, another meter).
46    /// `telegrams` holds what was read before, which is only part of the meter's data.
47    Incomplete {
48        /// Why the readout is not complete; never [`Outcome::Complete`].
49        outcome: Outcome,
50        /// The telegrams read before it ended.
51        telegrams: Vec<Telegram>,
52    },
53    /// A telegram could not be decoded.
54    Invalid(crate::Error),
55}
56
57impl fmt::Display for Error {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            Self::Io(e) => write!(f, "port: {e}"),
61            Self::Incomplete { outcome, telegrams } => {
62                write!(f, "incomplete readout after {} telegram(s): {outcome}", telegrams.len())
63            }
64            Self::Invalid(e) => write!(f, "invalid reply: {e}"),
65        }
66    }
67}
68
69impl std::error::Error for Error {
70    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
71        match self {
72            Self::Io(e) => Some(e),
73            Self::Invalid(e) => Some(e),
74            Self::Incomplete { .. } => None,
75        }
76    }
77}
78
79impl From<io::Error> for Error {
80    fn from(e: io::Error) -> Self {
81        Self::Io(e)
82    }
83}
84
85impl From<crate::Error> for Error {
86    fn from(e: crate::Error) -> Self {
87        Self::Invalid(e)
88    }
89}
90
91/// One telegram of a readout, as received (a long frame).
92#[derive(Clone, PartialEq, Eq)]
93pub struct Telegram {
94    frame: Vec<u8>,
95}
96
97impl Telegram {
98    /// The frame bytes, from `68` to `16`.
99    pub fn bytes(&self) -> &[u8] {
100        &self.frame
101    }
102
103    /// The application layer: header and records.
104    pub fn application(&self) -> crate::Result<Application<'_>> {
105        match Frame::parse(&self.frame)? {
106            Some((Frame::Long { ci, data, .. }, _)) => Application::parse(ci, data),
107            _ => Err(crate::Error::InvalidHeader),
108        }
109    }
110}
111
112impl fmt::Debug for Telegram {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        write!(f, "Telegram({:02X?})", self.frame)
115    }
116}
117
118/// What a search found.
119#[derive(Clone, Debug, Default, PartialEq, Eq)]
120pub struct Found {
121    /// Every meter with a unique secondary address.
122    pub meters: Vec<Address>,
123    /// Identification numbers several meters share (see [`master::Event::Ambiguous`](crate::master::Event::Ambiguous)).
124    pub ambiguous: Vec<SecondaryAddress>,
125    /// Selections a meter acknowledged without then naming itself (see
126    /// [`master::Event::Unreadable`](crate::master::Event::Unreadable)).
127    pub unreadable: Vec<SecondaryAddress>,
128    /// Whether the whole bus was covered; `false` when the search gave up at its
129    /// selection limit (a stuck line, a babbling device).
130    pub complete: bool,
131}
132
133/// A wired M-Bus behind a port.
134#[derive(Debug)]
135pub struct Bus<P> {
136    port: P,
137    baud: Baud,
138    slack: Duration,
139    rx: Vec<u8>,
140}
141
142/// After the last byte, how long the line must stay quiet before a reply is complete:
143/// generous for USB converters that deliver in chunks (FTDI latency timer 16 ms).
144const IDLE: Duration = Duration::from_millis(40);
145
146/// How long `bytes` take on the line at `baud` (11 bits each: start, 8 data, parity, stop).
147fn transfer(bytes: usize, baud: Baud) -> Duration {
148    let bits = u64::try_from(bytes.saturating_mul(11)).unwrap_or(u64::MAX);
149    Duration::from_millis(bits.saturating_mul(1000) / u64::from(baud.bits_per_second()).max(1))
150}
151
152/// The most noise bytes in front of a converter's echo of the request.
153const ECHO_NOISE: usize = 4;
154
155/// The most bytes kept for one reply: more is noise, and the read ends.
156const MAX_REPLY: usize = 512;
157
158/// When the first byte must have arrived, and when a reply ends at the latest.
159#[derive(Clone, Copy)]
160struct Window {
161    first: Instant,
162    hard: Instant,
163}
164
165impl<P: Read + Write> Bus<P> {
166    /// A bus at `baud` (the baud rate the port is opened with), with 50 ms of slack on
167    /// every response timeout for USB and network latency.
168    pub fn new(port: P, baud: Baud) -> Self {
169        Self { port, baud, slack: Duration::from_millis(50), rx: Vec::with_capacity(512) }
170    }
171
172    /// Extra time added to every response timeout: more for a gateway on the network,
173    /// zero for a UART on the same board.
174    #[must_use]
175    pub const fn slack(mut self, slack: Duration) -> Self {
176        self.slack = slack;
177        self
178    }
179
180    /// The port, e.g. to change its baud rate after [`master::set_baud`](crate::master::set_baud).
181    pub fn port_mut(&mut self) -> &mut P {
182        &mut self.port
183    }
184
185    /// The port back.
186    pub fn into_inner(self) -> P {
187        self.port
188    }
189
190    /// Read every telegram of one meter. Anything but a complete readout is an error
191    /// ([`Error::Incomplete`]).
192    pub fn readout(&mut self, target: Target) -> Result<Vec<Telegram>, Error> {
193        self.run_readout(Readout::new(target))
194    }
195
196    /// Read every telegram with a configured [`Readout`] (retries, telegram limit,
197    /// expected meter). `Ok` only when the readout is [complete](Outcome::Complete).
198    pub fn run_readout(&mut self, mut readout: Readout) -> Result<Vec<Telegram>, Error> {
199        let mut telegrams = Vec::new();
200        while let Some(request) = readout.next_request() {
201            self.send(&request)?;
202            if !request.expects_reply() {
203                readout.timeout(&[]);
204                continue;
205            }
206            let deadline = self.deadline(&request);
207            let mut start = 0;
208            loop {
209                let more = self.receive(deadline, request.bytes(), &mut start)?;
210                let reply = self.rx.get(start..).unwrap_or(&[]);
211                // Skip line noise in front of the frame (wired::scan); wait for the rest of
212                // a frame that has started.
213                let scan = if more { crate::wired::scan(reply) } else { crate::wired::scan_ended(reply) };
214                let frame = match scan {
215                    crate::wired::Scan::Frame { skip, len, .. } => reply.get(skip..skip + len),
216                    crate::wired::Scan::NeedMore { .. } if more => continue,
217                    crate::wired::Scan::NeedMore { .. } => None,
218                };
219                let event = match frame {
220                    Some(frame) => readout.reply(frame),
221                    None => readout.timeout(reply),
222                };
223                if let Event::Telegram(_) = event {
224                    telegrams.push(Telegram { frame: frame.unwrap_or_default().to_vec() });
225                }
226                break;
227            }
228        }
229        // The state machine ends every readout (after deselecting a secondary target).
230        match readout.outcome() {
231            Some(Outcome::Complete) => Ok(telegrams),
232            outcome => Err(Error::Incomplete { outcome: outcome.unwrap_or(Outcome::NoReply), telegrams }),
233        }
234    }
235
236    /// Find every meter on the bus by secondary address (wildcard search). Each
237    /// selection waits for the whole response window, so colliding replies are seen.
238    pub fn search(&mut self) -> Result<Found, Error> {
239        self.run_search(Search::new())
240    }
241
242    /// Search with a configured [`Search`] (selection limit).
243    pub fn run_search(&mut self, mut search: Search) -> Result<Found, Error> {
244        let mut found = Found::default();
245        while let Some(request) = search.next_request() {
246            self.send(&request)?;
247            let deadline = self.deadline(&request);
248            let mut start = 0;
249            // Collect until the line is quiet: a valid frame may be the first of several.
250            while self.receive(deadline, request.bytes(), &mut start)? {}
251            let reply = self.rx.get(start..).unwrap_or(&[]);
252            let event = if reply.is_empty() { search.timeout(reply) } else { search.reply(reply) };
253            match event {
254                Event::Found(meter) => found.meters.push(meter),
255                Event::Ambiguous(id) => found.ambiguous.push(id),
256                Event::Unreadable(id) => found.unreadable.push(id),
257                // A truncated frame at the end of the window: as good as garbage.
258                Event::NeedMore => {
259                    search.timeout(reply);
260                }
261                _ => {}
262            }
263        }
264        found.complete = search.is_complete();
265        Ok(found)
266    }
267
268    /// Send a command and wait for its acknowledgement: `Ok(true)` on `E5`, `Ok(false)`
269    /// when nothing (or something else) came back. A broadcast is `Ok(true)` unread.
270    pub fn command(&mut self, request: &Request) -> Result<bool, Error> {
271        self.send(request)?;
272        if !request.expects_reply() {
273            return Ok(true);
274        }
275        let deadline = self.deadline(request);
276        let mut start = 0;
277        let ack =
278            |rx: &[u8]| matches!(crate::wired::scan(rx), crate::wired::Scan::Frame { frame: Frame::Ack, .. });
279        while self.receive(deadline, request.bytes(), &mut start)? {
280            if ack(self.rx.get(start..).unwrap_or(&[])) {
281                return Ok(true);
282            }
283        }
284        Ok(matches!(
285            crate::wired::scan_ended(self.rx.get(start..).unwrap_or(&[])),
286            crate::wired::Scan::Frame { frame: Frame::Ack, .. }
287        ))
288    }
289
290    fn deadline(&self, request: &Request) -> Window {
291        // `flush` returns before the request is on the line (a USB converter, a socket):
292        // the response timeout runs from its last bit.
293        let first = Instant::now()
294            + transfer(request.bytes().len(), self.baud)
295            + Duration::from_millis(u64::from(request.timeout_ms(self.baud)))
296            + self.slack;
297        // The longest reply worth waiting for: echo, a 261-byte frame and some noise, then
298        // a quiet line. A port that never falls silent ends here.
299        Window { first, hard: first + transfer(MAX_REPLY, self.baud) + self.idle() + self.slack }
300    }
301
302    /// The quiet time that ends a reply: [`IDLE`] plus three character times.
303    fn idle(&self) -> Duration {
304        IDLE + transfer(3, self.baud)
305    }
306
307    fn send(&mut self, request: &Request) -> io::Result<()> {
308        self.rx.clear();
309        self.port.write_all(request.bytes())?;
310        self.port.flush()
311    }
312
313    /// Read what arrives until `window.first` (for the first byte), until the line has been
314    /// quiet for [`IDLE`], or at the latest until `window.hard` or [`MAX_REPLY`] bytes. `true` when new bytes arrived (call again for more), `false`
315    /// when the reply is over. `start` skips an echo of `sent`.
316    fn receive(&mut self, window: Window, sent: &[u8], start: &mut usize) -> io::Result<bool> {
317        let mut chunk = [0u8; 256];
318        let idle = self.idle();
319        let mut until = if self.rx.len() > *start { Instant::now() + idle } else { window.first };
320        loop {
321            if self.rx.len() >= MAX_REPLY || Instant::now() >= window.hard {
322                return Ok(false);
323            }
324            let n = match self.port.read(&mut chunk) {
325                Ok(n) => n,
326                Err(e)
327                    if matches!(
328                        e.kind(),
329                        ErrorKind::TimedOut | ErrorKind::WouldBlock | ErrorKind::Interrupted
330                    ) =>
331                {
332                    0
333                }
334                Err(e) => return Err(e),
335            };
336            if let Some(bytes) = chunk.get(..n).filter(|b| !b.is_empty()) {
337                self.rx.extend_from_slice(bytes);
338                // A converter that echoes: the request comes back first, perhaps after a
339                // byte or two of noise from switching the line.
340                if *start == 0 {
341                    if let Some(at) = self.rx.windows(sent.len()).take(ECHO_NOISE + 1).position(|w| w == sent)
342                    {
343                        *start = at + sent.len();
344                        until = window.first.max(Instant::now() + idle);
345                    }
346                }
347                if self.rx.len() > *start {
348                    return Ok(true);
349                }
350                continue;
351            }
352            if Instant::now() >= until {
353                return Ok(false);
354            }
355            if n == 0 {
356                std::thread::sleep(Duration::from_millis(1));
357            }
358        }
359    }
360}