use std::ffi::OsStr;
use anyhow::Context as _;
use clap::builder::{PossibleValue, TypedValueParser};
use clap::{Args, error::ErrorKind};
use serde_json::{Value, json};
use super::Report;
use crate::protocol::{
BulbType, Channel, Dimming, Kelvin, PULSE_SCENE_ID, PulseDelta, Scene, SceneId, Speed,
};
use crate::{Bulb, Pilot, PilotBuilder};
#[derive(Args, Debug, Clone, PartialEq, Eq, Default)]
pub struct StateOptions {
#[command(flatten)]
pub colour: ColourOptions,
#[arg(long, value_name = "N", value_parser = channel)]
#[arg(conflicts_with_all = ["kelvin", "scene"])]
pub cold: Option<Channel>,
#[arg(long, value_name = "N", value_parser = channel)]
#[arg(conflicts_with_all = ["kelvin", "scene"])]
pub warm: Option<Channel>,
#[arg(long, value_name = "SPEED", value_parser = speed)]
pub speed: Option<Speed>,
#[arg(long, short = 'b', value_name = "PERCENT", value_parser = brightness)]
pub brightness: Option<Dimming>,
}
#[derive(Args, Debug, Clone, PartialEq, Eq, Default)]
#[group(multiple = false)]
pub struct ColourOptions {
#[arg(long, value_name = "R,G,B", value_parser = rgb)]
pub rgb: Option<[Channel; 3]>,
#[arg(long, value_name = "H,S,V", value_parser = hsv)]
pub hsv: Option<[Channel; 3]>,
#[arg(long, short = 'k', value_name = "KELVIN", value_parser = kelvin)]
pub kelvin: Option<Kelvin>,
#[arg(long, short = 's', value_name = "SCENE", value_parser = SceneParser)]
pub scene: Option<SceneId>,
}
impl StateOptions {
#[must_use]
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
pub fn require_something(&self, command: &mut clap::Command) -> Result<(), clap::Error> {
if self.is_empty() {
return Err(command.error(
clap::error::ErrorKind::MissingRequiredArgument,
"`set` needs something to set: one of --rgb, --hsv, --cold, --warm, --kelvin, \
--scene, --speed or --brightness",
));
}
Ok(())
}
pub fn require_something_lit(&self, command: &mut clap::Command) -> Result<(), clap::Error> {
let given: Vec<&str> = [
self.colour.rgb.map(|_| "--rgb"),
self.colour.hsv.map(|_| "--hsv"),
self.cold.map(|_| "--cold"),
self.warm.map(|_| "--warm"),
]
.into_iter()
.flatten()
.collect();
let dark = self
.channels()
.is_none_or(|rgb| rgb.iter().all(|c| c.get() == 0))
&& self.cold.is_none_or(|c| c.get() == 0)
&& self.warm.is_none_or(|w| w.get() == 0);
if !given.is_empty() && dark {
return Err(command.error(
clap::error::ErrorKind::InvalidValue,
format!(
"{} asks for no light at all, and the bulb discards a colour with every \
channel at zero: use `off` to turn it off, or --brightness to dim it",
given.join(" and ")
),
));
}
Ok(())
}
fn channels(&self) -> Option<[Channel; 3]> {
self.colour.rgb.or(self.colour.hsv)
}
fn whites(&self) -> impl Iterator<Item = (&'static str, Channel)> {
[("cold", self.cold), ("warm", self.warm)]
.into_iter()
.filter_map(|(label, value)| Some((label, value?)))
}
pub fn apply(&self, mut builder: PilotBuilder) -> PilotBuilder {
if let Some([r, g, b]) = self.channels() {
builder = builder.rgb(r, g, b);
}
if let Some(c) = self.cold {
builder = builder.cold_white(c);
}
if let Some(w) = self.warm {
builder = builder.warm_white(w);
}
if let Some(kelvin) = self.colour.kelvin {
builder = builder.temp(kelvin);
}
if let Some(id) = self.colour.scene {
builder = builder.scene(id);
if self.speed.is_some() && !id.takes_speed() {
let name = id.scene().map_or("that scene", Scene::name);
tracing::warn!("{name} has no adjustable speed; --speed will be ignored");
}
}
if let Some(speed) = self.speed {
builder = builder.speed(speed);
}
if let Some(brightness) = self.brightness {
builder = builder.dimming(brightness);
}
builder
}
pub fn check(&self, bulb_type: &BulbType) -> anyhow::Result<()> {
let features = bulb_type.features;
let refuse = |what: &str| -> anyhow::Error {
anyhow::anyhow!("{}: it cannot {what}", describe(bulb_type))
};
if self.channels().is_some() && !features.color {
return Err(refuse("show a colour"));
}
if self.whites().next().is_some() && !features.color {
return Err(refuse("be given raw white channels"));
}
if self.colour.kelvin.is_some() && !features.color_tmp {
return Err(refuse("set a colour temperature"));
}
if self.brightness.is_some() && !features.brightness {
return Err(refuse("be dimmed"));
}
if let Some(id) = self.colour.scene {
if !features.effect {
return Err(refuse("play scenes"));
}
if id.as_user_slot().is_none() && !bulb_type.scenes().any(|scene| scene.id() == id) {
let name = id.scene().map_or_else(
|| format!("scene {}", id.get()),
|scene| format!("`{}`", scene.name()),
);
return Err(anyhow::anyhow!(
"{}: it does not play {name}",
describe(bulb_type)
));
}
}
Ok(())
}
}
fn describe(bulb_type: &BulbType) -> String {
let class = bulb_type.class;
match &bulb_type.module_name {
Some(name) => format!(
"{name} is a {} bulb ({})",
class.description(),
class.as_str()
),
None => format!(
"this is a {} bulb ({})",
class.description(),
class.as_str()
),
}
}
pub async fn status(bulb: &Bulb) -> anyhow::Result<Report> {
let pilot = bulb.get_pilot().await?;
Ok(Report::new(status_json(&pilot), describe_pilot(&pilot)))
}
pub async fn power(bulb: &Bulb, on: bool, options: &StateOptions) -> anyhow::Result<Report> {
if !options.is_empty() {
options.check(&bulb.bulb_type().await?)?;
}
let builder = options.apply(PilotBuilder::new().state(on));
bulb.set_pilot(&builder).await?;
Ok(written(on, options))
}
pub async fn toggle(bulb: &Bulb) -> anyhow::Result<Report> {
let pilot = bulb.get_pilot().await?;
let was_on = pilot
.state
.context("the bulb did not report whether it is on, so there is nothing to toggle")?;
bulb.set_pilot(&PilotBuilder::new().state(!was_on)).await?;
Ok(written(!was_on, &StateOptions::default()))
}
pub async fn set(bulb: &Bulb, options: &StateOptions) -> anyhow::Result<Report> {
options.check(&bulb.bulb_type().await?)?;
bulb.set_state(&options.apply(PilotBuilder::new())).await?;
Ok(written(true, options))
}
pub async fn pulse(bulb: &Bulb, delta: PulseDelta, duration_ms: u32) -> anyhow::Result<Report> {
let bulb_type = bulb.bulb_type().await?;
if !bulb_type.features.brightness {
anyhow::bail!("{}: it cannot pulse brightness", describe(&bulb_type));
}
bulb.pulse(delta.get(), duration_ms).await?;
let json = json!({
"delta": delta.get(),
"duration": duration_ms,
});
let human = format!("pulse {:+}% {duration_ms} ms", delta.get());
Ok(Report::new(json, human))
}
fn written(on: bool, options: &StateOptions) -> Report {
let mut parts = vec![if on {
"on".to_owned()
} else {
"off".to_owned()
}];
if let Some([r, g, b]) = options.channels() {
parts.push(format!("rgb {},{},{}", r.get(), g.get(), b.get()));
}
for (label, value) in options.whites() {
parts.push(format!("{label} {}", value.get()));
}
if let Some(kelvin) = options.colour.kelvin {
parts.push(format!("{} K", kelvin.get()));
}
if let Some(id) = options.colour.scene {
parts.push(match id.scene() {
Some(scene) => format!("scene {} ({})", scene.name(), id.get()),
None => format!("scene {}", id.get()),
});
}
if let Some(speed) = options.speed {
parts.push(format!("speed {}", speed.get()));
}
if let Some(brightness) = options.brightness {
parts.push(format!("{}%", brightness.get()));
}
let mut json = json!({ "state": on });
if let Some([r, g, b]) = options.channels() {
json["rgb"] = json!([r.get(), g.get(), b.get()]);
}
if let Some(c) = options.cold {
json["c"] = json!(c.get());
}
if let Some(w) = options.warm {
json["w"] = json!(w.get());
}
if let Some(kelvin) = options.colour.kelvin {
json["temp"] = json!(kelvin.get());
}
if let Some(id) = options.colour.scene {
json["sceneId"] = json!(id.get());
json["scene"] = id.scene().map_or(Value::Null, |scene| json!(scene.name()));
}
if let Some(speed) = options.speed {
json["speed"] = json!(speed.get());
}
if let Some(brightness) = options.brightness {
json["dimming"] = json!(brightness.get());
}
Report::new(json, parts.join(" "))
}
fn status_json(pilot: &Pilot) -> Value {
let mut value = serde_json::to_value(pilot).unwrap_or_else(|_| json!({}));
if let Some(scene) = pilot.scene() {
value["scene"] = json!(scene.name());
}
value
}
fn describe_pilot(pilot: &Pilot) -> String {
let mut parts = vec![match pilot.state {
Some(true) => "on".to_owned(),
Some(false) => "off".to_owned(),
None => "unknown".to_owned(),
}];
if let Some(id) = pilot.scene_id.filter(|id| *id != 0) {
parts.push(match pilot.scene() {
Some(scene) => format!("scene {} ({id})", scene.name()),
None if id == PULSE_SCENE_ID && pilot.effect.as_deref() == Some("pulse") => {
format!("effect pulse ({id})")
}
None => format!("scene {id}"),
});
} else if let Some(effect) = &pilot.effect {
parts.push(format!("effect {effect}"));
}
if pilot.scene_id.is_none_or(|id| id == 0) {
if let Some((r, g, b)) = pilot.rgb().filter(|(r, g, b)| (r | g | b) != 0) {
parts.push(format!("rgb {r},{g},{b}"));
}
for (label, value) in [("cold", pilot.c), ("warm", pilot.w)] {
if let Some(value) = value.filter(|value| *value != 0) {
parts.push(format!("{label} {value}"));
}
}
}
if let Some(temp) = pilot.temp {
parts.push(format!("{temp} K"));
}
if let Some(dimming) = pilot.dimming {
parts.push(format!("{dimming}%"));
}
if let Some(speed) = pilot.speed {
parts.push(format!("speed {speed}"));
}
if let Some(rssi) = pilot.rssi {
parts.push(format!("{rssi} dBm"));
}
parts.join(" ")
}
fn rgb(input: &str) -> Result<[Channel; 3], String> {
let [r, g, b] = triple(input, "R,G,B")?;
let mut channels = [Channel::new(0); 3];
for (channel, part) in channels.iter_mut().zip([r, g, b]) {
let value: u8 = part
.parse()
.map_err(|_| format!("`{part}` in `{input}` is not a channel value 0-255"))?;
*channel = Channel::new(value);
}
Ok(channels)
}
fn channel(input: &str) -> Result<Channel, String> {
input
.parse::<u8>()
.map(Channel::new)
.map_err(|_| format!("`{input}` is not a channel value 0-255"))
}
fn hsv(input: &str) -> Result<[Channel; 3], String> {
let parts = triple(input, "H,S,V")?;
let mut numbers = [0.0f64; 3];
for (slot, part) in numbers.iter_mut().zip(parts) {
*slot = part
.parse()
.map_err(|_| format!("`{part}` in `{input}` is not a number"))?;
}
let [h, s, v] = numbers;
if !(0.0..=360.0).contains(&h) || !(0.0..=100.0).contains(&s) || !(0.0..=100.0).contains(&v) {
return Err(format!(
"`{input}`: hue is 0-360, saturation and value are 0-100"
));
}
let (r, g, b) = hsv_to_rgb(h, s / 100.0, v / 100.0);
Ok([Channel::new(r), Channel::new(g), Channel::new(b)])
}
fn triple<'a>(input: &'a str, shape: &str) -> Result<[&'a str; 3], String> {
let parts: Vec<&str> = input.split(',').map(str::trim).collect();
match parts.as_slice() {
[a, b, c] => Ok([a, b, c]),
_ => Err(format!("`{input}` is not `{shape}`")),
}
}
fn hsv_to_rgb(h: f64, s: f64, v: f64) -> (u8, u8, u8) {
let c = v * s;
let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
let m = v - c;
let (r, g, b) = match h {
h if h < 60.0 => (c, x, 0.0),
h if h < 120.0 => (x, c, 0.0),
h if h < 180.0 => (0.0, c, x),
h if h < 240.0 => (0.0, x, c),
h if h < 300.0 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let byte = |value: f64| ((value + m) * 255.0).round().clamp(0.0, 255.0) as u8;
(byte(r), byte(g), byte(b))
}
fn kelvin(input: &str) -> Result<Kelvin, String> {
let value: u16 = input
.parse()
.map_err(|_| format!("`{input}` is not a colour temperature"))?;
Kelvin::new(value).map_err(|err| err.to_string())
}
fn speed(input: &str) -> Result<Speed, String> {
let value: u8 = input
.parse()
.map_err(|_| format!("`{input}` is not a speed"))?;
Speed::new(value).map_err(|err| err.to_string())
}
fn brightness(input: &str) -> Result<Dimming, String> {
let value: u8 = input
.parse()
.map_err(|_| format!("`{input}` is not a percentage"))?;
Dimming::new(value).map_err(|err| err.to_string())
}
pub(super) fn pulse_delta(input: &str) -> Result<PulseDelta, String> {
let value: i32 = input
.parse()
.map_err(|_| format!("`{input}` is not a signed percentage delta"))?;
PulseDelta::new(value).map_err(|err| err.to_string())
}
pub(super) fn pulse_duration_ms(input: &str) -> Result<u32, String> {
let value: u32 = input
.parse()
.map_err(|_| format!("`{input}` is not a duration in milliseconds"))?;
if value == 0 {
return Err("duration must be at least 1 ms, got 0".to_owned());
}
Ok(value)
}
#[derive(Clone)]
struct SceneParser;
impl TypedValueParser for SceneParser {
type Value = SceneId;
fn parse_ref(
&self,
command: &clap::Command,
_argument: Option<&clap::Arg>,
value: &OsStr,
) -> Result<Self::Value, clap::Error> {
let input = value
.to_str()
.ok_or_else(|| clap::Error::new(ErrorKind::InvalidUtf8).with_cmd(command))?;
scene(input).map_err(|message| {
clap::Error::raw(ErrorKind::ValueValidation, message).with_cmd(command)
})
}
fn possible_values(&self) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>> {
Some(Box::new(Scene::all().iter().copied().map(|scene| {
PossibleValue::new(scene.name().to_ascii_lowercase().replace(' ', "-"))
})))
}
}
fn scene(input: &str) -> Result<SceneId, String> {
if let Ok(id) = input.parse::<u16>() {
return SceneId::new(id).map_err(|err| err.to_string());
}
Scene::from_name(input)
.map(Scene::id)
.map_err(|err| err.to_string())
}