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
//! Matter TLV encoders and decoders for Access Control Cluster
//! Cluster ID: 0x001F
//!
//! This file is automatically generated from ACL-Cluster.xml

#![allow(clippy::too_many_arguments)]

use crate::tlv;
use anyhow;
use serde_json;


// Import serialization helpers for octet strings
use crate::clusters::helpers::{serialize_opt_bytes_as_hex};

// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum AccessControlEntryAuthMode {
    /// Passcode authenticated session
    Pase = 1,
    /// Certificate authenticated session
    Case = 2,
    /// Group authenticated session
    Group = 3,
}

impl AccessControlEntryAuthMode {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            1 => Some(AccessControlEntryAuthMode::Pase),
            2 => Some(AccessControlEntryAuthMode::Case),
            3 => Some(AccessControlEntryAuthMode::Group),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum AccessControlEntryPrivilege {
    /// Can read and observe all (except Access Control Cluster)
    View = 1,
    Proxyview = 2,
    /// View privileges, and can perform the primary function of this Node (except Access Control Cluster)
    Operate = 3,
    /// Operate privileges, and can modify persistent configuration of this Node (except Access Control Cluster)
    Manage = 4,
    /// Manage privileges, and can observe and modify the Access Control Cluster
    Administer = 5,
}

impl AccessControlEntryPrivilege {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            1 => Some(AccessControlEntryPrivilege::View),
            2 => Some(AccessControlEntryPrivilege::Proxyview),
            3 => Some(AccessControlEntryPrivilege::Operate),
            4 => Some(AccessControlEntryPrivilege::Manage),
            5 => Some(AccessControlEntryPrivilege::Administer),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum AccessRestrictionType {
    /// Clients on this fabric are currently forbidden from reading and writing an attribute
    Attributeaccessforbidden = 0,
    /// Clients on this fabric are currently forbidden from writing an attribute
    Attributewriteforbidden = 1,
    /// Clients on this fabric are currently forbidden from invoking a command
    Commandforbidden = 2,
    /// Clients on this fabric are currently forbidden from reading an event
    Eventforbidden = 3,
}

impl AccessRestrictionType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(AccessRestrictionType::Attributeaccessforbidden),
            1 => Some(AccessRestrictionType::Attributewriteforbidden),
            2 => Some(AccessRestrictionType::Commandforbidden),
            3 => Some(AccessRestrictionType::Eventforbidden),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ChangeType {
    /// Entry or extension was changed
    Changed = 0,
    /// Entry or extension was added
    Added = 1,
    /// Entry or extension was removed
    Removed = 2,
}

impl ChangeType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ChangeType::Changed),
            1 => Some(ChangeType::Added),
            2 => Some(ChangeType::Removed),
            _ => None,
        }
    }

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct AccessControlEntry {
    pub privilege: Option<AccessControlEntryPrivilege>,
    pub auth_mode: Option<AccessControlEntryAuthMode>,
    pub subjects: Option<Vec<u64>>,
    pub targets: Option<Vec<AccessControlTarget>>,
}

#[derive(Debug, serde::Serialize)]
pub struct AccessControlExtension {
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub data: Option<Vec<u8>>,
}

#[derive(Debug, serde::Serialize)]
pub struct AccessControlTarget {
    pub cluster: Option<u32>,
    pub endpoint: Option<u16>,
    pub device_type: Option<u32>,
}

#[derive(Debug, serde::Serialize)]
pub struct AccessRestrictionEntry {
    pub endpoint: Option<u16>,
    pub cluster: Option<u32>,
    pub restrictions: Option<Vec<AccessRestriction>>,
}

#[derive(Debug, serde::Serialize)]
pub struct AccessRestriction {
    pub type_: Option<AccessRestrictionType>,
    pub id: Option<u32>,
}

#[derive(Debug, serde::Serialize)]
pub struct CommissioningAccessRestrictionEntry {
    pub endpoint: Option<u16>,
    pub cluster: Option<u32>,
    pub restrictions: Option<Vec<AccessRestriction>>,
}

// Command encoders

/// Encode ReviewFabricRestrictions command (0x00)
pub fn encode_review_fabric_restrictions(arl: Vec<CommissioningAccessRestrictionEntry>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::Array(arl.into_iter().map(|v| {
                    let mut fields = Vec::new();
                    if let Some(x) = v.endpoint { fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                    if let Some(x) = v.cluster { fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
                    if let Some(listv) = v.restrictions {
                        let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
                            let mut nested_fields = Vec::new();
                                if let Some(x) = inner.type_ { nested_fields.push((0, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
                                if let Some(x) = inner.id { nested_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
                            (0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
                        }).collect();
                        fields.push((2, tlv::TlvItemValueEnc::Array(inner_vec)).into());
                    }
                    (0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
                }).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode ACL attribute (0x0000)
pub fn decode_acl(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<AccessControlEntry>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(AccessControlEntry {
                privilege: item.get_int(&[1]).and_then(|v| AccessControlEntryPrivilege::from_u8(v as u8)),
                auth_mode: item.get_int(&[2]).and_then(|v| AccessControlEntryAuthMode::from_u8(v as u8)),
                subjects: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[3]) {
                        let items: Vec<u64> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                targets: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[4]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(AccessControlTarget {
                cluster: list_item.get_int(&[0]).map(|v| v as u32),
                endpoint: list_item.get_int(&[1]).map(|v| v as u16),
                device_type: list_item.get_int(&[2]).map(|v| v as u32),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

/// Decode Extension attribute (0x0001)
pub fn decode_extension(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<AccessControlExtension>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(AccessControlExtension {
                data: item.get_octet_string_owned(&[1]),
            });
        }
    }
    Ok(res)
}

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

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

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

/// Decode CommissioningARL attribute (0x0005)
pub fn decode_commissioning_arl(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<CommissioningAccessRestrictionEntry>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(CommissioningAccessRestrictionEntry {
                endpoint: item.get_int(&[0]).map(|v| v as u16),
                cluster: item.get_int(&[1]).map(|v| v as u32),
                restrictions: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(AccessRestriction {
                type_: list_item.get_int(&[0]).and_then(|v| AccessRestrictionType::from_u8(v as u8)),
                id: list_item.get_int(&[1]).map(|v| v as u32),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

/// Decode ARL attribute (0x0006)
pub fn decode_arl(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<AccessRestrictionEntry>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(AccessRestrictionEntry {
                endpoint: item.get_int(&[0]).map(|v| v as u16),
                cluster: item.get_int(&[1]).map(|v| v as u32),
                restrictions: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(AccessRestriction {
                type_: list_item.get_int(&[0]).and_then(|v| AccessRestrictionType::from_u8(v as u8)),
                id: list_item.get_int(&[1]).map(|v| v as u32),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}


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

    match attribute_id {
        0x0000 => {
            match decode_acl(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_extension(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_subjects_per_access_control_entry(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_targets_per_access_control_entry(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_access_control_entries_per_fabric(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_commissioning_arl(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_arl(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, "ACL"),
        (0x0001, "Extension"),
        (0x0002, "SubjectsPerAccessControlEntry"),
        (0x0003, "TargetsPerAccessControlEntry"),
        (0x0004, "AccessControlEntriesPerFabric"),
        (0x0005, "CommissioningARL"),
        (0x0006, "ARL"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("ReviewFabricRestrictions"),
        _ => 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: "arl", kind: crate::clusters::codec::FieldKind::List { entry_type: "CommissioningAccessRestrictionEntryStruct" }, 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 \"ReviewFabricRestrictions\" has complex args: use raw mode")),
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct ReviewFabricRestrictionsResponse {
    pub token: Option<u64>,
}

// Command response decoders

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

// Typed facade (invokes + reads)

/// Invoke `ReviewFabricRestrictions` command on cluster `Access Control`.
pub async fn review_fabric_restrictions(conn: &crate::controller::Connection, endpoint: u16, arl: Vec<CommissioningAccessRestrictionEntry>) -> anyhow::Result<ReviewFabricRestrictionsResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ACCESS_CONTROL, crate::clusters::defs::CLUSTER_ACCESS_CONTROL_CMD_ID_REVIEWFABRICRESTRICTIONS, &encode_review_fabric_restrictions(arl)?).await?;
    decode_review_fabric_restrictions_response(&tlv)
}

/// Read `ACL` attribute from cluster `Access Control`.
pub async fn read_acl(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<AccessControlEntry>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ACCESS_CONTROL, crate::clusters::defs::CLUSTER_ACCESS_CONTROL_ATTR_ID_ACL).await?;
    decode_acl(&tlv)
}

/// Read `Extension` attribute from cluster `Access Control`.
pub async fn read_extension(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<AccessControlExtension>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ACCESS_CONTROL, crate::clusters::defs::CLUSTER_ACCESS_CONTROL_ATTR_ID_EXTENSION).await?;
    decode_extension(&tlv)
}

/// Read `SubjectsPerAccessControlEntry` attribute from cluster `Access Control`.
pub async fn read_subjects_per_access_control_entry(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ACCESS_CONTROL, crate::clusters::defs::CLUSTER_ACCESS_CONTROL_ATTR_ID_SUBJECTSPERACCESSCONTROLENTRY).await?;
    decode_subjects_per_access_control_entry(&tlv)
}

/// Read `TargetsPerAccessControlEntry` attribute from cluster `Access Control`.
pub async fn read_targets_per_access_control_entry(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ACCESS_CONTROL, crate::clusters::defs::CLUSTER_ACCESS_CONTROL_ATTR_ID_TARGETSPERACCESSCONTROLENTRY).await?;
    decode_targets_per_access_control_entry(&tlv)
}

/// Read `AccessControlEntriesPerFabric` attribute from cluster `Access Control`.
pub async fn read_access_control_entries_per_fabric(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ACCESS_CONTROL, crate::clusters::defs::CLUSTER_ACCESS_CONTROL_ATTR_ID_ACCESSCONTROLENTRIESPERFABRIC).await?;
    decode_access_control_entries_per_fabric(&tlv)
}

/// Read `CommissioningARL` attribute from cluster `Access Control`.
pub async fn read_commissioning_arl(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<CommissioningAccessRestrictionEntry>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ACCESS_CONTROL, crate::clusters::defs::CLUSTER_ACCESS_CONTROL_ATTR_ID_COMMISSIONINGARL).await?;
    decode_commissioning_arl(&tlv)
}

/// Read `ARL` attribute from cluster `Access Control`.
pub async fn read_arl(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<AccessRestrictionEntry>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ACCESS_CONTROL, crate::clusters::defs::CLUSTER_ACCESS_CONTROL_ATTR_ID_ARL).await?;
    decode_arl(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct AccessControlEntryChangedEvent {
    pub admin_node_id: Option<u64>,
    pub admin_passcode_id: Option<u16>,
    pub change_type: Option<ChangeType>,
    pub latest_value: Option<AccessControlEntry>,
}

#[derive(Debug, serde::Serialize)]
pub struct AccessControlExtensionChangedEvent {
    pub admin_node_id: Option<u64>,
    pub admin_passcode_id: Option<u16>,
    pub change_type: Option<ChangeType>,
    pub latest_value: Option<AccessControlExtension>,
}

#[derive(Debug, serde::Serialize)]
pub struct FabricRestrictionReviewUpdateEvent {
    pub token: Option<u64>,
    pub instruction: Option<String>,
    pub arl_request_flow_url: Option<String>,
}

// Event decoders

/// Decode AccessControlEntryChanged event (0x00, priority: info)
pub fn decode_access_control_entry_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<AccessControlEntryChangedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(AccessControlEntryChangedEvent {
                                admin_node_id: item.get_int(&[1]),
                                admin_passcode_id: item.get_int(&[2]).map(|v| v as u16),
                                change_type: item.get_int(&[3]).and_then(|v| ChangeType::from_u8(v as u8)),
                                latest_value: {
                    if let Some(nested_tlv) = item.get(&[4]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 4, value: nested_tlv.clone() };
                            Some(AccessControlEntry {
                privilege: nested_item.get_int(&[1]).and_then(|v| AccessControlEntryPrivilege::from_u8(v as u8)),
                auth_mode: nested_item.get_int(&[2]).and_then(|v| AccessControlEntryAuthMode::from_u8(v as u8)),
                subjects: {
                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[3]) {
                        let items: Vec<u64> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                targets: {
                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[4]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(AccessControlTarget {
                cluster: list_item.get_int(&[0]).map(|v| v as u32),
                endpoint: list_item.get_int(&[1]).map(|v| v as u16),
                device_type: list_item.get_int(&[2]).map(|v| v as u32),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode AccessControlExtensionChanged event (0x01, priority: info)
pub fn decode_access_control_extension_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<AccessControlExtensionChangedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(AccessControlExtensionChangedEvent {
                                admin_node_id: item.get_int(&[1]),
                                admin_passcode_id: item.get_int(&[2]).map(|v| v as u16),
                                change_type: item.get_int(&[3]).and_then(|v| ChangeType::from_u8(v as u8)),
                                latest_value: {
                    if let Some(nested_tlv) = item.get(&[4]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 4, value: nested_tlv.clone() };
                            Some(AccessControlExtension {
                data: nested_item.get_octet_string_owned(&[1]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode FabricRestrictionReviewUpdate event (0x02, priority: info)
pub fn decode_fabric_restriction_review_update_event(inp: &tlv::TlvItemValue) -> anyhow::Result<FabricRestrictionReviewUpdateEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(FabricRestrictionReviewUpdateEvent {
                                token: item.get_int(&[0]),
                                instruction: item.get_string_owned(&[1]),
                                arl_request_flow_url: item.get_string_owned(&[2]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}