1use std::time::Duration;
5
6use rumqttc::{AsyncClient, Event, LastWill, MqttOptions, Packet, QoS};
7use tokio::sync::mpsc;
8
9use crate::api::{Availability, BridgeState};
10use crate::config::MqttConfig;
11
12#[derive(Debug)]
14pub enum Incoming {
15 Connected,
17 Message {
19 topic: String,
21 payload: Vec<u8>,
23 },
24}
25
26#[derive(Clone, Debug)]
28pub struct Mqtt {
29 client: AsyncClient,
30}
31
32pub fn state_topic(base: &str) -> String {
34 format!("{base}/bridge/state")
35}
36
37pub fn connect(config: &MqttConfig) -> Result<(Mqtt, mpsc::Receiver<Incoming>), String> {
40 let mut options = MqttOptions::new(&config.client_id, &config.host, config.port);
41 options.set_keep_alive(Duration::from_secs(config.keepalive.max(5)));
42 options.set_clean_session(true);
43 options.set_max_packet_size(256 * 1024, 256 * 1024);
44 options.set_last_will(LastWill::new(
45 state_topic(&config.base_topic),
46 BridgeState::payload(Availability::Offline),
47 QoS::AtLeastOnce,
48 true,
49 ));
50 if let Some(user) = &config.username {
51 let password = match &config.password_file {
52 Some(path) => std::fs::read_to_string(path)
53 .map_err(|e| format!("mqtt.password_file {}: {e}", path.display()))?
54 .trim_end()
55 .to_string(),
56 None => String::new(),
57 };
58 options.set_credentials(user, password);
59 }
60 let (client, mut event_loop) = AsyncClient::new(options, 256);
61 let (tx, rx) = mpsc::channel(256);
62 tokio::spawn(async move {
63 loop {
64 match event_loop.poll().await {
65 Ok(Event::Incoming(Packet::ConnAck(_))) => {
66 tracing::info!("MQTT connected");
67 if tx.send(Incoming::Connected).await.is_err() {
68 return;
69 }
70 }
71 Ok(Event::Incoming(Packet::Publish(p))) => {
72 let message = Incoming::Message {
73 topic: p.topic.clone(),
74 payload: p.payload.to_vec(),
75 };
76 if tx.send(message).await.is_err() {
77 return;
78 }
79 }
80 Ok(_) => {}
81 Err(e) => {
82 tracing::warn!(error = %e, "MQTT connection; retrying");
83 tokio::time::sleep(Duration::from_secs(2)).await;
84 }
85 }
86 }
87 });
88 Ok((Mqtt { client }, rx))
89}
90
91impl Mqtt {
92 pub async fn publish(
94 &self,
95 topic: impl Into<String>,
96 payload: impl Into<Vec<u8>>,
97 retain: bool,
98 ) {
99 let topic = topic.into();
100 if let Err(e) = self
101 .client
102 .publish(topic.clone(), QoS::AtLeastOnce, retain, payload.into())
103 .await
104 {
105 tracing::warn!(%topic, error = %e, "MQTT publish");
106 }
107 }
108
109 pub async fn publish_json(
111 &self,
112 topic: impl Into<String>,
113 value: &impl serde::Serialize,
114 retain: bool,
115 ) {
116 self.publish(topic, serde_json::to_vec(value).unwrap_or_default(), retain)
117 .await;
118 }
119
120 pub async fn subscribe(&self, filter: &str) {
122 if let Err(e) = self.client.subscribe(filter, QoS::AtLeastOnce).await {
123 tracing::warn!(%filter, error = %e, "MQTT subscribe");
124 }
125 }
126
127 pub async fn disconnect(&self) {
129 let _ = self.client.disconnect().await;
130 }
131}