Skip to main content

mbus_kit/
vif.rs

1//! The value information block (EN 13757-3:2018, clause 6.4): what a value is.
2//!
3//! ```text
4//! VIF  [VIFE …]
5//! ```
6//!
7//! The VIF selects a quantity, its unit and decimal exponent from the **primary table**.
8//! Two VIF codes point to an extension table, whose code is the first VIFE: `FB`
9//! (larger units, °F, volume in US units) and `FD` (identifiers, versions, error flags,
10//! volts, amperes, storage and tariff metadata). Every other VIFE is **combinable**: it
11//! modifies the value ("per hour", "start date of", "upper limit", "× 10⁻²", "error:
12//! no data available").
13//!
14//! [`Vib::description`] answers *what* the value is; [`Vib::modifiers`] lists the
15//! combinable VIFEs. [`Record::quantity`](crate::Record::quantity) applies the
16//! multiplicative corrections and refuses to return a quantity when a modifier changes
17//! unit or meaning in a way this crate does not model.
18
19use core::fmt;
20
21use crate::value::Unit;
22
23/// The most VIFE (and DIFE) bytes that may follow one another.
24pub(crate) const MAX_EXTENSIONS: usize = 10;
25
26/// The value information block: VIF, up to 10 VIFEs, and a plain-text unit.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub struct Vib<'a> {
29    vif: u8,
30    vifes: [u8; MAX_EXTENSIONS],
31    vife_len: u8,
32    plain_text: Option<&'a [u8]>,
33}
34
35/// Which table a code came from.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub enum Table {
38    /// The primary VIF table (EN 13757-3, Table 10).
39    Primary,
40    /// The extension table after VIF `FB` (Table 14).
41    Fb,
42    /// The extension table after VIF `FD` (Table 12).
43    Fd,
44    /// The second-level table after `FD FD` (OMS sensors; EN 13757-3:2025).
45    FdSecond,
46    /// The reserved third extension table after VIF `EF`.
47    Third,
48}
49
50/// What a value is, independent of which table said so.
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
52#[non_exhaustive]
53pub enum Kind {
54    // ---- primary table
55    /// Energy (Wh, J, and from `FB` megawatt-hours, gigajoules, megacalories).
56    Energy,
57    /// Volume (m³, ft³, US gallons).
58    Volume,
59    /// Mass (kg, t).
60    Mass,
61    /// Time the meter has been switched on.
62    OnTime,
63    /// Time the meter has been measuring.
64    OperatingTime,
65    /// Power (W, J/h, MW, GJ/h).
66    Power,
67    /// Volume flow.
68    VolumeFlow,
69    /// Mass flow.
70    MassFlow,
71    /// Flow (supply) temperature.
72    FlowTemperature,
73    /// Return temperature.
74    ReturnTemperature,
75    /// Temperature difference.
76    TemperatureDifference,
77    /// External (outside) temperature.
78    ExternalTemperature,
79    /// Pressure.
80    Pressure,
81    /// A date (type G).
82    Date,
83    /// A date and time (type F or I), or a time of day (type J).
84    DateTime,
85    /// Units for heat cost allocator (dimensionless).
86    HcaUnits,
87    /// Averaging duration.
88    AveragingDuration,
89    /// Actuality duration: time since the value was measured.
90    ActualityDuration,
91    /// Fabrication number.
92    FabricationNumber,
93    /// (Enhanced) identification.
94    Identification,
95    /// Bus address.
96    BusAddress,
97    /// The unit is given as text (VIF `7C`/`FC`), see [`Vib::plain_text`].
98    PlainText,
99    /// Any VIF (`7E`/`FE`): readout selection by a master.
100    AnyVif,
101    /// Manufacturer-specific (`7F`/`FF`).
102    ManufacturerSpecific,
103
104    // ---- FD table
105    /// Credit, in the local legal currency.
106    Credit,
107    /// Debit, in the local legal currency.
108    Debit,
109    /// Unique message identification (access number).
110    AccessNumber,
111    /// Device type, as in the header.
112    Medium,
113    /// Manufacturer, as in the header.
114    Manufacturer,
115    /// Parameter set identification.
116    ParameterSetId,
117    /// Model / version.
118    ModelVersion,
119    /// Hardware version.
120    HardwareVersion,
121    /// Metrology (firmware) version.
122    FirmwareVersion,
123    /// Other software version.
124    SoftwareVersion,
125    /// Customer location.
126    CustomerLocation,
127    /// Customer.
128    Customer,
129    /// Access code, user.
130    AccessCodeUser,
131    /// Access code, operator.
132    AccessCodeOperator,
133    /// Access code, system operator.
134    AccessCodeSystemOperator,
135    /// Access code, developer.
136    AccessCodeDeveloper,
137    /// Password.
138    Password,
139    /// Error flags (binary, device-specific bits).
140    ErrorFlags,
141    /// Error mask.
142    ErrorMask,
143    /// Security key.
144    SecurityKey,
145    /// Digital output (binary).
146    DigitalOutput,
147    /// Digital input (binary).
148    DigitalInput,
149    /// Baud rate.
150    BaudRate,
151    /// Response delay time, in bit times.
152    ResponseDelay,
153    /// Retry.
154    Retry,
155    /// Remote control (device-specific).
156    RemoteControl,
157    /// First storage number for cyclic storage.
158    FirstStorageNumber,
159    /// Last storage number for cyclic storage.
160    LastStorageNumber,
161    /// Size of a storage block.
162    StorageBlockSize,
163    /// Descriptor for tariff and subunit.
164    TariffDescriptor,
165    /// Storage interval.
166    StorageInterval,
167    /// Operator-specific data.
168    OperatorSpecific,
169    /// Time point, second (0–59).
170    TimePointSecond,
171    /// Duration since the last readout.
172    DurationSinceReadout,
173    /// Start (date and time) of a tariff.
174    TariffStart,
175    /// Duration of a tariff.
176    TariffDuration,
177    /// Period of a tariff.
178    TariffPeriod,
179    /// Dimensionless: no VIF.
180    Dimensionless,
181    /// Data container for the wireless M-Bus protocol.
182    WmbusContainer,
183    /// Period of nominal data transmissions.
184    TransmissionPeriod,
185    /// Voltage.
186    Voltage,
187    /// Current.
188    Current,
189    /// Reset counter.
190    ResetCounter,
191    /// Cumulation counter.
192    CumulationCounter,
193    /// Control signal.
194    ControlSignal,
195    /// Day of week.
196    DayOfWeek,
197    /// Week number.
198    WeekNumber,
199    /// Time point of day change.
200    DayChange,
201    /// State of parameter activation.
202    ParameterActivation,
203    /// Special supplier information.
204    SupplierInformation,
205    /// Duration since the last cumulation.
206    DurationSinceCumulation,
207    /// Operating time of the battery.
208    BatteryOperatingTime,
209    /// Date and time of the battery change.
210    BatteryChange,
211    /// Received signal level (RSSI).
212    SignalLevel,
213    /// Daylight saving: beginning, ending, deviation (data type K).
214    DaylightSaving,
215    /// Listening window management (data type L).
216    ListeningWindow,
217    /// Remaining battery lifetime.
218    RemainingBatteryLife,
219    /// Number of times the meter was stopped.
220    StopCount,
221    /// Data container for a manufacturer-specific protocol.
222    ManufacturerContainer,
223
224    // ---- FB table
225    /// Reactive energy.
226    ReactiveEnergy,
227    /// Apparent energy.
228    ApparentEnergy,
229    /// Reactive power.
230    ReactivePower,
231    /// Apparent power.
232    ApparentPower,
233    /// Relative humidity.
234    RelativeHumidity,
235    /// Phase angle between two voltages.
236    PhaseVoltageVoltage,
237    /// Phase angle between voltage and current.
238    PhaseVoltageCurrent,
239    /// Frequency.
240    Frequency,
241    /// Cold / warm temperature limit.
242    TemperatureLimit,
243    /// Cumulative count of maximum power.
244    CumulativeMaxPower,
245
246    // ---- FD FD second-level table (OMS Vol. 2 Annex B)
247    /// Currently selected application.
248    SelectedApplication,
249    /// List of sub-device types.
250    SubDeviceTypes,
251    /// Carbon dioxide content.
252    CarbonDioxide,
253    /// Carbon monoxide content.
254    CarbonMonoxide,
255    /// Volatile organic compounds.
256    VolatileOrganicCompounds,
257    /// Particles (unspecified range, PM1, PM2.5 or PM10, see [`Kind::name`]).
258    Particles(Particles),
259    /// Illuminance.
260    Illuminance,
261    /// Luminous intensity.
262    LuminousIntensity,
263    /// Irradiance (radiant flux density).
264    Irradiance,
265    /// Wind speed.
266    WindSpeed,
267    /// Rainfall.
268    Rainfall,
269    /// Sound level, A-weighted.
270    SoundLevel,
271    /// Turbidity.
272    Turbidity,
273    /// pH.
274    Ph,
275    /// A counter of events of a smoke or sensor device.
276    Events(Event),
277    /// Battery status.
278    BatteryStatus,
279    /// Smoke chamber pollution level.
280    ChamberPollution,
281    /// Distance.
282    Distance,
283    /// Moisture level.
284    Moisture,
285    /// Status bits of a sensor.
286    StatusBits(Sensor),
287
288    /// A code the table reserves.
289    Reserved {
290        /// The table.
291        table: Table,
292        /// The code, extension bit cleared.
293        code: u8,
294    },
295    /// VIF `FB`/`FD` whose table code is missing (the extension bit was clear).
296    MissingExtension(Table),
297}
298
299impl Kind {
300    /// A short English name, e.g. `"volume flow"`.
301    #[allow(clippy::too_many_lines)]
302    pub const fn name(self) -> &'static str {
303        match self {
304            Self::Energy => "energy",
305            Self::Volume => "volume",
306            Self::Mass => "mass",
307            Self::OnTime => "on time",
308            Self::OperatingTime => "operating time",
309            Self::Power => "power",
310            Self::VolumeFlow => "volume flow",
311            Self::MassFlow => "mass flow",
312            Self::FlowTemperature => "flow temperature",
313            Self::ReturnTemperature => "return temperature",
314            Self::TemperatureDifference => "temperature difference",
315            Self::ExternalTemperature => "external temperature",
316            Self::Pressure => "pressure",
317            Self::Date => "date",
318            Self::DateTime => "date and time",
319            Self::HcaUnits => "heat cost allocation",
320            Self::AveragingDuration => "averaging duration",
321            Self::ActualityDuration => "actuality duration",
322            Self::FabricationNumber => "fabrication number",
323            Self::Identification => "identification",
324            Self::BusAddress => "bus address",
325            Self::PlainText => "plain-text unit",
326            Self::AnyVif => "any VIF",
327            Self::ManufacturerSpecific => "manufacturer specific",
328            Self::Credit => "credit",
329            Self::Debit => "debit",
330            Self::AccessNumber => "access number",
331            Self::Medium => "medium",
332            Self::Manufacturer => "manufacturer",
333            Self::ParameterSetId => "parameter set",
334            Self::ModelVersion => "model version",
335            Self::HardwareVersion => "hardware version",
336            Self::FirmwareVersion => "firmware version",
337            Self::SoftwareVersion => "software version",
338            Self::CustomerLocation => "customer location",
339            Self::Customer => "customer",
340            Self::AccessCodeUser => "access code (user)",
341            Self::AccessCodeOperator => "access code (operator)",
342            Self::AccessCodeSystemOperator => "access code (system operator)",
343            Self::AccessCodeDeveloper => "access code (developer)",
344            Self::Password => "password",
345            Self::ErrorFlags => "error flags",
346            Self::ErrorMask => "error mask",
347            Self::SecurityKey => "security key",
348            Self::DigitalOutput => "digital output",
349            Self::DigitalInput => "digital input",
350            Self::BaudRate => "baud rate",
351            Self::ResponseDelay => "response delay",
352            Self::Retry => "retry",
353            Self::RemoteControl => "remote control",
354            Self::FirstStorageNumber => "first storage number",
355            Self::LastStorageNumber => "last storage number",
356            Self::StorageBlockSize => "storage block size",
357            Self::TariffDescriptor => "tariff and subunit descriptor",
358            Self::StorageInterval => "storage interval",
359            Self::OperatorSpecific => "operator specific",
360            Self::TimePointSecond => "time point (second)",
361            Self::DurationSinceReadout => "duration since last readout",
362            Self::TariffStart => "tariff start",
363            Self::TariffDuration => "tariff duration",
364            Self::TariffPeriod => "tariff period",
365            Self::Dimensionless => "dimensionless",
366            Self::WmbusContainer => "wireless M-Bus container",
367            Self::TransmissionPeriod => "transmission period",
368            Self::Voltage => "voltage",
369            Self::Current => "current",
370            Self::ResetCounter => "reset counter",
371            Self::CumulationCounter => "cumulation counter",
372            Self::ControlSignal => "control signal",
373            Self::DayOfWeek => "day of week",
374            Self::WeekNumber => "week number",
375            Self::DayChange => "day change",
376            Self::ParameterActivation => "parameter activation",
377            Self::SupplierInformation => "supplier information",
378            Self::DurationSinceCumulation => "duration since last cumulation",
379            Self::BatteryOperatingTime => "battery operating time",
380            Self::BatteryChange => "battery change",
381            Self::SignalLevel => "signal level",
382            Self::DaylightSaving => "daylight saving",
383            Self::ListeningWindow => "listening window",
384            Self::RemainingBatteryLife => "remaining battery life",
385            Self::StopCount => "stop count",
386            Self::ManufacturerContainer => "manufacturer container",
387            Self::ReactiveEnergy => "reactive energy",
388            Self::ApparentEnergy => "apparent energy",
389            Self::ReactivePower => "reactive power",
390            Self::ApparentPower => "apparent power",
391            Self::RelativeHumidity => "relative humidity",
392            Self::PhaseVoltageVoltage => "phase U-U",
393            Self::PhaseVoltageCurrent => "phase U-I",
394            Self::Frequency => "frequency",
395            Self::TemperatureLimit => "temperature limit",
396            Self::CumulativeMaxPower => "cumulative max power",
397            Self::SelectedApplication => "selected application",
398            Self::SubDeviceTypes => "sub-device types",
399            Self::CarbonDioxide => "carbon dioxide",
400            Self::CarbonMonoxide => "carbon monoxide",
401            Self::VolatileOrganicCompounds => "volatile organic compounds",
402            Self::Particles(Particles::Any) => "particles",
403            Self::Particles(Particles::Pm1) => "particles PM1",
404            Self::Particles(Particles::Pm2_5) => "particles PM2.5",
405            Self::Particles(Particles::Pm10) => "particles PM10",
406            Self::Illuminance => "illuminance",
407            Self::LuminousIntensity => "luminous intensity",
408            Self::Irradiance => "irradiance",
409            Self::WindSpeed => "wind speed",
410            Self::Rainfall => "rainfall",
411            Self::SoundLevel => "sound level",
412            Self::Turbidity => "turbidity",
413            Self::Ph => "pH",
414            Self::Events(e) => e.name(),
415            Self::BatteryStatus => "battery status",
416            Self::ChamberPollution => "chamber pollution",
417            Self::Distance => "distance",
418            Self::Moisture => "moisture",
419            Self::StatusBits(s) => s.name(),
420            Self::Reserved { .. } => "reserved",
421            Self::MissingExtension(_) => "extension table without code",
422        }
423    }
424
425    /// Whether a value of this kind is a point in time, decoded from its size (2 bytes:
426    /// type G, 3: type J, 4: type F, 6: type I).
427    pub(crate) const fn is_time_point(self) -> bool {
428        matches!(
429            self,
430            Self::Date | Self::DateTime | Self::TariffStart | Self::BatteryChange | Self::DayChange
431        )
432    }
433}
434
435impl fmt::Display for Kind {
436    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437        match self {
438            Self::Reserved { table, code } => write!(f, "reserved {table:?} code 0x{code:02x}"),
439            other => f.write_str(other.name()),
440        }
441    }
442}
443
444/// Particle size range (`FD FD 17`–`1E`).
445#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
446pub enum Particles {
447    /// Unspecified range.
448    Any,
449    /// PM1.
450    Pm1,
451    /// PM2.5.
452    Pm2_5,
453    /// PM10.
454    Pm10,
455}
456
457/// What a sensor event counter counts (`FD FD 2C`–`34`).
458#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
459pub enum Event {
460    /// Dismounts / removals.
461    Dismounts,
462    /// Test button operations.
463    TestButton,
464    /// Alarms.
465    Alarms,
466    /// Alarm mute operations.
467    AlarmMutes,
468    /// Obstacles detected.
469    Obstacles,
470    /// Smoke entries blocked.
471    SmokeEntryBlocked,
472    /// Smoke chamber defects.
473    ChamberDefects,
474    /// Self-test failures.
475    SelfTestFailures,
476    /// Sounder defects.
477    SounderDefects,
478}
479
480impl Event {
481    const fn name(self) -> &'static str {
482        match self {
483            Self::Dismounts => "dismounts",
484            Self::TestButton => "test button operations",
485            Self::Alarms => "alarms",
486            Self::AlarmMutes => "alarm mutes",
487            Self::Obstacles => "obstacles detected",
488            Self::SmokeEntryBlocked => "smoke entries blocked",
489            Self::ChamberDefects => "smoke chamber defects",
490            Self::SelfTestFailures => "self-test failures",
491            Self::SounderDefects => "sounder defects",
492        }
493    }
494}
495
496/// Which sensor a status-bits record belongs to (`FD FD 40`–`44`).
497#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
498pub enum Sensor {
499    /// Pressure sensor.
500    Pressure,
501    /// Smoke alarm.
502    Smoke,
503    /// CO alarm.
504    CarbonMonoxide,
505    /// Heat alarm.
506    Heat,
507    /// Door / window sensor.
508    DoorWindow,
509}
510
511impl Sensor {
512    const fn name(self) -> &'static str {
513        match self {
514            Self::Pressure => "pressure sensor status",
515            Self::Smoke => "smoke alarm status",
516            Self::CarbonMonoxide => "CO alarm status",
517            Self::Heat => "heat alarm status",
518            Self::DoorWindow => "door/window sensor status",
519        }
520    }
521}
522
523/// What a value information block says about the value: what it is, and its unit and
524/// decimal exponent.
525#[derive(Clone, Copy, Debug, PartialEq, Eq)]
526pub struct Description {
527    /// What the value is.
528    pub kind: Kind,
529    /// The unit, for physical quantities and durations; `None` for identifiers,
530    /// counters, flags, dates and anything not interpreted.
531    pub unit: Option<Unit>,
532    /// The decimal exponent: the value is `raw × 10^exponent` in `unit`.
533    pub exponent: i8,
534    /// The table the code came from.
535    pub table: Table,
536}
537
538impl fmt::Display for Description {
539    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540        fmt::Display::fmt(&self.kind, f)
541    }
542}
543
544/// Which way a compact profile runs (EN 13757-3:2018 Annex F.2).
545#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
546pub enum Direction {
547    /// `1F`: elements follow the base value forward in time.
548    Forward,
549    /// `13`: elements go back in time from the base value.
550    Inverse,
551    /// `1E`: forward, with register (storage) numbers: OMS billing history.
552    WithRegisters,
553}
554
555/// The denominator of a "per" VIFE.
556#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
557#[non_exhaustive]
558pub enum Per {
559    /// Per second.
560    Second,
561    /// Per minute.
562    Minute,
563    /// Per hour.
564    Hour,
565    /// Per day.
566    Day,
567    /// Per week.
568    Week,
569    /// Per month.
570    Month,
571    /// Per year.
572    Year,
573    /// Per revolution / measurement.
574    Revolution,
575    /// Per litre.
576    Litre,
577    /// Per m³.
578    CubicMetre,
579    /// Per kg.
580    Kilogram,
581    /// Per K.
582    Kelvin,
583    /// Per kWh.
584    KilowattHour,
585    /// Per GJ.
586    Gigajoule,
587    /// Per kW.
588    Kilowatt,
589    /// Per K·l.
590    KelvinLitre,
591    /// Per V.
592    Volt,
593    /// Per A.
594    Ampere,
595}
596
597impl Per {
598    /// The unit symbol of the denominator, e.g. `"h"`.
599    pub const fn symbol(self) -> &'static str {
600        match self {
601            Self::Second => "s",
602            Self::Minute => "min",
603            Self::Hour => "h",
604            Self::Day => "d",
605            Self::Week => "week",
606            Self::Month => "month",
607            Self::Year => "year",
608            Self::Revolution => "revolution",
609            Self::Litre => "l",
610            Self::CubicMetre => "m³",
611            Self::Kilogram => "kg",
612            Self::Kelvin => "K",
613            Self::KilowattHour => "kWh",
614            Self::Gigajoule => "GJ",
615            Self::Kilowatt => "kW",
616            Self::KelvinLitre => "K·l",
617            Self::Volt => "V",
618            Self::Ampere => "A",
619        }
620    }
621}
622
623/// What a value is multiplied by (VIFE `36`–`38`).
624#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
625pub enum Times {
626    /// × s.
627    Second,
628    /// × s/V.
629    SecondPerVolt,
630    /// × s/A.
631    SecondPerAmpere,
632}
633
634/// A record error code, sent by a slave in a combinable VIFE `00`–`1F`
635/// (EN 13757-3, Table 19).
636#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
637pub struct RecordError(pub u8);
638
639impl RecordError {
640    /// A short English description, if the code is defined.
641    pub const fn name(self) -> Option<&'static str> {
642        Some(match self.0 {
643            0x00 => "none",
644            0x01 => "too many DIFEs",
645            0x02 => "storage number not implemented",
646            0x03 => "unit number not implemented",
647            0x04 => "tariff number not implemented",
648            0x05 => "function not implemented",
649            0x06 => "data class not implemented",
650            0x07 => "data size not implemented",
651            0x0B => "too many VIFEs",
652            0x0C => "illegal VIF group",
653            0x0D => "illegal VIF exponent",
654            0x0E => "VIF/DIF mismatch",
655            0x0F => "unimplemented action",
656            0x15 => "no data available",
657            0x16 => "data overflow",
658            0x17 => "data underflow",
659            0x18 => "data error",
660            0x1C => "premature end of record",
661            _ => return None,
662        })
663    }
664}
665
666/// One combinable (orthogonal) VIFE: how it modifies the value (EN 13757-3, Table 15).
667#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
668#[non_exhaustive]
669pub enum Modifier {
670    /// `00`–`11`, `15`–`1C`: the slave reports an error for this record.
671    Error(RecordError),
672    /// `12`: an average value.
673    Average,
674    /// `13`, `1E`, `1F`: the record is a compact profile (see
675    /// [`Record::profile`](crate::Record::profile)).
676    CompactProfile(Direction),
677    /// `14`: a relative deviation.
678    RelativeDeviation,
679    /// `1D`: standard-conformant data content (e.g. error flags as defined by OMS).
680    StandardConformant,
681    /// `20`–`27`, `2C`–`35`: the value is per this denominator.
682    Per(Per),
683    /// `28`–`2B`: increment per input or output pulse on channel 0 or 1.
684    IncrementPerPulse {
685        /// Output (`true`) or input channel.
686        output: bool,
687        /// Channel 0 or 1.
688        channel: u8,
689    },
690    /// `36`–`38`: the value is multiplied by this.
691    MultipliedBy(Times),
692    /// `39`: the value is the start date (and time) of what the VIF describes.
693    StartDateOf,
694    /// `3A`: the VIF is the uncorrected unit (e.g. volume at measuring conditions).
695    UncorrectedUnit,
696    /// `3B`: forward flow: accumulation of positive contributions only.
697    Forward,
698    /// `3C`: backward flow: accumulation of the absolute value of negative
699    /// contributions only.
700    Backward,
701    /// `3D`: an alternate, non-metric unit system.
702    NonMetric,
703    /// `3E`: the value at base conditions.
704    BaseConditions,
705    /// `3F`: OBIS declaration.
706    ObisDeclaration,
707    /// `40` / `48`: a lower or upper limit value.
708    Limit {
709        /// Upper (`true`) or lower limit.
710        upper: bool,
711    },
712    /// `41` / `49`: the number of times the lower or upper limit was exceeded.
713    ExceedCount {
714        /// Upper (`true`) or lower limit.
715        upper: bool,
716    },
717    /// `42`–`4F` (`E100 uf1b`): the date (and time) a limit exceed began or ended.
718    LimitExceedDate {
719        /// Upper (`true`) or lower limit.
720        upper: bool,
721        /// Last (`true`) or first exceed.
722        last: bool,
723        /// End (`true`) or beginning.
724        end: bool,
725    },
726    /// `50`–`5F` (`E101 ufnn`): how long a limit was exceeded.
727    LimitExceedDuration {
728        /// Upper (`true`) or lower limit.
729        upper: bool,
730        /// Last (`true`) or first exceed.
731        last: bool,
732        /// Seconds, minutes, hours or days.
733        unit: Unit,
734    },
735    /// `60`–`67` (`E110 0fnn`): a duration.
736    Duration {
737        /// Last (`true`) or first.
738        last: bool,
739        /// Seconds, minutes, hours or days.
740        unit: Unit,
741    },
742    /// `68` / `6C`: the value during a lower or upper limit exceed.
743    ValueDuringLimitExceed {
744        /// Upper (`true`) or lower limit.
745        upper: bool,
746    },
747    /// `69`: leakage values.
748    Leakage,
749    /// `6D`: overflow values.
750    Overflow,
751    /// `6A`, `6B`, `6E`, `6F` (`E110 1f1b`): the date (and time) of a first or last
752    /// beginning or end.
753    DateOf {
754        /// Last (`true`) or first.
755        last: bool,
756        /// End (`true`) or beginning.
757        end: bool,
758    },
759    /// `70`–`77` (×10^(nnn−6)) and `7D` (×10³): multiplicative correction, applied by
760    /// [`Record::quantity`](crate::Record::quantity).
761    Scale(i8),
762    /// `78`–`7B`: the record is an additive correction constant (offset) of
763    /// 10^(nn−3) × the VIF's unit.
764    Offset(i8),
765    /// `FC` and the code after it: from the extension of the combinable table.
766    Extension(Extension),
767    /// `7E`: a future value.
768    FutureValue,
769    /// `7F`: this and every following VIFE (and the data) are manufacturer-specific.
770    ManufacturerSpecific,
771    /// A code the table reserves.
772    Reserved(u8),
773}
774
775impl Modifier {
776    /// Whether [`Record::quantity`](crate::Record::quantity) may still report the value
777    /// in the VIF's unit: the modifier scales it (applied) or annotates it without
778    /// changing unit or meaning.
779    pub const fn keeps_quantity(self) -> bool {
780        matches!(
781            self,
782            Self::Scale(_)
783                | Self::Error(RecordError(0))
784                | Self::UncorrectedUnit
785                | Self::Forward
786                | Self::Backward
787                | Self::Average
788                | Self::StandardConformant
789                | Self::BaseConditions
790                | Self::Limit { .. }
791                | Self::ValueDuringLimitExceed { .. }
792                | Self::Leakage
793                | Self::Overflow
794                | Self::FutureValue
795        ) || matches!(self, Self::Extension(e) if e.keeps_quantity())
796    }
797
798    /// Whether the value becomes a point in time (and is decoded as a date).
799    pub(crate) const fn is_time_point(self) -> bool {
800        matches!(self, Self::StartDateOf | Self::LimitExceedDate { .. } | Self::DateOf { .. })
801    }
802
803    #[allow(clippy::cast_possible_wrap)] // every code here is masked to 7 bits
804    const fn from_code(code: u8) -> Self {
805        let c = code & 0x7F;
806        let upper = c & 0x08 != 0;
807        let last = c & 0x04 != 0;
808        match c {
809            0x12 => Self::Average,
810            0x13 => Self::CompactProfile(Direction::Inverse),
811            0x1E => Self::CompactProfile(Direction::WithRegisters),
812            0x1F => Self::CompactProfile(Direction::Forward),
813            0x14 => Self::RelativeDeviation,
814            0x1D => Self::StandardConformant,
815            0x00..=0x1C => Self::Error(RecordError(c)),
816            0x20 => Self::Per(Per::Second),
817            0x21 => Self::Per(Per::Minute),
818            0x22 => Self::Per(Per::Hour),
819            0x23 => Self::Per(Per::Day),
820            0x24 => Self::Per(Per::Week),
821            0x25 => Self::Per(Per::Month),
822            0x26 => Self::Per(Per::Year),
823            0x27 => Self::Per(Per::Revolution),
824            0x28..=0x2B => Self::IncrementPerPulse { output: c & 0x02 != 0, channel: c & 0x01 },
825            0x2C => Self::Per(Per::Litre),
826            0x2D => Self::Per(Per::CubicMetre),
827            0x2E => Self::Per(Per::Kilogram),
828            0x2F => Self::Per(Per::Kelvin),
829            0x30 => Self::Per(Per::KilowattHour),
830            0x31 => Self::Per(Per::Gigajoule),
831            0x32 => Self::Per(Per::Kilowatt),
832            0x33 => Self::Per(Per::KelvinLitre),
833            0x34 => Self::Per(Per::Volt),
834            0x35 => Self::Per(Per::Ampere),
835            0x36 => Self::MultipliedBy(Times::Second),
836            0x37 => Self::MultipliedBy(Times::SecondPerVolt),
837            0x38 => Self::MultipliedBy(Times::SecondPerAmpere),
838            0x39 => Self::StartDateOf,
839            0x3A => Self::UncorrectedUnit,
840            0x3B => Self::Forward,
841            0x3C => Self::Backward,
842            0x3D => Self::NonMetric,
843            0x3E => Self::BaseConditions,
844            0x3F => Self::ObisDeclaration,
845            0x40 | 0x48 => Self::Limit { upper },
846            0x41 | 0x49 => Self::ExceedCount { upper },
847            0x42 | 0x43 | 0x46 | 0x47 | 0x4A | 0x4B | 0x4E | 0x4F => {
848                Self::LimitExceedDate { upper, last, end: c & 0x01 != 0 }
849            }
850            0x50..=0x5F => Self::LimitExceedDuration { upper, last, unit: Unit::duration(c) },
851            0x60..=0x67 => Self::Duration { last, unit: Unit::duration(c) },
852            0x68 | 0x6C => Self::ValueDuringLimitExceed { upper: c & 0x04 != 0 },
853            0x69 => Self::Leakage,
854            0x6D => Self::Overflow,
855            0x6A | 0x6B | 0x6E | 0x6F => Self::DateOf { last, end: c & 0x01 != 0 },
856            0x70..=0x77 => Self::Scale((c & 0x07) as i8 - 6),
857            0x78..=0x7B => Self::Offset((c & 0x03) as i8 - 3),
858            0x7D => Self::Scale(3),
859            0x7E => Self::FutureValue,
860            0x7F => Self::ManufacturerSpecific,
861            _ => Self::Reserved(c),
862        }
863    }
864
865    /// A short English description, e.g. `"per hour"`.
866    pub const fn name(self) -> &'static str {
867        match self {
868            Self::Error(_) => "error",
869            Self::Average => "average",
870            Self::CompactProfile(_) => "compact profile",
871            Self::RelativeDeviation => "relative deviation",
872            Self::StandardConformant => "standard conformant",
873            Self::Per(Per::Second) => "per second",
874            Self::Per(Per::Minute) => "per minute",
875            Self::Per(Per::Hour) => "per hour",
876            Self::Per(Per::Day) => "per day",
877            Self::Per(Per::Week) => "per week",
878            Self::Per(Per::Month) => "per month",
879            Self::Per(Per::Year) => "per year",
880            Self::Per(Per::Revolution) => "per revolution",
881            Self::Per(_) => "per unit",
882            Self::IncrementPerPulse { output: false, .. } => "increment per input pulse",
883            Self::IncrementPerPulse { output: true, .. } => "increment per output pulse",
884            Self::MultipliedBy(_) => "multiplied by",
885            Self::StartDateOf => "start date of",
886            Self::UncorrectedUnit => "uncorrected",
887            Self::Forward => "forward",
888            Self::Backward => "backward",
889            Self::NonMetric => "non-metric",
890            Self::BaseConditions => "at base conditions",
891            Self::ObisDeclaration => "OBIS declaration",
892            Self::Limit { upper: false } => "lower limit",
893            Self::Limit { upper: true } => "upper limit",
894            Self::ExceedCount { upper: false } => "lower limit exceeds",
895            Self::ExceedCount { upper: true } => "upper limit exceeds",
896            Self::LimitExceedDate { .. } => "date of limit exceed",
897            Self::LimitExceedDuration { .. } => "duration of limit exceed",
898            Self::Duration { .. } => "duration",
899            Self::ValueDuringLimitExceed { upper: false } => "during lower limit exceed",
900            Self::ValueDuringLimitExceed { upper: true } => "during upper limit exceed",
901            Self::Leakage => "leakage",
902            Self::Overflow => "overflow",
903            Self::DateOf { .. } => "date of",
904            Self::Scale(_) => "corrected",
905            Self::Offset(_) => "additive correction",
906            Self::Extension(_) => "extended modifier",
907            Self::FutureValue => "future value",
908            Self::ManufacturerSpecific => "manufacturer specific",
909            Self::Reserved(_) => "reserved modifier",
910        }
911    }
912}
913
914impl fmt::Display for Modifier {
915    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916        let first_last = |last: bool| if last { "last" } else { "first" };
917        let lower_upper = |upper: bool| if upper { "upper" } else { "lower" };
918        match *self {
919            Self::Error(e) => match e.name() {
920                Some(n) => write!(f, "error: {n}"),
921                None => write!(f, "error 0x{:02x}", e.0),
922            },
923            Self::Per(p) if !matches!(p, Per::Second | Per::Minute | Per::Hour | Per::Day) => {
924                write!(f, "per {}", p.symbol())
925            }
926            Self::IncrementPerPulse { output, channel } => {
927                write!(
928                    f,
929                    "increment per {} pulse, channel {channel}",
930                    if output { "output" } else { "input" }
931                )
932            }
933            Self::MultipliedBy(t) => f.write_str(match t {
934                Times::Second => "× s",
935                Times::SecondPerVolt => "× s/V",
936                Times::SecondPerAmpere => "× s/A",
937            }),
938            Self::LimitExceedDate { upper, last, end } => write!(
939                f,
940                "{} of {} {} limit exceed",
941                if end { "end" } else { "begin" },
942                first_last(last),
943                lower_upper(upper)
944            ),
945            Self::LimitExceedDuration { upper, last, unit } => {
946                write!(f, "duration of {} {} limit exceed ({unit})", first_last(last), lower_upper(upper))
947            }
948            Self::Duration { last, unit } => write!(f, "duration of {} ({unit})", first_last(last)),
949            Self::DateOf { last, end } => {
950                write!(f, "date of {} {}", first_last(last), if end { "end" } else { "begin" })
951            }
952            Self::Scale(e) => write!(f, "× 10^{e}"),
953            Self::Offset(e) => write!(f, "additive correction × 10^{e}"),
954            Self::Extension(e) => write!(f, "{e}"),
955            Self::Reserved(c) => write!(f, "reserved modifier 0x{c:02x}"),
956            other => f.write_str(other.name()),
957        }
958    }
959}
960
961/// A code from the extension of the combinable VIFE table (after combinable `FC`).
962#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
963#[non_exhaustive]
964pub enum Extension {
965    /// At phase L1, L2 or L3 (`01`–`03`).
966    Phase(u8),
967    /// At neutral (`04`).
968    Neutral,
969    /// Between phases L1–L2, L2–L3, L3–L1 (`05`–`07`), given as the first phase.
970    BetweenPhases(u8),
971    /// In quadrant Q1–Q4 (`08`–`0B`).
972    Quadrant(u8),
973    /// Delta between import and export (`0C`).
974    ImportExportDelta,
975    /// Accumulation of the absolute value of positive and negative contributions (`10`).
976    Absolute,
977    /// The data is unsigned (data type C, `11`): applied when the value is decoded.
978    Unsigned,
979    /// The data is boolean (data type D, `12`).
980    Boolean,
981    /// A code this crate does not interpret.
982    Other(u8),
983}
984
985impl Extension {
986    const fn from_code(c: u8) -> Self {
987        match c {
988            0x01..=0x03 => Self::Phase(c),
989            0x04 => Self::Neutral,
990            0x05..=0x07 => Self::BetweenPhases(c - 4),
991            0x08..=0x0B => Self::Quadrant(c - 7),
992            0x0C => Self::ImportExportDelta,
993            0x10 => Self::Absolute,
994            0x11 => Self::Unsigned,
995            0x12 => Self::Boolean,
996            other => Self::Other(other),
997        }
998    }
999
1000    const fn keeps_quantity(self) -> bool {
1001        !matches!(self, Self::Boolean | Self::Other(_))
1002    }
1003}
1004
1005impl fmt::Display for Extension {
1006    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1007        match *self {
1008            Self::Phase(p) => write!(f, "phase L{p}"),
1009            Self::Neutral => f.write_str("neutral"),
1010            Self::BetweenPhases(p) => write!(f, "phase L{p}–L{}", p % 3 + 1),
1011            Self::Quadrant(q) => write!(f, "quadrant Q{q}"),
1012            Self::ImportExportDelta => f.write_str("import − export"),
1013            Self::Absolute => f.write_str("absolute"),
1014            Self::Unsigned => f.write_str("unsigned"),
1015            Self::Boolean => f.write_str("boolean"),
1016            Self::Other(c) => write!(f, "extended modifier 0x{c:02x}"),
1017        }
1018    }
1019}
1020
1021/// The combinable VIFEs of a [`Vib`], as [`Modifier`]s.
1022#[derive(Clone, Debug)]
1023pub struct Modifiers<'v> {
1024    rest: &'v [u8],
1025    manufacturer: bool,
1026}
1027
1028impl Iterator for Modifiers<'_> {
1029    type Item = Modifier;
1030
1031    fn next(&mut self) -> Option<Modifier> {
1032        if self.manufacturer {
1033            return None;
1034        }
1035        let (&code, rest) = self.rest.split_first()?;
1036        self.rest = rest;
1037        let m = match code & 0x7F {
1038            0x7C => {
1039                let (&next, rest) = self.rest.split_first().unwrap_or((&0, &[]));
1040                self.rest = rest;
1041                Modifier::Extension(Extension::from_code(next & 0x7F))
1042            }
1043            c => Modifier::from_code(c),
1044        };
1045        if m == Modifier::ManufacturerSpecific {
1046            self.manufacturer = true;
1047        }
1048        Some(m)
1049    }
1050}
1051
1052impl<'a> Vib<'a> {
1053    pub(crate) const fn new(
1054        vif: u8,
1055        vifes: [u8; MAX_EXTENSIONS],
1056        vife_len: u8,
1057        plain_text: Option<&'a [u8]>,
1058    ) -> Self {
1059        Self { vif, vifes, vife_len, plain_text }
1060    }
1061
1062    /// The VIF byte, as transmitted.
1063    pub const fn vif(&self) -> u8 {
1064        self.vif
1065    }
1066
1067    /// The VIFE bytes, as transmitted.
1068    pub fn vifes(&self) -> &[u8] {
1069        self.vifes.get(..usize::from(self.vife_len)).unwrap_or(&[])
1070    }
1071
1072    /// For a plain-text VIF (`7C`/`FC`): the unit text, as transmitted (M-Bus sends it
1073    /// last character first).
1074    pub const fn plain_text(&self) -> Option<&'a [u8]> {
1075        self.plain_text
1076    }
1077
1078    /// The extension table this VIF selects, and how many VIFEs name the code in it
1079    /// (`FD FD xx` takes two).
1080    fn table(&self) -> Option<(Table, usize)> {
1081        match (self.vif & 0x7F, self.vifes().first().map(|c| c & 0x7F)) {
1082            (0x7B, _) => Some((Table::Fb, 1)),
1083            (0x7D, Some(0x7D)) => Some((Table::FdSecond, 2)),
1084            (0x7D, _) => Some((Table::Fd, 1)),
1085            (0x6F, _) => Some((Table::Third, 1)),
1086            _ => None,
1087        }
1088    }
1089
1090    /// What the value is: kind, unit and decimal exponent, from the primary table or
1091    /// the `FB`/`FD` extension table. Combinable VIFEs are in [`Vib::modifiers`].
1092    pub fn description(&self) -> Description {
1093        let Some((table, len)) = self.table() else { return primary(self.vif & 0x7F) };
1094        let Some(&code) = self.vifes().get(len - 1) else {
1095            return d(Kind::MissingExtension(table), None, 0, table);
1096        };
1097        let code = code & 0x7F;
1098        match table {
1099            Table::Fb => fb(code),
1100            Table::Fd => fd(code),
1101            Table::FdSecond => fd_second(code),
1102            Table::Primary | Table::Third => d(Kind::Reserved { table, code }, None, 0, table),
1103        }
1104    }
1105
1106    /// The combinable VIFEs, as modifiers. After a manufacturer-specific VIF (`7F`/`FF`)
1107    /// or a `7F` VIFE, the remaining bytes are not interpreted.
1108    pub fn modifiers(&self) -> Modifiers<'_> {
1109        let vifes = self.vifes();
1110        let skip = self.table().map_or(0, |(_, len)| len);
1111        let rest = vifes.get(skip..).unwrap_or(&[]);
1112        Modifiers { rest, manufacturer: self.vif & 0x7F == 0x7F }
1113    }
1114}
1115
1116const fn d(kind: Kind, unit: Option<Unit>, exponent: i8, table: Table) -> Description {
1117    Description { kind, unit, exponent, table }
1118}
1119
1120/// `n` (the low 3 bits) minus `offset`, or the low 2 bits with `two` set.
1121#[allow(clippy::cast_possible_wrap)] // masked to at most 4 bits
1122const fn exp(code: u8, mask: u8, offset: i8) -> i8 {
1123    (code & mask) as i8 - offset
1124}
1125
1126/// The primary VIF table (EN 13757-3:2018, Table 10).
1127fn primary(v: u8) -> Description {
1128    use Kind as K;
1129    const P: Table = Table::Primary;
1130    let q = |kind, unit, e| d(kind, Some(unit), e, P);
1131    match v {
1132        0x00..=0x07 => q(K::Energy, Unit::Wh, exp(v, 7, 3)),
1133        0x08..=0x0F => q(K::Energy, Unit::J, exp(v, 7, 0)),
1134        0x10..=0x17 => q(K::Volume, Unit::M3, exp(v, 7, 6)),
1135        0x18..=0x1F => q(K::Mass, Unit::Kg, exp(v, 7, 3)),
1136        0x20..=0x23 => q(K::OnTime, Unit::duration(v), 0),
1137        0x24..=0x27 => q(K::OperatingTime, Unit::duration(v), 0),
1138        0x28..=0x2F => q(K::Power, Unit::W, exp(v, 7, 3)),
1139        0x30..=0x37 => q(K::Power, Unit::JPerH, exp(v, 7, 0)),
1140        0x38..=0x3F => q(K::VolumeFlow, Unit::M3PerH, exp(v, 7, 6)),
1141        0x40..=0x47 => q(K::VolumeFlow, Unit::M3PerMin, exp(v, 7, 7)),
1142        0x48..=0x4F => q(K::VolumeFlow, Unit::M3PerS, exp(v, 7, 9)),
1143        0x50..=0x57 => q(K::MassFlow, Unit::KgPerH, exp(v, 7, 3)),
1144        0x58..=0x5B => q(K::FlowTemperature, Unit::Celsius, exp(v, 3, 3)),
1145        0x5C..=0x5F => q(K::ReturnTemperature, Unit::Celsius, exp(v, 3, 3)),
1146        0x60..=0x63 => q(K::TemperatureDifference, Unit::Kelvin, exp(v, 3, 3)),
1147        0x64..=0x67 => q(K::ExternalTemperature, Unit::Celsius, exp(v, 3, 3)),
1148        0x68..=0x6B => q(K::Pressure, Unit::Bar, exp(v, 3, 3)),
1149        0x6C => d(K::Date, None, 0, P),
1150        0x6D => d(K::DateTime, None, 0, P),
1151        0x6E => d(K::HcaUnits, None, 0, P),
1152        0x70..=0x73 => q(K::AveragingDuration, Unit::duration(v), 0),
1153        0x74..=0x77 => q(K::ActualityDuration, Unit::duration(v), 0),
1154        0x78 => d(K::FabricationNumber, None, 0, P),
1155        0x79 => d(K::Identification, None, 0, P),
1156        0x7A => d(K::BusAddress, None, 0, P),
1157        0x7C => d(K::PlainText, None, 0, P),
1158        0x7E => d(K::AnyVif, None, 0, P),
1159        0x7F => d(K::ManufacturerSpecific, None, 0, P),
1160        // 0x6F; 0x7B and 0x7D only reach here without a table code.
1161        _ => d(K::Reserved { table: P, code: v }, None, 0, P),
1162    }
1163}
1164
1165/// The extension table after VIF `FD` (EN 13757-3:2018, Table 12).
1166#[allow(clippy::too_many_lines)]
1167fn fd(c: u8) -> Description {
1168    use Kind as K;
1169    const T: Table = Table::Fd;
1170    let n = |kind| d(kind, None, 0, T);
1171    let q = |kind, unit, e| d(kind, Some(unit), e, T);
1172    match c {
1173        0x00..=0x03 => q(K::Credit, Unit::Currency, exp(c, 3, 3)),
1174        0x04..=0x07 => q(K::Debit, Unit::Currency, exp(c, 3, 3)),
1175        0x08 => n(K::AccessNumber),
1176        0x09 => n(K::Medium),
1177        0x0A => n(K::Manufacturer),
1178        0x0B => n(K::ParameterSetId),
1179        0x0C => n(K::ModelVersion),
1180        0x0D => n(K::HardwareVersion),
1181        0x0E => n(K::FirmwareVersion),
1182        0x0F => n(K::SoftwareVersion),
1183        0x10 => n(K::CustomerLocation),
1184        0x11 => n(K::Customer),
1185        0x12 => n(K::AccessCodeUser),
1186        0x13 => n(K::AccessCodeOperator),
1187        0x14 => n(K::AccessCodeSystemOperator),
1188        0x15 => n(K::AccessCodeDeveloper),
1189        0x16 => n(K::Password),
1190        0x17 => n(K::ErrorFlags),
1191        0x18 => n(K::ErrorMask),
1192        0x19 => n(K::SecurityKey),
1193        0x1A => n(K::DigitalOutput),
1194        0x1B => n(K::DigitalInput),
1195        0x1C => q(K::BaudRate, Unit::Baud, 0),
1196        0x1D => q(K::ResponseDelay, Unit::BitTimes, 0),
1197        0x1E => n(K::Retry),
1198        0x1F => n(K::RemoteControl),
1199        0x20 => n(K::FirstStorageNumber),
1200        0x21 => n(K::LastStorageNumber),
1201        0x22 => n(K::StorageBlockSize),
1202        0x23 => n(K::TariffDescriptor),
1203        0x24..=0x27 => q(K::StorageInterval, Unit::duration(c), 0),
1204        0x28 => q(K::StorageInterval, Unit::Months, 0),
1205        0x29 => q(K::StorageInterval, Unit::Years, 0),
1206        0x2A => n(K::OperatorSpecific),
1207        0x2B => q(K::TimePointSecond, Unit::Seconds, 0),
1208        0x2C..=0x2F => q(K::DurationSinceReadout, Unit::duration(c), 0),
1209        0x30 => n(K::TariffStart),
1210        0x31..=0x33 => q(K::TariffDuration, Unit::duration(c), 0),
1211        0x34..=0x37 => q(K::TariffPeriod, Unit::duration(c), 0),
1212        0x38 => q(K::TariffPeriod, Unit::Months, 0),
1213        0x39 => q(K::TariffPeriod, Unit::Years, 0),
1214        0x3A => n(K::Dimensionless),
1215        0x3B => n(K::WmbusContainer),
1216        0x3C..=0x3F => q(K::TransmissionPeriod, Unit::duration(c), 0),
1217        0x40..=0x4F => q(K::Voltage, Unit::Volt, exp(c, 0x0F, 9)),
1218        0x50..=0x5F => q(K::Current, Unit::Ampere, exp(c, 0x0F, 12)),
1219        0x60 => n(K::ResetCounter),
1220        0x61 => n(K::CumulationCounter),
1221        0x62 => n(K::ControlSignal),
1222        0x63 => n(K::DayOfWeek),
1223        0x64 => n(K::WeekNumber),
1224        0x65 => n(K::DayChange),
1225        0x66 => n(K::ParameterActivation),
1226        0x67 => n(K::SupplierInformation),
1227        0x68..=0x6B => q(K::DurationSinceCumulation, Unit::long_duration(c), 0),
1228        0x6C..=0x6F => q(K::BatteryOperatingTime, Unit::long_duration(c), 0),
1229        0x70 => n(K::BatteryChange),
1230        0x71 => q(K::SignalLevel, Unit::Dbm, 0),
1231        0x72 => n(K::DaylightSaving),
1232        0x73 => n(K::ListeningWindow),
1233        0x74 => q(K::RemainingBatteryLife, Unit::Days, 0),
1234        0x75 => n(K::StopCount),
1235        0x76 => n(K::ManufacturerContainer),
1236        _ => n(K::Reserved { table: T, code: c }),
1237    }
1238}
1239
1240/// The extension table after VIF `FB` (EN 13757-3:2018, Table 14).
1241fn fb(c: u8) -> Description {
1242    use Kind as K;
1243    const T: Table = Table::Fb;
1244    let q = |kind, unit, e| d(kind, Some(unit), e, T);
1245    match c {
1246        // MWh × 10^(n−1) = Wh × 10^(n+5)
1247        0x00 | 0x01 => q(K::Energy, Unit::Wh, exp(c, 1, -5)),
1248        // kvarh × 10^(n−?) per EN 13757-3:2018
1249        0x02 | 0x03 => q(K::ReactiveEnergy, Unit::VarH, exp(c, 1, -3)),
1250        0x04 | 0x05 => q(K::ApparentEnergy, Unit::VaH, exp(c, 1, -3)),
1251        // GJ × 10^(n−1) = J × 10^(n+8)
1252        0x08 | 0x09 => q(K::Energy, Unit::J, exp(c, 1, -8)),
1253        // Mcal × 10^(n−1) = cal × 10^(n+5)
1254        0x0C..=0x0F => q(K::Energy, Unit::Calorie, exp(c, 3, -5)),
1255        // m³ × 10^(n+2)
1256        0x10 | 0x11 => q(K::Volume, Unit::M3, exp(c, 1, -2)),
1257        0x14..=0x17 => q(K::ReactivePower, Unit::Var, exp(c, 3, 0)),
1258        // t × 10^(n+2) = kg × 10^(n+5)
1259        0x18 | 0x19 => q(K::Mass, Unit::Kg, exp(c, 1, -5)),
1260        0x1A | 0x1B => q(K::RelativeHumidity, Unit::Percent, exp(c, 1, 1)),
1261        0x20 => q(K::Volume, Unit::CubicFeet, 0),
1262        0x21 => q(K::Volume, Unit::CubicFeet, -1),
1263        0x22 => q(K::Volume, Unit::UsGallon, -1),
1264        0x23 => q(K::Volume, Unit::UsGallon, 0),
1265        0x24 => q(K::VolumeFlow, Unit::UsGallonPerMin, -3),
1266        0x25 => q(K::VolumeFlow, Unit::UsGallonPerMin, 0),
1267        0x26 => q(K::VolumeFlow, Unit::UsGallonPerH, 0),
1268        // MW × 10^(n−1) = W × 10^(n+5)
1269        0x28 | 0x29 => q(K::Power, Unit::W, exp(c, 1, -5)),
1270        0x2A => q(K::PhaseVoltageVoltage, Unit::Degree, -1),
1271        0x2B => q(K::PhaseVoltageCurrent, Unit::Degree, -1),
1272        0x2C..=0x2F => q(K::Frequency, Unit::Hertz, exp(c, 3, 3)),
1273        // GJ/h × 10^(n−1) = J/h × 10^(n+8)
1274        0x30 | 0x31 => q(K::Power, Unit::JPerH, exp(c, 1, -8)),
1275        0x34..=0x37 => q(K::ApparentPower, Unit::VoltAmpere, exp(c, 3, 0)),
1276        0x58..=0x5B => q(K::FlowTemperature, Unit::Fahrenheit, exp(c, 3, 3)),
1277        0x5C..=0x5F => q(K::ReturnTemperature, Unit::Fahrenheit, exp(c, 3, 3)),
1278        0x60..=0x63 => q(K::TemperatureDifference, Unit::Fahrenheit, exp(c, 3, 3)),
1279        0x64..=0x67 => q(K::ExternalTemperature, Unit::Fahrenheit, exp(c, 3, 3)),
1280        0x70..=0x73 => q(K::TemperatureLimit, Unit::Fahrenheit, exp(c, 3, 3)),
1281        0x74..=0x77 => q(K::TemperatureLimit, Unit::Celsius, exp(c, 3, 3)),
1282        0x78..=0x7F => q(K::CumulativeMaxPower, Unit::W, exp(c, 7, 3)),
1283        _ => d(K::Reserved { table: T, code: c }, None, 0, T),
1284    }
1285}
1286
1287/// The second-level table after `FD FD` (OMS Vol. 2 Annex B, citing prEN 13757-3:2023).
1288fn fd_second(c: u8) -> Description {
1289    use Kind as K;
1290    const T: Table = Table::FdSecond;
1291    let n = |kind| d(kind, None, 0, T);
1292    let q = |kind, unit, e| d(kind, Some(unit), e, T);
1293    match c {
1294        0x00 => n(K::SelectedApplication),
1295        0x01 => n(K::SubDeviceTypes),
1296        0x02 => q(K::RemainingBatteryLife, Unit::Months, 0),
1297        0x10 | 0x11 => q(K::CarbonDioxide, Unit::Ppm, exp(c, 1, 0)),
1298        0x12 | 0x13 => q(K::CarbonMonoxide, Unit::Ppm, exp(c, 1, 0)),
1299        0x14 | 0x15 => q(K::VolatileOrganicCompounds, Unit::Ppb, exp(c, 1, 0)),
1300        0x16 => q(K::VolatileOrganicCompounds, Unit::MicrogramPerM3, 0),
1301        0x17 => q(K::Particles(Particles::Any), Unit::MicrogramPerM3, 0),
1302        0x18 => q(K::Particles(Particles::Pm1), Unit::MicrogramPerM3, 0),
1303        0x19 => q(K::Particles(Particles::Pm2_5), Unit::MicrogramPerM3, 0),
1304        0x1A => q(K::Particles(Particles::Pm10), Unit::MicrogramPerM3, 0),
1305        0x1B => q(K::Particles(Particles::Any), Unit::PerM3, 5),
1306        0x1C => q(K::Particles(Particles::Pm1), Unit::PerM3, 5),
1307        0x1D => q(K::Particles(Particles::Pm2_5), Unit::PerM3, 5),
1308        0x1E => q(K::Particles(Particles::Pm10), Unit::PerM3, 5),
1309        0x1F => q(K::Illuminance, Unit::Lux, 0),
1310        0x20 => q(K::LuminousIntensity, Unit::Candela, 0),
1311        0x21 => q(K::Irradiance, Unit::WattPerM2, 0),
1312        0x22 => q(K::WindSpeed, Unit::MetrePerS, 0),
1313        0x23 => n(K::Rainfall),
1314        0x24 => q(K::SoundLevel, Unit::Dba, 0),
1315        0x25 => q(K::Turbidity, Unit::Fnu, 0),
1316        0x27 => q(K::Ph, Unit::Ph, -1),
1317        0x2C => n(K::Events(Event::Dismounts)),
1318        0x2D => n(K::Events(Event::TestButton)),
1319        0x2E => n(K::Events(Event::Alarms)),
1320        0x2F => n(K::Events(Event::AlarmMutes)),
1321        0x30 => n(K::Events(Event::Obstacles)),
1322        0x31 => n(K::Events(Event::SmokeEntryBlocked)),
1323        0x32 => n(K::Events(Event::ChamberDefects)),
1324        0x33 => n(K::Events(Event::SelfTestFailures)),
1325        0x34 => n(K::Events(Event::SounderDefects)),
1326        0x38 => q(K::BatteryStatus, Unit::Percent, 0),
1327        0x39 => q(K::ChamberPollution, Unit::Percent, 0),
1328        0x3A | 0x3B => q(K::Distance, Unit::Millimetre, exp(c, 1, 0)),
1329        0x3E => q(K::Moisture, Unit::Percent, 0),
1330        0x40 => n(K::StatusBits(Sensor::Pressure)),
1331        0x41 => n(K::StatusBits(Sensor::Smoke)),
1332        0x42 => n(K::StatusBits(Sensor::CarbonMonoxide)),
1333        0x43 => n(K::StatusBits(Sensor::Heat)),
1334        0x44 => n(K::StatusBits(Sensor::DoorWindow)),
1335        _ => n(K::Reserved { table: T, code: c }),
1336    }
1337}
1338
1339#[cfg(test)]
1340mod tests {
1341    use super::*;
1342
1343    fn vib(vif: u8, vifes: &[u8]) -> Vib<'static> {
1344        let mut v = [0u8; MAX_EXTENSIONS];
1345        v[..vifes.len()].copy_from_slice(vifes);
1346        Vib::new(vif, v, u8::try_from(vifes.len()).unwrap(), None)
1347    }
1348
1349    #[test]
1350    fn modifiers_skip_the_table_code_and_stop_at_manufacturer() {
1351        let v = vib(0xFD, &[0x97, 0x22]);
1352        assert_eq!(v.description().kind, Kind::ErrorFlags);
1353        assert_eq!(
1354            v.modifiers().collect::<heapless_vec::V>().0,
1355            [Some(Modifier::Per(Per::Hour)), None, None]
1356        );
1357        let v = vib(0x93, &[0xFF, 0x75]);
1358        assert_eq!(v.modifiers().count(), 1);
1359        let v = vib(0xFF, &[0x75]);
1360        assert_eq!(v.modifiers().count(), 0);
1361        let v = vib(0x93, &[0xFC, 0x01]);
1362        assert_eq!(v.modifiers().next(), Some(Modifier::Extension(Extension::Phase(1))));
1363        let v = vib(0xFD, &[0xFD, 0x8E, 0x75]);
1364        assert_eq!(v.description().table, Table::FdSecond);
1365        assert_eq!(v.modifiers().next(), Some(Modifier::Scale(-1)));
1366        assert_eq!(vib(0xFD, &[]).description().kind, Kind::MissingExtension(Table::Fd));
1367    }
1368
1369    // A three-slot collector so the test stays allocation-free like the crate.
1370    mod heapless_vec {
1371        pub struct V(pub [Option<super::Modifier>; 3]);
1372        impl FromIterator<super::Modifier> for V {
1373            fn from_iter<I: IntoIterator<Item = super::Modifier>>(it: I) -> Self {
1374                let mut out = [None; 3];
1375                for (slot, m) in out.iter_mut().zip(it) {
1376                    *slot = Some(m);
1377                }
1378                Self(out)
1379            }
1380        }
1381    }
1382}