improve mqtt

This commit is contained in:
csehviktor
2025-07-03 06:09:09 +02:00
parent dbbc673efe
commit 58a4ab9974
4 changed files with 115 additions and 0 deletions

47
agent/src/mqtt.rs Normal file
View File

@@ -0,0 +1,47 @@
use common::{metrics::Metrics, mqtt::{StatusMessage, STATUS_TOPIC}};
use rumqttc::{AsyncClient, MqttOptions, QoS};
use std::time::Duration;
use tokio::task::JoinHandle;
use crate::config::MqttConfig;
pub struct MqttHandle {
pub agent: &'static str,
pub client: AsyncClient,
pub eventloop_handle: JoinHandle<()>,
}
impl MqttHandle {
pub async fn create(cfg: &'static MqttConfig) -> Self {
let mut mqttoptions = MqttOptions::new(&cfg.agent, &cfg.host, cfg.port);
mqttoptions.set_keep_alive(Duration::from_secs(5));
let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
let eventloop_handle = tokio::spawn(async move {
loop {
if let Err(e) = eventloop.poll().await {
eprintln!("event loop error: {:?}", e);
break;
}
}
});
Self {
agent: &cfg.agent,
client,
eventloop_handle
}
}
pub async fn send_metrics(&self, metrics: Metrics) -> anyhow::Result<()> {
let message = StatusMessage::new(&self.agent, metrics).to_string()?;
self.client
.publish(STATUS_TOPIC, QoS::AtLeastOnce, false, message.as_bytes())
.await
.expect("Failed to publish metrics");
Ok(())
}
}