1use core::fmt;
20
21use crate::value::Unit;
22
23pub(crate) const MAX_EXTENSIONS: usize = 10;
25
26#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub enum Table {
38 Primary,
40 Fb,
42 Fd,
44 FdSecond,
46 Third,
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
52#[non_exhaustive]
53pub enum Kind {
54 Energy,
57 Volume,
59 Mass,
61 OnTime,
63 OperatingTime,
65 Power,
67 VolumeFlow,
69 MassFlow,
71 FlowTemperature,
73 ReturnTemperature,
75 TemperatureDifference,
77 ExternalTemperature,
79 Pressure,
81 Date,
83 DateTime,
85 HcaUnits,
87 AveragingDuration,
89 ActualityDuration,
91 FabricationNumber,
93 Identification,
95 BusAddress,
97 PlainText,
99 AnyVif,
101 ManufacturerSpecific,
103
104 Credit,
107 Debit,
109 AccessNumber,
111 Medium,
113 Manufacturer,
115 ParameterSetId,
117 ModelVersion,
119 HardwareVersion,
121 FirmwareVersion,
123 SoftwareVersion,
125 CustomerLocation,
127 Customer,
129 AccessCodeUser,
131 AccessCodeOperator,
133 AccessCodeSystemOperator,
135 AccessCodeDeveloper,
137 Password,
139 ErrorFlags,
141 ErrorMask,
143 SecurityKey,
145 DigitalOutput,
147 DigitalInput,
149 BaudRate,
151 ResponseDelay,
153 Retry,
155 RemoteControl,
157 FirstStorageNumber,
159 LastStorageNumber,
161 StorageBlockSize,
163 TariffDescriptor,
165 StorageInterval,
167 OperatorSpecific,
169 TimePointSecond,
171 DurationSinceReadout,
173 TariffStart,
175 TariffDuration,
177 TariffPeriod,
179 Dimensionless,
181 WmbusContainer,
183 TransmissionPeriod,
185 Voltage,
187 Current,
189 ResetCounter,
191 CumulationCounter,
193 ControlSignal,
195 DayOfWeek,
197 WeekNumber,
199 DayChange,
201 ParameterActivation,
203 SupplierInformation,
205 DurationSinceCumulation,
207 BatteryOperatingTime,
209 BatteryChange,
211 SignalLevel,
213 DaylightSaving,
215 ListeningWindow,
217 RemainingBatteryLife,
219 StopCount,
221 ManufacturerContainer,
223
224 ReactiveEnergy,
227 ApparentEnergy,
229 ReactivePower,
231 ApparentPower,
233 RelativeHumidity,
235 PhaseVoltageVoltage,
237 PhaseVoltageCurrent,
239 Frequency,
241 TemperatureLimit,
243 CumulativeMaxPower,
245
246 SelectedApplication,
249 SubDeviceTypes,
251 CarbonDioxide,
253 CarbonMonoxide,
255 VolatileOrganicCompounds,
257 Particles(Particles),
259 Illuminance,
261 LuminousIntensity,
263 Irradiance,
265 WindSpeed,
267 Rainfall,
269 SoundLevel,
271 Turbidity,
273 Ph,
275 Events(Event),
277 BatteryStatus,
279 ChamberPollution,
281 Distance,
283 Moisture,
285 StatusBits(Sensor),
287
288 Reserved {
290 table: Table,
292 code: u8,
294 },
295 MissingExtension(Table),
297}
298
299impl Kind {
300 #[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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
446pub enum Particles {
447 Any,
449 Pm1,
451 Pm2_5,
453 Pm10,
455}
456
457#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
459pub enum Event {
460 Dismounts,
462 TestButton,
464 Alarms,
466 AlarmMutes,
468 Obstacles,
470 SmokeEntryBlocked,
472 ChamberDefects,
474 SelfTestFailures,
476 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
498pub enum Sensor {
499 Pressure,
501 Smoke,
503 CarbonMonoxide,
505 Heat,
507 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
526pub struct Description {
527 pub kind: Kind,
529 pub unit: Option<Unit>,
532 pub exponent: i8,
534 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
546pub enum Direction {
547 Forward,
549 Inverse,
551 WithRegisters,
553}
554
555#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
557#[non_exhaustive]
558pub enum Per {
559 Second,
561 Minute,
563 Hour,
565 Day,
567 Week,
569 Month,
571 Year,
573 Revolution,
575 Litre,
577 CubicMetre,
579 Kilogram,
581 Kelvin,
583 KilowattHour,
585 Gigajoule,
587 Kilowatt,
589 KelvinLitre,
591 Volt,
593 Ampere,
595}
596
597impl Per {
598 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
625pub enum Times {
626 Second,
628 SecondPerVolt,
630 SecondPerAmpere,
632}
633
634#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
637pub struct RecordError(pub u8);
638
639impl RecordError {
640 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
668#[non_exhaustive]
669pub enum Modifier {
670 Error(RecordError),
672 Average,
674 CompactProfile(Direction),
677 RelativeDeviation,
679 StandardConformant,
681 Per(Per),
683 IncrementPerPulse {
685 output: bool,
687 channel: u8,
689 },
690 MultipliedBy(Times),
692 StartDateOf,
694 UncorrectedUnit,
696 Forward,
698 Backward,
701 NonMetric,
703 BaseConditions,
705 ObisDeclaration,
707 Limit {
709 upper: bool,
711 },
712 ExceedCount {
714 upper: bool,
716 },
717 LimitExceedDate {
719 upper: bool,
721 last: bool,
723 end: bool,
725 },
726 LimitExceedDuration {
728 upper: bool,
730 last: bool,
732 unit: Unit,
734 },
735 Duration {
737 last: bool,
739 unit: Unit,
741 },
742 ValueDuringLimitExceed {
744 upper: bool,
746 },
747 Leakage,
749 Overflow,
751 DateOf {
754 last: bool,
756 end: bool,
758 },
759 Scale(i8),
762 Offset(i8),
765 Extension(Extension),
767 FutureValue,
769 ManufacturerSpecific,
771 Reserved(u8),
773}
774
775impl Modifier {
776 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 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)] 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
963#[non_exhaustive]
964pub enum Extension {
965 Phase(u8),
967 Neutral,
969 BetweenPhases(u8),
971 Quadrant(u8),
973 ImportExportDelta,
975 Absolute,
977 Unsigned,
979 Boolean,
981 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#[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 pub const fn vif(&self) -> u8 {
1064 self.vif
1065 }
1066
1067 pub fn vifes(&self) -> &[u8] {
1069 self.vifes.get(..usize::from(self.vife_len)).unwrap_or(&[])
1070 }
1071
1072 pub const fn plain_text(&self) -> Option<&'a [u8]> {
1075 self.plain_text
1076 }
1077
1078 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 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 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#[allow(clippy::cast_possible_wrap)] const fn exp(code: u8, mask: u8, offset: i8) -> i8 {
1123 (code & mask) as i8 - offset
1124}
1125
1126fn 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 _ => d(K::Reserved { table: P, code: v }, None, 0, P),
1162 }
1163}
1164
1165#[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
1240fn 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 0x00 | 0x01 => q(K::Energy, Unit::Wh, exp(c, 1, -5)),
1248 0x02 | 0x03 => q(K::ReactiveEnergy, Unit::VarH, exp(c, 1, -3)),
1250 0x04 | 0x05 => q(K::ApparentEnergy, Unit::VaH, exp(c, 1, -3)),
1251 0x08 | 0x09 => q(K::Energy, Unit::J, exp(c, 1, -8)),
1253 0x0C..=0x0F => q(K::Energy, Unit::Calorie, exp(c, 3, -5)),
1255 0x10 | 0x11 => q(K::Volume, Unit::M3, exp(c, 1, -2)),
1257 0x14..=0x17 => q(K::ReactivePower, Unit::Var, exp(c, 3, 0)),
1258 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 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 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
1287fn 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 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}