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, Readout, Request, Search, SecondaryAddress, Target};
37use crate::wired::Frame;
38
39#[derive(Debug)]
41pub enum Error {
42 Io(io::Error),
44 NoReply,
46 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#[derive(Clone, PartialEq, Eq)]
84pub struct Telegram {
85 frame: Vec<u8>,
86}
87
88impl Telegram {
89 pub fn bytes(&self) -> &[u8] {
91 &self.frame
92 }
93
94 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
111pub struct Found {
112 pub meters: Vec<Address>,
114 pub ambiguous: Vec<SecondaryAddress>,
116 pub complete: bool,
119}
120
121#[derive(Debug)]
123pub struct Bus<P> {
124 port: P,
125 baud: Baud,
126 slack: Duration,
127 rx: Vec<u8>,
128}
129
130const IDLE: Duration = Duration::from_millis(40);
133
134const MAX_REPLY: usize = 512;
136
137#[derive(Clone, Copy)]
139struct Window {
140 first: Instant,
141 hard: Instant,
142}
143
144impl<P: Read + Write> Bus<P> {
145 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 #[must_use]
154 pub const fn slack(mut self, slack: Duration) -> Self {
155 self.slack = slack;
156 self
157 }
158
159 pub fn port_mut(&mut self) -> &mut P {
161 &mut self.port
162 }
163
164 pub fn into_inner(self) -> P {
166 self.port
167 }
168
169 pub fn readout(&mut self, target: Target) -> Result<Vec<Telegram>, Error> {
171 self.run_readout(Readout::new(target))
172 }
173
174 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 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 pub fn search(&mut self) -> Result<Found, Error> {
215 self.run_search(Search::new())
216 }
217
218 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 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 Event::NeedMore => {
234 search.timeout(reply);
235 }
236 _ => {}
237 }
238 }
239 found.complete = search.is_complete();
240 Ok(found)
241 }
242
243 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 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 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 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}