1use crate::inclusion::InclusionState;
6use crate::node::{InterviewStage, NodeRecord, NodeStatus, ProtocolInfo};
7use crate::store::{self, StoreData};
8use crate::values;
9use crate::{Error, Event, NetworkKeys, NodeId};
10use std::collections::{HashMap, HashSet};
11use std::path::PathBuf;
12use std::sync::atomic::{AtomicU32, AtomicU8, AtomicUsize, Ordering};
13use std::sync::{Arc, Mutex};
14use std::time::{Duration, Instant};
15use tokio::sync::{mpsc, oneshot, Notify};
16use tracing::{debug, info, warn};
17use zwave_cc::{multi_channel, supervision, transport_service, wake_up, Command};
18use zwave_security::kex::KeyPair;
19use zwave_security::s0::{S0Manager, S0Payload};
20use zwave_security::s2::{EncryptOptions, KeyId, S2Manager};
21use zwave_security::SecurityClass;
22use zwave_serial::message::{
23 self, tx_options, ApplicationCommand, ApplicationUpdate, ControllerId, ControllerVersion,
24 InitData, NodeProtocolInfo, SendDataResult, SerialApiCapabilities, TransmitStatus,
25};
26use zwave_serial::port::Port;
27use zwave_serial::{DataFrame, FunctionId as F, Request, SerialApi};
28
29pub const MAX_PENDING_EVENTS: usize = 16 * 1024;
31
32#[derive(Debug)]
35pub struct Events {
36 rx: mpsc::UnboundedReceiver<Event>,
37 pending: Arc<AtomicUsize>,
38}
39
40impl Events {
41 pub async fn recv(&mut self) -> Option<Event> {
43 let e = self.rx.recv().await;
44 if e.is_some() {
45 self.pending.fetch_sub(1, Ordering::Relaxed);
46 }
47 e
48 }
49}
50
51pub const MAX_SEND_PAYLOAD: usize = 46;
53
54#[derive(Debug, Clone)]
56pub struct HostConfig {
57 pub store_path: Option<PathBuf>,
59 pub keys: NetworkKeys,
61 pub request_timeout: Duration,
63 pub nonce_timeout: Duration,
65 pub inclusion_timeout: Duration,
67 pub user_timeout: Duration,
69 pub wake_up_interval: u32,
71 pub awake_idle: Duration,
73 pub store_delay: Duration,
75 pub serial: zwave_serial::Config,
77}
78
79impl HostConfig {
80 pub fn new(keys: NetworkKeys, store_path: Option<PathBuf>) -> Self {
82 HostConfig {
83 store_path,
84 keys,
85 request_timeout: Duration::from_secs(5),
86 nonce_timeout: Duration::from_secs(3),
87 inclusion_timeout: Duration::from_secs(60),
88 user_timeout: Duration::from_secs(240),
89 wake_up_interval: 3600,
90 awake_idle: Duration::from_millis(1000),
91 store_delay: Duration::from_secs(1),
92 serial: zwave_serial::Config::default(),
93 }
94 }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Default)]
99pub struct ControllerInfo {
100 pub home_id: u32,
102 pub node_id: NodeId,
104 pub library_version: String,
106 pub library_type: String,
108 pub firmware: String,
110 pub manufacturer_id: u16,
112 pub product_type: u16,
114 pub product_id: u16,
116 pub chip_type: Option<u8>,
118 pub sis: bool,
120 pub secondary: bool,
122 pub region: Option<String>,
124 pub nodes: Vec<NodeId>,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Default)]
130pub struct Topology {
131 pub controller: NodeId,
133 pub nodes: Vec<TopologyNode>,
135}
136
137#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct TopologyNode {
140 pub id: NodeId,
142 pub neighbors: Vec<NodeId>,
144 pub last_route: Option<Vec<NodeId>>,
146 pub last_rssi: Option<i8>,
148 pub listening: bool,
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub(crate) enum RxSecurity {
155 S2(KeyId),
156 S0,
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub(crate) enum TxSecurity {
162 Plain,
163 S2(KeyId),
164 S0 {
165 temp: bool,
166 },
167 Auto,
169}
170
171#[derive(Debug, Clone)]
173pub(crate) enum Inbound {
174 Command {
175 endpoint: u8,
176 command: Command,
177 security: Option<RxSecurity>,
178 },
179 S2Nonce,
180 S0Nonce,
181 NodeInfo(message::NodeInfo),
182 NodeInfoFailed,
183}
184
185type Matcher = Box<dyn Fn(&Inbound) -> bool + Send>;
186
187enum WaiterTx {
188 Once(Option<oneshot::Sender<Inbound>>),
189 Stream(mpsc::UnboundedSender<Inbound>),
190}
191
192impl WaiterTx {
193 fn live(&self) -> bool {
194 match self {
195 WaiterTx::Once(t) => t.is_some(),
196 WaiterTx::Stream(t) => !t.is_closed(),
197 }
198 }
199}
200
201struct Waiter {
202 id: u32,
203 node: NodeId,
204 broadcast: bool,
205 matcher: Matcher,
206 tx: WaiterTx,
207}
208
209pub(crate) struct WaitGuard {
211 inner: Arc<Inner>,
212 id: u32,
213}
214
215impl Drop for WaitGuard {
216 fn drop(&mut self) {
217 if let Ok(mut w) = self.inner.waiters.lock() {
218 w.retain(|w| w.id != self.id);
219 }
220 }
221}
222
223#[derive(Default)]
224pub(crate) struct Runtime {
225 pub(crate) status: NodeStatus,
226 wake_tickets: Vec<oneshot::Sender<()>>,
227 inflight: u32,
228 last_activity: Option<Instant>,
229 sleeper: bool,
230 pub(crate) last_route: Option<(Vec<NodeId>, Option<i8>)>,
231 last_s2: Option<(Vec<u8>, KeyId, Instant)>,
233}
234
235pub(crate) struct Inner {
236 pub(crate) api: SerialApi,
237 pub(crate) cfg: HostConfig,
238 pub(crate) caps: SerialApiCapabilities,
239 pub(crate) info: Mutex<ControllerInfo>,
240 pub(crate) store: Mutex<StoreData>,
241 pub(crate) runtime: Mutex<HashMap<NodeId, Runtime>>,
242 pub(crate) s2: Mutex<S2Manager>,
243 pub(crate) s2_lr: Mutex<S2Manager>,
245 pub(crate) nid: usize,
247 pub(crate) s0: Mutex<S0Manager>,
248 pub(crate) keypair: KeyPair,
249 waiters: Mutex<Vec<Waiter>>,
250 next_waiter: AtomicU32,
251 events: mpsc::UnboundedSender<Event>,
252 pending_events: Arc<AtomicUsize>,
253 dirty: Notify,
254 store_failed: Mutex<Option<String>>,
255 store_io: Arc<Mutex<()>>,
257 node_locks: Mutex<HashMap<NodeId, Arc<tokio::sync::Mutex<()>>>>,
258 reassembler: Mutex<transport_service::Reassembler>,
259 supervision_session: AtomicU8,
260 transport_session: AtomicU8,
261 pub(crate) inclusion: Mutex<InclusionState>,
262 pub(crate) interviews: Mutex<HashSet<NodeId>>,
263}
264
265#[derive(Clone)]
267pub struct Controller {
268 pub(crate) inner: Arc<Inner>,
269}
270
271impl std::fmt::Debug for Controller {
272 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273 let info = self.info();
274 write!(f, "Controller({:08x}, node {})", info.home_id, info.node_id)
275 }
276}
277
278pub(crate) struct Activity {
280 inner: Arc<Inner>,
281 node: NodeId,
282}
283
284impl Drop for Activity {
285 fn drop(&mut self) {
286 if let Ok(mut rt) = self.inner.runtime.lock() {
287 let r = rt.entry(self.node).or_default();
288 r.inflight = r.inflight.saturating_sub(1);
289 r.last_activity = Some(Instant::now());
290 }
291 }
292}
293
294fn region_name(r: message::RfRegion) -> String {
295 format!("{r:?}")
296}
297
298impl Controller {
299 pub async fn start<P: Port>(port: P, cfg: HostConfig) -> Result<(Controller, Events), Error> {
303 let (api, unsolicited) = SerialApi::start(port, cfg.serial.clone());
304 let t = Duration::from_secs(2);
305 let caps = SerialApiCapabilities::parse(
306 &api.request(
307 DataFrame::request(F::GET_SERIAL_API_CAPABILITIES, vec![]),
308 t,
309 )
310 .await?
311 .payload,
312 )
313 .map_err(|e| Error::Controller(e.to_string()))?;
314 let version = ControllerVersion::parse(
315 &api.request(DataFrame::request(F::GET_CONTROLLER_VERSION, vec![]), t)
316 .await?
317 .payload,
318 )
319 .map_err(|e| Error::Controller(e.to_string()))?;
320 let mut nid = 1;
322 if caps.supports(F::SERIAL_API_SETUP) {
323 if let Ok(r) = api
324 .request(
325 DataFrame::request(
326 F::SERIAL_API_SETUP,
327 vec![
328 message::setup::SET_NODE_ID_TYPE,
329 message::setup::NODE_ID_LONG,
330 ],
331 ),
332 t,
333 )
334 .await
335 {
336 if r.payload.first() == Some(&message::setup::SET_NODE_ID_TYPE)
337 && r.payload.get(1).is_some_and(|&b| b != 0)
338 {
339 nid = 2;
340 }
341 }
342 }
343 let id = ControllerId::parse(
344 &api.request(DataFrame::request(F::GET_CONTROLLER_ID, vec![]), t)
345 .await?
346 .payload,
347 nid,
348 )
349 .map_err(|e| Error::Controller(e.to_string()))?;
350 let init = InitData::parse(
351 &api.request(DataFrame::request(F::GET_INIT_DATA, vec![]), t)
352 .await?
353 .payload,
354 )
355 .map_err(|e| Error::Controller(e.to_string()))?;
356 if init.is_end_node() {
357 return Err(Error::Controller(
358 "the device runs the end node API, not a controller".into(),
359 ));
360 }
361 let mut region = None;
362 if caps.supports(F::SERIAL_API_SETUP) {
363 let r = api
364 .request(
365 DataFrame::request(
366 F::SERIAL_API_SETUP,
367 vec![message::setup::SET_TX_STATUS_REPORT, 0xff],
368 ),
369 t,
370 )
371 .await;
372 if let Err(e) = r {
373 warn!("could not enable transmit reports: {e}");
374 }
375 if let Ok(r) = api
376 .request(
377 DataFrame::request(F::SERIAL_API_SETUP, vec![message::setup::GET_RF_REGION]),
378 t,
379 )
380 .await
381 {
382 if r.payload.first() == Some(&message::setup::GET_RF_REGION) {
383 region = r
384 .payload
385 .get(1)
386 .map(|&b| region_name(message::RfRegion::from_u8(b)));
387 }
388 }
389 }
390 let mut sis = init.is_sis();
391 if !init.is_secondary() && caps.supports(F::GET_SUC_NODE_ID) {
392 let suc = api
393 .request(DataFrame::request(F::GET_SUC_NODE_ID, vec![]), t)
394 .await?;
395 if suc.payload.first() == Some(&0) && caps.supports(F::SET_SUC_NODE_ID) {
396 let r = api
398 .request(
399 DataFrame::request(F::SET_SUC_NODE_ID, {
400 let mut v = Vec::new();
401 message::node_bytes(id.node_id, nid, &mut v);
402 v.extend_from_slice(&[0x01, 0x00, 0x01, 0x00]);
403 v
404 }),
405 t,
406 )
407 .await?;
408 sis = r.payload.first() == Some(&1);
409 info!("controller made SIS: {sis}");
410 } else {
411 sis = message::parse_node_id(&suc.payload, nid) == Some(id.node_id);
412 }
413 }
414
415 let mut data = match &cfg.store_path {
416 Some(p) => store::load(p).map_err(Error::Store)?,
417 None => StoreData::default(),
418 };
419 if let (Some(h), Some(p)) = (data.home_id, &cfg.store_path) {
420 if h != id.home_id {
421 let aside = p.with_extension(format!("json.{h:08x}"));
422 warn!(
423 "store {} is for home {h:08x}, the controller is in {:08x}; moving it to {}",
424 p.display(),
425 id.home_id,
426 aside.display()
427 );
428 std::fs::rename(p, &aside).map_err(|e| Error::Store(e.to_string()))?;
429 data = StoreData::default();
430 }
431 }
432 data.home_id = Some(id.home_id);
433 let mut nodes: Vec<NodeId> = init
434 .nodes
435 .iter()
436 .copied()
437 .filter(|&n| n != id.node_id)
438 .collect();
439 if nid == 2 && caps.supports(F::GET_LONG_RANGE_NODES) {
440 for segment in 0..4u8 {
441 let r = api
442 .request(
443 DataFrame::request(F::GET_LONG_RANGE_NODES, vec![segment]),
444 t,
445 )
446 .await?;
447 let (more, _, lr) = message::parse_long_range_nodes(&r.payload)
448 .map_err(|e| Error::Controller(e.to_string()))?;
449 nodes.extend(lr);
450 if !more {
451 break;
452 }
453 }
454 }
455 data.nodes.retain(|n, _| nodes.contains(n));
456 for &n in &nodes {
457 data.nodes.entry(n).or_insert_with(|| NodeRecord::new(n));
458 }
459
460 let mut s2 = S2Manager::new(id.node_id, id.home_id);
461 for class in SecurityClass::HIGHEST_FIRST {
462 s2.set_network_key(class, cfg.keys.key(class));
463 }
464 let mut s2_lr = S2Manager::new(id.node_id, id.home_id);
465 for class in [
466 SecurityClass::S2AccessControl,
467 SecurityClass::S2Authenticated,
468 ] {
469 if let Some(k) = cfg.keys.long_range_key(class) {
470 s2_lr.set_network_key(class, k);
471 }
472 }
473 for (n, r) in &data.nodes {
474 if !r.security.is_empty() {
475 if crate::is_long_range(*n) {
476 s2_lr.set_peer_classes(*n, &r.security);
477 } else {
478 s2.set_peer_classes(*n, &r.security);
479 }
480 }
481 }
482 let s0 = S0Manager::new(id.node_id, &cfg.keys.s0);
483 let keypair = KeyPair::from_private(cfg.keys.ecdh_private);
484 let info = ControllerInfo {
485 home_id: id.home_id,
486 node_id: id.node_id,
487 library_version: version.version.clone(),
488 library_type: version.library_name().to_string(),
489 firmware: format!("{}.{}", caps.firmware_major, caps.firmware_minor),
490 manufacturer_id: caps.manufacturer_id,
491 product_type: caps.product_type,
492 product_id: caps.product_id,
493 chip_type: init.chip_type,
494 sis,
495 secondary: init.is_secondary(),
496 region,
497 nodes: nodes.clone(),
498 };
499 let (etx, erx) = mpsc::unbounded_channel();
500 let pending_events = Arc::new(AtomicUsize::new(0));
501 let erx = Events {
502 rx: erx,
503 pending: pending_events.clone(),
504 };
505 let inner = Arc::new(Inner {
506 api,
507 cfg,
508 caps,
509 info: Mutex::new(info.clone()),
510 store: Mutex::new(data),
511 runtime: Mutex::new(HashMap::new()),
512 s2: Mutex::new(s2),
513 s2_lr: Mutex::new(s2_lr),
514 nid,
515 s0: Mutex::new(s0),
516 keypair,
517 waiters: Mutex::new(Vec::new()),
518 next_waiter: AtomicU32::new(1),
519 events: etx,
520 pending_events,
521 dirty: Notify::new(),
522 store_failed: Mutex::new(None),
523 store_io: Arc::new(Mutex::new(())),
524 node_locks: Mutex::new(HashMap::new()),
525 reassembler: Mutex::new(transport_service::Reassembler::default()),
526 supervision_session: AtomicU8::new(0),
527 transport_session: AtomicU8::new(0),
528 inclusion: Mutex::new(InclusionState::default()),
529 interviews: Mutex::new(HashSet::new()),
530 });
531 let c = Controller { inner };
532 c.mark_dirty();
533 tokio::spawn(c.clone().store_writer());
534 tokio::spawn(c.clone().dispatch(unsolicited));
535 c.emit(Event::Ready(info));
536 for n in nodes {
537 let needs_protocol = c
538 .with_node(n, |r| r.stage < InterviewStage::ProtocolInfo)
539 .unwrap_or(false);
540 if needs_protocol {
541 if let Err(e) = c.fetch_protocol_info(n).await {
542 warn!(node = n, "protocol info: {e}");
543 }
544 }
545 let sleeping = c.with_node(n, |r| r.protocol.sleeping()).unwrap_or(false);
546 c.set_status(
547 n,
548 if sleeping {
549 NodeStatus::Asleep
550 } else {
551 NodeStatus::Unknown
552 },
553 );
554 if c.with_node(n, |r| r.stage < InterviewStage::Complete)
555 .unwrap_or(false)
556 {
557 c.spawn_interview(n);
558 }
559 }
560 c.update_smartstart().await;
561 Ok((c, erx))
562 }
563
564 pub fn info(&self) -> ControllerInfo {
566 self.inner.info.lock().expect("info lock").clone()
567 }
568
569 pub fn serial(&self) -> &SerialApi {
571 &self.inner.api
572 }
573
574 pub fn dsk(&self) -> zwave_security::dsk::Dsk {
576 zwave_security::dsk::Dsk::from_public_key(self.inner.keypair.public())
577 }
578
579 pub fn node(&self, node: NodeId) -> Option<NodeRecord> {
581 self.inner
582 .store
583 .lock()
584 .expect("store lock")
585 .nodes
586 .get(&node)
587 .cloned()
588 }
589
590 pub fn nodes(&self) -> Vec<NodeRecord> {
592 self.inner
593 .store
594 .lock()
595 .expect("store lock")
596 .nodes
597 .values()
598 .cloned()
599 .collect()
600 }
601
602 pub fn status(&self, node: NodeId) -> NodeStatus {
604 self.inner
605 .runtime
606 .lock()
607 .expect("runtime lock")
608 .get(&node)
609 .map(|r| r.status)
610 .unwrap_or_default()
611 }
612
613 pub fn set_name(
615 &self,
616 node: NodeId,
617 name: Option<String>,
618 location: Option<String>,
619 ) -> Result<(), Error> {
620 self.update_node(node, |r| {
621 r.name = name;
622 r.location = location;
623 })?;
624 self.emit(Event::NodeUpdated { node });
625 Ok(())
626 }
627
628 pub fn store_error(&self) -> Option<String> {
630 self.inner.store_failed.lock().expect("lock").clone()
631 }
632
633 pub fn close(&self) -> Result<(), Error> {
638 let flushed = self.flush();
639 self.inner.api.close();
640 flushed
641 }
642
643 pub fn flush(&self) -> Result<(), Error> {
645 let Some(path) = self.inner.cfg.store_path.clone() else {
646 return Ok(());
647 };
648 let _io = self.inner.store_io.lock().expect("store io lock");
649 let data = self.inner.store.lock().expect("store lock").clone();
650 store::save(&path, &data).map_err(Error::Store)
651 }
652
653 pub(crate) fn emit(&self, e: Event) {
654 if self.inner.pending_events.load(Ordering::Relaxed) >= MAX_PENDING_EVENTS {
655 warn!("event dropped, the consumer is not reading events: {e:?}");
656 return;
657 }
658 if self.inner.events.send(e).is_ok() {
659 self.inner.pending_events.fetch_add(1, Ordering::Relaxed);
660 }
661 }
662
663 pub(crate) fn mark_dirty(&self) {
664 self.inner.dirty.notify_one();
665 }
666
667 async fn store_writer(self) {
668 let Some(path) = self.inner.cfg.store_path.clone() else {
669 return;
670 };
671 let weak = Arc::downgrade(&self.inner);
672 drop(self);
673 loop {
674 let Some(inner) = weak.upgrade() else { return };
675 inner.dirty.notified().await;
676 let delay = inner.cfg.store_delay;
677 drop(inner);
678 tokio::time::sleep(delay).await;
679 let Some(inner) = weak.upgrade() else { return };
680 let p = path.clone();
681 let io = inner.store_io.clone();
682 let snapshot = inner.clone();
683 let res = tokio::task::spawn_blocking(move || {
685 let _io = io.lock().expect("store io lock");
686 let data = snapshot.store.lock().expect("store lock").clone();
687 store::save(&p, &data)
688 })
689 .await;
690 let err = match res {
691 Ok(Ok(())) => None,
692 Ok(Err(e)) => Some(e),
693 Err(e) => Some(e.to_string()),
694 };
695 if let Some(e) = &err {
696 warn!("store write failed: {e}");
697 }
698 *inner.store_failed.lock().expect("lock") = err;
699 }
700 }
701
702 pub(crate) fn with_node<T>(&self, node: NodeId, f: impl FnOnce(&NodeRecord) -> T) -> Option<T> {
703 self.inner
704 .store
705 .lock()
706 .expect("store lock")
707 .nodes
708 .get(&node)
709 .map(f)
710 }
711
712 pub(crate) fn update_node(
713 &self,
714 node: NodeId,
715 f: impl FnOnce(&mut NodeRecord),
716 ) -> Result<(), Error> {
717 {
718 let mut s = self.inner.store.lock().expect("store lock");
719 let r = s.nodes.get_mut(&node).ok_or(Error::UnknownNode(node))?;
720 let before = r.clone();
721 f(r);
722 if *r == before {
723 return Ok(());
724 }
725 }
726 self.mark_dirty();
727 Ok(())
728 }
729
730 pub(crate) fn set_status(&self, node: NodeId, status: NodeStatus) {
731 let changed = {
732 let mut rt = self.inner.runtime.lock().expect("runtime lock");
733 let r = rt.entry(node).or_default();
734 let changed = r.status != status;
735 r.status = status;
736 if status == NodeStatus::Awake {
737 for t in r.wake_tickets.drain(..) {
738 let _ = t.send(());
739 }
740 }
741 changed
742 };
743 if changed {
744 self.emit(Event::NodeStatus { node, status });
745 }
746 }
747
748 pub(crate) fn activity(&self, node: NodeId) -> Activity {
749 let mut rt = self.inner.runtime.lock().expect("runtime lock");
750 let r = rt.entry(node).or_default();
751 r.inflight += 1;
752 r.last_activity = Some(Instant::now());
753 Activity {
754 inner: self.inner.clone(),
755 node,
756 }
757 }
758
759 fn node_lock(&self, node: NodeId) -> Arc<tokio::sync::Mutex<()>> {
760 self.inner
761 .node_locks
762 .lock()
763 .expect("lock")
764 .entry(node)
765 .or_default()
766 .clone()
767 }
768
769 pub(crate) fn wait_for(
771 &self,
772 node: NodeId,
773 broadcast: bool,
774 matcher: impl Fn(&Inbound) -> bool + Send + 'static,
775 ) -> (WaitGuard, oneshot::Receiver<Inbound>) {
776 let id = self.inner.next_waiter.fetch_add(1, Ordering::Relaxed);
777 let (tx, rx) = oneshot::channel();
778 self.inner
779 .waiters
780 .lock()
781 .expect("waiters lock")
782 .push(Waiter {
783 id,
784 node,
785 broadcast,
786 matcher: Box::new(matcher),
787 tx: WaiterTx::Once(Some(tx)),
788 });
789 (
790 WaitGuard {
791 inner: self.inner.clone(),
792 id,
793 },
794 rx,
795 )
796 }
797
798 pub(crate) fn subscribe(
800 &self,
801 node: NodeId,
802 matcher: impl Fn(&Inbound) -> bool + Send + 'static,
803 ) -> (WaitGuard, mpsc::UnboundedReceiver<Inbound>) {
804 let id = self.inner.next_waiter.fetch_add(1, Ordering::Relaxed);
805 let (tx, rx) = mpsc::unbounded_channel();
806 self.inner
807 .waiters
808 .lock()
809 .expect("waiters lock")
810 .push(Waiter {
811 id,
812 node,
813 broadcast: false,
814 matcher: Box::new(matcher),
815 tx: WaiterTx::Stream(tx),
816 });
817 (
818 WaitGuard {
819 inner: self.inner.clone(),
820 id,
821 },
822 rx,
823 )
824 }
825
826 fn deliver(&self, node: NodeId, what: Inbound) -> bool {
828 let mut w = self.inner.waiters.lock().expect("waiters lock");
829 let mut taken = false;
830 for waiter in w.iter_mut() {
831 if waiter.node == node && waiter.tx.live() && (waiter.matcher)(&what) {
832 match &mut waiter.tx {
833 WaiterTx::Once(t) => {
834 if let Some(tx) = t.take() {
835 let _ = tx.send(what.clone());
836 }
837 }
838 WaiterTx::Stream(tx) => {
839 let _ = tx.send(what.clone());
840 }
841 }
842 taken = true;
843 if !waiter.broadcast {
844 break;
845 }
846 }
847 }
848 w.retain(|w| w.tx.live());
849 taken
850 }
851
852 async fn dispatch(self, mut rx: mpsc::Receiver<DataFrame>) {
855 while let Some(f) = rx.recv().await {
856 match F(f.function) {
857 F::APPLICATION_COMMAND_HANDLER => {
858 match ApplicationCommand::parse(&f.payload, self.inner.nid) {
859 Ok(ac) => self.on_application_command(ac).await,
860 Err(e) => debug!("{e}"),
861 }
862 }
863 F::BRIDGE_APPLICATION_COMMAND_HANDLER => {
864 match ApplicationCommand::parse_bridge(&f.payload, self.inner.nid) {
865 Ok(ac) => self.on_application_command(ac).await,
866 Err(e) => debug!("{e}"),
867 }
868 }
869 F::APPLICATION_UPDATE => match ApplicationUpdate::parse(&f.payload, self.inner.nid)
870 {
871 Ok(u) => self.on_application_update(u).await,
872 Err(e) => debug!("{e}"),
873 },
874 F::ADD_NODE_TO_NETWORK => self.on_add_node_status(&f.payload),
875 F::REMOVE_NODE_FROM_NETWORK => self.on_remove_node_status(&f.payload),
876 F::REPLACE_FAILED_NODE => self.on_replace_status(&f.payload),
877 F::SERIAL_API_STARTED => warn!("the controller restarted"),
878 other => debug!("unsolicited {other} ignored"),
879 }
880 }
881 debug!("dispatcher stopped");
882 }
883
884 async fn on_application_update(&self, u: ApplicationUpdate) {
885 match u {
886 ApplicationUpdate::NodeInfoReceived { node, info } => {
887 let _ = self.update_node(node, |r| {
888 for cc in &info.supported {
889 r.root_mut().ccs.entry(*cc).or_default();
890 }
891 });
892 if !self.deliver(node, Inbound::NodeInfo(info)) {
893 debug!(node, "unrequested node information");
894 }
895 }
896 ApplicationUpdate::NodeInfoRequestFailed => {
897 let waiting: Vec<NodeId> = self
898 .inner
899 .waiters
900 .lock()
901 .expect("lock")
902 .iter()
903 .map(|w| w.node)
904 .collect();
905 for n in waiting {
906 self.deliver(n, Inbound::NodeInfoFailed);
907 }
908 }
909 ApplicationUpdate::SmartStartHomeIdReceived {
910 nwi_home_id,
911 long_range,
912 ..
913 } => self.on_smartstart_request(nwi_home_id, long_range),
914 ApplicationUpdate::NodeRemoved { node } => self.forget_node(node),
915 other => debug!("application update {other:?}"),
916 }
917 }
918
919 pub(crate) fn forget_node(&self, node: NodeId) {
920 let existed = self
921 .inner
922 .store
923 .lock()
924 .expect("store lock")
925 .nodes
926 .remove(&node)
927 .is_some();
928 self.inner.runtime.lock().expect("lock").remove(&node);
929 self.s2(node).lock().expect("lock").forget_peer(node);
930 {
931 let mut s = self.inner.store.lock().expect("store lock");
932 for e in s.provisioning.entries().to_vec() {
933 if e.node_id == Some(node) {
934 if let Some(m) = s.provisioning.get_mut(&e.dsk) {
935 m.node_id = None;
936 }
937 }
938 }
939 }
940 self.inner
941 .info
942 .lock()
943 .expect("lock")
944 .nodes
945 .retain(|&n| n != node);
946 if existed {
947 self.mark_dirty();
948 self.emit(Event::NodeRemoved { node });
949 }
950 }
951
952 async fn on_application_command(&self, ac: ApplicationCommand) {
954 let node = ac.source;
955 if node == self.info().node_id {
956 return;
957 }
958 if ac.rx_status.multicast() || ac.rx_status.broadcast() {
959 debug!(node, "multicast or broadcast frame");
960 }
961 let mut frame = ac.command;
962 let mut endpoint = 0u8;
963 let mut security: Option<RxSecurity> = None;
964 let mut supervision: Option<(u8, bool)> = None;
965 for _ in 0..8 {
966 let (Some(&cc), cmd) = (frame.first(), frame.get(1).copied()) else {
967 return;
968 };
969 match (cc, cmd) {
970 (transport_service::CC, _) => match transport_service::parse(&frame) {
971 Ok(
972 seg @ (transport_service::Segment::First { .. }
973 | transport_service::Segment::Subsequent { .. }),
974 ) => {
975 let session = match &seg {
976 transport_service::Segment::First { session, .. }
977 | transport_service::Segment::Subsequent { session, .. } => *session,
978 _ => 0,
979 };
980 let r = self.inner.reassembler.lock().expect("lock").push(node, seg);
981 match r {
982 Ok(transport_service::Reassembly::Done(d)) => {
983 self.send_detached(
984 node,
985 transport_service::complete(session),
986 TxSecurity::Plain,
987 );
988 frame = d;
989 continue;
990 }
991 Ok(transport_service::Reassembly::Pending) => return,
992 Err(e) => {
993 debug!(node, "transport service: {e}");
994 return;
995 }
996 }
997 }
998 Ok(other) => {
999 debug!(node, "transport service {other:?}");
1000 return;
1001 }
1002 Err(e) => {
1003 debug!(node, "transport service: {e}");
1004 return;
1005 }
1006 },
1007 (zwave_cc::crc16::CC, Some(0x01)) => match zwave_cc::crc16::decapsulate(&frame) {
1008 Some(inner) => frame = inner.to_vec(),
1009 None => {
1010 debug!(node, "CRC-16 mismatch");
1011 return;
1012 }
1013 },
1014 (0x9f, Some(0x01)) => {
1015 let report = self
1017 .s2(node)
1018 .lock()
1019 .expect("lock")
1020 .nonce_report(node, false);
1021 if let Ok(r) = report {
1022 self.transmit_logged(node, r).await;
1023 }
1024 return;
1025 }
1026 (0x9f, Some(0x02)) => {
1027 let r = self
1028 .s2(node)
1029 .lock()
1030 .expect("lock")
1031 .handle_nonce_report(node, &frame);
1032 match r {
1033 Ok(report) => {
1034 let ours = self.deliver(node, Inbound::S2Nonce);
1035 if !ours && report.sos {
1036 let last = {
1038 let mut rt = self.inner.runtime.lock().expect("lock");
1039 rt.get_mut(&node).and_then(|r| r.last_s2.take())
1040 };
1041 if let Some((bytes, key, at)) = last {
1042 if at.elapsed() < Duration::from_secs(3) {
1043 debug!(node, "re-sending after an S2 resync");
1044 self.send_detached(node, bytes, TxSecurity::S2(key));
1045 }
1046 }
1047 }
1048 }
1049 Err(e) => debug!(node, "nonce report: {e}"),
1050 }
1051 return;
1052 }
1053 (0x9f, Some(0x03)) => {
1054 let r = if ac.rx_status.multicast() {
1055 self.s2(node)
1056 .lock()
1057 .expect("lock")
1058 .decrypt_multicast(node, &frame)
1059 } else {
1060 self.s2(node).lock().expect("lock").decrypt(node, &frame)
1061 };
1062 match r {
1063 Ok(d) => {
1064 security = Some(RxSecurity::S2(d.key));
1065 frame = d.command;
1066 }
1067 Err(zwave_security::Error::Duplicate) => return,
1068 Err(e) => {
1069 debug!(node, "S2 decryption failed: {e}; asking for a resync");
1070 let mos = ac.rx_status.multicast();
1071 let report =
1072 self.s2(node).lock().expect("lock").nonce_report(node, mos);
1073 if let Ok(r) = report {
1074 self.transmit_logged(node, r).await;
1075 }
1076 return;
1077 }
1078 }
1079 }
1080 (0x98, Some(0x40)) => {
1081 let report = self.inner.s0.lock().expect("lock").nonce_report(node);
1082 if let Ok(r) = report {
1083 self.transmit_logged(node, r).await;
1084 }
1085 return;
1086 }
1087 (0x98, Some(0x80)) => {
1088 if self
1089 .inner
1090 .s0
1091 .lock()
1092 .expect("lock")
1093 .handle_nonce_report(node, &frame)
1094 .is_ok()
1095 {
1096 self.deliver(node, Inbound::S0Nonce);
1097 }
1098 return;
1099 }
1100 (0x98, Some(c @ (0x81 | 0xc1))) => {
1101 let r = self
1102 .inner
1103 .s0
1104 .lock()
1105 .expect("lock")
1106 .decapsulate(node, &frame, false);
1107 if c == 0xc1 {
1108 let report = self.inner.s0.lock().expect("lock").nonce_report(node);
1109 if let Ok(r) = report {
1110 self.transmit_logged(node, r).await;
1111 }
1112 }
1113 match r {
1114 Ok(S0Payload::Complete(cmd)) => {
1115 security = Some(RxSecurity::S0);
1116 frame = cmd;
1117 }
1118 Ok(S0Payload::FirstHalf) => return,
1119 Err(e) => {
1120 debug!(node, "S0 decapsulation failed: {e}");
1121 return;
1122 }
1123 }
1124 }
1125 (multi_channel::ID8, Some(multi_channel::CommandEncapsulation::ID)) => {
1126 match multi_channel::CommandEncapsulation::parse(&frame[2..]) {
1127 Ok(e) => {
1128 endpoint = e.source_end_point;
1129 frame = e.command;
1130 }
1131 Err(e) => {
1132 debug!(node, "{e}");
1133 return;
1134 }
1135 }
1136 }
1137 (supervision::ID8, Some(supervision::Get::ID)) => {
1138 match supervision::Get::parse(&frame[2..]) {
1139 Ok(g) => {
1140 supervision = Some((g.session_id, g.status_updates));
1141 frame = g.command;
1142 }
1143 Err(e) => {
1144 debug!(node, "{e}");
1145 return;
1146 }
1147 }
1148 }
1149 _ => break,
1150 }
1151 }
1152 let command = match Command::parse(&frame) {
1153 Ok(c) => c,
1154 Err(e) => {
1155 debug!(node, "{e}");
1156 return;
1157 }
1158 };
1159 let cc = command.cc();
1161 if security.is_none() {
1162 let must_be_secure = self
1163 .with_node(node, |r| {
1164 r.secure_ccs_known
1165 && r.endpoints
1166 .get(&endpoint)
1167 .and_then(|e| e.ccs.get(&cc))
1168 .is_some_and(|s| s.secure)
1169 })
1170 .unwrap_or(false);
1171 if must_be_secure {
1172 warn!(
1173 node,
1174 cc, "dropped a secure command class sent without security"
1175 );
1176 return;
1177 }
1178 }
1179 if let Some((session, _)) = supervision {
1180 let report: Command = supervision::Report {
1181 more_status_updates: false,
1182 wake_up_request: false,
1183 session_id: session,
1184 status: 0xff,
1185 duration: Some(0),
1186 }
1187 .into();
1188 let sec = match security {
1189 Some(RxSecurity::S2(k)) => TxSecurity::S2(k),
1190 Some(RxSecurity::S0) => TxSecurity::S0 { temp: false },
1191 None => TxSecurity::Plain,
1192 };
1193 let bytes = wrap_endpoint(report.encode(), endpoint);
1194 self.send_detached(node, bytes, sec);
1195 }
1196 self.on_command(node, endpoint, command, security, ac.rssi)
1197 .await;
1198 }
1199
1200 async fn on_command(
1201 &self,
1202 node: NodeId,
1203 endpoint: u8,
1204 command: Command,
1205 security: Option<RxSecurity>,
1206 rssi: Option<i8>,
1207 ) {
1208 {
1209 let mut rt = self.inner.runtime.lock().expect("lock");
1210 let r = rt.entry(node).or_default();
1211 r.last_activity = Some(Instant::now());
1212 }
1213 let listening = self
1214 .with_node(node, |r| !r.protocol.sleeping())
1215 .unwrap_or(true);
1216 if listening && self.status(node) != NodeStatus::Alive {
1217 self.set_status(node, NodeStatus::Alive);
1218 }
1219 if let Command::WakeUp(wake_up::Command::Notification(_)) = &command {
1220 self.on_wake_up(node);
1221 }
1222 if let Command::DeviceResetLocally(_) = &command {
1223 warn!(
1224 node,
1225 "the node was reset locally; remove it with remove_failed_node"
1226 );
1227 }
1228 let mut updates = values::from_command(node, endpoint, &command);
1229 for u in &mut updates {
1230 u.rssi = rssi;
1231 }
1232 let taken = self.deliver(
1233 node,
1234 Inbound::Command {
1235 endpoint,
1236 command: command.clone(),
1237 security,
1238 },
1239 );
1240 if updates.is_empty() {
1241 if !taken {
1242 self.emit(Event::Command {
1243 node,
1244 endpoint,
1245 command,
1246 });
1247 }
1248 } else {
1249 for u in updates {
1250 self.emit(Event::Value(u));
1251 }
1252 }
1253 }
1254
1255 fn on_wake_up(&self, node: NodeId) {
1256 self.set_status(node, NodeStatus::Awake);
1257 let start = {
1258 let mut rt = self.inner.runtime.lock().expect("lock");
1259 let r = rt.entry(node).or_default();
1260 r.last_activity = Some(Instant::now());
1261 !std::mem::replace(&mut r.sleeper, true)
1262 };
1263 if start {
1264 tokio::spawn(self.clone().sleeper(node));
1265 }
1266 }
1267
1268 async fn sleeper(self, node: NodeId) {
1270 let idle = self.inner.cfg.awake_idle;
1271 loop {
1272 tokio::time::sleep(idle / 2).await;
1273 let ready = {
1274 let rt = self.inner.runtime.lock().expect("lock");
1275 let Some(r) = rt.get(&node) else { return };
1276 r.inflight == 0
1277 && r.wake_tickets.is_empty()
1278 && r.last_activity.is_none_or(|t| t.elapsed() >= idle)
1279 };
1280 if ready {
1281 break;
1282 }
1283 }
1284 let nmi: Command = wake_up::NoMoreInformation {}.into();
1285 if let Err(e) = self.send_now(node, 0, &nmi).await {
1286 debug!(node, "No More Information: {e}");
1287 }
1288 {
1289 let mut rt = self.inner.runtime.lock().expect("lock");
1290 if let Some(r) = rt.get_mut(&node) {
1291 r.sleeper = false;
1292 }
1293 }
1294 self.set_status(node, NodeStatus::Asleep);
1295 }
1296
1297 pub(crate) fn assume_awake(&self, node: NodeId) {
1299 if self
1300 .with_node(node, |r| r.protocol.sleeping())
1301 .unwrap_or(false)
1302 {
1303 self.on_wake_up(node);
1304 } else {
1305 self.set_status(node, NodeStatus::Alive);
1306 }
1307 }
1308
1309 fn send_detached(&self, node: NodeId, bytes: Vec<u8>, sec: TxSecurity) {
1313 let c = self.clone();
1314 tokio::spawn(async move {
1315 if let Err(e) = c.send_bytes(node, bytes, sec).await {
1316 debug!(node, "reply not sent: {e}");
1317 }
1318 });
1319 }
1320
1321 async fn transmit_logged(&self, node: NodeId, frame: Vec<u8>) {
1322 if let Err(e) = self.transmit(node, frame).await {
1323 debug!(node, "transmit: {e}");
1324 }
1325 }
1326
1327 pub(crate) async fn transmit(&self, node: NodeId, frame: Vec<u8>) -> Result<(), Error> {
1329 if frame.len() > MAX_SEND_PAYLOAD {
1330 let session = self.inner.transport_session.fetch_add(1, Ordering::Relaxed) & 0x0f;
1331 for seg in
1332 transport_service::segment(&frame, session, transport_service::DEFAULT_SEGMENT)
1333 {
1334 self.send_data(node, seg).await?;
1335 }
1336 return Ok(());
1337 }
1338 self.send_data(node, frame).await
1339 }
1340
1341 async fn send_data(&self, node: NodeId, frame: Vec<u8>) -> Result<(), Error> {
1342 let api = &self.inner.api;
1343 let cb = api.next_callback_id();
1344 let req = Request::with_callback(
1345 message::send_data(
1346 node,
1347 self.inner.nid,
1348 &frame,
1349 if crate::is_long_range(node) {
1350 tx_options::ACK
1351 } else {
1352 tx_options::DEFAULT
1353 },
1354 cb,
1355 ),
1356 Duration::from_secs(10),
1357 cb,
1358 Duration::from_secs(65),
1359 );
1360 let ex = api.execute(req).await?;
1361 let resp = ex
1362 .response
1363 .ok_or(Error::Controller("no SendData response".into()))?;
1364 if resp.payload.first() != Some(&1) {
1365 return Err(Error::TransmitFailed(
1366 node,
1367 "controller refused SendData".into(),
1368 ));
1369 }
1370 let cbf = ex
1371 .callback
1372 .ok_or(Error::Controller("no SendData callback".into()))?;
1373 let res =
1374 SendDataResult::parse(&cbf.payload).map_err(|e| Error::Controller(e.to_string()))?;
1375 let listening = self
1376 .with_node(node, |r| !r.protocol.sleeping())
1377 .unwrap_or(true);
1378 match res.status {
1379 TransmitStatus::Ok => {
1380 if let Some(rep) = res.report {
1381 self.on_route(node, rep.repeaters, rep.ack_rssi);
1382 }
1383 if listening && self.status(node) == NodeStatus::Dead {
1384 self.set_status(node, NodeStatus::Alive);
1385 }
1386 Ok(())
1387 }
1388 TransmitStatus::NoAck => {
1389 if listening {
1390 self.set_status(node, NodeStatus::Dead);
1391 } else {
1392 self.set_status(node, NodeStatus::Asleep);
1393 }
1394 Err(Error::NoAck(node))
1395 }
1396 s => Err(Error::TransmitFailed(node, format!("{s:?}"))),
1397 }
1398 }
1399
1400 fn on_route(&self, node: NodeId, repeaters: Vec<NodeId>, rssi: Option<i8>) {
1401 let changed = {
1402 let mut rt = self.inner.runtime.lock().expect("lock");
1403 let r = rt.entry(node).or_default();
1404 let changed = r
1405 .last_route
1406 .as_ref()
1407 .map(|(rep, _)| rep != &repeaters)
1408 .unwrap_or(true);
1409 r.last_route = Some((repeaters.clone(), rssi));
1410 changed
1411 };
1412 if changed {
1413 self.emit(Event::Route {
1414 node,
1415 repeaters,
1416 rssi,
1417 });
1418 }
1419 }
1420
1421 fn resolve(&self, node: NodeId, endpoint: u8, cc: u16, sec: TxSecurity) -> TxSecurity {
1423 if sec != TxSecurity::Auto {
1424 return sec;
1425 }
1426 let Some((needs, s2, s0)) = self.with_node(node, |r| {
1427 (r.needs_security(endpoint, cc), r.highest_s2(), r.s0_only())
1428 }) else {
1429 return TxSecurity::Plain;
1430 };
1431 match (needs, s2, s0) {
1432 (true, Some(c), _) => TxSecurity::S2(KeyId::Class(c)),
1433 (true, None, true) => TxSecurity::S0 { temp: false },
1434 _ => TxSecurity::Plain,
1435 }
1436 }
1437
1438 pub(crate) async fn send_bytes(
1441 &self,
1442 node: NodeId,
1443 bytes: Vec<u8>,
1444 sec: TxSecurity,
1445 ) -> Result<(), Error> {
1446 let lock = self.node_lock(node);
1447 let _g = lock.lock().await;
1448 match sec {
1449 TxSecurity::Plain | TxSecurity::Auto => self.transmit(node, bytes).await,
1450 TxSecurity::S2(key) => {
1451 let frame = self.s2_encrypt(node, &bytes, key).await?;
1452 {
1453 let mut rt = self.inner.runtime.lock().expect("lock");
1454 rt.entry(node).or_default().last_s2 = Some((bytes, key, Instant::now()));
1455 }
1456 self.transmit(node, frame).await
1457 }
1458 TxSecurity::S0 { temp } => self.s0_send(node, &bytes, temp).await,
1459 }
1460 }
1461
1462 async fn s2_encrypt(&self, node: NodeId, bytes: &[u8], key: KeyId) -> Result<Vec<u8>, Error> {
1463 for attempt in 0..3 {
1464 let r = self.s2(node).lock().expect("lock").encrypt(
1465 node,
1466 bytes,
1467 &EncryptOptions {
1468 key: Some(key),
1469 ..Default::default()
1470 },
1471 );
1472 match r {
1473 Ok(f) => return Ok(f),
1474 Err(zwave_security::Error::NoSpan) if attempt < 2 => {
1475 let (_g, rx) = self.wait_for(node, true, |i| matches!(i, Inbound::S2Nonce));
1476 let get = self
1477 .s2(node)
1478 .lock()
1479 .expect("lock")
1480 .nonce_get(node)
1481 .map_err(|e| Error::Security(e.to_string()))?;
1482 self.transmit(node, get).await?;
1483 tokio::time::timeout(self.inner.cfg.nonce_timeout, rx)
1484 .await
1485 .map_err(|_| Error::Timeout(node))?
1486 .map_err(|_| Error::Stopped)?;
1487 }
1488 Err(e) => return Err(Error::Security(e.to_string())),
1489 }
1490 }
1491 Err(Error::Security("no S2 nonce".into()))
1492 }
1493
1494 async fn s0_nonce(&self, node: NodeId) -> Result<(), Error> {
1495 let (_g, rx) = self.wait_for(node, true, |i| matches!(i, Inbound::S0Nonce));
1496 self.transmit(node, S0Manager::nonce_get()).await?;
1497 tokio::time::timeout(self.inner.cfg.nonce_timeout, rx)
1498 .await
1499 .map_err(|_| Error::Timeout(node))?
1500 .map_err(|_| Error::Stopped)?;
1501 Ok(())
1502 }
1503
1504 async fn s0_send(&self, node: NodeId, bytes: &[u8], temp: bool) -> Result<(), Error> {
1505 let parts = match self.inner.s0.lock().expect("lock").split(bytes) {
1506 Some(p) => p.to_vec(),
1507 None => vec![(bytes.to_vec(), 0u8)],
1508 };
1509 let n = parts.len();
1510 let mut have_nonce = false;
1511 for (i, (part, control)) in parts.into_iter().enumerate() {
1512 let more = i + 1 < n;
1513 if !have_nonce {
1514 self.s0_nonce(node).await?;
1515 }
1516 let next = if more {
1518 Some(self.wait_for(node, true, |i| matches!(i, Inbound::S0Nonce)))
1519 } else {
1520 None
1521 };
1522 let frame = self
1523 .inner
1524 .s0
1525 .lock()
1526 .expect("lock")
1527 .encapsulate_part(node, &part, control, temp, more)
1528 .map_err(|e| Error::Security(e.to_string()))?;
1529 self.transmit(node, frame).await?;
1530 if let Some((_g, rx)) = next {
1531 tokio::time::timeout(self.inner.cfg.nonce_timeout, rx)
1532 .await
1533 .map_err(|_| Error::Timeout(node))?
1534 .map_err(|_| Error::Stopped)?;
1535 have_nonce = true;
1536 }
1537 }
1538 Ok(())
1539 }
1540
1541 pub(crate) async fn wait_awake(&self, node: NodeId) {
1543 let rx = {
1544 let sleeping = self
1545 .with_node(node, |r| r.protocol.sleeping())
1546 .unwrap_or(false);
1547 let mut rt = self.inner.runtime.lock().expect("lock");
1548 let r = rt.entry(node).or_default();
1549 if !sleeping || r.status == NodeStatus::Awake {
1550 return;
1551 }
1552 let (tx, rx) = oneshot::channel();
1553 r.wake_tickets.push(tx);
1554 rx
1555 };
1556 debug!(node, "waiting for the node to wake up");
1557 let _ = rx.await;
1558 }
1559
1560 pub(crate) async fn send_encoded(
1563 &self,
1564 node: NodeId,
1565 endpoint: u8,
1566 cc: u16,
1567 bytes: Vec<u8>,
1568 ) -> Result<(), Error> {
1569 let sec = self.resolve(node, endpoint, cc, TxSecurity::Auto);
1570 self.send_bytes(node, wrap_endpoint(bytes, endpoint), sec)
1571 .await
1572 }
1573
1574 pub(crate) async fn send_now(
1576 &self,
1577 node: NodeId,
1578 endpoint: u8,
1579 cmd: &Command,
1580 ) -> Result<(), Error> {
1581 let sec = self.resolve(node, endpoint, cmd.cc(), TxSecurity::Auto);
1582 self.send_bytes(node, wrap_endpoint(cmd.encode(), endpoint), sec)
1583 .await
1584 }
1585
1586 pub async fn send(&self, node: NodeId, endpoint: u8, cmd: &Command) -> Result<(), Error> {
1589 self.with_node(node, |_| ())
1590 .ok_or(Error::UnknownNode(node))?;
1591 let _a = self.activity(node);
1592 self.wait_awake(node).await;
1593 self.send_now(node, endpoint, cmd).await
1594 }
1595
1596 pub async fn send_supervised(
1599 &self,
1600 node: NodeId,
1601 endpoint: u8,
1602 cmd: &Command,
1603 ) -> Result<u8, Error> {
1604 let session = self
1605 .inner
1606 .supervision_session
1607 .fetch_add(1, Ordering::Relaxed)
1608 & 0x3f;
1609 let get: Command = supervision::Get {
1610 status_updates: false,
1611 session_id: session,
1612 command: cmd.encode(),
1613 }
1614 .into();
1615 let reply = self
1616 .request_with(node, endpoint, get, cmd.cc(), self.inner.cfg.request_timeout, move |c| {
1617 matches!(c, Command::Supervision(supervision::Command::Report(r)) if r.session_id == session)
1618 })
1619 .await?;
1620 let Command::Supervision(supervision::Command::Report(r)) = reply else {
1621 unreachable!()
1622 };
1623 match r.status {
1624 0xff | 0x01 => Ok(r.status),
1625 0x00 => Err(Error::Controller(format!(
1626 "node {node} does not support the command"
1627 ))),
1628 _ => Err(Error::Controller(format!("node {node} failed the command"))),
1629 }
1630 }
1631
1632 pub async fn request(
1634 &self,
1635 node: NodeId,
1636 endpoint: u8,
1637 cmd: Command,
1638 expect: impl Fn(&Command) -> bool + Send + Sync + 'static,
1639 ) -> Result<Command, Error> {
1640 let cc = cmd.cc();
1641 self.request_with(
1642 node,
1643 endpoint,
1644 cmd,
1645 cc,
1646 self.inner.cfg.request_timeout,
1647 expect,
1648 )
1649 .await
1650 }
1651
1652 pub(crate) async fn req<T: Send + 'static>(
1654 &self,
1655 node: NodeId,
1656 endpoint: u8,
1657 cmd: impl Into<Command>,
1658 f: impl Fn(&Command) -> Option<T> + Send + Sync + 'static,
1659 ) -> Result<T, Error> {
1660 let f = Arc::new(f);
1661 let m = f.clone();
1662 let c = self
1663 .request(node, endpoint, cmd.into(), move |c| m(c).is_some())
1664 .await?;
1665 Ok(f(&c).expect("matched"))
1666 }
1667
1668 async fn request_with(
1669 &self,
1670 node: NodeId,
1671 endpoint: u8,
1672 cmd: Command,
1673 security_cc: u16,
1674 timeout: Duration,
1675 expect: impl Fn(&Command) -> bool + Send + Sync + 'static,
1676 ) -> Result<Command, Error> {
1677 self.with_node(node, |_| ())
1678 .ok_or(Error::UnknownNode(node))?;
1679 let _a = self.activity(node);
1680 self.wait_awake(node).await;
1681 let expect = Arc::new(expect);
1682 let sec = self.resolve(node, endpoint, security_cc, TxSecurity::Auto);
1683 let bytes = wrap_endpoint(cmd.encode(), endpoint);
1684 let mut last = Error::Timeout(node);
1685 for attempt in 0..2 {
1686 let e = expect.clone();
1687 let (_g, rx) = self.wait_for(node, false, move |i| matches!(i, Inbound::Command { endpoint: ep, command, .. } if *ep == endpoint && e(command)));
1688 match self.send_bytes(node, bytes.clone(), sec).await {
1689 Ok(()) => {}
1690 Err(err @ (Error::NoAck(_) | Error::TransmitFailed(..))) if attempt == 0 => {
1691 last = err;
1692 continue;
1693 }
1694 Err(err) => return Err(err),
1695 }
1696 match tokio::time::timeout(timeout, rx).await {
1697 Ok(Ok(Inbound::Command { command, .. })) => return Ok(command),
1698 Ok(_) => return Err(Error::Stopped),
1699 Err(_) => {
1700 debug!(node, attempt, "no reply to {}", cmd.name());
1701 last = Error::Timeout(node);
1702 }
1703 }
1704 }
1705 Err(last)
1706 }
1707
1708 pub(crate) async fn request_secured(
1710 &self,
1711 node: NodeId,
1712 bytes: Vec<u8>,
1713 sec: TxSecurity,
1714 timeout: Duration,
1715 expect: impl Fn(&Command, Option<RxSecurity>) -> bool + Send + 'static,
1716 ) -> Result<(Command, Option<RxSecurity>), Error> {
1717 let (_g, rx) = self.wait_for(node, false, move |i| matches!(i, Inbound::Command { command, security, .. } if expect(command, *security)));
1718 self.send_bytes(node, bytes, sec).await?;
1719 match tokio::time::timeout(timeout, rx).await {
1720 Ok(Ok(Inbound::Command {
1721 command, security, ..
1722 })) => Ok((command, security)),
1723 Ok(_) => Err(Error::Stopped),
1724 Err(_) => Err(Error::Timeout(node)),
1725 }
1726 }
1727
1728 pub async fn set_value(
1730 &self,
1731 id: &values::ValueId,
1732 value: &values::ValueKind,
1733 ) -> Result<(), Error> {
1734 let cmd = values::set_command(id, value)
1735 .ok_or(Error::Controller(format!("{} is not writable", id.key())))?;
1736 let supervised = self
1737 .with_node(id.node, |r| {
1738 r.endpoints
1739 .get(&id.endpoint)
1740 .or(Some(r.root()))
1741 .is_some_and(|e| e.supports(supervision::ID))
1742 })
1743 .unwrap_or(false);
1744 if supervised {
1745 self.send_supervised(id.node, id.endpoint, &cmd).await?;
1746 } else {
1747 self.send(id.node, id.endpoint, &cmd).await?;
1748 }
1749 if let Some(get) = values::get_command(id) {
1750 let cc = get.cc();
1751 let _ = self
1752 .request(id.node, id.endpoint, get, move |c| {
1753 c.cc() == cc && c.name().ends_with(".report")
1754 })
1755 .await;
1756 }
1757 Ok(())
1758 }
1759
1760 pub async fn configure(
1765 &self,
1766 node: NodeId,
1767 config: &crate::device_config::DeviceConfig,
1768 settings: &[(String, i64)],
1769 ) -> Result<(), Error> {
1770 use crate::device_config::plan_settings;
1771 use zwave_cc::configuration;
1772 let bad = |e: crate::device_config::SettingsError| Error::Controller(e.to_string());
1773 let first = plan_settings(config, settings, &|_| None).map_err(bad)?;
1774 let mut current: HashMap<u16, u32> = HashMap::new();
1775 for w in first.iter().filter(|w| w.needs_current) {
1776 let p = w.parameter;
1777 let r = self
1778 .req(
1779 node,
1780 0,
1781 configuration::Get { parameter: p as u8 },
1782 move |c| match c {
1783 Command::Configuration(configuration::Command::Report(r))
1784 if u16::from(r.parameter) == p =>
1785 {
1786 Some((r.value, r.size))
1787 }
1788 _ => None,
1789 },
1790 )
1791 .await?;
1792 let raw = match r.1 {
1793 1 => u32::from(r.0 as u8),
1794 2 => u32::from(r.0 as u16),
1795 _ => r.0 as u32,
1796 };
1797 current.insert(p, raw);
1798 }
1799 let writes = plan_settings(config, settings, &|p| current.get(&p).copied()).map_err(bad)?;
1800 let supervised = self
1801 .with_node(node, |r| r.root().supports(supervision::ID))
1802 .unwrap_or(false);
1803 for w in writes {
1804 let set = w.command();
1805 if supervised {
1806 self.send_supervised(node, 0, &set).await?;
1807 } else {
1808 self.send(node, 0, &set).await?;
1809 }
1810 let p = w.parameter;
1811 let _ = self
1812 .req(node, 0, configuration::Get { parameter: p as u8 }, move |c| {
1813 matches!(c, Command::Configuration(configuration::Command::Report(r)) if u16::from(r.parameter) == p).then_some(())
1814 })
1815 .await;
1816 }
1817 Ok(())
1818 }
1819
1820 pub async fn factory_reset(&self) -> Result<(), Error> {
1823 let cb = self.inner.api.next_callback_id();
1824 let mut req = Request::with_callback(
1825 DataFrame::request(F::SET_DEFAULT, vec![cb]),
1826 Duration::from_secs(2),
1827 cb,
1828 Duration::from_secs(10),
1829 );
1830 req.response = None;
1831 self.inner.api.execute(req).await?;
1832 info!("controller reset to factory defaults");
1833 Ok(())
1834 }
1835
1836 pub async fn set_region(&self, region: message::RfRegion) -> Result<(), Error> {
1840 let r = self
1841 .inner
1842 .api
1843 .request(
1844 DataFrame::request(
1845 F::SERIAL_API_SETUP,
1846 vec![message::setup::SET_RF_REGION, region.to_u8()],
1847 ),
1848 Duration::from_secs(2),
1849 )
1850 .await?;
1851 if r.payload.first() != Some(&message::setup::SET_RF_REGION) || r.payload.get(1) == Some(&0)
1852 {
1853 return Err(Error::Controller(
1854 "the controller refused the region".into(),
1855 ));
1856 }
1857 self.inner
1858 .api
1859 .execute(Request::ack_only(DataFrame::request(F::SOFT_RESET, vec![])))
1860 .await?;
1861 Ok(())
1862 }
1863
1864 pub async fn configure_raw(
1868 &self,
1869 node: NodeId,
1870 settings: &[(String, i64)],
1871 ) -> Result<(), Error> {
1872 use crate::device_config::parse_param_key;
1873 use zwave_cc::configuration;
1874 type Parts = Vec<(Option<u32>, i64)>;
1875 let mut params: Vec<(u16, Parts)> = Vec::new();
1876 for (key, value) in settings {
1877 let (p, mask) = parse_param_key(key)
1878 .ok_or_else(|| Error::Controller(format!("bad parameter key {key}")))?;
1879 if p > 255 {
1880 return Err(Error::Controller(format!(
1881 "parameter {p} needs Configuration version 3 bulk commands"
1882 )));
1883 }
1884 match params.iter_mut().find(|(q, _)| *q == p) {
1885 Some((_, v)) => v.push((mask, *value)),
1886 None => params.push((p, vec![(mask, *value)])),
1887 }
1888 }
1889 let supervised = self
1890 .with_node(node, |r| r.root().supports(supervision::ID))
1891 .unwrap_or(false);
1892 for (p, parts) in params {
1893 let (current, size) = self
1894 .req(
1895 node,
1896 0,
1897 configuration::Get { parameter: p as u8 },
1898 move |c| match c {
1899 Command::Configuration(configuration::Command::Report(r))
1900 if u16::from(r.parameter) == p =>
1901 {
1902 Some((r.value, r.size))
1903 }
1904 _ => None,
1905 },
1906 )
1907 .await?;
1908 if !matches!(size, 1 | 2 | 4) {
1909 return Err(Error::Controller(format!(
1910 "parameter {p} reports size {size}"
1911 )));
1912 }
1913 let width: u32 = if size == 4 {
1914 u32::MAX
1915 } else {
1916 (1u32 << (8 * u32::from(size))) - 1
1917 };
1918 let mut raw = (current as u32) & width;
1919 for (mask, value) in parts {
1920 match mask {
1921 None => raw = (value as u32) & width,
1922 Some(m) => raw = (raw & !m) | (((value as u32) << m.trailing_zeros()) & m),
1923 }
1924 }
1925 let value = match size {
1926 1 => i32::from(raw as u8 as i8),
1927 2 => i32::from(raw as u16 as i16),
1928 _ => raw as i32,
1929 };
1930 let set: Command = configuration::Set {
1931 parameter: p as u8,
1932 default: false,
1933 size,
1934 value,
1935 }
1936 .into();
1937 if supervised {
1938 self.send_supervised(node, 0, &set).await?;
1939 } else {
1940 self.send(node, 0, &set).await?;
1941 }
1942 let _ = self
1943 .req(node, 0, configuration::Get { parameter: p as u8 }, move |c| {
1944 matches!(c, Command::Configuration(configuration::Command::Report(r)) if u16::from(r.parameter) == p).then_some(())
1945 })
1946 .await;
1947 }
1948 Ok(())
1949 }
1950
1951 pub async fn ping(&self, node: NodeId) -> bool {
1953 self.transmit(node, vec![0x00]).await.is_ok()
1954 }
1955
1956 pub(crate) async fn fetch_protocol_info(&self, node: NodeId) -> Result<(), Error> {
1957 let r = self
1958 .inner
1959 .api
1960 .request(
1961 DataFrame::request(F::GET_NODE_PROTOCOL_INFO, self.node_payload(node)),
1962 Duration::from_secs(2),
1963 )
1964 .await?;
1965 let p =
1966 NodeProtocolInfo::parse(&r.payload).map_err(|e| Error::Controller(e.to_string()))?;
1967 let Some(p) = p else {
1968 return Err(Error::UnknownNode(node));
1969 };
1970 self.update_node(node, |r| {
1971 r.protocol = ProtocolInfo {
1972 listening: p.listening,
1973 flirs: p.flirs_1000 || p.flirs_250,
1974 routing: p.routing,
1975 controller: p.controller,
1976 basic: p.basic,
1977 generic: p.generic,
1978 specific: p.specific,
1979 };
1980 if r.stage < InterviewStage::ProtocolInfo {
1981 r.stage = InterviewStage::ProtocolInfo;
1982 }
1983 })
1984 }
1985
1986 pub(crate) fn s2(&self, node: NodeId) -> &Mutex<S2Manager> {
1988 if crate::is_long_range(node) {
1989 &self.inner.s2_lr
1990 } else {
1991 &self.inner.s2
1992 }
1993 }
1994
1995 pub(crate) fn node_payload(&self, node: NodeId) -> Vec<u8> {
1997 let mut v = Vec::with_capacity(2);
1998 message::node_bytes(node, self.inner.nid, &mut v);
1999 v
2000 }
2001
2002 pub fn queued(&self, node: NodeId) -> usize {
2004 self.inner
2005 .runtime
2006 .lock()
2007 .expect("lock")
2008 .get(&node)
2009 .map(|r| r.wake_tickets.len())
2010 .unwrap_or(0)
2011 }
2012
2013 pub fn last_route(&self, node: NodeId) -> Option<(Vec<NodeId>, Option<i8>)> {
2015 self.inner
2016 .runtime
2017 .lock()
2018 .expect("lock")
2019 .get(&node)
2020 .and_then(|r| r.last_route.clone())
2021 }
2022
2023 pub async fn refresh_neighbors(&self, node: NodeId) -> Result<Vec<NodeId>, Error> {
2026 if crate::is_long_range(node) {
2027 return Ok(vec![]);
2028 }
2029 let r = self
2030 .inner
2031 .api
2032 .request(
2033 message::get_routing_info(node, self.inner.nid),
2034 Duration::from_secs(2),
2035 )
2036 .await?;
2037 let n = message::parse_routing_info(&r.payload)
2038 .map_err(|e| Error::Controller(e.to_string()))?;
2039 let own = self.info().node_id;
2040 let n: Vec<NodeId> = n.into_iter().filter(|&x| x != node).collect();
2041 let _ = own;
2042 self.update_node(node, |r| r.neighbors = n.clone())?;
2043 Ok(n)
2044 }
2045
2046 pub fn topology(&self) -> Topology {
2048 let rt = self.inner.runtime.lock().expect("lock");
2049 let s = self.inner.store.lock().expect("store lock");
2050 Topology {
2051 controller: self.info().node_id,
2052 nodes: s
2053 .nodes
2054 .values()
2055 .map(|r| {
2056 let route = rt.get(&r.id).and_then(|x| x.last_route.clone());
2057 TopologyNode {
2058 id: r.id,
2059 neighbors: r.neighbors.clone(),
2060 last_route: route.as_ref().map(|(rep, _)| rep.clone()),
2061 last_rssi: route.and_then(|(_, rssi)| rssi),
2062 listening: r.protocol.listening,
2063 }
2064 })
2065 .collect(),
2066 }
2067 }
2068}
2069
2070pub(crate) fn wrap_endpoint(bytes: Vec<u8>, endpoint: u8) -> Vec<u8> {
2072 if endpoint == 0 {
2073 return bytes;
2074 }
2075 Command::from(multi_channel::CommandEncapsulation {
2076 source_end_point: 0,
2077 bit_address: false,
2078 destination_end_point: endpoint,
2079 command: bytes,
2080 })
2081 .encode()
2082}