matter-kit 0.3.0

Matter (CSA smart-home standard) protocol implementation in Rust: no_std, no-alloc, executor-agnostic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
// Generated by `cargo xtask` from the CSA data model 1.6. Do not edit.
//
// Energy EVSE — cluster 0x0099.
//
// Regenerate with `cargo xtask clusters --dm <checkout>/data_model/1.6`; `cargo xtask check`
// is the CI gate that keeps this file honest. The XML itself is not vendored here — it
// carries the CSA's own copyright notice and is not redistributable.

//! Energy EVSE (cluster `0x0099`, revision 4).
//!
//! 37 identifiers, 5 feature bits, and the specification's own conformance for
//! every element. `CLUSTER` is the whole table.

#![allow(unused_imports)]

use crate::dm::conformance::{Clause, Condition, Conform, Conformance};
use crate::dm::meta::{EventPriority, Reporting};
use crate::dm::spec::{Attribute, Cluster, Command, Event, Feature};
use crate::dm::{Access, AccessQualities, AttributeQualities, Privilege};
use crate::error::Result;
use crate::im::{AttributeId, ClusterId, CommandId, EventId};
use crate::tlv::{
    ContainerKind, Element, FromTlv, Nullable, Tag, TlvList, TlvReader, TlvWriter, ToTlv, Value,
};

/// The cluster id.
pub const ID: ClusterId = 0x0099;

/// The highest revision the specification's history defines — what `ClusterRevision`
/// must report (Core §7.13.1).
pub const REVISION: u16 = 4;

/// The PICS code, which a certification declaration names the cluster by.
pub const PICS: &str = "EEVSE";

/// The `FeatureMap` bits (Core §7.13.2).
///
/// A feature has conformance of its own: a device may not claim one the
/// specification forbids it alongside another.
pub mod feature {
    /// EVSE supports storing user charging preferences
    ///
    /// Code `PREF`, bit 0.
    pub const CHARGING_PREFERENCES: u32 = 1 << 0;
    /// EVSE supports reporting of vehicle State of Charge (SoC)
    ///
    /// Code `SOC`, bit 1.
    pub const SO_C_REPORTING: u32 = 1 << 1;
    /// EVSE supports PLC to support Plug and Charge
    ///
    /// Code `PNC`, bit 2.
    pub const PLUG_AND_CHARGE: u32 = 1 << 2;
    /// EVSE is fitted with an RFID reader
    ///
    /// Code `RFID`, bit 3.
    pub const RFID: u32 = 1 << 3;
    /// EVSE supports bi-directional charging / discharging
    ///
    /// Code `V2X`, bit 4.
    pub const V2_X: u32 = 1 << 4;
}

/// Every feature bit, with its conformance.
pub const FEATURES: &[Feature] = &[
    Feature {
        bit: 0,
        code: "PREF",
        name: "ChargingPreferences",
        conform: Conform::MANDATORY,
    },
    Feature {
        bit: 1,
        code: "SOC",
        name: "SoCReporting",
        conform: Conform::OPTIONAL,
    },
    Feature {
        bit: 2,
        code: "PNC",
        name: "PlugAndCharge",
        conform: Conform::OPTIONAL,
    },
    Feature {
        bit: 3,
        code: "RFID",
        name: "RFID",
        conform: Conform::OPTIONAL,
    },
    Feature {
        bit: 4,
        code: "V2X",
        name: "V2X",
        conform: Conform::OPTIONAL,
    },
];

/// The attribute ids.
pub mod attribute {
    use crate::im::AttributeId;

    /// `State`.
    pub const STATE: AttributeId = 0x00;
    /// `SupplyState`.
    pub const SUPPLY_STATE: AttributeId = 0x01;
    /// `FaultState`.
    pub const FAULT_STATE: AttributeId = 0x02;
    /// `ChargingEnabledUntil`.
    pub const CHARGING_ENABLED_UNTIL: AttributeId = 0x03;
    /// `DischargingEnabledUntil`.
    pub const DISCHARGING_ENABLED_UNTIL: AttributeId = 0x04;
    /// `CircuitCapacity`.
    pub const CIRCUIT_CAPACITY: AttributeId = 0x05;
    /// `MinimumChargeCurrent`.
    pub const MINIMUM_CHARGE_CURRENT: AttributeId = 0x06;
    /// `MaximumChargeCurrent`.
    pub const MAXIMUM_CHARGE_CURRENT: AttributeId = 0x07;
    /// `MaximumDischargeCurrent`.
    pub const MAXIMUM_DISCHARGE_CURRENT: AttributeId = 0x08;
    /// `UserMaximumChargeCurrent`.
    pub const USER_MAXIMUM_CHARGE_CURRENT: AttributeId = 0x09;
    /// `RandomizationDelayWindow`.
    pub const RANDOMIZATION_DELAY_WINDOW: AttributeId = 0x0A;
    /// `NextChargeStartTime`.
    pub const NEXT_CHARGE_START_TIME: AttributeId = 0x23;
    /// `NextChargeTargetTime`.
    pub const NEXT_CHARGE_TARGET_TIME: AttributeId = 0x24;
    /// `NextChargeRequiredEnergy`.
    pub const NEXT_CHARGE_REQUIRED_ENERGY: AttributeId = 0x25;
    /// `NextChargeTargetSoC`.
    pub const NEXT_CHARGE_TARGET_SO_C: AttributeId = 0x26;
    /// `ApproximateEVEfficiency`.
    pub const APPROXIMATE_EV_EFFICIENCY: AttributeId = 0x27;
    /// `StateOfCharge`.
    pub const STATE_OF_CHARGE: AttributeId = 0x30;
    /// `BatteryCapacity`.
    pub const BATTERY_CAPACITY: AttributeId = 0x31;
    /// `VehicleID`.
    pub const VEHICLE_ID: AttributeId = 0x32;
    /// `SessionID`.
    pub const SESSION_ID: AttributeId = 0x40;
    /// `SessionDuration`.
    pub const SESSION_DURATION: AttributeId = 0x41;
    /// `SessionEnergyCharged`.
    pub const SESSION_ENERGY_CHARGED: AttributeId = 0x42;
    /// `SessionEnergyDischarged`.
    pub const SESSION_ENERGY_DISCHARGED: AttributeId = 0x43;
}

/// The command ids.
pub mod command {
    use crate::im::CommandId;

    /// `GetTargetsResponse`.
    pub const GET_TARGETS_RESPONSE: CommandId = 0x00;
    /// `Disable`.
    pub const DISABLE: CommandId = 0x01;
    /// `EnableCharging`.
    pub const ENABLE_CHARGING: CommandId = 0x02;
    /// `EnableDischarging`.
    pub const ENABLE_DISCHARGING: CommandId = 0x03;
    /// `StartDiagnostics`.
    pub const START_DIAGNOSTICS: CommandId = 0x04;
    /// `SetTargets`.
    pub const SET_TARGETS: CommandId = 0x05;
    /// `GetTargets`.
    pub const GET_TARGETS: CommandId = 0x06;
    /// `ClearTargets`.
    pub const CLEAR_TARGETS: CommandId = 0x07;
}

/// The event ids.
pub mod event {
    use crate::im::EventId;

    /// `EVConnected`.
    pub const EV_CONNECTED: EventId = 0x00;
    /// `EVNotDetected`.
    pub const EV_NOT_DETECTED: EventId = 0x01;
    /// `EnergyTransferStarted`.
    pub const ENERGY_TRANSFER_STARTED: EventId = 0x02;
    /// `EnergyTransferStopped`.
    pub const ENERGY_TRANSFER_STOPPED: EventId = 0x03;
    /// `Fault`.
    pub const FAULT: EventId = 0x04;
    /// `RFID`.
    pub const RFID: EventId = 0x05;
}

/// `EnergyTransferStoppedReasonEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum EnergyTransferStoppedReasonEnum {
    /// The EV decided to stop
    EVStopped = 0,
    /// The EVSE decided to stop
    EVSEStopped = 1,
    /// An other unknown reason
    Other = 2,
}

impl EnergyTransferStoppedReasonEnum {
    /// Reads a wire value, or `None` for one this revision does not define.
    #[must_use]
    pub const fn from_value(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::EVStopped),
            1 => Some(Self::EVSEStopped),
            2 => Some(Self::Other),
            _ => None,
        }
    }

    /// Its wire value.
    #[must_use]
    pub const fn value(self) -> u8 {
        self as u8
    }
}

impl ToTlv for EnergyTransferStoppedReasonEnum {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        self.value().to_tlv(w, tag)
    }
}

impl<'a> FromTlv<'a> for EnergyTransferStoppedReasonEnum {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
    }
}

/// `FaultStateEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum FaultStateEnum {
    /// The EVSE is not in an error state.
    NoError = 0,
    /// The EVSE is unable to obtain electrical measurements.
    MeterFailure = 1,
    /// The EVSE input voltage level is too high.
    OverVoltage = 2,
    /// The EVSE input voltage level is too low.
    UnderVoltage = 3,
    /// The EVSE detected charging current higher than allowed by charger.
    OverCurrent = 4,
    /// The EVSE detected voltage on charging pins when the contactor is open.
    ContactWetFailure = 5,
    /// The EVSE detected absence of voltage after enabling contactor.
    ContactDryFailure = 6,
    /// The EVSE has an unbalanced current supply.
    GroundFault = 7,
    /// The EVSE has detected a loss in power.
    PowerLoss = 8,
    /// The EVSE has detected another power quality issue (e.g. phase imbalance).
    PowerQuality = 9,
    /// The EVSE pilot signal amplitude short circuited to ground.
    PilotShortCircuit = 10,
    /// The emergency stop button was pressed.
    EmergencyStop = 11,
    /// The EVSE detected that the cable has been disconnected.
    EVDisconnected = 12,
    /// The EVSE could not determine proper power supply level.
    WrongPowerSupply = 13,
    /// The EVSE detected Live and Neutral are swapped.
    LiveNeutralSwap = 14,
    /// The EVSE internal temperature is too high.
    OverTemperature = 15,
    /// Any other reason.
    Other = 255,
}

impl FaultStateEnum {
    /// Reads a wire value, or `None` for one this revision does not define.
    #[must_use]
    pub const fn from_value(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::NoError),
            1 => Some(Self::MeterFailure),
            2 => Some(Self::OverVoltage),
            3 => Some(Self::UnderVoltage),
            4 => Some(Self::OverCurrent),
            5 => Some(Self::ContactWetFailure),
            6 => Some(Self::ContactDryFailure),
            7 => Some(Self::GroundFault),
            8 => Some(Self::PowerLoss),
            9 => Some(Self::PowerQuality),
            10 => Some(Self::PilotShortCircuit),
            11 => Some(Self::EmergencyStop),
            12 => Some(Self::EVDisconnected),
            13 => Some(Self::WrongPowerSupply),
            14 => Some(Self::LiveNeutralSwap),
            15 => Some(Self::OverTemperature),
            255 => Some(Self::Other),
            _ => None,
        }
    }

    /// Its wire value.
    #[must_use]
    pub const fn value(self) -> u8 {
        self as u8
    }
}

impl ToTlv for FaultStateEnum {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        self.value().to_tlv(w, tag)
    }
}

impl<'a> FromTlv<'a> for FaultStateEnum {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
    }
}

/// `StateEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum StateEnum {
    /// The EV is not plugged in.
    NotPluggedIn = 0,
    /// The EV is plugged in, but not demanding current.
    PluggedInNoDemand = 1,
    /// The EV is plugged in and is demanding current, but EVSE is not allowing current to flow.
    PluggedInDemand = 2,
    /// The EV is plugged in, charging is in progress, and current is flowing
    PluggedInCharging = 3,
    /// The EV is plugged in, discharging is in progress, and current is flowing
    PluggedInDischarging = 4,
    /// The EVSE is transitioning from any plugged-in state to NotPluggedIn
    SessionEnding = 5,
    /// There is a fault, further details in the FaultState attribute
    Fault = 6,
}

impl StateEnum {
    /// Reads a wire value, or `None` for one this revision does not define.
    #[must_use]
    pub const fn from_value(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::NotPluggedIn),
            1 => Some(Self::PluggedInNoDemand),
            2 => Some(Self::PluggedInDemand),
            3 => Some(Self::PluggedInCharging),
            4 => Some(Self::PluggedInDischarging),
            5 => Some(Self::SessionEnding),
            6 => Some(Self::Fault),
            _ => None,
        }
    }

    /// Its wire value.
    #[must_use]
    pub const fn value(self) -> u8 {
        self as u8
    }
}

impl ToTlv for StateEnum {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        self.value().to_tlv(w, tag)
    }
}

impl<'a> FromTlv<'a> for StateEnum {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
    }
}

/// `SupplyStateEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum SupplyStateEnum {
    /// The EV is not currently allowed to charge or discharge
    Disabled = 0,
    /// The EV is currently allowed to charge
    ChargingEnabled = 1,
    /// The EV is currently allowed to discharge
    DischargingEnabled = 2,
    /// The EV is not currently allowed to charge or discharge due to an error. The error must be cleared before operation can continue.
    DisabledError = 3,
    /// The EV is not currently allowed to charge or discharge due to self-diagnostics mode.
    DisabledDiagnostics = 4,
    /// The EV is currently allowed to charge and discharge
    Enabled = 5,
}

impl SupplyStateEnum {
    /// Reads a wire value, or `None` for one this revision does not define.
    #[must_use]
    pub const fn from_value(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::Disabled),
            1 => Some(Self::ChargingEnabled),
            2 => Some(Self::DischargingEnabled),
            3 => Some(Self::DisabledError),
            4 => Some(Self::DisabledDiagnostics),
            5 => Some(Self::Enabled),
            _ => None,
        }
    }

    /// Its wire value.
    #[must_use]
    pub const fn value(self) -> u8 {
        self as u8
    }
}

impl ToTlv for SupplyStateEnum {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        self.value().to_tlv(w, tag)
    }
}

impl<'a> FromTlv<'a> for SupplyStateEnum {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
    }
}

bitflags::bitflags! {
    /// `TargetDayOfWeekBitmap`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
    pub struct TargetDayOfWeekBitmap: u8 {
        /// Sunday
        const SUNDAY = 1 << 0;
        /// Monday
        const MONDAY = 1 << 1;
        /// Tuesday
        const TUESDAY = 1 << 2;
        /// Wednesday
        const WEDNESDAY = 1 << 3;
        /// Thursday
        const THURSDAY = 1 << 4;
        /// Friday
        const FRIDAY = 1 << 5;
        /// Saturday
        const SATURDAY = 1 << 6;
    }
}

impl ToTlv for TargetDayOfWeekBitmap {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        self.bits().to_tlv(w, tag)
    }
}

impl<'a> FromTlv<'a> for TargetDayOfWeekBitmap {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        let bits = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
        Self::from_bits(bits).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
    }
}

/// `ChargingTargetScheduleStruct`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ChargingTargetScheduleStruct<'a> {
    /// `DayOfWeekForSequence`, field 0.
    pub day_of_week_for_sequence: TargetDayOfWeekBitmap,
    /// `ChargingTargets`, field 1.
    pub charging_targets: TlvList<'a, ChargingTargetStruct>,
}

impl<'a> ToTlv for ChargingTargetScheduleStruct<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.day_of_week_for_sequence.to_tlv(w, Tag::Context(0))?;
        self.charging_targets.to_tlv(w, Tag::Context(1))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for ChargingTargetScheduleStruct<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut day_of_week_for_sequence = None;
        let mut charging_targets = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => {
                    day_of_week_for_sequence =
                        Some(<TargetDayOfWeekBitmap>::from_tlv(reader, &field)?)
                }
                Some(1) => {
                    charging_targets = Some(<TlvList<'a, ChargingTargetStruct>>::from_tlv(
                        reader, &field,
                    )?)
                }
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            day_of_week_for_sequence: day_of_week_for_sequence
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            charging_targets: charging_targets
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// `ChargingTargetStruct`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ChargingTargetStruct {
    /// `TargetTimeMinutesPastMidnight`, field 0.
    pub target_time_minutes_past_midnight: u16,
    /// `TargetSoC`, field 1.
    pub target_so_c: Option<u8>,
    /// `AddedEnergy`, field 2.
    pub added_energy: Option<i64>,
}

impl ToTlv for ChargingTargetStruct {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.target_time_minutes_past_midnight
            .to_tlv(w, Tag::Context(0))?;
        if let Some(value) = &self.target_so_c {
            value.to_tlv(w, Tag::Context(1))?;
        }
        if let Some(value) = &self.added_energy {
            value.to_tlv(w, Tag::Context(2))?;
        }
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for ChargingTargetStruct {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut target_time_minutes_past_midnight = None;
        let mut target_so_c = None;
        let mut added_energy = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => {
                    target_time_minutes_past_midnight = Some(<u16>::from_tlv(reader, &field)?)
                }
                Some(1) => target_so_c = Some(<u8>::from_tlv(reader, &field)?),
                Some(2) => added_energy = Some(<i64>::from_tlv(reader, &field)?),
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            target_time_minutes_past_midnight: target_time_minutes_past_midnight
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            target_so_c,
            added_energy,
        })
    }
}

/// The fields of `GetTargetsResponse` (command `0x00`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GetTargetsResponseFields<'a> {
    /// `ChargingTargetSchedules`, field 0.
    pub charging_target_schedules: TlvList<'a, ChargingTargetScheduleStruct<'a>>,
}

impl<'a> ToTlv for GetTargetsResponseFields<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.charging_target_schedules.to_tlv(w, Tag::Context(0))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for GetTargetsResponseFields<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut charging_target_schedules = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => {
                    charging_target_schedules = Some(
                        <TlvList<'a, ChargingTargetScheduleStruct<'a>>>::from_tlv(reader, &field)?,
                    )
                }
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            charging_target_schedules: charging_target_schedules
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `EnableCharging` (command `0x02`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EnableChargingFields {
    /// `ChargingEnabledUntil`, field 0.
    pub charging_enabled_until: Nullable<u32>,
    /// `MinimumChargeCurrent`, field 1.
    pub minimum_charge_current: i32,
    /// `MaximumChargeCurrent`, field 2.
    pub maximum_charge_current: i32,
}

impl ToTlv for EnableChargingFields {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.charging_enabled_until.to_tlv(w, Tag::Context(0))?;
        self.minimum_charge_current.to_tlv(w, Tag::Context(1))?;
        self.maximum_charge_current.to_tlv(w, Tag::Context(2))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for EnableChargingFields {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut charging_enabled_until = None;
        let mut minimum_charge_current = None;
        let mut maximum_charge_current = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => {
                    charging_enabled_until = Some(<Nullable<u32>>::from_tlv(reader, &field)?)
                }
                Some(1) => minimum_charge_current = Some(<i32>::from_tlv(reader, &field)?),
                Some(2) => maximum_charge_current = Some(<i32>::from_tlv(reader, &field)?),
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            charging_enabled_until: charging_enabled_until
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            minimum_charge_current: minimum_charge_current
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            maximum_charge_current: maximum_charge_current
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `EnableDischarging` (command `0x03`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EnableDischargingFields {
    /// `DischargingEnabledUntil`, field 0.
    pub discharging_enabled_until: Nullable<u32>,
    /// `MaximumDischargeCurrent`, field 1.
    pub maximum_discharge_current: i32,
}

impl ToTlv for EnableDischargingFields {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.discharging_enabled_until.to_tlv(w, Tag::Context(0))?;
        self.maximum_discharge_current.to_tlv(w, Tag::Context(1))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for EnableDischargingFields {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut discharging_enabled_until = None;
        let mut maximum_discharge_current = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => {
                    discharging_enabled_until = Some(<Nullable<u32>>::from_tlv(reader, &field)?)
                }
                Some(1) => maximum_discharge_current = Some(<i32>::from_tlv(reader, &field)?),
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            discharging_enabled_until: discharging_enabled_until
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            maximum_discharge_current: maximum_discharge_current
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `SetTargets` (command `0x05`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SetTargetsFields<'a> {
    /// `ChargingTargetSchedules`, field 0.
    pub charging_target_schedules: TlvList<'a, ChargingTargetScheduleStruct<'a>>,
}

impl<'a> ToTlv for SetTargetsFields<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.charging_target_schedules.to_tlv(w, Tag::Context(0))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for SetTargetsFields<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut charging_target_schedules = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => {
                    charging_target_schedules = Some(
                        <TlvList<'a, ChargingTargetScheduleStruct<'a>>>::from_tlv(reader, &field)?,
                    )
                }
                // A field this revision does not define. §7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            charging_target_schedules: charging_target_schedules
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// Every attribute the specification defines, with its conformance.
pub const ATTRIBUTES: &[Attribute] = &[
    Attribute {
        id: 0x0000,
        name: "State",
        kind: "StateEnum",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0001,
        name: "SupplyState",
        kind: "SupplyStateEnum",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0002,
        name: "FaultState",
        kind: "FaultStateEnum",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0003,
        name: "ChargingEnabledUntil",
        kind: "epoch-s",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE.union(AttributeQualities::NON_VOLATILE),
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0004,
        name: "DischargingEnabledUntil",
        kind: "epoch-s",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE.union(AttributeQualities::NON_VOLATILE),
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(4),
            }],
        },
    },
    Attribute {
        id: 0x0005,
        name: "CircuitCapacity",
        kind: "amperage-mA",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0006,
        name: "MinimumChargeCurrent",
        kind: "amperage-mA",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0007,
        name: "MaximumChargeCurrent",
        kind: "amperage-mA",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0008,
        name: "MaximumDischargeCurrent",
        kind: "amperage-mA",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(4),
            }],
        },
    },
    Attribute {
        id: 0x0009,
        name: "UserMaximumChargeCurrent",
        kind: "amperage-mA",
        access: Access::read_write_with(Privilege::View, Privilege::Manage),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform::OPTIONAL,
    },
    Attribute {
        id: 0x000A,
        name: "RandomizationDelayWindow",
        kind: "elapsed-s",
        access: Access::read_write_with(Privilege::View, Privilege::Manage),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform::OPTIONAL,
    },
    Attribute {
        id: 0x0023,
        name: "NextChargeStartTime",
        kind: "epoch-s",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0024,
        name: "NextChargeTargetTime",
        kind: "epoch-s",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0025,
        name: "NextChargeRequiredEnergy",
        kind: "energy-mWh",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0026,
        name: "NextChargeTargetSoC",
        kind: "percent",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0027,
        name: "ApproximateEVEfficiency",
        kind: "uint16",
        access: Access::read_write_with(Privilege::View, Privilege::Manage),
        qualities: AttributeQualities::NULLABLE.union(AttributeQualities::NON_VOLATILE),
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Optional,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0030,
        name: "StateOfCharge",
        kind: "percent",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(1),
            }],
        },
    },
    Attribute {
        id: 0x0031,
        name: "BatteryCapacity",
        kind: "energy-mWh",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(1),
            }],
        },
    },
    Attribute {
        id: 0x0032,
        name: "VehicleID",
        kind: "string",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(2),
            }],
        },
    },
    Attribute {
        id: 0x0040,
        name: "SessionID",
        kind: "uint32",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE.union(AttributeQualities::NON_VOLATILE),
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0041,
        name: "SessionDuration",
        kind: "elapsed-s",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE.union(AttributeQualities::NON_VOLATILE),
        reporting: Reporting::Quieter,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0042,
        name: "SessionEnergyCharged",
        kind: "energy-mWh",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE.union(AttributeQualities::NON_VOLATILE),
        reporting: Reporting::Quieter,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0043,
        name: "SessionEnergyDischarged",
        kind: "energy-mWh",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE.union(AttributeQualities::NON_VOLATILE),
        reporting: Reporting::Quieter,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(4),
            }],
        },
    },
];

/// Every command, with its conformance.
pub const COMMANDS: &[Command] = &[
    Command {
        id: 0x00,
        name: "GetTargetsResponse",
        to_server: false,
        response: None,
        access: Access::invoke(Privilege::Operate),
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Command {
        id: 0x01,
        name: "Disable",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Operate).with_qualities(AccessQualities::TIMED),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x02,
        name: "EnableCharging",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Operate).with_qualities(AccessQualities::TIMED),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x03,
        name: "EnableDischarging",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Operate).with_qualities(AccessQualities::TIMED),
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(4),
            }],
        },
    },
    Command {
        id: 0x04,
        name: "StartDiagnostics",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Operate).with_qualities(AccessQualities::TIMED),
        conform: Conform::OPTIONAL,
    },
    Command {
        id: 0x05,
        name: "SetTargets",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Operate).with_qualities(AccessQualities::TIMED),
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Command {
        id: 0x06,
        name: "GetTargets",
        to_server: true,
        response: Some(0x00),
        access: Access::invoke(Privilege::Operate).with_qualities(AccessQualities::TIMED),
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Command {
        id: 0x07,
        name: "ClearTargets",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Operate).with_qualities(AccessQualities::TIMED),
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
];

/// Every event, with its conformance.
pub const EVENTS: &[Event] = &[
    Event {
        id: 0x00,
        name: "EVConnected",
        priority: EventPriority::Info,
        access: Access::read_only(Privilege::View),
        conform: Conform::MANDATORY,
    },
    Event {
        id: 0x01,
        name: "EVNotDetected",
        priority: EventPriority::Info,
        access: Access::read_only(Privilege::View),
        conform: Conform::MANDATORY,
    },
    Event {
        id: 0x02,
        name: "EnergyTransferStarted",
        priority: EventPriority::Info,
        access: Access::read_only(Privilege::View),
        conform: Conform::MANDATORY,
    },
    Event {
        id: 0x03,
        name: "EnergyTransferStopped",
        priority: EventPriority::Info,
        access: Access::read_only(Privilege::View),
        conform: Conform::MANDATORY,
    },
    Event {
        id: 0x04,
        name: "Fault",
        priority: EventPriority::Critical,
        access: Access::read_only(Privilege::View),
        conform: Conform::MANDATORY,
    },
    Event {
        id: 0x05,
        name: "RFID",
        priority: EventPriority::Info,
        access: Access::read_only(Privilege::View),
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Optional,
                when: Condition::Feature(3),
            }],
        },
    },
];

/// The whole cluster, as the specification defines it.
pub const CLUSTER: Cluster = Cluster {
    id: ID,
    name: "Energy EVSE",
    revision: REVISION,
    pics: "EEVSE",
    derived_from: None,
    features: FEATURES,
    attributes: ATTRIBUTES,
    commands: COMMANDS,
    events: EVENTS,
};