1extern 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#[derive(Debug)]
41pub enum Error {
42 Io(io::Error),
44 Incomplete {
48 outcome: Outcome,
50 telegrams: Vec<Telegram>,
52 },
53 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#[derive(Clone, PartialEq, Eq)]
93pub struct Telegram {
94 frame: Vec<u8>,
95}
96
97impl Telegram {
98 pub fn bytes(&self) -> &[u8] {
100 &self.frame
101 }
102
103 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
120pub struct Found {
121 pub meters: Vec<Address>,
123 pub ambiguous: Vec<SecondaryAddress>,
125 pub unreadable: Vec<SecondaryAddress>,
128 pub complete: bool,
131}
132
133#[derive(Debug)]
135pub struct Bus<P> {
136 port: P,
137 baud: Baud,
138 slack: Duration,
139 rx: Vec<u8>,
140}
141
142const IDLE: Duration = Duration::from_millis(40);
145
146fn 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
152const ECHO_NOISE: usize = 4;
154
155const MAX_REPLY: usize = 512;
157
158#[derive(Clone, Copy)]
160struct Window {
161 first: Instant,
162 hard: Instant,
163}
164
165impl<P: Read + Write> Bus<P> {
166 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 #[must_use]
175 pub const fn slack(mut self, slack: Duration) -> Self {
176 self.slack = slack;
177 self
178 }
179
180 pub fn port_mut(&mut self) -> &mut P {
182 &mut self.port
183 }
184
185 pub fn into_inner(self) -> P {
187 self.port
188 }
189
190 pub fn readout(&mut self, target: Target) -> Result<Vec<Telegram>, Error> {
193 self.run_readout(Readout::new(target))
194 }
195
196 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 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 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 pub fn search(&mut self) -> Result<Found, Error> {
239 self.run_search(Search::new())
240 }
241
242 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 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 Event::NeedMore => {
259 search.timeout(reply);
260 }
261 _ => {}
262 }
263 }
264 found.complete = search.is_complete();
265 Ok(found)
266 }
267
268 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 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 Window { first, hard: first + transfer(MAX_REPLY, self.baud) + self.idle() + self.slack }
300 }
301
302 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 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 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}