Make periodic refreshs

This commit is contained in:
2024-04-20 17:55:27 +02:00
parent bd4d8e5ba9
commit 7e0d11815a
3 changed files with 43 additions and 20 deletions

22
Cargo.lock generated
View File

@@ -208,6 +208,7 @@ dependencies = [
"serialport",
"strum",
"tokio",
"tokio-scoped",
"tokio_schedule",
]
@@ -879,6 +880,27 @@ dependencies = [
"syn",
]
[[package]]
name = "tokio-scoped"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4beb8ba13bc53ac53ce1d52b42f02e5d8060f0f42138862869beb769722b256"
dependencies = [
"tokio",
"tokio-stream",
]
[[package]]
name = "tokio-stream"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "267ac89e0bec6e691e5813911606935d77c476ff49024f98abcea3e7b15e37af"
dependencies = [
"futures-core",
"pin-project-lite",
"tokio",
]
[[package]]
name = "tokio_schedule"
version = "0.3.1"

View File

@@ -15,4 +15,5 @@ log = "0.4.21"
serialport = "4.3.0"
strum = { version = "0.26.2", features = ["derive"] }
tokio = { version = "1.37.0", features = ["full"] }
tokio-scoped = "0.2.0"
tokio_schedule = "0.3.1"

View File

@@ -107,23 +107,20 @@ where
async fn main() {
let state = Arc::new(Mutex::new(None::<Status>));
// let periodic_state = Arc::clone(&state);
// let periodic_refresh = every(5).minutes().perform(|| async {
// log::info!("Periodic data fetch");
// let mut lock = periodic_state.lock().unwrap();
// if let Ok(status) = get_status_from_device() {
// *lock = Some(status.clone());
// }
// });
// tokio::spawn(async move {
// loop {
// log::info!("Periodic data fetch");
// let mut lock = periodic_state.lock().unwrap();
// if let Ok(status) = get_status_from_device() {
// *lock = Some(status.clone());
// }
// }
// });
let periodic_state = Arc::clone(&state);
tokio::spawn(async move {
loop {
log::info!("Periodic data fetch");
{
let mut lock = periodic_state.lock().unwrap();
if let Ok(status) = get_status_from_device() {
*lock = Some(status.clone());
}
}
tokio::time::sleep(tokio::time::Duration::from_secs(5 * 60)).await;
}
});
let app = Router::new().route("/", get(handler)).with_state(state);
@@ -137,12 +134,15 @@ async fn handler(
log::info!("Fetch new data");
let mut lock = state.lock().unwrap();
let status = if let Ok(status) = get_status_from_device() {
let fetched_status = get_status_from_device();
let status = if let Ok(status) = fetched_status {
*lock = Some(status.clone());
status
} else {
lock.clone().context("No device state yet fetched")?
lock.clone()
.context(fetched_status.unwrap_err())
.context("Device state not yet fetched")?
};
Ok(Html(format!(
@@ -177,7 +177,7 @@ async fn handler(
fn get_status_from_device() -> anyhow::Result<Status> {
let data = read_device().context("Could not retrieve device data")?;
let data_string = std::str::from_utf8(&data).unwrap();
let data_string = std::str::from_utf8(&data)?;
let status_map = StatusTag::iter()
.zip(data_string.split('\t'))