瀏覽代碼

配置mqtt到文件中

dev
OCEAN 3 月之前
父節點
當前提交
5e562ab10a
共有 2 個文件被更改,包括 31 次插入6 次删除
  1. +10
    -1
      config.json
  2. +21
    -5
      src/main.rs

+ 10
- 1
config.json 查看文件

@@ -1,5 +1,14 @@
{ {
"scale_type": "001", "scale_type": "001",
"serial_port": "/dev/ttyS1", "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 查看文件

@@ -6,7 +6,6 @@ use std::io::{self, Read};
use std::time::Duration; use std::time::Duration;
use std::thread; use std::thread;
use serialport; use serialport;
use std::process::Command;
use actix_web::{web, App, HttpServer, HttpResponse}; use actix_web::{web, App, HttpServer, HttpResponse};
use actix_cors::Cors; use actix_cors::Cors;
use std::fs; use std::fs;
@@ -27,11 +26,23 @@ struct ScaleTypeResponse {
scale_type: String, 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)] #[derive(Deserialize)]
struct Config { struct Config {
scale_type: String, scale_type: String,
serial_port: String, serial_port: String,
baud_rate: u32, baud_rate: u32,
mqtt: MqttConfig,
} }


fn read_config() -> Result<Config> { fn read_config() -> Result<Config> {
@@ -122,9 +133,13 @@ async fn run_mqtt_and_serial() -> Result<()> {
let config = read_config()?; let config = read_config()?;
// 创建 MQTT 客户端 // 创建 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); let (mut client, mut connection) = Client::new(mqttopts, 10);


// 在单独的线程中处理 MQTT 连接 // 在单独的线程中处理 MQTT 连接
@@ -192,7 +207,8 @@ async fn run_mqtt_and_serial() -> Result<()> {
let mac_address = get_mac_address(); let mac_address = get_mac_address();
println!("MAC地址: {}", mac_address); println!("MAC地址: {}", mac_address);
// 发布到 MQTT,主题中包含MAC地址 // 发布到 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); eprintln!("MQTT发布错误: {:?}", e);
} else { } else {
println!("成功发送数据到MQTT"); println!("成功发送数据到MQTT");


Loading…
取消
儲存