mirror of
https://git.sdf.org/epl692/tui-mqtt-chat.git
synced 2025-12-08 05:48:49 -05:00
feat: move mqtt configuration to config.ini
This commit is contained in:
25
src/main.rs
25
src/main.rs
@@ -5,11 +5,12 @@ use crossterm::{
|
||||
};
|
||||
use ratatui::{prelude::*, widgets::*};
|
||||
use rumqttc::{AsyncClient, MqttOptions, QoS};
|
||||
use std::{io, time::Duration};
|
||||
use std::{io, time::Duration, path::Path};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_stream::StreamExt;
|
||||
use rand::Rng;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use configparser::ini::Ini;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct ChatMessage {
|
||||
@@ -81,8 +82,28 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
async fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Result<()> {
|
||||
let (tx, mut rx) = mpsc::channel::<(String, String)>(100);
|
||||
|
||||
let mut mqttoptions = MqttOptions::new(app.username.clone(), "172.16.0.3", 1883);
|
||||
let mut config = Ini::new();
|
||||
let config_path = "config.ini";
|
||||
|
||||
if !Path::new(config_path).exists() {
|
||||
config.set("mqtt", "server", Some("172.16.0.3".to_owned()));
|
||||
config.set("mqtt", "port", Some("1883".to_owned()));
|
||||
config.set("mqtt", "username", Some("".to_owned()));
|
||||
config.set("mqtt", "password", Some("".to_owned()));
|
||||
config.write(config_path).unwrap();
|
||||
}
|
||||
|
||||
let map = config.load(config_path).unwrap();
|
||||
let server = map.get("mqtt").unwrap().get("server").unwrap().clone().unwrap();
|
||||
let port = map.get("mqtt").unwrap().get("port").unwrap().clone().unwrap().parse::<u16>().unwrap();
|
||||
let username = map.get("mqtt").unwrap().get("username").unwrap().clone().unwrap();
|
||||
let password = map.get("mqtt").unwrap().get("password").unwrap().clone().unwrap();
|
||||
|
||||
let mut mqttoptions = MqttOptions::new(app.username.clone(), server, port);
|
||||
mqttoptions.set_keep_alive(Duration::from_secs(5));
|
||||
if !username.is_empty() {
|
||||
mqttoptions.set_credentials(username, password);
|
||||
}
|
||||
|
||||
let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
|
||||
client.subscribe(&format!("chat/{}", app.current_room), QoS::AtMostOnce).await.unwrap();
|
||||
|
||||
Reference in New Issue
Block a user