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
//! Matter TLV encoders and decoders for Device Energy Management Cluster
//! Cluster ID: 0x0098
//!
//! This file is automatically generated from DeviceEnergyManagement.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 AdjustmentCause {
    /// The adjustment is to optimize the local energy usage
    Localoptimization = 0,
    /// The adjustment is to optimize the grid energy usage
    Gridoptimization = 1,
}

impl AdjustmentCause {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(AdjustmentCause::Localoptimization),
            1 => Some(AdjustmentCause::Gridoptimization),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum Cause {
    /// The ESA completed the power adjustment as requested
    Normalcompletion = 0,
    /// The ESA was set to offline
    Offline = 1,
    /// The ESA has developed a fault could not complete the adjustment
    Fault = 2,
    /// The user has disabled the ESA's flexibility capability
    Useroptout = 3,
    /// The adjustment was cancelled by a client
    Cancelled = 4,
}

impl Cause {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Cause::Normalcompletion),
            1 => Some(Cause::Offline),
            2 => Some(Cause::Fault),
            3 => Some(Cause::Useroptout),
            4 => Some(Cause::Cancelled),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum CostType {
    /// Financial cost
    Financial = 0,
    /// Grid CO2e grams cost
    Ghgemissions = 1,
    /// Consumer comfort impact cost
    Comfort = 2,
    /// Temperature impact cost
    Temperature = 3,
}

impl CostType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(CostType::Financial),
            1 => Some(CostType::Ghgemissions),
            2 => Some(CostType::Comfort),
            3 => Some(CostType::Temperature),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ESAState {
    /// The ESA is not available to the EMS (e.g. start-up, maintenance mode)
    Offline = 0,
    /// The ESA is working normally and can be controlled by the EMS
    Online = 1,
    /// The ESA has developed a fault and cannot provide service
    Fault = 2,
    /// The ESA is in the middle of a power adjustment event
    Poweradjustactive = 3,
    /// The ESA is currently paused by a client using the PauseRequest command
    Paused = 4,
}

impl ESAState {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ESAState::Offline),
            1 => Some(ESAState::Online),
            2 => Some(ESAState::Fault),
            3 => Some(ESAState::Poweradjustactive),
            4 => Some(ESAState::Paused),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ESAType {
    /// EV Supply Equipment
    Evse = 0,
    /// Space heating appliance
    Spaceheating = 1,
    /// Water heating appliance
    Waterheating = 2,
    /// Space cooling appliance
    Spacecooling = 3,
    /// Space heating and cooling appliance
    Spaceheatingcooling = 4,
    /// Battery Electric Storage System
    Batterystorage = 5,
    /// Solar PV inverter
    Solarpv = 6,
    /// Fridge / Freezer
    Fridgefreezer = 7,
    /// Washing Machine
    Washingmachine = 8,
    /// Dishwasher
    Dishwasher = 9,
    /// Cooking appliance
    Cooking = 10,
    /// Home water pump (e.g. drinking well)
    Homewaterpump = 11,
    /// Irrigation water pump
    Irrigationwaterpump = 12,
    /// Pool pump
    Poolpump = 13,
    /// Other appliance type
    Other = 255,
}

impl ESAType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ESAType::Evse),
            1 => Some(ESAType::Spaceheating),
            2 => Some(ESAType::Waterheating),
            3 => Some(ESAType::Spacecooling),
            4 => Some(ESAType::Spaceheatingcooling),
            5 => Some(ESAType::Batterystorage),
            6 => Some(ESAType::Solarpv),
            7 => Some(ESAType::Fridgefreezer),
            8 => Some(ESAType::Washingmachine),
            9 => Some(ESAType::Dishwasher),
            10 => Some(ESAType::Cooking),
            11 => Some(ESAType::Homewaterpump),
            12 => Some(ESAType::Irrigationwaterpump),
            13 => Some(ESAType::Poolpump),
            255 => Some(ESAType::Other),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ForecastUpdateReason {
    /// The update was due to internal ESA device optimization
    Internaloptimization = 0,
    /// The update was due to local EMS optimization
    Localoptimization = 1,
    /// The update was due to grid optimization
    Gridoptimization = 2,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum OptOutState {
    /// The user has not opted out of either local or grid optimizations
    Nooptout = 0,
    /// The user has opted out of local EMS optimizations only
    Localoptout = 1,
    /// The user has opted out of grid EMS optimizations only
    Gridoptout = 2,
    /// The user has opted out of all external optimizations
    Optout = 3,
}

impl OptOutState {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(OptOutState::Nooptout),
            1 => Some(OptOutState::Localoptout),
            2 => Some(OptOutState::Gridoptout),
            3 => Some(OptOutState::Optout),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum PowerAdjustReason {
    /// There is no Power Adjustment active
    Noadjustment = 0,
    /// There is PowerAdjustment active due to local EMS optimization
    Localoptimizationadjustment = 1,
    /// There is PowerAdjustment active due to grid optimization
    Gridoptimizationadjustment = 2,
}

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

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct Constraints {
    pub start_time: Option<u64>,
    pub duration: Option<u32>,
    pub nominal_power: Option<u32>,
    pub maximum_energy: Option<u64>,
    pub load_control: Option<i8>,
}

#[derive(Debug, serde::Serialize)]
pub struct Cost {
    pub cost_type: Option<CostType>,
    pub value: Option<i32>,
    pub decimal_points: Option<u8>,
    pub currency: Option<u16>,
}

#[derive(Debug, serde::Serialize)]
pub struct Forecast {
    pub forecast_id: Option<u32>,
    pub active_slot_number: Option<u16>,
    pub start_time: Option<u64>,
    pub end_time: Option<u64>,
    pub earliest_start_time: Option<u64>,
    pub latest_end_time: Option<u64>,
    pub is_pausable: Option<bool>,
    pub slots: Option<Vec<Slot>>,
    pub forecast_update_reason: Option<ForecastUpdateReason>,
}

#[derive(Debug, serde::Serialize)]
pub struct PowerAdjustCapability {
    pub power_adjust_capability: Option<Vec<PowerAdjust>>,
    pub cause: Option<PowerAdjustReason>,
}

#[derive(Debug, serde::Serialize)]
pub struct PowerAdjust {
    pub min_power: Option<u32>,
    pub max_power: Option<u32>,
    pub min_duration: Option<u32>,
    pub max_duration: Option<u32>,
}

#[derive(Debug, serde::Serialize)]
pub struct SlotAdjustment {
    pub slot_index: Option<u8>,
    pub nominal_power: Option<u32>,
    pub duration: Option<u32>,
}

#[derive(Debug, serde::Serialize)]
pub struct Slot {
    pub min_duration: Option<u32>,
    pub max_duration: Option<u32>,
    pub default_duration: Option<u32>,
    pub elapsed_slot_time: Option<u32>,
    pub remaining_slot_time: Option<u32>,
    pub slot_is_pausable: Option<bool>,
    pub min_pause_duration: Option<u32>,
    pub max_pause_duration: Option<u32>,
    pub manufacturer_esa_state: Option<u16>,
    pub nominal_power: Option<u32>,
    pub min_power: Option<u32>,
    pub max_power: Option<u32>,
    pub nominal_energy: Option<u64>,
    pub costs: Option<Vec<Cost>>,
    pub min_power_adjustment: Option<u32>,
    pub max_power_adjustment: Option<u32>,
    pub min_duration_adjustment: Option<u32>,
    pub max_duration_adjustment: Option<u32>,
}

// Command encoders

/// Encode PowerAdjustRequest command (0x00)
pub fn encode_power_adjust_request(power: u32, duration: u32, cause: AdjustmentCause) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt32(power)).into(),
        (1, tlv::TlvItemValueEnc::UInt32(duration)).into(),
        (2, tlv::TlvItemValueEnc::UInt8(cause.to_u8())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode StartTimeAdjustRequest command (0x02)
pub fn encode_start_time_adjust_request(requested_start_time: u64, cause: AdjustmentCause) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt64(requested_start_time)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(cause.to_u8())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode PauseRequest command (0x03)
pub fn encode_pause_request(duration: u32, cause: AdjustmentCause) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt32(duration)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(cause.to_u8())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode ModifyForecastRequest command (0x05)
pub fn encode_modify_forecast_request(forecast_id: u32, slot_adjustments: Vec<SlotAdjustment>, cause: AdjustmentCause) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt32(forecast_id)).into(),
        (1, tlv::TlvItemValueEnc::Array(slot_adjustments.into_iter().map(|v| {
                    let mut fields = Vec::new();
                    if let Some(x) = v.slot_index { fields.push((0, tlv::TlvItemValueEnc::UInt8(x)).into()); }
                    if let Some(x) = v.nominal_power { fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
                    if let Some(x) = v.duration { fields.push((2, tlv::TlvItemValueEnc::UInt32(x)).into()); }
                    (0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
                }).collect())).into(),
        (2, tlv::TlvItemValueEnc::UInt8(cause.to_u8())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RequestConstraintBasedForecast command (0x06)
pub fn encode_request_constraint_based_forecast(constraints: Vec<Constraints>, cause: AdjustmentCause) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::Array(constraints.into_iter().map(|v| {
                    let mut fields = Vec::new();
                    if let Some(x) = v.start_time { fields.push((0, tlv::TlvItemValueEnc::UInt64(x)).into()); }
                    if let Some(x) = v.duration { fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
                    if let Some(x) = v.nominal_power { fields.push((2, tlv::TlvItemValueEnc::UInt32(x)).into()); }
                    if let Some(x) = v.maximum_energy { fields.push((3, tlv::TlvItemValueEnc::UInt64(x)).into()); }
                    if let Some(x) = v.load_control { fields.push((4, tlv::TlvItemValueEnc::Int8(x)).into()); }
                    (0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
                }).collect())).into(),
        (1, tlv::TlvItemValueEnc::UInt8(cause.to_u8())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode ESAType attribute (0x0000)
pub fn decode_esa_type(inp: &tlv::TlvItemValue) -> anyhow::Result<ESAType> {
    if let tlv::TlvItemValue::Int(v) = inp {
        ESAType::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

/// Decode ESACanGenerate attribute (0x0001)
pub fn decode_esa_can_generate(inp: &tlv::TlvItemValue) -> anyhow::Result<bool> {
    if let tlv::TlvItemValue::Bool(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected Bool"))
    }
}

/// Decode ESAState attribute (0x0002)
pub fn decode_esa_state(inp: &tlv::TlvItemValue) -> anyhow::Result<ESAState> {
    if let tlv::TlvItemValue::Int(v) = inp {
        ESAState::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

/// Decode AbsMinPower attribute (0x0003)
pub fn decode_abs_min_power(inp: &tlv::TlvItemValue) -> anyhow::Result<u32> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u32)
    } else {
        Err(anyhow::anyhow!("Expected UInt32"))
    }
}

/// Decode AbsMaxPower attribute (0x0004)
pub fn decode_abs_max_power(inp: &tlv::TlvItemValue) -> anyhow::Result<u32> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u32)
    } else {
        Err(anyhow::anyhow!("Expected UInt32"))
    }
}

/// Decode PowerAdjustmentCapability attribute (0x0005)
pub fn decode_power_adjustment_capability(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<PowerAdjustCapability>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(PowerAdjustCapability {
                power_adjust_capability: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(PowerAdjust {
                min_power: list_item.get_int(&[0]).map(|v| v as u32),
                max_power: list_item.get_int(&[1]).map(|v| v as u32),
                min_duration: list_item.get_int(&[2]).map(|v| v as u32),
                max_duration: list_item.get_int(&[3]).map(|v| v as u32),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
                cause: item.get_int(&[1]).and_then(|v| PowerAdjustReason::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 Forecast attribute (0x0006)
pub fn decode_forecast(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<Forecast>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(Forecast {
                forecast_id: item.get_int(&[0]).map(|v| v as u32),
                active_slot_number: item.get_int(&[1]).map(|v| v as u16),
                start_time: item.get_int(&[2]),
                end_time: item.get_int(&[3]),
                earliest_start_time: item.get_int(&[4]),
                latest_end_time: item.get_int(&[5]),
                is_pausable: item.get_bool(&[6]),
                slots: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[7]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(Slot {
                min_duration: list_item.get_int(&[0]).map(|v| v as u32),
                max_duration: list_item.get_int(&[1]).map(|v| v as u32),
                default_duration: list_item.get_int(&[2]).map(|v| v as u32),
                elapsed_slot_time: list_item.get_int(&[3]).map(|v| v as u32),
                remaining_slot_time: list_item.get_int(&[4]).map(|v| v as u32),
                slot_is_pausable: list_item.get_bool(&[5]),
                min_pause_duration: list_item.get_int(&[6]).map(|v| v as u32),
                max_pause_duration: list_item.get_int(&[7]).map(|v| v as u32),
                manufacturer_esa_state: list_item.get_int(&[8]).map(|v| v as u16),
                nominal_power: list_item.get_int(&[9]).map(|v| v as u32),
                min_power: list_item.get_int(&[10]).map(|v| v as u32),
                max_power: list_item.get_int(&[11]).map(|v| v as u32),
                nominal_energy: list_item.get_int(&[12]),
                costs: {
                    if let Some(tlv::TlvItemValue::List(l)) = list_item.get(&[13]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(Cost {
                cost_type: list_item.get_int(&[0]).and_then(|v| CostType::from_u8(v as u8)),
                value: list_item.get_int(&[1]).map(|v| v as i32),
                decimal_points: list_item.get_int(&[2]).map(|v| v as u8),
                currency: list_item.get_int(&[3]).map(|v| v as u16),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
                min_power_adjustment: list_item.get_int(&[14]).map(|v| v as u32),
                max_power_adjustment: list_item.get_int(&[15]).map(|v| v as u32),
                min_duration_adjustment: list_item.get_int(&[16]).map(|v| v as u32),
                max_duration_adjustment: list_item.get_int(&[17]).map(|v| v as u32),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
                forecast_update_reason: item.get_int(&[8]).and_then(|v| ForecastUpdateReason::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 OptOutState attribute (0x0007)
pub fn decode_opt_out_state(inp: &tlv::TlvItemValue) -> anyhow::Result<OptOutState> {
    if let tlv::TlvItemValue::Int(v) = inp {
        OptOutState::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}


// 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 != 0x0098 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0098, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_esa_type(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_esa_can_generate(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_esa_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_abs_min_power(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_abs_max_power(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_power_adjustment_capability(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_forecast(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_opt_out_state(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, "ESAType"),
        (0x0001, "ESACanGenerate"),
        (0x0002, "ESAState"),
        (0x0003, "AbsMinPower"),
        (0x0004, "AbsMaxPower"),
        (0x0005, "PowerAdjustmentCapability"),
        (0x0006, "Forecast"),
        (0x0007, "OptOutState"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "PowerAdjustRequest"),
        (0x01, "CancelPowerAdjustRequest"),
        (0x02, "StartTimeAdjustRequest"),
        (0x03, "PauseRequest"),
        (0x04, "ResumeRequest"),
        (0x05, "ModifyForecastRequest"),
        (0x06, "RequestConstraintBasedForecast"),
        (0x07, "CancelRequest"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("PowerAdjustRequest"),
        0x01 => Some("CancelPowerAdjustRequest"),
        0x02 => Some("StartTimeAdjustRequest"),
        0x03 => Some("PauseRequest"),
        0x04 => Some("ResumeRequest"),
        0x05 => Some("ModifyForecastRequest"),
        0x06 => Some("RequestConstraintBasedForecast"),
        0x07 => Some("CancelRequest"),
        _ => 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: "power", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "duration", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "cause", kind: crate::clusters::codec::FieldKind::Enum { name: "AdjustmentCause", variants: &[(0, "Localoptimization"), (1, "Gridoptimization")] }, optional: false, nullable: false },
        ]),
        0x01 => Some(vec![]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "requested_start_time", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "cause", kind: crate::clusters::codec::FieldKind::Enum { name: "AdjustmentCause", variants: &[(0, "Localoptimization"), (1, "Gridoptimization")] }, optional: false, nullable: false },
        ]),
        0x03 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "duration", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "cause", kind: crate::clusters::codec::FieldKind::Enum { name: "AdjustmentCause", variants: &[(0, "Localoptimization"), (1, "Gridoptimization")] }, optional: false, nullable: false },
        ]),
        0x04 => Some(vec![]),
        0x05 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "forecast_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "slot_adjustments", kind: crate::clusters::codec::FieldKind::List { entry_type: "SlotAdjustmentStruct" }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "cause", kind: crate::clusters::codec::FieldKind::Enum { name: "AdjustmentCause", variants: &[(0, "Localoptimization"), (1, "Gridoptimization")] }, optional: false, nullable: false },
        ]),
        0x06 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "constraints", kind: crate::clusters::codec::FieldKind::List { entry_type: "ConstraintsStruct" }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "cause", kind: crate::clusters::codec::FieldKind::Enum { name: "AdjustmentCause", variants: &[(0, "Localoptimization"), (1, "Gridoptimization")] }, optional: false, nullable: false },
        ]),
        0x07 => Some(vec![]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => {
        let power = crate::clusters::codec::json_util::get_u32(args, "power")?;
        let duration = crate::clusters::codec::json_util::get_u32(args, "duration")?;
        let cause = {
            let n = crate::clusters::codec::json_util::get_u64(args, "cause")?;
            AdjustmentCause::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid AdjustmentCause: {}", n))?
        };
        encode_power_adjust_request(power, duration, cause)
        }
        0x01 => Ok(vec![]),
        0x02 => {
        let requested_start_time = crate::clusters::codec::json_util::get_u64(args, "requested_start_time")?;
        let cause = {
            let n = crate::clusters::codec::json_util::get_u64(args, "cause")?;
            AdjustmentCause::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid AdjustmentCause: {}", n))?
        };
        encode_start_time_adjust_request(requested_start_time, cause)
        }
        0x03 => {
        let duration = crate::clusters::codec::json_util::get_u32(args, "duration")?;
        let cause = {
            let n = crate::clusters::codec::json_util::get_u64(args, "cause")?;
            AdjustmentCause::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid AdjustmentCause: {}", n))?
        };
        encode_pause_request(duration, cause)
        }
        0x04 => Ok(vec![]),
        0x05 => Err(anyhow::anyhow!("command \"ModifyForecastRequest\" has complex args: use raw mode")),
        0x06 => Err(anyhow::anyhow!("command \"RequestConstraintBasedForecast\" has complex args: use raw mode")),
        0x07 => Ok(vec![]),
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `PowerAdjustRequest` command on cluster `Device Energy Management`.
pub async fn power_adjust_request(conn: &crate::controller::Connection, endpoint: u16, power: u32, duration: u32, cause: AdjustmentCause) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_CMD_ID_POWERADJUSTREQUEST, &encode_power_adjust_request(power, duration, cause)?).await?;
    Ok(())
}

/// Invoke `CancelPowerAdjustRequest` command on cluster `Device Energy Management`.
pub async fn cancel_power_adjust_request(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_CMD_ID_CANCELPOWERADJUSTREQUEST, &[]).await?;
    Ok(())
}

/// Invoke `StartTimeAdjustRequest` command on cluster `Device Energy Management`.
pub async fn start_time_adjust_request(conn: &crate::controller::Connection, endpoint: u16, requested_start_time: u64, cause: AdjustmentCause) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_CMD_ID_STARTTIMEADJUSTREQUEST, &encode_start_time_adjust_request(requested_start_time, cause)?).await?;
    Ok(())
}

/// Invoke `PauseRequest` command on cluster `Device Energy Management`.
pub async fn pause_request(conn: &crate::controller::Connection, endpoint: u16, duration: u32, cause: AdjustmentCause) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_CMD_ID_PAUSEREQUEST, &encode_pause_request(duration, cause)?).await?;
    Ok(())
}

/// Invoke `ResumeRequest` command on cluster `Device Energy Management`.
pub async fn resume_request(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_CMD_ID_RESUMEREQUEST, &[]).await?;
    Ok(())
}

/// Invoke `ModifyForecastRequest` command on cluster `Device Energy Management`.
pub async fn modify_forecast_request(conn: &crate::controller::Connection, endpoint: u16, forecast_id: u32, slot_adjustments: Vec<SlotAdjustment>, cause: AdjustmentCause) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_CMD_ID_MODIFYFORECASTREQUEST, &encode_modify_forecast_request(forecast_id, slot_adjustments, cause)?).await?;
    Ok(())
}

/// Invoke `RequestConstraintBasedForecast` command on cluster `Device Energy Management`.
pub async fn request_constraint_based_forecast(conn: &crate::controller::Connection, endpoint: u16, constraints: Vec<Constraints>, cause: AdjustmentCause) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_CMD_ID_REQUESTCONSTRAINTBASEDFORECAST, &encode_request_constraint_based_forecast(constraints, cause)?).await?;
    Ok(())
}

/// Invoke `CancelRequest` command on cluster `Device Energy Management`.
pub async fn cancel_request(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_CMD_ID_CANCELREQUEST, &[]).await?;
    Ok(())
}

/// Read `ESAType` attribute from cluster `Device Energy Management`.
pub async fn read_esa_type(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<ESAType> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_ATTR_ID_ESATYPE).await?;
    decode_esa_type(&tlv)
}

/// Read `ESACanGenerate` attribute from cluster `Device Energy Management`.
pub async fn read_esa_can_generate(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_ATTR_ID_ESACANGENERATE).await?;
    decode_esa_can_generate(&tlv)
}

/// Read `ESAState` attribute from cluster `Device Energy Management`.
pub async fn read_esa_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<ESAState> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_ATTR_ID_ESASTATE).await?;
    decode_esa_state(&tlv)
}

/// Read `AbsMinPower` attribute from cluster `Device Energy Management`.
pub async fn read_abs_min_power(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_ATTR_ID_ABSMINPOWER).await?;
    decode_abs_min_power(&tlv)
}

/// Read `AbsMaxPower` attribute from cluster `Device Energy Management`.
pub async fn read_abs_max_power(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_ATTR_ID_ABSMAXPOWER).await?;
    decode_abs_max_power(&tlv)
}

/// Read `PowerAdjustmentCapability` attribute from cluster `Device Energy Management`.
pub async fn read_power_adjustment_capability(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<PowerAdjustCapability>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_ATTR_ID_POWERADJUSTMENTCAPABILITY).await?;
    decode_power_adjustment_capability(&tlv)
}

/// Read `Forecast` attribute from cluster `Device Energy Management`.
pub async fn read_forecast(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<Forecast>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_ATTR_ID_FORECAST).await?;
    decode_forecast(&tlv)
}

/// Read `OptOutState` attribute from cluster `Device Energy Management`.
pub async fn read_opt_out_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<OptOutState> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_DEVICE_ENERGY_MANAGEMENT, crate::clusters::defs::CLUSTER_DEVICE_ENERGY_MANAGEMENT_ATTR_ID_OPTOUTSTATE).await?;
    decode_opt_out_state(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct PowerAdjustEndEvent {
    pub cause: Option<Cause>,
    pub duration: Option<u32>,
    pub energy_use: Option<u64>,
}

#[derive(Debug, serde::Serialize)]
pub struct ResumedEvent {
    pub cause: Option<Cause>,
}

// Event decoders

/// Decode PowerAdjustEnd event (0x01, priority: info)
pub fn decode_power_adjust_end_event(inp: &tlv::TlvItemValue) -> anyhow::Result<PowerAdjustEndEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(PowerAdjustEndEvent {
                                cause: item.get_int(&[0]).and_then(|v| Cause::from_u8(v as u8)),
                                duration: item.get_int(&[1]).map(|v| v as u32),
                                energy_use: item.get_int(&[2]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode Resumed event (0x03, priority: info)
pub fn decode_resumed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<ResumedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ResumedEvent {
                                cause: item.get_int(&[0]).and_then(|v| Cause::from_u8(v as u8)),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}