Skip to content

Commit

Permalink
Improve logging output
Browse files Browse the repository at this point in the history
  • Loading branch information
koarlchen committed Oct 6, 2024
1 parent 945557b commit 0182f08
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 26 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ The configuration takes place within the file `config.json`:

The template for the Space API JSON document is defined within the file `status.json`.

By default, the app sets the log level to `info`.
You may adjust it to your needs by using the environment variable `RUST_LOG`.

## Build

Expand Down
16 changes: 10 additions & 6 deletions src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ struct QueryResults {
struct QueryResult {
#[allow(dead_code)]
pub statement_id: u64,
pub series: Vec<QuerySeries>,
pub series: Option<Vec<QuerySeries>>,
}

#[derive(Deserialize, Clone)]
Expand Down Expand Up @@ -110,24 +110,28 @@ impl Database {
.await
.map_err(|e| StatusError::Database(e.to_string()))?;

let results: QueryResults =
serde_json::from_str(&results_raw).map_err(|e| StatusError::Database(e.to_string()))?;
let results: QueryResults = serde_json::from_str(&results_raw)
.map_err(|e| StatusError::Database(format!("serde '{}'", e)))?;

let values = results
.results
.first()
.ok_or(StatusError::Database(
"Unexpected response: no results".into(),
"unexpected response, no results".into(),
))?
.series
.as_ref()
.ok_or(StatusError::Database(
"unexpected response, statements result does not contain any data".into(),
))?
.first()
.ok_or(StatusError::Database(
"Unexpected response: no series".into(),
"unexpected response, no series".into(),
))?
.values
.first()
.ok_or(StatusError::Database(
"Unexpected response: no values".into(),
"unexpected response, no values".into(),
))?;

let time: DateTime<Utc> = DateTime::parse_from_rfc3339(&values.0)
Expand Down
8 changes: 4 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ mod template;

#[derive(Error, Debug, PartialEq, Eq)]
pub enum StatusError {
#[error("Failed to interact with database")]
#[error("Failed to interact with database: {0}")]
Database(String),

#[error("Failed to parse template file")]
#[error("Failed to parse template file: {0}")]
Template(String),

#[error("Failed to parse configuration file")]
#[error("Failed to parse configuration file: {0}")]
Configuration(String),

#[error("Failed to start server")]
#[error("Failed to start server: {0}")]
Server(String),
}

Expand Down
58 changes: 42 additions & 16 deletions src/server/routes/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,20 +85,33 @@ async fn get_temperature(
let mut sensors: Vec<sensors::TemperatureSensor> = Vec::new();

for sensor in config.temperature.name.iter() {
if let Ok(temp) = database
match database
.get_temperature(&sensor.id, &config.temperature.unit)
.await
{
if let Some(val) = validate_time(temp, config.temperature.validity) {
sensors.push(sensors::TemperatureSensor {
value: val,
Ok(temp) => match validate_time(&temp, config.temperature.validity) {
Some(value) => sensors.push(sensors::TemperatureSensor {
value: *value,
unit: config.temperature.unit.clone(),
metadata: sensors::SensorMetadataWithLocation {
location: sensor.location.clone(),
..Default::default()
},
});
}
}),
None => log::warn!(
"Latest sensor measurement too old: id='{}' unit='{}' sample_time='{}' validity='{}'",
sensor.id,
config.temperature.unit,
temp.time,
config.temperature.validity
),
},
Err(err) => log::warn!(
"Failed to query temperature: id='{}' unit='{}' ({})",
sensor.id,
config.temperature.unit,
err
),
}
}

Expand All @@ -114,20 +127,33 @@ async fn get_humidity(
let mut sensors: Vec<sensors::HumiditySensor> = Vec::new();

for sensor in config.humidity.name.iter() {
if let Ok(temp) = database
match database
.get_humidity(&sensor.id, &config.humidity.unit)
.await
{
if let Some(val) = validate_time(temp, config.humidity.validity) {
sensors.push(sensors::HumiditySensor {
value: val as f64,
Ok(temp) => match validate_time(&temp, config.humidity.validity) {
Some(value) => sensors.push(sensors::HumiditySensor {
value: *value as f64,
unit: config.humidity.unit.clone(),
metadata: sensors::SensorMetadataWithLocation {
location: sensor.location.clone(),
..Default::default()
},
});
}
}),
None => log::warn!(
"Latest sensor measurement too old: id='{}' unit='{}' sample_time='{}' validity='{}'",
sensor.id,
config.humidity.unit,
temp.time,
config.humidity.validity
),
},
Err(err) => log::warn!(
"Failed to query humidity: id='{}' unit='{}' ({})",
sensor.id,
config.humidity.unit,
err
),
}
}

Expand All @@ -144,18 +170,18 @@ async fn get_door(
.get_door_status(&config.door.name, &config.door.unit)
.await
{
Ok(door) => validate_time(door, config.door.validity).map(|val| spaceapi::State {
open: Some(val),
Ok(door) => validate_time(&door, config.door.validity).map(|val| spaceapi::State {
open: Some(*val),
..Default::default()
}),
Err(_) => None,
}
}

fn validate_time<T>(tv: TimeValue<T>, validity: chrono::TimeDelta) -> Option<T> {
fn validate_time<T>(tv: &TimeValue<T>, validity: chrono::TimeDelta) -> Option<&T> {
let start = chrono::Utc::now() - validity;
if tv.time > start || validity.is_zero() {
Some(tv.value)
Some(&tv.value)
} else {
None
}
Expand Down

0 comments on commit 0182f08

Please sign in to comment.