rs-matter 0.1.0

Native Rust implementation of the Matter (Smart-Home) ecosystem
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
/*
 *
 *    Copyright (c) 2020-2022 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

use crate::{
    data_model::objects::{ClusterId, EndptId},
    error::{Error, ErrorCode},
    tlv::{FromTLV, TLVWriter, TagType, ToTLV},
};

// A generic path with endpoint, clusters, and a leaf
// The leaf could be command, attribute, event
#[derive(Default, Clone, Debug, PartialEq, FromTLV, ToTLV)]
#[tlvargs(datatype = "list")]
pub struct GenericPath {
    pub endpoint: Option<EndptId>,
    pub cluster: Option<ClusterId>,
    pub leaf: Option<u32>,
}

impl GenericPath {
    pub fn new(endpoint: Option<EndptId>, cluster: Option<ClusterId>, leaf: Option<u32>) -> Self {
        Self {
            endpoint,
            cluster,
            leaf,
        }
    }

    /// Returns Ok, if the path is non wildcard, otherwise returns an error
    pub fn not_wildcard(&self) -> Result<(EndptId, ClusterId, u32), Error> {
        match *self {
            GenericPath {
                endpoint: Some(e),
                cluster: Some(c),
                leaf: Some(l),
            } => Ok((e, c, l)),
            _ => Err(ErrorCode::Invalid.into()),
        }
    }
    /// Returns true, if the path is wildcard
    pub fn is_wildcard(&self) -> bool {
        !matches!(
            *self,
            GenericPath {
                endpoint: Some(_),
                cluster: Some(_),
                leaf: Some(_),
            }
        )
    }
}

pub mod msg {

    use crate::{
        error::Error,
        interaction_model::core::IMStatusCode,
        tlv::{FromTLV, TLVArray, TLVWriter, TagType, ToTLV},
    };

    use super::ib::{
        self, AttrData, AttrPath, AttrResp, AttrStatus, CmdData, DataVersionFilter, EventFilter,
        EventPath,
    };

    #[derive(Debug, Default, FromTLV, ToTLV)]
    #[tlvargs(lifetime = "'a")]
    pub struct SubscribeReq<'a> {
        pub keep_subs: bool,
        pub min_int_floor: u16,
        pub max_int_ceil: u16,
        pub attr_requests: Option<TLVArray<'a, AttrPath>>,
        event_requests: Option<TLVArray<'a, EventPath>>,
        event_filters: Option<TLVArray<'a, EventFilter>>,
        // The Context Tags are discontiguous for some reason
        _dummy: Option<bool>,
        pub fabric_filtered: bool,
        pub dataver_filters: Option<TLVArray<'a, DataVersionFilter>>,
    }

    impl<'a> SubscribeReq<'a> {
        pub fn new(fabric_filtered: bool, min_int_floor: u16, max_int_ceil: u16) -> Self {
            Self {
                fabric_filtered,
                min_int_floor,
                max_int_ceil,
                ..Default::default()
            }
        }

        pub fn set_attr_requests(mut self, requests: &'a [AttrPath]) -> Self {
            self.attr_requests = Some(TLVArray::new(requests));
            self
        }
    }

    #[derive(Debug, FromTLV, ToTLV)]
    pub struct SubscribeResp {
        pub subs_id: u32,
        // The Context Tags are discontiguous for some reason
        _dummy: Option<u32>,
        pub max_int: u16,
    }

    impl SubscribeResp {
        pub fn new(subs_id: u32, max_int: u16) -> Self {
            Self {
                subs_id,
                _dummy: None,
                max_int,
            }
        }
    }

    #[derive(FromTLV, ToTLV)]
    pub struct TimedReq {
        pub timeout: u16,
    }

    #[derive(FromTLV, ToTLV)]
    pub struct StatusResp {
        pub status: IMStatusCode,
    }

    pub enum InvReqTag {
        SupressResponse = 0,
        TimedReq = 1,
        InvokeRequests = 2,
    }

    #[derive(FromTLV, ToTLV)]
    #[tlvargs(lifetime = "'a")]
    pub struct InvReq<'a> {
        pub suppress_response: Option<bool>,
        pub timed_request: Option<bool>,
        pub inv_requests: Option<TLVArray<'a, CmdData<'a>>>,
    }

    #[derive(FromTLV, ToTLV, Debug)]
    #[tlvargs(lifetime = "'a")]
    pub struct InvResp<'a> {
        pub suppress_response: Option<bool>,
        pub inv_responses: Option<TLVArray<'a, ib::InvResp<'a>>>,
    }

    // This enum is helpful when we are constructing the response
    // step by step in incremental manner
    pub enum InvRespTag {
        SupressResponse = 0,
        InvokeResponses = 1,
    }

    #[derive(Default, ToTLV, FromTLV, Debug)]
    #[tlvargs(lifetime = "'a")]
    pub struct ReadReq<'a> {
        pub attr_requests: Option<TLVArray<'a, AttrPath>>,
        event_requests: Option<TLVArray<'a, EventPath>>,
        event_filters: Option<TLVArray<'a, EventFilter>>,
        pub fabric_filtered: bool,
        pub dataver_filters: Option<TLVArray<'a, DataVersionFilter>>,
    }

    impl<'a> ReadReq<'a> {
        pub fn new(fabric_filtered: bool) -> Self {
            Self {
                fabric_filtered,
                ..Default::default()
            }
        }

        pub fn set_attr_requests(mut self, requests: &'a [AttrPath]) -> Self {
            self.attr_requests = Some(TLVArray::new(requests));
            self
        }
    }

    #[derive(FromTLV, ToTLV, Debug)]
    #[tlvargs(lifetime = "'a")]
    pub struct WriteReq<'a> {
        pub supress_response: Option<bool>,
        timed_request: Option<bool>,
        pub write_requests: TLVArray<'a, AttrData<'a>>,
        more_chunked: Option<bool>,
    }

    impl<'a> WriteReq<'a> {
        pub fn new(supress_response: bool, write_requests: &'a [AttrData<'a>]) -> Self {
            let mut w = Self {
                supress_response: None,
                write_requests: TLVArray::new(write_requests),
                timed_request: None,
                more_chunked: None,
            };
            if supress_response {
                w.supress_response = Some(true);
            }
            w
        }
    }

    // Report Data
    #[derive(FromTLV, ToTLV, Debug)]
    #[tlvargs(lifetime = "'a")]
    pub struct ReportDataMsg<'a> {
        pub subscription_id: Option<u32>,
        pub attr_reports: Option<TLVArray<'a, AttrResp<'a>>>,
        // TODO
        pub event_reports: Option<bool>,
        pub more_chunks: Option<bool>,
        pub suppress_response: Option<bool>,
    }

    pub enum ReportDataTag {
        SubscriptionId = 0,
        AttributeReports = 1,
        _EventReport = 2,
        MoreChunkedMsgs = 3,
        SupressResponse = 4,
    }

    // Write Response
    #[derive(ToTLV, FromTLV, Debug)]
    #[tlvargs(lifetime = "'a")]
    pub struct WriteResp<'a> {
        pub write_responses: TLVArray<'a, AttrStatus>,
    }

    pub enum WriteRespTag {
        WriteResponses = 0,
    }
}

pub mod ib {
    use core::fmt::Debug;

    use crate::{
        data_model::objects::{AttrDetails, AttrId, ClusterId, CmdId, EncodeValue, EndptId},
        error::{Error, ErrorCode},
        interaction_model::core::IMStatusCode,
        tlv::{FromTLV, Nullable, TLVElement, TLVWriter, TagType, ToTLV},
    };
    use log::error;

    use super::GenericPath;

    // Command Response
    #[derive(Clone, FromTLV, ToTLV, Debug)]
    #[tlvargs(lifetime = "'a")]
    pub enum InvResp<'a> {
        Cmd(CmdData<'a>),
        Status(CmdStatus),
    }

    impl<'a> InvResp<'a> {
        pub fn status_new(cmd_path: CmdPath, status: IMStatusCode, cluster_status: u16) -> Self {
            Self::Status(CmdStatus {
                path: cmd_path,
                status: Status::new(status, cluster_status),
            })
        }
    }

    impl<'a> From<CmdData<'a>> for InvResp<'a> {
        fn from(value: CmdData<'a>) -> Self {
            Self::Cmd(value)
        }
    }

    pub enum InvRespTag {
        Cmd = 0,
        Status = 1,
    }

    impl<'a> From<CmdStatus> for InvResp<'a> {
        fn from(value: CmdStatus) -> Self {
            Self::Status(value)
        }
    }

    #[derive(FromTLV, ToTLV, Clone, PartialEq, Debug)]
    pub struct CmdStatus {
        path: CmdPath,
        status: Status,
    }

    impl CmdStatus {
        pub fn new(path: CmdPath, status: IMStatusCode, cluster_status: u16) -> Self {
            Self {
                path,
                status: Status {
                    status,
                    cluster_status,
                },
            }
        }
    }

    #[derive(Debug, Clone, FromTLV, ToTLV)]
    #[tlvargs(lifetime = "'a")]
    pub struct CmdData<'a> {
        pub path: CmdPath,
        pub data: EncodeValue<'a>,
    }

    impl<'a> CmdData<'a> {
        pub fn new(path: CmdPath, data: EncodeValue<'a>) -> Self {
            Self { path, data }
        }
    }

    pub enum CmdDataTag {
        Path = 0,
        Data = 1,
    }

    // Status
    #[derive(Debug, Clone, PartialEq, FromTLV, ToTLV)]
    pub struct Status {
        pub status: IMStatusCode,
        pub cluster_status: u16,
    }

    impl Status {
        pub fn new(status: IMStatusCode, cluster_status: u16) -> Status {
            Status {
                status,
                cluster_status,
            }
        }
    }

    // Attribute Response
    #[derive(Clone, FromTLV, ToTLV, PartialEq, Debug)]
    #[tlvargs(lifetime = "'a")]
    pub enum AttrResp<'a> {
        Status(AttrStatus),
        Data(AttrData<'a>),
    }

    impl<'a> AttrResp<'a> {
        pub fn unwrap_data(self) -> AttrData<'a> {
            match self {
                AttrResp::Data(d) => d,
                _ => {
                    panic!("No data exists");
                }
            }
        }
    }

    impl<'a> From<AttrData<'a>> for AttrResp<'a> {
        fn from(value: AttrData<'a>) -> Self {
            Self::Data(value)
        }
    }

    impl<'a> From<AttrStatus> for AttrResp<'a> {
        fn from(value: AttrStatus) -> Self {
            Self::Status(value)
        }
    }

    pub enum AttrRespTag {
        Status = 0,
        Data = 1,
    }

    // Attribute Data
    #[derive(Clone, PartialEq, FromTLV, ToTLV, Debug)]
    #[tlvargs(lifetime = "'a")]
    pub struct AttrData<'a> {
        pub data_ver: Option<u32>,
        pub path: AttrPath,
        pub data: EncodeValue<'a>,
    }

    impl<'a> AttrData<'a> {
        pub fn new(data_ver: Option<u32>, path: AttrPath, data: EncodeValue<'a>) -> Self {
            Self {
                data_ver,
                path,
                data,
            }
        }
    }

    pub enum AttrDataTag {
        DataVer = 0,
        Path = 1,
        Data = 2,
    }

    #[derive(Debug)]
    /// Operations on an Interaction Model List
    pub enum ListOperation {
        /// Add (append) an item to the list
        AddItem,
        /// Edit an item from the list
        EditItem(u16),
        /// Delete item from the list
        DeleteItem(u16),
        /// Delete the whole list
        DeleteList,
    }

    /// Attribute Lists in Attribute Data are special. Infer the correct meaning using this function
    pub fn attr_list_write<F>(attr: &AttrDetails, data: &TLVElement, mut f: F) -> Result<(), Error>
    where
        F: FnMut(ListOperation, &TLVElement) -> Result<(), Error>,
    {
        if let Some(Nullable::NotNull(index)) = attr.list_index {
            // If list index is valid,
            //    - this is a modify item or delete item operation
            if data.null().is_ok() {
                // If data is NULL, delete item
                f(ListOperation::DeleteItem(index), data)
            } else {
                f(ListOperation::EditItem(index), data)
            }
        } else if data.confirm_array().is_ok() {
            // If data is list, this is either Delete List or OverWrite List operation
            // in either case, we have to first delete the whole list
            f(ListOperation::DeleteList, data)?;
            // Now the data must be a list, that should be added item by item

            let container = data.enter().ok_or(ErrorCode::Invalid)?;
            for d in container {
                f(ListOperation::AddItem, &d)?;
            }
            Ok(())
        } else {
            // If data is not a list, this must be an add operation
            f(ListOperation::AddItem, data)
        }
    }

    #[derive(Debug, Clone, PartialEq, FromTLV, ToTLV)]
    pub struct AttrStatus {
        path: AttrPath,
        status: Status,
    }

    impl AttrStatus {
        pub fn new(path: &GenericPath, status: IMStatusCode, cluster_status: u16) -> Self {
            Self {
                path: AttrPath::new(path),
                status: super::ib::Status::new(status, cluster_status),
            }
        }
    }

    // Attribute Path
    #[derive(Default, Clone, Debug, PartialEq, FromTLV, ToTLV)]
    #[tlvargs(datatype = "list")]
    pub struct AttrPath {
        pub tag_compression: Option<bool>,
        pub node: Option<u64>,
        pub endpoint: Option<EndptId>,
        pub cluster: Option<ClusterId>,
        pub attr: Option<AttrId>,
        pub list_index: Option<Nullable<u16>>,
    }

    impl AttrPath {
        pub fn new(path: &GenericPath) -> Self {
            Self {
                endpoint: path.endpoint,
                cluster: path.cluster,
                attr: path.leaf.map(|x| x as u16),
                ..Default::default()
            }
        }

        pub fn to_gp(&self) -> GenericPath {
            GenericPath::new(self.endpoint, self.cluster, self.attr.map(|x| x as u32))
        }
    }

    // Command Path
    #[derive(Default, Debug, Clone, PartialEq)]
    pub struct CmdPath {
        pub path: GenericPath,
    }

    #[macro_export]
    macro_rules! cmd_path_ib {
        ($endpoint:literal,$cluster:ident,$command:expr) => {{
            use $crate::interaction_model::messages::{ib::CmdPath, GenericPath};
            CmdPath {
                path: GenericPath {
                    endpoint: Some($endpoint),
                    cluster: Some($cluster),
                    leaf: Some($command as u32),
                },
            }
        }};
    }

    impl CmdPath {
        pub fn new(
            endpoint: Option<EndptId>,
            cluster: Option<ClusterId>,
            command: Option<CmdId>,
        ) -> Self {
            Self {
                path: GenericPath {
                    endpoint,
                    cluster,
                    leaf: command,
                },
            }
        }
    }

    impl FromTLV<'_> for CmdPath {
        fn from_tlv(cmd_path: &TLVElement) -> Result<Self, Error> {
            let c = CmdPath {
                path: GenericPath::from_tlv(cmd_path)?,
            };

            if c.path.leaf.is_none() {
                error!("Wildcard command parameter not supported");
                Err(ErrorCode::CommandNotFound.into())
            } else {
                Ok(c)
            }
        }
    }

    impl ToTLV for CmdPath {
        fn to_tlv(&self, tw: &mut TLVWriter, tag_type: TagType) -> Result<(), Error> {
            self.path.to_tlv(tw, tag_type)
        }
    }

    #[derive(FromTLV, ToTLV, Clone, Debug)]
    pub struct ClusterPath {
        pub node: Option<u64>,
        pub endpoint: EndptId,
        pub cluster: ClusterId,
    }

    #[derive(FromTLV, ToTLV, Clone, Debug)]
    pub struct DataVersionFilter {
        pub path: ClusterPath,
        pub data_ver: u32,
    }

    #[derive(FromTLV, ToTLV, Clone, Debug)]
    #[tlvargs(datatype = "list")]
    pub struct EventPath {
        pub node: Option<u64>,
        pub endpoint: Option<EndptId>,
        pub cluster: Option<ClusterId>,
        pub event: Option<u32>,
        pub is_urgent: Option<bool>,
    }

    #[derive(FromTLV, ToTLV, Clone, Debug)]
    pub struct EventFilter {
        pub node: Option<u64>,
        pub event_min: Option<u64>,
    }
}