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
//! Matter TLV encoders and decoders for Zone Management Cluster
//! Cluster ID: 0x0550
//!
//! This file is automatically generated from ZoneManagement.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 ZoneEventStoppedReason {
    /// Indicates that whatever triggered the Zone event has stopped being detected.
    Actionstopped = 0,
    /// Indicates that the max duration for detecting triggering activity has been reached.
    Timeout = 1,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ZoneEventTriggeredReason {
    /// Zone event triggered because motion is detected
    Motion = 0,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ZoneSource {
    /// Indicates a Manufacturer defined Zone.
    Mfg = 0,
    /// Indicates a User defined Zone.
    User = 1,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ZoneType {
    /// Indicates a Two Dimensional Cartesian Zone
    Twodcartzone = 0,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ZoneUse {
    /// Indicates Zone is intended to detect Motion
    Motion = 0,
    /// Indicates Zone is intended to protect privacy
    Privacy = 1,
    /// Indicates Zone provides a focus area
    Focus = 2,
}

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

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct TwoDCartesianVertex {
    pub x: Option<u16>,
    pub y: Option<u16>,
}

#[derive(Debug, serde::Serialize)]
pub struct TwoDCartesianZone {
    pub name: Option<String>,
    pub use_: Option<ZoneUse>,
    pub vertices: Option<Vec<TwoDCartesianVertex>>,
    pub color: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct ZoneInformation {
    pub zone_id: Option<u8>,
    pub zone_type: Option<ZoneType>,
    pub zone_source: Option<ZoneSource>,
    pub two_d_cartesian_zone: Option<TwoDCartesianZone>,
}

#[derive(Debug, serde::Serialize)]
pub struct ZoneTriggerControl {
    pub zone_id: Option<u8>,
    pub initial_duration: Option<u32>,
    pub augmentation_duration: Option<u32>,
    pub max_duration: Option<u32>,
    pub blind_duration: Option<u32>,
    pub sensitivity: Option<u8>,
}

// Command encoders

/// Encode CreateTwoDCartesianZone command (0x00)
pub fn encode_create_two_d_cartesian_zone(zone: TwoDCartesianZone) -> anyhow::Result<Vec<u8>> {
            // Encode struct TwoDCartesianZoneStruct
            let mut zone_fields = Vec::new();
            if let Some(x) = zone.name { zone_fields.push((0, tlv::TlvItemValueEnc::String(x.clone())).into()); }
            if let Some(x) = zone.use_ { zone_fields.push((1, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
            if let Some(listv) = zone.vertices {
                let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
                    let mut nested_fields = Vec::new();
                        if let Some(x) = inner.x { nested_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                        if let Some(x) = inner.y { nested_fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                    (0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
                }).collect();
                zone_fields.push((2, tlv::TlvItemValueEnc::Array(inner_vec)).into());
            }
            if let Some(x) = zone.color { zone_fields.push((3, tlv::TlvItemValueEnc::String(x.clone())).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::StructInvisible(zone_fields)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode UpdateTwoDCartesianZone command (0x02)
pub fn encode_update_two_d_cartesian_zone(zone_id: u8, zone: TwoDCartesianZone) -> anyhow::Result<Vec<u8>> {
            // Encode struct TwoDCartesianZoneStruct
            let mut zone_fields = Vec::new();
            if let Some(x) = zone.name { zone_fields.push((0, tlv::TlvItemValueEnc::String(x.clone())).into()); }
            if let Some(x) = zone.use_ { zone_fields.push((1, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
            if let Some(listv) = zone.vertices {
                let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
                    let mut nested_fields = Vec::new();
                        if let Some(x) = inner.x { nested_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                        if let Some(x) = inner.y { nested_fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                    (0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
                }).collect();
                zone_fields.push((2, tlv::TlvItemValueEnc::Array(inner_vec)).into());
            }
            if let Some(x) = zone.color { zone_fields.push((3, tlv::TlvItemValueEnc::String(x.clone())).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(zone_id)).into(),
        (1, tlv::TlvItemValueEnc::StructInvisible(zone_fields)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RemoveZone command (0x03)
pub fn encode_remove_zone(zone_id: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(zone_id)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode CreateOrUpdateTrigger command (0x04)
pub fn encode_create_or_update_trigger(trigger: ZoneTriggerControl) -> anyhow::Result<Vec<u8>> {
            // Encode struct ZoneTriggerControlStruct
            let mut trigger_fields = Vec::new();
            // TODO: encoding for field zone_id (ZoneID) not implemented
            if let Some(x) = trigger.initial_duration { trigger_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
            if let Some(x) = trigger.augmentation_duration { trigger_fields.push((2, tlv::TlvItemValueEnc::UInt32(x)).into()); }
            if let Some(x) = trigger.max_duration { trigger_fields.push((3, tlv::TlvItemValueEnc::UInt32(x)).into()); }
            if let Some(x) = trigger.blind_duration { trigger_fields.push((4, tlv::TlvItemValueEnc::UInt32(x)).into()); }
            if let Some(x) = trigger.sensitivity { trigger_fields.push((5, tlv::TlvItemValueEnc::UInt8(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::StructInvisible(trigger_fields)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RemoveTrigger command (0x05)
pub fn encode_remove_trigger(zone_id: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(zone_id)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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

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

/// Decode Zones attribute (0x0002)
pub fn decode_zones(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ZoneInformation>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(ZoneInformation {
                zone_id: item.get_int(&[0]).map(|v| v as u8),
                zone_type: item.get_int(&[1]).and_then(|v| ZoneType::from_u8(v as u8)),
                zone_source: item.get_int(&[2]).and_then(|v| ZoneSource::from_u8(v as u8)),
                two_d_cartesian_zone: {
                    if let Some(nested_tlv) = item.get(&[3]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 3, value: nested_tlv.clone() };
                            Some(TwoDCartesianZone {
                name: nested_item.get_string_owned(&[0]),
                use_: nested_item.get_int(&[1]).and_then(|v| ZoneUse::from_u8(v as u8)),
                vertices: {
                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[2]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(TwoDCartesianVertex {
                x: list_item.get_int(&[0]).map(|v| v as u16),
                y: list_item.get_int(&[1]).map(|v| v as u16),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
                color: nested_item.get_string_owned(&[3]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

/// Decode Triggers attribute (0x0003)
pub fn decode_triggers(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ZoneTriggerControl>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(ZoneTriggerControl {
                zone_id: item.get_int(&[0]).map(|v| v as u8),
                initial_duration: item.get_int(&[1]).map(|v| v as u32),
                augmentation_duration: item.get_int(&[2]).map(|v| v as u32),
                max_duration: item.get_int(&[3]).map(|v| v as u32),
                blind_duration: item.get_int(&[4]).map(|v| v as u32),
                sensitivity: item.get_int(&[5]).map(|v| v as u8),
            });
        }
    }
    Ok(res)
}

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

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

/// Decode TwoDCartesianMax attribute (0x0006)
pub fn decode_two_d_cartesian_max(inp: &tlv::TlvItemValue) -> anyhow::Result<TwoDCartesianVertex> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(TwoDCartesianVertex {
                x: item.get_int(&[0]).map(|v| v as u16),
                y: item.get_int(&[1]).map(|v| v as u16),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}


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

    match attribute_id {
        0x0000 => {
            match decode_max_user_defined_zones(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_max_zones(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_zones(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_triggers(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_sensitivity_max(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_sensitivity(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_two_d_cartesian_max(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, "MaxUserDefinedZones"),
        (0x0001, "MaxZones"),
        (0x0002, "Zones"),
        (0x0003, "Triggers"),
        (0x0004, "SensitivityMax"),
        (0x0005, "Sensitivity"),
        (0x0006, "TwoDCartesianMax"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "CreateTwoDCartesianZone"),
        (0x02, "UpdateTwoDCartesianZone"),
        (0x03, "RemoveZone"),
        (0x04, "CreateOrUpdateTrigger"),
        (0x05, "RemoveTrigger"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("CreateTwoDCartesianZone"),
        0x02 => Some("UpdateTwoDCartesianZone"),
        0x03 => Some("RemoveZone"),
        0x04 => Some("CreateOrUpdateTrigger"),
        0x05 => Some("RemoveTrigger"),
        _ => 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: "zone", kind: crate::clusters::codec::FieldKind::Struct { name: "TwoDCartesianZoneStruct" }, optional: false, nullable: false },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "zone_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "zone", kind: crate::clusters::codec::FieldKind::Struct { name: "TwoDCartesianZoneStruct" }, optional: false, nullable: false },
        ]),
        0x03 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "zone_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x04 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "trigger", kind: crate::clusters::codec::FieldKind::Struct { name: "ZoneTriggerControlStruct" }, optional: false, nullable: false },
        ]),
        0x05 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "zone_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => Err(anyhow::anyhow!("command \"CreateTwoDCartesianZone\" has complex args: use raw mode")),
        0x02 => Err(anyhow::anyhow!("command \"UpdateTwoDCartesianZone\" has complex args: use raw mode")),
        0x03 => {
        let zone_id = crate::clusters::codec::json_util::get_u8(args, "zone_id")?;
        encode_remove_zone(zone_id)
        }
        0x04 => Err(anyhow::anyhow!("command \"CreateOrUpdateTrigger\" has complex args: use raw mode")),
        0x05 => {
        let zone_id = crate::clusters::codec::json_util::get_u8(args, "zone_id")?;
        encode_remove_trigger(zone_id)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct CreateTwoDCartesianZoneResponse {
    pub zone_id: Option<u8>,
}

// Command response decoders

/// Decode CreateTwoDCartesianZoneResponse command response (01)
pub fn decode_create_two_d_cartesian_zone_response(inp: &tlv::TlvItemValue) -> anyhow::Result<CreateTwoDCartesianZoneResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(CreateTwoDCartesianZoneResponse {
                zone_id: item.get_int(&[0]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `CreateTwoDCartesianZone` command on cluster `Zone Management`.
pub async fn create_two_d_cartesian_zone(conn: &crate::controller::Connection, endpoint: u16, zone: TwoDCartesianZone) -> anyhow::Result<CreateTwoDCartesianZoneResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_CMD_ID_CREATETWODCARTESIANZONE, &encode_create_two_d_cartesian_zone(zone)?).await?;
    decode_create_two_d_cartesian_zone_response(&tlv)
}

/// Invoke `UpdateTwoDCartesianZone` command on cluster `Zone Management`.
pub async fn update_two_d_cartesian_zone(conn: &crate::controller::Connection, endpoint: u16, zone_id: u8, zone: TwoDCartesianZone) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_CMD_ID_UPDATETWODCARTESIANZONE, &encode_update_two_d_cartesian_zone(zone_id, zone)?).await?;
    Ok(())
}

/// Invoke `RemoveZone` command on cluster `Zone Management`.
pub async fn remove_zone(conn: &crate::controller::Connection, endpoint: u16, zone_id: u8) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_CMD_ID_REMOVEZONE, &encode_remove_zone(zone_id)?).await?;
    Ok(())
}

/// Invoke `CreateOrUpdateTrigger` command on cluster `Zone Management`.
pub async fn create_or_update_trigger(conn: &crate::controller::Connection, endpoint: u16, trigger: ZoneTriggerControl) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_CMD_ID_CREATEORUPDATETRIGGER, &encode_create_or_update_trigger(trigger)?).await?;
    Ok(())
}

/// Invoke `RemoveTrigger` command on cluster `Zone Management`.
pub async fn remove_trigger(conn: &crate::controller::Connection, endpoint: u16, zone_id: u8) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_CMD_ID_REMOVETRIGGER, &encode_remove_trigger(zone_id)?).await?;
    Ok(())
}

/// Read `MaxUserDefinedZones` attribute from cluster `Zone Management`.
pub async fn read_max_user_defined_zones(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_ATTR_ID_MAXUSERDEFINEDZONES).await?;
    decode_max_user_defined_zones(&tlv)
}

/// Read `MaxZones` attribute from cluster `Zone Management`.
pub async fn read_max_zones(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_ATTR_ID_MAXZONES).await?;
    decode_max_zones(&tlv)
}

/// Read `Zones` attribute from cluster `Zone Management`.
pub async fn read_zones(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ZoneInformation>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_ATTR_ID_ZONES).await?;
    decode_zones(&tlv)
}

/// Read `Triggers` attribute from cluster `Zone Management`.
pub async fn read_triggers(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ZoneTriggerControl>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_ATTR_ID_TRIGGERS).await?;
    decode_triggers(&tlv)
}

/// Read `SensitivityMax` attribute from cluster `Zone Management`.
pub async fn read_sensitivity_max(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_ATTR_ID_SENSITIVITYMAX).await?;
    decode_sensitivity_max(&tlv)
}

/// Read `Sensitivity` attribute from cluster `Zone Management`.
pub async fn read_sensitivity(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_ATTR_ID_SENSITIVITY).await?;
    decode_sensitivity(&tlv)
}

/// Read `TwoDCartesianMax` attribute from cluster `Zone Management`.
pub async fn read_two_d_cartesian_max(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<TwoDCartesianVertex> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ZONE_MANAGEMENT, crate::clusters::defs::CLUSTER_ZONE_MANAGEMENT_ATTR_ID_TWODCARTESIANMAX).await?;
    decode_two_d_cartesian_max(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct ZoneTriggeredEvent {
    pub zone: Option<u8>,
    pub reason: Option<ZoneEventTriggeredReason>,
}

#[derive(Debug, serde::Serialize)]
pub struct ZoneStoppedEvent {
    pub zone: Option<u8>,
    pub reason: Option<ZoneEventStoppedReason>,
}

// Event decoders

/// Decode ZoneTriggered event (0x00, priority: info)
pub fn decode_zone_triggered_event(inp: &tlv::TlvItemValue) -> anyhow::Result<ZoneTriggeredEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ZoneTriggeredEvent {
                                zone: item.get_int(&[0]).map(|v| v as u8),
                                reason: item.get_int(&[1]).and_then(|v| ZoneEventTriggeredReason::from_u8(v as u8)),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode ZoneStopped event (0x01, priority: info)
pub fn decode_zone_stopped_event(inp: &tlv::TlvItemValue) -> anyhow::Result<ZoneStoppedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ZoneStoppedEvent {
                                zone: item.get_int(&[0]).map(|v| v as u8),
                                reason: item.get_int(&[1]).and_then(|v| ZoneEventStoppedReason::from_u8(v as u8)),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}