implement reconnecting

This commit is contained in:
csehviktor
2025-07-15 03:35:21 +02:00
parent f3b3044cce
commit 20f4c1f521
2 changed files with 22 additions and 4 deletions

View File

@@ -20,6 +20,13 @@ struct Args {
#[arg(long, default_value_t = 1883)] #[arg(long, default_value_t = 1883)]
port: u16, port: u16,
#[arg(long, default_value_t = 6)]
reconnect_after: u8,
}
async fn connect(args: &Args) -> MqttHandle {
MqttHandle::create(args.name.clone(), args.host.clone(), args.port).await
} }
#[tokio::main] #[tokio::main]
@@ -28,12 +35,24 @@ async fn main() -> anyhow::Result<()> {
println!("running agent: {:?}", args); println!("running agent: {:?}", args);
let client = MqttHandle::create(args.name, args.host, args.port).await; let mut client = connect(&args).await;
let mut collector = Collector::new(); let mut collector = Collector::new();
let mut consecutive_failures = 0;
loop { loop {
let metrics = collector.collect_all(); let metrics = collector.collect_all();
client.send_metrics(metrics).await?;
match client.send_metrics(metrics).await {
Ok(_) => consecutive_failures = 0,
Err(_) => {
consecutive_failures += 1;
if consecutive_failures >= args.reconnect_after {
client = connect(&args).await;
consecutive_failures = 0;
}
}
}
thread::sleep(Duration::from_secs(MQTT_SEND_INTERVAL)); thread::sleep(Duration::from_secs(MQTT_SEND_INTERVAL));
} }

View File

@@ -37,8 +37,7 @@ impl MqttHandle {
self.client self.client
.publish(MQTT_TOPIC, QoS::AtLeastOnce, false, message.as_bytes()) .publish(MQTT_TOPIC, QoS::AtLeastOnce, false, message.as_bytes())
.await .await?;
.expect("Failed to publish metrics");
Ok(()) Ok(())
} }