Request update in a configurable intervall

This commit is contained in:
Ollo
2026-02-28 20:50:01 +01:00
parent cdf92bb56d
commit 98b72736ee

View File

@@ -1,6 +1,6 @@
use clap::Parser;
use rumqttc::{AsyncClient, Event, MqttOptions, Packet, QoS};
use std::time::Duration;
use std::time::{Duration, Instant};
use tokio::time::sleep;
mod straba;
@@ -29,15 +29,24 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
);
mqttoptions.set_keep_alive(Duration::from_secs(30));
let (client, mut eventloop) = AsyncClient::new(mqttoptions, args.interval as usize);
let (client, mut eventloop) = AsyncClient::new(mqttoptions, 100);
loop {
let departure_data = tokio::task::spawn_blocking(|| straba::fetch_data(Some(true)))
let mut last_request = Instant::now();
let interval = Duration::from_millis(args.interval as u64);
let mut departure_data = tokio::task::spawn_blocking(|| straba::fetch_data(Some(true)))
.await
.unwrap();
let mut data_published = false;
loop {
let now = Instant::now();
if now.duration_since(last_request) > interval {
data_published = false;
last_request = Instant::now();
let mut departure_data = tokio::task::spawn_blocking(|| straba::fetch_data(Some(false)))
.await
.unwrap();
if departure_data.failure {
client
.publish("departure/failure", QoS::AtLeastOnce, false, b"Failed to fetch departure data")
@@ -54,13 +63,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("{}", outbound_msg);
println!("{}", inbound_msg);
}
}
match eventloop.poll().await {
Ok(Event::Incoming(Packet::Publish(_))) => {}
Ok(Event::Incoming(Packet::ConnAck(_))) => {
println!("Connected to MQTT broker");
}
Ok(_) => {
if data_published == false
{
client
.publish("departure/station", QoS::AtLeastOnce, false, departure_data.station_name.as_bytes())
.await?;
@@ -77,7 +88,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
client
.publish("departure/inbound/diff", QoS::AtLeastOnce, false, format!("{}", departure_data.inbound_diff))
.await?;
data_published = true;
}
}
Err(e) => {
println!("Error: {:?}", e);