diff --git a/Cargo.toml b/Cargo.toml index 70f4958..bf23c38 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,3 @@ serde_json = "1.0.140" thiserror = "2.0.12" tokio = { version = "1.44.1", features = ["full"] } toml = "0.8.20" - -[[bin]] -name="cli" -path="src/bin/cli.rs" \ No newline at end of file diff --git a/README.md b/README.md index 09e892f..d4dd52e 100644 --- a/README.md +++ b/README.md @@ -1,57 +1,7 @@ -# POWER -this repository provides both -1. modular library for interfacing with powered devices -2. CLI application which uses this library to control powered devices from the command line +CLI application for interfacing with powered devices. -**IMPORTANT:** this is a work in progress, and the API will likely have breaking changes as it grows. ADDITIONALLY, currently there is only trait implementations for Tasmota outlets, however other devices can be supported by implementing these traits for your device-specific API. You can use `tasmota.rs` as an example of how to do this. once implemented, your devices will be compatible with this library. +in this case, tasmota smart outlets being used on the hydroponics project -# CLI -## BUILDING THE CLI -with a working rust toolchain on your machine, run the following: -`cargo build --release --bin cli` - -once built, the CLI binary will be available at the following path: -`/target/release/cli` - -## CONFIGURING THE SYSTEM DESCRIPTION FILE -a `system` consists of a number of `components` which are defined in a configuration `toml` file. - -an example, `config.toml` has been provided. - -each entry corresponds to a `component` and provides a `name` as well as the `target` IP address of the (in this case tasmota) power device. - -```toml -components = [ - {name="OUTLET 1", target="OUTLET_1_IP"}, # OUTLET 1 - {name="OUTLET 2", target="OUTLET_2_IP"}, # OUTLET 2 - {name="OUTLET 3", target="OUTLET_3_IP"}, # OUTLET 3 ... -] -``` - -## RUNNING THE CLI -the CLI takes as an argument the `config-file` (described above) as well as a subcommand. - -more usage information about the CLI can be obtained by running - -`./cli help` - -## COMMANDS -### MONITOR -the `monitor` command will output the power consumption of the components listed in the config file. - -example: -```log -OUTLET_1 -* POWER: 31W ------------------- -OUTLET_2 -* POWER: 0W ------------------- -OUTLET_3 -* POWER: 0W ------------------- -``` - -### SET -the `set` command allows a user to set the power state of a `component` at a given `index`. `component`s are indexed starting at 0 in the order they are defined in your configuration file. \ No newline at end of file +TODO: +* add reqwest support to access the tasmota outlets \ No newline at end of file diff --git a/config.toml b/config.toml index a3605da..43620fe 100644 --- a/config.toml +++ b/config.toml @@ -1,5 +1,3 @@ -components = [ - {name="OUTLET 1", target="OUTLET_1_IP"}, # OUTLET 1 - {name="OUTLET 2", target="OUTLET_2_IP"}, # OUTLET 2 - {name="OUTLET 3", target="OUTLET_3_IP"}, # OUTLET 3 ... -] \ No newline at end of file +target = [ + "YOUR IP HERE" + ] \ No newline at end of file diff --git a/src/control.rs b/src/control.rs deleted file mode 100644 index 05f44a9..0000000 --- a/src/control.rs +++ /dev/null @@ -1,8 +0,0 @@ -use crate::types::{Error, PowerState}; - -pub trait Control { - fn set_power( - &self, - state: PowerState, - ) -> impl std::future::Future> + Send; -} diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100644 index aa9de85..0000000 --- a/src/lib.rs +++ /dev/null @@ -1,5 +0,0 @@ -pub mod control; -pub mod monitor; -pub mod system; -pub mod tasmota; -pub mod types; diff --git a/src/bin/cli.rs b/src/main.rs similarity index 54% rename from src/bin/cli.rs rename to src/main.rs index 533519b..73f1b28 100644 --- a/src/bin/cli.rs +++ b/src/main.rs @@ -1,31 +1,23 @@ use clap::{Parser, Subcommand}; +use monitor::Monitor; -#[derive(Parser)] -pub struct PowerCommand { - index: usize, - #[command(subcommand)] - state: power::types::PowerState, -} +mod monitor; +mod tasmota; #[derive(Subcommand)] pub enum Commands { Monitor, - Set(PowerCommand), } impl Commands { pub async fn execute(self, config_file: &str) { - let s = power::system::System::new_from_file(config_file).unwrap(); - let handle = match self { - Self::Monitor => tokio::spawn(async move { - s.try_get_power().await.unwrap(); - }), - Self::Set(command) => { - // let c = Controller::new_from_file(config_file).unwrap(); + Self::Monitor => { + let m = Monitor::new_from_file(config_file).unwrap(); tokio::spawn(async move { - s.try_set_power(command.index, command.state).await.unwrap(); + m.get_power().await.unwrap(); }) + // println!("[TODO] Power: ----W") } }; handle.await.unwrap(); diff --git a/src/monitor.rs b/src/monitor.rs index ce999ff..dec5afd 100644 --- a/src/monitor.rs +++ b/src/monitor.rs @@ -1,5 +1,68 @@ -use crate::types::Error; +use crate::tasmota::{PowerStatusData, StatusResponse, TasmotaInterface, TasmotaInterfaceConfig}; +use reqwest::Client; +use serde::Deserialize; +use std::fs; +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum Error { + #[error("io error")] + IoError(#[from] std::io::Error), + #[error("toml parsing error")] + ParseError(#[from] toml::de::Error), + #[error("request error")] + RequestError(#[from] reqwest::Error), + #[error("JSON Parse error")] + JsonParseError(#[from] serde_json::Error), +} pub trait Monitoring { - fn get_power(&self) -> impl std::future::Future> + Send; + async fn get_power(&self) -> Result; +} + +#[derive(Deserialize)] +pub struct MonitorConfig { + targets: Vec, +} +impl MonitorConfig { + fn print(&self) { + for t in &self.targets { + t.print(); + } + } +} + +pub struct Monitor { + targets: Vec, + client: Client, +} + +impl Monitor { + pub fn new_from_file(config_file: &str) -> Result { + let config_str = fs::read_to_string(config_file)?; + let config: MonitorConfig = toml::from_str(&config_str)?; + config.print(); + + Ok(Self { + targets: Monitor::load_targets(&config.targets), + client: Client::new(), + }) + } + + pub fn load_targets(targets: &Vec) -> Vec { + let mut v = Vec::new(); + for target in targets { + v.push(TasmotaInterface::new(target.clone())); + } + v + } + + pub async fn get_power(&self) -> Result<(), Error> { + for target in &self.targets { + if let Ok(res) = target.get_power().await { + println!("POWER: {}W", res); + } + } + Ok(()) + } } diff --git a/src/system.rs b/src/system.rs deleted file mode 100644 index e917d22..0000000 --- a/src/system.rs +++ /dev/null @@ -1,58 +0,0 @@ -use crate::control::Control; -use crate::monitor::Monitoring; -use crate::tasmota::{TasmotaInterface, TasmotaInterfaceConfig}; -use crate::types::{self, Error}; -use serde::Deserialize; -use std::fs; - -#[derive(Deserialize)] -pub struct SystemConfig { - components: Vec, -} -impl SystemConfig { - #[allow(unused)] - fn print(&self) { - for t in &self.components { - t.print(); - } - } -} - -pub struct System { - components: Vec, -} - -impl System { - pub fn new_from_file(config_file: &str) -> Result { - let config_str = fs::read_to_string(config_file)?; - let config: SystemConfig = toml::from_str(&config_str)?; - Ok(Self { - components: System::load_targets(&config.components), - }) - } - - pub fn load_targets(targets: &Vec) -> Vec { - let mut v = Vec::new(); - for target in targets { - v.push(TasmotaInterface::new(target.clone())); - } - v - } - - pub async fn try_get_power(&self) -> Result<(), Error> { - for component in &self.components { - if let Ok(res) = component.get_power().await { - component.print(); - println!("* POWER: {}W", res); - println!("------------------") - } - } - Ok(()) - } - - pub async fn try_set_power(&self, index: usize, state: types::PowerState) -> Result<(), Error> { - //TODO: check bounds - self.components[index].set_power(state).await?; - Ok(()) - } -} diff --git a/src/tasmota.rs b/src/tasmota.rs index b8bae8a..dcc010b 100644 --- a/src/tasmota.rs +++ b/src/tasmota.rs @@ -1,11 +1,8 @@ use reqwest::Client; use serde::Deserialize; -use crate::{ - control::Control, - monitor::Monitoring, - types::{Error, PowerState}, -}; +use crate::monitor::Error; +use crate::monitor::Monitoring; #[derive(Deserialize)] pub struct EnergyData { @@ -29,13 +26,11 @@ pub struct StatusResponse { #[derive(Deserialize, Clone)] pub struct TasmotaInterfaceConfig { - name: String, target: String, } impl TasmotaInterfaceConfig { pub fn print(&self) { - println!("{}", self.name); println!("* {}", self.target); } } @@ -52,9 +47,6 @@ impl TasmotaInterface { client: Client::new(), } } - pub fn print(&self) { - println!("{}", self.config.name) - } } // Monitoring @@ -72,23 +64,3 @@ impl Monitoring for TasmotaInterface { Ok(data.status.energy.power) } } - -impl Control for TasmotaInterface { - async fn set_power(&self, state: PowerState) -> Result<(), Error> { - let cmd = match state { - PowerState::Off => "OFF", - PowerState::On => "ON", - }; - let _res = self - .client - .get(format!( - "http://{}/cm?cmnd=Power%20{}", - &self.config.target, cmd - )) - .send() - .await? - .text() - .await?; - Ok(()) - } -} diff --git a/src/types.rs b/src/types.rs deleted file mode 100644 index d25711e..0000000 --- a/src/types.rs +++ /dev/null @@ -1,21 +0,0 @@ -use clap::Parser; -use serde::{Deserialize, Serialize}; -use thiserror::Error; - -#[derive(Error, Debug)] -pub enum Error { - #[error("io error")] - IoError(#[from] std::io::Error), - #[error("toml parsing error")] - ParseError(#[from] toml::de::Error), - #[error("request error")] - RequestError(#[from] reqwest::Error), - #[error("JSON Parse error")] - JsonParseError(#[from] serde_json::Error), -} - -#[derive(Serialize, Deserialize, Parser, Clone)] -pub enum PowerState { - Off, - On, -}