mirror of
https://github.com/csehviktor/status-monitor.git
synced 2025-08-08 18:06:14 +02:00
improve mqtt
This commit is contained in:
47
agent/src/mqtt.rs
Normal file
47
agent/src/mqtt.rs
Normal 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(())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user