1use core::fmt;
17
18use crate::time::{Date, DateTime, Time};
19use crate::value::{self, Quantity, Value};
20use crate::vif::{Description, Extension, Kind, MAX_EXTENSIONS, Modifier, RecordError, Vib};
21use crate::{Error, Result};
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Function {
26 Instantaneous,
28 Maximum,
30 Minimum,
32 DuringError,
34}
35
36impl fmt::Display for Function {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 f.write_str(match self {
39 Self::Instantaneous => "instantaneous",
40 Self::Maximum => "maximum",
41 Self::Minimum => "minimum",
42 Self::DuringError => "during error",
43 })
44 }
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum DataField {
50 None,
52 Int(u8),
54 Real32,
56 Bcd(u8),
58 Variable,
60 Selection,
62}
63
64impl DataField {
65 pub const fn size(self) -> Option<usize> {
67 match self {
68 Self::None | Self::Selection => Some(0),
69 Self::Int(n) | Self::Bcd(n) => Some(n as usize),
70 Self::Real32 => Some(4),
71 Self::Variable => None,
72 }
73 }
74
75 pub(crate) const fn from_nibble(n: u8) -> Self {
76 match n & 0x0F {
77 0x1 => Self::Int(1),
78 0x2 => Self::Int(2),
79 0x3 => Self::Int(3),
80 0x4 => Self::Int(4),
81 0x5 => Self::Real32,
82 0x6 => Self::Int(6),
83 0x7 => Self::Int(8),
84 0x8 => Self::Selection,
85 0x9 => Self::Bcd(1),
86 0xA => Self::Bcd(2),
87 0xB => Self::Bcd(3),
88 0xC => Self::Bcd(4),
89 0xD => Self::Variable,
90 0xE => Self::Bcd(6),
91 _ => Self::None,
93 }
94 }
95}
96
97pub(crate) fn lvar_len(lvar: u8) -> Result<usize> {
99 Ok(match lvar {
100 0x00..=0xBF => usize::from(lvar),
101 0xC0..=0xC9 => usize::from(lvar - 0xC0),
102 0xD0..=0xD9 => usize::from(lvar - 0xD0),
103 0xE0..=0xEF => usize::from(lvar - 0xE0),
104 0xF0..=0xF4 => 4 * usize::from(lvar - 0xEC),
105 0xF5 => 48,
106 0xF6 => 64,
107 other => return Err(Error::UnsupportedLvar(other)),
108 })
109}
110
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub struct Dib {
114 pub dif: u8,
116 pub function: Function,
118 pub data: DataField,
120 pub storage: u64,
122 pub tariff: u32,
124 pub subunit: u16,
126}
127
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub struct Record<'a> {
131 pub dib: Dib,
133 pub vib: Vib<'a>,
135 pub value: Value<'a>,
137 pub from_ciphertext: bool,
142 pub header: Option<&'a [u8]>,
144}
145
146impl Record<'_> {
147 pub fn description(&self) -> Description {
149 self.vib.description()
150 }
151
152 pub fn profile(&self) -> Option<crate::profile::Profile<'_>> {
156 let direction = self.vib.modifiers().find_map(|m| match m {
157 Modifier::CompactProfile(d) => Some(d),
158 _ => None,
159 })?;
160 match self.value {
161 Value::Text(b) | Value::Bytes(b) => crate::profile::Profile::parse(direction, b),
162 _ => None,
163 }
164 }
165
166 pub fn name(&self) -> &'static str {
168 self.vib.description().kind.name()
169 }
170
171 pub fn quantity(&self) -> Option<Quantity> {
181 if let Value::Duration(q) = self.value {
182 return Some(q);
183 }
184 let (mantissa, base) = self.value.as_decimal()?;
185 let d = self.vib.description();
186 let unit = match d.kind {
188 Kind::PlainText => None,
189 _ => Some(d.unit?),
190 };
191 let mut exponent = d.exponent.checked_add(base)?;
192 for m in self.vib.modifiers() {
193 match m {
194 Modifier::Scale(e) => exponent = exponent.checked_add(e)?,
195 m if m.keeps_quantity() => {}
196 _ => return None,
197 }
198 }
199 Some(Quantity { mantissa, exponent, unit })
200 }
201}
202
203impl fmt::Display for Record<'_> {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213 let d = self.vib.description();
214 match (d.kind, self.vib.plain_text()) {
215 (Kind::PlainText, Some(unit)) if self.quantity().is_none() => {
217 f.write_str("value in ")?;
218 value::escaped(f, unit.iter().rev())?;
219 }
220 (Kind::PlainText, Some(_)) => f.write_str("value")?,
221 (kind, _) => write!(f, "{kind}")?,
222 }
223 let shown = |m: &Modifier| !matches!(m, Modifier::Scale(_) | Modifier::Error(RecordError(0)));
225 for m in self.vib.modifiers().filter(shown) {
226 write!(f, " · {m}")?;
227 }
228 let dib = &self.dib;
229 if dib.function != Function::Instantaneous {
230 write!(f, " · {}", dib.function)?;
231 }
232 if dib.storage != 0 {
233 write!(f, " · storage {}", dib.storage)?;
234 }
235 if dib.tariff != 0 {
236 write!(f, " · tariff {}", dib.tariff)?;
237 }
238 if dib.subunit != 0 {
239 write!(f, " · subunit {}", dib.subunit)?;
240 }
241 f.write_str(" — ")?;
242 match (self.quantity(), self.value) {
243 (Some(q), Value::Real32(_)) => match q.significant(9) {
245 Some(r) if r != q => write!(f, "≈ {r}")?,
246 _ => write!(f, "{q}")?,
247 },
248 (Some(q), Value::Duration(_)) => write!(f, "{q} before reception")?,
251 (Some(q), _) => write!(f, "{q}")?,
252 (None, _) if self.profile().is_some() => {
253 if let Some(p) = self.profile() {
254 write!(f, "{p}")?;
255 }
256 }
257 (None, value) => write!(f, "{value}")?,
258 }
259 if let (Some(_), Some(text)) = (self.quantity().filter(|q| q.unit.is_none()), self.vib.plain_text()) {
260 f.write_str(" ")?;
261 value::escaped(f, text.iter().rev())?;
262 }
263 Ok(())
264 }
265}
266
267#[derive(Clone, Debug)]
272pub struct Records<'a> {
273 buf: &'a [u8],
274 pos: usize,
275 done: bool,
276 manufacturer: Option<&'a [u8]>,
277 more_follows: bool,
278 ciphertext_end: usize,
279}
280
281impl<'a> Records<'a> {
282 pub const fn new(buf: &'a [u8]) -> Self {
284 Self { buf, pos: 0, done: false, manufacturer: None, more_follows: false, ciphertext_end: 0 }
285 }
286
287 pub(crate) const fn decrypted(buf: &'a [u8], ciphertext_end: usize) -> Self {
289 Self { buf, pos: 0, done: false, manufacturer: None, more_follows: false, ciphertext_end }
290 }
291
292 pub const fn manufacturer_data(&self) -> Option<&'a [u8]> {
294 self.manufacturer
295 }
296
297 pub const fn more_follows(&self) -> bool {
299 self.more_follows
300 }
301
302 fn byte(&mut self) -> Result<u8> {
303 let b = self.buf.get(self.pos).copied().ok_or(Error::UnexpectedEnd)?;
304 self.pos += 1;
305 Ok(b)
306 }
307
308 fn take(&mut self, n: usize) -> Result<&'a [u8]> {
309 let end = self.pos.checked_add(n).ok_or(Error::UnexpectedEnd)?;
310 let s = self.buf.get(self.pos..end).ok_or(Error::UnexpectedEnd)?;
311 self.pos = end;
312 Ok(s)
313 }
314
315 fn record(&mut self, dif: u8) -> Result<Record<'a>> {
316 let header_start = self.pos.saturating_sub(1);
317 let function = match (dif >> 4) & 0x03 {
318 0 => Function::Instantaneous,
319 1 => Function::Maximum,
320 2 => Function::Minimum,
321 _ => Function::DuringError,
322 };
323 let mut storage = u64::from((dif >> 6) & 1);
324 let mut tariff = 0u32;
325 let mut subunit = 0u16;
326 let mut ext = dif & 0x80 != 0;
327 let mut i = 0u32;
328 while ext {
329 if i as usize >= MAX_EXTENSIONS {
330 return Err(Error::TooManyExtensions);
331 }
332 let dife = self.byte()?;
333 storage |= u64::from(dife & 0x0F) << (1 + 4 * i);
334 tariff |= u32::from((dife >> 4) & 0x03) << (2 * i);
335 subunit |= u16::from((dife >> 6) & 1) << i;
336 ext = dife & 0x80 != 0;
337 i += 1;
338 }
339 let data = DataField::from_nibble(dif);
340 let dib = Dib { dif, function, data, storage, tariff, subunit };
341
342 let start = self.pos;
346 match self.value_part(dib, false, header_start) {
347 Err(e) if self.buf.get(start) == Some(&0xFC) => {
348 self.pos = start;
349 self.value_part(dib, true, header_start).map_err(|_| e)
350 }
351 r => r,
352 }
353 }
354
355 fn plain_text(&mut self) -> Result<&'a [u8]> {
356 let n = self.byte()?;
357 self.take(usize::from(n))
358 }
359
360 fn value_part(&mut self, dib: Dib, text_first: bool, header_start: usize) -> Result<Record<'a>> {
361 let data = dib.data;
362 let vif = self.byte()?;
363 let mut plain_text = if text_first { Some(self.plain_text()?) } else { None };
364 let mut vifes = [0u8; MAX_EXTENSIONS];
365 let mut vife_len = 0u8;
366 let mut ext = vif & 0x80 != 0;
367 while ext {
368 let vife = self.byte()?;
369 *vifes.get_mut(usize::from(vife_len)).ok_or(Error::TooManyExtensions)? = vife;
370 vife_len += 1;
371 ext = vife & 0x80 != 0;
372 }
373 let header = (vif & 0x7F != 0x7C).then(|| self.buf.get(header_start..self.pos)).flatten();
375 if vif & 0x7F == 0x7C && plain_text.is_none() {
376 plain_text = Some(self.plain_text()?);
377 }
378 let vib = Vib::new(vif, vifes, vife_len, plain_text);
379 let time_point =
380 vib.description().kind.is_time_point() || vib.modifiers().any(Modifier::is_time_point);
381 let unsigned = vib.modifiers().any(|m| m == Modifier::Extension(Extension::Unsigned));
382
383 let value = match data {
384 DataField::None | DataField::Selection => Value::None,
385 DataField::Int(n) => {
386 let bytes = self.take(usize::from(n))?;
387 match (time_point, bytes) {
388 (true, &[b0, b1]) => Value::Date(Date::from_type_g(b0, b1)),
389 (true, &[b0, b1, b2]) => Value::Time(Time::from_type_j(b0, b1, b2)),
390 (true, &[b0, b1, b2, b3]) => Value::DateTime(DateTime::from_type_f([b0, b1, b2, b3])),
391 (true, &[b0, b1, b2, b3, b4, b5]) => {
392 Value::DateTime(DateTime::from_type_i([b0, b1, b2, b3, b4, b5]))
393 }
394 _ if unsigned => Value::UInt(value::le_unsigned(bytes)),
395 _ => Value::Int(value::le_signed(bytes)),
396 }
397 }
398 DataField::Real32 => {
399 let b = self.take(4)?;
400 Value::Real32(u32::from_le_bytes(b.try_into().map_err(|_| Error::UnexpectedEnd)?))
401 }
402 DataField::Bcd(n) => value::bcd(self.take(usize::from(n))?),
403 DataField::Variable => {
404 let lvar = self.byte()?;
405 match lvar {
406 0x00..=0xBF => Value::Text(self.take(usize::from(lvar))?),
407 0xC0..=0xC9 => value::bcd(self.take(usize::from(lvar - 0xC0))?),
408 0xD0..=0xD9 => value::bcd(self.take(usize::from(lvar - 0xD0))?).negate(),
409 0xE0..=0xEF => {
410 let bytes = self.take(usize::from(lvar - 0xE0))?;
411 if let Some(d) = time_point.then(|| value::type_m(bytes)).flatten() {
412 Value::Duration(d)
413 } else if bytes.len() <= 8 {
414 Value::Int(value::le_signed(bytes))
415 } else {
416 Value::Bytes(bytes)
417 }
418 }
419 0xF0..=0xF4 => Value::Bytes(self.take(4 * usize::from(lvar - 0xEC))?),
422 0xF5 => Value::Bytes(self.take(48)?),
423 0xF6 => Value::Bytes(self.take(64)?),
424 other => return Err(Error::UnsupportedLvar(other)),
425 }
426 }
427 };
428 Ok(Record { dib, vib, value, from_ciphertext: false, header })
429 }
430}
431
432impl<'a> Iterator for Records<'a> {
433 type Item = Result<Record<'a>>;
434
435 fn next(&mut self) -> Option<Self::Item> {
436 while !self.done {
437 let Some(&dif) = self.buf.get(self.pos) else {
438 self.done = true;
439 return None;
440 };
441 self.pos += 1;
442 match dif {
443 0x2F | 0x7F => {}
445 0x0F | 0x1F => {
446 self.more_follows = dif == 0x1F;
447 self.manufacturer = Some(self.buf.get(self.pos..).unwrap_or(&[]));
448 self.done = true;
449 return None;
450 }
451 d if d & 0x0F == 0x0F => {
452 self.done = true;
453 return Some(Err(Error::ReservedDif(d)));
454 }
455 d => {
456 let r = self.record(d).map(|mut r| {
457 r.from_ciphertext = self.pos <= self.ciphertext_end;
458 r
459 });
460 self.done = r.is_err();
461 return Some(r);
462 }
463 }
464 }
465 None
466 }
467}
468
469#[cfg(test)]
470mod tests {
471 extern crate std;
472 use super::*;
473 use std::string::ToString;
474
475 #[test]
476 fn storage_tariff_and_subunit_from_extensions() {
477 let mut r = Records::new(&[0xDA, 0x02, 0x3B, 0x13, 0x01]);
479 let rec = r.next().unwrap().unwrap();
480 assert_eq!(rec.dib.storage, 5);
481 assert_eq!(rec.dib.function, Function::Maximum);
482 assert_eq!(rec.dib.data, DataField::Bcd(2));
483 assert_eq!(rec.value, Value::Bcd(113));
484 let rec = Records::new(&[0x8B, 0x60, 0x04, 0x37, 0x18, 0x02]).next().unwrap().unwrap();
486 assert_eq!((rec.dib.storage, rec.dib.tariff, rec.dib.subunit), (0, 2, 1));
487 }
488
489 #[test]
490 fn filler_and_manufacturer_data() {
491 let mut r = Records::new(&[0x2F, 0x2F, 0x01, 0xFD, 0x08, 0x05, 0x0F, 0xAA, 0xBB]);
492 let rec = r.next().unwrap().unwrap();
493 assert_eq!(rec.vib.vif(), 0xFD);
494 assert_eq!(rec.vib.vifes(), &[0x08]);
495 assert_eq!(rec.name(), "access number");
496 assert_eq!(rec.value, Value::Int(5));
497 assert!(r.next().is_none());
498 assert_eq!(r.manufacturer_data(), Some(&[0xAA, 0xBB][..]));
499 assert!(!r.more_follows());
500 }
501
502 #[test]
503 fn plain_text_vif() {
504 let rec = Records::new(&[0x01, 0x7C, 0x03, b'a', b'P', b'h', 0x2A]).next().unwrap().unwrap();
506 assert_eq!(rec.vib.plain_text(), Some(&b"aPh"[..]));
507 assert_eq!(rec.to_string(), "value — 42 hPa");
508 assert_eq!(rec.value, Value::Int(42));
509 }
510
511 #[test]
512 fn plain_text_after_vifes_and_the_elvaco_deviation() {
513 let rec =
515 Records::new(&[0x0C, 0xFC, 0xA2, 0x73, 0x04, b'l', b'a', b'g', b'i', 0x26, 0x08, 0x42, 0x75])
516 .next()
517 .unwrap()
518 .unwrap();
519 assert_eq!(rec.vib.plain_text(), Some(&b"lagi"[..]));
520 assert_eq!(rec.value, Value::Bcd(75_420_826));
521 assert_eq!(rec.to_string(), "value in igal · per hour — 75420826");
522 let rec =
524 Records::new(&[0x02, 0xFC, 0x03, b'H', b'R', b'%', 0x74, 0x22, 0x15]).next().unwrap().unwrap();
525 assert_eq!(rec.vib.plain_text(), Some(&b"HR%"[..]));
526 assert_eq!(rec.vib.vifes(), &[0x74]);
527 assert_eq!(rec.value, Value::Int(0x1522));
528 }
529
530 #[test]
531 fn too_many_extensions() {
532 let input = [0x84u8, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00];
533 assert_eq!(Records::new(&input).next(), Some(Err(Error::TooManyExtensions)));
534 }
535
536 #[test]
537 fn truncation_is_an_error() {
538 let full = [0x04u8, 0x13, 0x01, 0x02, 0x03, 0x04];
539 for cut in 1..full.len() {
540 assert!(matches!(Records::new(&full[..cut]).next(), Some(Err(_))), "cut {cut}");
541 }
542 }
543}