wizlight 0.1.0-beta.1

Async client for Philips WiZ smart bulbs over the local UDP protocol, plus the wizlight CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! The commands that read and write a bulb's pilot state.

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};

/// The state options `on` and `set` share.
#[derive(Args, Debug, Clone, PartialEq, Eq, Default)]
pub struct StateOptions {
    /// The colour to show, in one of the several ways of saying it.
    #[command(flatten)]
    pub colour: ColourOptions,

    /// Cold white emitter, 0-255. Send with `--rgb` or `--hsv`, or alone for
    /// white only — the channels left out go dark.
    #[arg(long, value_name = "N", value_parser = channel)]
    #[arg(conflicts_with_all = ["kelvin", "scene"])]
    pub cold: Option<Channel>,

    /// Warm white emitter, 0-255. Send with `--rgb` or `--hsv`, or alone for
    /// white only — the channels left out go dark.
    #[arg(long, value_name = "N", value_parser = channel)]
    #[arg(conflicts_with_all = ["kelvin", "scene"])]
    pub warm: Option<Channel>,

    /// Scene animation speed, 10-200.
    #[arg(long, value_name = "SPEED", value_parser = speed)]
    pub speed: Option<Speed>,

    /// Brightness percent, 1-100.
    #[arg(long, short = 'b', value_name = "PERCENT", value_parser = brightness)]
    pub brightness: Option<Dimming>,
}

/// The mutually exclusive ways of saying what a bulb should show.
///
/// clap enforces the exclusivity, so `--rgb ... --kelvin ...` is a usage error
/// before anything is sent. [`PilotBuilder`] refuses the same combination, but
/// it can only do so once the command is already running, and its message has
/// no `--flag` in it to point at.
///
/// The white emitters are deliberately *not* in here. `r`/`g`/`b` and `c`/`w`
/// are halves of one colour mode rather than two modes, so `--cold` and
/// `--warm` live beside this group and conflict only with `--kelvin` and
/// `--scene` — see [`StateOptions`].
#[derive(Args, Debug, Clone, PartialEq, Eq, Default)]
#[group(multiple = false)]
pub struct ColourOptions {
    /// Colour as `R,G,B`, each 0-255.
    #[arg(long, value_name = "R,G,B", value_parser = rgb)]
    pub rgb: Option<[Channel; 3]>,

    /// Colour as `H,S,V` — hue 0-360, saturation and value 0-100.
    #[arg(long, value_name = "H,S,V", value_parser = hsv)]
    pub hsv: Option<[Channel; 3]>,

    /// White colour temperature, in Kelvin.
    #[arg(long, short = 'k', value_name = "KELVIN", value_parser = kelvin)]
    pub kelvin: Option<Kelvin>,

    /// Scene, by id or by name.
    #[arg(long, short = 's', value_name = "SCENE", value_parser = SceneParser)]
    pub scene: Option<SceneId>,
}

impl StateOptions {
    /// Whether nothing at all was asked for.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        *self == Self::default()
    }

    /// Rejects a `set` with nothing to set, as a usage error.
    ///
    /// `on` is complete on its own and `set` is not, which no single clap
    /// group can express: the options live in one struct shared by both. So
    /// the rule is checked after parsing and reported through clap anyway,
    /// which keeps the message in clap's voice and the exit code at 2 with
    /// every other usage error.
    ///
    /// # Errors
    ///
    /// A clap error naming the options that would have made it valid.
    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(())
    }

    /// Rejects a colour with every channel at zero, as a usage error.
    ///
    /// Measured on `ESP25_SHRGB_01` fw 1.38.0: `r`/`g`/`b`/`c`/`w` are one
    /// instruction, and the bulb honours it only if a channel is non-zero. An
    /// all-zero one is discarded — and `on --rgb 0,0,0` is the shape that
    /// makes this worth catching, because there the request also carries
    /// `state`, so the bulb answers `success` having ignored the colour
    /// entirely. `set --rgb 0,0,0` at least fails, with the bulb's own
    /// `-32600` and no mention of a flag.
    ///
    /// [`PilotBuilder`] refuses the same thing, for callers that come at it
    /// from the library; this is the version that can name what you typed.
    ///
    /// # Errors
    ///
    /// A clap error naming the flags that are all zero.
    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(())
    }

    /// The colour triple, however it was spelled.
    fn channels(&self) -> Option<[Channel; 3]> {
        self.colour.rgb.or(self.colour.hsv)
    }

    /// The white emitters that were asked for, labelled for output.
    fn whites(&self) -> impl Iterator<Item = (&'static str, Channel)> {
        [("cold", self.cold), ("warm", self.warm)]
            .into_iter()
            .filter_map(|(label, value)| Some((label, value?)))
    }

    /// Adds everything that was asked for to a builder.
    ///
    /// # Errors
    ///
    /// Whatever [`PilotBuilder`] refuses, though clap has already rejected the
    /// combinations it would refuse for.
    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);
            // Sent anyway — the bulb takes it and discards it — but worth
            // saying, because the flag looks like it did something.
            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
    }

    /// Refuses an option the bulb has no hardware for, naming the class.
    ///
    /// The bulb will not do this itself. Measured on `ESP25_SHRGB_01` fw
    /// 1.38.0: it accepts the dual-head `ratio` parameter and answers
    /// `success`, having nothing to balance — so a device answering `success`
    /// is not evidence that anything happened, and a dimmable white bulb told
    /// to go red would report exactly the same.
    ///
    /// # Errors
    ///
    /// A message naming the class and what it lacks.
    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"));
        }
        // Gated on `color` rather than on a white-emitter count, for two
        // reasons. `nowc` cannot carry the check: both measured
        // `ESP25_SHRGB_01` report `nowc: 1` and yet answer visibly
        // differently to `c` and to `w`. And raw channels are the colour
        // mode, so the classes known to honour them are the colour ones. A
        // tunable white bulb is the interesting case — it is the class that
        // has two white emitters, and it may well take `c`/`w` directly —
        // but none has been on hand to try, so it is refused rather than
        // guessed at.
        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"));
            }
            // A user slot holds whatever its owner saved into it, so there is
            // nothing to check it against; a named scene is only playable by
            // the classes the table lists it for.
            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(())
    }
}

/// How an error refers to the device it is complaining about.
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()
        ),
    }
}

/// `wizlight status <target>` — what the bulb says it is doing.
///
/// # Errors
///
/// Whatever `getPilot` failed with.
pub async fn status(bulb: &Bulb) -> anyhow::Result<Report> {
    let pilot = bulb.get_pilot().await?;
    Ok(Report::new(status_json(&pilot), describe_pilot(&pilot)))
}

/// `wizlight on|off <target>`.
///
/// # Errors
///
/// Whatever the write failed with, or a capability the bulb does not have.
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))
}

/// `wizlight toggle <target>`.
///
/// # Errors
///
/// As [`power`], plus a bulb that does not report a power state to invert.
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()))
}

/// `wizlight set <target>` — the same options as `on`, sent as `setState`.
///
/// This does **not** leave the bulb alone if it was off. Measured on
/// `ESP25_SHRGB_01` fw 1.38.0: `setState` turns the bulb on exactly as
/// `setPilot` does. The command is kept because the method exists and is worth
/// being able to send; the promise that used to go with it is not.
///
/// # Errors
///
/// As [`power`]. An invocation that asked for nothing is caught earlier, as
/// the usage error it is — see [`StateOptions::require_something`].
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))
}

/// `wizlight pulse <target> --delta <N> --duration <MS>`.
///
/// Fades the active light by `delta` (`-100..=-1` or `1..=100`%) over
/// `duration_ms` ms and fades back over `duration_ms` ms, restoring the bulb's
/// prior state when finished.
///
/// # Errors
///
/// Returns an error if the bulb has no brightness control (for example a smart
/// socket) or if the `pulse` request fails.
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))
}

/// What a write reports back.
///
/// The bulb's acknowledgement carries no state, so this describes the request
/// rather than pretending to have read anything: `status` is how you see what
/// the bulb settled on, and on a scene or a temperature that is not what was
/// asked for.
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()));
    }
    // Zero is worth echoing here, unlike in `status`: this describes what was
    // asked for, and `--warm 0` is a request to switch that emitter off.
    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()]);
    }
    // Keyed as the bulb keys them, so a reader can line the request up against
    // the `c`/`w` a later `status` reports.
    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("  "))
}

/// The reported state, with the scene named where the id names one.
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
}

/// One line: whether it is on, what it is showing, and how well it hears us.
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(),
    }];

    // Scene first: while one is playing it is what the bulb is doing, and the
    // colour channels it also reports are the current frame of it. `248` is
    // the internal slot reported alongside `effect: "pulse"` while a transient
    // pulse is active.
    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) {
        // Only what is lit. Measured on `ESP25_SHRGB_01` fw 1.38.0, a bulb in
        // channel mode reports all five channels on every read, and the ones
        // nothing set read `0` — a white-only bulb reports `rgb 0,0,0` and a
        // plain colour reports `c` and `w` at zero. Printing those would add
        // columns that say nothing, so the line carries the emitters that are
        // actually on. `--json` renders whatever the bulb reported, either
        // way.
        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("  ")
}

/// Parses `R,G,B`.
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)
}

/// Parses one channel value, for the flags that take a single emitter.
///
/// The whole of `u8` is on the wire, and measured on `ESP25_SHRGB_01` fw
/// 1.38.0 every value in it is honoured exactly and read back unchanged —
/// there is no clamp partway up, which the 128 ceiling in `pywizlight`'s
/// conversion might suggest. That ceiling is the algorithm's, not the
/// hardware's.
fn channel(input: &str) -> Result<Channel, String> {
    input
        .parse::<u8>()
        .map(Channel::new)
        .map_err(|_| format!("`{input}` is not a channel value 0-255"))
}

/// Parses `H,S,V` and converts it, because the protocol has no HSV.
///
/// `V` scales the colour channels; it is not the bulb's own brightness, which
/// is `--brightness` and a separate parameter on the wire.
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)])
}

/// Three comma-separated fields.
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}`")),
    }
}

/// The standard conversion, with `s` and `v` as fractions.
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))
}

/// Parses a Kelvin value against the wire bound.
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())
}

/// Parses a signed non-zero pulse delta (`-100..=-1` or `1..=100`).
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())
}

/// Parses a non-zero pulse duration in milliseconds (`>= 1`).
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(' ', "-"))
        })))
    }
}

/// Parses a scene, by id or by name.
///
/// Both are checked here rather than against the bulb: the id has to be one
/// the hardware will actually play — several it accepts do something else
/// entirely — and the name has to be in the table. What is left for the bulb
/// is whether *its* class plays that scene, which is [`StateOptions::check`].
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())
}