pub struct PeriodEntry<'a> {
pub obis: Obis,
pub unit: Unit,
pub scaler: i8,
pub value: SmlValue<'a>,
pub value_signature: Option<&'a [u8]>,
}Expand description
SML_PeriodEntry: one value of a profile period, or a historic value.
Fields§
§obis: ObisWhat the value is.
unit: UnitThe unit.
scaler: i8The decimal exponent.
value: SmlValue<'a>The value.
value_signature: Option<&'a [u8]>A signature over the value, when the device signs. Not verified by this crate.
Implementations§
Source§impl PeriodEntry<'_>
impl PeriodEntry<'_>
Sourcepub fn quantity(&self) -> Option<Quantity>
pub fn quantity(&self) -> Option<Quantity>
The value as an exact Quantity, when it is numeric.
Examples found in repository?
examples/decode.rs (line 182)
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}Trait Implementations§
Source§impl<'a> Clone for PeriodEntry<'a>
impl<'a> Clone for PeriodEntry<'a>
impl<'a> Copy for PeriodEntry<'a>
Source§impl<'a> Debug for PeriodEntry<'a>
impl<'a> Debug for PeriodEntry<'a>
impl<'a> Element<'a> for PeriodEntry<'a>
impl<'a> Eq for PeriodEntry<'a>
Source§impl<'a> Hash for PeriodEntry<'a>
impl<'a> Hash for PeriodEntry<'a>
Source§impl<'a> PartialEq for PeriodEntry<'a>
impl<'a> PartialEq for PeriodEntry<'a>
impl<'a> StructuralPartialEq for PeriodEntry<'a>
Auto Trait Implementations§
impl<'a> Forget for PeriodEntry<'a>
impl<'a> Freeze for PeriodEntry<'a>
impl<'a> Move for PeriodEntry<'a>
impl<'a> RefUnwindSafe for PeriodEntry<'a>
impl<'a> Send for PeriodEntry<'a>
impl<'a> Sync for PeriodEntry<'a>
impl<'a> Unpin for PeriodEntry<'a>
impl<'a> UnsafeUnpin for PeriodEntry<'a>where
&'a [u8]: UnsafeUnpin,
impl<'a> UnwindSafe for PeriodEntry<'a>where
&'a [u8]: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more