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
//! Matter TLV encoders and decoders for Electrical Power Measurement Cluster
//! Cluster ID: 0x0090
//!
//! This file is automatically generated from ElectricalPowerMeasurement.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 MeasurementType {
    Unspecified = 0,
    /// Voltage in millivolts (mV)
    Voltage = 1,
    /// Active current in milliamps (mA)
    Activecurrent = 2,
    /// Reactive current in milliamps (mA)
    Reactivecurrent = 3,
    /// Apparent current in milliamps (mA)
    Apparentcurrent = 4,
    /// Active power in milliwatts (mW)
    Activepower = 5,
    /// Reactive power in millivolt-amps reactive (mVAR)
    Reactivepower = 6,
    /// Apparent power in millivolt-amps (mVA)
    Apparentpower = 7,
    /// Root mean squared voltage in millivolts (mV)
    Rmsvoltage = 8,
    /// Root mean squared current in milliamps (mA)
    Rmscurrent = 9,
    /// Root mean squared power in milliwatts (mW)
    Rmspower = 10,
    /// AC frequency in millihertz (mHz)
    Frequency = 11,
    /// Power Factor ratio in +/- 1/100ths of a percent.
    Powerfactor = 12,
    /// AC neutral current in milliamps (mA)
    Neutralcurrent = 13,
    /// Electrical energy in milliwatt-hours (mWh)
    Electricalenergy = 14,
    /// Reactive power in millivolt-amp-hours reactive (mVARh)
    Reactiveenergy = 15,
    /// Apparent power in millivolt-amp-hours (mVAh)
    Apparentenergy = 16,
}

impl MeasurementType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(MeasurementType::Unspecified),
            1 => Some(MeasurementType::Voltage),
            2 => Some(MeasurementType::Activecurrent),
            3 => Some(MeasurementType::Reactivecurrent),
            4 => Some(MeasurementType::Apparentcurrent),
            5 => Some(MeasurementType::Activepower),
            6 => Some(MeasurementType::Reactivepower),
            7 => Some(MeasurementType::Apparentpower),
            8 => Some(MeasurementType::Rmsvoltage),
            9 => Some(MeasurementType::Rmscurrent),
            10 => Some(MeasurementType::Rmspower),
            11 => Some(MeasurementType::Frequency),
            12 => Some(MeasurementType::Powerfactor),
            13 => Some(MeasurementType::Neutralcurrent),
            14 => Some(MeasurementType::Electricalenergy),
            15 => Some(MeasurementType::Reactiveenergy),
            16 => Some(MeasurementType::Apparentenergy),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum PowerMode {
    Unknown = 0,
    /// Direct current
    Dc = 1,
    /// Alternating current, either single-phase or polyphase
    Ac = 2,
}

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

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct HarmonicMeasurement {
    pub order: Option<u8>,
    pub measurement: Option<i64>,
}

#[derive(Debug, serde::Serialize)]
pub struct MeasurementAccuracyRange {
    pub range_min: Option<i64>,
    pub range_max: Option<i64>,
    pub percent_max: Option<u16>,
    pub percent_min: Option<u16>,
    pub percent_typical: Option<u16>,
    pub fixed_max: Option<u64>,
    pub fixed_min: Option<u64>,
    pub fixed_typical: Option<u64>,
}

#[derive(Debug, serde::Serialize)]
pub struct MeasurementAccuracy {
    pub measurement_type: Option<MeasurementType>,
    pub measured: Option<bool>,
    pub min_measured_value: Option<i64>,
    pub max_measured_value: Option<i64>,
    pub accuracy_ranges: Option<Vec<MeasurementAccuracyRange>>,
}

#[derive(Debug, serde::Serialize)]
pub struct MeasurementRange {
    pub measurement_type: Option<MeasurementType>,
    pub min: Option<i64>,
    pub max: Option<i64>,
    pub start_timestamp: Option<u64>,
    pub end_timestamp: Option<u64>,
    pub min_timestamp: Option<u64>,
    pub max_timestamp: Option<u64>,
    pub start_systime: Option<u8>,
    pub end_systime: Option<u8>,
    pub min_systime: Option<u8>,
    pub max_systime: Option<u8>,
}

// Attribute decoders

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

/// Decode NumberOfMeasurementTypes attribute (0x0001)
pub fn decode_number_of_measurement_types(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected UInt8"))
    }
}

/// Decode Accuracy attribute (0x0002)
pub fn decode_accuracy(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<MeasurementAccuracy>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(MeasurementAccuracy {
                measurement_type: item.get_int(&[0]).and_then(|v| MeasurementType::from_u8(v as u8)),
                measured: item.get_bool(&[1]),
                min_measured_value: item.get_int(&[2]).map(|v| v as i64),
                max_measured_value: item.get_int(&[3]).map(|v| v as i64),
                accuracy_ranges: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[4]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(MeasurementAccuracyRange {
                range_min: list_item.get_int(&[0]).map(|v| v as i64),
                range_max: list_item.get_int(&[1]).map(|v| v as i64),
                percent_max: list_item.get_int(&[2]).map(|v| v as u16),
                percent_min: list_item.get_int(&[3]).map(|v| v as u16),
                percent_typical: list_item.get_int(&[4]).map(|v| v as u16),
                fixed_max: list_item.get_int(&[5]),
                fixed_min: list_item.get_int(&[6]),
                fixed_typical: list_item.get_int(&[7]),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

/// Decode Ranges attribute (0x0003)
pub fn decode_ranges(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<MeasurementRange>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(MeasurementRange {
                measurement_type: item.get_int(&[0]).and_then(|v| MeasurementType::from_u8(v as u8)),
                min: item.get_int(&[1]).map(|v| v as i64),
                max: item.get_int(&[2]).map(|v| v as i64),
                start_timestamp: item.get_int(&[3]),
                end_timestamp: item.get_int(&[4]),
                min_timestamp: item.get_int(&[5]),
                max_timestamp: item.get_int(&[6]),
                start_systime: item.get_int(&[7]).map(|v| v as u8),
                end_systime: item.get_int(&[8]).map(|v| v as u8),
                min_systime: item.get_int(&[9]).map(|v| v as u8),
                max_systime: item.get_int(&[10]).map(|v| v as u8),
            });
        }
    }
    Ok(res)
}

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

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

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

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

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

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

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

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

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

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

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

/// Decode HarmonicCurrents attribute (0x000F)
pub fn decode_harmonic_currents(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<HarmonicMeasurement>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(HarmonicMeasurement {
                order: item.get_int(&[0]).map(|v| v as u8),
                measurement: item.get_int(&[1]).map(|v| v as i64),
            });
        }
    }
    Ok(res)
}

/// Decode HarmonicPhases attribute (0x0010)
pub fn decode_harmonic_phases(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<HarmonicMeasurement>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(HarmonicMeasurement {
                order: item.get_int(&[0]).map(|v| v as u8),
                measurement: item.get_int(&[1]).map(|v| v as i64),
            });
        }
    }
    Ok(res)
}

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

/// Decode NeutralCurrent attribute (0x0012)
pub fn decode_neutral_current(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*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 != 0x0090 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0090, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_power_mode(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_number_of_measurement_types(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_accuracy(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_ranges(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_voltage(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_active_current(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_reactive_current(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_apparent_current(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_active_power(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_reactive_power(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000A => {
            match decode_apparent_power(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000B => {
            match decode_rms_voltage(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000C => {
            match decode_rms_current(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000D => {
            match decode_rms_power(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000E => {
            match decode_frequency(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000F => {
            match decode_harmonic_currents(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0010 => {
            match decode_harmonic_phases(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0011 => {
            match decode_power_factor(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0012 => {
            match decode_neutral_current(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, "PowerMode"),
        (0x0001, "NumberOfMeasurementTypes"),
        (0x0002, "Accuracy"),
        (0x0003, "Ranges"),
        (0x0004, "Voltage"),
        (0x0005, "ActiveCurrent"),
        (0x0006, "ReactiveCurrent"),
        (0x0007, "ApparentCurrent"),
        (0x0008, "ActivePower"),
        (0x0009, "ReactivePower"),
        (0x000A, "ApparentPower"),
        (0x000B, "RMSVoltage"),
        (0x000C, "RMSCurrent"),
        (0x000D, "RMSPower"),
        (0x000E, "Frequency"),
        (0x000F, "HarmonicCurrents"),
        (0x0010, "HarmonicPhases"),
        (0x0011, "PowerFactor"),
        (0x0012, "NeutralCurrent"),
    ]
}

// Typed facade (invokes + reads)

/// Read `PowerMode` attribute from cluster `Electrical Power Measurement`.
pub async fn read_power_mode(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<PowerMode> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_POWERMODE).await?;
    decode_power_mode(&tlv)
}

/// Read `NumberOfMeasurementTypes` attribute from cluster `Electrical Power Measurement`.
pub async fn read_number_of_measurement_types(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_NUMBEROFMEASUREMENTTYPES).await?;
    decode_number_of_measurement_types(&tlv)
}

/// Read `Accuracy` attribute from cluster `Electrical Power Measurement`.
pub async fn read_accuracy(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<MeasurementAccuracy>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_ACCURACY).await?;
    decode_accuracy(&tlv)
}

/// Read `Ranges` attribute from cluster `Electrical Power Measurement`.
pub async fn read_ranges(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<MeasurementRange>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_RANGES).await?;
    decode_ranges(&tlv)
}

/// Read `Voltage` attribute from cluster `Electrical Power Measurement`.
pub async fn read_voltage(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_VOLTAGE).await?;
    decode_voltage(&tlv)
}

/// Read `ActiveCurrent` attribute from cluster `Electrical Power Measurement`.
pub async fn read_active_current(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_ACTIVECURRENT).await?;
    decode_active_current(&tlv)
}

/// Read `ReactiveCurrent` attribute from cluster `Electrical Power Measurement`.
pub async fn read_reactive_current(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_REACTIVECURRENT).await?;
    decode_reactive_current(&tlv)
}

/// Read `ApparentCurrent` attribute from cluster `Electrical Power Measurement`.
pub async fn read_apparent_current(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_APPARENTCURRENT).await?;
    decode_apparent_current(&tlv)
}

/// Read `ActivePower` attribute from cluster `Electrical Power Measurement`.
pub async fn read_active_power(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_ACTIVEPOWER).await?;
    decode_active_power(&tlv)
}

/// Read `ReactivePower` attribute from cluster `Electrical Power Measurement`.
pub async fn read_reactive_power(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_REACTIVEPOWER).await?;
    decode_reactive_power(&tlv)
}

/// Read `ApparentPower` attribute from cluster `Electrical Power Measurement`.
pub async fn read_apparent_power(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_APPARENTPOWER).await?;
    decode_apparent_power(&tlv)
}

/// Read `RMSVoltage` attribute from cluster `Electrical Power Measurement`.
pub async fn read_rms_voltage(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_RMSVOLTAGE).await?;
    decode_rms_voltage(&tlv)
}

/// Read `RMSCurrent` attribute from cluster `Electrical Power Measurement`.
pub async fn read_rms_current(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_RMSCURRENT).await?;
    decode_rms_current(&tlv)
}

/// Read `RMSPower` attribute from cluster `Electrical Power Measurement`.
pub async fn read_rms_power(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_RMSPOWER).await?;
    decode_rms_power(&tlv)
}

/// Read `Frequency` attribute from cluster `Electrical Power Measurement`.
pub async fn read_frequency(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<i64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_FREQUENCY).await?;
    decode_frequency(&tlv)
}

/// Read `HarmonicCurrents` attribute from cluster `Electrical Power Measurement`.
pub async fn read_harmonic_currents(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<HarmonicMeasurement>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_HARMONICCURRENTS).await?;
    decode_harmonic_currents(&tlv)
}

/// Read `HarmonicPhases` attribute from cluster `Electrical Power Measurement`.
pub async fn read_harmonic_phases(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<HarmonicMeasurement>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_HARMONICPHASES).await?;
    decode_harmonic_phases(&tlv)
}

/// Read `PowerFactor` attribute from cluster `Electrical Power Measurement`.
pub async fn read_power_factor(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<i64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_POWERFACTOR).await?;
    decode_power_factor(&tlv)
}

/// Read `NeutralCurrent` attribute from cluster `Electrical Power Measurement`.
pub async fn read_neutral_current(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_POWER_MEASUREMENT, crate::clusters::defs::CLUSTER_ELECTRICAL_POWER_MEASUREMENT_ATTR_ID_NEUTRALCURRENT).await?;
    decode_neutral_current(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct MeasurementPeriodRangesEvent {
    pub ranges: Option<Vec<MeasurementRange>>,
}

// Event decoders

/// Decode MeasurementPeriodRanges event (0x00, priority: info)
pub fn decode_measurement_period_ranges_event(inp: &tlv::TlvItemValue) -> anyhow::Result<MeasurementPeriodRangesEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(MeasurementPeriodRangesEvent {
                                ranges: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(MeasurementRange {
                measurement_type: list_item.get_int(&[0]).and_then(|v| MeasurementType::from_u8(v as u8)),
                min: list_item.get_int(&[1]).map(|v| v as i64),
                max: list_item.get_int(&[2]).map(|v| v as i64),
                start_timestamp: list_item.get_int(&[3]),
                end_timestamp: list_item.get_int(&[4]),
                min_timestamp: list_item.get_int(&[5]),
                max_timestamp: list_item.get_int(&[6]),
                start_systime: list_item.get_int(&[7]).map(|v| v as u8),
                end_systime: list_item.get_int(&[8]).map(|v| v as u8),
                min_systime: list_item.get_int(&[9]).map(|v| v as u8),
                max_systime: list_item.get_int(&[10]).map(|v| v as u8),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}