Skip to main content

ParseOptions

Struct ParseOptions 

Source
pub struct ParseOptions {
    pub crc: CrcCheck,
    pub bare_time: bool,
    pub dzg_power: bool,
}
Expand description

How messages are read: how strictly the CRC is checked, and which named meter deviations are tolerated.

The default is strict: the specification, nothing else. A meter that deviates is read by naming the deviation, so it stays visible:

use sml_kit::{CrcCheck, ParseOptions};

let strict = ParseOptions::default();
let holley = ParseOptions::lenient();                 // KERMIT CRC, time without choice
let dzg = ParseOptions::default().with_dzg_power(true); // DZG DVS74 sign bug
let damaged = ParseOptions { crc: CrcCheck::Off, ..ParseOptions::default() };

Fields§

§crc: CrcCheck

How each message’s CRC is checked. CrcCheck::Strict by default.

§bare_time: bool

Accept a bare Unsigned where an SML_Time belongs and read it as a seconds index. Some Holley DTZ541 and DDZ285 omit the time’s choice tag. Off by default.

§dzg_power: bool

Correct the DZG DVS74 power sign bug. Off by default, and not part of ParseOptions::lenient, because it changes values.

Affected DZG meters send a positive power of 327.68 W or more (scaler −2) as a short signed integer, so 356.24 W reads −299.12 W. With this set, a negative Integer of 1–3 bytes for active power (1-0:16.7.0, 36.7.0, 56.7.0, 76.7.0) is read as the unsigned number of the same bytes, in lists whose server ID names manufacturer DZG. Affected meters send genuine negatives in 4 bytes or more, which stay negative.

Only set it for a meter that shows the bug: a DZG meter with fixed firmware may send a genuine negative power in 2 bytes, which this would corrupt.

Implementations§

Source§

impl ParseOptions

Source

pub const fn lenient() -> Self

Every allowance that does not change a value: CrcCheck::Lenient (KERMIT or either byte order) and ParseOptions::bare_time.

Examples found in repository?
examples/decode.rs (line 31)
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}
Source

pub const fn with_dzg_power(self, on: bool) -> Self

These options with the DZG power correction set or cleared.

Examples found in repository?
examples/decode.rs (line 52)
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}

Trait Implementations§

Source§

impl Clone for ParseOptions

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for ParseOptions

Source§

impl Debug for ParseOptions

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ParseOptions

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Eq for ParseOptions

Source§

impl Hash for ParseOptions

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for ParseOptions

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for ParseOptions

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.