Files
status-monitor/common/src/lib.rs
2025-07-08 14:47:52 +02:00

45 lines
1.0 KiB
Rust

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Error;
use crate::metrics::Metrics;
pub mod metrics;
pub const MQTT_TOPIC: &str = "system/metrics";
pub const MQTT_SEND_INTERVAL: u64 = 5;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatusMessage {
pub agent: String,
pub metrics: Metrics,
pub timestamp: DateTime<Utc>,
}
impl<'a> StatusMessage {
pub fn new(agent: &'a str, metrics: Metrics) -> Self {
Self {
agent: agent.to_string(),
metrics,
timestamp: Utc::now(),
}
}
pub fn to_string(&self) -> Result<String, Error> {
serde_json::to_string_pretty(&self)
}
}
impl<'a> TryFrom<&'a [u8]> for StatusMessage {
type Error = serde_json::Error;
fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
serde_json::from_slice(value)
}
}
impl From<StatusMessage> for String {
fn from(msg: StatusMessage) -> String {
serde_json::to_string(&msg).unwrap_or_else(|_| String::new())
}
}