matter-kit 0.3.0

Matter (CSA smart-home standard) protocol implementation in Rust: no_std, no-alloc, executor-agnostic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
// Generated by `cargo xtask` from the CSA data model 1.6. Do not edit.
//
// WebRTC Transport Provider โ€” cluster 0x0553.
//
// Regenerate with `cargo xtask clusters --dm <checkout>/data_model/1.6`; `cargo xtask check`
// is the CI gate that keeps this file honest. The XML itself is not vendored here โ€” it
// carries the CSA's own copyright notice and is not redistributable.

//! WebRTC Transport Provider (cluster `0x0553`, revision 2).
//!
//! 8 identifiers, 1 feature bits, and the specification's own conformance for
//! every element. `CLUSTER` is the whole table.

#![allow(unused_imports)]

use crate::dm::conformance::{Clause, Condition, Conform, Conformance};
use crate::dm::meta::{EventPriority, Reporting};
use crate::dm::spec::{Attribute, Cluster, Command, Event, Feature};
use crate::dm::{Access, AccessQualities, AttributeQualities, Privilege};
use crate::error::Result;
use crate::im::{AttributeId, ClusterId, CommandId, EventId};
use crate::tlv::{
    ContainerKind, Element, FromTlv, Nullable, Tag, TlvList, TlvReader, TlvWriter, ToTlv, Value,
};

/// The cluster id.
pub const ID: ClusterId = 0x0553;

/// The highest revision the specification's history defines โ€” what `ClusterRevision`
/// must report (Core ยง7.13.1).
pub const REVISION: u16 = 2;

/// The PICS code, which a certification declaration names the cluster by.
pub const PICS: &str = "WEBRTCP";

/// The `FeatureMap` bits (Core ยง7.13.2).
///
/// A feature has conformance of its own: a device may not claim one the
/// specification forbids it alongside another.
pub mod feature {
    /// Supports metadata transmission in WebRTC sessions
    ///
    /// Code `METADATA`, bit 0.
    pub const METADATA: u32 = 1 << 0;
}

/// Every feature bit, with its conformance.
pub const FEATURES: &[Feature] = &[Feature {
    bit: 0,
    code: "METADATA",
    name: "Metadata",
    conform: Conform {
        clauses: &[
            Clause {
                verdict: Conformance::Provisional,
                when: Condition::Always,
            },
            Clause {
                verdict: Conformance::Optional,
                when: Condition::Always,
            },
        ],
    },
}];

/// The attribute ids.
pub mod attribute {
    use crate::im::AttributeId;

    /// `CurrentSessions`.
    pub const CURRENT_SESSIONS: AttributeId = 0x00;
}

/// The command ids.
pub mod command {
    use crate::im::CommandId;

    /// `SolicitOffer`.
    pub const SOLICIT_OFFER: CommandId = 0x00;
    /// `SolicitOfferResponse`.
    pub const SOLICIT_OFFER_RESPONSE: CommandId = 0x01;
    /// `ProvideOffer`.
    pub const PROVIDE_OFFER: CommandId = 0x02;
    /// `ProvideOfferResponse`.
    pub const PROVIDE_OFFER_RESPONSE: CommandId = 0x03;
    /// `ProvideAnswer`.
    pub const PROVIDE_ANSWER: CommandId = 0x04;
    /// `ProvideICECandidates`.
    pub const PROVIDE_ICE_CANDIDATES: CommandId = 0x05;
    /// `EndSession`.
    pub const END_SESSION: CommandId = 0x06;
}

/// The fields of `SolicitOffer` (command `0x00`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SolicitOfferFields<'a> {
    /// `StreamUsage`, field 0.
    pub stream_usage: crate::clusters::generated::globals::StreamUsageEnum,
    /// `OriginatingEndpointID`, field 1.
    pub originating_endpoint_id: u16,
    /// `VideoStreamID`, field 2.
    pub video_stream_id: Option<Nullable<u16>>,
    /// `AudioStreamID`, field 3.
    pub audio_stream_id: Option<Nullable<u16>>,
    /// `ICEServers`, field 4.
    pub ice_servers: Option<TlvList<'a, crate::clusters::generated::globals::ICEServerStruct<'a>>>,
    /// `ICETransportPolicy`, field 5.
    pub ice_transport_policy: Option<&'a str>,
    /// `MetadataEnabled`, field 6.
    pub metadata_enabled: Option<bool>,
    /// `VideoStreams`, field 8.
    pub video_streams: Option<TlvList<'a, u16>>,
    /// `AudioStreams`, field 9.
    pub audio_streams: Option<TlvList<'a, u16>>,
}

impl<'a> ToTlv for SolicitOfferFields<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.stream_usage.to_tlv(w, Tag::Context(0))?;
        self.originating_endpoint_id.to_tlv(w, Tag::Context(1))?;
        if let Some(value) = &self.video_stream_id {
            value.to_tlv(w, Tag::Context(2))?;
        }
        if let Some(value) = &self.audio_stream_id {
            value.to_tlv(w, Tag::Context(3))?;
        }
        if let Some(value) = &self.ice_servers {
            value.to_tlv(w, Tag::Context(4))?;
        }
        if let Some(value) = &self.ice_transport_policy {
            value.to_tlv(w, Tag::Context(5))?;
        }
        if let Some(value) = &self.metadata_enabled {
            value.to_tlv(w, Tag::Context(6))?;
        }
        if let Some(value) = &self.video_streams {
            value.to_tlv(w, Tag::Context(8))?;
        }
        if let Some(value) = &self.audio_streams {
            value.to_tlv(w, Tag::Context(9))?;
        }
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for SolicitOfferFields<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut stream_usage = None;
        let mut originating_endpoint_id = None;
        let mut video_stream_id = None;
        let mut audio_stream_id = None;
        let mut ice_servers = None;
        let mut ice_transport_policy = None;
        let mut metadata_enabled = None;
        let mut video_streams = None;
        let mut audio_streams = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => {
                    stream_usage = Some(
                        <crate::clusters::generated::globals::StreamUsageEnum>::from_tlv(
                            reader, &field,
                        )?,
                    )
                }
                Some(1) => originating_endpoint_id = Some(<u16>::from_tlv(reader, &field)?),
                Some(2) => video_stream_id = Some(<Nullable<u16>>::from_tlv(reader, &field)?),
                Some(3) => audio_stream_id = Some(<Nullable<u16>>::from_tlv(reader, &field)?),
                Some(4) => {
                    ice_servers = Some(<TlvList<
                        'a,
                        crate::clusters::generated::globals::ICEServerStruct<'a>,
                    >>::from_tlv(reader, &field)?)
                }
                Some(5) => ice_transport_policy = Some(<&'a str>::from_tlv(reader, &field)?),
                Some(6) => metadata_enabled = Some(<bool>::from_tlv(reader, &field)?),
                Some(8) => video_streams = Some(<TlvList<'a, u16>>::from_tlv(reader, &field)?),
                Some(9) => audio_streams = Some(<TlvList<'a, u16>>::from_tlv(reader, &field)?),
                // A field this revision does not define. ยง7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            stream_usage: stream_usage.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            originating_endpoint_id: originating_endpoint_id
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            video_stream_id,
            audio_stream_id,
            ice_servers,
            ice_transport_policy,
            metadata_enabled,
            video_streams,
            audio_streams,
        })
    }
}

/// The fields of `SolicitOfferResponse` (command `0x01`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SolicitOfferResponseFields {
    /// `WebRTCSessionID`, field 0.
    pub web_rtc_session_id: u16,
    /// `DeferredOffer`, field 1.
    pub deferred_offer: bool,
    /// `VideoStreamID`, field 2.
    pub video_stream_id: Option<Nullable<u16>>,
    /// `AudioStreamID`, field 3.
    pub audio_stream_id: Option<Nullable<u16>>,
}

impl ToTlv for SolicitOfferResponseFields {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.web_rtc_session_id.to_tlv(w, Tag::Context(0))?;
        self.deferred_offer.to_tlv(w, Tag::Context(1))?;
        if let Some(value) = &self.video_stream_id {
            value.to_tlv(w, Tag::Context(2))?;
        }
        if let Some(value) = &self.audio_stream_id {
            value.to_tlv(w, Tag::Context(3))?;
        }
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for SolicitOfferResponseFields {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut web_rtc_session_id = None;
        let mut deferred_offer = None;
        let mut video_stream_id = None;
        let mut audio_stream_id = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => web_rtc_session_id = Some(<u16>::from_tlv(reader, &field)?),
                Some(1) => deferred_offer = Some(<bool>::from_tlv(reader, &field)?),
                Some(2) => video_stream_id = Some(<Nullable<u16>>::from_tlv(reader, &field)?),
                Some(3) => audio_stream_id = Some(<Nullable<u16>>::from_tlv(reader, &field)?),
                // A field this revision does not define. ยง7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            web_rtc_session_id: web_rtc_session_id
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            deferred_offer: deferred_offer
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            video_stream_id,
            audio_stream_id,
        })
    }
}

/// The fields of `ProvideOffer` (command `0x02`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ProvideOfferFields<'a> {
    /// `WebRTCSessionID`, field 0.
    pub web_rtc_session_id: Nullable<u16>,
    /// `SDP`, field 1.
    pub sdp: &'a str,
    /// `StreamUsage`, field 2.
    pub stream_usage: Option<crate::clusters::generated::globals::StreamUsageEnum>,
    /// `OriginatingEndpointID`, field 3.
    pub originating_endpoint_id: Option<u16>,
    /// `VideoStreamID`, field 4.
    pub video_stream_id: Option<Nullable<u16>>,
    /// `AudioStreamID`, field 5.
    pub audio_stream_id: Option<Nullable<u16>>,
    /// `ICEServers`, field 6.
    pub ice_servers: Option<TlvList<'a, crate::clusters::generated::globals::ICEServerStruct<'a>>>,
    /// `ICETransportPolicy`, field 7.
    pub ice_transport_policy: Option<&'a str>,
    /// `MetadataEnabled`, field 8.
    pub metadata_enabled: Option<bool>,
    /// `VideoStreams`, field 10.
    pub video_streams: Option<TlvList<'a, u16>>,
    /// `AudioStreams`, field 11.
    pub audio_streams: Option<TlvList<'a, u16>>,
}

impl<'a> ToTlv for ProvideOfferFields<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.web_rtc_session_id.to_tlv(w, Tag::Context(0))?;
        self.sdp.to_tlv(w, Tag::Context(1))?;
        if let Some(value) = &self.stream_usage {
            value.to_tlv(w, Tag::Context(2))?;
        }
        if let Some(value) = &self.originating_endpoint_id {
            value.to_tlv(w, Tag::Context(3))?;
        }
        if let Some(value) = &self.video_stream_id {
            value.to_tlv(w, Tag::Context(4))?;
        }
        if let Some(value) = &self.audio_stream_id {
            value.to_tlv(w, Tag::Context(5))?;
        }
        if let Some(value) = &self.ice_servers {
            value.to_tlv(w, Tag::Context(6))?;
        }
        if let Some(value) = &self.ice_transport_policy {
            value.to_tlv(w, Tag::Context(7))?;
        }
        if let Some(value) = &self.metadata_enabled {
            value.to_tlv(w, Tag::Context(8))?;
        }
        if let Some(value) = &self.video_streams {
            value.to_tlv(w, Tag::Context(10))?;
        }
        if let Some(value) = &self.audio_streams {
            value.to_tlv(w, Tag::Context(11))?;
        }
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for ProvideOfferFields<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut web_rtc_session_id = None;
        let mut sdp = None;
        let mut stream_usage = None;
        let mut originating_endpoint_id = None;
        let mut video_stream_id = None;
        let mut audio_stream_id = None;
        let mut ice_servers = None;
        let mut ice_transport_policy = None;
        let mut metadata_enabled = None;
        let mut video_streams = None;
        let mut audio_streams = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => web_rtc_session_id = Some(<Nullable<u16>>::from_tlv(reader, &field)?),
                Some(1) => sdp = Some(<&'a str>::from_tlv(reader, &field)?),
                Some(2) => {
                    stream_usage = Some(
                        <crate::clusters::generated::globals::StreamUsageEnum>::from_tlv(
                            reader, &field,
                        )?,
                    )
                }
                Some(3) => originating_endpoint_id = Some(<u16>::from_tlv(reader, &field)?),
                Some(4) => video_stream_id = Some(<Nullable<u16>>::from_tlv(reader, &field)?),
                Some(5) => audio_stream_id = Some(<Nullable<u16>>::from_tlv(reader, &field)?),
                Some(6) => {
                    ice_servers = Some(<TlvList<
                        'a,
                        crate::clusters::generated::globals::ICEServerStruct<'a>,
                    >>::from_tlv(reader, &field)?)
                }
                Some(7) => ice_transport_policy = Some(<&'a str>::from_tlv(reader, &field)?),
                Some(8) => metadata_enabled = Some(<bool>::from_tlv(reader, &field)?),
                Some(10) => video_streams = Some(<TlvList<'a, u16>>::from_tlv(reader, &field)?),
                Some(11) => audio_streams = Some(<TlvList<'a, u16>>::from_tlv(reader, &field)?),
                // A field this revision does not define. ยง7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            web_rtc_session_id: web_rtc_session_id
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            sdp: sdp.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            stream_usage,
            originating_endpoint_id,
            video_stream_id,
            audio_stream_id,
            ice_servers,
            ice_transport_policy,
            metadata_enabled,
            video_streams,
            audio_streams,
        })
    }
}

/// The fields of `ProvideOfferResponse` (command `0x03`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ProvideOfferResponseFields {
    /// `WebRTCSessionID`, field 0.
    pub web_rtc_session_id: u16,
    /// `VideoStreamID`, field 1.
    pub video_stream_id: Option<Nullable<u16>>,
    /// `AudioStreamID`, field 2.
    pub audio_stream_id: Option<Nullable<u16>>,
}

impl ToTlv for ProvideOfferResponseFields {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.web_rtc_session_id.to_tlv(w, Tag::Context(0))?;
        if let Some(value) = &self.video_stream_id {
            value.to_tlv(w, Tag::Context(1))?;
        }
        if let Some(value) = &self.audio_stream_id {
            value.to_tlv(w, Tag::Context(2))?;
        }
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for ProvideOfferResponseFields {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut web_rtc_session_id = None;
        let mut video_stream_id = None;
        let mut audio_stream_id = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => web_rtc_session_id = Some(<u16>::from_tlv(reader, &field)?),
                Some(1) => video_stream_id = Some(<Nullable<u16>>::from_tlv(reader, &field)?),
                Some(2) => audio_stream_id = Some(<Nullable<u16>>::from_tlv(reader, &field)?),
                // A field this revision does not define. ยง7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            web_rtc_session_id: web_rtc_session_id
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            video_stream_id,
            audio_stream_id,
        })
    }
}

/// The fields of `ProvideAnswer` (command `0x04`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ProvideAnswerFields<'a> {
    /// `WebRTCSessionID`, field 0.
    pub web_rtc_session_id: u16,
    /// `SDP`, field 1.
    pub sdp: &'a str,
}

impl<'a> ToTlv for ProvideAnswerFields<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.web_rtc_session_id.to_tlv(w, Tag::Context(0))?;
        self.sdp.to_tlv(w, Tag::Context(1))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for ProvideAnswerFields<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut web_rtc_session_id = None;
        let mut sdp = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => web_rtc_session_id = Some(<u16>::from_tlv(reader, &field)?),
                Some(1) => sdp = Some(<&'a str>::from_tlv(reader, &field)?),
                // A field this revision does not define. ยง7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            web_rtc_session_id: web_rtc_session_id
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            sdp: sdp.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `ProvideICECandidates` (command `0x05`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ProvideICECandidatesFields<'a> {
    /// `WebRTCSessionID`, field 0.
    pub web_rtc_session_id: u16,
    /// `ICECandidates`, field 1.
    pub ice_candidates: TlvList<'a, crate::clusters::generated::globals::ICECandidateStruct<'a>>,
}

impl<'a> ToTlv for ProvideICECandidatesFields<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.web_rtc_session_id.to_tlv(w, Tag::Context(0))?;
        self.ice_candidates.to_tlv(w, Tag::Context(1))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for ProvideICECandidatesFields<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut web_rtc_session_id = None;
        let mut ice_candidates = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => web_rtc_session_id = Some(<u16>::from_tlv(reader, &field)?),
                Some(1) => {
                    ice_candidates = Some(<TlvList<
                        'a,
                        crate::clusters::generated::globals::ICECandidateStruct<'a>,
                    >>::from_tlv(reader, &field)?)
                }
                // A field this revision does not define. ยง7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            web_rtc_session_id: web_rtc_session_id
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            ice_candidates: ice_candidates
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// The fields of `EndSession` (command `0x06`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EndSessionFields {
    /// `WebRTCSessionID`, field 0.
    pub web_rtc_session_id: u16,
    /// `Reason`, field 1.
    pub reason: crate::clusters::generated::globals::WebRTCEndReasonEnum,
}

impl ToTlv for EndSessionFields {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.web_rtc_session_id.to_tlv(w, Tag::Context(0))?;
        self.reason.to_tlv(w, Tag::Context(1))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for EndSessionFields {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut web_rtc_session_id = None;
        let mut reason = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => web_rtc_session_id = Some(<u16>::from_tlv(reader, &field)?),
                Some(1) => {
                    reason = Some(
                        <crate::clusters::generated::globals::WebRTCEndReasonEnum>::from_tlv(
                            reader, &field,
                        )?,
                    )
                }
                // A field this revision does not define. ยง7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            web_rtc_session_id: web_rtc_session_id
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            reason: reason.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// Every attribute the specification defines, with its conformance.
pub const ATTRIBUTES: &[Attribute] = &[Attribute {
    id: 0x0000,
    name: "CurrentSessions",
    kind: "list[WebRTCSessionStruct]",
    access: Access::read_only(Privilege::Manage).with_qualities(AccessQualities::FABRIC_SENSITIVE),
    qualities: AttributeQualities::empty(),
    reporting: Reporting::OnChange,
    conform: Conform::MANDATORY,
}];

/// Every command, with its conformance.
pub const COMMANDS: &[Command] = &[
    Command {
        id: 0x00,
        name: "SolicitOffer",
        to_server: true,
        response: Some(0x01),
        access: Access::invoke(Privilege::Operate)
            .with_qualities(AccessQualities::FABRIC_SCOPED.union(AccessQualities::LARGE)),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x01,
        name: "SolicitOfferResponse",
        to_server: false,
        response: None,
        access: Access::invoke(Privilege::Operate).with_qualities(AccessQualities::LARGE),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x02,
        name: "ProvideOffer",
        to_server: true,
        response: Some(0x03),
        access: Access::invoke(Privilege::Operate)
            .with_qualities(AccessQualities::FABRIC_SCOPED.union(AccessQualities::LARGE)),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x03,
        name: "ProvideOfferResponse",
        to_server: false,
        response: None,
        access: Access::invoke(Privilege::Operate).with_qualities(AccessQualities::LARGE),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x04,
        name: "ProvideAnswer",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Operate)
            .with_qualities(AccessQualities::FABRIC_SCOPED.union(AccessQualities::LARGE)),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x05,
        name: "ProvideICECandidates",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Operate)
            .with_qualities(AccessQualities::FABRIC_SCOPED.union(AccessQualities::LARGE)),
        conform: Conform::MANDATORY,
    },
    Command {
        id: 0x06,
        name: "EndSession",
        to_server: true,
        response: None,
        access: Access::invoke(Privilege::Operate)
            .with_qualities(AccessQualities::FABRIC_SCOPED.union(AccessQualities::LARGE)),
        conform: Conform::MANDATORY,
    },
];

/// Every event, with its conformance.
pub const EVENTS: &[Event] = &[];

/// The whole cluster, as the specification defines it.
pub const CLUSTER: Cluster = Cluster {
    id: ID,
    name: "WebRTC Transport Provider",
    revision: REVISION,
    pics: "WEBRTCP",
    derived_from: None,
    features: FEATURES,
    attributes: ATTRIBUTES,
    commands: COMMANDS,
    events: EVENTS,
};