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
/*
 *
 *    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 core::fmt::{Debug, Formatter};
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};

use crate::interaction_model::core::IMStatusCode;
use crate::interaction_model::messages::ib::{
    AttrPath, AttrResp, AttrStatus, CmdDataTag, CmdPath, CmdStatus, InvResp, InvRespTag,
};
use crate::tlv::UtfStr;
use crate::transport::exchange::Exchange;
use crate::{
    error::{Error, ErrorCode},
    interaction_model::messages::ib::{AttrDataTag, AttrRespTag},
    tlv::{FromTLV, TLVElement, TLVWriter, TagType, ToTLV},
};
use log::error;

use super::{AttrDetails, CmdDetails, DataModelHandler};

// TODO: Should this return an IMStatusCode Error? But if yes, the higher layer
// may have already started encoding the 'success' headers, we might not want to manage
// the tw.rewind() in that case, if we add this support
pub type EncodeValueGen<'a> = &'a dyn Fn(TagType, &mut TLVWriter);

#[derive(Clone)]
/// A structure for encoding various types of values
pub enum EncodeValue<'a> {
    /// This indicates a value that is dynamically generated. This variant
    /// is typically used in the transmit/to-tlv path where we want to encode a value at
    /// run time
    Closure(EncodeValueGen<'a>),
    /// This indicates a value that is in the TLVElement form. this variant is
    /// typically used in the receive/from-tlv path where we don't want to decode the
    /// full value but it can be done at the time of its usage
    Tlv(TLVElement<'a>),
    /// This indicates a static value. This variant is typically used in the transmit/
    /// to-tlv path
    Value(&'a dyn ToTLV),
}

impl<'a> EncodeValue<'a> {
    pub fn unwrap_tlv(self) -> Option<TLVElement<'a>> {
        match self {
            EncodeValue::Tlv(t) => Some(t),
            _ => None,
        }
    }
}

impl<'a> PartialEq for EncodeValue<'a> {
    fn eq(&self, other: &Self) -> bool {
        match self {
            EncodeValue::Closure(_) => {
                error!("PartialEq not yet supported");
                false
            }
            EncodeValue::Tlv(a) => {
                if let EncodeValue::Tlv(b) = other {
                    a == b
                } else {
                    false
                }
            }
            // Just claim false for now
            EncodeValue::Value(_) => {
                error!("PartialEq not yet supported");
                false
            }
        }
    }
}

impl<'a> Debug for EncodeValue<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
        match self {
            EncodeValue::Closure(_) => write!(f, "Contains closure"),
            EncodeValue::Tlv(t) => write!(f, "{:?}", t),
            EncodeValue::Value(_) => write!(f, "Contains EncodeValue"),
        }?;
        Ok(())
    }
}

impl<'a> ToTLV for EncodeValue<'a> {
    fn to_tlv(&self, tw: &mut TLVWriter, tag_type: TagType) -> Result<(), Error> {
        match self {
            EncodeValue::Closure(f) => {
                (f)(tag_type, tw);
                Ok(())
            }
            EncodeValue::Tlv(_) => panic!("This looks invalid"),
            EncodeValue::Value(v) => v.to_tlv(tw, tag_type),
        }
    }
}

impl<'a> FromTLV<'a> for EncodeValue<'a> {
    fn from_tlv(data: &TLVElement<'a>) -> Result<Self, Error> {
        Ok(EncodeValue::Tlv(data.clone()))
    }
}

pub struct AttrDataEncoder<'a, 'b, 'c> {
    dataver_filter: Option<u32>,
    path: AttrPath,
    tw: &'a mut TLVWriter<'b, 'c>,
}

impl<'a, 'b, 'c> AttrDataEncoder<'a, 'b, 'c> {
    pub async fn handle_read<T: DataModelHandler>(
        item: &Result<AttrDetails<'_>, AttrStatus>,
        handler: &T,
        tw: &mut TLVWriter<'_, '_>,
    ) -> Result<bool, Error> {
        let status = match item {
            Ok(attr) => {
                let encoder = AttrDataEncoder::new(attr, tw);

                let result = {
                    #[cfg(not(feature = "nightly"))]
                    {
                        handler.read(attr, encoder)
                    }

                    #[cfg(feature = "nightly")]
                    {
                        handler.read(attr, encoder).await
                    }
                };

                match result {
                    Ok(()) => None,
                    Err(e) => {
                        if e.code() == ErrorCode::NoSpace {
                            return Ok(false);
                        } else {
                            attr.status(e.into())?
                        }
                    }
                }
            }
            Err(status) => Some(status.clone()),
        };

        if let Some(status) = status {
            AttrResp::Status(status).to_tlv(tw, TagType::Anonymous)?;
        }

        Ok(true)
    }

    pub async fn handle_write<T: DataModelHandler>(
        item: &Result<(AttrDetails<'_>, TLVElement<'_>), AttrStatus>,
        handler: &T,
        tw: &mut TLVWriter<'_, '_>,
    ) -> Result<(), Error> {
        let status = match item {
            Ok((attr, data)) => {
                let result = {
                    #[cfg(not(feature = "nightly"))]
                    {
                        handler.write(attr, AttrData::new(attr.dataver, data))
                    }

                    #[cfg(feature = "nightly")]
                    {
                        handler.write(attr, AttrData::new(attr.dataver, data)).await
                    }
                };

                match result {
                    Ok(()) => attr.status(IMStatusCode::Success)?,
                    Err(error) => attr.status(error.into())?,
                }
            }
            Err(status) => Some(status.clone()),
        };

        if let Some(status) = status {
            status.to_tlv(tw, TagType::Anonymous)?;
        }

        Ok(())
    }

    pub fn new(attr: &AttrDetails, tw: &'a mut TLVWriter<'b, 'c>) -> Self {
        Self {
            dataver_filter: attr.dataver,
            path: attr.path(),
            tw,
        }
    }

    pub fn with_dataver(self, dataver: u32) -> Result<Option<AttrDataWriter<'a, 'b, 'c>>, Error> {
        if self
            .dataver_filter
            .map(|dataver_filter| dataver_filter != dataver)
            .unwrap_or(true)
        {
            let mut writer = AttrDataWriter::new(self.tw);

            writer.start_struct(TagType::Anonymous)?;
            writer.start_struct(TagType::Context(AttrRespTag::Data as _))?;
            writer.u32(TagType::Context(AttrDataTag::DataVer as _), dataver)?;
            self.path
                .to_tlv(&mut writer, TagType::Context(AttrDataTag::Path as _))?;

            Ok(Some(writer))
        } else {
            Ok(None)
        }
    }
}

pub struct AttrDataWriter<'a, 'b, 'c> {
    tw: &'a mut TLVWriter<'b, 'c>,
    anchor: usize,
    completed: bool,
}

impl<'a, 'b, 'c> AttrDataWriter<'a, 'b, 'c> {
    pub const TAG: TagType = TagType::Context(AttrDataTag::Data as _);

    fn new(tw: &'a mut TLVWriter<'b, 'c>) -> Self {
        let anchor = tw.get_tail();

        Self {
            tw,
            anchor,
            completed: false,
        }
    }

    pub fn set<T: ToTLV>(self, value: T) -> Result<(), Error> {
        value.to_tlv(self.tw, Self::TAG)?;
        self.complete()
    }

    pub fn complete(mut self) -> Result<(), Error> {
        self.tw.end_container()?;
        self.tw.end_container()?;

        self.completed = true;

        Ok(())
    }

    fn reset(&mut self) {
        self.tw.rewind_to(self.anchor);
    }
}

impl<'a, 'b, 'c> Drop for AttrDataWriter<'a, 'b, 'c> {
    fn drop(&mut self) {
        if !self.completed {
            self.reset();
        }
    }
}

impl<'a, 'b, 'c> Deref for AttrDataWriter<'a, 'b, 'c> {
    type Target = TLVWriter<'b, 'c>;

    fn deref(&self) -> &Self::Target {
        self.tw
    }
}

impl<'a, 'b, 'c> DerefMut for AttrDataWriter<'a, 'b, 'c> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.tw
    }
}

pub struct AttrData<'a> {
    for_dataver: Option<u32>,
    data: &'a TLVElement<'a>,
}

impl<'a> AttrData<'a> {
    pub fn new(for_dataver: Option<u32>, data: &'a TLVElement<'a>) -> Self {
        Self { for_dataver, data }
    }

    pub fn with_dataver(self, dataver: u32) -> Result<&'a TLVElement<'a>, Error> {
        if let Some(req_dataver) = self.for_dataver {
            if req_dataver != dataver {
                Err(ErrorCode::DataVersionMismatch)?;
            }
        }

        Ok(self.data)
    }
}

#[derive(Default)]
pub struct CmdDataTracker {
    skip_status: bool,
}

impl CmdDataTracker {
    pub const fn new() -> Self {
        Self { skip_status: false }
    }

    pub(crate) fn complete(&mut self) {
        self.skip_status = true;
    }

    pub fn needs_status(&self) -> bool {
        !self.skip_status
    }
}

pub struct CmdDataEncoder<'a, 'b, 'c> {
    tracker: &'a mut CmdDataTracker,
    path: CmdPath,
    tw: &'a mut TLVWriter<'b, 'c>,
}

impl<'a, 'b, 'c> CmdDataEncoder<'a, 'b, 'c> {
    pub async fn handle<T: DataModelHandler>(
        item: &Result<(CmdDetails<'_>, TLVElement<'_>), CmdStatus>,
        handler: &T,
        tw: &mut TLVWriter<'_, '_>,
        exchange: &Exchange<'_>,
    ) -> Result<(), Error> {
        let status = match item {
            Ok((cmd, data)) => {
                let mut tracker = CmdDataTracker::new();
                let encoder = CmdDataEncoder::new(cmd, &mut tracker, tw);

                let result = {
                    #[cfg(not(feature = "nightly"))]
                    {
                        handler.invoke(exchange, cmd, data, encoder)
                    }

                    #[cfg(feature = "nightly")]
                    {
                        handler.invoke(exchange, cmd, data, encoder).await
                    }
                };

                match result {
                    Ok(()) => cmd.success(&tracker),
                    Err(error) => {
                        error!("Error invoking command: {}", error);
                        cmd.status(error.into())
                    }
                }
            }
            Err(status) => {
                error!("Error invoking command: {:?}", status);
                Some(status.clone())
            }
        };

        if let Some(status) = status {
            InvResp::Status(status).to_tlv(tw, TagType::Anonymous)?;
        }

        Ok(())
    }

    pub fn new(
        cmd: &CmdDetails,
        tracker: &'a mut CmdDataTracker,
        tw: &'a mut TLVWriter<'b, 'c>,
    ) -> Self {
        Self {
            tracker,
            path: cmd.path(),
            tw,
        }
    }

    pub fn with_command(mut self, cmd: u16) -> Result<CmdDataWriter<'a, 'b, 'c>, Error> {
        let mut writer = CmdDataWriter::new(self.tracker, self.tw);

        writer.start_struct(TagType::Anonymous)?;
        writer.start_struct(TagType::Context(InvRespTag::Cmd as _))?;

        self.path.path.leaf = Some(cmd as _);
        self.path
            .to_tlv(&mut writer, TagType::Context(CmdDataTag::Path as _))?;

        Ok(writer)
    }
}

pub struct CmdDataWriter<'a, 'b, 'c> {
    tracker: &'a mut CmdDataTracker,
    tw: &'a mut TLVWriter<'b, 'c>,
    anchor: usize,
    completed: bool,
}

impl<'a, 'b, 'c> CmdDataWriter<'a, 'b, 'c> {
    pub const TAG: TagType = TagType::Context(CmdDataTag::Data as _);

    fn new(tracker: &'a mut CmdDataTracker, tw: &'a mut TLVWriter<'b, 'c>) -> Self {
        let anchor = tw.get_tail();

        Self {
            tracker,
            tw,
            anchor,
            completed: false,
        }
    }

    pub fn set<T: ToTLV>(self, value: T) -> Result<(), Error> {
        value.to_tlv(self.tw, Self::TAG)?;
        self.complete()
    }

    pub fn complete(mut self) -> Result<(), Error> {
        self.tw.end_container()?;
        self.tw.end_container()?;

        self.completed = true;
        self.tracker.complete();

        Ok(())
    }

    fn reset(&mut self) {
        self.tw.rewind_to(self.anchor);
    }
}

impl<'a, 'b, 'c> Drop for CmdDataWriter<'a, 'b, 'c> {
    fn drop(&mut self) {
        if !self.completed {
            self.reset();
        }
    }
}

impl<'a, 'b, 'c> Deref for CmdDataWriter<'a, 'b, 'c> {
    type Target = TLVWriter<'b, 'c>;

    fn deref(&self) -> &Self::Target {
        self.tw
    }
}

impl<'a, 'b, 'c> DerefMut for CmdDataWriter<'a, 'b, 'c> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.tw
    }
}

#[derive(Copy, Clone, Debug)]
pub struct AttrType<T>(PhantomData<fn() -> T>);

impl<T> AttrType<T> {
    pub const fn new() -> Self {
        Self(PhantomData)
    }

    pub fn encode(&self, writer: AttrDataWriter, value: T) -> Result<(), Error>
    where
        T: ToTLV,
    {
        writer.set(value)
    }

    pub fn decode<'a>(&self, data: &'a TLVElement) -> Result<T, Error>
    where
        T: FromTLV<'a>,
    {
        T::from_tlv(data)
    }
}

impl<T> Default for AttrType<T> {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Copy, Clone, Debug, Default)]
pub struct AttrUtfType;

impl AttrUtfType {
    pub const fn new() -> Self {
        Self
    }

    pub fn encode(&self, writer: AttrDataWriter, value: &str) -> Result<(), Error> {
        writer.set(UtfStr::new(value.as_bytes()))
    }

    pub fn decode<'a>(&self, data: &'a TLVElement) -> Result<&'a str, IMStatusCode> {
        data.str().map_err(|_| IMStatusCode::InvalidDataType)
    }
}

#[allow(unused_macros)]
#[macro_export]
macro_rules! attribute_enum {
    ($en:ty) => {
        impl core::convert::TryFrom<$crate::data_model::objects::AttrId> for $en {
            type Error = $crate::error::Error;

            fn try_from(id: $crate::data_model::objects::AttrId) -> Result<Self, Self::Error> {
                <$en>::from_repr(id)
                    .ok_or_else(|| $crate::error::ErrorCode::AttributeNotFound.into())
            }
        }
    };
}

#[allow(unused_macros)]
#[macro_export]
macro_rules! command_enum {
    ($en:ty) => {
        impl core::convert::TryFrom<$crate::data_model::objects::CmdId> for $en {
            type Error = $crate::error::Error;

            fn try_from(id: $crate::data_model::objects::CmdId) -> Result<Self, Self::Error> {
                <$en>::from_repr(id).ok_or_else(|| $crate::error::ErrorCode::CommandNotFound.into())
            }
        }
    };
}