Skip to main content

zigbee_bridge/
lib.rs

1#![doc = include_str!("../README.md")]
2
3pub mod bridge;
4pub mod config;
5pub mod exposes;
6pub mod mqtt;
7pub mod network;
8
9use std::path::Path;
10
11use zigbee_host::{
12    AnyAdapter, Backup, Host, HostConfig, HostError, JoinPolicy, NcpKind, StartMode,
13};
14
15pub use config::Config;
16
17/// The device store's file name in the data directory.
18pub const STORE_FILE: &str = "devices.json";
19/// The latest backup's file name in the data directory.
20pub const BACKUP_FILE: &str = "backup.json";
21/// A backup staged by `zigbee-bridge restore`, restored on the next start.
22pub const RESTORE_FILE: &str = "restore-pending.json";
23
24/// Why the bridge stopped.
25#[derive(Debug, thiserror::Error)]
26pub enum RunError {
27    /// Bad configuration or data directory.
28    #[error("{0}")]
29    Setup(String),
30    /// The coordinator could not be opened or started.
31    #[error("coordinator: {0}")]
32    Coordinator(#[from] HostError),
33    /// A restore wrote the coordinator's IEEE address; start again to
34    /// finish it.
35    #[error(
36        "the coordinator's IEEE address was written for the restore; start again to finish it"
37    )]
38    RestartRequired,
39    /// The bridge stopped running.
40    #[error("{0}")]
41    Stopped(String),
42}
43
44/// Stage a backup to be restored onto the coordinator on the next start.
45pub fn stage_restore(config: &Config, backup_json: &str) -> Result<Backup, RunError> {
46    let backup = Backup::from_json(backup_json).map_err(|e| RunError::Setup(e.to_string()))?;
47    let dir = &config.data.dir;
48    create_dir(dir)?;
49    zigbee_host::store::write_atomic(&dir.join(RESTORE_FILE), backup_json.as_bytes())
50        .map_err(|e| RunError::Setup(e.to_string()))?;
51    Ok(backup)
52}
53
54fn create_dir(dir: &Path) -> Result<(), RunError> {
55    std::fs::create_dir_all(dir)
56        .map_err(|e| RunError::Setup(format!("data directory {}: {e}", dir.display())))?;
57    #[cfg(unix)]
58    {
59        use std::os::unix::fs::PermissionsExt;
60        let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
61    }
62    Ok(())
63}
64
65/// Probe `port` for each coordinator family.
66async fn detect(port: &str, baud: u32) -> Result<NcpKind, RunError> {
67    match zigbee_host::probe::probe_any(port, baud).await {
68        Ok(Some(id)) if id.supported => {
69            tracing::info!(kind = id.kind.name(), firmware = %id.firmware, "coordinator detected");
70            Ok(id.kind)
71        }
72        Ok(Some(id)) => Err(RunError::Setup(format!(
73            "{port}: {} coordinator firmware {} is too old; update it (EmberZNet 7.4 or newer, Z-Stack 3, deCONZ 0x26580700 or newer)",
74            id.kind.name(),
75            id.firmware
76        ))),
77        Ok(None) => Err(RunError::Setup(format!(
78            "{port}: no EZSP, ZNP or deCONZ coordinator answered at {baud} baud (set serial.adapter to skip detection)"
79        ))),
80        Err(e) => Err(RunError::Setup(format!("{port}: {e}"))),
81    }
82}
83
84/// Run the bridge until `stop` resolves.
85pub async fn run(
86    config: Config,
87    stop: impl std::future::Future<Output = ()>,
88) -> Result<(), RunError> {
89    let dir = config.data.dir.clone();
90    create_dir(&dir)?;
91
92    let restore_path = dir.join(RESTORE_FILE);
93    let mode = match std::fs::read_to_string(&restore_path) {
94        Ok(text) => {
95            let backup = Backup::from_json(&text)
96                .map_err(|e| RunError::Setup(format!("{}: {e}", restore_path.display())))?;
97            tracing::warn!(pan = format!("{:04x}", backup.pan_id), ieee = %backup.coordinator_ieee, "restoring a backup onto the coordinator");
98            network::save(&dir, &network::from_backup(&backup)).map_err(RunError::Setup)?;
99            StartMode::Restore(Box::new(backup))
100        }
101        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
102            let (settings, created) =
103                network::load_or_create(&dir, config.network.channel, config.network.tx_power)
104                    .map_err(RunError::Setup)?;
105            if created {
106                tracing::info!(
107                    channel = settings.channel,
108                    pan = format!("{:04x}", settings.pan_id),
109                    "new network settings written"
110                );
111            }
112            StartMode::Normal {
113                settings,
114                replace_other: config.network.replace_other,
115            }
116        }
117        Err(e) => return Err(RunError::Setup(format!("{}: {e}", restore_path.display()))),
118    };
119    let restoring = matches!(mode, StartMode::Restore(_));
120
121    let flow = match config.serial.flow_control {
122        config::FlowControl::None => zigbee_host::port::FlowControl::None,
123        config::FlowControl::Hardware => zigbee_host::port::FlowControl::Hardware,
124        config::FlowControl::Software => zigbee_host::port::FlowControl::Software,
125    };
126    let kind = match config.serial.adapter {
127        config::AdapterChoice::Ezsp => NcpKind::Ezsp,
128        config::AdapterChoice::Znp => NcpKind::Znp,
129        config::AdapterChoice::Deconz => NcpKind::Deconz,
130        config::AdapterChoice::Auto => detect(&config.serial.port, config.serial.baud).await?,
131    };
132    let port = zigbee_host::port::open(&config.serial.port, config.serial.baud, flow)
133        .await
134        .map_err(|e| RunError::Setup(format!("opening {}: {e}", config.serial.port)))?;
135    let (adapter, adapter_events) = AnyAdapter::connect(port, kind).await?;
136    let host_config = HostConfig {
137        store_path: Some(dir.join(STORE_FILE)),
138        backup_path: Some(dir.join(BACKUP_FILE)),
139        join: JoinPolicy {
140            install_code_only: config.join.install_code_only,
141            allow_legacy: config.join.allow_legacy,
142        },
143        ota_dir: Some(config.ota.dir.clone().unwrap_or_else(|| dir.join("ota"))),
144        ..HostConfig::default()
145    };
146    let (host, host_events) = match Host::start(adapter, adapter_events, mode, host_config).await {
147        Ok(started) => started,
148        Err(HostError::RestartRequired) => return Err(RunError::RestartRequired),
149        Err(e) => return Err(e.into()),
150    };
151    if restoring {
152        let _ = std::fs::remove_file(&restore_path);
153        tracing::info!("restore finished");
154    }
155    let (mqtt, mqtt_in) = mqtt::connect(&config.mqtt).map_err(RunError::Setup)?;
156    let bridge = bridge::Bridge::new(host, mqtt, config);
157    bridge::run_loop(bridge, host_events, mqtt_in, stop)
158        .await
159        .map_err(RunError::Stopped)
160}