Finish metrics api

This commit is contained in:
Maxime Augier 2024-04-20 09:14:15 +02:00
parent 0c7a3126da
commit 96100bbe0a

View File

@ -1,8 +1,8 @@
use std::{collections::HashMap, sync::Arc, time::{SystemTime, UNIX_EPOCH}}; use std::{collections::HashMap, convert::Infallible, sync::Arc, time::{SystemTime, UNIX_EPOCH}};
use bluer::{self, Adapter, AdapterEvent, Address}; use bluer::{self, Adapter, AdapterEvent, Address};
use anyhow::{Result, Context}; use anyhow::Result;
use futures::{Stream, StreamExt}; use futures::{Stream, StreamExt};
use tokio; use tokio;
use warp::Filter; use warp::Filter;
@ -61,8 +61,8 @@ impl DataStore {
let Data { addr, temperature, humidity, co2 } = data; let Data { addr, temperature, humidity, co2 } = data;
let time = point.duration_since(UNIX_EPOCH).expect("Time went backwards").as_millis(); let time = point.duration_since(UNIX_EPOCH).expect("Time went backwards").as_millis();
scrape += &format!("sensirion_temperature_celsius{{id=\"{addr}\"}} {temperature} {time}\n"); scrape += &format!("sensirion_temperature_celsius{{id=\"{addr}\"}} {temperature} {time}\n");
scrape += &format!("sensirion_humidity_percent{{id=\"{addr}\"}} {temperature} {time}\n"); scrape += &format!("sensirion_humidity_percent{{id=\"{addr}\"}} {humidity} {time}\n");
scrape += &format!("sensirion_co2_ppm{{id=\"{addr}\"}} {temperature} {time}\n"); scrape += &format!("sensirion_co2_ppm{{id=\"{addr}\"}} {co2} {time}\n");
} }
scrape scrape
@ -79,19 +79,21 @@ async fn main() -> Result<()> {
let mut stream = Box::pin(sensor_reports(adapter).await?); let mut stream = Box::pin(sensor_reports(adapter).await?);
let (tx, rx)= tokio::sync::mpsc::channel(256); let sniffer_store = Arc::clone(&store);
tokio::spawn(async move {
let sniffer: tokio::task::JoinHandle<()> = tokio::spawn(async move {
while let Some(data) = stream.next().await { while let Some(data) = stream.next().await {
tx.send(data).await; eprintln!("Data point: {:?}", data);
sniffer_store.lock().await.insert(data, SystemTime::now());
} }
}); });
let filter = let filter =
warp::path!("metrics").map(move || store.lock().unwrap().scrape()) warp::path!("metrics")
.or(warp::path!().map(move || { warp::reply::html("<h1>Sensirion BLE exporter</h1>") })); .map(move || Arc::clone(&store))
.and_then(|store: Arc<Mutex<DataStore>>| async move { Ok::<_,Infallible>(store.lock().await.scrape()) })
.or(warp::path!().map(|| { warp::reply::html("<h1>Sensirion BLE exporter</h1>") }));
Ok(warp::serve(filter).run("127.0.0.1:9177").await) Ok(warp::serve(filter).run(([127,0,0,1],9177)).await)
} }