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
//! Matter TLV encoders and decoders for General Commissioning Cluster
//! Cluster ID: 0x0030
//!
//! This file is automatically generated from GeneralCommissioningCluster.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 CommissioningError {
    /// No error
    Ok = 0,
    /// Attempting to set regulatory configuration to a region or indoor/outdoor mode for which the server does not have proper configuration.
    Valueoutsiderange = 1,
    /// Executed CommissioningComplete outside CASE session.
    Invalidauthentication = 2,
    /// Executed CommissioningComplete when there was no active Fail-Safe context.
    Nofailsafe = 3,
    /// Attempting to arm fail-safe or execute CommissioningComplete from a fabric different than the one associated with the current fail-safe context.
    Busywithotheradmin = 4,
    /// One or more required TC features from the Enhanced Setup Flow were not accepted.
    Requiredtcnotaccepted = 5,
    /// TCAcknowledgementsNotReceived No or insufficient acknowledgements from the user for the TC features were received.
    Tcacknowledgementsnotreceived = 6,
    /// TCMinVersionNotMet The version of the TC features acknowledged by the user did not meet the minimum required version.
    Tcminversionnotmet = 7,
}

impl CommissioningError {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(CommissioningError::Ok),
            1 => Some(CommissioningError::Valueoutsiderange),
            2 => Some(CommissioningError::Invalidauthentication),
            3 => Some(CommissioningError::Nofailsafe),
            4 => Some(CommissioningError::Busywithotheradmin),
            5 => Some(CommissioningError::Requiredtcnotaccepted),
            6 => Some(CommissioningError::Tcacknowledgementsnotreceived),
            7 => Some(CommissioningError::Tcminversionnotmet),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum NetworkRecoveryReason {
    /// Unspecified / unknown reason of network failure
    Unspecified = 0,
    /// Credentials for the configured operational network are not valid
    Auth = 1,
    /// Configured network cannot be found (e.g. the device cannot see the configured Wi-Fi SSID, Thread end-node is unable to find a parent router on the PAN)
    Visibility = 2,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum RegulatoryLocationType {
    /// Indoor only
    Indoor = 0,
    /// Outdoor only
    Outdoor = 1,
    /// Indoor/Outdoor
    Indooroutdoor = 2,
}

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

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct BasicCommissioningInfo {
    pub fail_safe_expiry_length_seconds: Option<u16>,
    pub max_cumulative_failsafe_seconds: Option<u16>,
}

// Command encoders

/// Encode ArmFailSafe command (0x00)
pub fn encode_arm_fail_safe(expiry_length_seconds: u16, breadcrumb: u64) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt16(expiry_length_seconds)).into(),
        (1, tlv::TlvItemValueEnc::UInt64(breadcrumb)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SetRegulatoryConfig command (0x02)
pub fn encode_set_regulatory_config(new_regulatory_config: RegulatoryLocationType, country_code: String, breadcrumb: u64) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(new_regulatory_config.to_u8())).into(),
        (1, tlv::TlvItemValueEnc::String(country_code)).into(),
        (2, tlv::TlvItemValueEnc::UInt64(breadcrumb)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SetTCAcknowledgements command (0x06)
pub fn encode_set_tc_acknowledgements(tc_version: u16, tc_user_response: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt16(tc_version)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(tc_user_response)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode Breadcrumb attribute (0x0000)
pub fn decode_breadcrumb(inp: &tlv::TlvItemValue) -> anyhow::Result<u64> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected UInt64"))
    }
}

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

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

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

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

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

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

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

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

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

/// Decode RecoveryIdentifier attribute (0x000A)
pub fn decode_recovery_identifier(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<u8>> {
    if let tlv::TlvItemValue::OctetString(v) = inp {
        Ok(v.clone())
    } else {
        Err(anyhow::anyhow!("Expected OctetString"))
    }
}

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

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


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

    match attribute_id {
        0x0000 => {
            match decode_breadcrumb(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_basic_commissioning_info(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_regulatory_config(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_location_capability(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_supports_concurrent_connection(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_tc_accepted_version(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_tc_min_required_version(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_tc_acknowledgements(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_tc_acknowledgements_required(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_tc_update_deadline(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000A => {
            match decode_recovery_identifier(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000B => {
            match decode_network_recovery_reason(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000C => {
            match decode_is_commissioning_without_power(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, "Breadcrumb"),
        (0x0001, "BasicCommissioningInfo"),
        (0x0002, "RegulatoryConfig"),
        (0x0003, "LocationCapability"),
        (0x0004, "SupportsConcurrentConnection"),
        (0x0005, "TCAcceptedVersion"),
        (0x0006, "TCMinRequiredVersion"),
        (0x0007, "TCAcknowledgements"),
        (0x0008, "TCAcknowledgementsRequired"),
        (0x0009, "TCUpdateDeadline"),
        (0x000A, "RecoveryIdentifier"),
        (0x000B, "NetworkRecoveryReason"),
        (0x000C, "IsCommissioningWithoutPower"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "ArmFailSafe"),
        (0x02, "SetRegulatoryConfig"),
        (0x04, "CommissioningComplete"),
        (0x06, "SetTCAcknowledgements"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("ArmFailSafe"),
        0x02 => Some("SetRegulatoryConfig"),
        0x04 => Some("CommissioningComplete"),
        0x06 => Some("SetTCAcknowledgements"),
        _ => 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: "expiry_length_seconds", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "breadcrumb", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "new_regulatory_config", kind: crate::clusters::codec::FieldKind::Enum { name: "RegulatoryLocationType", variants: &[(0, "Indoor"), (1, "Outdoor"), (2, "Indooroutdoor")] }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "country_code", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "breadcrumb", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
        ]),
        0x04 => Some(vec![]),
        0x06 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "tc_version", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "tc_user_response", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => {
        let expiry_length_seconds = crate::clusters::codec::json_util::get_u16(args, "expiry_length_seconds")?;
        let breadcrumb = crate::clusters::codec::json_util::get_u64(args, "breadcrumb")?;
        encode_arm_fail_safe(expiry_length_seconds, breadcrumb)
        }
        0x02 => {
        let new_regulatory_config = {
            let n = crate::clusters::codec::json_util::get_u64(args, "new_regulatory_config")?;
            RegulatoryLocationType::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid RegulatoryLocationType: {}", n))?
        };
        let country_code = crate::clusters::codec::json_util::get_string(args, "country_code")?;
        let breadcrumb = crate::clusters::codec::json_util::get_u64(args, "breadcrumb")?;
        encode_set_regulatory_config(new_regulatory_config, country_code, breadcrumb)
        }
        0x04 => Ok(vec![]),
        0x06 => {
        let tc_version = crate::clusters::codec::json_util::get_u16(args, "tc_version")?;
        let tc_user_response = crate::clusters::codec::json_util::get_u8(args, "tc_user_response")?;
        encode_set_tc_acknowledgements(tc_version, tc_user_response)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct ArmFailSafeResponse {
    pub error_code: Option<CommissioningError>,
    pub debug_text: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct SetRegulatoryConfigResponse {
    pub error_code: Option<CommissioningError>,
    pub debug_text: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct CommissioningCompleteResponse {
    pub error_code: Option<CommissioningError>,
    pub debug_text: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct SetTCAcknowledgementsResponse {
    pub error_code: Option<CommissioningError>,
}

// Command response decoders

/// Decode ArmFailSafeResponse command response (01)
pub fn decode_arm_fail_safe_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ArmFailSafeResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ArmFailSafeResponse {
                error_code: item.get_int(&[0]).and_then(|v| CommissioningError::from_u8(v as u8)),
                debug_text: item.get_string_owned(&[1]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode SetRegulatoryConfigResponse command response (03)
pub fn decode_set_regulatory_config_response(inp: &tlv::TlvItemValue) -> anyhow::Result<SetRegulatoryConfigResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(SetRegulatoryConfigResponse {
                error_code: item.get_int(&[0]).and_then(|v| CommissioningError::from_u8(v as u8)),
                debug_text: item.get_string_owned(&[1]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode CommissioningCompleteResponse command response (05)
pub fn decode_commissioning_complete_response(inp: &tlv::TlvItemValue) -> anyhow::Result<CommissioningCompleteResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(CommissioningCompleteResponse {
                error_code: item.get_int(&[0]).and_then(|v| CommissioningError::from_u8(v as u8)),
                debug_text: item.get_string_owned(&[1]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

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

// Typed facade (invokes + reads)

/// Invoke `ArmFailSafe` command on cluster `General Commissioning`.
pub async fn arm_fail_safe(conn: &crate::controller::Connection, endpoint: u16, expiry_length_seconds: u16, breadcrumb: u64) -> anyhow::Result<ArmFailSafeResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_CMD_ID_ARMFAILSAFE, &encode_arm_fail_safe(expiry_length_seconds, breadcrumb)?).await?;
    decode_arm_fail_safe_response(&tlv)
}

/// Invoke `SetRegulatoryConfig` command on cluster `General Commissioning`.
pub async fn set_regulatory_config(conn: &crate::controller::Connection, endpoint: u16, new_regulatory_config: RegulatoryLocationType, country_code: String, breadcrumb: u64) -> anyhow::Result<SetRegulatoryConfigResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_CMD_ID_SETREGULATORYCONFIG, &encode_set_regulatory_config(new_regulatory_config, country_code, breadcrumb)?).await?;
    decode_set_regulatory_config_response(&tlv)
}

/// Invoke `CommissioningComplete` command on cluster `General Commissioning`.
pub async fn commissioning_complete(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<CommissioningCompleteResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_CMD_ID_COMMISSIONINGCOMPLETE, &[]).await?;
    decode_commissioning_complete_response(&tlv)
}

/// Invoke `SetTCAcknowledgements` command on cluster `General Commissioning`.
pub async fn set_tc_acknowledgements(conn: &crate::controller::Connection, endpoint: u16, tc_version: u16, tc_user_response: u8) -> anyhow::Result<SetTCAcknowledgementsResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_CMD_ID_SETTCACKNOWLEDGEMENTS, &encode_set_tc_acknowledgements(tc_version, tc_user_response)?).await?;
    decode_set_tc_acknowledgements_response(&tlv)
}

/// Read `Breadcrumb` attribute from cluster `General Commissioning`.
pub async fn read_breadcrumb(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u64> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_BREADCRUMB).await?;
    decode_breadcrumb(&tlv)
}

/// Read `BasicCommissioningInfo` attribute from cluster `General Commissioning`.
pub async fn read_basic_commissioning_info(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<BasicCommissioningInfo> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_BASICCOMMISSIONINGINFO).await?;
    decode_basic_commissioning_info(&tlv)
}

/// Read `RegulatoryConfig` attribute from cluster `General Commissioning`.
pub async fn read_regulatory_config(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<RegulatoryLocationType> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_REGULATORYCONFIG).await?;
    decode_regulatory_config(&tlv)
}

/// Read `LocationCapability` attribute from cluster `General Commissioning`.
pub async fn read_location_capability(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<RegulatoryLocationType> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_LOCATIONCAPABILITY).await?;
    decode_location_capability(&tlv)
}

/// Read `SupportsConcurrentConnection` attribute from cluster `General Commissioning`.
pub async fn read_supports_concurrent_connection(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_SUPPORTSCONCURRENTCONNECTION).await?;
    decode_supports_concurrent_connection(&tlv)
}

/// Read `TCAcceptedVersion` attribute from cluster `General Commissioning`.
pub async fn read_tc_accepted_version(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_TCACCEPTEDVERSION).await?;
    decode_tc_accepted_version(&tlv)
}

/// Read `TCMinRequiredVersion` attribute from cluster `General Commissioning`.
pub async fn read_tc_min_required_version(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_TCMINREQUIREDVERSION).await?;
    decode_tc_min_required_version(&tlv)
}

/// Read `TCAcknowledgements` attribute from cluster `General Commissioning`.
pub async fn read_tc_acknowledgements(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_TCACKNOWLEDGEMENTS).await?;
    decode_tc_acknowledgements(&tlv)
}

/// Read `TCAcknowledgementsRequired` attribute from cluster `General Commissioning`.
pub async fn read_tc_acknowledgements_required(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_TCACKNOWLEDGEMENTSREQUIRED).await?;
    decode_tc_acknowledgements_required(&tlv)
}

/// Read `TCUpdateDeadline` attribute from cluster `General Commissioning`.
pub async fn read_tc_update_deadline(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_TCUPDATEDEADLINE).await?;
    decode_tc_update_deadline(&tlv)
}

/// Read `RecoveryIdentifier` attribute from cluster `General Commissioning`.
pub async fn read_recovery_identifier(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_RECOVERYIDENTIFIER).await?;
    decode_recovery_identifier(&tlv)
}

/// Read `NetworkRecoveryReason` attribute from cluster `General Commissioning`.
pub async fn read_network_recovery_reason(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<NetworkRecoveryReason>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_NETWORKRECOVERYREASON).await?;
    decode_network_recovery_reason(&tlv)
}

/// Read `IsCommissioningWithoutPower` attribute from cluster `General Commissioning`.
pub async fn read_is_commissioning_without_power(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_GENERAL_COMMISSIONING, crate::clusters::defs::CLUSTER_GENERAL_COMMISSIONING_ATTR_ID_ISCOMMISSIONINGWITHOUTPOWER).await?;
    decode_is_commissioning_without_power(&tlv)
}