Skip to main content

matter_kit/node/
driver.rs

1//! The whole loop, over the platform traits: a device with sockets and a timer writes none.
2
3use core::future::poll_fn;
4use core::pin::pin;
5use core::task::Poll;
6
7use heapless::Vec;
8
9use super::{AccessList, ChangeLog, Device, EventLog, GroupKeyStore, Notice, Runtime};
10use crate::commissioning::window::WindowStatus;
11use crate::config::{Config, MAX_UDP_MESSAGE};
12use crate::crypto::KeyStore;
13use crate::discovery::advertiser::{Advertiser, OpenWindow};
14use crate::discovery::{CommissioningMode, Responder};
15use crate::im::ClusterHandler;
16use crate::platform::{Duration, Instant, Peer, PeerAddr, Rng, Timer, Udp};
17
18/// The mDNS side of [`Runtime::run`]: the socket bound to 5353, the group answers go to, and
19/// the interface both live on.
20///
21/// The interface index matters twice: it is the link the multicast group is joined on, and the
22/// zone every answer is sent with. `ff02::fb` is link-local, so a send with no interface is
23/// ambiguous and the operating system refuses it.
24#[derive(Debug)]
25pub struct Mdns<'a, M: Udp> {
26    /// The mDNS socket.
27    pub socket: &'a M,
28    /// `ff02::fb` on the interface — [`StdUdp::mdns_group`](crate::platform::os::StdUdp) on std.
29    pub group: PeerAddr,
30    /// The interface index, also used to join groupcast addresses.
31    pub interface: u32,
32}
33
34/// What woke the loop.
35enum Event {
36    Matter(usize, PeerAddr),
37    Mdns(usize),
38    Deadline,
39}
40
41impl<
42    C: Config,
43    const S: usize,
44    const X: usize,
45    const I: usize,
46    const R: usize,
47    const Q: usize,
48    const B: usize,
49> Runtime<C, S, X, I, R, Q, B>
50{
51    /// Runs the node: Matter datagrams, mDNS queries, timers, for ever.
52    ///
53    /// Every iteration does the time-driven work first ([`Runtime::poll`]) and only then waits,
54    /// whichever source woke it. A select that returns the first ready source starves whichever
55    /// it polls last, and both orderings fail: sockets first starves the timer on a link with
56    /// steady mDNS traffic, timer first starves the sockets the moment any deadline is overdue.
57    /// Waiting may prefer the sockets because nothing time-driven happens in it.
58    ///
59    /// `on_notice` hears every [`Notice`], in order.
60    pub async fn run<
61        K,
62        G,
63        H,
64        Ac,
65        Gk,
66        Ev,
67        V,
68        U,
69        M,
70        T,
71        const F: usize,
72        const AF: usize,
73        const A: usize,
74    >(
75        &mut self,
76        device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
77        matter: &U,
78        mdns: Mdns<'_, M>,
79        advertiser: &mut Advertiser<AF, A>,
80        timer: &T,
81        mut on_notice: impl FnMut(Notice),
82    ) -> !
83    where
84        K: KeyStore,
85        G: Rng,
86        H: ClusterHandler,
87        Ac: AccessList,
88        Gk: GroupKeyStore,
89        Ev: EventLog,
90        V: ChangeLog,
91        U: Udp,
92        M: Udp,
93        T: Timer,
94    {
95        let mut matter_buf = [0u8; MAX_UDP_MESSAGE];
96        let mut mdns_buf = [0u8; MAX_UDP_MESSAGE];
97        let mut answer = [0u8; MAX_UDP_MESSAGE];
98        let mut joined: Vec<[u8; 16], 16> = Vec::new();
99        loop {
100            let now = timer.now();
101            self.poll(device, now);
102            self.flush(matter).await;
103            while let Some(notice) = self.notice() {
104                on_notice(notice);
105            }
106            refresh(device, advertiser, now);
107            join_groups(device, matter, mdns.interface, &mut joined);
108
109            let deadline = self
110                .next_deadline(device)
111                .unwrap_or_else(|| now.saturating_add(Duration::from_secs(1)));
112            let event = {
113                let mut from_matter = pin!(matter.recv_from(&mut matter_buf));
114                let mut from_mdns = pin!(mdns.socket.recv_from(&mut mdns_buf));
115                let mut sleep = pin!(timer.sleep_until(deadline));
116                poll_fn(|cx| {
117                    if let Poll::Ready(Ok((n, from))) = from_matter.as_mut().poll(cx) {
118                        return Poll::Ready(Event::Matter(n, from));
119                    }
120                    if let Poll::Ready(Ok((n, _))) = from_mdns.as_mut().poll(cx) {
121                        return Poll::Ready(Event::Mdns(n));
122                    }
123                    if sleep.as_mut().poll(cx).is_ready() {
124                        return Poll::Ready(Event::Deadline);
125                    }
126                    Poll::Pending
127                })
128                .await
129            };
130            match event {
131                Event::Matter(n, from) => {
132                    if let Some(datagram) = matter_buf.get_mut(..n) {
133                        self.receive(device, datagram, Peer::Udp(from), timer.now());
134                    }
135                    self.flush(matter).await;
136                }
137                Event::Mdns(n) => {
138                    // Most traffic on 5353 is other people's; `respond` answers only what is
139                    // asked of this node, and never answers a response (RFC 6762 §6).
140                    let advertisements = advertiser.advertisements();
141                    let responder = Responder::new(&advertisements);
142                    if let Some(query) = mdns_buf.get(..n)
143                        && let Ok((bytes, answered)) = responder.respond(query, &mut answer)
144                        && !answered.is_empty()
145                    {
146                        let _ = mdns.socket.send_to(bytes, mdns.group).await;
147                    }
148                }
149                Event::Deadline => {}
150            }
151        }
152    }
153
154    /// Sends everything queued.
155    async fn flush<U: Udp>(&mut self, matter: &U) {
156        while let Some((peer, bytes)) = self.transmit() {
157            if let Peer::Udp(addr) = peer {
158                // A failed send is a lost datagram; MRP retransmits a reliable one.
159                let _ = matter.send_to(bytes, addr).await;
160            }
161        }
162    }
163}
164
165/// Rebuilds the advertisement set from the fabric table and the window.
166fn refresh<C, K, G, H, Ac, Gk, Ev, V, const F: usize, const AF: usize, const A: usize>(
167    device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
168    advertiser: &mut Advertiser<AF, A>,
169    now: Instant,
170) where
171    C: Config,
172    K: KeyStore,
173    G: Rng,
174    H: ClusterHandler,
175    Ac: AccessList,
176    Gk: GroupKeyStore,
177    Ev: EventLog,
178    V: ChangeLog,
179{
180    let window = device
181        .commissioning
182        .window
183        .borrow()
184        .open(now)
185        .map(|w| OpenWindow {
186            discriminator: w.discriminator,
187            mode: match w.status {
188                WindowStatus::EnhancedOpen => CommissioningMode::Enhanced,
189                _ => CommissioningMode::Basic,
190            },
191        });
192    let fabrics = device.credentials.fabrics.borrow();
193    let operational = fabrics
194        .iter()
195        .map(|f| (f.instance_name(), f.compressed.subtype()));
196    let _ = advertiser.refresh(operational, window);
197}
198
199/// §2.5.6.2: a group is reached at an address derived from the fabric id and the group id, and a
200/// node that never joins it is a node no groupcast reaches. Idempotent per address.
201fn join_groups<C, K, G, H, Ac, Gk, Ev, V, U, const F: usize>(
202    device: &Device<'_, C, K, G, H, Ac, Gk, Ev, V, F>,
203    matter: &U,
204    interface: u32,
205    joined: &mut Vec<[u8; 16], 16>,
206) where
207    C: Config,
208    K: KeyStore,
209    G: Rng,
210    H: ClusterHandler,
211    Ac: AccessList,
212    Gk: GroupKeyStore,
213    Ev: EventLog,
214    V: ChangeLog,
215    U: Udp,
216{
217    let Some(memberships) = device.memberships else {
218        return;
219    };
220    let fabrics = device.credentials.fabrics.borrow();
221    memberships.memberships(&mut |fabric, group, _endpoint| {
222        let Some(fabric_id) = fabrics.find(fabric).map(|f| f.fabric_id) else {
223            return;
224        };
225        let address = crate::group::multicast_address(fabric_id, group).addr;
226        if !joined.contains(&address) && matter.join_multicast(address, interface).is_ok() {
227            let _ = joined.push(address);
228        }
229    });
230}