rs-matter 0.2.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
/*
 *
 *    Copyright (c) 2022-2026 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::{self, Debug, Display};
use core::future::Future;
use core::pin::pin;

pub use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};

use embassy_futures::select::{select, Either};

use crate::error::{Error, ErrorCode};

pub mod btp;
pub mod mdns;
pub mod tcp;
pub mod udp;
pub mod wifi;

// Maximum UDP RX packet size per Matter spec
pub const MAX_RX_PACKET_SIZE: usize = 1583;

// Maximum UDP TX packet size per Matter spec
pub const MAX_TX_PACKET_SIZE: usize = 1280 - 40/*IPV6 header size*/ - 8/*UDP header size*/;

// Maximum TCP RX packet size per Matter spec
pub const MAX_RX_LARGE_PACKET_SIZE: usize = 1024 * 1024;

// Maximum TCP TX packet size per Matter spec
pub const MAX_TX_LARGE_PACKET_SIZE: usize = MAX_RX_LARGE_PACKET_SIZE;

/// A Matter service that **this** node advertises (publishes) over a discovery
/// transport such as mDNS.
///
/// This is the *publish-side* identity; the *query-side* analog is
/// [`MatterRemoteService`]. The discovery-transport encoding (e.g. the mDNS
/// `MdnsLocalService` record) lives in the [`mdns`] module
/// (`MatterLocalService::service`).
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum MatterLocalService {
    /// A commissioned Matter service for a particular fabric
    ///
    /// The published name is in the form `<compressed-fabric-id-hex>-<node-id-hex>`.
    Commissioned {
        compressed_fabric_id: u64,
        node_id: u64,
    },
    /// A non-commissioned Matter service
    ///
    /// The published name is in the form `<id-hex>`. The discriminator should be used as an mDNS TXT entry
    Commissionable {
        id: u64,
        /// The discriminator to be communicated over mDNS
        discriminator: u16,
        /// Whether this is an enhanced (ECM) commissioning window (`CM=2`) vs basic (`CM=1`)
        enhanced: bool,
    },
}

/// A Matter service **elsewhere** that this node resolves / looks up over a
/// discovery transport such as mDNS.
///
/// This is the *query-side* analog of the *publish-side* [`MatterLocalService`]:
/// it identifies a single Matter service instance to resolve (SRV/TXT/A/AAAA),
/// rather than describing one to advertise. The discovery-transport encoding
/// (e.g. the mDNS instance name) lives in the [`mdns`] module
/// (`MatterRemoteService::instance_name`).
///
/// Note that *browsing* (enumerating all commissionable or operational nodes)
/// does not need a `MatterRemoteService` - it is a PTR query against the bare
/// service type.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum MatterRemoteService {
    /// A specific operational (commissioned) node.
    ///
    /// The instance name is `<compressed-fabric-id-hex>-<node-id-hex>._matter._tcp.local`.
    Operational {
        compressed_fabric_id: u64,
        node_id: u64,
    },
    /// A specific commissionable instance.
    ///
    /// The instance name is `<id-hex>._matterc._udp.local`.
    Commissionable { id: u64 },
}

/// A Bluetooth address.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct BtAddr(pub [u8; 6]);

impl Display for BtAddr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
            self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]
        )
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for BtAddr {
    fn format(&self, f: defmt::Formatter<'_>) {
        defmt::write!(
            f,
            "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
            self.0[0],
            self.0[1],
            self.0[2],
            self.0[3],
            self.0[4],
            self.0[5]
        )
    }
}

/// An enum representing a network address for all supported protocols by the Matter specification (UDP, TCP and BTP).
#[derive(Eq, PartialEq, Copy, Clone)]
pub enum Address {
    Udp(SocketAddr),
    Tcp(SocketAddr),
    Btp(BtAddr),
}

impl Address {
    pub const fn new() -> Self {
        Self::Udp(SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0))
    }

    pub const fn is_reliable(&self) -> bool {
        matches!(self, Self::Tcp(_) | Self::Btp(_))
    }

    pub const fn is_udp(&self) -> bool {
        matches!(self, Self::Udp(_))
    }

    pub const fn is_tcp(&self) -> bool {
        matches!(self, Self::Tcp(_))
    }

    pub const fn is_btp(&self) -> bool {
        matches!(self, Self::Btp(_))
    }

    /// Return this address with its IP canonicalized: an IPv4-mapped IPv6
    /// address (`::ffff:a.b.c.d`) is rewritten to its true IPv4 form, leaving
    /// genuine IPv4 / IPv6 / BTP addresses unchanged.
    ///
    /// This matters because a dual-stack IPv6 socket reports an IPv4 peer's
    /// packets to `recv_from` in IPv4-mapped form, whereas the same peer is
    /// usually *sent to* (and stored on the session) as a plain `V4` address.
    /// `Address` derives `PartialEq`/`Eq` over the `SocketAddr` (family
    /// included), so without canonicalization `V4(x)` and `V6(::ffff:x)` would
    /// compare unequal and session lookup by peer address would fail (PASE then
    /// reports "PAKE session not found").
    ///
    /// This is used only when *comparing* a session's peer address against a
    /// received one (see `Session::is_for_rx` / `is_pase_for_addr`); the address
    /// stored on the session is left untouched so it still routes replies to the
    /// exact address the peer was reached at.
    pub fn canonical(self) -> Self {
        match self {
            Self::Udp(addr) => Self::Udp(canonical_sockaddr(addr)),
            Self::Tcp(addr) => Self::Tcp(canonical_sockaddr(addr)),
            other => other,
        }
    }

    pub const fn udp(self) -> Option<SocketAddr> {
        match self {
            Self::Udp(addr) => Some(addr),
            _ => None,
        }
    }

    pub const fn tcp(self) -> Option<SocketAddr> {
        match self {
            Self::Tcp(addr) => Some(addr),
            _ => None,
        }
    }

    pub const fn btp(self) -> Option<BtAddr> {
        match self {
            Self::Btp(addr) => Some(addr),
            _ => None,
        }
    }
}

/// Canonicalize a [`SocketAddr`]: an IPv4-mapped IPv6 address
/// (`::ffff:a.b.c.d`) is rewritten to its true IPv4 form (preserving port),
/// everything else is returned unchanged. See [`Address::canonical`].
fn canonical_sockaddr(addr: SocketAddr) -> SocketAddr {
    match addr {
        SocketAddr::V6(v6) => match v6.ip().to_canonical() {
            // `IpAddr::to_canonical` (stable since Rust 1.75) maps
            // `::ffff:a.b.c.d` to `a.b.c.d` and leaves true IPv6 untouched.
            IpAddr::V4(v4) => SocketAddr::new(IpAddr::V4(v4), v6.port()),
            IpAddr::V6(_) => addr,
        },
        SocketAddr::V4(_) => addr,
    }
}

impl Default for Address {
    fn default() -> Self {
        Self::new()
    }
}

impl Display for Address {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Address::Udp(addr) => write!(f, "UDP {}", addr),
            Address::Tcp(addr) => write!(f, "TCP {}", addr),
            Address::Btp(addr) => write!(f, "BTP {}", addr),
        }
    }
}

impl Debug for Address {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Address::Udp(addr) => writeln!(f, "{}", addr),
            Address::Tcp(addr) => writeln!(f, "{}", addr),
            Address::Btp(addr) => writeln!(f, "{:?}", addr),
        }
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for Address {
    fn format(&self, f: defmt::Formatter<'_>) {
        match self {
            Address::Udp(addr) => defmt::write!(f, "UDP {}", addr),
            Address::Tcp(addr) => defmt::write!(f, "TCP {}", addr),
            Address::Btp(addr) => defmt::write!(f, "BTP {}", addr),
        }
    }
}

/// A trait for sending data to a network address.
///
/// All network communication in the Matter transport is packetized (including via TCP and Bluetooth), hence
/// this trait models the sending of a single Matter packet of data to a network address.
///
/// Data packetization is expected to be handled by the implementation of this trait, and is trivial
/// for e.g. the UDP transport which is packetized by default, but more complex for e.g. the TCP transport and especially for BTP.
pub trait NetworkSend {
    /// Send a Matter packet represented as a sequence of bytes (`data`) to the specified address.
    ///
    /// Might return an error if the address is not supported, or if there is a general error on the network interface.
    async fn send_to(&mut self, data: &[u8], addr: Address) -> Result<(), Error>;
}

impl<T> NetworkSend for &mut T
where
    T: NetworkSend,
{
    fn send_to(&mut self, data: &[u8], addr: Address) -> impl Future<Output = Result<(), Error>> {
        (*self).send_to(data, addr)
    }
}

/// A trait for receiving data from a network address.
///
/// All network communication in the Matter transport is packetized (including via TCP and Bluetooth), hence
/// this trait models the receiving of a single Matter packet of data from a network address.
///
/// Data packetization is expected to be handled by the implementation of this trait, and is trivial
/// for e.g. the UDP transport which is packetized by default, but more complex for e.g. the TCP transport and especially for BTP.
pub trait NetworkReceive {
    /// Wait until a data packet is available to be received.
    ///
    /// Allows the Matter transport layer to re-use a single RX buffer accross all network protocol implementatiins.
    ///
    /// Might return an error if there is a general error on the network interface.
    async fn wait_available(&mut self) -> Result<(), Error>;

    /// Receive a single data packet from the network.
    ///
    /// Might return an error if there is a general error on the network interface.
    async fn recv_from(&mut self, buffer: &mut [u8]) -> Result<(usize, Address), Error>;
}

impl<T> NetworkReceive for &mut T
where
    T: NetworkReceive,
{
    fn wait_available(&mut self) -> impl Future<Output = Result<(), Error>> {
        (*self).wait_available()
    }

    fn recv_from(
        &mut self,
        buffer: &mut [u8],
    ) -> impl Future<Output = Result<(usize, Address), Error>> {
        (*self).recv_from(buffer)
    }
}

/// A trait to listen for IPv6 multicast on supported network types
///
/// This is used for listening to groupcast messages
pub trait NetworkMulticast {
    /// Join a multicast group with the specified address.
    async fn join(&mut self, addr: IpAddr) -> Result<(), Error>;

    /// Leave a multicast group with the specified address.
    async fn leave(&mut self, addr: IpAddr) -> Result<(), Error>;
}

impl<T> NetworkMulticast for &mut T
where
    T: NetworkMulticast,
{
    fn join(&mut self, addr: IpAddr) -> impl Future<Output = Result<(), Error>> {
        (*self).join(addr)
    }

    fn leave(&mut self, addr: IpAddr) -> impl Future<Output = Result<(), Error>> {
        (*self).leave(addr)
    }
}

/// A network implementation that does not support any network communication:
/// - Trying to send a packet always results in a `ErrorCode::NoNetworkInterface` error.
/// - Trying to wait/receive a packet pends forever.
/// - Joining/leaving multicast groups is a no-op that always succeeds.
///
/// Useful when chaining multiple network interfaces together to serve as the last network interface in the chain.
pub struct NoNetwork;

impl NetworkSend for NoNetwork {
    async fn send_to(&mut self, _data: &[u8], _addr: Address) -> Result<(), Error> {
        Err(ErrorCode::NoNetworkInterface.into())
    }
}

impl NetworkReceive for NoNetwork {
    async fn wait_available(&mut self) -> Result<(), Error> {
        core::future::pending().await
    }

    async fn recv_from(&mut self, _buffer: &mut [u8]) -> Result<(usize, Address), Error> {
        core::future::pending().await
    }
}

impl NetworkMulticast for NoNetwork {
    async fn join(&mut self, _addr: IpAddr) -> Result<(), Error> {
        Ok(())
    }

    async fn leave(&mut self, _addr: IpAddr) -> Result<(), Error> {
        Ok(())
    }
}

/// A network implementation that chains two network implementations together in a composite network interface.
///
/// This allows for e.g. a network implementation that can send/receive data to/from both a UDP and a TCP network interface - or -
/// with e.g. further chaining - from all of UDP, TCP and BTP network interfaces.
#[derive(Clone)]
pub struct ChainedNetwork<H, T, F> {
    pub handler_can_send: F,
    pub handler: H,
    pub next: T,
}

impl<H, T, F> ChainedNetwork<H, T, F> {
    /// Construct a chained handler that works as follows:
    /// - When a packet is about to be send, the `handler_can_send` function is called with the destination address.
    ///   If it returns `true`, the packet is sent via the `handler` network interface, otherwise it is sent via the `next` network interface.
    /// - When `wait_available` is called, the function waits until a packet is available on either network interface.
    /// - When `recv_from` is called, the function receives a packet from the first network interface that has a packet available.
    pub const fn new(handler_can_send: F, handler: H, next: T) -> Self {
        Self {
            handler_can_send,
            handler,
            next,
        }
    }

    /// Chain itself with another handler.
    ///
    /// The returned chained handler works as follows:
    /// - When a packet is about to be send, the `handler_can_send` function is called with the destination address.
    ///   If it returns `true`, the packet is sent via the `handler` network interface, otherwise it is sent via `self`.
    /// - When `wait_available` is called, the function waits until a packet is available on either network interface.
    /// - When `recv_from` is called, the function receives a packet from the first network interface that has a packet available.
    pub const fn chain<H2, F2>(
        self,
        handler_can_send: F2,
        handler: H2,
    ) -> ChainedNetwork<H2, Self, F2> {
        ChainedNetwork::new(handler_can_send, handler, self)
    }
}

impl<H, T, F> NetworkReceive for ChainedNetwork<H, T, F>
where
    H: NetworkReceive,
    T: NetworkReceive,
{
    async fn wait_available(&mut self) -> Result<(), Error> {
        let mut first = pin!(self.handler.wait_available());
        let mut second = pin!(self.next.wait_available());

        select(&mut first, &mut second).await;

        Ok(())
    }

    async fn recv_from(&mut self, buffer: &mut [u8]) -> Result<(usize, Address), Error> {
        let first = {
            let mut first_available = pin!(self.handler.wait_available());
            let mut second_available = pin!(self.next.wait_available());

            matches!(
                select(&mut first_available, &mut second_available).await,
                Either::First(_)
            )
        };

        if first {
            self.handler.recv_from(buffer).await
        } else {
            self.next.recv_from(buffer).await
        }
    }
}

impl<H, T, F> NetworkSend for ChainedNetwork<H, T, F>
where
    H: NetworkSend,
    T: NetworkSend,
    F: Fn(&Address) -> bool,
{
    async fn send_to(&mut self, data: &[u8], addr: Address) -> Result<(), Error> {
        if (self.handler_can_send)(&addr) {
            self.handler.send_to(data, addr).await
        } else {
            self.next.send_to(data, addr).await
        }
    }
}

impl<H, T, F> NetworkMulticast for ChainedNetwork<H, T, F>
where
    H: NetworkMulticast,
    T: NetworkMulticast,
{
    async fn join(&mut self, addr: IpAddr) -> Result<(), Error> {
        self.handler.join(addr).await?;
        self.next.join(addr).await
    }

    async fn leave(&mut self, addr: IpAddr) -> Result<(), Error> {
        self.handler.leave(addr).await?;
        self.next.leave(addr).await
    }
}