Skip to main content

serial/
serial.rs

1//! Read a meter through an infrared head in a blocking loop.
2//!
3//! ```text
4//! stty -F /dev/ttyUSB0 9600 raw -echo min 1  # Linux; macOS: stty -f
5//! cargo run --example serial -- /dev/ttyUSB0
6//! xxd -r -p tests/corpus/emh-ehz-apollon77.hex | cargo run --example serial
7//! ```
8//!
9//! Without a path it reads raw bytes from stdin. The serial port must be configured
10//! beforehand (typically 9600 baud, 8N1, blocking reads: `min 1`): sml-kit opens no port
11//! itself, and a read that returns 0 bytes ends the loop as end of input.
12
13use std::io::Read;
14
15use sml_kit::io::{FrameReader, ReadError};
16use sml_kit::{Obis, readout};
17
18fn main() -> std::io::Result<()> {
19    let source: Box<dyn Read> = match std::env::args().nth(1) {
20        Some(path) => Box::new(std::fs::File::open(path)?),
21        None => Box::new(std::io::stdin()),
22    };
23    for frame in FrameReader::new(source) {
24        let frame = match frame {
25            Ok(frame) => frame,
26            Err(ReadError::Frame(e)) => {
27                eprintln!("skipped a damaged frame: {e}");
28                continue;
29            }
30            // A quiet line: keep reading.
31            Err(ReadError::Io(e))
32                if matches!(e.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock) =>
33            {
34                continue;
35            }
36            Err(ReadError::Io(e)) => return Err(e),
37        };
38        match readout(&frame) {
39            Ok(list) => {
40                let show = |obis| list.quantity(obis).map_or_else(|| "-".to_owned(), |q| q.to_string());
41                println!(
42                    "{}  A+ {}  A- {}  P {}",
43                    list.server_id,
44                    show(Obis::ENERGY_IMPORT),
45                    show(Obis::ENERGY_EXPORT),
46                    show(Obis::POWER)
47                );
48            }
49            Err(e) => eprintln!("no readings: {e} (try `cargo run --example decode` on a capture)"),
50        }
51    }
52    Ok(())
53}