Browse Source

add lock_state() fn

main
Nareshkumar Rao 7 months ago
parent
commit
27be36cdbf
  1. 12
      src/cli_mode.rs
  2. 6
      src/control/light.rs
  3. 6
      src/control/soil.rs
  4. 6
      src/control/temperature.rs
  5. 6
      src/data_logging.rs
  6. 4
      src/error.rs
  7. 10
      src/server.rs
  8. 12
      src/state.rs

12
src/cli_mode.rs

@ -4,10 +4,10 @@ use rustyline::{config::Configurer, error::ReadlineError, history::FileHistory};
use crate::{ use crate::{
actuators, actuators,
error::{lock_err, GenericResult},
error::GenericResult,
io::{self, get_input_voltage}, io::{self, get_input_voltage},
sensors, sensors,
state::ProgramStateShared,
state::{lock_state, ProgramStateShared},
}; };
struct LoopFlags { struct LoopFlags {
@ -31,7 +31,7 @@ fn process_input(input: String, program_state: ProgramStateShared) -> GenericRes
} }
fn command_pump(args: &[&str], program_state: ProgramStateShared) -> GenericResult<()> { fn command_pump(args: &[&str], program_state: ProgramStateShared) -> GenericResult<()> {
let mut program_state = program_state.lock().map_err(lock_err)?;
let mut program_state = lock_state(&program_state)?;
let use_grams = args let use_grams = args
.get(2) .get(2)
@ -59,7 +59,7 @@ fn command_temp(args: &[&str], program_state: ProgramStateShared) -> GenericResu
.map(|arg| matches!(*arg, "loop")) .map(|arg| matches!(*arg, "loop"))
.unwrap_or(false); .unwrap_or(false);
loop { loop {
let program_state = program_state.lock().map_err(lock_err)?;
let program_state = lock_state(&program_state)?;
let temperature = sensors::get_temperature(&program_state.config)?; let temperature = sensors::get_temperature(&program_state.config)?;
println!("Temperature: {}C", temperature); println!("Temperature: {}C", temperature);
if !show_loop { if !show_loop {
@ -77,7 +77,7 @@ fn command_soil(args: &[&str], program_state: ProgramStateShared) -> GenericResu
.unwrap_or(false); .unwrap_or(false);
loop { loop {
let program_state = program_state.lock().map_err(lock_err)?;
let program_state = lock_state(&program_state)?;
let humidity = sensors::get_soil_moisture(&program_state.config)?; let humidity = sensors::get_soil_moisture(&program_state.config)?;
println!("Soil humidity: {}", humidity); println!("Soil humidity: {}", humidity);
if !show_loop { if !show_loop {
@ -90,7 +90,7 @@ fn command_soil(args: &[&str], program_state: ProgramStateShared) -> GenericResu
} }
fn command_rel(args: &[&str], program_state: ProgramStateShared) -> GenericResult<()> { fn command_rel(args: &[&str], program_state: ProgramStateShared) -> GenericResult<()> {
let mut program_state = program_state.lock().map_err(lock_err)?;
let mut program_state = lock_state(&program_state)?;
let pin = args let pin = args
.get(1) .get(1)

6
src/control/light.rs

@ -4,13 +4,13 @@ use chrono::{Local, Timelike};
use crate::{ use crate::{
actuators, actuators,
error::{lock_err, GenericResult},
state::ProgramStateShared,
error::GenericResult,
state::{lock_state, ProgramStateShared},
}; };
fn light_control(program_state: ProgramStateShared) -> GenericResult<()> { fn light_control(program_state: ProgramStateShared) -> GenericResult<()> {
let program_state = program_state.clone(); let program_state = program_state.clone();
let mut program_state = program_state.lock().map_err(lock_err)?;
let mut program_state = lock_state(&program_state)?;
let local = Local::now(); let local = Local::now();
let hour = local.time().hour(); let hour = local.time().hour();
if hour as u64 <= program_state.config.controller_settings.sunlight_hours { if hour as u64 <= program_state.config.controller_settings.sunlight_hours {

6
src/control/soil.rs

@ -3,8 +3,8 @@ use std::time::Duration;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use crate::{ use crate::{
error::{lock_err, GenericResult},
state::ProgramStateShared,
error::GenericResult,
state::{lock_state, ProgramStateShared},
}; };
pub async fn soil_moisture_control_loop(program_state: ProgramStateShared) { pub async fn soil_moisture_control_loop(program_state: ProgramStateShared) {
@ -20,7 +20,7 @@ pub async fn soil_moisture_control_loop(program_state: ProgramStateShared) {
} }
fn soil_moisture_control(program_state: ProgramStateShared) -> GenericResult<()> { fn soil_moisture_control(program_state: ProgramStateShared) -> GenericResult<()> {
let program_state = program_state.lock().map_err(lock_err)?;
let program_state = lock_state(&program_state)?;
let config = &program_state.config.controller_settings; let config = &program_state.config.controller_settings;
let history = &program_state.history.watering_records; let history = &program_state.history.watering_records;

6
src/control/temperature.rs

@ -2,13 +2,13 @@ use std::time::Duration;
use crate::{ use crate::{
actuators, actuators,
error::{lock_err, GenericResult},
error::GenericResult,
sensors, sensors,
state::ProgramStateShared,
state::{lock_state, ProgramStateShared},
}; };
fn temperature_control(program_state: ProgramStateShared) -> GenericResult<()> { fn temperature_control(program_state: ProgramStateShared) -> GenericResult<()> {
let mut program_state = program_state.lock().map_err(lock_err)?;
let mut program_state = lock_state(&program_state)?;
let config = &program_state.config.controller_settings; let config = &program_state.config.controller_settings;
let current_temperature = sensors::get_temperature(&program_state.config)?; let current_temperature = sensors::get_temperature(&program_state.config)?;

6
src/data_logging.rs

@ -2,9 +2,9 @@ use chrono::Utc;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{ use crate::{
error::{lock_err, GenericResult},
error::GenericResult,
sensors, sensors,
state::ProgramStateShared,
state::{lock_state, ProgramStateShared},
}; };
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@ -32,7 +32,7 @@ impl DataRecords {
Ok(DataRecords { records: result }) Ok(DataRecords { records: result })
} }
pub fn push(program_state: ProgramStateShared) -> GenericResult<()> { pub fn push(program_state: ProgramStateShared) -> GenericResult<()> {
let program_state = program_state.lock().map_err(lock_err)?;
let program_state = lock_state(&program_state)?;
let config = &program_state.config; let config = &program_state.config;
let record = DataRecord { let record = DataRecord {
timestamp: Utc::now().timestamp(), timestamp: Utc::now().timestamp(),

4
src/error.rs

@ -1,7 +1,3 @@
use std::error::Error; use std::error::Error;
pub type GenericResult<T> = Result<T, Box<dyn Error>>; pub type GenericResult<T> = Result<T, Box<dyn Error>>;
pub fn lock_err<T: std::fmt::Display>(e: T) -> String {
format!("{}", e)
}

10
src/server.rs

@ -10,10 +10,10 @@ use tower_http::cors::{Any, CorsLayer};
use crate::{ use crate::{
actuators, actuators,
error::{lock_err, GenericResult},
error::GenericResult,
io::RelaySwitchState, io::RelaySwitchState,
sensors, sensors,
state::ProgramStateShared,
state::{lock_state, ProgramStateShared},
}; };
pub async fn run_server(program_state: ProgramStateShared) { pub async fn run_server(program_state: ProgramStateShared) {
@ -40,7 +40,7 @@ async fn pump_handler(
State(program_state): State<ProgramStateShared>, State(program_state): State<ProgramStateShared>,
) -> impl IntoResponse { ) -> impl IntoResponse {
let exec = || -> GenericResult<()> { let exec = || -> GenericResult<()> {
let mut program_state = program_state.lock().map_err(lock_err)?;
let mut program_state = lock_state(&program_state)?;
actuators::pump_water(quantity, &mut program_state)?; actuators::pump_water(quantity, &mut program_state)?;
Ok(()) Ok(())
}; };
@ -55,7 +55,7 @@ async fn switch_handler(
State(program_state): State<ProgramStateShared>, State(program_state): State<ProgramStateShared>,
) -> impl IntoResponse { ) -> impl IntoResponse {
let exec = || -> GenericResult<()> { let exec = || -> GenericResult<()> {
let mut program_state = program_state.lock().map_err(lock_err)?;
let mut program_state = lock_state(&program_state)?;
match device.as_str() { match device.as_str() {
"lights" => actuators::switch_lights(state, &mut program_state)?, "lights" => actuators::switch_lights(state, &mut program_state)?,
"fan" => actuators::switch_fan(state, &mut program_state)?, "fan" => actuators::switch_fan(state, &mut program_state)?,
@ -81,7 +81,7 @@ struct Info {
async fn info_handler( async fn info_handler(
State(program_state): State<ProgramStateShared>, State(program_state): State<ProgramStateShared>,
) -> Result<Json<Info>, String> { ) -> Result<Json<Info>, String> {
let mut program_state = program_state.lock().map_err(lock_err)?;
let mut program_state = lock_state(&program_state).map_err(|e| e.to_string())?;
let temperature = sensors::get_temperature(&program_state.config).map_err(|e| e.to_string())?; let temperature = sensors::get_temperature(&program_state.config).map_err(|e| e.to_string())?;
let soil_moisture = let soil_moisture =
sensors::get_soil_moisture(&program_state.config).map_err(|e| e.to_string())?; sensors::get_soil_moisture(&program_state.config).map_err(|e| e.to_string())?;

12
src/state.rs

@ -1,4 +1,4 @@
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, MutexGuard};
use crate::{config::Configuration, error::GenericResult, history::History, io}; use crate::{config::Configuration, error::GenericResult, history::History, io};
@ -9,6 +9,16 @@ pub struct ProgramState {
pub history: History, pub history: History,
} }
fn lock_err<T: std::fmt::Display>(e: T) -> String {
format!("{}", e)
}
pub fn lock_state(
program_state: &ProgramStateShared,
) -> GenericResult<MutexGuard<'_, ProgramState>> {
Ok(program_state.lock().map_err(lock_err)?)
}
pub fn init_state(config: Configuration) -> GenericResult<ProgramStateShared> { pub fn init_state(config: Configuration) -> GenericResult<ProgramStateShared> {
let relay = io::Relay::new(&config)?; let relay = io::Relay::new(&config)?;
let history = History::load().unwrap_or_default(); let history = History::load().unwrap_or_default();

Loading…
Cancel
Save