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, 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 meter did not answer, after every retry.
45    NoReply,
46    /// The meter answered with a frame that is not a valid telegram.
47    Invalid(crate::Error),
48}
49
50impl fmt::Display for Error {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::Io(e) => write!(f, "port: {e}"),
54            Self::NoReply => f.write_str("the meter does not answer"),
55            Self::Invalid(e) => write!(f, "invalid reply: {e}"),
56        }
57    }
58}
59
60impl std::error::Error for Error {
61    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
62        match self {
63            Self::Io(e) => Some(e),
64            Self::Invalid(e) => Some(e),
65            Self::NoReply => None,
66        }
67    }
68}
69
70impl From<io::Error> for Error {
71    fn from(e: io::Error) -> Self {
72        Self::Io(e)
73    }
74}
75
76impl From<crate::Error> for Error {
77    fn from(e: crate::Error) -> Self {
78        Self::Invalid(e)
79    }
80}
81
82/// One telegram of a readout, as received (a long frame).
83#[derive(Clone, PartialEq, Eq)]
84pub struct Telegram {
85    frame: Vec<u8>,
86}
87
88impl Telegram {
89    /// The frame bytes, from `68` to `16`.
90    pub fn bytes(&self) -> &[u8] {
91        &self.frame
92    }
93
94    /// The application layer: header and records.
95    pub fn application(&self) -> crate::Result<Application<'_>> {
96        match Frame::parse(&self.frame)? {
97            Some((Frame::Long { ci, data, .. }, _)) => Application::parse(ci, data),
98            _ => Err(crate::Error::InvalidHeader),
99        }
100    }
101}
102
103impl fmt::Debug for Telegram {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        write!(f, "Telegram({:02X?})", self.frame)
106    }
107}
108
109/// What a search found.
110#[derive(Clone, Debug, Default, PartialEq, Eq)]
111pub struct Found {
112    /// Every meter with a unique secondary address.
113    pub meters: Vec<Address>,
114    /// Identification numbers several meters share (see [`master::Event::Ambiguous`](crate::master::Event::Ambiguous)).
115    pub ambiguous: Vec<SecondaryAddress>,
116    /// Whether the whole bus was covered; `false` when the search gave up at its
117    /// selection limit (a stuck line, a babbling device).
118    pub complete: bool,
119}
120
121/// A wired M-Bus behind a port.
122#[derive(Debug)]
123pub struct Bus<P> {
124    port: P,
125    baud: Baud,
126    slack: Duration,
127    rx: Vec<u8>,
128}
129
130/// After the last byte, how long the line must stay quiet before a reply is complete:
131/// generous for USB converters that deliver in chunks (FTDI latency timer 16 ms).
132const IDLE: Duration = Duration::from_millis(40);
133
134/// The most bytes kept for one reply: more is noise, and the read ends.
135const MAX_REPLY: usize = 512;
136
137/// When the first byte must have arrived, and when a reply ends at the latest.
138#[derive(Clone, Copy)]
139struct Window {
140    first: Instant,
141    hard: Instant,
142}
143
144impl<P: Read + Write> Bus<P> {
145    /// A bus at `baud` (the baud rate the port is opened with), with 50 ms of slack on
146    /// every response timeout for USB and network latency.
147    pub fn new(port: P, baud: Baud) -> Self {
148        Self { port, baud, slack: Duration::from_millis(50), rx: Vec::with_capacity(512) }
149    }
150
151    /// Extra time added to every response timeout: more for a gateway on the network,
152    /// zero for a UART on the same board.
153    #[must_use]
154    pub const fn slack(mut self, slack: Duration) -> Self {
155        self.slack = slack;
156        self
157    }
158
159    /// The port, e.g. to change its baud rate after [`master::set_baud`](crate::master::set_baud).
160    pub fn port_mut(&mut self) -> &mut P {
161        &mut self.port
162    }
163
164    /// The port back.
165    pub fn into_inner(self) -> P {
166        self.port
167    }
168
169    /// Read every telegram of one meter.
170    pub fn readout(&mut self, target: Target) -> Result<Vec<Telegram>, Error> {
171        self.run_readout(Readout::new(target))
172    }
173
174    /// Read every telegram with a configured [`Readout`] (retries, telegram limit).
175    pub fn run_readout(&mut self, mut readout: Readout) -> Result<Vec<Telegram>, Error> {
176        let mut telegrams = Vec::new();
177        while let Some(request) = readout.next_request() {
178            self.send(&request)?;
179            if !request.expects_reply() {
180                readout.timeout(&[]);
181                continue;
182            }
183            let deadline = self.deadline(&request);
184            let mut start = 0;
185            loop {
186                let more = self.receive(deadline, request.bytes(), &mut start)?;
187                let reply = self.rx.get(start..).unwrap_or(&[]);
188                // Skip line noise in front of the frame (wired::scan); wait for the rest of
189                // a frame that has started.
190                let frame = match crate::wired::scan(reply) {
191                    crate::wired::Scan::Frame { skip, len, .. } => reply.get(skip..skip + len),
192                    crate::wired::Scan::NeedMore { .. } if more => continue,
193                    crate::wired::Scan::NeedMore { .. } => None,
194                };
195                let event = match frame {
196                    Some(frame) => readout.reply(frame),
197                    None => readout.timeout(reply),
198                };
199                match event {
200                    Event::Telegram(_) => {
201                        telegrams.push(Telegram { frame: frame.unwrap_or_default().to_vec() });
202                    }
203                    Event::Invalid(e) => return Err(Error::Invalid(e)),
204                    _ => {}
205                }
206                break;
207            }
208        }
209        if readout.is_complete() { Ok(telegrams) } else { Err(Error::NoReply) }
210    }
211
212    /// Find every meter on the bus by secondary address (wildcard search). Each
213    /// selection waits for the whole response window, so colliding replies are seen.
214    pub fn search(&mut self) -> Result<Found, Error> {
215        self.run_search(Search::new())
216    }
217
218    /// Search with a configured [`Search`] (selection limit).
219    pub fn run_search(&mut self, mut search: Search) -> Result<Found, Error> {
220        let mut found = Found::default();
221        while let Some(request) = search.next_request() {
222            self.send(&request)?;
223            let deadline = self.deadline(&request);
224            let mut start = 0;
225            // Collect until the line is quiet: a valid frame may be the first of several.
226            while self.receive(deadline, request.bytes(), &mut start)? {}
227            let reply = self.rx.get(start..).unwrap_or(&[]);
228            let event = if reply.is_empty() { search.timeout(reply) } else { search.reply(reply) };
229            match event {
230                Event::Found(meter) => found.meters.push(meter),
231                Event::Ambiguous(id) => found.ambiguous.push(id),
232                // A truncated frame at the end of the window: as good as garbage.
233                Event::NeedMore => {
234                    search.timeout(reply);
235                }
236                _ => {}
237            }
238        }
239        found.complete = search.is_complete();
240        Ok(found)
241    }
242
243    /// Send a command and wait for its acknowledgement: `Ok(true)` on `E5`, `Ok(false)`
244    /// when nothing (or something else) came back. A broadcast is `Ok(true)` unread.
245    pub fn command(&mut self, request: &Request) -> Result<bool, Error> {
246        self.send(request)?;
247        if !request.expects_reply() {
248            return Ok(true);
249        }
250        let deadline = self.deadline(request);
251        let mut start = 0;
252        while self.receive(deadline, request.bytes(), &mut start)? {
253            if self.rx.get(start..) == Some(&[0xE5][..]) {
254                return Ok(true);
255            }
256        }
257        Ok(self.rx.get(start..) == Some(&[0xE5][..]))
258    }
259
260    fn deadline(&self, request: &Request) -> Window {
261        let first =
262            Instant::now() + Duration::from_millis(u64::from(request.timeout_ms(self.baud))) + self.slack;
263        // The longest reply worth waiting for: echo, a 261-byte frame and some noise, at
264        // 11 bits per byte, then a quiet line. A port that never falls silent ends here.
265        let bits = u64::try_from(MAX_REPLY * 11).unwrap_or(u64::MAX);
266        let transfer = Duration::from_millis(bits * 1000 / u64::from(self.baud.bits_per_second()).max(1));
267        Window { first, hard: first + transfer + IDLE + self.slack }
268    }
269
270    fn send(&mut self, request: &Request) -> io::Result<()> {
271        self.rx.clear();
272        self.port.write_all(request.bytes())?;
273        self.port.flush()
274    }
275
276    /// Read what arrives until `window.first` (for the first byte), until the line has been
277    /// quiet for [`IDLE`], or at the latest until `window.hard` or [`MAX_REPLY`] bytes. `true` when new bytes arrived (call again for more), `false`
278    /// when the reply is over. `start` skips an echo of `sent`.
279    fn receive(&mut self, window: Window, sent: &[u8], start: &mut usize) -> io::Result<bool> {
280        let mut chunk = [0u8; 256];
281        let mut until = if self.rx.len() > *start { Instant::now() + IDLE } else { window.first };
282        loop {
283            if self.rx.len() >= MAX_REPLY || Instant::now() >= window.hard {
284                return Ok(false);
285            }
286            let n = match self.port.read(&mut chunk) {
287                Ok(n) => n,
288                Err(e)
289                    if matches!(
290                        e.kind(),
291                        ErrorKind::TimedOut | ErrorKind::WouldBlock | ErrorKind::Interrupted
292                    ) =>
293                {
294                    0
295                }
296                Err(e) => return Err(e),
297            };
298            if let Some(bytes) = chunk.get(..n).filter(|b| !b.is_empty()) {
299                self.rx.extend_from_slice(bytes);
300                // A converter that echoes: the request comes back first.
301                if *start == 0 && self.rx.len() >= sent.len() && self.rx.starts_with(sent) {
302                    *start = sent.len();
303                    until = window.first.max(Instant::now() + IDLE);
304                }
305                if self.rx.len() > *start {
306                    return Ok(true);
307                }
308                continue;
309            }
310            if Instant::now() >= until {
311                return Ok(false);
312            }
313            if n == 0 {
314                std::thread::sleep(Duration::from_millis(1));
315            }
316        }
317    }
318}