|
@@ -0,0 +1,44 @@
|
|
|
+use crate::cmd::config::app_config;
|
|
|
+use anyhow::anyhow;
|
|
|
+use mosquitto_rs::Client;
|
|
|
+use std::os::raw::c_int;
|
|
|
+use std::sync::OnceLock;
|
|
|
+
|
|
|
+static MQTT: OnceLock<MqttClient> = OnceLock::new();
|
|
|
+
|
|
|
+pub async fn mqtt_client() -> anyhow::Result<&'static MqttClient> {
|
|
|
+ let conn = match MQTT.get() {
|
|
|
+ Some(client) => client,
|
|
|
+ None => {
|
|
|
+ let client = MqttClient::new().await?;
|
|
|
+ MQTT.set(client)
|
|
|
+ .map_err(|_| anyhow!("MQTT already initialized"))?;
|
|
|
+ MQTT.get().unwrap()
|
|
|
+ }
|
|
|
+ };
|
|
|
+ Ok(&conn)
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+pub struct MqttClient {
|
|
|
+ pub mosq: Client,
|
|
|
+}
|
|
|
+
|
|
|
+impl MqttClient {
|
|
|
+ async fn new() -> anyhow::Result<Self> {
|
|
|
+ let mqtt_config = &app_config().mqtt;
|
|
|
+ let mosq = Client::with_auto_id()?;
|
|
|
+ mosq.set_username_and_password(
|
|
|
+ Some(mqtt_config.username.as_str()),
|
|
|
+ Some(mqtt_config.password.as_str()),
|
|
|
+ )?;
|
|
|
+ mosq.connect(
|
|
|
+ &*mqtt_config.host,
|
|
|
+ mqtt_config.port as c_int,
|
|
|
+ std::time::Duration::from_secs(5),
|
|
|
+ None,
|
|
|
+ )
|
|
|
+ .await?;
|
|
|
+ Ok(MqttClient { mosq })
|
|
|
+ }
|
|
|
+}
|