Skip to main content

zigbee_bridge/
lib.rs

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