Store actual result
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

Use atomics to store the actual result.
This commit is contained in:
finga 2022-04-23 20:50:44 +02:00
parent e820273c89
commit 52f1452613

View file

@ -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<Metrics>) -> 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(())
}