1use std::collections::HashMap;
17use std::sync::atomic::{AtomicU8, Ordering};
18use std::sync::{Arc, Mutex};
19use std::time::{Duration, SystemTime, UNIX_EPOCH};
20
21use tokio::io::{AsyncRead, AsyncWrite};
22use tokio::sync::{mpsc, oneshot, watch};
23use zigbee_primitives::wire::{Reader, Writer};
24use zigbee_primitives::{ExtPanId, Ieee, Key, NodeId};
25use zigbee_znp::client::{ClientConfig, Znp, ZnpError, ZnpEvent};
26use zigbee_znp::ids::{
27 addr_mode, af_option, commissioning, nv, nv_ex, product, startup_option, state, status,
28};
29use zigbee_znp::{Indication, Request};
30
31use crate::adapter::{
32 Adapter, AdapterEvent, AdapterInfo, Aps, Beacon, JoinPolicy, NetworkInfo, NetworkSettings,
33 StartMode, StartOutcome,
34};
35use crate::backup::{
36 self, Backup, BackupDevice, Internal, Metadata, NetworkKey, StackSpecific, ZstackSpecific,
37};
38use crate::error::HostError;
39
40const NETWORK_TIMEOUT: Duration = Duration::from_secs(20);
42const RESET_TIMEOUT: Duration = Duration::from_secs(5);
44const MGMT_NWK_UPDATE_NOTIFY: u16 = 0x8038;
46const ALL_ZDO_CLUSTERS: u16 = 0xFFFF;
48const HOME_AUTOMATION: u16 = 0x0104;
50
51const ENDPOINT_INPUT_CLUSTERS: &[u16] = &[
53 0x0000, 0x0003, 0x0006, 0x000A, 0x0019, 0x0300, 0x0402, 0x0405, 0x0500, 0x0702, 0x0B04,
54];
55const ENDPOINT_OUTPUT_CLUSTERS: &[u16] = &[
56 0x0000, 0x0001, 0x0003, 0x0004, 0x0005, 0x0006, 0x0008, 0x000F, 0x0012, 0x0020, 0x0101, 0x0102,
57 0x0201, 0x0202, 0x0300, 0x0400, 0x0402, 0x0403, 0x0405, 0x0406, 0x0500, 0x0502, 0x0702, 0x0B04,
58 0x0B05,
59];
60
61type ScanResult = Result<Vec<(u8, i8)>, HostError>;
62type Discovery = (Vec<Beacon>, oneshot::Sender<Result<Vec<Beacon>, HostError>>);
63
64struct Shared {
65 state: watch::Sender<u8>,
67 resets: watch::Sender<u32>,
69 commissioning: watch::Sender<Option<(u8, u8)>>,
71 endpoints: Mutex<HashMap<u8, u16>>,
73 scan: Mutex<Option<oneshot::Sender<ScanResult>>>,
75 discovery: Mutex<Option<Discovery>>,
77}
78
79pub struct ZnpAdapter {
81 znp: Znp,
82 shared: Arc<Shared>,
83 tag: AtomicU8,
84 events: mpsc::UnboundedSender<AdapterEvent>,
86}
87
88impl std::fmt::Debug for ZnpAdapter {
89 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90 f.debug_struct("ZnpAdapter")
91 .field("version", &self.znp.version())
92 .finish_non_exhaustive()
93 }
94}
95
96impl From<ZnpError> for HostError {
97 fn from(e: ZnpError) -> Self {
98 match e {
99 ZnpError::Down(why) => HostError::Ncp(format!("ZNP port down: {why}")),
100 other => HostError::Ncp(other.to_string()),
101 }
102 }
103}
104
105fn now_unix() -> u64 {
106 SystemTime::now()
107 .duration_since(UNIX_EPOCH)
108 .map(|d| d.as_secs())
109 .unwrap_or(0)
110}
111
112fn random_key() -> Result<Key, HostError> {
113 let mut k = [0u8; 16];
114 getrandom::fill(&mut k).map_err(|e| HostError::Io(format!("random: {e}")))?;
115 Ok(Key(k))
116}
117
118fn ed_to_dbm(ed: u8) -> i8 {
121 (-100 + i16::from(ed) * 40 / 255) as i8
122}
123
124fn translate(ind: Indication, shared: &Shared) -> Option<AdapterEvent> {
125 match ind {
126 Indication::Reset { .. } => {
127 shared.resets.send_modify(|n| *n = n.wrapping_add(1));
128 None
129 }
130 Indication::StateChange { state: s } => {
131 let was = *shared.state.borrow();
132 shared.state.send_replace(s);
133 match (was == state::ZB_COORD, s == state::ZB_COORD) {
134 (false, true) => Some(AdapterEvent::NetworkUp),
135 (true, false) => Some(AdapterEvent::NetworkDown),
136 _ => None,
137 }
138 }
139 Indication::Commissioning { status, mode, .. } => {
140 if status != 1 {
142 shared.commissioning.send_replace(Some((mode, status)));
143 }
144 None
145 }
146 Indication::Incoming(m) => {
147 let profile = shared
148 .endpoints
149 .lock()
150 .ok()
151 .and_then(|e| e.get(&m.destination_endpoint).copied())
152 .unwrap_or(HOME_AUTOMATION);
153 Some(AdapterEvent::Message {
154 source: m.source,
155 source_ieee: m.source_ieee,
156 aps: Aps {
157 profile,
158 cluster: m.cluster,
159 source_endpoint: m.source_endpoint,
160 destination_endpoint: m.destination_endpoint,
161 },
162 broadcast: m.broadcast || m.group != 0,
163 group: (m.group != 0).then_some(m.group),
164 lqi: m.lqi,
165 rssi: None,
166 payload: m.data,
167 })
168 }
169 Indication::ZdoMessage {
170 source,
171 broadcast,
172 cluster,
173 tsn,
174 data,
175 ..
176 } => {
177 if cluster == MGMT_NWK_UPDATE_NOTIFY && source == 0x0000 {
178 if let Some(done) = shared.scan.lock().ok().and_then(|mut s| s.take()) {
179 let _ = done.send(parse_scan_notify(&data));
180 return None;
181 }
182 }
183 let mut payload = Vec::with_capacity(data.len() + 1);
184 payload.push(tsn);
185 payload.extend_from_slice(&data);
186 Some(AdapterEvent::Message {
187 source,
188 source_ieee: None,
189 aps: Aps {
190 profile: zigbee_zdo::PROFILE_ID,
191 cluster,
192 source_endpoint: 0,
193 destination_endpoint: 0,
194 },
195 broadcast,
196 group: None,
197 lqi: 0,
198 rssi: None,
199 payload,
200 })
201 }
202 Indication::TcDevice { nwk, ieee, parent } => Some(AdapterEvent::Joined {
203 nwk,
204 ieee,
205 parent,
206 rejoin: false,
207 }),
208 Indication::Leave {
209 nwk, ieee, rejoin, ..
210 } => (!rejoin).then_some(AdapterEvent::Left { nwk, ieee }),
211 Indication::SourceRoute { source, relays } => Some(AdapterEvent::RouteRecord {
212 source,
213 ieee: None,
214 relays,
215 lqi: None,
216 rssi: None,
217 }),
218 Indication::DataConfirm {
219 status: s,
220 trans_id,
221 ..
222 } => Some(AdapterEvent::Delivery {
223 tag: u16::from(trans_id),
224 delivered: s == status::SUCCESS,
225 }),
226 Indication::Beacons(beacons) => {
227 if let Ok(mut d) = shared.discovery.lock() {
228 if let Some((found, _)) = d.as_mut() {
229 for b in beacons
230 .into_iter()
231 .take(256usize.saturating_sub(found.len()))
232 {
233 found.push(Beacon {
234 channel: b.channel,
235 pan_id: b.pan_id,
236 extended_pan_id: b.extended_pan_id,
237 permit_joining: b.permit_joining,
238 nwk_update_id: b.update_id,
239 lqi: b.lqi,
240 rssi: None,
241 });
242 }
243 }
244 }
245 None
246 }
247 Indication::DiscoveryDone { status: s } => {
248 if let Some((found, done)) = shared.discovery.lock().ok().and_then(|mut d| d.take()) {
249 let _ = done.send(if s == status::SUCCESS {
250 Ok(found)
251 } else {
252 Err(HostError::Ncp(format!(
253 "network discovery failed ({s:#04x})"
254 )))
255 });
256 }
257 None
258 }
259 Indication::DeviceAnnounce { .. } | Indication::PermitJoin { .. } => None,
261 }
262}
263
264fn parse_scan_notify(data: &[u8]) -> ScanResult {
265 let mut r = Reader::new(data);
266 let parse = |r: &mut Reader<'_>| -> Result<Vec<(u8, i8)>, zigbee_primitives::wire::Truncated> {
267 let status = r.u8()?;
268 if status != 0 {
269 return Ok(Vec::new());
270 }
271 let _total = r.u16()?;
272 let _failures = r.u16()?;
273 let mask = r.u32()?;
274 let count = usize::from(r.u8()?);
275 let energies = r.bytes(count)?;
276 Ok((11..=26u8)
277 .filter(|c| mask & (1 << c) != 0)
278 .zip(energies.iter())
279 .map(|(c, ed)| (c, ed_to_dbm(*ed)))
280 .collect())
281 };
282 parse(&mut r).map_err(|e| HostError::Ncp(format!("network update notify: {e}")))
283}
284
285impl ZnpAdapter {
286 pub async fn connect<T>(
289 io: T,
290 config: ClientConfig,
291 ) -> Result<(ZnpAdapter, mpsc::UnboundedReceiver<AdapterEvent>), HostError>
292 where
293 T: AsyncRead + AsyncWrite + Send + 'static,
294 {
295 let (znp, mut znp_events) = Znp::start(io, config).await?;
296 let v = znp.version();
297 tracing::info!(product = v.product, firmware = %v.firmware(), "Z-Stack coordinator connected");
298 let shared = Arc::new(Shared {
299 state: watch::channel(state::HOLD).0,
300 resets: watch::channel(0).0,
301 commissioning: watch::channel(None).0,
302 endpoints: Mutex::new(HashMap::new()),
303 scan: Mutex::new(None),
304 discovery: Mutex::new(None),
305 });
306 let (tx, rx) = mpsc::unbounded_channel();
307 let events = tx.clone();
308 let task_shared = shared.clone();
309 tokio::spawn(async move {
310 while let Some(event) = znp_events.recv().await {
311 let out = match event {
312 ZnpEvent::Indication(ind) => translate(ind, &task_shared),
313 ZnpEvent::Down(why) => Some(AdapterEvent::Failed(why)),
314 };
315 if let Some(out) = out {
316 if tx.send(out).is_err() {
317 break;
318 }
319 }
320 }
321 });
322 Ok((
323 ZnpAdapter {
324 znp,
325 shared,
326 tag: AtomicU8::new(1),
327 events,
328 },
329 rx,
330 ))
331 }
332
333 pub fn version(&self) -> zigbee_znp::client::Version {
335 self.znp.version()
336 }
337
338 async fn ok(&self, request: Request) -> Result<(), HostError> {
339 self.znp.request_ok(request).await?;
340 Ok(())
341 }
342
343 async fn reset(&self) -> Result<(), HostError> {
345 let mut resets = self.shared.resets.subscribe();
346 self.shared.state.send_replace(state::HOLD);
347 self.ok(Request::SysReset { soft: true }).await?;
348 match tokio::time::timeout(RESET_TIMEOUT, resets.changed()).await {
349 Ok(Ok(())) => {}
350 _ => {
351 return Err(HostError::Ncp(
352 "the coordinator did not come back from a reset".into(),
353 ))
354 }
355 }
356 if let Ok(mut e) = self.shared.endpoints.lock() {
357 e.clear();
358 }
359 Ok(())
360 }
361
362 async fn wait_coordinator(&self) -> Result<(), HostError> {
363 let mut s = self.shared.state.subscribe();
364 let up = tokio::time::timeout(NETWORK_TIMEOUT, s.wait_for(|s| *s == state::ZB_COORD))
365 .await
366 .is_ok_and(|r| r.is_ok());
367 if up {
368 Ok(())
369 } else {
370 Err(HostError::Ncp("the network did not come up".into()))
371 }
372 }
373
374 async fn startup(&self) -> Result<bool, HostError> {
377 let data = self
378 .znp
379 .request(Request::ZdoStartupFromApp { delay: 100 })
380 .await?;
381 if data.first() == Some(&0) {
383 self.wait_coordinator().await?;
384 Ok(true)
385 } else {
386 Ok(false)
387 }
388 }
389
390 async fn nwk_info(&self) -> Result<(NodeId, u16, ExtPanId, u8), HostError> {
391 let data = self.znp.request(Request::ZdoExtNwkInfo).await?;
392 let mut r = Reader::new(&data);
393 let parse = |r: &mut Reader<'_>| -> Result<_, zigbee_primitives::wire::Truncated> {
394 let nwk = r.u16()?;
395 let _state = r.u8()?;
396 let pan = r.u16()?;
397 let _parent = r.u16()?;
398 let ext = r.ext_pan_id()?;
399 let _parent_ext = r.u64()?;
400 let channel = r.u8()?;
401 Ok((nwk, pan, ext, channel))
402 };
403 parse(&mut r).map_err(|e| HostError::Ncp(format!("ZDO_EXT_NWK_INFO: {e}")))
404 }
405
406 async fn ieee(&self) -> Result<Ieee, HostError> {
407 let data = self.znp.request_ok(Request::UtilGetDeviceInfo).await?;
408 let mut r = Reader::new(&data);
409 let _ = r.u8();
410 r.ieee()
411 .map_err(|e| HostError::Ncp(format!("UTIL_GET_DEVICE_INFO: {e}")))
412 }
413
414 async fn network_key(&self) -> Result<(u8, Key), HostError> {
415 let item = self
416 .znp
417 .nv_read(nv::NWK_ACTIVE_KEY_INFO)
418 .await?
419 .ok_or_else(|| HostError::Ncp("no active network key".into()))?;
420 let mut r = Reader::new(&item);
421 let seq = r.u8().map_err(|e| HostError::Ncp(e.to_string()))?;
422 let key = r.key().map_err(|e| HostError::Ncp(e.to_string()))?;
423 Ok((seq, key))
424 }
425
426 fn sec_material_id(&self) -> SecMaterial {
427 if self.znp.version().product == product::ZSTACK_3X0 {
428 SecMaterial::Extended
429 } else {
430 SecMaterial::Legacy
431 }
432 }
433
434 async fn frame_counter(&self) -> Result<u32, HostError> {
435 let item = match self.sec_material_id() {
436 SecMaterial::Extended => {
437 self.znp
438 .nv_ex_read(nv_ex::SYSID_ZSTACK, nv_ex::NWK_SEC_MATERIAL_TABLE, 0)
439 .await?
440 }
441 SecMaterial::Legacy => {
442 self.znp
443 .nv_read(nv::LEGACY_NWK_SEC_MATERIAL_TABLE_START)
444 .await?
445 }
446 };
447 let item = item.ok_or_else(|| HostError::Ncp("no network frame counter".into()))?;
448 Reader::new(&item)
449 .u32()
450 .map_err(|e| HostError::Ncp(format!("network security material: {e}")))
451 }
452
453 async fn set_frame_counter(&self, counter: u32, ext: ExtPanId) -> Result<(), HostError> {
454 let mut item = Vec::new();
455 item.put_u32(counter);
456 item.put_ext_pan_id(ext);
457 match self.sec_material_id() {
458 SecMaterial::Extended => {
459 self.znp
460 .nv_ex_write(nv_ex::SYSID_ZSTACK, nv_ex::NWK_SEC_MATERIAL_TABLE, 0, &item)
461 .await?
462 }
463 SecMaterial::Legacy => {
464 self.znp
465 .nv_write(nv::LEGACY_NWK_SEC_MATERIAL_TABLE_START, &item)
466 .await?
467 }
468 }
469 Ok(())
470 }
471
472 async fn form(&self, settings: &NetworkSettings, seed: Key) -> Result<(), HostError> {
474 self.znp
475 .nv_write(
476 nv::STARTUP_OPTION,
477 &[startup_option::CLEAR_STATE | startup_option::CLEAR_CONFIG],
478 )
479 .await?;
480 self.reset().await?;
481 let mask = 1u32 << settings.channel;
482 self.znp.nv_write(nv::LOGICAL_TYPE, &[0]).await?;
483 self.znp.nv_write(nv::PRECFGKEYS_ENABLE, &[0]).await?;
484 self.znp.nv_write(nv::ZDO_DIRECT_CB, &[1]).await?;
485 self.znp.nv_write(nv::CHANLIST, &mask.to_le_bytes()).await?;
486 self.znp
487 .nv_write(nv::PANID, &settings.pan_id.to_le_bytes())
488 .await?;
489 let ext = settings.extended_pan_id.to_le_bytes();
490 self.znp.nv_write(nv::EXTENDED_PAN_ID, &ext).await?;
491 self.znp.nv_write(nv::APS_USE_EXT_PANID, &ext).await?;
492 self.znp
493 .nv_write(nv::PRECFGKEY, &settings.network_key.0)
494 .await?;
495 self.znp.nv_write(nv::TCLK_SEED, &seed.0).await?;
496 self.ok(Request::BdbSetChannel {
497 primary: true,
498 channel_mask: mask,
499 })
500 .await?;
501 self.ok(Request::BdbSetChannel {
502 primary: false,
503 channel_mask: 0,
504 })
505 .await?;
506 let mut done = self.shared.commissioning.subscribe();
507 self.shared.commissioning.send_replace(None);
508 self.ok(Request::BdbStartCommissioning {
509 mode: commissioning::FORMATION,
510 })
511 .await?;
512 let result = tokio::time::timeout(
513 NETWORK_TIMEOUT,
514 done.wait_for(|r| matches!(r, Some((m, _)) if *m & commissioning::FORMATION != 0)),
515 )
516 .await
517 .ok()
518 .and_then(|r| r.ok().map(|r| *r));
519 match result {
520 Some(Some((_, 0))) => {}
521 Some(r) => {
522 return Err(HostError::Ncp(format!(
523 "network formation failed (status {:?})",
524 r.map(|(_, s)| s)
525 )))
526 }
527 None => return Err(HostError::Ncp("network formation did not finish".into())),
528 }
529 self.wait_coordinator().await
530 }
531
532 async fn restore(&self, backup: &Backup) -> Result<(), HostError> {
533 let ieee = self.ieee().await?;
534 if ieee != backup.coordinator_ieee {
535 self.znp
537 .nv_write(nv::EXTADDR, &backup.coordinator_ieee.to_le_bytes())
538 .await?;
539 self.reset().await?;
540 let now = self.ieee().await?;
541 if now != backup.coordinator_ieee {
542 return Err(HostError::RestoreRefused(format!(
543 "this coordinator kept its IEEE address {now}; the backup needs {}",
544 backup.coordinator_ieee
545 )));
546 }
547 }
548 let seed = backup
549 .stack_specific
550 .as_ref()
551 .and_then(|s| s.zstack.as_ref())
552 .map(|z| z.tclk_seed);
553 let settings = NetworkSettings {
554 channel: backup.channel,
555 pan_id: backup.pan_id,
556 extended_pan_id: backup.extended_pan_id,
557 network_key: backup.network_key.key,
558 tx_power: None,
559 };
560 self.form(&settings, seed.map_or_else(random_key, Ok)?)
561 .await?;
562 self.set_frame_counter(backup.restore_frame_counter(), backup.extended_pan_id)
563 .await?;
564 if backup.network_key.sequence_number != 0 {
565 let mut item = vec![backup.network_key.sequence_number];
566 item.put_key(&backup.network_key.key);
567 self.znp.nv_write(nv::NWK_ACTIVE_KEY_INFO, &item).await?;
568 }
569 if seed.is_none() {
570 for d in &backup.devices {
572 if let Some(link) = &d.link_key {
573 self.ok(Request::ZdoSetLinkKey {
574 nwk: d.nwk_address.unwrap_or(0xFFFE),
575 ieee: d.ieee_address,
576 key: link.key,
577 })
578 .await?;
579 }
580 }
581 }
582 Ok(())
583 }
584
585 async fn register_endpoint(&self, endpoint: u8, profile: u16) -> Result<(), HostError> {
586 let known = self
587 .shared
588 .endpoints
589 .lock()
590 .ok()
591 .and_then(|e| e.get(&endpoint).copied());
592 match known {
593 Some(p) if p == profile => return Ok(()),
594 Some(p) => {
595 return Err(HostError::Invalid(format!(
596 "endpoint {endpoint} is registered for profile {p:#06x}, not {profile:#06x}"
597 )))
598 }
599 None => {}
600 }
601 let (inputs, outputs) = if endpoint == 1 {
602 (
603 ENDPOINT_INPUT_CLUSTERS.to_vec(),
604 ENDPOINT_OUTPUT_CLUSTERS.to_vec(),
605 )
606 } else {
607 (Vec::new(), Vec::new())
608 };
609 self.ok(Request::AfRegister {
610 endpoint,
611 profile,
612 device_id: 0x0005,
613 version: 0,
614 input_clusters: inputs,
615 output_clusters: outputs,
616 })
617 .await?;
618 if let Ok(mut e) = self.shared.endpoints.lock() {
619 e.insert(endpoint, profile);
620 }
621 Ok(())
622 }
623
624 async fn after_up(&self, power: Option<i8>) -> Result<NetworkInfo, HostError> {
625 self.ok(Request::ZdoMsgCbRegister {
626 cluster: ALL_ZDO_CLUSTERS,
627 })
628 .await?;
629 self.register_endpoint(1, HOME_AUTOMATION).await?;
630 self.ok(Request::SetAllowRejoinTcPolicy { allow: true })
631 .await?;
632 if let Some(dbm) = power {
633 if let Err(e) = self.znp.request(Request::SetTxPower { dbm }).await {
634 tracing::warn!(dbm, error = %e, "setting transmit power");
635 }
636 }
637 self.read_network_info().await
638 }
639
640 async fn read_network_info(&self) -> Result<NetworkInfo, HostError> {
641 let (nwk, pan_id, extended_pan_id, channel) = self.nwk_info().await?;
642 Ok(NetworkInfo {
643 ieee: self.ieee().await?,
644 nwk,
645 channel,
646 pan_id,
647 extended_pan_id,
648 nwk_update_id: 0,
649 })
650 }
651
652 fn next_tag(&self) -> u8 {
653 self.tag.fetch_add(1, Ordering::Relaxed)
654 }
655}
656
657enum SecMaterial {
658 Extended,
659 Legacy,
660}
661
662impl Adapter for ZnpAdapter {
663 fn info(&self) -> AdapterInfo {
664 let v = self.znp.version();
665 AdapterInfo {
666 kind: "znp",
667 firmware: v.firmware(),
668 protocol: v.transport,
669 reports_key_exchange: false,
670 }
671 }
672
673 async fn start(&self, mode: StartMode) -> Result<(StartOutcome, NetworkInfo), HostError> {
674 self.reset().await?;
675 self.znp.nv_write(nv::ZDO_DIRECT_CB, &[1]).await?;
676 let has_network = self.startup().await?;
677 match mode {
678 StartMode::Restore(backup) => {
679 self.restore(&backup).await?;
680 Ok((StartOutcome::Restored, self.after_up(None).await?))
681 }
682 StartMode::Normal {
683 settings,
684 replace_other,
685 } => {
686 if has_network {
687 let (_, pan, ext, channel) = self.nwk_info().await?;
688 let (_, key) = self.network_key().await?;
689 if pan == settings.pan_id
690 && ext == settings.extended_pan_id
691 && key == settings.network_key
692 {
693 return Ok((
694 StartOutcome::Resumed,
695 self.after_up(settings.tx_power).await?,
696 ));
697 }
698 let found = format!("channel {channel}, PAN {pan:04x}, extended PAN {ext}");
699 if !replace_other {
700 return Err(HostError::NetworkMismatch { found });
701 }
702 tracing::warn!(%found, "replacing the coordinator's other network, as configured");
703 }
704 self.form(&settings, random_key()?).await?;
705 Ok((
706 StartOutcome::Formed,
707 self.after_up(settings.tx_power).await?,
708 ))
709 }
710 }
711 }
712
713 async fn permit_join(&self, seconds: u8, join: &JoinPolicy) -> Result<(), HostError> {
714 if seconds > 0 {
715 self.ok(Request::BdbSetJoinUsesInstallCodeKey {
716 required: join.install_code_only,
717 })
718 .await?;
719 self.ok(Request::BdbSetTcRequireKeyExchange {
720 required: !join.allow_legacy,
721 })
722 .await?;
723 }
724 for (mode, destination) in [(addr_mode::SHORT, 0x0000), (addr_mode::BROADCAST, 0xFFFC)] {
725 self.ok(Request::ZdoMgmtPermitJoin {
726 addr_mode: mode,
727 destination,
728 duration: seconds,
729 tc_significance: 0,
730 })
731 .await?;
732 }
733 Ok(())
734 }
735
736 async fn add_join_key(&self, ieee: Ieee, key: Key) -> Result<(), HostError> {
737 self.ok(Request::BdbAddInstallCode {
739 format: 2,
740 ieee,
741 code: key.0.to_vec(),
742 })
743 .await
744 }
745
746 async fn send_unicast(
747 &self,
748 nwk: NodeId,
749 aps: Aps,
750 payload: Vec<u8>,
751 ) -> Result<u16, HostError> {
752 let tag = self.next_tag();
753 if aps.profile == zigbee_zdo::PROFILE_ID && aps.destination_endpoint == 0 {
754 let (tsn, data) = payload
755 .split_first()
756 .ok_or_else(|| HostError::Invalid("empty ZDO frame".into()))?;
757 self.ok(Request::ZdoSendData {
758 destination: nwk,
759 tsn: *tsn,
760 cluster: aps.cluster,
761 data: data.to_vec(),
762 })
763 .await?;
764 let _ = self.events.send(AdapterEvent::Delivery {
766 tag: u16::from(tag),
767 delivered: true,
768 });
769 return Ok(u16::from(tag));
770 }
771 self.register_endpoint(aps.source_endpoint, aps.profile)
772 .await?;
773 self.ok(Request::AfDataRequest {
774 destination: nwk,
775 destination_endpoint: aps.destination_endpoint,
776 source_endpoint: aps.source_endpoint,
777 cluster: aps.cluster,
778 trans_id: tag,
779 options: af_option::ACK_REQUEST | af_option::DISCOVER_ROUTE,
780 radius: 30,
781 data: payload,
782 })
783 .await?;
784 Ok(u16::from(tag))
785 }
786
787 async fn send_broadcast(
788 &self,
789 destination: NodeId,
790 aps: Aps,
791 payload: Vec<u8>,
792 ) -> Result<(), HostError> {
793 if aps.profile == zigbee_zdo::PROFILE_ID && aps.destination_endpoint == 0 {
794 let (tsn, data) = payload
795 .split_first()
796 .ok_or_else(|| HostError::Invalid("empty ZDO frame".into()))?;
797 return self
798 .ok(Request::ZdoSendData {
799 destination,
800 tsn: *tsn,
801 cluster: aps.cluster,
802 data: data.to_vec(),
803 })
804 .await;
805 }
806 self.register_endpoint(aps.source_endpoint, aps.profile)
807 .await?;
808 self.ok(Request::AfDataRequestExt {
809 addr_mode: addr_mode::BROADCAST,
810 destination: u64::from(destination),
811 destination_endpoint: aps.destination_endpoint,
812 destination_pan: 0,
813 source_endpoint: aps.source_endpoint,
814 cluster: aps.cluster,
815 trans_id: self.next_tag(),
816 options: 0,
817 radius: 30,
818 data: payload,
819 })
820 .await
821 }
822
823 async fn network_info(&self) -> Result<NetworkInfo, HostError> {
824 self.read_network_info().await
825 }
826
827 async fn backup(&self) -> Result<Backup, HostError> {
828 let (_, pan_id, extended_pan_id, channel) = self.nwk_info().await?;
829 let (sequence_number, key) = self.network_key().await?;
830 let frame_counter = self.frame_counter().await?;
831 let seed = self
832 .znp
833 .nv_read(nv::TCLK_SEED)
834 .await?
835 .and_then(|v| <[u8; 16]>::try_from(v.as_slice()).ok())
836 .map(Key);
837 let v = self.znp.version();
838 Ok(Backup {
839 metadata: Metadata {
840 format: backup::FORMAT.into(),
841 version: 1,
842 source: concat!("zigbee-bridge@", env!("CARGO_PKG_VERSION")).into(),
843 internal: Internal {
844 created_unix: Some(now_unix()),
845 ezsp_version: None,
846 firmware: Some(v.firmware()),
847 },
848 },
849 stack_specific: seed.map(|tclk_seed| StackSpecific {
850 ezsp: None,
851 zstack: Some(ZstackSpecific { tclk_seed }),
852 }),
853 coordinator_ieee: self.ieee().await?,
854 pan_id,
855 extended_pan_id,
856 nwk_update_id: 0,
857 security_level: 5,
858 channel,
859 channel_mask: vec![channel],
860 network_key: NetworkKey {
861 key,
862 sequence_number,
863 frame_counter,
864 },
865 devices: Vec::<BackupDevice>::new(),
866 })
867 }
868
869 async fn active_scan(&self, channel_mask: u32) -> Result<Vec<Beacon>, HostError> {
870 let (tx, rx) = oneshot::channel();
871 if let Ok(mut d) = self.shared.discovery.lock() {
872 if d.is_some() {
873 return Err(HostError::Invalid("a scan is already running".into()));
874 }
875 *d = Some((Vec::new(), tx));
876 }
877 let sent = self
878 .ok(Request::ZdoNwkDiscovery {
879 channel_mask,
880 scan_duration: 3,
881 })
882 .await;
883 if let Err(e) = sent {
884 if let Ok(mut d) = self.shared.discovery.lock() {
885 *d = None;
886 }
887 return Err(e);
888 }
889 match tokio::time::timeout(Duration::from_secs(30), rx).await {
890 Ok(Ok(result)) => result,
891 _ => {
892 if let Ok(mut d) = self.shared.discovery.lock() {
893 *d = None;
894 }
895 Err(HostError::Ncp("network discovery did not complete".into()))
896 }
897 }
898 }
899
900 async fn leave(&self) -> Result<(), HostError> {
901 self.znp
903 .nv_write(
904 nv::STARTUP_OPTION,
905 &[startup_option::CLEAR_STATE | startup_option::CLEAR_CONFIG],
906 )
907 .await?;
908 self.reset().await
909 }
910
911 async fn energy_scan(&self, channel_mask: u32) -> Result<Vec<(u8, i8)>, HostError> {
912 let (tx, rx) = oneshot::channel();
913 if let Ok(mut s) = self.shared.scan.lock() {
914 if s.is_some() {
915 return Err(HostError::Invalid("a scan is already running".into()));
916 }
917 *s = Some(tx);
918 }
919 let sent = self
920 .ok(Request::ZdoMgmtNwkUpdate {
921 destination: 0x0000,
922 addr_mode: addr_mode::SHORT,
923 channel_mask,
924 scan_duration: 3,
925 scan_count: 1,
926 manager: 0x0000,
927 })
928 .await;
929 if let Err(e) = sent {
930 if let Ok(mut s) = self.shared.scan.lock() {
931 *s = None;
932 }
933 return Err(e);
934 }
935 match tokio::time::timeout(Duration::from_secs(30), rx).await {
936 Ok(Ok(result)) => result,
937 _ => {
938 if let Ok(mut s) = self.shared.scan.lock() {
939 *s = None;
940 }
941 Err(HostError::Ncp("energy scan did not complete".into()))
942 }
943 }
944 }
945}