Skip to main content

zigbee_bridge/
mqtt.rs

1//! The MQTT session: one connection, re-established by rumqttc's event
2//! loop, with the bridge's availability as the last will.
3
4use std::time::Duration;
5
6use rumqttc::{AsyncClient, Event, LastWill, MqttOptions, Packet, QoS};
7use tokio::sync::mpsc;
8
9use crate::config::MqttConfig;
10
11/// Something from the broker.
12#[derive(Debug)]
13pub enum Incoming {
14    /// The session (re)connected: subscribe and republish retained state.
15    Connected,
16    /// A message on a subscribed topic.
17    Message {
18        /// Topic.
19        topic: String,
20        /// Payload.
21        payload: Vec<u8>,
22    },
23}
24
25/// A cloneable publisher.
26#[derive(Clone, Debug)]
27pub struct Mqtt {
28    client: AsyncClient,
29}
30
31/// The availability topic.
32pub fn state_topic(base: &str) -> String {
33    format!("{base}/bridge/state")
34}
35
36/// Connect (in the background) and return the publisher and incoming
37/// messages.
38pub fn connect(config: &MqttConfig) -> Result<(Mqtt, mpsc::Receiver<Incoming>), String> {
39    let mut options = MqttOptions::new(&config.client_id, &config.host, config.port);
40    options.set_keep_alive(Duration::from_secs(config.keepalive.max(5)));
41    options.set_clean_session(true);
42    options.set_max_packet_size(256 * 1024, 256 * 1024);
43    options.set_last_will(LastWill::new(
44        state_topic(&config.base_topic),
45        r#"{"state":"offline"}"#,
46        QoS::AtLeastOnce,
47        true,
48    ));
49    if let Some(user) = &config.username {
50        let password = match &config.password_file {
51            Some(path) => std::fs::read_to_string(path)
52                .map_err(|e| format!("mqtt.password_file {}: {e}", path.display()))?
53                .trim_end()
54                .to_string(),
55            None => String::new(),
56        };
57        options.set_credentials(user, password);
58    }
59    let (client, mut event_loop) = AsyncClient::new(options, 256);
60    let (tx, rx) = mpsc::channel(256);
61    tokio::spawn(async move {
62        loop {
63            match event_loop.poll().await {
64                Ok(Event::Incoming(Packet::ConnAck(_))) => {
65                    tracing::info!("MQTT connected");
66                    if tx.send(Incoming::Connected).await.is_err() {
67                        return;
68                    }
69                }
70                Ok(Event::Incoming(Packet::Publish(p))) => {
71                    let message = Incoming::Message {
72                        topic: p.topic.clone(),
73                        payload: p.payload.to_vec(),
74                    };
75                    if tx.send(message).await.is_err() {
76                        return;
77                    }
78                }
79                Ok(_) => {}
80                Err(e) => {
81                    tracing::warn!(error = %e, "MQTT connection; retrying");
82                    tokio::time::sleep(Duration::from_secs(2)).await;
83                }
84            }
85        }
86    });
87    Ok((Mqtt { client }, rx))
88}
89
90impl Mqtt {
91    /// Publish without blocking the caller on the broker.
92    pub async fn publish(
93        &self,
94        topic: impl Into<String>,
95        payload: impl Into<Vec<u8>>,
96        retain: bool,
97    ) {
98        let topic = topic.into();
99        if let Err(e) = self
100            .client
101            .publish(topic.clone(), QoS::AtLeastOnce, retain, payload.into())
102            .await
103        {
104            tracing::warn!(%topic, error = %e, "MQTT publish");
105        }
106    }
107
108    /// Publish JSON.
109    pub async fn publish_json(
110        &self,
111        topic: impl Into<String>,
112        value: &serde_json::Value,
113        retain: bool,
114    ) {
115        self.publish(topic, serde_json::to_vec(value).unwrap_or_default(), retain)
116            .await;
117    }
118
119    /// Subscribe.
120    pub async fn subscribe(&self, filter: &str) {
121        if let Err(e) = self.client.subscribe(filter, QoS::AtLeastOnce).await {
122            tracing::warn!(%filter, error = %e, "MQTT subscribe");
123        }
124    }
125
126    /// Disconnect cleanly (the will is not sent).
127    pub async fn disconnect(&self) {
128        let _ = self.client.disconnect().await;
129    }
130}