matc 0.1.3

Matter protocol library (controller side)
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
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
//! Matter TLV encoders and decoders for Commodity Tariff Cluster
//! Cluster ID: 0x0700
//!
//! This file is automatically generated from CommodityTariff.xml

#![allow(clippy::too_many_arguments)]

use crate::tlv;
use anyhow;
use serde_json;


// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum AuxiliaryLoadSetting {
    /// The switch should be in the OFF state
    Off = 0,
    /// The switch should be in the ON state
    On = 1,
    /// No state is required
    None = 2,
}

impl AuxiliaryLoadSetting {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(AuxiliaryLoadSetting::Off),
            1 => Some(AuxiliaryLoadSetting::On),
            2 => Some(AuxiliaryLoadSetting::None),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<AuxiliaryLoadSetting> for u8 {
    fn from(val: AuxiliaryLoadSetting) -> Self {
        val as u8
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum BlockMode {
    /// Tariff has no usage blocks
    Noblock = 0,
    /// Usage is metered in combined blocks
    Combined = 1,
    /// Usage is metered separately by tariff component
    Individual = 2,
}

impl BlockMode {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(BlockMode::Noblock),
            1 => Some(BlockMode::Combined),
            2 => Some(BlockMode::Individual),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<BlockMode> for u8 {
    fn from(val: BlockMode) -> Self {
        val as u8
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum DayEntryRandomizationType {
    /// No randomization applied
    None = 0,
    /// An unchanging offset
    Fixed = 1,
    /// A random value
    Random = 2,
    /// A random positive value
    Randompositive = 3,
    /// A random negative value
    Randomnegative = 4,
}

impl DayEntryRandomizationType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(DayEntryRandomizationType::None),
            1 => Some(DayEntryRandomizationType::Fixed),
            2 => Some(DayEntryRandomizationType::Random),
            3 => Some(DayEntryRandomizationType::Randompositive),
            4 => Some(DayEntryRandomizationType::Randomnegative),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<DayEntryRandomizationType> for u8 {
    fn from(val: DayEntryRandomizationType) -> Self {
        val as u8
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum DayType {
    /// Standard
    Standard = 0,
    /// Holiday
    Holiday = 1,
    /// Dynamic Pricing
    Dynamic = 2,
    /// Individual Events
    Event = 3,
}

impl DayType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(DayType::Standard),
            1 => Some(DayType::Holiday),
            2 => Some(DayType::Dynamic),
            3 => Some(DayType::Event),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<DayType> for u8 {
    fn from(val: DayType) -> Self {
        val as u8
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum PeakPeriodSeverity {
    /// Unused
    Unused = 0,
    /// Low
    Low = 1,
    /// Medium
    Medium = 2,
    /// High
    High = 3,
}

impl PeakPeriodSeverity {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(PeakPeriodSeverity::Unused),
            1 => Some(PeakPeriodSeverity::Low),
            2 => Some(PeakPeriodSeverity::Medium),
            3 => Some(PeakPeriodSeverity::High),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<PeakPeriodSeverity> for u8 {
    fn from(val: PeakPeriodSeverity) -> Self {
        val as u8
    }
}

// Bitmap definitions

/// DayPatternDayOfWeek bitmap type
pub type DayPatternDayOfWeek = u8;

/// Constants for DayPatternDayOfWeek
pub mod daypatterndayofweek {
    /// Sunday
    pub const SUNDAY: u8 = 0x01;
    /// Monday
    pub const MONDAY: u8 = 0x02;
    /// Tuesday
    pub const TUESDAY: u8 = 0x04;
    /// Wednesday
    pub const WEDNESDAY: u8 = 0x08;
    /// Thursday
    pub const THURSDAY: u8 = 0x10;
    /// Friday
    pub const FRIDAY: u8 = 0x20;
    /// Saturday
    pub const SATURDAY: u8 = 0x40;
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct AuxiliaryLoadSwitchSettings {
    pub number: Option<u8>,
    pub required_state: Option<AuxiliaryLoadSetting>,
}

#[derive(Debug, serde::Serialize)]
pub struct AuxiliaryLoadSwitchesSettings {
    pub switch_states: Option<Vec<AuxiliaryLoadSwitchSettings>>,
}

#[derive(Debug, serde::Serialize)]
pub struct CalendarPeriod {
    pub start_date: Option<u64>,
    pub day_pattern_i_ds: Option<Vec<u32>>,
}

#[derive(Debug, serde::Serialize)]
pub struct DayEntry {
    pub day_entry_id: Option<u32>,
    pub start_time: Option<u16>,
    pub duration: Option<u16>,
    pub randomization_offset: Option<i16>,
    pub randomization_type: Option<DayEntryRandomizationType>,
}

#[derive(Debug, serde::Serialize)]
pub struct DayPattern {
    pub day_pattern_id: Option<u32>,
    pub days_of_week: Option<DayPatternDayOfWeek>,
    pub day_entry_i_ds: Option<Vec<u32>>,
}

#[derive(Debug, serde::Serialize)]
pub struct Day {
    pub date: Option<u64>,
    pub day_type: Option<DayType>,
    pub day_entry_i_ds: Option<Vec<u32>>,
}

#[derive(Debug, serde::Serialize)]
pub struct PeakPeriod {
    pub severity: Option<PeakPeriodSeverity>,
    pub peak_period: Option<u16>,
}

#[derive(Debug, serde::Serialize)]
pub struct TariffComponent {
    pub tariff_component_id: Option<u32>,
    pub price: Option<TariffPrice>,
    pub friendly_credit: Option<bool>,
    pub auxiliary_load: Option<AuxiliaryLoadSwitchSettings>,
    pub peak_period: Option<PeakPeriod>,
    pub threshold: Option<i64>,
    pub label: Option<String>,
    pub predicted: Option<bool>,
}

#[derive(Debug, serde::Serialize)]
pub struct TariffInformation {
    pub tariff_label: Option<String>,
    pub provider_name: Option<String>,
    pub block_mode: Option<BlockMode>,
}

#[derive(Debug, serde::Serialize)]
pub struct TariffPeriod {
    pub label: Option<String>,
    pub day_entry_i_ds: Option<Vec<u32>>,
    pub tariff_component_i_ds: Option<Vec<u32>>,
}

#[derive(Debug, serde::Serialize)]
pub struct TariffPrice {
    pub price_type: Option<u8>,
    pub price: Option<u8>,
    pub price_level: Option<i16>,
}

// Command encoders

/// Encode GetTariffComponent command (0x00)
pub fn encode_get_tariff_component(tariff_component_id: u32) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt32(tariff_component_id)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode GetDayEntry command (0x01)
pub fn encode_get_day_entry(day_entry_id: u32) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt32(day_entry_id)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode TariffInfo attribute (0x0000)
pub fn decode_tariff_info(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<TariffInformation>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(TariffInformation {
                tariff_label: item.get_string_owned(&[0]),
                provider_name: item.get_string_owned(&[1]),
                block_mode: item.get_int(&[3]).and_then(|v| BlockMode::from_u8(v as u8)),
        }))
    //} else if let tlv::TlvItemValue::Null = inp {
    //    // Null value for nullable struct
    //    Ok(None)
    } else {
    Ok(None)
    //    Err(anyhow::anyhow!("Expected struct fields or null"))
    }
}

/// Decode TariffUnit attribute (0x0001)
pub fn decode_tariff_unit(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u8))
    } else {
        Ok(None)
    }
}

/// Decode StartDate attribute (0x0002)
pub fn decode_start_date(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v))
    } else {
        Ok(None)
    }
}

/// Decode DayEntries attribute (0x0003)
pub fn decode_day_entries(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<DayEntry>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(DayEntry {
                day_entry_id: item.get_int(&[0]).map(|v| v as u32),
                start_time: item.get_int(&[1]).map(|v| v as u16),
                duration: item.get_int(&[2]).map(|v| v as u16),
                randomization_offset: item.get_int(&[3]).map(|v| v as i16),
                randomization_type: item.get_int(&[4]).and_then(|v| DayEntryRandomizationType::from_u8(v as u8)),
            });
        }
    }
    Ok(res)
}

/// Decode DayPatterns attribute (0x0004)
pub fn decode_day_patterns(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<DayPattern>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(DayPattern {
                day_pattern_id: item.get_int(&[0]).map(|v| v as u32),
                days_of_week: item.get_int(&[1]).map(|v| v as u8),
                day_entry_i_ds: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let items: Vec<u32> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u32) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

/// Decode CalendarPeriods attribute (0x0005)
pub fn decode_calendar_periods(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<CalendarPeriod>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(CalendarPeriod {
                start_date: item.get_int(&[0]),
                day_pattern_i_ds: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[1]) {
                        let items: Vec<u32> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u32) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

/// Decode IndividualDays attribute (0x0006)
pub fn decode_individual_days(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<Day>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(Day {
                date: item.get_int(&[0]),
                day_type: item.get_int(&[1]).and_then(|v| DayType::from_u8(v as u8)),
                day_entry_i_ds: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let items: Vec<u32> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u32) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

/// Decode CurrentDay attribute (0x0007)
pub fn decode_current_day(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<Day>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(Day {
                date: item.get_int(&[0]),
                day_type: item.get_int(&[1]).and_then(|v| DayType::from_u8(v as u8)),
                day_entry_i_ds: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let items: Vec<u32> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u32) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
        }))
    //} else if let tlv::TlvItemValue::Null = inp {
    //    // Null value for nullable struct
    //    Ok(None)
    } else {
    Ok(None)
    //    Err(anyhow::anyhow!("Expected struct fields or null"))
    }
}

/// Decode NextDay attribute (0x0008)
pub fn decode_next_day(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<Day>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(Day {
                date: item.get_int(&[0]),
                day_type: item.get_int(&[1]).and_then(|v| DayType::from_u8(v as u8)),
                day_entry_i_ds: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let items: Vec<u32> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u32) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
        }))
    //} else if let tlv::TlvItemValue::Null = inp {
    //    // Null value for nullable struct
    //    Ok(None)
    } else {
    Ok(None)
    //    Err(anyhow::anyhow!("Expected struct fields or null"))
    }
}

/// Decode CurrentDayEntry attribute (0x0009)
pub fn decode_current_day_entry(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<DayEntry>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(DayEntry {
                day_entry_id: item.get_int(&[0]).map(|v| v as u32),
                start_time: item.get_int(&[1]).map(|v| v as u16),
                duration: item.get_int(&[2]).map(|v| v as u16),
                randomization_offset: item.get_int(&[3]).map(|v| v as i16),
                randomization_type: item.get_int(&[4]).and_then(|v| DayEntryRandomizationType::from_u8(v as u8)),
        }))
    //} else if let tlv::TlvItemValue::Null = inp {
    //    // Null value for nullable struct
    //    Ok(None)
    } else {
    Ok(None)
    //    Err(anyhow::anyhow!("Expected struct fields or null"))
    }
}

/// Decode CurrentDayEntryDate attribute (0x000A)
pub fn decode_current_day_entry_date(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v))
    } else {
        Ok(None)
    }
}

/// Decode NextDayEntry attribute (0x000B)
pub fn decode_next_day_entry(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<DayEntry>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(DayEntry {
                day_entry_id: item.get_int(&[0]).map(|v| v as u32),
                start_time: item.get_int(&[1]).map(|v| v as u16),
                duration: item.get_int(&[2]).map(|v| v as u16),
                randomization_offset: item.get_int(&[3]).map(|v| v as i16),
                randomization_type: item.get_int(&[4]).and_then(|v| DayEntryRandomizationType::from_u8(v as u8)),
        }))
    //} else if let tlv::TlvItemValue::Null = inp {
    //    // Null value for nullable struct
    //    Ok(None)
    } else {
    Ok(None)
    //    Err(anyhow::anyhow!("Expected struct fields or null"))
    }
}

/// Decode NextDayEntryDate attribute (0x000C)
pub fn decode_next_day_entry_date(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v))
    } else {
        Ok(None)
    }
}

/// Decode TariffComponents attribute (0x000D)
pub fn decode_tariff_components(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TariffComponent>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TariffComponent {
                tariff_component_id: item.get_int(&[0]).map(|v| v as u32),
                price: {
                    if let Some(nested_tlv) = item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(TariffPrice {
                price_type: nested_item.get_int(&[0]).map(|v| v as u8),
                price: nested_item.get_int(&[1]).map(|v| v as u8),
                price_level: nested_item.get_int(&[2]).map(|v| v as i16),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                friendly_credit: item.get_bool(&[2]),
                auxiliary_load: {
                    if let Some(nested_tlv) = item.get(&[3]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 3, value: nested_tlv.clone() };
                            Some(AuxiliaryLoadSwitchSettings {
                number: nested_item.get_int(&[0]).map(|v| v as u8),
                required_state: nested_item.get_int(&[1]).and_then(|v| AuxiliaryLoadSetting::from_u8(v as u8)),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                peak_period: {
                    if let Some(nested_tlv) = item.get(&[4]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 4, value: nested_tlv.clone() };
                            Some(PeakPeriod {
                severity: nested_item.get_int(&[0]).and_then(|v| PeakPeriodSeverity::from_u8(v as u8)),
                peak_period: nested_item.get_int(&[1]).map(|v| v as u16),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                threshold: item.get_int(&[6]).map(|v| v as i64),
                label: item.get_string_owned(&[7]),
                predicted: item.get_bool(&[8]),
            });
        }
    }
    Ok(res)
}

/// Decode TariffPeriods attribute (0x000E)
pub fn decode_tariff_periods(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TariffPeriod>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TariffPeriod {
                label: item.get_string_owned(&[0]),
                day_entry_i_ds: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[1]) {
                        let items: Vec<u32> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u32) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                tariff_component_i_ds: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let items: Vec<u32> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u32) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

/// Decode CurrentTariffComponents attribute (0x000F)
pub fn decode_current_tariff_components(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TariffComponent>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TariffComponent {
                tariff_component_id: item.get_int(&[0]).map(|v| v as u32),
                price: {
                    if let Some(nested_tlv) = item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(TariffPrice {
                price_type: nested_item.get_int(&[0]).map(|v| v as u8),
                price: nested_item.get_int(&[1]).map(|v| v as u8),
                price_level: nested_item.get_int(&[2]).map(|v| v as i16),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                friendly_credit: item.get_bool(&[2]),
                auxiliary_load: {
                    if let Some(nested_tlv) = item.get(&[3]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 3, value: nested_tlv.clone() };
                            Some(AuxiliaryLoadSwitchSettings {
                number: nested_item.get_int(&[0]).map(|v| v as u8),
                required_state: nested_item.get_int(&[1]).and_then(|v| AuxiliaryLoadSetting::from_u8(v as u8)),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                peak_period: {
                    if let Some(nested_tlv) = item.get(&[4]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 4, value: nested_tlv.clone() };
                            Some(PeakPeriod {
                severity: nested_item.get_int(&[0]).and_then(|v| PeakPeriodSeverity::from_u8(v as u8)),
                peak_period: nested_item.get_int(&[1]).map(|v| v as u16),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                threshold: item.get_int(&[6]).map(|v| v as i64),
                label: item.get_string_owned(&[7]),
                predicted: item.get_bool(&[8]),
            });
        }
    }
    Ok(res)
}

/// Decode NextTariffComponents attribute (0x0010)
pub fn decode_next_tariff_components(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TariffComponent>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TariffComponent {
                tariff_component_id: item.get_int(&[0]).map(|v| v as u32),
                price: {
                    if let Some(nested_tlv) = item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(TariffPrice {
                price_type: nested_item.get_int(&[0]).map(|v| v as u8),
                price: nested_item.get_int(&[1]).map(|v| v as u8),
                price_level: nested_item.get_int(&[2]).map(|v| v as i16),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                friendly_credit: item.get_bool(&[2]),
                auxiliary_load: {
                    if let Some(nested_tlv) = item.get(&[3]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 3, value: nested_tlv.clone() };
                            Some(AuxiliaryLoadSwitchSettings {
                number: nested_item.get_int(&[0]).map(|v| v as u8),
                required_state: nested_item.get_int(&[1]).and_then(|v| AuxiliaryLoadSetting::from_u8(v as u8)),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                peak_period: {
                    if let Some(nested_tlv) = item.get(&[4]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 4, value: nested_tlv.clone() };
                            Some(PeakPeriod {
                severity: nested_item.get_int(&[0]).and_then(|v| PeakPeriodSeverity::from_u8(v as u8)),
                peak_period: nested_item.get_int(&[1]).map(|v| v as u16),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                threshold: item.get_int(&[6]).map(|v| v as i64),
                label: item.get_string_owned(&[7]),
                predicted: item.get_bool(&[8]),
            });
        }
    }
    Ok(res)
}

/// Decode DefaultRandomizationOffset attribute (0x0011)
pub fn decode_default_randomization_offset(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<i16>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as i16))
    } else {
        Ok(None)
    }
}

/// Decode DefaultRandomizationType attribute (0x0012)
pub fn decode_default_randomization_type(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<DayEntryRandomizationType>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(DayEntryRandomizationType::from_u8(*v as u8))
    } else {
        Ok(None)
    }
}


// JSON dispatcher function

/// Decode attribute value and return as JSON string
///
/// # Parameters
/// * `cluster_id` - The cluster identifier
/// * `attribute_id` - The attribute identifier
/// * `tlv_value` - The TLV value to decode
///
/// # Returns
/// JSON string representation of the decoded value or error
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
    // Verify this is the correct cluster
    if cluster_id != 0x0700 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0700, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_tariff_info(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_tariff_unit(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_start_date(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_day_entries(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_day_patterns(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_calendar_periods(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_individual_days(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_current_day(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_next_day(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_current_day_entry(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000A => {
            match decode_current_day_entry_date(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000B => {
            match decode_next_day_entry(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000C => {
            match decode_next_day_entry_date(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000D => {
            match decode_tariff_components(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000E => {
            match decode_tariff_periods(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000F => {
            match decode_current_tariff_components(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0010 => {
            match decode_next_tariff_components(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0011 => {
            match decode_default_randomization_offset(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0012 => {
            match decode_default_randomization_type(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
    }
}

/// Get list of all attributes supported by this cluster
///
/// # Returns
/// Vector of tuples containing (attribute_id, attribute_name)
pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x0000, "TariffInfo"),
        (0x0001, "TariffUnit"),
        (0x0002, "StartDate"),
        (0x0003, "DayEntries"),
        (0x0004, "DayPatterns"),
        (0x0005, "CalendarPeriods"),
        (0x0006, "IndividualDays"),
        (0x0007, "CurrentDay"),
        (0x0008, "NextDay"),
        (0x0009, "CurrentDayEntry"),
        (0x000A, "CurrentDayEntryDate"),
        (0x000B, "NextDayEntry"),
        (0x000C, "NextDayEntryDate"),
        (0x000D, "TariffComponents"),
        (0x000E, "TariffPeriods"),
        (0x000F, "CurrentTariffComponents"),
        (0x0010, "NextTariffComponents"),
        (0x0011, "DefaultRandomizationOffset"),
        (0x0012, "DefaultRandomizationType"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "GetTariffComponent"),
        (0x01, "GetDayEntry"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("GetTariffComponent"),
        0x01 => Some("GetDayEntry"),
        _ => None,
    }
}

pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
    match cmd_id {
        0x00 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "tariff_component_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "day_entry_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => {
        let tariff_component_id = crate::clusters::codec::json_util::get_u32(args, "tariff_component_id")?;
        encode_get_tariff_component(tariff_component_id)
        }
        0x01 => {
        let day_entry_id = crate::clusters::codec::json_util::get_u32(args, "day_entry_id")?;
        encode_get_day_entry(day_entry_id)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct GetTariffComponentResponse {
    pub label: Option<String>,
    pub day_entry_i_ds: Option<Vec<u32>>,
    pub tariff_component: Option<TariffComponent>,
}

#[derive(Debug, serde::Serialize)]
pub struct GetDayEntryResponse {
    pub day_entry: Option<DayEntry>,
}

// Command response decoders

/// Decode GetTariffComponentResponse command response (00)
pub fn decode_get_tariff_component_response(inp: &tlv::TlvItemValue) -> anyhow::Result<GetTariffComponentResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(GetTariffComponentResponse {
                label: item.get_string_owned(&[0]),
                day_entry_i_ds: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[1]) {
                        let items: Vec<u32> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u32) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                tariff_component: {
                    if let Some(nested_tlv) = item.get(&[2]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 2, value: nested_tlv.clone() };
                            Some(TariffComponent {
                tariff_component_id: nested_item.get_int(&[0]).map(|v| v as u32),
                price: {
                    if let Some(nested_tlv) = nested_item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(TariffPrice {
                price_type: nested_item.get_int(&[0]).map(|v| v as u8),
                price: nested_item.get_int(&[1]).map(|v| v as u8),
                price_level: nested_item.get_int(&[2]).map(|v| v as i16),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                friendly_credit: nested_item.get_bool(&[2]),
                auxiliary_load: {
                    if let Some(nested_tlv) = nested_item.get(&[3]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 3, value: nested_tlv.clone() };
                            Some(AuxiliaryLoadSwitchSettings {
                number: nested_item.get_int(&[0]).map(|v| v as u8),
                required_state: nested_item.get_int(&[1]).and_then(|v| AuxiliaryLoadSetting::from_u8(v as u8)),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                peak_period: {
                    if let Some(nested_tlv) = nested_item.get(&[4]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 4, value: nested_tlv.clone() };
                            Some(PeakPeriod {
                severity: nested_item.get_int(&[0]).and_then(|v| PeakPeriodSeverity::from_u8(v as u8)),
                peak_period: nested_item.get_int(&[1]).map(|v| v as u16),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                threshold: nested_item.get_int(&[6]).map(|v| v as i64),
                label: nested_item.get_string_owned(&[7]),
                predicted: nested_item.get_bool(&[8]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode GetDayEntryResponse command response (01)
pub fn decode_get_day_entry_response(inp: &tlv::TlvItemValue) -> anyhow::Result<GetDayEntryResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(GetDayEntryResponse {
                day_entry: {
                    if let Some(nested_tlv) = item.get(&[0]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
                            Some(DayEntry {
                day_entry_id: nested_item.get_int(&[0]).map(|v| v as u32),
                start_time: nested_item.get_int(&[1]).map(|v| v as u16),
                duration: nested_item.get_int(&[2]).map(|v| v as u16),
                randomization_offset: nested_item.get_int(&[3]).map(|v| v as i16),
                randomization_type: nested_item.get_int(&[4]).and_then(|v| DayEntryRandomizationType::from_u8(v as u8)),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `GetTariffComponent` command on cluster `Commodity Tariff`.
pub async fn get_tariff_component(conn: &crate::controller::Connection, endpoint: u16, tariff_component_id: u32) -> anyhow::Result<GetTariffComponentResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_CMD_ID_GETTARIFFCOMPONENT, &encode_get_tariff_component(tariff_component_id)?).await?;
    decode_get_tariff_component_response(&tlv)
}

/// Invoke `GetDayEntry` command on cluster `Commodity Tariff`.
pub async fn get_day_entry(conn: &crate::controller::Connection, endpoint: u16, day_entry_id: u32) -> anyhow::Result<GetDayEntryResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_CMD_ID_GETDAYENTRY, &encode_get_day_entry(day_entry_id)?).await?;
    decode_get_day_entry_response(&tlv)
}

/// Read `TariffInfo` attribute from cluster `Commodity Tariff`.
pub async fn read_tariff_info(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<TariffInformation>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_TARIFFINFO).await?;
    decode_tariff_info(&tlv)
}

/// Read `TariffUnit` attribute from cluster `Commodity Tariff`.
pub async fn read_tariff_unit(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_TARIFFUNIT).await?;
    decode_tariff_unit(&tlv)
}

/// Read `StartDate` attribute from cluster `Commodity Tariff`.
pub async fn read_start_date(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_STARTDATE).await?;
    decode_start_date(&tlv)
}

/// Read `DayEntries` attribute from cluster `Commodity Tariff`.
pub async fn read_day_entries(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<DayEntry>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_DAYENTRIES).await?;
    decode_day_entries(&tlv)
}

/// Read `DayPatterns` attribute from cluster `Commodity Tariff`.
pub async fn read_day_patterns(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<DayPattern>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_DAYPATTERNS).await?;
    decode_day_patterns(&tlv)
}

/// Read `CalendarPeriods` attribute from cluster `Commodity Tariff`.
pub async fn read_calendar_periods(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<CalendarPeriod>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_CALENDARPERIODS).await?;
    decode_calendar_periods(&tlv)
}

/// Read `IndividualDays` attribute from cluster `Commodity Tariff`.
pub async fn read_individual_days(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<Day>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_INDIVIDUALDAYS).await?;
    decode_individual_days(&tlv)
}

/// Read `CurrentDay` attribute from cluster `Commodity Tariff`.
pub async fn read_current_day(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<Day>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_CURRENTDAY).await?;
    decode_current_day(&tlv)
}

/// Read `NextDay` attribute from cluster `Commodity Tariff`.
pub async fn read_next_day(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<Day>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_NEXTDAY).await?;
    decode_next_day(&tlv)
}

/// Read `CurrentDayEntry` attribute from cluster `Commodity Tariff`.
pub async fn read_current_day_entry(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<DayEntry>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_CURRENTDAYENTRY).await?;
    decode_current_day_entry(&tlv)
}

/// Read `CurrentDayEntryDate` attribute from cluster `Commodity Tariff`.
pub async fn read_current_day_entry_date(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_CURRENTDAYENTRYDATE).await?;
    decode_current_day_entry_date(&tlv)
}

/// Read `NextDayEntry` attribute from cluster `Commodity Tariff`.
pub async fn read_next_day_entry(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<DayEntry>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_NEXTDAYENTRY).await?;
    decode_next_day_entry(&tlv)
}

/// Read `NextDayEntryDate` attribute from cluster `Commodity Tariff`.
pub async fn read_next_day_entry_date(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_NEXTDAYENTRYDATE).await?;
    decode_next_day_entry_date(&tlv)
}

/// Read `TariffComponents` attribute from cluster `Commodity Tariff`.
pub async fn read_tariff_components(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TariffComponent>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_TARIFFCOMPONENTS).await?;
    decode_tariff_components(&tlv)
}

/// Read `TariffPeriods` attribute from cluster `Commodity Tariff`.
pub async fn read_tariff_periods(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TariffPeriod>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_TARIFFPERIODS).await?;
    decode_tariff_periods(&tlv)
}

/// Read `CurrentTariffComponents` attribute from cluster `Commodity Tariff`.
pub async fn read_current_tariff_components(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TariffComponent>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_CURRENTTARIFFCOMPONENTS).await?;
    decode_current_tariff_components(&tlv)
}

/// Read `NextTariffComponents` attribute from cluster `Commodity Tariff`.
pub async fn read_next_tariff_components(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TariffComponent>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_NEXTTARIFFCOMPONENTS).await?;
    decode_next_tariff_components(&tlv)
}

/// Read `DefaultRandomizationOffset` attribute from cluster `Commodity Tariff`.
pub async fn read_default_randomization_offset(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<i16>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_DEFAULTRANDOMIZATIONOFFSET).await?;
    decode_default_randomization_offset(&tlv)
}

/// Read `DefaultRandomizationType` attribute from cluster `Commodity Tariff`.
pub async fn read_default_randomization_type(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<DayEntryRandomizationType>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_TARIFF, crate::clusters::defs::CLUSTER_COMMODITY_TARIFF_ATTR_ID_DEFAULTRANDOMIZATIONTYPE).await?;
    decode_default_randomization_type(&tlv)
}