Procházet zdrojové kódy

配置mqtt到文件中

dev
OCEAN před 3 měsíci
rodič
revize
5e562ab10a
2 změnil soubory, kde provedl 31 přidání a 6 odebrání
  1. +10
    -1
      config.json
  2. +21
    -5
      src/main.rs

+ 10
- 1
config.json Zobrazit soubor

@@ -1,5 +1,14 @@
{
"scale_type": "001",
"serial_port": "/dev/ttyS1",
"baud_rate": 9600
"baud_rate": 9600,
"mqtt": {
"client_id": "weight_reader",
"host": "112.33.111.160",
"port": 1883,
"username": "auseft",
"password": "1q2w3E**",
"keep_alive_secs": 5,
"topic_prefix": "weight/data"
}
}

+ 21
- 5
src/main.rs Zobrazit soubor

@@ -6,7 +6,6 @@ use std::io::{self, Read};
use std::time::Duration;
use std::thread;
use serialport;
use std::process::Command;
use actix_web::{web, App, HttpServer, HttpResponse};
use actix_cors::Cors;
use std::fs;
@@ -27,11 +26,23 @@ struct ScaleTypeResponse {
scale_type: String,
}

#[derive(Deserialize)]
struct MqttConfig {
client_id: String,
host: String,
port: u16,
username: String,
password: String,
keep_alive_secs: u64,
topic_prefix: String,
}

#[derive(Deserialize)]
struct Config {
scale_type: String,
serial_port: String,
baud_rate: u32,
mqtt: MqttConfig,
}

fn read_config() -> Result<Config> {
@@ -122,9 +133,13 @@ async fn run_mqtt_and_serial() -> Result<()> {
let config = read_config()?;
// 创建 MQTT 客户端
let mut mqttopts = MqttOptions::new("weight_reader", "112.33.111.160", 1883);
mqttopts.set_keep_alive(Duration::from_secs(5));
mqttopts.set_credentials("auseft", "1q2w3E**");
let mut mqttopts = MqttOptions::new(
&config.mqtt.client_id,
&config.mqtt.host,
config.mqtt.port
);
mqttopts.set_keep_alive(Duration::from_secs(config.mqtt.keep_alive_secs));
mqttopts.set_credentials(&config.mqtt.username, &config.mqtt.password);
let (mut client, mut connection) = Client::new(mqttopts, 10);

// 在单独的线程中处理 MQTT 连接
@@ -192,7 +207,8 @@ async fn run_mqtt_and_serial() -> Result<()> {
let mac_address = get_mac_address();
println!("MAC地址: {}", mac_address);
// 发布到 MQTT,主题中包含MAC地址
if let Err(e) = client.publish(format!("weight/data/{}", mac_address), QoS::AtLeastOnce, false, json_data) {
let topic = format!("{}/{}", config.mqtt.topic_prefix, mac_address);
if let Err(e) = client.publish(topic, QoS::AtLeastOnce, false, json_data) {
eprintln!("MQTT发布错误: {:?}", e);
} else {
println!("成功发送数据到MQTT");


Načítá se…
Zrušit
Uložit