Skip to main content

zigbee_bridge/
api.rs

1//! The MQTT API: every payload the bridge publishes or reads, as a type.
2//!
3//! The bridge serializes these and nothing else, so they are the contract.
4//! With the `unstable-asyncapi-docs` feature each one also derives a JSON
5//! Schema and an AsyncAPI message, and `tests/asyncapi.rs` assembles them
6//! into the AsyncAPI description the docs site renders as the MQTT
7//! reference. That feature is docs tooling, not API: it may change in any
8//! release, and the bridge's own builds never turn it on.
9//!
10//! Topics are under the base topic (`mqtt.base_topic`, default `zigbee`).
11//! `<device>` is the name a person gave the device, or its IEEE address as
12//! `0x00124b0001020304`. Keys never appear on MQTT.
13
14use serde::{Deserialize, Serialize};
15use serde_json::{Map, Value as Json};
16
17#[cfg(feature = "unstable-asyncapi-docs")]
18use asyncapi_rust::ToAsyncApiMessage;
19#[cfg(feature = "unstable-asyncapi-docs")]
20use schemars::JsonSchema;
21
22// ---------------------------------------------------------------------------
23// Availability
24
25/// The bridge's availability, retained on `bridge/state`. The broker
26/// publishes `offline` as the bridge's last will when the connection drops.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[cfg_attr(
29    feature = "unstable-asyncapi-docs",
30    derive(JsonSchema, ToAsyncApiMessage)
31)]
32#[cfg_attr(
33    feature = "unstable-asyncapi-docs",
34    asyncapi(summary = "The bridge is online or offline")
35)]
36pub struct BridgeState {
37    /// `online` while the bridge runs, `offline` once it stops or its
38    /// connection drops.
39    pub state: Availability,
40}
41
42/// Online or offline.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
45#[serde(rename_all = "snake_case")]
46pub enum Availability {
47    /// Running and connected to the coordinator.
48    Online,
49    /// Stopped, or the MQTT connection dropped.
50    Offline,
51}
52
53impl BridgeState {
54    /// The availability as the payload the bridge publishes.
55    pub fn payload(state: Availability) -> Vec<u8> {
56        serde_json::to_vec(&BridgeState { state }).unwrap_or_default()
57    }
58}
59
60// ---------------------------------------------------------------------------
61// Bridge info and devices
62
63/// The bridge, its coordinator and its network, retained on `bridge/info`.
64/// Republished when any of it changes.
65#[derive(Debug, Clone, Serialize, Deserialize)]
66#[cfg_attr(
67    feature = "unstable-asyncapi-docs",
68    derive(JsonSchema, ToAsyncApiMessage)
69)]
70#[cfg_attr(
71    feature = "unstable-asyncapi-docs",
72    asyncapi(summary = "The bridge's version, coordinator, network and join state")
73)]
74pub struct BridgeInfo {
75    /// The bridge's version.
76    pub version: String,
77    /// The coordinator.
78    pub coordinator: CoordinatorInfo,
79    /// The Zigbee network.
80    pub network: NetworkInfo,
81    /// Devices may join now.
82    pub permit_join: bool,
83    /// Seconds joining stays open; 0 when closed.
84    pub permit_join_timeout: u8,
85}
86
87/// The coordinator.
88#[derive(Debug, Clone, Serialize, Deserialize)]
89#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
90pub struct CoordinatorInfo {
91    /// Its IEEE address.
92    pub ieee_address: String,
93    /// The firmware family: `ezsp`, `znp` or `deconz`.
94    #[serde(rename = "type")]
95    pub kind: String,
96    /// The firmware version.
97    pub firmware: String,
98    /// The serial protocol version.
99    pub protocol: u8,
100}
101
102/// The Zigbee network.
103#[derive(Debug, Clone, Serialize, Deserialize)]
104#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
105pub struct NetworkInfo {
106    /// The radio channel, 11 to 26.
107    pub channel: u8,
108    /// The PAN id.
109    pub pan_id: u16,
110    /// The extended PAN id, as hex.
111    pub extended_pan_id: String,
112    /// The network update id, raised by each channel change.
113    pub update_id: u8,
114}
115
116/// Every device in the network, retained on `bridge/devices`. Republished
117/// when one joins, leaves, is renamed or finishes its interview.
118#[derive(Debug, Clone, Serialize, Deserialize)]
119#[cfg_attr(
120    feature = "unstable-asyncapi-docs",
121    derive(JsonSchema, ToAsyncApiMessage)
122)]
123#[cfg_attr(
124    feature = "unstable-asyncapi-docs",
125    asyncapi(summary = "Every device and its interview")
126)]
127#[serde(transparent)]
128pub struct BridgeDevices(pub Vec<DeviceSummary>);
129
130/// A device.
131#[derive(Debug, Clone, Serialize, Deserialize)]
132#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
133pub struct DeviceSummary {
134    /// Its IEEE address.
135    pub ieee_address: String,
136    /// Its current network address.
137    pub network_address: u16,
138    /// The name it is published under: the name a person gave it, or its
139    /// IEEE address.
140    pub friendly_name: String,
141    /// From the Basic cluster.
142    pub manufacturer: Option<String>,
143    /// From the Basic cluster.
144    pub model: Option<String>,
145    /// From the Basic cluster: 1 mains, 3 battery, 4 DC; `null` until the
146    /// interview reads it.
147    pub power_source: Option<u8>,
148    /// From the Basic cluster.
149    pub software_build_id: Option<String>,
150    /// From the Basic cluster.
151    pub date_code: Option<String>,
152    /// Its role, from the node descriptor; `null` until the interview reads
153    /// it.
154    #[serde(rename = "type")]
155    pub kind: Option<LogicalType>,
156    /// How far its interview got.
157    pub interview: InterviewSummary,
158    /// It has a Zigbee 3.0 unique trust center link key.
159    pub unique_link_key: bool,
160    /// Its endpoints, from the simple descriptors.
161    pub endpoints: Vec<EndpointSummary>,
162}
163
164/// A device's role in the network.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
166#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
167#[serde(rename_all = "snake_case")]
168pub enum LogicalType {
169    /// The coordinator.
170    Coordinator,
171    /// A router: mains powered, relays for others.
172    Router,
173    /// An end device: often sleepy, talks through its parent.
174    EndDevice,
175    /// A reserved value.
176    Unknown,
177}
178
179impl From<zigbee_zdo::LogicalType> for LogicalType {
180    fn from(t: zigbee_zdo::LogicalType) -> Self {
181        match t {
182            zigbee_zdo::LogicalType::Coordinator => LogicalType::Coordinator,
183            zigbee_zdo::LogicalType::Router => LogicalType::Router,
184            zigbee_zdo::LogicalType::EndDevice => LogicalType::EndDevice,
185            zigbee_zdo::LogicalType::Reserved(_) => LogicalType::Unknown,
186        }
187    }
188}
189
190/// How far an interview got.
191#[derive(Debug, Clone, Serialize, Deserialize)]
192#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
193pub struct InterviewSummary {
194    /// The stage it is at, or `done`.
195    pub stage: InterviewStage,
196    /// Every stage finished.
197    pub done: bool,
198    /// Why the interview stopped, if it did; it resumes when the device next
199    /// talks.
200    pub error: Option<String>,
201}
202
203/// An interview stage, in order.
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
205#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
206#[serde(rename_all = "snake_case")]
207pub enum InterviewStage {
208    /// Reading the node descriptor.
209    NodeDescriptor,
210    /// Reading the endpoint list.
211    ActiveEndpoints,
212    /// Reading each endpoint's clusters.
213    SimpleDescriptors,
214    /// Reading the Basic cluster.
215    Basic,
216    /// Binding and configuring reporting.
217    Configure,
218    /// Finished.
219    Done,
220}
221
222impl From<zigbee_host::InterviewStage> for InterviewStage {
223    fn from(s: zigbee_host::InterviewStage) -> Self {
224        use zigbee_host::InterviewStage as S;
225        match s {
226            S::NodeDescriptor => InterviewStage::NodeDescriptor,
227            S::ActiveEndpoints => InterviewStage::ActiveEndpoints,
228            S::SimpleDescriptors => InterviewStage::SimpleDescriptors,
229            S::Basic => InterviewStage::Basic,
230            S::Configure => InterviewStage::Configure,
231            S::Done => InterviewStage::Done,
232        }
233    }
234}
235
236/// An endpoint.
237#[derive(Debug, Clone, Serialize, Deserialize)]
238#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
239pub struct EndpointSummary {
240    /// The endpoint number.
241    pub endpoint: u8,
242    /// The application profile (0x0104 Home Automation).
243    pub profile_id: u16,
244    /// The device type within the profile.
245    pub device_id: u16,
246    /// Server clusters, by name, or as hex when the bridge does not know
247    /// the cluster.
248    pub input_clusters: Vec<String>,
249    /// Client clusters, by name or hex.
250    pub output_clusters: Vec<String>,
251}
252
253// ---------------------------------------------------------------------------
254// Events
255
256/// Something that happened in the network, on `bridge/event`. Not
257/// retained.
258#[derive(Debug, Clone, Serialize, Deserialize)]
259#[cfg_attr(
260    feature = "unstable-asyncapi-docs",
261    derive(JsonSchema, ToAsyncApiMessage)
262)]
263#[serde(tag = "type", content = "data")]
264pub enum BridgeEvent {
265    /// Joining opened or closed.
266    #[serde(rename = "permit_join")]
267    #[cfg_attr(
268        feature = "unstable-asyncapi-docs",
269        asyncapi(summary = "Joining opened or closed")
270    )]
271    PermitJoin {
272        /// Seconds it stays open; 0 when closed.
273        time: u8,
274        /// The router joining was opened through, when only one.
275        device: Option<String>,
276    },
277    /// A device joined, or rejoined.
278    #[serde(rename = "device_joined")]
279    #[cfg_attr(
280        feature = "unstable-asyncapi-docs",
281        asyncapi(summary = "A device joined")
282    )]
283    DeviceJoined {
284        /// Its IEEE address.
285        ieee_address: String,
286        /// Its network address.
287        network_address: u16,
288        /// A rejoin rather than a first join.
289        rejoin: bool,
290    },
291    /// A device announced itself, after joining or a power cycle.
292    #[serde(rename = "device_announce")]
293    #[cfg_attr(
294        feature = "unstable-asyncapi-docs",
295        asyncapi(summary = "A device announced itself")
296    )]
297    DeviceAnnounce {
298        /// Its IEEE address.
299        ieee_address: String,
300        /// Its network address.
301        network_address: u16,
302    },
303    /// A device left the network.
304    #[serde(rename = "device_leave")]
305    #[cfg_attr(
306        feature = "unstable-asyncapi-docs",
307        asyncapi(summary = "A device left")
308    )]
309    DeviceLeave {
310        /// Its IEEE address.
311        ieee_address: String,
312    },
313    /// The bridge removed a device.
314    #[serde(rename = "device_removed")]
315    #[cfg_attr(
316        feature = "unstable-asyncapi-docs",
317        asyncapi(summary = "The bridge removed a device")
318    )]
319    DeviceRemoved {
320        /// Its IEEE address.
321        ieee_address: String,
322        /// Why.
323        reason: String,
324    },
325    /// An interview started, finished or failed.
326    #[serde(rename = "device_interview")]
327    #[cfg_attr(
328        feature = "unstable-asyncapi-docs",
329        asyncapi(summary = "An interview started, finished or failed")
330    )]
331    DeviceInterview(InterviewEvent),
332    /// A device asked for a firmware update and the OTA directory has a
333    /// newer image for it.
334    #[serde(rename = "ota_available")]
335    #[cfg_attr(
336        feature = "unstable-asyncapi-docs",
337        asyncapi(summary = "A firmware update is available")
338    )]
339    OtaAvailable {
340        /// The device's name.
341        device: String,
342        /// Its IEEE address.
343        ieee_address: String,
344        /// The file version it runs.
345        installed_version: u32,
346        /// The newest version in the OTA directory.
347        latest_version: u32,
348    },
349    /// A firmware download's progress.
350    #[serde(rename = "ota_progress")]
351    #[cfg_attr(
352        feature = "unstable-asyncapi-docs",
353        asyncapi(summary = "A firmware download's progress")
354    )]
355    OtaProgress {
356        /// The device's name.
357        device: String,
358        /// Its IEEE address.
359        ieee_address: String,
360        /// Percent downloaded.
361        progress: u8,
362    },
363    /// A firmware update ended.
364    #[serde(rename = "ota_finished")]
365    #[cfg_attr(
366        feature = "unstable-asyncapi-docs",
367        asyncapi(summary = "A firmware update ended")
368    )]
369    OtaFinished {
370        /// The device's name.
371        device: String,
372        /// Its IEEE address.
373        ieee_address: String,
374        /// The version it ran.
375        from_version: u32,
376        /// The version it downloaded.
377        to_version: u32,
378        /// The device applied it.
379        success: bool,
380        /// The device's upgrade end status (ZCL status code).
381        status: u8,
382    },
383    /// The network moved to another channel.
384    #[serde(rename = "channel_changed")]
385    #[cfg_attr(
386        feature = "unstable-asyncapi-docs",
387        asyncapi(summary = "The network changed channel")
388    )]
389    ChannelChanged {
390        /// The new channel.
391        channel: u8,
392        /// The new network update id.
393        update_id: u8,
394    },
395}
396
397/// An interview's progress, by `status`.
398#[derive(Debug, Clone, Serialize, Deserialize)]
399#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
400#[serde(tag = "status")]
401pub enum InterviewEvent {
402    /// The interview started or resumed.
403    #[serde(rename = "started")]
404    Started {
405        /// The device's IEEE address.
406        ieee_address: String,
407    },
408    /// The interview finished.
409    #[serde(rename = "successful")]
410    Successful {
411        /// The device's IEEE address.
412        ieee_address: String,
413        /// From the Basic cluster.
414        manufacturer: Option<String>,
415        /// From the Basic cluster.
416        model: Option<String>,
417        /// The device, as on `bridge/devices`.
418        definition: Box<DeviceSummary>,
419    },
420    /// The interview stopped; the bridge retries it later.
421    #[serde(rename = "failed")]
422    Failed {
423        /// The device's IEEE address.
424        ieee_address: String,
425        /// The stage that failed.
426        stage: InterviewStage,
427        /// Why.
428        error: String,
429    },
430}
431
432// ---------------------------------------------------------------------------
433// Devices
434
435/// A device's state on `<device>`: its readings, merged as they arrive, plus
436/// `linkquality`. Retained unless `mqtt.retain_state` is off; an empty
437/// retained message clears it when the device leaves or is renamed.
438///
439/// Which keys appear depends on the device's clusters. A reading from a
440/// second endpoint with the same cluster gets the endpoint number as a
441/// suffix, as in `temperature_2`.
442#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
443#[cfg_attr(feature = "unstable-asyncapi-docs", derive(ToAsyncApiMessage))]
444#[cfg_attr(
445    feature = "unstable-asyncapi-docs",
446    asyncapi(summary = "A device's readings")
447)]
448#[serde(transparent)]
449pub struct DeviceState(pub Map<String, Json>);
450
451#[cfg(feature = "unstable-asyncapi-docs")]
452impl JsonSchema for DeviceState {
453    fn schema_name() -> std::borrow::Cow<'static, str> {
454        "DeviceState".into()
455    }
456
457    // The keys are the bridge's own table of standard attributes, so the
458    // schema lists exactly what the bridge can publish.
459    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
460        use crate::exposes::{self, Convert, EXPOSES};
461        use serde_json::json;
462        let mut properties = Map::new();
463        properties.insert(
464            "state".into(),
465            json!({"description": "On/off cluster: the switch or light is on.", "enum": ["ON", "OFF"]}),
466        );
467        properties.insert(
468            "brightness".into(),
469            json!({"description": "Level control cluster: the current level.", "type": "integer", "minimum": 0, "maximum": 254}),
470        );
471        for e in EXPOSES {
472            let cluster = zigbee_zcl::cluster(e.cluster)
473                .map(|c| c.name.replace('_', " "))
474                .unwrap_or_else(|| format!("{:#06x}", e.cluster));
475            let unit = e.unit.map(|u| format!(", in {u}")).unwrap_or_default();
476            let schema = match e.convert {
477                Convert::OnOff => json!({"enum": ["ON", "OFF"]}),
478                Convert::Bit(_) => json!({"type": "boolean"}),
479                Convert::Raw => json!({"type": "integer"}),
480                Convert::Scale(..) | Convert::Lux => json!({"type": "number"}),
481            };
482            let mut schema = schema.as_object().cloned().unwrap_or_default();
483            let description = format!("{}{unit}.", capitalize(&cluster));
484            schema.insert("description".into(), description.into());
485            properties
486                .entry(e.field.to_string())
487                .or_insert(Json::Object(schema));
488        }
489        for zone_type in [
490            None,
491            Some(0x0015),
492            Some(0x000D),
493            Some(0x002A),
494            Some(0x0028),
495            Some(0x002B),
496            Some(0x002D),
497        ] {
498            for (field, _) in exposes::ias_fields(zone_type, 0) {
499                properties.entry(field.to_string()).or_insert_with(|| {
500                    json!({"description": format!("IAS zone: {}.", field.replace('_', " ")), "type": "boolean"})
501                });
502            }
503        }
504        properties.insert(
505            "linkquality".into(),
506            json!({"description": "The link quality of the device's last message, 0 to 255.", "type": "integer", "minimum": 0, "maximum": 255}),
507        );
508        schemars::json_schema!({
509            "type": "object",
510            "description": "The device's readings. Which keys appear depends on its clusters; a reading from a second endpoint with the same cluster has the endpoint number as a suffix, as in `temperature_2`.",
511            "properties": properties,
512            "additionalProperties": true,
513        })
514    }
515}
516
517#[cfg(feature = "unstable-asyncapi-docs")]
518fn capitalize(s: &str) -> String {
519    let mut c = s.chars();
520    match c.next() {
521        Some(f) => f.to_uppercase().chain(c).collect(),
522        None => String::new(),
523    }
524}
525
526/// A command for a device, on `<device>/set`. Any combination of keys.
527#[derive(Debug, Clone, Default, Serialize, Deserialize)]
528#[cfg_attr(
529    feature = "unstable-asyncapi-docs",
530    derive(JsonSchema, ToAsyncApiMessage)
531)]
532#[cfg_attr(
533    feature = "unstable-asyncapi-docs",
534    asyncapi(summary = "Switch, dim or tune a device")
535)]
536pub struct SetRequest {
537    /// `ON`, `OFF` or `TOGGLE`, in any case. `ON` together with
538    /// `brightness` sets the level and turns the light on in one command.
539    #[serde(default, skip_serializing_if = "Option::is_none")]
540    pub state: Option<String>,
541    /// The level, 0 to 254.
542    #[serde(default, skip_serializing_if = "Option::is_none")]
543    pub brightness: Option<u64>,
544    /// The color temperature in mireds.
545    #[serde(default, skip_serializing_if = "Option::is_none")]
546    pub color_temp: Option<u64>,
547    /// How long a `brightness` or `color_temp` change takes, in seconds, to a
548    /// tenth.
549    #[serde(default, skip_serializing_if = "Option::is_none")]
550    pub transition: Option<f64>,
551}
552
553/// An attribute report, raw, on `<device>/report`. Not retained.
554#[derive(Debug, Clone, Serialize, Deserialize)]
555#[cfg_attr(
556    feature = "unstable-asyncapi-docs",
557    derive(JsonSchema, ToAsyncApiMessage)
558)]
559#[cfg_attr(
560    feature = "unstable-asyncapi-docs",
561    asyncapi(summary = "Every attribute report, raw, by cluster and attribute name")
562)]
563pub struct AttributeReport {
564    /// The endpoint it came from.
565    pub endpoint: u8,
566    /// The cluster, by name, or as hex when the bridge does not know it.
567    pub cluster: String,
568    /// Each attribute's value, by name or hex id.
569    pub attributes: Map<String, Json>,
570}
571
572/// A cluster command the device sent, such as a button press or an
573/// alarm, on `<device>/action`. Not retained.
574#[derive(Debug, Clone, Serialize, Deserialize)]
575#[cfg_attr(
576    feature = "unstable-asyncapi-docs",
577    derive(JsonSchema, ToAsyncApiMessage)
578)]
579#[cfg_attr(
580    feature = "unstable-asyncapi-docs",
581    asyncapi(summary = "A command the device sent: a button press, an alarm")
582)]
583pub struct DeviceAction {
584    /// The endpoint it came from.
585    pub endpoint: u8,
586    /// The cluster, by name or hex.
587    pub cluster: String,
588    /// The command, by name, or as hex when the bridge does not know it.
589    pub command: String,
590    /// The command's fields, by name.
591    pub fields: Map<String, Json>,
592}
593
594// ---------------------------------------------------------------------------
595// Requests and responses
596
597/// `ok` or `error`.
598#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
599#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
600#[serde(rename_all = "snake_case")]
601pub enum Status {
602    /// Done; `data` has the result.
603    Ok,
604    /// Not done; `error` says why.
605    Error,
606}
607
608macro_rules! response {
609    ($(#[$doc:meta])* $name:ident, $data:ty, $summary:literal) => {
610        $(#[$doc])*
611        ///
612        /// A response is published once per request, to
613        /// `bridge/response/<request>`, and is not retained.
614        #[derive(Debug, Clone, Serialize, Deserialize)]
615        #[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema, ToAsyncApiMessage))]
616        #[cfg_attr(feature = "unstable-asyncapi-docs", asyncapi(summary = $summary))]
617        pub struct $name {
618            /// `ok` or `error`.
619            pub status: Status,
620            /// The result, when `status` is `ok`.
621            #[serde(default, skip_serializing_if = "Option::is_none")]
622            pub data: Option<$data>,
623            /// What went wrong, when `status` is `error`.
624            #[serde(default, skip_serializing_if = "Option::is_none")]
625            pub error: Option<String>,
626            /// The request's `transaction`, echoed when it had one.
627            #[serde(default, skip_serializing_if = "Option::is_none")]
628            pub transaction: Option<Json>,
629        }
630
631        impl $name {
632            /// The response to a request with `transaction`.
633            pub fn new(result: Result<$data, String>, transaction: Option<Json>) -> Self {
634                match result {
635                    Ok(data) => $name { status: Status::Ok, data: Some(data), error: None, transaction },
636                    Err(error) => $name { status: Status::Error, data: None, error: Some(error), transaction },
637                }
638            }
639        }
640    };
641}
642
643macro_rules! request {
644    ($(#[$doc:meta])* $name:ident, $summary:literal { $($(#[$fdoc:meta])* $field:ident : $ty:ty),* $(,)? }) => {
645        $(#[$doc])*
646        #[derive(Debug, Clone, Default, Serialize, Deserialize)]
647        #[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema, ToAsyncApiMessage))]
648        #[cfg_attr(feature = "unstable-asyncapi-docs", asyncapi(summary = $summary))]
649        pub struct $name {
650            $($(#[$fdoc])* #[serde(default)] pub $field: $ty,)*
651            /// Any value; the response echoes it, so a client can match the
652            /// two.
653            #[serde(default, skip_serializing_if = "Option::is_none")]
654            pub transaction: Option<Json>,
655        }
656    };
657}
658
659request!(
660    /// Open or close joining, on `bridge/request/permit_join`.
661    PermitJoinRequest, "Open or close joining" {
662        /// Seconds to keep joining open; 0 closes it. Values over 254 are
663        /// capped at 254.
664        time: Option<u64>,
665        /// `true` for 254 seconds, `false` to close; used when `time` is
666        /// absent.
667        value: Option<bool>,
668        /// Open joining through this router only, by name or IEEE address.
669        device: Option<String>,
670    }
671);
672
673/// The result of `permit_join`.
674#[derive(Debug, Clone, Serialize, Deserialize)]
675#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
676pub struct PermitJoinData {
677    /// Seconds joining stays open.
678    pub time: u8,
679}
680
681response!(
682    /// The response to `permit_join`.
683    PermitJoinResponse, PermitJoinData, "Joining is open or closed"
684);
685
686request!(
687    /// Remove a device, on `bridge/request/remove`.
688    RemoveRequest, "Remove a device" {
689        /// The device, by name or IEEE address (`id` also works).
690        #[serde(alias = "id")]
691        device: Option<String>,
692        /// Forget the device even if it does not answer the leave request.
693        force: bool,
694    }
695);
696
697/// A device, by the name it was published under.
698#[derive(Debug, Clone, Serialize, Deserialize)]
699#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
700pub struct DeviceData {
701    /// The device's name.
702    pub device: String,
703}
704
705response!(
706    /// The response to `remove`.
707    RemoveResponse, DeviceData, "The device is removed"
708);
709
710request!(
711    /// Rename a device, on `bridge/request/rename`. Its topics move to the
712    /// new name; the readings stay.
713    RenameRequest, "Rename a device" {
714        /// The device, by name or IEEE address (`device` also works).
715        #[serde(alias = "device")]
716        from: Option<String>,
717        /// The new name (`name` also works). Not empty, no `+` or `#`, no
718        /// leading or trailing `/`, not ending in `/set`, not `bridge`.
719        #[serde(alias = "name")]
720        to: Option<String>,
721    }
722);
723
724/// The result of `rename`.
725#[derive(Debug, Clone, Serialize, Deserialize)]
726#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
727pub struct RenameData {
728    /// The old name.
729    pub from: String,
730    /// The new name.
731    pub to: String,
732}
733
734response!(
735    /// The response to `rename`.
736    RenameResponse, RenameData, "The device is renamed"
737);
738
739request!(
740    /// Add an install code, on `bridge/request/install_code`, so the device
741    /// with it can join.
742    InstallCodeRequest, "Let a device join with its install code" {
743        /// The device's IEEE address (`device` also works).
744        #[serde(alias = "device")]
745        ieee_address: Option<String>,
746        /// The install code in hex, as printed with its CRC; spaces, dashes
747        /// and colons are ignored.
748        code: Option<String>,
749    }
750);
751
752/// A device, by IEEE address.
753#[derive(Debug, Clone, Serialize, Deserialize)]
754#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
755pub struct IeeeData {
756    /// The device's IEEE address.
757    pub ieee_address: String,
758}
759
760response!(
761    /// The response to `install_code`.
762    InstallCodeResponse, IeeeData, "The install code is added"
763);
764
765request!(
766    /// Interview a device again, on `bridge/request/interview`.
767    InterviewRequest, "Interview a device again" {
768        /// The device, by name or IEEE address.
769        device: Option<String>,
770    }
771);
772
773response!(
774    /// The response to `interview`; `bridge/event` follows the interview.
775    InterviewResponse, DeviceData, "The interview is queued"
776);
777
778request!(
779    /// Write a backup of the network to the data directory, on
780    /// `bridge/request/backup`. The backup holds the network key, so it is
781    /// never published.
782    BackupRequest, "Back up the network" {}
783);
784
785/// The result of `backup`.
786#[derive(Debug, Clone, Serialize, Deserialize)]
787#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
788pub struct BackupData {
789    /// Where the backup was written.
790    pub path: String,
791    /// How many devices it has.
792    pub devices: usize,
793    /// The network key's outgoing frame counter.
794    pub frame_counter: u32,
795}
796
797response!(
798    /// The response to `backup`.
799    BackupResponse, BackupData, "The backup is written"
800);
801
802request!(
803    /// The network's links as the bridge knows them, on
804    /// `bridge/request/topology`.
805    TopologyRequest, "The network's links" {}
806);
807
808/// The result of `topology`.
809#[derive(Debug, Clone, Serialize, Deserialize)]
810#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
811pub struct TopologyData {
812    /// Every link.
813    pub links: Vec<TopologyLink>,
814}
815
816/// A link from one device to another (towards the coordinator for links
817/// learned from traffic).
818#[derive(Debug, Clone, Serialize, Deserialize)]
819#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
820pub struct TopologyLink {
821    /// The sending device's IEEE address, when known.
822    pub from: Option<String>,
823    /// The receiving device's IEEE address, when known.
824    pub to: Option<String>,
825    /// The sending device's network address.
826    pub from_network_address: u16,
827    /// The receiving device's network address.
828    pub to_network_address: u16,
829    /// Link quality, 0 to 255.
830    pub lqi: Option<u8>,
831    /// Signal strength in dBm.
832    pub rssi: Option<i8>,
833    /// Where the bridge learned the link.
834    pub source: LinkSource,
835    /// When it was last seen, in Unix seconds.
836    pub seen: u64,
837}
838
839/// Where a link was learned.
840#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
841#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
842#[serde(rename_all = "snake_case")]
843pub enum LinkSource {
844    /// The last hop of a message the coordinator received.
845    LastHop,
846    /// A hop in a route record.
847    RouteRecord,
848    /// A router's neighbor table.
849    NeighborTable,
850}
851
852impl From<zigbee_host::topology::LinkSource> for LinkSource {
853    fn from(s: zigbee_host::topology::LinkSource) -> Self {
854        use zigbee_host::topology::LinkSource as S;
855        match s {
856            S::LastHop => LinkSource::LastHop,
857            S::RouteRecord => LinkSource::RouteRecord,
858            S::NeighborTable => LinkSource::NeighborTable,
859        }
860    }
861}
862
863response!(
864    /// The response to `topology`.
865    TopologyResponse, TopologyData, "The network's links"
866);
867
868request!(
869    /// Ask a router for its neighbor table, on
870    /// `bridge/request/scan_neighbors`.
871    ScanNeighborsRequest, "Read a router's neighbor table" {
872        /// The router, by name or IEEE address; the coordinator when absent.
873        device: Option<String>,
874    }
875);
876
877/// The result of `scan_neighbors`.
878#[derive(Debug, Clone, Serialize, Deserialize)]
879#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
880pub struct ScanNeighborsData {
881    /// The router's neighbor table.
882    pub neighbors: Vec<Neighbor>,
883}
884
885/// A neighbor table entry.
886#[derive(Debug, Clone, Serialize, Deserialize)]
887#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
888pub struct Neighbor {
889    /// The neighbor's extended PAN id, as hex.
890    pub extended_pan_id: String,
891    /// Its IEEE address, as hex without `0x`.
892    pub ieee: String,
893    /// Its network address.
894    pub nwk: u16,
895    /// Device type (bits 0-1), receiver on when idle (2-3), relationship
896    /// (4-6).
897    pub flags: u8,
898    /// Permit joining (bits 0-1).
899    pub permit_joining: u8,
900    /// Tree depth.
901    pub depth: u8,
902    /// Link quality, 0 to 255.
903    pub lqi: u8,
904}
905
906impl From<zigbee_zdo::Neighbor> for Neighbor {
907    fn from(n: zigbee_zdo::Neighbor) -> Self {
908        Neighbor {
909            extended_pan_id: n.extended_pan_id.to_string(),
910            ieee: n.ieee.to_string(),
911            nwk: n.nwk,
912            flags: n.flags,
913            permit_joining: n.permit_joining,
914            depth: n.depth,
915            lqi: n.lqi,
916        }
917    }
918}
919
920response!(
921    /// The response to `scan_neighbors`.
922    ScanNeighborsResponse, ScanNeighborsData, "The router's neighbors"
923);
924
925request!(
926    /// Ask whether the OTA directory has newer firmware for a device, on
927    /// `bridge/request/ota_check`. A sleepy device answers when it next
928    /// wakes, so the response can take a while.
929    OtaCheckRequest, "Check a device for a firmware update" {
930        /// The device, by name or IEEE address.
931        device: Option<String>,
932    }
933);
934
935/// The result of `ota_check` and `ota_update`.
936#[derive(Debug, Clone, Serialize, Deserialize)]
937#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
938pub struct OtaData {
939    /// The device's name.
940    pub device: String,
941    /// The file version it runs.
942    pub installed_version: u32,
943    /// The newest newer version in the OTA directory.
944    pub latest_version: Option<u32>,
945    /// That image's size in bytes.
946    pub size: Option<u32>,
947    /// An update started; `bridge/event` reports its progress.
948    pub updating: bool,
949}
950
951response!(
952    /// The response to `ota_check`.
953    OtaCheckResponse, OtaData, "Whether a firmware update is available"
954);
955
956request!(
957    /// Update a device's firmware from the OTA directory, on
958    /// `bridge/request/ota_update`. The response comes once the device
959    /// starts the download; `bridge/event` reports the rest.
960    OtaUpdateRequest, "Update a device's firmware" {
961        /// The device, by name or IEEE address.
962        device: Option<String>,
963    }
964);
965
966response!(
967    /// The response to `ota_update`.
968    OtaUpdateResponse, OtaData, "The firmware update started"
969);
970
971request!(
972    /// Move the network to another channel without pairing again, on
973    /// `bridge/request/change_channel`.
974    ChangeChannelRequest, "Move the network to another channel" {
975        /// The new channel, 11 to 26.
976        channel: Option<u64>,
977    }
978);
979
980/// The result of `change_channel`.
981#[derive(Debug, Clone, Serialize, Deserialize)]
982#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
983pub struct ChannelData {
984    /// The channel now.
985    pub channel: u8,
986    /// The network update id now.
987    pub update_id: u8,
988}
989
990response!(
991    /// The response to `change_channel`.
992    ChangeChannelResponse, ChannelData, "The network changed channel"
993);
994
995request!(
996    /// Measure the noise on every channel, on `bridge/request/energy_scan`.
997    EnergyScanRequest, "Measure the noise on every channel" {}
998);
999
1000/// The result of `energy_scan`.
1001#[derive(Debug, Clone, Serialize, Deserialize)]
1002#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
1003pub struct EnergyScanData {
1004    /// Each channel's loudest signal.
1005    pub channels: Vec<ChannelEnergy>,
1006}
1007
1008/// One channel's energy.
1009#[derive(Debug, Clone, Serialize, Deserialize)]
1010#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
1011pub struct ChannelEnergy {
1012    /// The channel.
1013    pub channel: u8,
1014    /// The loudest signal on it, in dBm.
1015    pub max_rssi: i8,
1016}
1017
1018response!(
1019    /// The response to `energy_scan`.
1020    EnergyScanResponse, EnergyScanData, "Each channel's noise"
1021);
1022
1023request!(
1024    /// Publish `bridge/devices` again, on `bridge/request/devices`.
1025    DevicesRequest, "Publish the device list again" {}
1026);
1027
1028/// An empty result.
1029#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1030#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
1031pub struct Empty {}
1032
1033response!(
1034    /// The response to `devices`.
1035    DevicesResponse, Empty, "The device list is published"
1036);
1037
1038response!(
1039    /// The response to a request the bridge does not know; `error` names
1040    /// it.
1041    UnknownResponse, Empty, "The request is unknown"
1042);
1043
1044// ---------------------------------------------------------------------------
1045// Home Assistant
1046
1047/// Home Assistant's own availability, on its birth topic
1048/// (`homeassistant.status_topic`, default `homeassistant/status`). When it
1049/// says `online`, the bridge publishes discovery again. Plain text, not
1050/// JSON.
1051#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1052#[cfg_attr(
1053    feature = "unstable-asyncapi-docs",
1054    derive(JsonSchema, ToAsyncApiMessage)
1055)]
1056#[cfg_attr(
1057    feature = "unstable-asyncapi-docs",
1058    asyncapi(
1059        summary = "Home Assistant started or stopped",
1060        content_type = "text/plain"
1061    )
1062)]
1063#[serde(transparent)]
1064pub struct HomeAssistantStatus(pub HomeAssistantState);
1065
1066/// Whether Home Assistant runs.
1067#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1068#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
1069#[serde(rename_all = "snake_case")]
1070pub enum HomeAssistantState {
1071    /// Home Assistant started.
1072    Online,
1073    /// Home Assistant stopped.
1074    Offline,
1075}
1076
1077impl HomeAssistantStatus {
1078    /// The status in a payload, if it is one.
1079    pub fn parse(payload: &[u8]) -> Option<HomeAssistantState> {
1080        match payload {
1081            b"online" => Some(HomeAssistantState::Online),
1082            b"offline" => Some(HomeAssistantState::Offline),
1083            _ => None,
1084        }
1085    }
1086}
1087
1088/// A Home Assistant MQTT discovery config, retained on
1089/// `<discovery_prefix>/<component>/<ieee>/<field>/config`: one entity per
1090/// reading, light or switch. An empty retained message removes the entity.
1091/// Keys are Home Assistant's; see its MQTT integration documentation.
1092#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1093#[cfg_attr(
1094    feature = "unstable-asyncapi-docs",
1095    derive(JsonSchema, ToAsyncApiMessage)
1096)]
1097#[cfg_attr(
1098    feature = "unstable-asyncapi-docs",
1099    asyncapi(summary = "A Home Assistant entity for one of a device's readings")
1100)]
1101pub struct DiscoveryConfig {
1102    /// The entity's name.
1103    pub name: String,
1104    /// Unique across Home Assistant: `<ieee>_<field>_zigbee-bridge`.
1105    pub unique_id: String,
1106    /// The entity id Home Assistant derives: `<device>_<field>`.
1107    pub object_id: String,
1108    /// The device's state topic.
1109    pub state_topic: String,
1110    /// Picks the reading out of the state.
1111    #[serde(default, skip_serializing_if = "Option::is_none")]
1112    pub value_template: Option<String>,
1113    /// The bridge's availability.
1114    pub availability: Vec<DiscoveryAvailability>,
1115    /// The device the entity belongs to.
1116    pub device: DiscoveryDevice,
1117    /// The bridge, as the entity's origin.
1118    pub origin: DiscoveryOrigin,
1119    /// `json` for lights: state and commands are JSON.
1120    #[serde(default, skip_serializing_if = "Option::is_none")]
1121    pub schema: Option<String>,
1122    /// The device's `/set` topic, for lights and switches.
1123    #[serde(default, skip_serializing_if = "Option::is_none")]
1124    pub command_topic: Option<String>,
1125    /// Lights: supports brightness.
1126    #[serde(default, skip_serializing_if = "Option::is_none")]
1127    pub brightness: Option<bool>,
1128    /// Lights: the highest level.
1129    #[serde(default, skip_serializing_if = "Option::is_none")]
1130    pub brightness_scale: Option<u16>,
1131    /// Lights: `color_temp` when the light has color control.
1132    #[serde(default, skip_serializing_if = "Option::is_none")]
1133    pub supported_color_modes: Option<Vec<String>>,
1134    /// The reading's unit.
1135    #[serde(default, skip_serializing_if = "Option::is_none")]
1136    pub unit_of_measurement: Option<String>,
1137    /// Home Assistant's device class for the reading.
1138    #[serde(default, skip_serializing_if = "Option::is_none")]
1139    pub device_class: Option<String>,
1140    /// Home Assistant's state class for the reading.
1141    #[serde(default, skip_serializing_if = "Option::is_none")]
1142    pub state_class: Option<String>,
1143    /// `diagnostic` for battery, link quality and tamper.
1144    #[serde(default, skip_serializing_if = "Option::is_none")]
1145    pub entity_category: Option<String>,
1146    /// Binary sensors: the value that means on. Switches: the command that
1147    /// turns it on.
1148    #[serde(default, skip_serializing_if = "Option::is_none")]
1149    pub payload_on: Option<DiscoveryPayload>,
1150    /// Binary sensors: the value that means off. Switches: the command that
1151    /// turns it off.
1152    #[serde(default, skip_serializing_if = "Option::is_none")]
1153    pub payload_off: Option<DiscoveryPayload>,
1154    /// Switches: the state that means on.
1155    #[serde(default, skip_serializing_if = "Option::is_none")]
1156    pub state_on: Option<String>,
1157    /// Switches: the state that means off.
1158    #[serde(default, skip_serializing_if = "Option::is_none")]
1159    pub state_off: Option<String>,
1160    /// The entity's icon.
1161    #[serde(default, skip_serializing_if = "Option::is_none")]
1162    pub icon: Option<String>,
1163}
1164
1165/// A binary sensor's value or a switch's command.
1166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1167#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
1168#[serde(untagged)]
1169pub enum DiscoveryPayload {
1170    /// A binary sensor's value.
1171    Bool(bool),
1172    /// A switch's command, as JSON text.
1173    Text(String),
1174}
1175
1176/// Where Home Assistant reads availability.
1177#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1178#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
1179pub struct DiscoveryAvailability {
1180    /// The bridge's `bridge/state`.
1181    pub topic: String,
1182    /// Picks `state` out of it.
1183    pub value_template: String,
1184}
1185
1186/// The device an entity belongs to.
1187#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1188#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
1189pub struct DiscoveryDevice {
1190    /// `zigbee-bridge_<ieee>`.
1191    pub identifiers: Vec<String>,
1192    /// The device's name.
1193    pub name: String,
1194    /// From the Basic cluster.
1195    #[serde(default, skip_serializing_if = "Option::is_none")]
1196    pub manufacturer: Option<String>,
1197    /// From the Basic cluster.
1198    #[serde(default, skip_serializing_if = "Option::is_none")]
1199    pub model: Option<String>,
1200    /// From the Basic cluster.
1201    #[serde(default, skip_serializing_if = "Option::is_none")]
1202    pub sw_version: Option<String>,
1203}
1204
1205/// The software that published the entity.
1206#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1207#[cfg_attr(feature = "unstable-asyncapi-docs", derive(JsonSchema))]
1208pub struct DiscoveryOrigin {
1209    /// `zigbee-bridge`.
1210    pub name: String,
1211    /// The bridge's version.
1212    pub sw_version: String,
1213}