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
//! Matter TLV encoders and decoders for Closure Dimension Cluster
//! Cluster ID: 0x0105
//!
//! This file is automatically generated from ClosureDimension.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 ClosureUnit {
    /// Millimeter used as unit
    Millimeter = 0,
    /// Degree used as unit
    Degree = 1,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ModulationType {
    /// Orientation of the slats
    Slatsorientation = 0,
    /// Aperture of the slats
    Slatsopenwork = 1,
    /// Alignment of blind stripes (Zebra)
    Stripesalignment = 2,
    /// Opacity of a surface
    Opacity = 3,
    /// Ventilation control
    Ventilation = 4,
}

impl ModulationType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ModulationType::Slatsorientation),
            1 => Some(ModulationType::Slatsopenwork),
            2 => Some(ModulationType::Stripesalignment),
            3 => Some(ModulationType::Opacity),
            4 => Some(ModulationType::Ventilation),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum Overflow {
    /// No overflow
    Nooverflow = 0,
    /// Inside overflow
    Inside = 1,
    /// Outside overflow
    Outside = 2,
    /// Top inside overflow
    Topinside = 3,
    /// Top outside overflow
    Topoutside = 4,
    /// Bottom inside overflow
    Bottominside = 5,
    /// Bottom outside overflow
    Bottomoutside = 6,
    /// Left inside overflow
    Leftinside = 7,
    /// Left outside overflow
    Leftoutside = 8,
    /// Right inside overflow
    Rightinside = 9,
    /// Right outside overflow
    Rightoutside = 10,
}

impl Overflow {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Overflow::Nooverflow),
            1 => Some(Overflow::Inside),
            2 => Some(Overflow::Outside),
            3 => Some(Overflow::Topinside),
            4 => Some(Overflow::Topoutside),
            5 => Some(Overflow::Bottominside),
            6 => Some(Overflow::Bottomoutside),
            7 => Some(Overflow::Leftinside),
            8 => Some(Overflow::Leftoutside),
            9 => Some(Overflow::Rightinside),
            10 => Some(Overflow::Rightoutside),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum RotationAxis {
    /// The panel rotates around a vertical axis located on the left side of the panel
    Left = 0,
    /// The panel rotates around a vertical axis located in the center of the panel
    Centeredvertical = 1,
    /// The panels rotates around vertical axes located on the left and right sides of the panel
    Leftandright = 2,
    /// The panel rotates around a vertical axis located on the right side of the panel
    Right = 3,
    /// The panel rotates around a horizontal axis located on the top of the panel
    Top = 4,
    /// The panel rotates around a horizontal axis located in the center of the panel
    Centeredhorizontal = 5,
    /// The panels rotates around horizontal axes located on the top and bottom of the panel
    Topandbottom = 6,
    /// The panel rotates around a horizontal axis located on the bottom of the panel
    Bottom = 7,
    /// The barrier tilts around an axis located at the left end of the barrier
    Leftbarrier = 8,
    /// The dual barriers tilt around axes located at each side of the composite barrier
    Leftandrightbarriers = 9,
    /// The barrier tilts around an axis located at the right end of the barrier
    Rightbarrier = 10,
}

impl RotationAxis {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(RotationAxis::Left),
            1 => Some(RotationAxis::Centeredvertical),
            2 => Some(RotationAxis::Leftandright),
            3 => Some(RotationAxis::Right),
            4 => Some(RotationAxis::Top),
            5 => Some(RotationAxis::Centeredhorizontal),
            6 => Some(RotationAxis::Topandbottom),
            7 => Some(RotationAxis::Bottom),
            8 => Some(RotationAxis::Leftbarrier),
            9 => Some(RotationAxis::Leftandrightbarriers),
            10 => Some(RotationAxis::Rightbarrier),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StepDirection {
    /// Decrease towards 0.00%
    Decrease = 0,
    /// Increase towards 100.00%
    Increase = 1,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum TranslationDirection {
    /// Downward translation
    Downward = 0,
    /// Upward translation
    Upward = 1,
    /// Vertical mask translation
    Verticalmask = 2,
    /// Vertical symmetry translation
    Verticalsymmetry = 3,
    /// Leftward translation
    Leftward = 4,
    /// Rightward translation
    Rightward = 5,
    /// Horizontal mask translation
    Horizontalmask = 6,
    /// Horizontal symmetry translation
    Horizontalsymmetry = 7,
    /// Forward translation
    Forward = 8,
    /// Backward translation
    Backward = 9,
    /// Depth mask translation
    Depthmask = 10,
    /// Depth symmetry translation
    Depthsymmetry = 11,
}

impl TranslationDirection {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(TranslationDirection::Downward),
            1 => Some(TranslationDirection::Upward),
            2 => Some(TranslationDirection::Verticalmask),
            3 => Some(TranslationDirection::Verticalsymmetry),
            4 => Some(TranslationDirection::Leftward),
            5 => Some(TranslationDirection::Rightward),
            6 => Some(TranslationDirection::Horizontalmask),
            7 => Some(TranslationDirection::Horizontalsymmetry),
            8 => Some(TranslationDirection::Forward),
            9 => Some(TranslationDirection::Backward),
            10 => Some(TranslationDirection::Depthmask),
            11 => Some(TranslationDirection::Depthsymmetry),
            _ => None,
        }
    }

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

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

// Bitmap definitions

/// LatchControlModes bitmap type
pub type LatchControlModes = u8;

/// Constants for LatchControlModes
pub mod latchcontrolmodes {
    /// Remote latching capability
    pub const REMOTE_LATCHING: u8 = 0x01;
    /// Remote unlatching capability
    pub const REMOTE_UNLATCHING: u8 = 0x02;
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct DimensionState {
    pub position: Option<u16>,
    pub latch: Option<bool>,
    pub speed: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct RangePercent {
    pub min: Option<u16>,
    pub max: Option<u16>,
}

#[derive(Debug, serde::Serialize)]
pub struct UnitRange {
    pub min: Option<i16>,
    pub max: Option<i16>,
}

// Command encoders

/// Encode SetTarget command (0x00)
pub fn encode_set_target(position: Option<u16>, latch: Option<bool>, speed: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    if let Some(x) = position { tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
    if let Some(x) = latch { tlv_fields.push((1, tlv::TlvItemValueEnc::Bool(x)).into()); }
    if let Some(x) = speed { tlv_fields.push((2, tlv::TlvItemValueEnc::UInt8(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode Step command (0x01)
pub fn encode_step(direction: StepDirection, number_of_steps: u16, speed: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt8(direction.to_u8())).into());
    tlv_fields.push((1, tlv::TlvItemValueEnc::UInt16(number_of_steps)).into());
    if let Some(x) = speed { tlv_fields.push((2, tlv::TlvItemValueEnc::UInt8(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode CurrentState attribute (0x0000)
pub fn decode_current_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<DimensionState>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(DimensionState {
                position: item.get_int(&[0]).map(|v| v as u16),
                latch: item.get_bool(&[1]),
                speed: item.get_int(&[2]).map(|v| 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 TargetState attribute (0x0001)
pub fn decode_target_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<DimensionState>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(DimensionState {
                position: item.get_int(&[0]).map(|v| v as u16),
                latch: item.get_bool(&[1]),
                speed: item.get_int(&[2]).map(|v| 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 Resolution attribute (0x0002)
pub fn decode_resolution(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u16)
    } else {
        Err(anyhow::anyhow!("Expected UInt16"))
    }
}

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

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

/// Decode UnitRange attribute (0x0005)
pub fn decode_unit_range(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<UnitRange>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(UnitRange {
                min: item.get_int(&[0]).map(|v| v as i16),
                max: item.get_int(&[1]).map(|v| v as i16),
        }))
    //} 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 LimitRange attribute (0x0006)
pub fn decode_limit_range(inp: &tlv::TlvItemValue) -> anyhow::Result<RangePercent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(RangePercent {
                min: item.get_int(&[0]).map(|v| v as u16),
                max: item.get_int(&[1]).map(|v| v as u16),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

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

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

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

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

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

    match attribute_id {
        0x0000 => {
            match decode_current_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_target_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_resolution(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_step_value(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_unit(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_unit_range(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_limit_range(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_translation_direction(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_rotation_axis(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_overflow(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000A => {
            match decode_modulation_type(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000B => {
            match decode_latch_control_modes(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, "CurrentState"),
        (0x0001, "TargetState"),
        (0x0002, "Resolution"),
        (0x0003, "StepValue"),
        (0x0004, "Unit"),
        (0x0005, "UnitRange"),
        (0x0006, "LimitRange"),
        (0x0007, "TranslationDirection"),
        (0x0008, "RotationAxis"),
        (0x0009, "Overflow"),
        (0x000A, "ModulationType"),
        (0x000B, "LatchControlModes"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("SetTarget"),
        0x01 => Some("Step"),
        _ => 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: "position", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "latch", kind: crate::clusters::codec::FieldKind::Bool, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "speed", kind: crate::clusters::codec::FieldKind::U8, optional: true, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "direction", kind: crate::clusters::codec::FieldKind::Enum { name: "StepDirection", variants: &[(0, "Decrease"), (1, "Increase")] }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "number_of_steps", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "speed", kind: crate::clusters::codec::FieldKind::U8, optional: true, nullable: false },
        ]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => {
        let position = crate::clusters::codec::json_util::get_opt_u16(args, "position")?;
        let latch = crate::clusters::codec::json_util::get_opt_bool(args, "latch")?;
        let speed = crate::clusters::codec::json_util::get_opt_u8(args, "speed")?;
        encode_set_target(position, latch, speed)
        }
        0x01 => {
        let direction = {
            let n = crate::clusters::codec::json_util::get_u64(args, "direction")?;
            StepDirection::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid StepDirection: {}", n))?
        };
        let number_of_steps = crate::clusters::codec::json_util::get_u16(args, "number_of_steps")?;
        let speed = crate::clusters::codec::json_util::get_opt_u8(args, "speed")?;
        encode_step(direction, number_of_steps, speed)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `SetTarget` command on cluster `Closure Dimension`.
pub async fn set_target(conn: &crate::controller::Connection, endpoint: u16, position: Option<u16>, latch: Option<bool>, speed: Option<u8>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_CMD_ID_SETTARGET, &encode_set_target(position, latch, speed)?).await?;
    Ok(())
}

/// Invoke `Step` command on cluster `Closure Dimension`.
pub async fn step(conn: &crate::controller::Connection, endpoint: u16, direction: StepDirection, number_of_steps: u16, speed: Option<u8>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_CMD_ID_STEP, &encode_step(direction, number_of_steps, speed)?).await?;
    Ok(())
}

/// Read `CurrentState` attribute from cluster `Closure Dimension`.
pub async fn read_current_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<DimensionState>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_CURRENTSTATE).await?;
    decode_current_state(&tlv)
}

/// Read `TargetState` attribute from cluster `Closure Dimension`.
pub async fn read_target_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<DimensionState>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_TARGETSTATE).await?;
    decode_target_state(&tlv)
}

/// Read `Resolution` attribute from cluster `Closure Dimension`.
pub async fn read_resolution(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_RESOLUTION).await?;
    decode_resolution(&tlv)
}

/// Read `StepValue` attribute from cluster `Closure Dimension`.
pub async fn read_step_value(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_STEPVALUE).await?;
    decode_step_value(&tlv)
}

/// Read `Unit` attribute from cluster `Closure Dimension`.
pub async fn read_unit(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<ClosureUnit> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_UNIT).await?;
    decode_unit(&tlv)
}

/// Read `UnitRange` attribute from cluster `Closure Dimension`.
pub async fn read_unit_range(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<UnitRange>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_UNITRANGE).await?;
    decode_unit_range(&tlv)
}

/// Read `LimitRange` attribute from cluster `Closure Dimension`.
pub async fn read_limit_range(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<RangePercent> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_LIMITRANGE).await?;
    decode_limit_range(&tlv)
}

/// Read `TranslationDirection` attribute from cluster `Closure Dimension`.
pub async fn read_translation_direction(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<TranslationDirection> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_TRANSLATIONDIRECTION).await?;
    decode_translation_direction(&tlv)
}

/// Read `RotationAxis` attribute from cluster `Closure Dimension`.
pub async fn read_rotation_axis(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<RotationAxis> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_ROTATIONAXIS).await?;
    decode_rotation_axis(&tlv)
}

/// Read `Overflow` attribute from cluster `Closure Dimension`.
pub async fn read_overflow(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Overflow> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_OVERFLOW).await?;
    decode_overflow(&tlv)
}

/// Read `ModulationType` attribute from cluster `Closure Dimension`.
pub async fn read_modulation_type(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<ModulationType> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_MODULATIONTYPE).await?;
    decode_modulation_type(&tlv)
}

/// Read `LatchControlModes` attribute from cluster `Closure Dimension`.
pub async fn read_latch_control_modes(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<LatchControlModes> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_DIMENSION, crate::clusters::defs::CLUSTER_CLOSURE_DIMENSION_ATTR_ID_LATCHCONTROLMODES).await?;
    decode_latch_control_modes(&tlv)
}