Skip to main content

decode/
decode.rs

1//! Decode a capture from a real meter, and say what it takes to read it.
2//!
3//! ```text
4//! cargo run --example decode -- capture.bin           # raw bytes from the head
5//! cargo run --example decode -- capture.hex           # or hex, whitespace ignored
6//! xxd -p capture.bin | cargo run --example decode     # or stdin
7//! cargo run --example decode -- --lenient capture.hex # KERMIT CRC, time without choice
8//! cargo run --example decode -- --dzg capture.hex     # DZG DVS74 power sign bug
9//! ```
10//!
11//! Without options the capture is read strictly. If that fails, the tool tries each
12//! named allowance and reports the smallest set that reads every frame, so you know
13//! which option your meter needs. If a real meter needs one, please open an issue with
14//! the capture.
15
16use std::io::Read;
17
18use sml_kit::{
19    Body, CrcCheck, Decoder, Direction, Error, ListEntry, Messages, Obis, ParseOptions, ServerId, SmlValue,
20    StatusWord, readout_with,
21};
22
23/// The allowances tried, smallest first.
24const CANDIDATES: [(&str, ParseOptions); 4] = [
25    ("strict", ParseOptions { crc: CrcCheck::Strict, bare_time: false, dzg_power: false }),
26    (
27        "lenient CRC (KERMIT or swapped byte order)",
28        ParseOptions { crc: CrcCheck::Lenient, bare_time: false, dzg_power: false },
29    ),
30    ("time without choice", ParseOptions { crc: CrcCheck::Strict, bare_time: true, dzg_power: false }),
31    ("lenient CRC and time without choice", ParseOptions::lenient()),
32];
33
34fn main() -> Result<(), Box<dyn std::error::Error>> {
35    let args: Vec<String> = std::env::args().skip(1).collect();
36    let lenient = args.iter().any(|a| a == "--lenient");
37    let dzg = args.iter().any(|a| a == "--dzg");
38    let mut raw = Vec::new();
39    match args.iter().find(|a| !a.starts_with("--")) {
40        Some(path) => raw = std::fs::read(path)?,
41        None => {
42            std::io::stdin().read_to_end(&mut raw)?;
43        }
44    }
45    let bytes = if raw.iter().all(|b| b.is_ascii_hexdigit() || b.is_ascii_whitespace()) {
46        from_hex(&raw)?
47    } else {
48        raw
49    };
50
51    let chosen = if lenient { ParseOptions::lenient() } else { ParseOptions::default() };
52    let options = chosen.with_dzg_power(dzg);
53    let (failures, (possible, confirmed)) = print(&bytes, options);
54    // The DZG correction never causes an error, so its effect is reported by value.
55    if dzg && possible + confirmed > 0 {
56        eprintln!("ℹ --dzg corrected the power in {} frame(s)", possible + confirmed);
57    } else if dzg {
58        eprintln!("ℹ --dzg changed no value in this capture");
59    } else if confirmed > 0 {
60        eprintln!(
61            "ℹ a DZG meter sent a negative power in {confirmed} frame(s) while its status word \
62             says import: the DVS74 sign bug. Use --dzg (see the Meter quirks page)."
63        );
64    } else if possible > 0 {
65        eprintln!(
66            "ℹ a DZG meter sent a short negative power in {possible} frame(s). If it only \
67             consumes, it may have the DVS74 sign bug: try --dzg (see the Meter quirks page)."
68        );
69    }
70    if failures == 0 {
71        let strict_too = check(&bytes, ParseOptions::default().with_dzg_power(dzg)).is_ok();
72        match (lenient, strict_too) {
73            (false, _) => eprintln!("✔ reads strictly"),
74            (true, true) => eprintln!("✔ reads; --lenient is not needed"),
75            (true, false) => eprintln!("✔ reads with --lenient; strictly it does not"),
76        }
77        return Ok(());
78    }
79    // Diagnose: which named allowance makes every frame read?
80    match CANDIDATES.iter().skip(1).find(|(_, o)| check(&bytes, o.with_dzg_power(dzg)).is_ok()) {
81        Some((name, _)) if !lenient => {
82            eprintln!("✘ {failures} error(s) strictly; reads with: {name}. Run with --lenient.");
83        }
84        _ => eprintln!(
85            "✘ {failures} error(s); no named allowance reads this capture. Is it complete and undamaged?"
86        ),
87    }
88    std::process::exit(1);
89}
90
91fn from_hex(text: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
92    let digits: Vec<u8> = text.iter().copied().filter(u8::is_ascii_hexdigit).collect();
93    if digits.len() % 2 != 0 {
94        return Err("odd number of hex digits".into());
95    }
96    digits.chunks(2).map(|p| Ok(u8::from_str_radix(std::str::from_utf8(p)?, 16)?)).collect()
97}
98
99/// Read every frame and message with `options`; the first error, if any.
100fn check(bytes: &[u8], options: ParseOptions) -> Result<usize, Error> {
101    let mut decoder = Decoder::new(vec![0u8; 64 * 1024]).with_crc_check(options.crc);
102    let mut result = Ok(0);
103    decoder.push_slice(bytes, |frame| {
104        let outcome = frame.and_then(|f| {
105            Messages::new(f, options).try_for_each(|m| match m?.body {
106                Body::GetListResponse(list) => list.entries.iter().try_for_each(|e| e.map(drop)),
107                _ => Ok(()),
108            })
109        });
110        result = match (result, outcome) {
111            (Ok(n), Ok(())) => Ok(n + 1),
112            (Ok(_), Err(e)) | (Err(e), _) => Err(e),
113        };
114    });
115    match result {
116        Ok(0) => Err(Error::UnexpectedEnd),
117        other => other,
118    }
119}
120
121/// Print every frame; the number of errors, and of frames whose power the DZG correction
122/// changes.
123fn print(bytes: &[u8], options: ParseOptions) -> (usize, (usize, usize)) {
124    let mut decoder = Decoder::new(vec![0u8; 64 * 1024]).with_crc_check(options.crc);
125    let (mut frames, mut errors) = (0, 0);
126    let mut dzg_frames = (0, 0); // (possible, confirmed by the status word)
127    decoder.push_slice(bytes, |frame| {
128        let frame = match frame {
129            Ok(f) => f,
130            Err(e) => {
131                errors += 1;
132                return eprintln!("frame error: {e}");
133            }
134        };
135        frames += 1;
136        println!("── frame {frames} · {} bytes", frame.len());
137        let mut messages = Messages::new(frame, options);
138        while let Some(message) = messages.next() {
139            match message {
140                Err(e) => {
141                    errors += 1;
142                    eprintln!("   message error at byte {}: {e}", messages.offset());
143                }
144                Ok(m) => match m.body {
145                    Body::GetListResponse(list) => {
146                        let time = list.act_sensor_time.map(|t| format!("  at {t}")).unwrap_or_default();
147                        println!("   GetListResponse  server {}{time}", list.server_id);
148                        match dzg_suspect(frame, options.with_dzg_power(false)) {
149                            Dzg::Unchanged => {}
150                            Dzg::Possible => dzg_frames.0 += 1,
151                            Dzg::Confirmed => dzg_frames.1 += 1,
152                        }
153                        for entry in list.entries {
154                            match entry {
155                                Ok(e) => println!("   {}", line(&e)),
156                                Err(err) => {
157                                    errors += 1;
158                                    eprintln!("   entry error: {err}");
159                                }
160                            }
161                        }
162                    }
163                    Body::OpenResponse(o) => println!("   OpenResponse     server {}", o.server_id),
164                    Body::CloseResponse(_) => println!("   CloseResponse"),
165                    Body::Attention(a) => {
166                        println!("   Attention        {:02x?} {}", a.number, a.description().unwrap_or(""));
167                    }
168                    Body::GetProcParameterResponse(r) => {
169                        println!("   GetProcParameterResponse  server {}", r.server_id);
170                        tree(&r.tree, 2);
171                    }
172                    Body::SetProcParameterRequest(r) => {
173                        println!("   SetProcParameterRequest");
174                        tree(&r.tree, 2);
175                    }
176                    Body::GetProfileListResponse(r) => {
177                        println!(
178                            "   GetProfileListResponse  server {}  period {} s",
179                            r.server_id, r.reg_period
180                        );
181                        for e in r.entries.iter().flatten() {
182                            let q = e.quantity().map_or_else(|| format!("{:?}", e.value), |q| q.to_string());
183                            println!("     {:<24} {q}", e.obis.to_string());
184                        }
185                    }
186                    Body::GetProfilePackResponse(p) => {
187                        println!(
188                            "   GetProfilePackResponse  server {}  period {} s",
189                            p.server_id, p.reg_period
190                        );
191                        for row in p.periods.iter().flatten() {
192                            let cells: Vec<String> = p
193                                .columns
194                                .iter()
195                                .flatten()
196                                .map(|c| {
197                                    p.quantity(&row, c.obis)
198                                        .map_or_else(|| "–".into(), |q| format!("{} {q}", c.obis))
199                                })
200                                .collect();
201                            println!("     {}  {}", row.val_time, cells.join("  "));
202                        }
203                    }
204                    Body::Other { tag, raw } => {
205                        println!("   body 0x{tag:08x} ({} bytes, not typed)", raw.len())
206                    }
207                    other => println!("   {other:?}"),
208                },
209            }
210        }
211    });
212    if frames == 0 && errors == 0 {
213        if looks_like_iec_62056_21(bytes) {
214            eprintln!(
215                "no SML frame: this is IEC 62056-21 text (D0), an older protocol, not SML. \
216                 Read it with an IEC 62056-21 parser."
217            );
218        } else {
219            eprintln!("no complete frame found: is the capture long enough (a few seconds) and 9600 8N1?");
220        }
221        errors += 1;
222    }
223    (errors, dzg_frames)
224}
225
226/// What the DZG DVS74 correction would do to this frame. The bug decodes without an
227/// error; the status word (bit 11 on DZG meters) says whether a negative power is an
228/// export or the bug. Without a status only the user can tell: a hint, never a fix.
229#[derive(Clone, Copy, PartialEq)]
230enum Dzg {
231    Unchanged,
232    Possible,
233    Confirmed,
234}
235
236fn dzg_suspect(frame: &[u8], options: ParseOptions) -> Dzg {
237    let (Ok(as_sent), Ok(corrected)) =
238        (readout_with(frame, options), readout_with(frame, options.with_dzg_power(true)))
239    else {
240        return Dzg::Unchanged;
241    };
242    let changed = [Obis::POWER, Obis::POWER_L1, Obis::POWER_L2, Obis::POWER_L3]
243        .into_iter()
244        .any(|o| as_sent.quantity(o) != corrected.quantity(o));
245    match (changed, as_sent.direction(StatusWord::Mme)) {
246        (false, _) | (true, Some(Direction::Export)) => Dzg::Unchanged,
247        (true, Some(Direction::Import)) => Dzg::Confirmed,
248        (true, None) => Dzg::Possible,
249    }
250}
251
252/// IEC 62056-21 (D0) text: an identification line `/XXX5…` and data lines such as
253/// `1-0:1.8.0*255(00012345.6*kWh)`, ended by `!`. Some older meters send it instead of SML.
254fn looks_like_iec_62056_21(bytes: &[u8]) -> bool {
255    let text = bytes.iter().filter(|b| b.is_ascii_graphic() || b.is_ascii_whitespace()).count();
256    let has = |needle: &[u8]| bytes.windows(needle.len()).any(|w| w == needle);
257    text * 10 >= bytes.len() * 9 && has(b"/") && (has(b"1.8.0(") || has(b"1.8.0*255(") || has(b"!"))
258}
259
260fn line(e: &ListEntry<'_>) -> String {
261    let value = match (e.quantity(), e.value) {
262        (Some(q), _) => q.to_string(),
263        (None, SmlValue::Bytes(b)) if [Obis::DEVICE_ID, Obis::SERIAL].contains(&e.obis) => {
264            ServerId::new(b).to_string()
265        }
266        // Printable ASCII is shown quoted and escaped; nothing a meter sends reaches the
267        // terminal as a control character.
268        (None, SmlValue::Bytes(b))
269            if !b.is_empty() && b.iter().all(|c| c.is_ascii_graphic() || *c == b' ') =>
270        {
271            format!("\"{}\"", b.escape_ascii())
272        }
273        (None, SmlValue::Bytes(b)) => b.iter().map(|c| format!("{c:02x}")).collect(),
274        (None, SmlValue::Time(t)) => t.to_string(),
275        (None, other) => format!("{other:?}"),
276    };
277    let name = e.obis.name().unwrap_or("");
278    format!("{:<24} {:<36} {value}", e.obis.to_string(), name)
279}
280
281/// Print a parameter tree, one node per line, indented by depth.
282fn tree(t: &sml_kit::Tree<'_>, depth: usize) {
283    let name = Obis::from_bytes(t.name).map_or_else(
284        |_| hex(t.name),
285        |o| format!("{o}{}", o.name().map(|n| format!(" ({n})")).unwrap_or_default()),
286    );
287    let value = match t.value {
288        None => String::new(),
289        Some(sml_kit::ProcParValue::Value(SmlValue::Bytes(b))) => format!("= {}", text(b)),
290        Some(sml_kit::ProcParValue::Value(v)) => format!("= {v:?}"),
291        Some(sml_kit::ProcParValue::Entry(e)) => format!(
292            "= {}{}",
293            e.quantity().map_or_else(|| format!("{:?}", e.value), |q| q.to_string()),
294            if e.value_signature.is_some() { " (signed, not verified)" } else { "" }
295        ),
296        Some(sml_kit::ProcParValue::Period(p)) => {
297            format!("= {}", p.quantity().map_or_else(|| format!("{:?}", p.value), |q| q.to_string()))
298        }
299        Some(sml_kit::ProcParValue::Time(t)) => format!("= {t}"),
300        Some(sml_kit::ProcParValue::Tupel(t)) => {
301            format!("= A+ {} A- {}", t.a_plus.quantity(), t.a_minus.quantity())
302        }
303    };
304    println!("{:indent$}{name} {value}", "", indent = 2 * depth + 1);
305    for child in t.children.into_iter().flatten() {
306        match child {
307            Ok(c) => tree(&c, depth + 1),
308            Err(e) => eprintln!("{:indent$}child error: {e}", "", indent = 2 * depth + 3),
309        }
310    }
311}
312
313fn hex(b: &[u8]) -> String {
314    b.iter().map(|c| format!("{c:02x}")).collect()
315}
316
317/// Printable ASCII quoted and escaped, anything else as hex: meter bytes never reach the
318/// terminal as control characters.
319fn text(b: &[u8]) -> String {
320    if !b.is_empty() && b.iter().all(|c| c.is_ascii_graphic() || *c == b' ') {
321        format!("\"{}\"", b.escape_ascii())
322    } else {
323        hex(b)
324    }
325}