From 52f1452613e97cca986105de836e08c9266f9d95 Mon Sep 17 00:00:00 2001 From: finga Date: Sat, 23 Apr 2022 20:50:44 +0200 Subject: [PATCH] Store actual result Use atomics to store the actual result. --- src/main.rs | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index 66f3930..b81c7f4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,13 +3,29 @@ use log::{debug, trace}; use std::{ io::{BufRead, BufReader}, str::FromStr, + sync::{ + atomic::{AtomicU32, AtomicUsize, Ordering}, + Arc, + }, time::Duration, }; use tokio::{spawn, task::JoinHandle, try_join}; +#[derive(Default)] +struct AtomicF32 { + storage: AtomicU32, +} + +impl AtomicF32 { + fn store(&self, value: f32, ordering: Ordering) { + let as_u32 = value.to_bits(); + self.storage.store(as_u32, ordering); + } +} + #[derive(Debug)] enum Speed { - Slow, + Slow = 0, Fast, Inst, } @@ -27,6 +43,14 @@ impl FromStr for Speed { } } +#[derive(Default)] +struct Metrics { + cps: AtomicUsize, + cpm: AtomicUsize, + radiation: AtomicF32, + mode: AtomicUsize, +} + fn parse(input: &str) -> Result<(usize, usize, f32, Speed)> { let input = input .replace("CPS, ", "") @@ -52,7 +76,7 @@ fn parse(input: &str) -> Result<(usize, usize, f32, Speed)> { } #[allow(clippy::unused_async, clippy::similar_names)] -async fn listen_serial() -> Result<()> { +async fn listen_serial(metrics: Arc) -> Result<()> { let port_name = "/dev/serial0"; let baud_rate = 9600; @@ -66,7 +90,12 @@ async fn listen_serial() -> Result<()> { port.read_line(&mut line)?; let line = line.trim(); debug!("Reading line from serial port: {}", line); - let (_cps, _cpm, _radiation, _mode) = parse(line)?; + let (cps, cpm, radiation, mode) = parse(line)?; + + metrics.cps.store(cps, Ordering::Relaxed); + metrics.cpm.store(cpm, Ordering::Relaxed); + metrics.radiation.store(radiation, Ordering::Relaxed); + metrics.mode.store(mode as usize, Ordering::Relaxed); } } @@ -84,8 +113,9 @@ where #[tokio::main] async fn main() -> Result<()> { env_logger::init(); + let metrics = Arc::new(Metrics::default()); - try_join!(flatten(spawn(listen_serial())))?; + try_join!(flatten(spawn(listen_serial(Arc::clone(&metrics)))))?; Ok(()) }