Skip to main content

zigbee_host/
ezsp_adapter.rs

1//! The [`Adapter`] for Silicon Labs EmberZNet NCPs over EZSP.
2//!
3//! Security follows Zigbee 3.0 with hashed trust center link keys: joining
4//! devices use the well-known key (or their install code key) to receive
5//! the network key, then ask the trust center for a link key of their own,
6//! which the NCP derives from a random root key and the device's IEEE
7//! address. The root key is in every backup, so the derived keys survive a
8//! restore without a key table entry per device.
9
10use std::sync::atomic::{AtomicU16, Ordering};
11use std::sync::{Arc, Mutex};
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14use tokio::io::{AsyncRead, AsyncWrite};
15use tokio::sync::{mpsc, watch};
16use zigbee_ezsp::client::{ClientConfig, Ezsp, EzspEvent, NcpInfo};
17use zigbee_ezsp::ids::{
18    self, aps_option, config, decision, ext_security, policy, security, tc_decision, value,
19};
20use zigbee_ezsp::types::{InitialSecurityState, NetworkParameters, SecManContext};
21use zigbee_ezsp::{ApsFrame, Callback, Command, Response, Status};
22use zigbee_primitives::{ExtPanId, Ieee, Key, NodeId};
23
24use crate::adapter::{
25    Adapter, AdapterEvent, AdapterInfo, Aps, Beacon, JoinPolicy, NetworkInfo, NetworkSettings,
26    StartMode, StartOutcome,
27};
28use crate::backup::{
29    self, Backup, BackupDevice, EzspSpecific, Internal, LinkKey, Metadata, NetworkKey,
30    StackSpecific,
31};
32use crate::error::HostError;
33
34/// How long to wait for the network to come up or go down.
35const NETWORK_TIMEOUT: Duration = Duration::from_secs(10);
36/// Silicon Labs' manufacturer code, which the coordinator reports.
37const MANUFACTURER_CODE: u16 = 0x1049;
38/// Every 2.4 GHz channel.
39const ALL_CHANNELS: u32 = 0x07FF_F800;
40/// Default APS options for unicasts.
41const UNICAST_OPTIONS: u16 =
42    aps_option::RETRY | aps_option::ENABLE_ROUTE_DISCOVERY | aps_option::ENABLE_ADDRESS_DISCOVERY;
43
44/// The clusters the host's endpoint 1 serves and uses; devices bind their
45/// reporting clusters to it.
46const ENDPOINT_INPUT_CLUSTERS: &[u16] = &[
47    0x0000, 0x0003, 0x0006, 0x000A, 0x0019, 0x0300, 0x0402, 0x0405, 0x0500, 0x0702, 0x0B04,
48];
49const ENDPOINT_OUTPUT_CLUSTERS: &[u16] = &[
50    0x0000, 0x0001, 0x0003, 0x0004, 0x0005, 0x0006, 0x0008, 0x000F, 0x0012, 0x0020, 0x0101, 0x0102,
51    0x0201, 0x0202, 0x0300, 0x0400, 0x0402, 0x0403, 0x0405, 0x0406, 0x0500, 0x0502, 0x0702, 0x0B04,
52    0x0B05,
53];
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56enum NetState {
57    Unknown,
58    Up,
59    Down,
60}
61
62type ScanResult = Result<(Vec<(u8, i8)>, Vec<Beacon>), HostError>;
63
64struct ScanCollector {
65    results: Vec<(u8, i8)>,
66    beacons: Vec<Beacon>,
67    done: Option<tokio::sync::oneshot::Sender<ScanResult>>,
68}
69
70/// An EmberZNet NCP.
71pub struct EzspAdapter {
72    ezsp: Ezsp,
73    info: NcpInfo,
74    net: watch::Receiver<NetState>,
75    scan: Arc<Mutex<Option<ScanCollector>>>,
76    tag: AtomicU16,
77}
78
79impl std::fmt::Debug for EzspAdapter {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        f.debug_struct("EzspAdapter")
82            .field("info", &self.info)
83            .finish_non_exhaustive()
84    }
85}
86
87fn now_unix() -> u64 {
88    SystemTime::now()
89        .duration_since(UNIX_EPOCH)
90        .map(|d| d.as_secs())
91        .unwrap_or(0)
92}
93
94fn translate(
95    cb: Callback,
96    net: &watch::Sender<NetState>,
97    scan: &Mutex<Option<ScanCollector>>,
98) -> Option<AdapterEvent> {
99    match cb {
100        Callback::StackStatus { status } => {
101            if status.is_network_up() {
102                let _ = net.send(NetState::Up);
103                Some(AdapterEvent::NetworkUp)
104            } else if status.is_network_down() {
105                let _ = net.send(NetState::Down);
106                Some(AdapterEvent::NetworkDown)
107            } else {
108                tracing::debug!(%status, "stack status");
109                None
110            }
111        }
112        Callback::IncomingMessage {
113            kind,
114            aps,
115            info,
116            payload,
117        } => Some(AdapterEvent::Message {
118            source: info.sender,
119            source_ieee: info.sender_ieee,
120            aps: Aps {
121                profile: aps.profile_id,
122                cluster: aps.cluster_id,
123                source_endpoint: aps.source_endpoint,
124                destination_endpoint: aps.destination_endpoint,
125            },
126            broadcast: !matches!(kind, ids::incoming::UNICAST | ids::incoming::UNICAST_REPLY),
127            group: matches!(
128                kind,
129                ids::incoming::MULTICAST | ids::incoming::MULTICAST_LOOPBACK
130            )
131            .then_some(aps.group_id),
132            lqi: info.last_hop_lqi,
133            rssi: Some(info.last_hop_rssi),
134            payload,
135        }),
136        Callback::TrustCenterJoin {
137            node_id,
138            ieee,
139            status,
140            decision,
141            parent,
142        } => match status {
143            ids::device_update::DEVICE_LEFT => Some(AdapterEvent::Left { nwk: node_id, ieee }),
144            _ if decision == ids::join_decision::DENY_JOIN => {
145                tracing::info!(%ieee, "trust center denied a join");
146                None
147            }
148            ids::device_update::UNSECURED_JOIN => Some(AdapterEvent::Joined {
149                nwk: node_id,
150                ieee,
151                parent,
152                rejoin: false,
153            }),
154            _ => Some(AdapterEvent::Joined {
155                nwk: node_id,
156                ieee,
157                parent,
158                rejoin: true,
159            }),
160        },
161        Callback::ZigbeeKeyEstablishment { partner, status } => {
162            use ids::key_status::*;
163            let success = matches!(
164                status,
165                TRUST_CENTER_LINK_KEY_ESTABLISHED
166                    | TC_RESPONDED_TO_KEY_REQUEST
167                    | VERIFY_LINK_KEY_SUCCESS
168            );
169            tracing::debug!(%partner, status, "key establishment");
170            Some(AdapterEvent::KeyExchange {
171                ieee: partner,
172                success,
173            })
174        }
175        Callback::IncomingRouteRecord {
176            source,
177            ieee,
178            last_hop_lqi,
179            last_hop_rssi,
180            relays,
181        } => Some(AdapterEvent::RouteRecord {
182            source,
183            ieee: Some(ieee),
184            relays,
185            lqi: Some(last_hop_lqi),
186            rssi: Some(last_hop_rssi),
187        }),
188        Callback::MessageSent { status, tag, .. } => Some(AdapterEvent::Delivery {
189            tag,
190            delivered: status.is_ok(),
191        }),
192        Callback::EnergyScanResult { channel, max_rssi } => {
193            if let Ok(mut s) = scan.lock() {
194                if let Some(c) = s.as_mut() {
195                    c.results.push((channel, max_rssi));
196                }
197            }
198            None
199        }
200        Callback::NetworkFound {
201            channel,
202            pan_id,
203            extended_pan_id,
204            allowing_join,
205            nwk_update_id,
206            lqi,
207            rssi,
208            ..
209        } => {
210            if let Ok(mut s) = scan.lock() {
211                if let Some(c) = s.as_mut() {
212                    if c.beacons.len() < 256 {
213                        c.beacons.push(Beacon {
214                            channel,
215                            pan_id,
216                            extended_pan_id,
217                            permit_joining: allowing_join,
218                            nwk_update_id,
219                            lqi,
220                            rssi: Some(rssi),
221                        });
222                    }
223                }
224            }
225            None
226        }
227        Callback::ScanComplete { status, channel } => {
228            if let Some(mut c) = scan.lock().ok().and_then(|mut s| s.take()) {
229                let result = if status.is_ok() {
230                    Ok((
231                        std::mem::take(&mut c.results),
232                        std::mem::take(&mut c.beacons),
233                    ))
234                } else {
235                    Err(HostError::Ncp(format!(
236                        "scan failed on channel {channel}: {status}"
237                    )))
238                };
239                if let Some(done) = c.done.take() {
240                    let _ = done.send(result);
241                }
242            }
243            None
244        }
245        Callback::IdConflict { node_id } => {
246            tracing::warn!(node_id, "network address conflict");
247            None
248        }
249        other => {
250            tracing::trace!(?other, "unhandled callback");
251            None
252        }
253    }
254}
255
256impl EzspAdapter {
257    /// Connect to an NCP over `io`. Returns the adapter and its events.
258    pub async fn connect<T>(
259        io: T,
260        config: ClientConfig,
261    ) -> Result<(EzspAdapter, mpsc::UnboundedReceiver<AdapterEvent>), HostError>
262    where
263        T: AsyncRead + AsyncWrite + Send + 'static,
264    {
265        let (ezsp, info, mut ezsp_events) = Ezsp::start(io, config).await?;
266        tracing::info!(protocol = info.protocol.0, firmware = %info.stack_version, "EZSP NCP connected");
267        let (net_tx, net) = watch::channel(NetState::Unknown);
268        let scan: Arc<Mutex<Option<ScanCollector>>> = Arc::new(Mutex::new(None));
269        let (tx, rx) = mpsc::unbounded_channel();
270        let scan_for_task = scan.clone();
271        tokio::spawn(async move {
272            while let Some(event) = ezsp_events.recv().await {
273                let out = match event {
274                    EzspEvent::Callback(cb) => translate(cb, &net_tx, &scan_for_task),
275                    EzspEvent::Down(why) => Some(AdapterEvent::Failed(why)),
276                };
277                if let Some(out) = out {
278                    if tx.send(out).is_err() {
279                        break;
280                    }
281                }
282            }
283        });
284        Ok((
285            EzspAdapter {
286                ezsp,
287                info,
288                net,
289                scan,
290                tag: AtomicU16::new(1),
291            },
292            rx,
293        ))
294    }
295
296    /// The NCP's start-up report.
297    pub fn ncp_info(&self) -> &NcpInfo {
298        &self.info
299    }
300
301    async fn wait_net(&self, want: NetState) -> Result<(), HostError> {
302        let mut net = self.net.clone();
303        let reached = matches!(
304            tokio::time::timeout(NETWORK_TIMEOUT, net.wait_for(|s| *s == want)).await,
305            Ok(Ok(_))
306        );
307        if reached {
308            Ok(())
309        } else {
310            Err(HostError::Ncp(format!(
311                "network did not go {}",
312                if want == NetState::Up { "up" } else { "down" }
313            )))
314        }
315    }
316
317    async fn ok(&self, command: Command) -> Result<(), HostError> {
318        self.ezsp.call_ok(command).await.map_err(HostError::from)
319    }
320
321    /// Configuration that must be set after every NCP reset, before the
322    /// network starts.
323    async fn configure(&self) -> Result<(), HostError> {
324        let required = [
325            (config::STACK_PROFILE, ids::STACK_PROFILE_ZIGBEE_PRO),
326            (config::SECURITY_LEVEL, ids::SECURITY_LEVEL_Z3),
327            (config::SUPPORTED_NETWORKS, 1),
328        ];
329        for (id, v) in required {
330            self.ezsp.set_config(id, v).await?;
331        }
332        // Tuning the firmware may refuse (its build fixes some sizes).
333        let tuning = [
334            (config::MAX_HOPS, 30),
335            (config::INDIRECT_TRANSMISSION_TIMEOUT, 7680),
336            (config::TRUST_CENTER_ADDRESS_CACHE_SIZE, 2),
337            (config::MAX_END_DEVICE_CHILDREN, 32),
338            (config::END_DEVICE_POLL_TIMEOUT, 8),
339            (config::TRANSIENT_KEY_TIMEOUT_S, 300),
340        ];
341        for (id, v) in tuning {
342            if let Err(e) = self.ezsp.set_config(id, v).await {
343                tracing::warn!(config_id = id, value = v, error = %e, "NCP kept its own configuration value");
344            }
345        }
346        self.ezsp
347            .set_policy(
348                policy::BINDING_MODIFICATION,
349                decision::CHECK_BINDING_MODIFICATIONS_ARE_VALID_ENDPOINT_CLUSTERS,
350            )
351            .await?;
352        self.ezsp
353            .set_policy(
354                policy::MESSAGE_CONTENTS_IN_CALLBACK,
355                decision::MESSAGE_TAG_ONLY_IN_CALLBACK,
356            )
357            .await?;
358        self.ezsp
359            .set_policy(
360                policy::TC_KEY_REQUEST,
361                decision::ALLOW_TC_KEY_REQUESTS_AND_SEND_CURRENT_KEY,
362            )
363            .await?;
364        self.ezsp
365            .set_policy(policy::APP_KEY_REQUEST, decision::DENY_APP_KEY_REQUESTS)
366            .await?;
367        self.ezsp
368            .set_policy(policy::TRUST_CENTER, tc_decision::ALLOW_UNSECURED_REJOINS)
369            .await?;
370        self.ok(Command::SetManufacturerCode {
371            code: MANUFACTURER_CODE,
372        })
373        .await?;
374        let endpoint = Command::AddEndpoint {
375            endpoint: 1,
376            profile_id: zigbee_zcl::PROFILE_HOME_AUTOMATION,
377            device_id: 0x0005,
378            device_version: 0,
379            input_clusters: ENDPOINT_INPUT_CLUSTERS.to_vec(),
380            output_clusters: ENDPOINT_OUTPUT_CLUSTERS.to_vec(),
381        };
382        if let Err(e) = self.ok(endpoint).await {
383            // After a soft restart without a reset the endpoint exists.
384            tracing::warn!(error = %e, "adding endpoint 1");
385        }
386        Ok(())
387    }
388
389    async fn network_parameters(&self) -> Result<(u8, NetworkParameters), HostError> {
390        match self.ezsp.call(Command::GetNetworkParameters).await? {
391            Response::GetNetworkParameters {
392                status,
393                node_type,
394                parameters,
395            } if status.is_ok() => Ok((node_type, parameters)),
396            other => Err(HostError::Ncp(format!("getNetworkParameters: {other:?}"))),
397        }
398    }
399
400    async fn export_key(&self, key_type: u8) -> Result<Key, HostError> {
401        match self
402            .ezsp
403            .call(Command::ExportKey {
404                context: SecManContext::for_key(key_type),
405            })
406            .await?
407        {
408            Response::ExportKey { status, key, .. } if status.is_ok() => Ok(key),
409            other => Err(HostError::Ncp(format!("exportKey({key_type}): {other:?}"))),
410        }
411    }
412
413    async fn eui64(&self) -> Result<Ieee, HostError> {
414        match self.ezsp.call(Command::GetEui64).await? {
415            Response::GetEui64 { ieee } => Ok(ieee),
416            other => Err(HostError::Ncp(format!("getEui64: {other:?}"))),
417        }
418    }
419
420    async fn leave_network(&self) -> Result<(), HostError> {
421        self.ok(Command::LeaveNetwork { options: 0 }).await?;
422        self.wait_net(NetState::Down).await?;
423        tokio::time::sleep(Duration::from_millis(200)).await;
424        Ok(())
425    }
426
427    async fn form(
428        &self,
429        settings: &NetworkSettings,
430        tc_root: Key,
431        restore: Option<&Backup>,
432    ) -> Result<(), HostError> {
433        let mut bitmask = security::TRUST_CENTER_GLOBAL_LINK_KEY
434            | security::HAVE_PRECONFIGURED_KEY
435            | security::HAVE_NETWORK_KEY
436            | security::TRUST_CENTER_USES_HASHED_LINK_KEY
437            | security::REQUIRE_ENCRYPTED_KEY;
438        let mut sequence = 0;
439        if let Some(backup) = restore {
440            bitmask |= security::NO_FRAME_COUNTER_RESET;
441            sequence = backup.network_key.sequence_number;
442            self.ezsp
443                .set_value(
444                    value::NWK_FRAME_COUNTER,
445                    backup.restore_frame_counter().to_le_bytes().to_vec(),
446                )
447                .await?;
448        }
449        self.ok(Command::SetInitialSecurityState {
450            state: InitialSecurityState {
451                bitmask,
452                preconfigured_key: tc_root,
453                network_key: settings.network_key,
454                network_key_sequence: sequence,
455                preconfigured_trust_center: Ieee::ZERO,
456            },
457        })
458        .await?;
459        let ext =
460            ext_security::JOINER_GLOBAL_LINK_KEY | ext_security::NWK_LEAVE_REQUEST_NOT_ALLOWED;
461        self.ezsp
462            .set_value(value::EXTENDED_SECURITY_BITMASK, ext.to_le_bytes().to_vec())
463            .await?;
464        if restore.is_none() {
465            if let Err(e) = self.ok(Command::ClearKeyTable).await {
466                tracing::warn!(error = %e, "clearing the key table");
467            }
468        }
469        let parameters = NetworkParameters {
470            extended_pan_id: settings.extended_pan_id,
471            pan_id: settings.pan_id,
472            radio_tx_power: settings.tx_power.unwrap_or(5),
473            radio_channel: settings.channel,
474            join_method: 0,
475            nwk_manager_id: 0,
476            nwk_update_id: restore.map(|b| b.nwk_update_id).unwrap_or(0),
477            channels: ALL_CHANNELS,
478        };
479        self.ok(Command::FormNetwork { parameters }).await?;
480        self.wait_net(NetState::Up).await?;
481        if let Err(e) = self
482            .ezsp
483            .set_value(value::STACK_TOKEN_WRITING, vec![1])
484            .await
485        {
486            tracing::warn!(error = %e, "enabling stack token writing");
487        }
488        Ok(())
489    }
490
491    async fn restore(&self, backup: &Backup) -> Result<(), HostError> {
492        let ieee = self.eui64().await?;
493        if ieee != backup.coordinator_ieee {
494            // The custom EUI-64 token can be written once; all ones means unset.
495            let token = match self
496                .ezsp
497                .call(Command::GetMfgToken {
498                    token_id: ids::mfg_token::CUSTOM_EUI_64,
499                })
500                .await?
501            {
502                Response::GetMfgToken { data } => data,
503                other => return Err(HostError::Ncp(format!("getMfgToken: {other:?}"))),
504            };
505            if token.len() != 8 || token.iter().any(|b| *b != 0xFF) {
506                return Err(HostError::RestoreRefused(format!(
507                    "this coordinator is {ieee} and its IEEE address token is already written; the backup needs {}",
508                    backup.coordinator_ieee
509                )));
510            }
511            self.ok(Command::SetMfgToken {
512                token_id: ids::mfg_token::CUSTOM_EUI_64,
513                data: backup.coordinator_ieee.to_le_bytes().to_vec(),
514            })
515            .await?;
516            return Err(HostError::RestartRequired);
517        }
518        let key_table = self
519            .ezsp
520            .get_config(config::KEY_TABLE_SIZE)
521            .await
522            .unwrap_or(0);
523        let keys: Vec<(Ieee, &LinkKey)> = backup
524            .devices
525            .iter()
526            .filter_map(|d| d.link_key.as_ref().map(|k| (d.ieee_address, k)))
527            .collect();
528        if keys.len() > usize::from(key_table) {
529            return Err(HostError::RestoreRefused(format!(
530                "{} link keys do not fit the NCP's key table of {key_table}",
531                keys.len()
532            )));
533        }
534        for index in 0..key_table {
535            let result = match keys.get(usize::from(index)) {
536                Some((ieee, link)) => {
537                    self.ok(Command::ImportLinkKey {
538                        index: index as u8,
539                        ieee: *ieee,
540                        key: link.key,
541                    })
542                    .await
543                }
544                None => {
545                    self.ok(Command::EraseKeyTableEntry { index: index as u8 })
546                        .await
547                }
548            };
549            if let Err(e) = result {
550                tracing::warn!(index, error = %e, "restoring key table entry");
551            }
552        }
553        // A backup from another family has no root key: a new one, with the
554        // devices' own link keys (if the backup has them) in the key table.
555        let tc_root = match backup.stack_specific.as_ref().and_then(|s| s.ezsp.as_ref()) {
556            Some(e) => e.hashed_tclk,
557            None => {
558                tracing::info!(
559                    keys = keys.len(),
560                    "restoring a backup from another coordinator family"
561                );
562                random_key()?
563            }
564        };
565        let settings = NetworkSettings {
566            channel: backup.channel,
567            pan_id: backup.pan_id,
568            extended_pan_id: backup.extended_pan_id,
569            network_key: backup.network_key.key,
570            tx_power: None,
571        };
572        self.form(&settings, tc_root, Some(backup)).await
573    }
574
575    async fn after_up(&self, settings_power: Option<i8>) -> Result<NetworkInfo, HostError> {
576        self.ok(Command::SetConcentrator {
577            on: true,
578            kind: ids::concentrator::HIGH_RAM,
579            min_time: 5,
580            max_time: 60,
581            route_error_threshold: 3,
582            delivery_failure_threshold: 1,
583            max_hops: 0,
584        })
585        .await?;
586        if let Err(e) = self
587            .ezsp
588            .call(Command::SetSourceRouteDiscoveryMode { mode: 2 })
589            .await
590        {
591            tracing::warn!(error = %e, "source route discovery mode");
592        }
593        if let Some(power) = settings_power {
594            if let Err(e) = self.ok(Command::SetRadioPower { power }).await {
595                tracing::warn!(power, error = %e, "setting radio power");
596            }
597        }
598        self.read_network_info().await
599    }
600
601    async fn read_network_info(&self) -> Result<NetworkInfo, HostError> {
602        let (_, p) = self.network_parameters().await?;
603        let nwk = match self.ezsp.call(Command::GetNodeId).await? {
604            Response::GetNodeId { node_id } => node_id,
605            _ => 0,
606        };
607        Ok(NetworkInfo {
608            ieee: self.eui64().await?,
609            nwk,
610            channel: p.radio_channel,
611            pan_id: p.pan_id,
612            extended_pan_id: p.extended_pan_id,
613            nwk_update_id: p.nwk_update_id,
614        })
615    }
616
617    fn next_tag(&self) -> u16 {
618        // Protocol 13 carries one-byte tags.
619        let tag = self.tag.fetch_add(1, Ordering::Relaxed);
620        if self.ezsp.version().sl_status() {
621            tag
622        } else {
623            tag & 0xFF
624        }
625    }
626}
627
628fn describe(p: &NetworkParameters) -> String {
629    format!(
630        "channel {}, PAN {:04x}, extended PAN {}",
631        p.radio_channel, p.pan_id, p.extended_pan_id
632    )
633}
634
635fn random_key() -> Result<Key, HostError> {
636    let mut k = [0u8; 16];
637    getrandom::fill(&mut k).map_err(|e| HostError::Io(format!("random: {e}")))?;
638    Ok(Key(k))
639}
640
641impl Adapter for EzspAdapter {
642    fn info(&self) -> AdapterInfo {
643        let v = self.info.stack_version;
644        AdapterInfo {
645            kind: "ezsp",
646            firmware: format!("{}.{}.{}.{}", v.major, v.minor, v.patch, v.special),
647            protocol: self.info.protocol.0,
648            reports_key_exchange: true,
649        }
650    }
651
652    async fn start(&self, mode: StartMode) -> Result<(StartOutcome, NetworkInfo), HostError> {
653        self.configure().await?;
654        let init = self
655            .ezsp
656            .call(Command::NetworkInit {
657                bitmask: ids::network_init::PARENT_INFO_IN_TOKEN
658                    | ids::network_init::END_DEVICE_REJOIN_ON_REBOOT,
659            })
660            .await?;
661        let status = init.status().unwrap_or(Status::SL_OK);
662        let has_network = status.is_ok();
663        if !has_network && !status.is_not_joined() {
664            return Err(HostError::Ncp(format!("networkInit: {status}")));
665        }
666        if has_network {
667            self.wait_net(NetState::Up).await?;
668        }
669
670        match mode {
671            StartMode::Restore(backup) => {
672                if has_network {
673                    self.leave_network().await?;
674                }
675                self.restore(&backup).await?;
676                Ok((StartOutcome::Restored, self.after_up(None).await?))
677            }
678            StartMode::Normal {
679                settings,
680                replace_other,
681            } => {
682                if has_network {
683                    let (node_type, p) = self.network_parameters().await?;
684                    let key = self.export_key(ids::key_type::NETWORK).await?;
685                    let same = node_type == ids::node_type::COORDINATOR
686                        && p.pan_id == settings.pan_id
687                        && p.extended_pan_id == settings.extended_pan_id
688                        && key == settings.network_key;
689                    if same {
690                        return Ok((
691                            StartOutcome::Resumed,
692                            self.after_up(settings.tx_power).await?,
693                        ));
694                    }
695                    if !replace_other {
696                        return Err(HostError::NetworkMismatch {
697                            found: describe(&p),
698                        });
699                    }
700                    tracing::warn!(found = %describe(&p), "leaving the NCP's other network, as configured");
701                    self.leave_network().await?;
702                }
703                self.form(&settings, random_key()?, None).await?;
704                Ok((
705                    StartOutcome::Formed,
706                    self.after_up(settings.tx_power).await?,
707                ))
708            }
709        }
710    }
711
712    async fn permit_join(&self, seconds: u8, join: &JoinPolicy) -> Result<(), HostError> {
713        if seconds > 0 {
714            if !join.install_code_only {
715                // The well-known key for any device, while open.
716                self.ok(Command::ImportTransientKey {
717                    ieee: Ieee::ZERO,
718                    key: Key::ZIGBEE_ALLIANCE_09,
719                })
720                .await?;
721            }
722            let mut decision_bits = tc_decision::ALLOW_JOINS | tc_decision::ALLOW_UNSECURED_REJOINS;
723            if join.install_code_only {
724                decision_bits |= tc_decision::JOINS_USE_INSTALL_CODE_KEY;
725            }
726            self.ezsp
727                .set_policy(policy::TRUST_CENTER, decision_bits)
728                .await?;
729        } else {
730            self.ezsp
731                .set_policy(policy::TRUST_CENTER, tc_decision::ALLOW_UNSECURED_REJOINS)
732                .await?;
733        }
734        self.ok(Command::PermitJoining { duration: seconds })
735            .await?;
736        if seconds == 0 {
737            self.ok(Command::ClearTransientLinkKeys).await?;
738        }
739        Ok(())
740    }
741
742    async fn add_join_key(&self, ieee: Ieee, key: Key) -> Result<(), HostError> {
743        self.ok(Command::ImportTransientKey { ieee, key }).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        let frame = ApsFrame {
754            profile_id: aps.profile,
755            cluster_id: aps.cluster,
756            source_endpoint: aps.source_endpoint,
757            destination_endpoint: aps.destination_endpoint,
758            options: UNICAST_OPTIONS,
759            group_id: 0,
760            sequence: 0,
761        };
762        match self
763            .ezsp
764            .call(Command::SendUnicast {
765                kind: ids::outgoing::DIRECT,
766                destination: nwk,
767                aps: frame,
768                tag,
769                payload,
770            })
771            .await?
772        {
773            Response::Sent { status, .. } if status.is_ok() => Ok(tag),
774            Response::Sent { status, .. } => Err(HostError::Ncp(format!(
775                "sendUnicast to {nwk:#06x}: {status}"
776            ))),
777            other => Err(HostError::Ncp(format!("sendUnicast: {other:?}"))),
778        }
779    }
780
781    async fn send_broadcast(
782        &self,
783        destination: NodeId,
784        aps: Aps,
785        payload: Vec<u8>,
786    ) -> Result<(), HostError> {
787        let tag = self.next_tag();
788        let frame = ApsFrame {
789            profile_id: aps.profile,
790            cluster_id: aps.cluster,
791            source_endpoint: aps.source_endpoint,
792            destination_endpoint: aps.destination_endpoint,
793            options: aps_option::NONE,
794            group_id: 0,
795            sequence: 0,
796        };
797        let command = Command::SendBroadcast {
798            alias: 0,
799            destination,
800            nwk_sequence: 0,
801            aps: frame,
802            radius: 30,
803            tag,
804            payload,
805        };
806        match self.ezsp.call(command).await? {
807            Response::Sent { status, .. } if status.is_ok() => Ok(()),
808            other => Err(HostError::Ncp(format!("sendBroadcast: {other:?}"))),
809        }
810    }
811
812    async fn network_info(&self) -> Result<NetworkInfo, HostError> {
813        self.read_network_info().await
814    }
815
816    async fn backup(&self) -> Result<Backup, HostError> {
817        let (_, p) = self.network_parameters().await?;
818        let network_key = self.export_key(ids::key_type::NETWORK).await?;
819        let tc_root = self.export_key(ids::key_type::TC_LINK).await?;
820        let (sequence_number, frame_counter) =
821            match self.ezsp.call(Command::GetNetworkKeyInfo).await? {
822                Response::GetNetworkKeyInfo { status, info } if status.is_ok() => {
823                    (info.network_key_sequence, info.network_key_frame_counter)
824                }
825                other => return Err(HostError::Ncp(format!("getNetworkKeyInfo: {other:?}"))),
826            };
827        let key_table = self
828            .ezsp
829            .get_config(config::KEY_TABLE_SIZE)
830            .await
831            .unwrap_or(0);
832        let mut devices = Vec::new();
833        for index in 0..key_table.min(255) {
834            if let Ok(Response::ExportLinkKeyByIndex {
835                status,
836                context,
837                key,
838                metadata,
839            }) = self
840                .ezsp
841                .call(Command::ExportLinkKeyByIndex { index: index as u8 })
842                .await
843            {
844                if status.is_ok() && context.ieee != Ieee::ZERO && context.ieee != Ieee::UNSET {
845                    devices.push(BackupDevice {
846                        nwk_address: None,
847                        ieee_address: context.ieee,
848                        is_child: false,
849                        link_key: Some(LinkKey {
850                            key,
851                            tx_counter: metadata.outgoing_frame_counter,
852                            rx_counter: metadata.incoming_frame_counter,
853                        }),
854                    });
855                }
856            }
857        }
858        let firmware = self.info().firmware;
859        Ok(Backup {
860            metadata: Metadata {
861                format: backup::FORMAT.into(),
862                version: 1,
863                source: concat!("zigbee-bridge@", env!("CARGO_PKG_VERSION")).into(),
864                internal: Internal {
865                    created_unix: Some(now_unix()),
866                    ezsp_version: Some(self.info.protocol.0),
867                    firmware: Some(firmware),
868                },
869            },
870            stack_specific: Some(StackSpecific {
871                ezsp: Some(EzspSpecific {
872                    hashed_tclk: tc_root,
873                }),
874                zstack: None,
875            }),
876            coordinator_ieee: self.eui64().await?,
877            pan_id: p.pan_id,
878            extended_pan_id: p.extended_pan_id,
879            nwk_update_id: p.nwk_update_id,
880            security_level: 5,
881            channel: p.radio_channel,
882            channel_mask: (11..=26).filter(|c| p.channels & (1 << c) != 0).collect(),
883            network_key: NetworkKey {
884                key: network_key,
885                sequence_number,
886                frame_counter,
887            },
888            devices,
889        })
890    }
891
892    async fn active_scan(&self, channel_mask: u32) -> Result<Vec<Beacon>, HostError> {
893        Ok(self.scan(ids::scan_type::ACTIVE, channel_mask).await?.1)
894    }
895
896    async fn leave(&self) -> Result<(), HostError> {
897        let joined = |r: Response| matches!(r, Response::NetworkState { state } if state != ids::network_status::NO_NETWORK);
898        let mut up = joined(self.ezsp.call(Command::NetworkState).await?);
899        if !up {
900            // Bring up a stored network first, so leaving erases it.
901            let init = self
902                .ezsp
903                .call(Command::NetworkInit {
904                    bitmask: ids::network_init::PARENT_INFO_IN_TOKEN,
905                })
906                .await?;
907            if init.status().is_some_and(|s| s.is_ok()) {
908                self.wait_net(NetState::Up).await?;
909                up = true;
910            }
911        }
912        if up {
913            self.leave_network().await?;
914        }
915        if let Err(e) = self.ok(Command::ClearKeyTable).await {
916            tracing::warn!(error = %e, "clearing the key table");
917        }
918        Ok(())
919    }
920
921    async fn energy_scan(&self, channel_mask: u32) -> Result<Vec<(u8, i8)>, HostError> {
922        Ok(self.scan(ids::scan_type::ENERGY, channel_mask).await?.0)
923    }
924}
925
926impl EzspAdapter {
927    async fn scan(&self, scan_type: u8, channel_mask: u32) -> ScanResult {
928        let (tx, rx) = tokio::sync::oneshot::channel();
929        if let Ok(mut s) = self.scan.lock() {
930            if s.is_some() {
931                return Err(HostError::Invalid("a scan is already running".into()));
932            }
933            *s = Some(ScanCollector {
934                results: Vec::new(),
935                beacons: Vec::new(),
936                done: Some(tx),
937            });
938        }
939        let started = self
940            .ezsp
941            .call_ok(Command::StartScan {
942                scan_type,
943                channel_mask,
944                duration: 3,
945            })
946            .await;
947        if let Err(e) = started {
948            if let Ok(mut s) = self.scan.lock() {
949                *s = None;
950            }
951            return Err(e.into());
952        }
953        match tokio::time::timeout(Duration::from_secs(30), rx).await {
954            Ok(Ok(result)) => result,
955            _ => {
956                if let Ok(mut s) = self.scan.lock() {
957                    *s = None;
958                }
959                Err(HostError::Ncp("the scan did not complete".into()))
960            }
961        }
962    }
963}
964
965/// A fresh random network: channel `channel`, random PAN ids and network
966/// key. For a platform that manages keys itself, build
967/// [`NetworkSettings`] from its own values instead.
968pub fn random_network(channel: u8) -> Result<NetworkSettings, HostError> {
969    let mut pan = [0u8; 2];
970    let mut ext = [0u8; 8];
971    getrandom::fill(&mut pan).map_err(|e| HostError::Io(format!("random: {e}")))?;
972    getrandom::fill(&mut ext).map_err(|e| HostError::Io(format!("random: {e}")))?;
973    // 0x0000 and 0xFFF8 to 0xFFFF are reserved PAN ids.
974    let pan_id = u16::from_le_bytes(pan) % 0xFFF7 + 1;
975    Ok(NetworkSettings {
976        channel,
977        pan_id,
978        extended_pan_id: ExtPanId(u64::from_le_bytes(ext)),
979        network_key: random_key()?,
980        tx_power: None,
981    })
982}