Add env feature for clap, add command to set volume.

This commit is contained in:
Erwin Boskma 2022-03-21 21:57:19 +01:00
parent 338ebc36b1
commit 4a37e9ff9b
Signed by: erwin
GPG key ID: 270B20D17394F7E5
2 changed files with 18 additions and 6 deletions

View file

@ -7,7 +7,7 @@ edition = "2021"
[dependencies]
anyhow = "1.0.56"
clap = { version = "3.1.6", features = ["cargo", "unicode", "derive"] }
clap = { version = "3.1.6", features = ["cargo", "unicode", "derive", "env"] }
color-eyre = "0.6.1"
html-escape = "0.2.11"
reqwest = { version = "0.11.10", features = ["blocking", "json"] }

View file

@ -5,7 +5,7 @@ use clap::Parser;
use color_eyre::{eyre::WrapErr, Result};
use serde_json::json;
use std::fmt::Display;
use tracing::debug;
use tracing::{debug, trace};
use tracing_subscriber::EnvFilter;
/// Bert
@ -21,11 +21,11 @@ struct Opts {
entity: String,
/// API token
#[clap(short, long)]
#[clap(short, long, env)]
token: Option<String>,
/// File with the API token
#[clap(long)]
#[clap(long, env)]
token_file: Option<PathBuf>,
/// Use HTTP instead of HTTPS
@ -47,6 +47,8 @@ enum Command {
VolumeUp,
/// Lower volume
VolumeDown,
/// Set volume to value
Volume { volume: u8 },
}
impl Display for Command {
@ -55,6 +57,7 @@ impl Display for Command {
Command::PlayPause => write!(f, "Play/Pause"),
Command::VolumeUp => write!(f, "Volume Up"),
Command::VolumeDown => write!(f, "Volume Down"),
Command::Volume { volume } => write!(f, "Volume {volume}"),
}
}
}
@ -91,9 +94,11 @@ fn main() -> Result<()> {
if let Some(token) = token {
if let Some(cmd) = cmd {
debug!("Calling service '{cmd}' on entity '{entity}'");
call_service(cmd, host, entity, insecure, token)
.wrap_err_with(|| format!("Unable to execute command {cmd}"))?;
} else {
debug!("Retrieving state of '{entity}' on '{host}'");
get_now_playing(host, entity, insecure, token)
.wrap_err("Unable to retrieve now playing info")?;
}
@ -131,7 +136,7 @@ fn get_now_playing(host: String, entity: String, insecure: bool, token: String)
.send()?
.json::<serde_json::Value>()?;
debug!("Response: {:#?}", response);
trace!("Response: {:#?}", response);
if response["state"] == "playing" {
let attributes = &response["attributes"];
@ -180,6 +185,7 @@ fn call_service(
Command::PlayPause => "media_play_pause",
Command::VolumeUp => "volume_up",
Command::VolumeDown => "volume_down",
Command::Volume { .. } => "volume_set",
};
let url = format!(
@ -189,7 +195,13 @@ fn call_service(
cmd
);
let body = json!({ "entity_id": entity }).to_string();
let body = match command {
Command::Volume { volume } => {
json!({ "entity_id": entity, "volume_level": volume.clamp(0, 100) as f32 / 100. })
.to_string()
}
_ => json!({ "entity_id": entity }).to_string(),
};
let client = reqwest::blocking::Client::new();
let response = client