Skip to main content

zigbee_host/
interview.rs

1//! The interview: learn what a new device is, then configure it.
2//!
3//! Each step's result is stored before the next runs, so an interview a
4//! sleepy device interrupts resumes at the step that failed the next time
5//! the device talks, instead of starting over.
6
7use zigbee_primitives::Ieee;
8use zigbee_zcl::foundation::ReportingConfig;
9use zigbee_zcl::{attr, cluster_id, DataType, Value};
10use zigbee_zdo::{Body, SimpleDescriptor};
11
12use crate::adapter::Adapter;
13use crate::device::{ConfiguredReport, InterviewStage};
14use crate::error::HostError;
15use crate::host::{Host, HostEvent};
16
17/// Basic cluster attributes read at interview, in two small batches (some
18/// devices reject long reads).
19const BASIC_FIRST: &[u16] = &[
20    attr::basic::MANUFACTURER_NAME,
21    attr::basic::MODEL_IDENTIFIER,
22    attr::basic::POWER_SOURCE,
23];
24const BASIC_SECOND: &[u16] = &[
25    attr::basic::APPLICATION_VERSION,
26    attr::basic::DATE_CODE,
27    attr::basic::SW_BUILD_ID,
28];
29const BASIC_THIRD: &[u16] = &[
30    attr::basic::ZCL_VERSION,
31    attr::basic::STACK_VERSION,
32    attr::basic::HW_VERSION,
33];
34
35/// Run or resume the interview of `ieee`.
36pub(crate) async fn run<A: Adapter>(host: &Host<A>, ieee: Ieee) {
37    host.emit_event(HostEvent::InterviewStarted { ieee });
38    loop {
39        let Some(device) = host.device(ieee) else {
40            return;
41        };
42        let stage = device.interview.stage;
43        if stage == InterviewStage::Done {
44            break;
45        }
46        match step(host, ieee, stage).await {
47            Ok(()) => {
48                host.update_device(ieee, |d| {
49                    d.interview.stage = stage.next();
50                    d.interview.error = None;
51                });
52                host.emit_event(HostEvent::InterviewStep { ieee, stage });
53            }
54            Err(e) => {
55                tracing::warn!(%ieee, ?stage, error = %e, "interview step failed");
56                host.update_device(ieee, |d| {
57                    d.interview.error = Some(e.to_string());
58                    d.interview.attempts += 1;
59                });
60                host.emit_event(HostEvent::InterviewFailed {
61                    ieee,
62                    stage,
63                    error: e.to_string(),
64                });
65                return;
66            }
67        }
68    }
69    if let Some(device) = host.device(ieee) {
70        tracing::info!(%ieee, manufacturer = ?device.manufacturer, model = ?device.model, "interview done");
71        host.mark_backup_wanted();
72        host.emit_event(HostEvent::InterviewDone {
73            device: Box::new(device),
74        });
75    }
76}
77
78async fn step<A: Adapter>(
79    host: &Host<A>,
80    ieee: Ieee,
81    stage: InterviewStage,
82) -> Result<(), HostError> {
83    let device = host.device(ieee).ok_or(HostError::UnknownDevice(ieee))?;
84    let nwk = device.nwk;
85    match stage {
86        InterviewStage::NodeDescriptor => {
87            let m = host
88                .zdo_request_retry(nwk, Body::NodeDescReq { nwk })
89                .await?;
90            match m.body {
91                Body::NodeDescRsp {
92                    status: 0,
93                    descriptor: Some(d),
94                    ..
95                } => {
96                    host.update_device(ieee, |dev| dev.node_descriptor = Some(d));
97                    Ok(())
98                }
99                Body::NodeDescRsp { status, .. } => Err(HostError::Status {
100                    what: "Node_Desc_req".into(),
101                    status,
102                }),
103                _ => Err(HostError::BadFrame("unexpected Node_Desc reply".into())),
104            }
105        }
106        InterviewStage::ActiveEndpoints => {
107            let m = host
108                .zdo_request_retry(nwk, Body::ActiveEpReq { nwk })
109                .await?;
110            match m.body {
111                Body::ActiveEpRsp {
112                    status: 0,
113                    endpoints,
114                    ..
115                } => {
116                    host.update_device(ieee, |dev| {
117                        dev.endpoints = endpoints
118                            .iter()
119                            .map(|e| SimpleDescriptor {
120                                endpoint: *e,
121                                ..SimpleDescriptor::default()
122                            })
123                            .collect();
124                    });
125                    Ok(())
126                }
127                Body::ActiveEpRsp { status, .. } => Err(HostError::Status {
128                    what: "Active_EP_req".into(),
129                    status,
130                }),
131                _ => Err(HostError::BadFrame("unexpected Active_EP reply".into())),
132            }
133        }
134        InterviewStage::SimpleDescriptors => {
135            let pending: Vec<u8> = device
136                .endpoints
137                .iter()
138                .filter(|e| {
139                    e.profile_id == 0 && e.input_clusters.is_empty() && e.output_clusters.is_empty()
140                })
141                .map(|e| e.endpoint)
142                .collect();
143            for endpoint in pending {
144                let m = host
145                    .zdo_request_retry(nwk, Body::SimpleDescReq { nwk, endpoint })
146                    .await?;
147                match m.body {
148                    Body::SimpleDescRsp {
149                        status: 0,
150                        descriptor: Some(d),
151                        ..
152                    } => {
153                        host.update_device(ieee, |dev| {
154                            if let Some(slot) =
155                                dev.endpoints.iter_mut().find(|e| e.endpoint == endpoint)
156                            {
157                                *slot = d;
158                            }
159                        });
160                    }
161                    Body::SimpleDescRsp { status, .. } => {
162                        return Err(HostError::Status {
163                            what: format!("Simple_Desc_req({endpoint})"),
164                            status,
165                        })
166                    }
167                    _ => return Err(HostError::BadFrame("unexpected Simple_Desc reply".into())),
168                }
169            }
170            Ok(())
171        }
172        InterviewStage::Basic => {
173            let Some(endpoint) = device
174                .endpoint_with(cluster_id::BASIC)
175                .map(|e| e.endpoint)
176                .or(device.endpoints.first().map(|e| e.endpoint))
177            else {
178                return Ok(());
179            };
180            for (i, batch) in [BASIC_FIRST, BASIC_SECOND, BASIC_THIRD]
181                .into_iter()
182                .enumerate()
183            {
184                let records = match host
185                    .read_attributes(ieee, endpoint, cluster_id::BASIC, batch)
186                    .await
187                {
188                    Ok(r) => r,
189                    // Only the first batch is required.
190                    Err(e) if i > 0 => {
191                        tracing::debug!(%ieee, error = %e, "second Basic read");
192                        continue;
193                    }
194                    Err(e) => return Err(e),
195                };
196                host.update_device(ieee, |dev| {
197                    for r in records {
198                        let Some(value) = r.value else { continue };
199                        match r.attribute {
200                            attr::basic::MANUFACTURER_NAME => {
201                                dev.manufacturer = value.as_str().map(clean)
202                            }
203                            attr::basic::MODEL_IDENTIFIER => dev.model = value.as_str().map(clean),
204                            attr::basic::POWER_SOURCE => {
205                                dev.power_source = value.as_u64().map(|v| v as u8)
206                            }
207                            attr::basic::APPLICATION_VERSION => {
208                                dev.app_version = value.as_u64().map(|v| v as u8)
209                            }
210                            attr::basic::ZCL_VERSION => {
211                                dev.zcl_version = value.as_u64().map(|v| v as u8)
212                            }
213                            attr::basic::STACK_VERSION => {
214                                dev.stack_version = value.as_u64().map(|v| v as u8)
215                            }
216                            attr::basic::HW_VERSION => {
217                                dev.hw_version = value.as_u64().map(|v| v as u8)
218                            }
219                            attr::basic::DATE_CODE => dev.date_code = value.as_str().map(clean),
220                            attr::basic::SW_BUILD_ID => dev.sw_build_id = value.as_str().map(clean),
221                            _ => {}
222                        }
223                    }
224                });
225            }
226            Ok(())
227        }
228        InterviewStage::Configure => {
229            if host.config().configure_reporting {
230                configure(host, ieee).await;
231            }
232            Ok(())
233        }
234        InterviewStage::Done => Ok(()),
235    }
236}
237
238/// Model and manufacturer strings arrive padded with NULs or spaces.
239fn clean(s: &str) -> String {
240    s.trim_matches(|c: char| c == '\0' || c.is_whitespace())
241        .to_string()
242}
243
244/// Bind and configure reporting for every server cluster that has default
245/// reporting in the cluster library, and enroll IAS zones. Best effort: a
246/// device that refuses one cluster still gets the others.
247async fn configure<A: Adapter>(host: &Host<A>, ieee: Ieee) {
248    let Some(device) = host.device(ieee) else {
249        return;
250    };
251    let mut configured = Vec::new();
252    for ep in &device.endpoints {
253        for cluster in &ep.input_clusters {
254            if *cluster == cluster_id::IAS_ZONE {
255                if let Err(e) = enroll(host, ieee, ep.endpoint).await {
256                    tracing::warn!(%ieee, endpoint = ep.endpoint, error = %e, "IAS zone enrollment");
257                }
258            }
259            let Some(def) = zigbee_zcl::cluster(*cluster) else {
260                continue;
261            };
262            let configs: Vec<ReportingConfig> = def
263                .attributes
264                .iter()
265                .filter_map(|a| {
266                    a.report.map(|r| ReportingConfig {
267                        attribute: a.id,
268                        data_type: a.data_type,
269                        min_interval: r.min_interval,
270                        max_interval: r.max_interval,
271                        reportable_change: r.change.map(|c| change_value(a.data_type, c)),
272                    })
273                })
274                .collect();
275            if configs.is_empty() {
276                continue;
277            }
278            if let Err(e) = host.bind_to_host(ieee, ep.endpoint, *cluster).await {
279                tracing::warn!(%ieee, endpoint = ep.endpoint, cluster, error = %e, "bind");
280                continue;
281            }
282            let attributes: Vec<u16> = configs.iter().map(|c| c.attribute).collect();
283            match host
284                .configure_reporting(ieee, ep.endpoint, *cluster, configs)
285                .await
286            {
287                Ok(records) => {
288                    for attribute in attributes {
289                        // One record without an attribute means all succeeded.
290                        let status = records
291                            .iter()
292                            .find(|r| r.attribute == Some(attribute))
293                            .or_else(|| records.iter().find(|r| r.attribute.is_none()))
294                            .map(|r| r.status)
295                            .unwrap_or(zigbee_zcl::status::SUCCESS);
296                        configured.push(ConfiguredReport {
297                            endpoint: ep.endpoint,
298                            cluster: *cluster,
299                            attribute,
300                            status,
301                        });
302                    }
303                }
304                Err(e) => {
305                    tracing::warn!(%ieee, endpoint = ep.endpoint, cluster, error = %e, "configure reporting")
306                }
307            }
308        }
309    }
310    host.update_device(ieee, |d| d.reporting = configured);
311}
312
313fn change_value(data_type: DataType, change: u64) -> Value {
314    match data_type.class() {
315        zigbee_zcl::types::Class::Signed => Value::Int(data_type, change as i64),
316        zigbee_zcl::types::Class::Float => Value::Float(data_type, change as f64),
317        _ => Value::Uint(data_type, change),
318    }
319}
320
321/// Write the coordinator as the zone's CIE, then answer with an enroll
322/// response (auto-enroll-response, which every IAS device accepts).
323async fn enroll<A: Adapter>(host: &Host<A>, ieee: Ieee, endpoint: u8) -> Result<(), HostError> {
324    if let Ok(records) = host
325        .read_attributes(
326            ieee,
327            endpoint,
328            cluster_id::IAS_ZONE,
329            &[attr::ias_zone::ZONE_TYPE],
330        )
331        .await
332    {
333        if let Some(zone_type) = records
334            .first()
335            .and_then(|r| r.value.as_ref())
336            .and_then(Value::as_u64)
337        {
338            host.update_device(ieee, |d| d.ias_zone_type = Some(zone_type as u16));
339        }
340    }
341    let cie = Value::Ieee(host.network().ieee);
342    host.write_attributes(
343        ieee,
344        endpoint,
345        cluster_id::IAS_ZONE,
346        vec![(attr::ias_zone::IAS_CIE_ADDRESS, cie)],
347    )
348    .await?;
349    enroll_response(host, ieee, endpoint).await
350}
351
352/// Send an IAS zone enroll response with the device's zone id (assigning
353/// the lowest free id the first time).
354pub(crate) async fn enroll_response<A: Adapter>(
355    host: &Host<A>,
356    ieee: Ieee,
357    endpoint: u8,
358) -> Result<(), HostError> {
359    let zone_id = match host.device(ieee).and_then(|d| d.ias_zone_id) {
360        Some(id) => id,
361        None => {
362            let used = host.used_zone_ids();
363            let id = (0u8..=0xFE).find(|i| !used.contains(i)).unwrap_or(0);
364            host.update_device(ieee, |d| d.ias_zone_id = Some(id));
365            id
366        }
367    };
368    host.command(
369        ieee,
370        endpoint,
371        cluster_id::IAS_ZONE,
372        "zone_enroll_response",
373        &[Value::enum8(0), Value::u8(zone_id)],
374    )
375    .await
376    .map(|_| ())
377}