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