Parcourir la source

【框架】引入MQTT

mikasa il y a 1 mois
Parent
commit
33eb07a602
4 fichiers modifiés avec 63 ajouts et 4 suppressions
  1. 9 4
      emu-config.yaml
  2. 9 0
      src/cmd/config.rs
  3. 1 0
      src/internal/utils/mod.rs
  4. 44 0
      src/internal/utils/mqtt.rs

+ 9 - 4
emu-config.yaml

@@ -1,7 +1,7 @@
 emu:
   ver: '0.0.1'
   pcs:
-    host: "127.0.0.1"
+    host: '127.0.0.1'
     port: 33434
   bms:
   ems:
@@ -10,7 +10,12 @@ emu:
 rabbitmq:
   host: '122.51.163.61'
   port: 5672
-  username: "guest"
-  password: "yuanan520."
+  username: 'guest'
+  password: 'yuanan520.'
+mqtt:
+  host: '122.51.163.61'
+  port: 1883
+  username: 'inpower'
+  password: 'inpower@123'
 log:
-  path: "logs"
+  path: 'logs'

+ 9 - 0
src/cmd/config.rs

@@ -13,6 +13,7 @@ pub fn app_config() -> &'static AppConfig {
 pub struct AppConfig {
     pub emu: EmuConfig,
     pub rabbitmq: RabbitMQConfig,
+    pub mqtt: MqttConfig,
     pub log: LogConfig,
 }
 
@@ -48,3 +49,11 @@ pub struct RabbitMQConfig {
 pub struct LogConfig {
     pub path: String,
 }
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct MqttConfig {
+    pub host: String,
+    pub port: u16,
+    pub username: String,
+    pub password: String,
+}

+ 1 - 0
src/internal/utils/mod.rs

@@ -3,6 +3,7 @@ use rand::{rng, Rng};
 
 pub mod log;
 pub mod mq;
+pub mod mqtt;
 
 pub fn generate_random_str(len: usize) -> String {
     rng()

+ 44 - 0
src/internal/utils/mqtt.rs

@@ -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 })
+    }
+}