Skip to main content

zigbee_host/
deconz_adapter.rs

1//! The [`Adapter`] for dresden elektronik ConBee and RaspBee coordinators
2//! over the deCONZ serial protocol.
3//!
4//! The firmware queues received frames and delivery confirms and says so in
5//! its device state; the adapter reads them whenever a frame reports one
6//! waiting, and asks for the state every few seconds in case a notice was
7//! lost. Network settings are parameters: the adapter takes the network
8//! offline, writes them, and brings it back up.
9//!
10//! The firmware reports no joins or leaves (the host learns of a device from
11//! its announce), keeps one global trust center link key rather than a key
12//! per device, and cannot restrict joining to install codes; the adapter
13//! refuses `install_code_only` rather than pretend.
14
15use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
16use std::sync::{Arc, Mutex};
17use std::time::{Duration, SystemTime, UNIX_EPOCH};
18
19use tokio::io::{AsyncRead, AsyncWrite};
20use tokio::sync::{mpsc, oneshot, watch};
21use zigbee_deconz::client::{ClientConfig, Deconz, DeconzError, DeconzEvent};
22use zigbee_deconz::ids::{device_state, net_state, param, security_mode, status, tx_option};
23use zigbee_deconz::{Address, ApsRequest, Request, Response};
24use zigbee_primitives::wire::Reader;
25use zigbee_primitives::{ExtPanId, Ieee, Key, NodeId};
26
27use crate::adapter::{
28    Adapter, AdapterEvent, AdapterInfo, Aps, Beacon, JoinPolicy, NetworkInfo, NetworkSettings,
29    StartMode, StartOutcome,
30};
31use crate::backup::{self, Backup, Internal, Metadata, NetworkKey};
32use crate::error::HostError;
33
34/// How long the network may take to come up or go down.
35const NETWORK_TIMEOUT: Duration = Duration::from_secs(20);
36/// How often to ask for the device state regardless.
37const STATE_POLL: Duration = Duration::from_secs(5);
38/// The firmware watchdog: it resets the stick unless refreshed.
39const WATCHDOG_TTL: u32 = 600;
40const WATCHDOG_REFRESH: Duration = Duration::from_secs(240);
41/// ZDO cluster of a network update notify.
42const MGMT_NWK_UPDATE_NOTIFY: u16 = 0x8038;
43
44type ScanResult = Result<Vec<(u8, i8)>, HostError>;
45
46struct Shared {
47    /// The network state bits.
48    net: watch::Sender<u8>,
49    scan: Mutex<Option<oneshot::Sender<ScanResult>>>,
50}
51
52/// A ConBee or RaspBee.
53pub struct DeconzAdapter {
54    deconz: Deconz,
55    shared: Arc<Shared>,
56    tag: AtomicU8,
57    protocol: u16,
58    legacy_warned: AtomicBool,
59}
60
61impl std::fmt::Debug for DeconzAdapter {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.debug_struct("DeconzAdapter")
64            .field("firmware", &self.deconz.version().text())
65            .finish_non_exhaustive()
66    }
67}
68
69impl From<DeconzError> for HostError {
70    fn from(e: DeconzError) -> Self {
71        HostError::Ncp(e.to_string())
72    }
73}
74
75fn now_unix() -> u64 {
76    SystemTime::now()
77        .duration_since(UNIX_EPOCH)
78        .map(|d| d.as_secs())
79        .unwrap_or(0)
80}
81
82fn ed_to_dbm(ed: u8) -> i8 {
83    (-100 + i16::from(ed) * 40 / 255) as i8
84}
85
86fn parse_scan_notify(data: &[u8]) -> ScanResult {
87    let mut r = Reader::new(data);
88    let parse = |r: &mut Reader<'_>| -> Result<Vec<(u8, i8)>, zigbee_primitives::wire::Truncated> {
89        let _tsn = r.u8()?;
90        if r.u8()? != 0 {
91            return Ok(Vec::new());
92        }
93        let _total = r.u16()?;
94        let _failures = r.u16()?;
95        let mask = r.u32()?;
96        let count = usize::from(r.u8()?);
97        let energies = r.bytes(count)?;
98        Ok((11..=26u8)
99            .filter(|c| mask & (1 << c) != 0)
100            .zip(energies.iter())
101            .map(|(c, ed)| (c, ed_to_dbm(*ed)))
102            .collect())
103    };
104    parse(&mut r).map_err(|e| HostError::Ncp(format!("network update notify: {e}")))
105}
106
107/// Read every queued frame and confirm the device state says is waiting.
108async fn drain(
109    deconz: &Deconz,
110    mut state: u8,
111    shared: &Shared,
112    tx: &mpsc::UnboundedSender<AdapterEvent>,
113) {
114    // Bounded: a firmware that keeps saying "pending" cannot spin forever.
115    for _ in 0..64 {
116        shared.net.send_replace(state & device_state::NETWORK_MASK);
117        let next = if state & device_state::INDICATION_PENDING != 0 {
118            deconz.request(Request::ApsDataIndication).await
119        } else if state & device_state::CONFIRM_PENDING != 0 {
120            deconz.request(Request::ApsDataConfirm).await
121        } else {
122            return;
123        };
124        match next {
125            Ok(Response::ApsDataIndication(i)) => {
126                state = i.device_state;
127                if i.cluster == MGMT_NWK_UPDATE_NOTIFY
128                    && i.profile == zigbee_zdo::PROFILE_ID
129                    && i.source.nwk() == Some(0x0000)
130                {
131                    if let Some(done) = shared.scan.lock().ok().and_then(|mut s| s.take()) {
132                        let _ = done.send(parse_scan_notify(&i.asdu));
133                        continue;
134                    }
135                }
136                let broadcast = matches!(i.destination, Address::Group(_))
137                    || i.destination.nwk().is_some_and(|n| n >= 0xFFF8);
138                let _ = tx.send(AdapterEvent::Message {
139                    source: i.source.nwk().unwrap_or(0xFFFE),
140                    source_ieee: i.source.ieee(),
141                    aps: Aps {
142                        profile: i.profile,
143                        cluster: i.cluster,
144                        source_endpoint: i.source_endpoint,
145                        destination_endpoint: i.destination_endpoint,
146                    },
147                    broadcast,
148                    group: match i.destination {
149                        Address::Group(g) => Some(g),
150                        _ => None,
151                    },
152                    lqi: i.lqi.unwrap_or(0),
153                    rssi: i.rssi,
154                    payload: i.asdu,
155                });
156            }
157            Ok(Response::ApsDataConfirm(c)) => {
158                state = c.device_state;
159                let _ = tx.send(AdapterEvent::Delivery {
160                    tag: u16::from(c.request_id),
161                    delivered: c.status == 0,
162                });
163            }
164            // Nothing queued after all.
165            Ok(_) | Err(DeconzError::Status { .. }) => return,
166            Err(e) => {
167                tracing::warn!(error = %e, "reading the deCONZ queue");
168                return;
169            }
170        }
171    }
172}
173
174impl DeconzAdapter {
175    /// Connect to a ConBee or RaspBee over `io`. Returns the adapter and
176    /// its events.
177    pub async fn connect<T>(
178        io: T,
179        config: ClientConfig,
180    ) -> Result<(DeconzAdapter, mpsc::UnboundedReceiver<AdapterEvent>), HostError>
181    where
182        T: AsyncRead + AsyncWrite + Send + 'static,
183    {
184        let (deconz, mut events) = Deconz::start(io, config).await?;
185        let v = deconz.version();
186        tracing::info!(firmware = %v.text(), product = v.product(), "deCONZ coordinator connected");
187        let protocol = deconz
188            .read_parameter(param::PROTOCOL_VERSION, &[])
189            .await
190            .ok()
191            .and_then(|v| <[u8; 2]>::try_from(v.as_slice()).ok())
192            .map(u16::from_le_bytes)
193            .unwrap_or(0);
194        if let Err(e) = deconz
195            .write_parameter(param::APP_ZDP_RESPONSE_HANDLING, &1u16.to_le_bytes())
196            .await
197        {
198            tracing::debug!(error = %e, "ZDP response handling");
199        }
200        let shared = Arc::new(Shared {
201            net: watch::channel(net_state::OFFLINE).0,
202            scan: Mutex::new(None),
203        });
204        let (tx, rx) = mpsc::unbounded_channel();
205        let task = (deconz.clone(), shared.clone(), tx.clone());
206        tokio::spawn(async move {
207            let (deconz, shared, tx) = task;
208            let mut tick = tokio::time::interval(STATE_POLL);
209            let mut watchdog = tokio::time::interval(WATCHDOG_REFRESH);
210            loop {
211                tokio::select! {
212                    event = events.recv() => match event {
213                        Some(DeconzEvent::State(s)) => drain(&deconz, s, &shared, &tx).await,
214                        Some(DeconzEvent::Notice(_)) => {}
215                        Some(DeconzEvent::Down(why)) => {
216                            let _ = tx.send(AdapterEvent::Failed(why));
217                            return;
218                        }
219                        None => {
220                            let _ = tx.send(AdapterEvent::Failed("deCONZ events ended".into()));
221                            return;
222                        }
223                    },
224                    _ = tick.tick() => {
225                        if let Ok(Response::DeviceState { device_state }) = deconz.request(Request::DeviceState).await {
226                            drain(&deconz, device_state, &shared, &tx).await;
227                        }
228                    }
229                    _ = watchdog.tick() => {
230                        let _ = deconz.write_parameter(param::WATCHDOG_TTL, &WATCHDOG_TTL.to_le_bytes()).await;
231                    }
232                }
233                if tx.is_closed() {
234                    return;
235                }
236            }
237        });
238        Ok((
239            DeconzAdapter {
240                deconz,
241                shared,
242                tag: AtomicU8::new(1),
243                protocol,
244                legacy_warned: AtomicBool::new(false),
245            },
246            rx,
247        ))
248    }
249
250    async fn read(&self, p: u8) -> Result<Vec<u8>, HostError> {
251        Ok(self.deconz.read_parameter(p, &[]).await?)
252    }
253
254    async fn read_u16(&self, p: u8) -> Result<u16, HostError> {
255        let v = self.read(p).await?;
256        Reader::new(&v)
257            .u16()
258            .map_err(|e| HostError::Ncp(format!("parameter {p:#04x}: {e}")))
259    }
260
261    async fn read_u64(&self, p: u8) -> Result<u64, HostError> {
262        let v = self.read(p).await?;
263        Reader::new(&v)
264            .u64()
265            .map_err(|e| HostError::Ncp(format!("parameter {p:#04x}: {e}")))
266    }
267
268    async fn write(&self, p: u8, value: &[u8]) -> Result<(), HostError> {
269        Ok(self.deconz.write_parameter(p, value).await?)
270    }
271
272    async fn network_key(&self) -> Result<Key, HostError> {
273        let v = self.deconz.read_parameter(param::NETWORK_KEY, &[0]).await?;
274        v.get(1..17)
275            .and_then(|k| <[u8; 16]>::try_from(k).ok())
276            .map(Key)
277            .ok_or_else(|| HostError::Ncp("no network key".into()))
278    }
279
280    async fn device_state(&self) -> Result<u8, HostError> {
281        match self.deconz.request(Request::DeviceState).await? {
282            Response::DeviceState { device_state } => Ok(device_state),
283            other => Err(HostError::Ncp(format!("device state: {other:?}"))),
284        }
285    }
286
287    async fn set_net_state(&self, want: u8) -> Result<(), HostError> {
288        let mut net = self.shared.net.subscribe();
289        self.deconz
290            .request(Request::ChangeNetworkState { state: want })
291            .await?;
292        // The firmware announces the change; ask as well, in case it does
293        // not.
294        let deadline = tokio::time::Instant::now() + NETWORK_TIMEOUT;
295        loop {
296            let s = self.device_state().await? & device_state::NETWORK_MASK;
297            self.shared.net.send_replace(s);
298            if s == want {
299                return Ok(());
300            }
301            let wait = tokio::time::timeout_at(deadline, net.changed()).await;
302            if wait.is_err() {
303                return Err(HostError::Ncp(format!(
304                    "the network did not go {}",
305                    if want == net_state::CONNECTED {
306                        "up"
307                    } else {
308                        "down"
309                    }
310                )));
311            }
312        }
313    }
314
315    /// Whether the stored parameters describe `settings`.
316    async fn holds(&self, settings: &NetworkSettings) -> Result<bool, HostError> {
317        let designed = self.read(param::APS_DESIGNED_COORDINATOR).await?.first() == Some(&1);
318        let up = self.device_state().await? & device_state::NETWORK_MASK == net_state::CONNECTED;
319        let ext = if up {
320            self.read_u64(param::NWK_EXTENDED_PANID).await?
321        } else {
322            self.read_u64(param::APS_EXTENDED_PANID).await?
323        };
324        Ok(designed
325            && self.read_u16(param::NWK_PANID).await? == settings.pan_id
326            && ExtPanId(ext) == settings.extended_pan_id
327            && self.network_key().await.ok() == Some(settings.network_key))
328    }
329
330    async fn form(
331        &self,
332        settings: &NetworkSettings,
333        restore: Option<&Backup>,
334    ) -> Result<(), HostError> {
335        self.set_net_state(net_state::OFFLINE).await?;
336        if let Some(b) = restore {
337            self.write(param::MAC_ADDRESS, &b.coordinator_ieee.to_le_bytes())
338                .await?;
339            let now = Ieee(self.read_u64(param::MAC_ADDRESS).await?);
340            if now != b.coordinator_ieee {
341                return Err(HostError::RestoreRefused(format!(
342                    "this coordinator kept its IEEE address {now}; the backup needs {}",
343                    b.coordinator_ieee
344                )));
345            }
346            self.write(
347                param::NWK_FRAME_COUNTER,
348                &b.restore_frame_counter().to_le_bytes(),
349            )
350            .await?;
351            self.write(param::NWK_UPDATE_ID, &[b.nwk_update_id]).await?;
352        }
353        let ieee = Ieee(self.read_u64(param::MAC_ADDRESS).await?);
354        self.write(param::APS_DESIGNED_COORDINATOR, &[1]).await?;
355        self.write(param::NWK_PANID, &settings.pan_id.to_le_bytes())
356            .await?;
357        self.write(
358            param::APS_EXTENDED_PANID,
359            &settings.extended_pan_id.to_le_bytes(),
360        )
361        .await?;
362        self.write(param::USE_PREDEFINED_NWK_PANID, &[1]).await?;
363        self.write(
364            param::CHANNEL_MASK,
365            &(1u32 << settings.channel).to_le_bytes(),
366        )
367        .await?;
368        let mut key = vec![0];
369        key.extend_from_slice(&settings.network_key.0);
370        self.write(param::NETWORK_KEY, &key).await?;
371        self.write(param::SECURITY_MODE, &[security_mode::TC_LINK_KEY])
372            .await?;
373        self.write(param::TRUST_CENTER_ADDRESS, &ieee.to_le_bytes())
374            .await?;
375        let mut tclk = ieee.to_le_bytes().to_vec();
376        tclk.extend_from_slice(&Key::ZIGBEE_ALLIANCE_09.0);
377        self.write(param::LINK_KEY, &tclk).await?;
378        self.set_net_state(net_state::CONNECTED).await
379    }
380
381    async fn read_network_info(&self) -> Result<NetworkInfo, HostError> {
382        Ok(NetworkInfo {
383            ieee: Ieee(self.read_u64(param::MAC_ADDRESS).await?),
384            nwk: self.read_u16(param::NWK_ADDRESS).await?,
385            channel: self
386                .read(param::CURRENT_CHANNEL)
387                .await?
388                .first()
389                .copied()
390                .unwrap_or(0),
391            pan_id: self.read_u16(param::NWK_PANID).await?,
392            extended_pan_id: ExtPanId(self.read_u64(param::NWK_EXTENDED_PANID).await?),
393            nwk_update_id: self
394                .read(param::NWK_UPDATE_ID)
395                .await?
396                .first()
397                .copied()
398                .unwrap_or(0),
399        })
400    }
401
402    async fn send(&self, request: ApsRequest) -> Result<(), HostError> {
403        let request = Box::new(request);
404        for attempt in 0..5u64 {
405            match self
406                .deconz
407                .request(Request::ApsDataRequest(request.clone()))
408                .await
409            {
410                Ok(_) => return Ok(()),
411                Err(DeconzError::Status {
412                    status: status::BUSY,
413                    ..
414                }) => tokio::time::sleep(Duration::from_millis(50 * (attempt + 1))).await,
415                Err(e) => return Err(e.into()),
416            }
417        }
418        Err(HostError::Ncp("the coordinator stayed busy".into()))
419    }
420
421    fn next_tag(&self) -> u8 {
422        self.tag.fetch_add(1, Ordering::Relaxed)
423    }
424}
425
426impl Adapter for DeconzAdapter {
427    fn info(&self) -> AdapterInfo {
428        AdapterInfo {
429            kind: "deconz",
430            firmware: self.deconz.version().text(),
431            protocol: (self.protocol & 0xFF) as u8,
432            reports_key_exchange: false,
433        }
434    }
435
436    async fn start(&self, mode: StartMode) -> Result<(StartOutcome, NetworkInfo), HostError> {
437        let state = self.device_state().await?;
438        self.shared
439            .net
440            .send_replace(state & device_state::NETWORK_MASK);
441        match mode {
442            StartMode::Restore(backup) => {
443                let settings = NetworkSettings {
444                    channel: backup.channel,
445                    pan_id: backup.pan_id,
446                    extended_pan_id: backup.extended_pan_id,
447                    network_key: backup.network_key.key,
448                    tx_power: None,
449                };
450                self.form(&settings, Some(&backup)).await?;
451                Ok((StartOutcome::Restored, self.read_network_info().await?))
452            }
453            StartMode::Normal {
454                settings,
455                replace_other,
456            } => {
457                let designed =
458                    self.read(param::APS_DESIGNED_COORDINATOR).await?.first() == Some(&1);
459                if designed && self.holds(&settings).await? {
460                    if state & device_state::NETWORK_MASK != net_state::CONNECTED {
461                        self.set_net_state(net_state::CONNECTED).await?;
462                    }
463                    return Ok((StartOutcome::Resumed, self.read_network_info().await?));
464                }
465                if designed {
466                    let pan = self.read_u16(param::NWK_PANID).await?;
467                    let found = format!("PAN {pan:04x}");
468                    if !replace_other {
469                        return Err(HostError::NetworkMismatch { found });
470                    }
471                    tracing::warn!(%found, "replacing the coordinator's other network, as configured");
472                }
473                if settings.tx_power.is_some() {
474                    tracing::warn!("deCONZ firmware sets its own transmit power");
475                }
476                self.form(&settings, None).await?;
477                Ok((StartOutcome::Formed, self.read_network_info().await?))
478            }
479        }
480    }
481
482    async fn permit_join(&self, seconds: u8, join: &JoinPolicy) -> Result<(), HostError> {
483        if seconds > 0 {
484            if join.install_code_only {
485                return Err(HostError::Invalid(
486                    "deCONZ firmware cannot restrict joining to install codes".into(),
487                ));
488            }
489            if !join.allow_legacy && !self.legacy_warned.swap(true, Ordering::Relaxed) {
490                tracing::warn!(
491                    "deCONZ firmware cannot turn away devices that skip the link key exchange"
492                );
493            }
494        }
495        self.write(param::PERMIT_JOIN, &[seconds]).await
496    }
497
498    async fn add_join_key(&self, ieee: Ieee, key: Key) -> Result<(), HostError> {
499        let mut v = ieee.to_le_bytes().to_vec();
500        v.extend_from_slice(&key.0);
501        self.write(param::LINK_KEY, &v).await
502    }
503
504    async fn send_unicast(
505        &self,
506        nwk: NodeId,
507        aps: Aps,
508        payload: Vec<u8>,
509    ) -> Result<u16, HostError> {
510        let tag = self.next_tag();
511        self.send(ApsRequest {
512            request_id: tag,
513            destination: Address::Nwk(nwk),
514            destination_endpoint: Some(aps.destination_endpoint),
515            profile: aps.profile,
516            cluster: aps.cluster,
517            source_endpoint: aps.source_endpoint,
518            asdu: payload,
519            tx_options: tx_option::ACK,
520            radius: 0,
521        })
522        .await?;
523        Ok(u16::from(tag))
524    }
525
526    async fn send_broadcast(
527        &self,
528        destination: NodeId,
529        aps: Aps,
530        payload: Vec<u8>,
531    ) -> Result<(), HostError> {
532        self.send(ApsRequest {
533            request_id: self.next_tag(),
534            destination: Address::Nwk(destination),
535            destination_endpoint: Some(aps.destination_endpoint),
536            profile: aps.profile,
537            cluster: aps.cluster,
538            source_endpoint: aps.source_endpoint,
539            asdu: payload,
540            tx_options: 0,
541            radius: 0,
542        })
543        .await
544    }
545
546    async fn network_info(&self) -> Result<NetworkInfo, HostError> {
547        self.read_network_info().await
548    }
549
550    async fn backup(&self) -> Result<Backup, HostError> {
551        let info = self.read_network_info().await?;
552        let frame_counter = self
553            .read(param::NWK_FRAME_COUNTER)
554            .await
555            .ok()
556            .and_then(|v| <[u8; 4]>::try_from(v.as_slice()).ok())
557            .map(u32::from_le_bytes)
558            .ok_or_else(|| {
559                HostError::Ncp("this firmware does not report its frame counter".into())
560            })?;
561        Ok(Backup {
562            metadata: Metadata {
563                format: backup::FORMAT.into(),
564                version: 1,
565                source: concat!("zigbee-bridge@", env!("CARGO_PKG_VERSION")).into(),
566                internal: Internal {
567                    created_unix: Some(now_unix()),
568                    ezsp_version: None,
569                    firmware: Some(self.deconz.version().text()),
570                },
571            },
572            stack_specific: None,
573            coordinator_ieee: info.ieee,
574            pan_id: info.pan_id,
575            extended_pan_id: info.extended_pan_id,
576            nwk_update_id: info.nwk_update_id,
577            security_level: 5,
578            channel: info.channel,
579            channel_mask: vec![info.channel],
580            network_key: NetworkKey {
581                key: self.network_key().await?,
582                sequence_number: 0,
583                frame_counter,
584            },
585            devices: Vec::new(),
586        })
587    }
588
589    async fn active_scan(&self, _channel_mask: u32) -> Result<Vec<Beacon>, HostError> {
590        // The serial protocol has no network discovery.
591        Ok(Vec::new())
592    }
593
594    async fn leave(&self) -> Result<(), HostError> {
595        self.set_net_state(net_state::OFFLINE).await?;
596        self.write(param::APS_DESIGNED_COORDINATOR, &[0]).await?;
597        self.write(param::NETWORK_KEY, &[0; 17]).await?;
598        self.write(param::NWK_PANID, &0xFFFFu16.to_le_bytes()).await
599    }
600
601    async fn energy_scan(&self, channel_mask: u32) -> Result<Vec<(u8, i8)>, HostError> {
602        let (tx, rx) = oneshot::channel();
603        if let Ok(mut s) = self.shared.scan.lock() {
604            if s.is_some() {
605                return Err(HostError::Invalid("a scan is already running".into()));
606            }
607            *s = Some(tx);
608        }
609        let mut asdu = vec![self.next_tag()];
610        asdu.extend_from_slice(&channel_mask.to_le_bytes());
611        asdu.extend_from_slice(&[3, 1]);
612        let sent = self
613            .send(ApsRequest {
614                request_id: self.next_tag(),
615                destination: Address::Nwk(0x0000),
616                destination_endpoint: Some(0),
617                profile: zigbee_zdo::PROFILE_ID,
618                cluster: 0x0038,
619                source_endpoint: 0,
620                asdu,
621                tx_options: 0,
622                radius: 0,
623            })
624            .await;
625        if let Err(e) = sent {
626            if let Ok(mut s) = self.shared.scan.lock() {
627                *s = None;
628            }
629            return Err(e);
630        }
631        match tokio::time::timeout(Duration::from_secs(30), rx).await {
632            Ok(Ok(result)) => result,
633            _ => {
634                if let Ok(mut s) = self.shared.scan.lock() {
635                    *s = None;
636                }
637                Err(HostError::Ncp("energy scan did not complete".into()))
638            }
639        }
640    }
641}