Merge pull request 'set by name, not by index' (#1) from seb/power:set-by-name into main

Reviewed-on: #1
This commit is contained in:
sigil-03 2025-05-14 21:43:37 -06:00
commit 7fa7fad3a8
4 changed files with 18 additions and 11 deletions

View file

@ -2,7 +2,7 @@ use clap::{Parser, Subcommand};
#[derive(Parser)]
pub struct PowerCommand {
index: usize,
name: String,
#[command(subcommand)]
state: power::types::PowerState,
}
@ -23,9 +23,9 @@ impl Commands {
}),
Self::Set(command) => {
// let c = Controller::new_from_file(config_file).unwrap();
tokio::spawn(async move {
s.try_set_power(command.index, command.state).await.unwrap();
})
tokio::spawn(
async move { s.try_set_power(&command.name, command.state).await.unwrap() },
)
}
};
handle.await.unwrap();

View file

@ -50,9 +50,14 @@ impl System {
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(())
pub async fn try_set_power(&self, name: &str, state: types::PowerState) -> Result<(), Error> {
match self
.components
.iter()
.find(|&component| component.config.name == name)
{
Some(component) => component.set_power(state).await,
None => Err(Error::DeviceNameNotFound(String::from(name))),
}
}
}

View file

@ -29,8 +29,8 @@ pub struct StatusResponse {
#[derive(Deserialize, Clone)]
pub struct TasmotaInterfaceConfig {
name: String,
target: String,
pub name: String,
pub target: String,
}
impl TasmotaInterfaceConfig {
@ -41,7 +41,7 @@ impl TasmotaInterfaceConfig {
}
pub struct TasmotaInterface {
config: TasmotaInterfaceConfig,
pub config: TasmotaInterfaceConfig,
client: Client,
}

View file

@ -12,6 +12,8 @@ pub enum Error {
RequestError(#[from] reqwest::Error),
#[error("JSON Parse error")]
JsonParseError(#[from] serde_json::Error),
#[error("device {0} not found")]
DeviceNameNotFound(String),
}
#[derive(Serialize, Deserialize, Parser, Clone)]