use std::io::Read;
use sml_kit::{
Body, CrcCheck, Decoder, Direction, Error, ListEntry, Messages, Obis, ParseOptions, ServerId, SmlValue,
StatusWord, readout_with,
};
const CANDIDATES: [(&str, ParseOptions); 4] = [
("strict", ParseOptions { crc: CrcCheck::Strict, bare_time: false, dzg_power: false }),
(
"lenient CRC (KERMIT or swapped byte order)",
ParseOptions { crc: CrcCheck::Lenient, bare_time: false, dzg_power: false },
),
("time without choice", ParseOptions { crc: CrcCheck::Strict, bare_time: true, dzg_power: false }),
("lenient CRC and time without choice", ParseOptions::lenient()),
];
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().skip(1).collect();
let lenient = args.iter().any(|a| a == "--lenient");
let dzg = args.iter().any(|a| a == "--dzg");
let mut raw = Vec::new();
match args.iter().find(|a| !a.starts_with("--")) {
Some(path) => raw = std::fs::read(path)?,
None => {
std::io::stdin().read_to_end(&mut raw)?;
}
}
let bytes = if raw.iter().all(|b| b.is_ascii_hexdigit() || b.is_ascii_whitespace()) {
from_hex(&raw)?
} else {
raw
};
let chosen = if lenient { ParseOptions::lenient() } else { ParseOptions::default() };
let options = chosen.with_dzg_power(dzg);
let (failures, (possible, confirmed)) = print(&bytes, options);
if dzg && possible + confirmed > 0 {
eprintln!("ℹ --dzg corrected the power in {} frame(s)", possible + confirmed);
} else if dzg {
eprintln!("ℹ --dzg changed no value in this capture");
} else if confirmed > 0 {
eprintln!(
"ℹ a DZG meter sent a negative power in {confirmed} frame(s) while its status word \
says import: the DVS74 sign bug. Use --dzg (see the Meter quirks page)."
);
} else if possible > 0 {
eprintln!(
"ℹ a DZG meter sent a short negative power in {possible} frame(s). If it only \
consumes, it may have the DVS74 sign bug: try --dzg (see the Meter quirks page)."
);
}
if failures == 0 {
let strict_too = check(&bytes, ParseOptions::default().with_dzg_power(dzg)).is_ok();
match (lenient, strict_too) {
(false, _) => eprintln!("✔ reads strictly"),
(true, true) => eprintln!("✔ reads; --lenient is not needed"),
(true, false) => eprintln!("✔ reads with --lenient; strictly it does not"),
}
return Ok(());
}
match CANDIDATES.iter().skip(1).find(|(_, o)| check(&bytes, o.with_dzg_power(dzg)).is_ok()) {
Some((name, _)) if !lenient => {
eprintln!("✘ {failures} error(s) strictly; reads with: {name}. Run with --lenient.");
}
_ => eprintln!(
"✘ {failures} error(s); no named allowance reads this capture. Is it complete and undamaged?"
),
}
std::process::exit(1);
}
fn from_hex(text: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let digits: Vec<u8> = text.iter().copied().filter(u8::is_ascii_hexdigit).collect();
if digits.len() % 2 != 0 {
return Err("odd number of hex digits".into());
}
digits.chunks(2).map(|p| Ok(u8::from_str_radix(std::str::from_utf8(p)?, 16)?)).collect()
}
fn check(bytes: &[u8], options: ParseOptions) -> Result<usize, Error> {
let mut decoder = Decoder::new(vec![0u8; 64 * 1024]).with_crc_check(options.crc);
let mut result = Ok(0);
decoder.push_slice(bytes, |frame| {
let outcome = frame.and_then(|f| {
Messages::new(f, options).try_for_each(|m| match m?.body {
Body::GetListResponse(list) => list.entries.iter().try_for_each(|e| e.map(drop)),
_ => Ok(()),
})
});
result = match (result, outcome) {
(Ok(n), Ok(())) => Ok(n + 1),
(Ok(_), Err(e)) | (Err(e), _) => Err(e),
};
});
match result {
Ok(0) => Err(Error::UnexpectedEnd),
other => other,
}
}
fn print(bytes: &[u8], options: ParseOptions) -> (usize, (usize, usize)) {
let mut decoder = Decoder::new(vec![0u8; 64 * 1024]).with_crc_check(options.crc);
let (mut frames, mut errors) = (0, 0);
let mut dzg_frames = (0, 0); decoder.push_slice(bytes, |frame| {
let frame = match frame {
Ok(f) => f,
Err(e) => {
errors += 1;
return eprintln!("frame error: {e}");
}
};
frames += 1;
println!("── frame {frames} · {} bytes", frame.len());
let mut messages = Messages::new(frame, options);
while let Some(message) = messages.next() {
match message {
Err(e) => {
errors += 1;
eprintln!(" message error at byte {}: {e}", messages.offset());
}
Ok(m) => match m.body {
Body::GetListResponse(list) => {
let time = list.act_sensor_time.map(|t| format!(" at {t}")).unwrap_or_default();
println!(" GetListResponse server {}{time}", list.server_id);
match dzg_suspect(frame, options.with_dzg_power(false)) {
Dzg::Unchanged => {}
Dzg::Possible => dzg_frames.0 += 1,
Dzg::Confirmed => dzg_frames.1 += 1,
}
for entry in list.entries {
match entry {
Ok(e) => println!(" {}", line(&e)),
Err(err) => {
errors += 1;
eprintln!(" entry error: {err}");
}
}
}
}
Body::OpenResponse(o) => println!(" OpenResponse server {}", o.server_id),
Body::CloseResponse(_) => println!(" CloseResponse"),
Body::Attention(a) => {
println!(" Attention {:02x?} {}", a.number, a.description().unwrap_or(""));
}
Body::GetProcParameterResponse(r) => {
println!(" GetProcParameterResponse server {}", r.server_id);
tree(&r.tree, 2);
}
Body::SetProcParameterRequest(r) => {
println!(" SetProcParameterRequest");
tree(&r.tree, 2);
}
Body::GetProfileListResponse(r) => {
println!(
" GetProfileListResponse server {} period {} s",
r.server_id, r.reg_period
);
for e in r.entries.iter().flatten() {
let q = e.quantity().map_or_else(|| format!("{:?}", e.value), |q| q.to_string());
println!(" {:<24} {q}", e.obis.to_string());
}
}
Body::GetProfilePackResponse(p) => {
println!(
" GetProfilePackResponse server {} period {} s",
p.server_id, p.reg_period
);
for row in p.periods.iter().flatten() {
let cells: Vec<String> = p
.columns
.iter()
.flatten()
.map(|c| {
p.quantity(&row, c.obis)
.map_or_else(|| "–".into(), |q| format!("{} {q}", c.obis))
})
.collect();
println!(" {} {}", row.val_time, cells.join(" "));
}
}
Body::Other { tag, raw } => {
println!(" body 0x{tag:08x} ({} bytes, not typed)", raw.len())
}
other => println!(" {other:?}"),
},
}
}
});
if frames == 0 && errors == 0 {
if looks_like_iec_62056_21(bytes) {
eprintln!(
"no SML frame: this is IEC 62056-21 text (D0), an older protocol, not SML. \
Read it with an IEC 62056-21 parser."
);
} else {
eprintln!("no complete frame found: is the capture long enough (a few seconds) and 9600 8N1?");
}
errors += 1;
}
(errors, dzg_frames)
}
#[derive(Clone, Copy, PartialEq)]
enum Dzg {
Unchanged,
Possible,
Confirmed,
}
fn dzg_suspect(frame: &[u8], options: ParseOptions) -> Dzg {
let (Ok(as_sent), Ok(corrected)) =
(readout_with(frame, options), readout_with(frame, options.with_dzg_power(true)))
else {
return Dzg::Unchanged;
};
let changed = [Obis::POWER, Obis::POWER_L1, Obis::POWER_L2, Obis::POWER_L3]
.into_iter()
.any(|o| as_sent.quantity(o) != corrected.quantity(o));
match (changed, as_sent.direction(StatusWord::Mme)) {
(false, _) | (true, Some(Direction::Export)) => Dzg::Unchanged,
(true, Some(Direction::Import)) => Dzg::Confirmed,
(true, None) => Dzg::Possible,
}
}
fn looks_like_iec_62056_21(bytes: &[u8]) -> bool {
let text = bytes.iter().filter(|b| b.is_ascii_graphic() || b.is_ascii_whitespace()).count();
let has = |needle: &[u8]| bytes.windows(needle.len()).any(|w| w == needle);
text * 10 >= bytes.len() * 9 && has(b"/") && (has(b"1.8.0(") || has(b"1.8.0*255(") || has(b"!"))
}
fn line(e: &ListEntry<'_>) -> String {
let value = match (e.quantity(), e.value) {
(Some(q), _) => q.to_string(),
(None, SmlValue::Bytes(b)) if [Obis::DEVICE_ID, Obis::SERIAL].contains(&e.obis) => {
ServerId::new(b).to_string()
}
(None, SmlValue::Bytes(b))
if !b.is_empty() && b.iter().all(|c| c.is_ascii_graphic() || *c == b' ') =>
{
format!("\"{}\"", b.escape_ascii())
}
(None, SmlValue::Bytes(b)) => b.iter().map(|c| format!("{c:02x}")).collect(),
(None, SmlValue::Time(t)) => t.to_string(),
(None, other) => format!("{other:?}"),
};
let name = e.obis.name().unwrap_or("");
format!("{:<24} {:<36} {value}", e.obis.to_string(), name)
}
fn tree(t: &sml_kit::Tree<'_>, depth: usize) {
let name = Obis::from_bytes(t.name).map_or_else(
|_| hex(t.name),
|o| format!("{o}{}", o.name().map(|n| format!(" ({n})")).unwrap_or_default()),
);
let value = match t.value {
None => String::new(),
Some(sml_kit::ProcParValue::Value(SmlValue::Bytes(b))) => format!("= {}", text(b)),
Some(sml_kit::ProcParValue::Value(v)) => format!("= {v:?}"),
Some(sml_kit::ProcParValue::Entry(e)) => format!(
"= {}{}",
e.quantity().map_or_else(|| format!("{:?}", e.value), |q| q.to_string()),
if e.value_signature.is_some() { " (signed, not verified)" } else { "" }
),
Some(sml_kit::ProcParValue::Period(p)) => {
format!("= {}", p.quantity().map_or_else(|| format!("{:?}", p.value), |q| q.to_string()))
}
Some(sml_kit::ProcParValue::Time(t)) => format!("= {t}"),
Some(sml_kit::ProcParValue::Tupel(t)) => {
format!("= A+ {} A- {}", t.a_plus.quantity(), t.a_minus.quantity())
}
};
println!("{:indent$}{name} {value}", "", indent = 2 * depth + 1);
for child in t.children.into_iter().flatten() {
match child {
Ok(c) => tree(&c, depth + 1),
Err(e) => eprintln!("{:indent$}child error: {e}", "", indent = 2 * depth + 3),
}
}
}
fn hex(b: &[u8]) -> String {
b.iter().map(|c| format!("{c:02x}")).collect()
}
fn text(b: &[u8]) -> String {
if !b.is_empty() && b.iter().all(|c| c.is_ascii_graphic() || *c == b' ') {
format!("\"{}\"", b.escape_ascii())
} else {
hex(b)
}
}