rs-matter-stack 0.2.0

Utility for configuring and running rs-matter
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
use core::future::Future;

use embassy_futures::select::select4;

use rs_matter::crypto::{Crypto, RngCore};
use rs_matter::dm::clusters::gen_comm::CommPolicy;
use rs_matter::dm::clusters::gen_diag::{GenDiag, NetifDiag};
use rs_matter::dm::clusters::net_comm::{DummyNetworks, NetworkType};
use rs_matter::dm::clusters::sw_diag::SwDiag;
use rs_matter::dm::endpoints::{eth_sys_handler, EthSysHandler, ROOT_ENDPOINT_ID};
use rs_matter::dm::networks::wireless::NoopWirelessNetCtl;
use rs_matter::dm::networks::NetChangeNotif;
use rs_matter::dm::{ChainedHandler, DataModel, Endpoint, EpClMatcher};
use rs_matter::error::Error;
use rs_matter::pairing::DiscoveryCapabilities;
use rs_matter::persist::{KvBlobStore, KvBlobStoreAccess};
use rs_matter::root_endpoint;
use rs_matter::transport::network::NoNetwork;
use rs_matter::utils::init::{init, init_from_closure, Init};
use rs_matter::utils::select::Coalesce;

use crate::mdns::Mdns;
use crate::nal::NetStack;
use crate::network::{Embedding, Network};
use crate::private::Sealed;
use crate::{pin_alloc, DummyAttrNotifier, MatterStack, UserTask};

/// An implementation of the `Network` trait for Ethernet.
///
/// Note that "Ethernet" - in the context of this crate - means
/// not just the Ethernet transport, but also any other IP-based transport
/// (like Wifi or Thread), where the Matter stack would not be concerned
/// with the management of the network transport (as in re-connecting to the
/// network on lost signal, managing network credentials and so on).
///
/// The expectation is nevertheless that for production use-cases
/// the `Eth` network would really only be used for Ethernet.
pub struct Eth<E = ()> {
    embedding: E,
}

impl<E> Sealed for Eth<E> {}

impl<E> Network for Eth<E>
where
    E: Embedding,
{
    const INIT: Self = Self { embedding: E::INIT };

    type Embedding<'a>
        = E
    where
        E: 'a;

    // Ethernet does not manage network credentials, so use the no-op networks store.
    type Networks = DummyNetworks;

    const NETWORKS: Self::Networks = DummyNetworks;

    fn init() -> impl Init<Self> {
        init!(Self {
            embedding <- E::init(),
        })
    }

    fn init_networks() -> impl Init<Self::Networks> {
        unsafe {
            init_from_closure(|slot: *mut DummyNetworks| {
                slot.write(DummyNetworks);
                Ok(())
            })
        }
    }

    fn discovery_capabilities(&self) -> DiscoveryCapabilities {
        DiscoveryCapabilities::IP
    }

    fn embedding(&self) -> &Self::Embedding<'_> {
        &self.embedding
    }
}

// A type alias for a Matter stack running over Ethernet.
pub type EthMatterStack<'a, const B: usize, E = ()> = MatterStack<'a, B, Eth<E>>;

/// A trait representing a task that needs access to the operational Ethernet interface
/// (Network stack and Netif) to perform its work.
pub trait EthernetTask {
    /// Run the task with the given network stack, network interface and mDNS
    async fn run<S, N, M>(&mut self, net_stack: S, netif: N, mdns: M) -> Result<(), Error>
    where
        S: NetStack,
        N: NetifDiag + NetChangeNotif,
        M: Mdns;
}

impl<T> EthernetTask for &mut T
where
    T: EthernetTask,
{
    fn run<S, N, M>(
        &mut self,
        net_stack: S,
        netif: N,
        mdns: M,
    ) -> impl Future<Output = Result<(), Error>>
    where
        S: NetStack,
        N: NetifDiag + NetChangeNotif,
        M: Mdns,
    {
        (*self).run(net_stack, netif, mdns)
    }
}

/// A trait for running a task within a context where the ethernet interface is initialized and operable
pub trait Ethernet {
    /// Setup Ethernet and run the given task
    async fn run<T>(&mut self, task: T) -> Result<(), Error>
    where
        T: EthernetTask;
}

impl<T> Ethernet for &mut T
where
    T: Ethernet,
{
    fn run<A>(&mut self, task: A) -> impl Future<Output = Result<(), Error>>
    where
        A: EthernetTask,
    {
        (*self).run(task)
    }
}

/// A utility type for running an ethernet task with a pre-existing ethernet interface
/// rather than bringing up / tearing down the ethernet interface for the task.
pub struct PreexistingEthernet<S, N, M> {
    stack: S,
    netif: N,
    mdns: M,
}

impl<S, N, M> PreexistingEthernet<S, N, M> {
    /// Create a new `PreexistingEthernet` instance with the given network interface, UDP stack and mDNS.
    pub const fn new(stack: S, netif: N, mdns: M) -> Self {
        Self { stack, netif, mdns }
    }
}

impl<S, N, M> Ethernet for PreexistingEthernet<S, N, M>
where
    S: NetStack,
    N: NetifDiag + NetChangeNotif,
    M: Mdns,
{
    async fn run<T>(&mut self, mut task: T) -> Result<(), Error>
    where
        T: EthernetTask,
    {
        task.run(&self.stack, &self.netif, &mut self.mdns).await
    }
}

/// A specialization of the `MatterStack` for Ethernet.
impl<const B: usize, E> MatterStack<'_, B, Eth<E>>
where
    E: Embedding,
{
    /// Return a metadata for the root (Endpoint 0) of the Matter Node
    /// configured for Ethernet network.
    pub const fn root_endpoint() -> Endpoint<'static> {
        const ENDPOINT: Endpoint<'static> = root_endpoint!(eth);

        ENDPOINT
    }

    /// Return a handler for the root (Endpoint 0) of the Matter Node
    /// configured for Ethernet network.
    fn root_handler<'a>(
        &self,
        comm_policy: &'a dyn CommPolicy,
        gen_diag: &'a dyn GenDiag,
        netif_diag: &'a dyn NetifDiag,
        sw_diag: &'a dyn SwDiag,
        rand: impl RngCore + Copy,
    ) -> EthSysHandler<'a> {
        eth_sys_handler(comm_policy, gen_diag, netif_diag, sw_diag, rand)
    }

    /// Reset the Matter instance to the factory defaults by removing all fabrics and basic info settings
    ///
    /// `handler` is the same data model handler that is passed to `run`: the
    /// Interaction Model broadcasts a `FactoryReset` lifecycle op to it, so
    /// cluster handlers owning persisted state of their own can drop it too.
    pub async fn reset<C, H, S>(&mut self, crypto: C, handler: H, store: S) -> Result<(), Error>
    where
        C: Crypto,
        H: DataModel,
        S: KvBlobStore,
    {
        let kv = self.matter.kv(store);

        self.matter.factory_reset(&kv)?;

        // Reset the events counter (and the - no-op for Ethernet - networks store)
        // so we don't carry a stale watermark across a factory reset
        // (Matter Core spec R1.5.1, §7.14.1.1).
        self.im(
            crypto,
            handler,
            &kv,
            NoopWirelessNetCtl::new(NetworkType::Ethernet),
        )
        .factory_reset()
        .await
    }

    /// Run the startup sequence of the stack: re-hydrate the persisted state and
    /// open the basic commissioning window if the device is not commissioned yet.
    ///
    /// This is the `Matter`-level half of the startup (fabrics, basic info, RTC,
    /// sessions). The Interaction Model half - the events watermark, the networks
    /// store and the persisted subscriptions - is re-hydrated by `run`, because
    /// `InteractionModel::startup` has to run on the very Interaction Model
    /// instance that is then run: a resumed subscription borrows that instance's
    /// IM buffers, and constructing an `InteractionModel` clears the
    /// subscriptions table.
    pub async fn startup<C, S>(&mut self, crypto: C, store: S) -> Result<(), Error>
    where
        C: Crypto,
        S: KvBlobStore,
    {
        let kv = self.matter.kv(store);

        self.matter.startup(&kv)?;

        if !self.matter().has_fabrics() {
            info!("Device is not commissioned yet, opening commissioning window...");

            self.open_basic_comm_window(crypto, &DummyAttrNotifier)?;
        } else {
            info!("Device is already commissioned");
        }

        Ok(())
    }

    /// Run the Matter stack for a pre-existing Ethernet network.
    ///
    /// # Arguments
    /// - `net_stack` - a user-provided network stack implementation
    /// - `netif` - a user-provided `Netif` implementation for the Ethernet network
    /// - `mdns` - a user-provided mDNS implementation
    /// - `crypto` - a user-provided crypto implementation
    /// - `handler` - a user-provided DM handler implementation
    /// - `kv` - a user-provided `KvBlobStoreAccess` implementation for loading the persisted state of the stack
    /// - `user` - a user-provided future that will be polled only when the netif interface is up
    #[allow(clippy::too_many_arguments)]
    pub fn run_preex<'t, U, N, M, C, H, K, X>(
        &'t self,
        net_stack: U,
        netif: N,
        mdns: M,
        crypto: C,
        handler: H,
        kv: K,
        user: X,
    ) -> impl Future<Output = Result<(), Error>> + 't
    where
        U: NetStack + 't,
        N: NetifDiag + NetChangeNotif + 't,
        M: Mdns + 't,
        C: Crypto + 't,
        H: DataModel + 't,
        K: KvBlobStoreAccess + 't,
        X: UserTask + 't,
    {
        self.run(
            PreexistingEthernet::new(net_stack, netif, mdns),
            crypto,
            handler,
            kv,
            user,
        )
    }

    /// Run the Matter stack for an Ethernet network.
    ///
    /// # Arguments
    /// - `ethernet` - a user-provided `Ethernet` implementation
    /// - `crypto` - a user-provided crypto implementation
    /// - `handler` - a user-provided DM handler implementation
    /// - `kv` - a user-provided `KvBlobStoreAccess` implementation for loading the persisted state of the stack
    /// - `user` - a user-provided future that will be polled only when the netif interface is up
    pub async fn run<N, C, H, K, X>(
        &self,
        mut ethernet: N,
        crypto: C,
        handler: H,
        kv: K,
        user: X,
    ) -> Result<(), Error>
    where
        N: Ethernet,
        C: Crypto,
        H: DataModel,
        K: KvBlobStoreAccess,
        X: UserTask,
    {
        let _lock = self.run_lock.lock().await;

        info!("Matter Stack memory: {}b", core::mem::size_of_val(self));

        // Since this is the last code executed in the method, resetting the allocator should be safe
        // because all boxes returned by it should be dropped by then
        let _defer = scopeguard::guard((), |_| unsafe {
            self.bump.reset();
        });

        self.matter().reset_transport()?;

        let net_task = pin_alloc!(
            self.bump,
            self.run_ethernet(&mut ethernet, crypto, handler, &kv, user)
        );

        net_task.await
    }

    fn run_ethernet<'t, N, C, H, K, X>(
        &'t self,
        ethernet: &'t mut N,
        crypto: C,
        handler: H,
        kv: K,
        user: X,
    ) -> impl Future<Output = Result<(), Error>> + 't
    where
        N: Ethernet + 't,
        C: Crypto + 't,
        H: DataModel + 't,
        K: KvBlobStoreAccess + 't,
        X: UserTask + 't,
    {
        Ethernet::run(
            ethernet,
            MatterStackEthernetTask {
                stack: self,
                crypto,
                handler,
                kv,
                user_task: user,
            },
        )
    }
}

struct MatterStackEthernetTask<'a, const B: usize, E, C, H, K, X>
where
    E: Embedding,
    C: Crypto,
    H: DataModel,
    K: KvBlobStoreAccess,
    X: UserTask,
{
    stack: &'a MatterStack<'a, B, Eth<E>>,
    crypto: C,
    handler: H,
    kv: K,
    user_task: X,
}

impl<const B: usize, E, C, H, K, X> EthernetTask for MatterStackEthernetTask<'_, B, E, C, H, K, X>
where
    E: Embedding,
    C: Crypto,
    H: DataModel,
    K: KvBlobStoreAccess,
    X: UserTask,
{
    async fn run<N, I, M>(&mut self, net_stack: N, netif: I, mut mdns: M) -> Result<(), Error>
    where
        N: NetStack,
        I: NetifDiag + NetChangeNotif,
        M: Mdns,
    {
        info!("Ethernet driver started");

        // The sys-handler chain (built per phase so per-phase `NetCtl` /
        // diag implementations can vary) covers every cluster on the
        // root endpoint; route anything on EP0 to it, and any other
        // endpoint to the user's handler. `&self.handler` doubles as
        // the `Metadata` provider (`(M, H)` form for `InteractionModel::new`).
        let sys = self
            .stack
            .root_handler(&false, &(), &netif, &(), self.crypto.weak_rand()?);
        let combined = ChainedHandler::new(
            EpClMatcher::new(Some(ROOT_ENDPOINT_ID), None),
            sys,
            &self.handler,
        );
        // Ethernet does not manage networks, so use the inert wireless net-ctl;
        // the engine's connection-manager branch then stays dormant.
        let im = self.stack.im(
            &self.crypto,
            (&self.handler, combined),
            &self.kv,
            NoopWirelessNetCtl::new(NetworkType::Ethernet),
        );

        let mut net_task = pin_alloc!(
            self.stack.bump,
            self.stack.run_oper_net(
                &self.crypto,
                &net_stack,
                0, // TODO
                core::future::pending(),
                Option::<(NoNetwork, NoNetwork)>::None,
            )
        );

        let mut mdns_task = pin_alloc!(
            self.stack.bump,
            self.stack
                .run_oper_netif_mdns(&self.crypto, &net_stack, &netif, &mut mdns)
        );

        let mut im_task = pin_alloc!(self.stack.bump, self.stack.run_im_with_bump(&im));

        let mut user_task = pin_alloc!(self.stack.bump, self.user_task.run(&net_stack, &netif));

        select4(&mut net_task, &mut mdns_task, &mut im_task, &mut user_task)
            .coalesce()
            .await
    }
}