Skip to main content

bluetooth_bridge/
mqtt.rs

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