use std::collections::BTreeSet;
use std::future::Future;
use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::process::ExitCode;
use std::time::Duration;
use anyhow::Context as _;
use clap::{ArgAction, Args, CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use if_addrs::IfAddr;
use serde_json::{Value, json};
use tokio::task::JoinSet;
mod bench;
mod describe;
mod discover;
mod output;
mod pilot;
mod target;
mod watch;
pub use crate::protocol::PulseDelta;
use crate::{Bulb, Discovery, Error, PORT, RetryPolicy};
pub use bench::{Bench, BenchMode, PulseStepSummary, RttStats, StepSummary, rate_steps};
pub use output::{
HumanRenderer, JsonRenderer, OutputRenderer, colour_on_stderr, colour_on_stdout, render_json,
};
pub use pilot::{ColourOptions, StateOptions};
pub use target::{BadTarget, NotFound, Resolved, TargetSpec};
pub const EXIT_NOT_FOUND: u8 = 3;
pub const EXIT_TIMEOUT: u8 = 4;
#[derive(Debug, Parser)]
#[command(
name = "wizlight",
about = "Control Philips WiZ bulbs over the local network"
)]
#[command(
version,
arg_required_else_help = true,
long_about = "Control Philips WiZ bulbs directly over the local network — no cloud, account or hub.\n\nStart with:\n wizlight discover\n wizlight status <TARGET>\n wizlight on <TARGET> --rgb 255,80,0\n wizlight off <TARGET>"
)]
pub struct Cli {
#[arg(long, short = 'j', global = true, action = ArgAction::SetTrue)]
pub json: bool,
#[arg(
long,
global = true,
default_value = "2",
value_name = "SECONDS",
value_parser = seconds
)]
pub timeout: Duration,
#[arg(
long,
global = true,
default_value = "5",
value_name = "SECONDS",
value_parser = seconds
)]
pub wait: Duration,
#[arg(long, global = true, value_name = "ADDR", value_parser = address)]
pub broadcast: Vec<SocketAddr>,
#[arg(long, short = 'v', global = true, action = ArgAction::Count)]
pub verbose: u8,
#[command(subcommand)]
pub command: Command,
}
impl Cli {
#[must_use]
pub fn policy(&self) -> RetryPolicy {
RetryPolicy {
attempt_timeout: self.timeout,
..RetryPolicy::default()
}
}
pub fn discovery(&self, system_config: bool) -> anyhow::Result<Discovery> {
let discovery = Discovery::new()
.system_config(system_config)
.policy(self.policy());
let targets = broadcast_targets(&self.broadcast, local_ipv4_interfaces)?;
tracing::debug!(?targets, "selected discovery targets");
Ok(targets
.iter()
.fold(discovery, |discovery, addr| discovery.target(*addr)))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct InterfaceAddress {
ip: Ipv4Addr,
netmask: Ipv4Addr,
up: bool,
point_to_point: bool,
}
fn local_ipv4_interfaces() -> io::Result<Vec<InterfaceAddress>> {
if_addrs::get_if_addrs().map(|interfaces| {
interfaces
.into_iter()
.filter_map(|interface| {
let up = interface.is_oper_up();
let point_to_point = interface.is_p2p();
match interface.addr {
IfAddr::V4(addr) => Some(InterfaceAddress {
ip: addr.ip,
netmask: addr.netmask,
up,
point_to_point,
}),
IfAddr::V6(_) => None,
}
})
.collect()
})
}
fn broadcast_targets<F>(explicit: &[SocketAddr], enumerate: F) -> anyhow::Result<Vec<SocketAddr>>
where
F: FnOnce() -> io::Result<Vec<InterfaceAddress>>,
{
if !explicit.is_empty() {
return Ok(explicit.to_vec());
}
let interfaces = enumerate().context("could not enumerate local network interfaces")?;
let targets: BTreeSet<SocketAddr> = interfaces
.into_iter()
.filter_map(|interface| {
let mask = u32::from(interface.netmask);
let host_mask = !mask;
let host_bits = host_mask.count_ones();
let contiguous = mask.leading_ones() + mask.trailing_zeros() == 32;
let viable = interface.up
&& !interface.point_to_point
&& !interface.ip.is_loopback()
&& !interface.ip.is_link_local()
&& !interface.ip.is_unspecified()
&& !interface.ip.is_multicast()
&& interface.ip != Ipv4Addr::BROADCAST
&& contiguous
&& (2..32).contains(&host_bits);
viable.then(|| {
SocketAddr::new(
IpAddr::V4(Ipv4Addr::from(u32::from(interface.ip) | host_mask)),
PORT,
)
})
})
.collect();
if targets.is_empty() {
anyhow::bail!("no viable IPv4 network interface found; pass --broadcast ADDRESS")
}
Ok(targets.into_iter().collect())
}
fn seconds(input: &str) -> Result<Duration, String> {
let secs: f64 = input
.parse()
.map_err(|_| format!("`{input}` is not a number of seconds"))?;
Duration::try_from_secs_f64(secs).map_err(|err| format!("`{input}`: {err}"))
}
fn address(input: &str) -> Result<SocketAddr, String> {
if let Ok(addr) = input.parse::<SocketAddr>() {
return Ok(addr);
}
input
.parse::<IpAddr>()
.map(|ip| SocketAddr::new(ip, PORT))
.map_err(|_| format!("`{input}` is not an address"))
}
#[derive(Args, Debug, Clone, PartialEq, Eq)]
#[group(required = true, multiple = false)]
pub struct Target {
#[arg(value_name = "TARGET")]
pub target: Option<TargetSpec>,
#[arg(long)]
pub all: bool,
}
#[derive(Args, Debug, Clone, PartialEq, Eq)]
pub struct Write {
#[command(flatten)]
pub target: Target,
#[command(flatten)]
pub options: StateOptions,
}
#[derive(Args, Debug, Clone, PartialEq, Eq)]
pub struct Pulse {
#[command(flatten)]
pub target: Target,
#[arg(
long,
short = 'd',
allow_hyphen_values = true,
value_name = "PERCENT",
value_parser = pilot::pulse_delta
)]
pub delta: PulseDelta,
#[arg(
long,
value_name = "MS",
value_parser = pilot::pulse_duration_ms
)]
pub duration: u32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Report {
json: Value,
human: String,
}
impl Report {
#[must_use]
pub fn new(json: Value, human: impl Into<String>) -> Self {
Self {
json,
human: human.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
pub enum Command {
Discover,
Status(Target),
#[command(
after_long_help = "Examples:\n wizlight on 9877d5230f0a\n wizlight on 9877d5230f0a --rgb 255,80,0 --brightness 60\n wizlight on --all --scene 'Deep dive' --speed 120"
)]
On(Write),
Off(Target),
Info(Target),
#[command(
after_long_help = "Examples:\n wizlight set 9877d5230f0a --kelvin 2700\n wizlight set 9877d5230f0a --rgb 255,80,0 --warm 64\n wizlight set --all --brightness 40"
)]
Set(Write),
Toggle(Target),
#[command(
after_long_help = "Examples:\n wizlight pulse 9877d5230f0a --delta -80 --duration 150\n wizlight pulse --all --delta -50 --duration 300\n wizlight pulse 9877d5230f0a --delta 60 --duration 200 --json"
)]
Pulse(Pulse),
Scenes(Target),
Watch(Target),
#[command(
after_long_help = "Examples:\n wizlight bench 9877d5230f0a\n wizlight bench 9877d5230f0a --min-rate 5 --max-rate 40 --steps 8 --hold 2\n wizlight bench 9877d5230f0a --json"
)]
Bench(Bench),
#[command(hide = true)]
Completions {
#[arg(value_enum)]
shell: Shell,
},
}
impl Command {
#[must_use]
pub const fn name(&self) -> &'static str {
match self {
Self::Discover => "discover",
Self::Status(_) => "status",
Self::Info(_) => "info",
Self::On(_) => "on",
Self::Off(_) => "off",
Self::Toggle(_) => "toggle",
Self::Set(_) => "set",
Self::Pulse(_) => "pulse",
Self::Scenes(_) => "scenes",
Self::Watch(_) => "watch",
Self::Bench(_) => "bench",
Self::Completions { .. } => "completions",
}
}
#[must_use]
pub fn selection(&self) -> Option<&Target> {
match self {
Self::Discover | Self::Completions { .. } => None,
Self::On(write) | Self::Set(write) => Some(&write.target),
Self::Pulse(pulse) => Some(&pulse.target),
Self::Bench(bench) => Some(&bench.target),
Self::Status(t)
| Self::Info(t)
| Self::Off(t)
| Self::Toggle(t)
| Self::Scenes(t)
| Self::Watch(t) => Some(t),
}
}
#[must_use]
pub fn target(&self) -> Option<&str> {
Some(self.selection()?.target.as_ref()?.raw())
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Outcome {
result: Value,
human: String,
ok: bool,
}
impl Outcome {
#[must_use]
pub fn new(result: Value, human: impl Into<String>) -> Self {
Self {
result,
human: human.into(),
ok: true,
}
}
#[must_use]
pub fn partial(result: Value, human: impl Into<String>) -> Self {
Self {
ok: false,
..Self::new(result, human)
}
}
#[must_use]
pub const fn succeeded(&self) -> bool {
self.ok
}
#[must_use]
pub fn render(&self, command: &Command, json: bool) -> String {
let payload = if json {
json!({
"ok": self.ok,
"command": command.name(),
"target": command.target(),
"result": self.result,
})
} else {
Value::String(self.human.clone())
};
renderer(json).render(&payload)
}
}
pub async fn run_command(cli: &Cli) -> anyhow::Result<Outcome> {
match &cli.command {
Command::Discover => {
let discovery = cli.discovery(true)?;
discover::run(&discovery, cli.wait).await
}
Command::Status(target) => {
act(
cli,
target,
|bulb| async move { pilot::status(&bulb).await },
)
.await
}
Command::Info(target) => {
act(
cli,
target,
|bulb| async move { describe::info(&bulb).await },
)
.await
}
Command::Scenes(target) => {
act(
cli,
target,
|bulb| async move { describe::scenes(&bulb).await },
)
.await
}
Command::On(write) => {
let options = write.options.clone();
act(cli, &write.target, move |bulb| {
let options = options.clone();
async move { pilot::power(&bulb, true, &options).await }
})
.await
}
Command::Off(target) => {
act(cli, target, |bulb| async move {
pilot::power(&bulb, false, &StateOptions::default()).await
})
.await
}
Command::Toggle(target) => {
act(
cli,
target,
|bulb| async move { pilot::toggle(&bulb).await },
)
.await
}
Command::Set(write) => {
let options = write.options.clone();
act(cli, &write.target, move |bulb| {
let options = options.clone();
async move { pilot::set(&bulb, &options).await }
})
.await
}
Command::Pulse(pulse) => {
let delta = pulse.delta;
let duration = pulse.duration;
act(cli, &pulse.target, move |bulb| async move {
pilot::pulse(&bulb, delta, duration).await
})
.await
}
Command::Completions { shell } => Ok(completions(*shell)),
Command::Bench(bench) => bench::run(cli, bench).await,
Command::Watch(_) => {
anyhow::bail!("`watch` streams output and must be run as the CLI process")
}
}
}
fn completions(shell: Shell) -> Outcome {
let mut command = Cli::command();
let mut output = Vec::new();
clap_complete::generate(shell, &mut command, "wizlight", &mut output);
let output = String::from_utf8(output).expect("clap completion scripts are UTF-8");
let human = output.trim_end_matches(['\r', '\n']).to_owned();
Outcome::new(Value::String(output), human)
}
async fn act<F, Fut>(cli: &Cli, selection: &Target, op: F) -> anyhow::Result<Outcome>
where
F: Fn(Bulb) -> Fut + Clone + Send + 'static,
Fut: Future<Output = anyhow::Result<Report>> + Send + 'static,
{
let policy = cli.policy();
if let Some(spec) = &selection.target {
let bulb = match spec.address() {
Some(addr) => Resolved { addr, mac: None },
None => {
let discovery = cli.discovery(false)?;
target::resolve(spec, &discovery, cli.wait).await?
}
};
let report = op(bulb.connect(&policy).await?).await?;
return Ok(Outcome::new(report.json, report.human));
}
let discovery = cli.discovery(false)?;
let bulbs = target::resolve_all(&discovery, cli.wait).await?;
tracing::info!(bulbs = bulbs.len(), "fanning out");
let mut tasks = JoinSet::new();
for bulb in bulbs {
let op = op.clone();
let policy = policy.clone();
tasks.spawn(async move {
let label = bulb.label();
let result = match bulb.connect(&policy).await {
Ok(handle) => op(handle).await,
Err(err) => Err(err.into()),
};
(label, result)
});
}
let mut results = Vec::new();
while let Some(joined) = tasks.join_next().await {
results.push(joined?);
}
results.sort_by(|(a, _), (b, _)| a.cmp(b));
Ok(collect(results))
}
fn collect(results: Vec<(String, anyhow::Result<Report>)>) -> Outcome {
let failed = results.iter().filter(|(_, r)| r.is_err()).count();
let json: Vec<Value> = results
.iter()
.map(|(label, result)| match result {
Ok(report) => json!({"target": label, "ok": true, "result": report.json}),
Err(err) => json!({"target": label, "ok": false, "error": err.to_string()}),
})
.collect();
let human = results
.iter()
.map(|(label, result)| match result {
Ok(report) => prefixed(label, &report.human),
Err(err) => prefixed(label, &format!("error: {err}")),
})
.collect::<Vec<_>>()
.join("\n");
let value = Value::Array(json);
if failed == 0 {
Outcome::new(value, human)
} else {
Outcome::partial(value, human)
}
}
fn prefixed(label: &str, body: &str) -> String {
if body.contains('\n') {
let indented: Vec<String> = body.lines().map(|line| format!(" {line}")).collect();
format!("{label}:\n{}", indented.join("\n"))
} else {
format!("{label} {body}")
}
}
#[must_use]
pub fn render_failure(command: Option<&Command>, message: &str, json: bool) -> String {
let payload = if json {
json!({
"ok": false,
"command": command.map(Command::name),
"target": command.and_then(Command::target),
"error": message,
})
} else {
Value::String(format!("error: {message}"))
};
renderer(json).render(&payload)
}
#[must_use]
pub fn renderer(json: bool) -> Box<dyn OutputRenderer> {
if json {
Box::new(JsonRenderer)
} else {
Box::new(HumanRenderer)
}
}
fn exit_code(err: &anyhow::Error) -> ExitCode {
if err.downcast_ref::<NotFound>().is_some() {
return ExitCode::from(EXIT_NOT_FOUND);
}
if matches!(err.downcast_ref::<Error>(), Some(Error::Timeout { .. })) {
return ExitCode::from(EXIT_TIMEOUT);
}
ExitCode::FAILURE
}
fn init_logging(verbose: u8, json: bool) {
let default = match verbose {
0 => "warn",
1 => "info",
2 => "debug",
_ => "trace",
};
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(default));
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_writer(std::io::stderr)
.with_ansi(colour_on_stderr(json))
.init();
}
#[must_use]
pub fn run() -> ExitCode {
let cli = Cli::parse();
if let Command::Set(write) = &cli.command {
if let Err(err) = write.options.require_something(&mut Cli::command()) {
err.exit();
}
}
if let Command::On(write) | Command::Set(write) = &cli.command {
if let Err(err) = write.options.require_something_lit(&mut Cli::command()) {
err.exit();
}
}
if let Command::Bench(bench) = &cli.command {
if let Err(err) = bench.validate(&mut Cli::command()) {
err.exit();
}
}
init_logging(cli.verbose, cli.json);
tracing::debug!(
command = cli.command.name(),
target = cli.command.target(),
timeout = ?cli.timeout,
wait = ?cli.wait,
broadcast = ?cli.broadcast,
json = cli.json,
"parsed invocation"
);
let runtime = match tokio::runtime::Runtime::new() {
Ok(runtime) => runtime,
Err(err) => {
eprintln!(
"{}",
render_failure(
Some(&cli.command),
&format!("could not start the async runtime: {err}"),
cli.json
)
);
return ExitCode::FAILURE;
}
};
let result = match &cli.command {
Command::Watch(target) => runtime.block_on(watch::run(&cli, target)).map(|()| None),
_ => runtime.block_on(run_command(&cli)).map(Some),
};
match result {
Ok(Some(outcome)) => {
println!("{}", outcome.render(&cli.command, cli.json));
if outcome.succeeded() {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}
Ok(None) => ExitCode::SUCCESS,
Err(err) => {
eprintln!(
"{}",
render_failure(Some(&cli.command), &err.to_string(), cli.json)
);
exit_code(&err)
}
}
}
#[cfg(test)]
mod tests {
use super::{InterfaceAddress, broadcast_targets};
use std::io;
use std::net::{Ipv4Addr, SocketAddr};
fn interface(ip: [u8; 4], prefix: u8, up: bool, point_to_point: bool) -> InterfaceAddress {
let netmask = match prefix {
0 => 0,
prefix => u32::MAX << (32 - prefix),
};
InterfaceAddress {
ip: Ipv4Addr::from(ip),
netmask: Ipv4Addr::from(netmask),
up,
point_to_point,
}
}
#[test]
fn automatic_broadcasts_cover_every_viable_subnet_once() {
let interfaces = vec![
interface([192, 168, 4, 20], 24, true, false),
interface([192, 168, 4, 21], 24, true, false),
interface([10, 12, 8, 9], 20, true, false),
interface([172, 16, 1, 8], 24, false, false),
interface([127, 0, 0, 1], 8, true, false),
interface([169, 254, 8, 2], 16, true, false),
interface([100, 64, 0, 1], 30, true, true),
interface([198, 51, 100, 8], 31, true, false),
interface([203, 0, 113, 8], 32, true, false),
];
let targets = broadcast_targets(&[], || Ok(interfaces)).expect("interfaces enumerate");
let expected: Vec<SocketAddr> = ["10.12.15.255:38899", "192.168.4.255:38899"]
.into_iter()
.map(|addr| addr.parse().expect("a socket address"))
.collect();
assert_eq!(targets, expected);
}
#[test]
fn automatic_broadcasts_fail_without_a_viable_interface() {
let interfaces = vec![
interface([127, 0, 0, 1], 8, true, false),
interface([169, 254, 8, 2], 16, true, false),
interface([192, 168, 4, 20], 24, false, false),
];
let error = broadcast_targets(&[], || Ok(interfaces)).expect_err("no viable interface");
assert!(error.to_string().contains("--broadcast"));
}
#[test]
fn explicit_broadcasts_bypass_interface_enumeration() {
let explicit = ["192.168.9.255:38899".parse().expect("a socket address")];
let targets = broadcast_targets(&explicit, || -> io::Result<Vec<InterfaceAddress>> {
panic!("explicit targets must not enumerate interfaces")
})
.expect("explicit targets work without enumeration");
assert_eq!(targets, explicit);
}
}