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
//! Matter TLV encoders and decoders for TLS Certificate Management Cluster
//! Cluster ID: 0x0801
//!
//! This file is automatically generated from TLSCertificateManagement.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, serialize_opt_vec_bytes_as_hex};

// Struct definitions

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

#[derive(Debug, serde::Serialize)]
pub struct TLSClientCertificateDetail {
    pub ccdid: Option<u8>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub client_certificate: Option<Vec<u8>>,
    #[serde(serialize_with = "serialize_opt_vec_bytes_as_hex")]
    pub intermediate_certificates: Option<Vec<Vec<u8>>>,
}

// Command encoders

/// Encode ProvisionRootCertificate command (0x00)
pub fn encode_provision_root_certificate(certificate: Vec<u8>, caid: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(certificate)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(caid.unwrap_or(0))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode FindRootCertificate command (0x02)
pub fn encode_find_root_certificate(caid: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(caid.unwrap_or(0))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode LookupRootCertificate command (0x04)
pub fn encode_lookup_root_certificate(fingerprint: Vec<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(fingerprint)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

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

/// Encode ClientCSR command (0x07)
pub fn encode_client_csr(nonce: Vec<u8>, ccdid: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(nonce)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(ccdid.unwrap_or(0))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode ProvisionClientCertificate command (0x09)
pub fn encode_provision_client_certificate(ccdid: u8, client_certificate: Vec<u8>, intermediate_certificates: Vec<Vec<u8>>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(ccdid)).into(),
        (1, tlv::TlvItemValueEnc::OctetString(client_certificate)).into(),
        (2, tlv::TlvItemValueEnc::StructAnon(intermediate_certificates.into_iter().map(|v| (0, tlv::TlvItemValueEnc::OctetString(v)).into()).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode FindClientCertificate command (0x0A)
pub fn encode_find_client_certificate(ccdid: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(ccdid.unwrap_or(0))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode LookupClientCertificate command (0x0C)
pub fn encode_lookup_client_certificate(fingerprint: Vec<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(fingerprint)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

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

// Attribute decoders

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

/// Decode ProvisionedRootCertificates attribute (0x0001)
pub fn decode_provisioned_root_certificates(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TLSCert>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TLSCert {
                caid: item.get_int(&[0]).map(|v| v as u8),
                certificate: item.get_octet_string_owned(&[1]),
            });
        }
    }
    Ok(res)
}

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

/// Decode ProvisionedClientCertificates attribute (0x0003)
pub fn decode_provisioned_client_certificates(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TLSClientCertificateDetail>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TLSClientCertificateDetail {
                ccdid: item.get_int(&[0]).map(|v| v as u8),
                client_certificate: item.get_octet_string_owned(&[1]),
                intermediate_certificates: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let items: Vec<Vec<u8>> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::OctetString(v) = &e.value { Some(v.clone()) } else { None } }).collect();
                        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 != 0x0801 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0801, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_max_root_certificates(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_provisioned_root_certificates(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_max_client_certificates(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_provisioned_client_certificates(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, "MaxRootCertificates"),
        (0x0001, "ProvisionedRootCertificates"),
        (0x0002, "MaxClientCertificates"),
        (0x0003, "ProvisionedClientCertificates"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "ProvisionRootCertificate"),
        (0x02, "FindRootCertificate"),
        (0x04, "LookupRootCertificate"),
        (0x06, "RemoveRootCertificate"),
        (0x07, "ClientCSR"),
        (0x09, "ProvisionClientCertificate"),
        (0x0A, "FindClientCertificate"),
        (0x0C, "LookupClientCertificate"),
        (0x0E, "RemoveClientCertificate"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("ProvisionRootCertificate"),
        0x02 => Some("FindRootCertificate"),
        0x04 => Some("LookupRootCertificate"),
        0x06 => Some("RemoveRootCertificate"),
        0x07 => Some("ClientCSR"),
        0x09 => Some("ProvisionClientCertificate"),
        0x0A => Some("FindClientCertificate"),
        0x0C => Some("LookupClientCertificate"),
        0x0E => Some("RemoveClientCertificate"),
        _ => 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: "certificate", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "caid", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: true },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "caid", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: true },
        ]),
        0x04 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "fingerprint", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
        ]),
        0x06 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "caid", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x07 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "nonce", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "ccdid", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: true },
        ]),
        0x09 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "ccdid", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "client_certificate", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "intermediate_certificates", kind: crate::clusters::codec::FieldKind::List { entry_type: "octstr" }, optional: false, nullable: false },
        ]),
        0x0A => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "ccdid", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: true },
        ]),
        0x0C => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "fingerprint", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
        ]),
        0x0E => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "ccdid", 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 certificate = crate::clusters::codec::json_util::get_octstr(args, "certificate")?;
        let caid = crate::clusters::codec::json_util::get_opt_u8(args, "caid")?;
        encode_provision_root_certificate(certificate, caid)
        }
        0x02 => {
        let caid = crate::clusters::codec::json_util::get_opt_u8(args, "caid")?;
        encode_find_root_certificate(caid)
        }
        0x04 => {
        let fingerprint = crate::clusters::codec::json_util::get_octstr(args, "fingerprint")?;
        encode_lookup_root_certificate(fingerprint)
        }
        0x06 => {
        let caid = crate::clusters::codec::json_util::get_u8(args, "caid")?;
        encode_remove_root_certificate(caid)
        }
        0x07 => {
        let nonce = crate::clusters::codec::json_util::get_octstr(args, "nonce")?;
        let ccdid = crate::clusters::codec::json_util::get_opt_u8(args, "ccdid")?;
        encode_client_csr(nonce, ccdid)
        }
        0x09 => Err(anyhow::anyhow!("command \"ProvisionClientCertificate\" has complex args: use raw mode")),
        0x0A => {
        let ccdid = crate::clusters::codec::json_util::get_opt_u8(args, "ccdid")?;
        encode_find_client_certificate(ccdid)
        }
        0x0C => {
        let fingerprint = crate::clusters::codec::json_util::get_octstr(args, "fingerprint")?;
        encode_lookup_client_certificate(fingerprint)
        }
        0x0E => {
        let ccdid = crate::clusters::codec::json_util::get_u8(args, "ccdid")?;
        encode_remove_client_certificate(ccdid)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

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

#[derive(Debug, serde::Serialize)]
pub struct FindRootCertificateResponse {
    pub certificate_details: Option<Vec<TLSCert>>,
}

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

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

#[derive(Debug, serde::Serialize)]
pub struct FindClientCertificateResponse {
    pub certificate_details: Option<Vec<TLSClientCertificateDetail>>,
}

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

// Command response decoders

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

/// Decode FindRootCertificateResponse command response (03)
pub fn decode_find_root_certificate_response(inp: &tlv::TlvItemValue) -> anyhow::Result<FindRootCertificateResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(FindRootCertificateResponse {
                certificate_details: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(TLSCert {
                caid: list_item.get_int(&[0]).map(|v| v as u8),
                certificate: list_item.get_octet_string_owned(&[1]),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

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

/// Decode ClientCSRResponse command response (08)
pub fn decode_client_csr_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ClientCSRResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ClientCSRResponse {
                ccdid: item.get_int(&[0]).map(|v| v as u8),
                csr: item.get_octet_string_owned(&[1]),
                nonce_signature: item.get_octet_string_owned(&[2]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode FindClientCertificateResponse command response (0B)
pub fn decode_find_client_certificate_response(inp: &tlv::TlvItemValue) -> anyhow::Result<FindClientCertificateResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(FindClientCertificateResponse {
                certificate_details: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(TLSClientCertificateDetail {
                ccdid: list_item.get_int(&[0]).map(|v| v as u8),
                client_certificate: list_item.get_octet_string_owned(&[1]),
                intermediate_certificates: {
                    if let Some(tlv::TlvItemValue::List(l)) = list_item.get(&[2]) {
                        let items: Vec<Vec<u8>> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::OctetString(v) = &e.value { Some(v.clone()) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

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

// Typed facade (invokes + reads)

/// Invoke `ProvisionRootCertificate` command on cluster `TLS Certificate Management`.
pub async fn provision_root_certificate(conn: &crate::controller::Connection, endpoint: u16, certificate: Vec<u8>, caid: Option<u8>) -> anyhow::Result<ProvisionRootCertificateResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_CMD_ID_PROVISIONROOTCERTIFICATE, &encode_provision_root_certificate(certificate, caid)?).await?;
    decode_provision_root_certificate_response(&tlv)
}

/// Invoke `FindRootCertificate` command on cluster `TLS Certificate Management`.
pub async fn find_root_certificate(conn: &crate::controller::Connection, endpoint: u16, caid: Option<u8>) -> anyhow::Result<FindRootCertificateResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_CMD_ID_FINDROOTCERTIFICATE, &encode_find_root_certificate(caid)?).await?;
    decode_find_root_certificate_response(&tlv)
}

/// Invoke `LookupRootCertificate` command on cluster `TLS Certificate Management`.
pub async fn lookup_root_certificate(conn: &crate::controller::Connection, endpoint: u16, fingerprint: Vec<u8>) -> anyhow::Result<LookupRootCertificateResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_CMD_ID_LOOKUPROOTCERTIFICATE, &encode_lookup_root_certificate(fingerprint)?).await?;
    decode_lookup_root_certificate_response(&tlv)
}

/// Invoke `RemoveRootCertificate` command on cluster `TLS Certificate Management`.
pub async fn remove_root_certificate(conn: &crate::controller::Connection, endpoint: u16, caid: u8) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_CMD_ID_REMOVEROOTCERTIFICATE, &encode_remove_root_certificate(caid)?).await?;
    Ok(())
}

/// Invoke `ClientCSR` command on cluster `TLS Certificate Management`.
pub async fn client_csr(conn: &crate::controller::Connection, endpoint: u16, nonce: Vec<u8>, ccdid: Option<u8>) -> anyhow::Result<ClientCSRResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_CMD_ID_CLIENTCSR, &encode_client_csr(nonce, ccdid)?).await?;
    decode_client_csr_response(&tlv)
}

/// Invoke `ProvisionClientCertificate` command on cluster `TLS Certificate Management`.
pub async fn provision_client_certificate(conn: &crate::controller::Connection, endpoint: u16, ccdid: u8, client_certificate: Vec<u8>, intermediate_certificates: Vec<Vec<u8>>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_CMD_ID_PROVISIONCLIENTCERTIFICATE, &encode_provision_client_certificate(ccdid, client_certificate, intermediate_certificates)?).await?;
    Ok(())
}

/// Invoke `FindClientCertificate` command on cluster `TLS Certificate Management`.
pub async fn find_client_certificate(conn: &crate::controller::Connection, endpoint: u16, ccdid: Option<u8>) -> anyhow::Result<FindClientCertificateResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_CMD_ID_FINDCLIENTCERTIFICATE, &encode_find_client_certificate(ccdid)?).await?;
    decode_find_client_certificate_response(&tlv)
}

/// Invoke `LookupClientCertificate` command on cluster `TLS Certificate Management`.
pub async fn lookup_client_certificate(conn: &crate::controller::Connection, endpoint: u16, fingerprint: Vec<u8>) -> anyhow::Result<LookupClientCertificateResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_CMD_ID_LOOKUPCLIENTCERTIFICATE, &encode_lookup_client_certificate(fingerprint)?).await?;
    decode_lookup_client_certificate_response(&tlv)
}

/// Invoke `RemoveClientCertificate` command on cluster `TLS Certificate Management`.
pub async fn remove_client_certificate(conn: &crate::controller::Connection, endpoint: u16, ccdid: u8) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_CMD_ID_REMOVECLIENTCERTIFICATE, &encode_remove_client_certificate(ccdid)?).await?;
    Ok(())
}

/// Read `MaxRootCertificates` attribute from cluster `TLS Certificate Management`.
pub async fn read_max_root_certificates(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_ATTR_ID_MAXROOTCERTIFICATES).await?;
    decode_max_root_certificates(&tlv)
}

/// Read `ProvisionedRootCertificates` attribute from cluster `TLS Certificate Management`.
pub async fn read_provisioned_root_certificates(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TLSCert>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_ATTR_ID_PROVISIONEDROOTCERTIFICATES).await?;
    decode_provisioned_root_certificates(&tlv)
}

/// Read `MaxClientCertificates` attribute from cluster `TLS Certificate Management`.
pub async fn read_max_client_certificates(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_ATTR_ID_MAXCLIENTCERTIFICATES).await?;
    decode_max_client_certificates(&tlv)
}

/// Read `ProvisionedClientCertificates` attribute from cluster `TLS Certificate Management`.
pub async fn read_provisioned_client_certificates(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TLSClientCertificateDetail>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TLS_CERTIFICATE_MANAGEMENT, crate::clusters::defs::CLUSTER_TLS_CERTIFICATE_MANAGEMENT_ATTR_ID_PROVISIONEDCLIENTCERTIFICATES).await?;
    decode_provisioned_client_certificates(&tlv)
}