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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
//! Typed `setPilot` / `setState` params and the `getPilot` result.

use serde::{Deserialize, Serialize};

use super::scene::Scene;
use super::types::{
    Channel, Devices, Dimming, Kelvin, PULSE_SCENE_ID, PulseDelta, Ratio, SceneId, Speed,
};
use crate::error::{Error, Result};
use crate::protocol::Request;

/// Which colour-bearing field a [`PilotBuilder`] will put on the wire.
///
/// `r`/`g`/`b`/`c`/`w`, `temp` and `sceneId` are mutually exclusive in a single
/// request: the bulb honours whichever it finds, and a later mode clears the
/// previous one from `getPilot`. Rather than guess which one the caller meant,
/// the builder records the clash and [`PilotBuilder::params`] refuses to
/// produce anything at all.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ColourMode {
    /// Raw channels. `r`/`g`/`b` and `c`/`w` compose, and either half may be
    /// sent without the other — though the half left out goes dark, since the
    /// bulb takes all five as one instruction.
    Channels {
        r: Option<Channel>,
        g: Option<Channel>,
        b: Option<Channel>,
        c: Option<Channel>,
        w: Option<Channel>,
    },
    Temp(Kelvin),
    Scene(SceneId),
}

impl ColourMode {
    const CHANNELS: &'static str = "r/g/b/c/w";

    const fn empty_channels() -> Self {
        Self::Channels {
            r: None,
            g: None,
            b: None,
            c: None,
            w: None,
        }
    }

    /// How this mode is named in a conflict message.
    const fn name(self) -> &'static str {
        match self {
            Self::Channels { .. } => Self::CHANNELS,
            Self::Temp(_) => "temp",
            Self::Scene(_) => "sceneId",
        }
    }

    /// True for the placeholder created before any channel is filled in.
    const fn is_empty(self) -> bool {
        matches!(
            self,
            Self::Channels {
                r: None,
                g: None,
                b: None,
                c: None,
                w: None
            }
        )
    }

    /// Whether a channel write has anything lit in it.
    ///
    /// Measured on `ESP25_SHRGB_01` fw 1.38.0: the five channels are one
    /// instruction, and the bulb honours it only if at least one of them is
    /// non-zero. An all-zero group is **discarded** — the bulb keeps showing
    /// whatever it was showing — and a request with nothing else left in it is
    /// then refused as an empty one, `-32600 Invalid Request`.
    fn is_dark(self) -> bool {
        let Self::Channels { r, g, b, c, w } = self else {
            return false;
        };
        let (mut set, mut lit) = (false, false);
        for channel in [r, g, b, c, w].into_iter().flatten() {
            set = true;
            lit |= channel.get() != 0;
        }
        set && !lit
    }
}

/// Builds the params object for `setPilot` or `setState`.
///
/// One builder, two messages: [`PilotBuilder::set_pilot`] and
/// [`PilotBuilder::set_state`] differ only in the method name. On the hardware
/// measured so far (`ESP25_SHRGB_01` fw 1.38.0) both turn the bulb on when the
/// request carries colour, temperature or a scene — the historical claim that
/// `setState` leaves power alone does not hold.
///
/// Colour, colour temperature and scene are mutually exclusive. Asking for two
/// of them is an error at build time rather than a silent choice between them,
/// because a caller that sets both has a bug and a bulb that receives both has
/// no defined behaviour:
///
/// ```
/// use wizlight::protocol::{Channel, Kelvin, PilotBuilder};
///
/// let clash = PilotBuilder::new()
///     .rgb(Channel::new(255), Channel::new(0), Channel::new(0))
///     .temp(Kelvin::new(2700)?)
///     .set_pilot();
/// assert!(clash.is_err());
/// # Ok::<(), wizlight::Error>(())
/// ```
///
/// Fields that do not carry colour — `state`, `dimming`, `ratio`, `devices` —
/// compose with any of the three. `speed` is the exception, because it belongs
/// to a scene: see [`PilotBuilder::speed`].
///
/// ```
/// use wizlight::protocol::{Channel, Dimming, PilotBuilder};
///
/// let request = PilotBuilder::new()
///     .rgb(Channel::new(255), Channel::new(80), Channel::new(0))
///     .dimming(Dimming::new(40)?)
///     .set_pilot()?;
/// assert_eq!(
///     serde_json::to_value(&request)?,
///     serde_json::json!({
///         "method": "setPilot",
///         "params": {"r": 255, "g": 80, "b": 0, "dimming": 40},
///     }),
/// );
/// # Ok::<(), wizlight::Error>(())
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PilotBuilder {
    state: Option<bool>,
    dimming: Option<Dimming>,
    speed: Option<Speed>,
    ratio: Option<Ratio>,
    devices: Option<Devices>,
    colour: Option<ColourMode>,
    /// The first clash seen, as `(rejected, already set)`. Reported by
    /// [`PilotBuilder::params`]; kept rather than acted on so the setters can
    /// stay chainable and infallible.
    conflict: Option<(&'static str, &'static str)>,
}

impl PilotBuilder {
    /// An empty builder. Building it without any field set is an error: the
    /// bulb rejects both a missing and an empty `params` object.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets `state`.
    #[must_use]
    pub fn state(mut self, on: bool) -> Self {
        self.state = Some(on);
        self
    }

    /// Sets `dimming` (1–100).
    #[must_use]
    pub fn dimming(mut self, dimming: Dimming) -> Self {
        self.dimming = Some(dimming);
        self
    }

    /// Sets scene animation `speed` (10–200).
    ///
    /// `speed` only means something to a scene that animates, so it may
    /// accompany [`scene`](PilotBuilder::scene) — or go on its own, which
    /// retunes whatever scene the bulb is already running. Sending it alongside
    /// a colour, a temperature, or a scene the table calls static is an error
    /// from [`params`](PilotBuilder::params): the bulb takes it and nothing
    /// happens.
    ///
    /// A scene no source documents is not treated as static, so `speed` is
    /// allowed through for it. And if the table turns out to be wrong about
    /// one, the way round is to send the scene and the speed as two requests.
    #[must_use]
    pub fn speed(mut self, speed: Speed) -> Self {
        self.speed = Some(speed);
        self
    }

    /// Sets dual-head `ratio` (0–100).
    #[must_use]
    pub fn ratio(mut self, ratio: Ratio) -> Self {
        self.ratio = Some(ratio);
        self
    }

    /// Sets the dual-head `devices` selector.
    #[must_use]
    pub fn devices(mut self, devices: Devices) -> Self {
        self.devices = Some(devices);
        self
    }

    /// Sets `r`/`g`/`b`.
    ///
    /// Does **not** run RGB→RGB+CW conversion; that is a separate concern.
    /// Send raw channels, or add cold/warm white with
    /// [`cold_white`](PilotBuilder::cold_white) /
    /// [`warm_white`](PilotBuilder::warm_white).
    ///
    /// **The channels left out go dark.** Measured on `ESP25_SHRGB_01` fw
    /// 1.38.0: the five channels are one instruction and a write replaces all
    /// of them, so this turns off any white the bulb was mixing in. It is not
    /// a way to change the colour and leave the whites alone — there is no
    /// such request.
    ///
    /// Conflicts with [`temp`](PilotBuilder::temp) and
    /// [`scene`](PilotBuilder::scene).
    #[must_use]
    pub fn rgb(mut self, r: Channel, g: Channel, b: Channel) -> Self {
        if let Some(ColourMode::Channels {
            r: rs,
            g: gs,
            b: bs,
            ..
        }) = self.channels()
        {
            *rs = Some(r);
            *gs = Some(g);
            *bs = Some(b);
        }
        self
    }

    /// Sets `r`/`g`/`b`/`w`, where `w` is the **warm** white emitter.
    ///
    /// The cold one is left alone; [`rgbww`](PilotBuilder::rgbww) sets both.
    #[must_use]
    pub fn rgbw(self, r: Channel, g: Channel, b: Channel, w: Channel) -> Self {
        self.rgb(r, g, b).warm_white(w)
    }

    /// Sets `r`/`g`/`b`/`c`/`w` — **cold white then warm white**, matching
    /// `pywizlight`'s `rgbww` tuple and Home Assistant's `rgbww` colour mode.
    ///
    /// Worth stating rather than leaving to the parameter list, because the
    /// name says "ww" while the signature takes one of each, and swapping the
    /// two is silent: the bulb accepts it and lights the wrong emitter.
    ///
    /// A shorthand for the three setters, with no behaviour of its own —
    /// `rgb(r, g, b).cold_white(c).warm_white(w)` puts the same five keys on
    /// the wire, and either white may be set without the other.
    #[must_use]
    pub fn rgbww(self, r: Channel, g: Channel, b: Channel, c: Channel, w: Channel) -> Self {
        self.rgb(r, g, b).cold_white(c).warm_white(w)
    }

    /// Sets cold white (`c`), with or without an RGB triple.
    ///
    /// Without one it is a white-only request: the colour channels are part of
    /// the same instruction, so leaving them out turns them off. See
    /// [`rgb`](PilotBuilder::rgb).
    ///
    /// Conflicts with [`temp`](PilotBuilder::temp) and
    /// [`scene`](PilotBuilder::scene).
    #[must_use]
    pub fn cold_white(mut self, c: Channel) -> Self {
        if let Some(ColourMode::Channels { c: slot, .. }) = self.channels() {
            *slot = Some(c);
        }
        self
    }

    /// Sets warm white (`w`), with or without an RGB triple.
    ///
    /// Without one it is a white-only request, as
    /// [`cold_white`](PilotBuilder::cold_white) describes.
    ///
    /// Conflicts with [`temp`](PilotBuilder::temp) and
    /// [`scene`](PilotBuilder::scene).
    #[must_use]
    pub fn warm_white(mut self, w: Channel) -> Self {
        if let Some(ColourMode::Channels { w: slot, .. }) = self.channels() {
            *slot = Some(w);
        }
        self
    }

    /// Sets `temp`.
    ///
    /// Conflicts with the raw channels and with
    /// [`scene`](PilotBuilder::scene).
    #[must_use]
    pub fn temp(mut self, temp: Kelvin) -> Self {
        self.set_colour(ColourMode::Temp(temp));
        self
    }

    /// Sets `sceneId`.
    ///
    /// Conflicts with the raw channels and with [`temp`](PilotBuilder::temp).
    #[must_use]
    pub fn scene(mut self, scene: SceneId) -> Self {
        self.set_colour(ColourMode::Scene(scene));
        self
    }

    /// Serialises into a `setPilot` request.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidParam`] if two colour modes were set, or if no
    /// field was set at all — the bulb refuses an empty params object.
    pub fn set_pilot(&self) -> Result<Request> {
        self.to_request("setPilot")
    }

    /// Serialises into a `setState` request.
    ///
    /// Same params shape as [`PilotBuilder::set_pilot`]. On measured firmware
    /// this still turns the bulb on when colour / temp / scene is present.
    ///
    /// # Errors
    ///
    /// As [`set_pilot`](PilotBuilder::set_pilot).
    pub fn set_state(&self) -> Result<Request> {
        self.to_request("setState")
    }

    /// The params object alone, for callers that want to inspect or merge it.
    ///
    /// # Errors
    ///
    /// As [`set_pilot`](PilotBuilder::set_pilot).
    pub fn params(&self) -> Result<PilotParams> {
        if let Some((rejected, existing)) = self.conflict {
            return Err(Error::InvalidParam {
                message: format!(
                    "`{rejected}` conflicts with `{existing}`: colour, colour temperature \
                     and scene are mutually exclusive in one request"
                ),
            });
        }

        if self.is_empty() {
            return Err(Error::InvalidParam {
                message: "pilot params must set at least one field".into(),
            });
        }

        // Refused here rather than sent, for the same reason as `speed`
        // below: the bulb does not always say no. A bare `{"w":0}` is refused
        // outright, but pair it with `state` or `dimming` and the same
        // instruction is accepted, discarded, and acknowledged `success` — so
        // a caller who sent it has no way of learning it did nothing.
        if self.colour.is_some_and(ColourMode::is_dark) {
            return Err(Error::InvalidParam {
                message: "`r`/`g`/`b`/`c`/`w` are all zero, and a channel write with nothing lit \
                          in it is discarded: to go dark use `state(false)`, and to go dim use \
                          `dimming`"
                    .into(),
            });
        }

        self.check_speed()?;

        let mut params = PilotParams {
            state: self.state,
            dimming: self.dimming,
            speed: self.speed,
            ratio: self.ratio,
            devices: self.devices,
            ..PilotParams::default()
        };

        match self.colour {
            Some(ColourMode::Channels { r, g, b, c, w }) => {
                params.r = r;
                params.g = g;
                params.b = b;
                params.c = c;
                params.w = w;
            }
            Some(ColourMode::Temp(temp)) => params.temp = Some(temp),
            Some(ColourMode::Scene(scene)) => params.scene_id = Some(scene),
            None => {}
        }

        Ok(params)
    }

    /// Refuses a `speed` that cannot do anything.
    ///
    /// `speed` is the animation rate of a running scene, and this request either
    /// starts an animating scene, leaves whatever is running alone, or replaces
    /// it with something that does not animate. Only the last two cases can be
    /// judged here, and the third is the one worth refusing: the bulb accepts
    /// the parameter either way and reports success, so a caller that pairs
    /// `speed` with a colour has no way of finding out it did nothing.
    fn check_speed(&self) -> Result<()> {
        if self.speed.is_none() {
            return Ok(());
        }
        let refuse = |reason: String| {
            Err(Error::InvalidParam {
                message: format!("`speed` sets the rate of an animating scene, but {reason}"),
            })
        };
        match self.colour {
            Some(ColourMode::Channels { .. }) => {
                refuse("this request sets `r`/`g`/`b`/`c`/`w`, which stops any scene".to_owned())
            }
            Some(ColourMode::Temp(_)) => {
                refuse("this request sets `temp`, which stops any scene".to_owned())
            }
            Some(ColourMode::Scene(scene)) if !scene.takes_speed() => refuse(format!(
                "the rate of `{}` cannot be set",
                scene.scene().map_or_else(
                    || format!("scene {}", scene.get()),
                    |scene| scene.to_string()
                )
            )),
            // No colour mode: the scene already running keeps playing, and this
            // is the request that changes its rate.
            _ => Ok(()),
        }
    }

    /// The channel mode to write into, or `None` if a different colour mode is
    /// already set — in which case the clash has been recorded.
    fn channels(&mut self) -> Option<&mut ColourMode> {
        match self.colour {
            Some(ColourMode::Channels { .. }) => self.colour.as_mut(),
            Some(other) => {
                self.note_conflict(ColourMode::CHANNELS, other.name());
                None
            }
            None => {
                self.colour = Some(ColourMode::empty_channels());
                self.colour.as_mut()
            }
        }
    }

    /// Sets a whole-mode colour field, recording a clash with any other mode.
    /// Replacing a mode with the same kind — two `temp` calls — is not a
    /// clash; the last one wins, as with every other setter.
    fn set_colour(&mut self, mode: ColourMode) {
        match self.colour {
            Some(existing) if existing.name() != mode.name() => {
                self.note_conflict(mode.name(), existing.name());
            }
            _ => self.colour = Some(mode),
        }
    }

    /// Keeps the first clash: it is the one that explains what the caller did.
    fn note_conflict(&mut self, rejected: &'static str, existing: &'static str) {
        self.conflict.get_or_insert((rejected, existing));
    }

    fn is_empty(&self) -> bool {
        self.state.is_none()
            && self.dimming.is_none()
            && self.speed.is_none()
            && self.ratio.is_none()
            && self.devices.is_none()
            && self.colour.is_none_or(ColourMode::is_empty)
    }

    fn to_request(&self, method: &str) -> Result<Request> {
        Request::with_params(method, &self.params()?)
    }
}

/// The params object of a `setPilot` / `setState` request.
///
/// Absent fields are omitted on the wire. Construct this through
/// [`PilotBuilder`] so mutual exclusion and ranges are enforced.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct PilotParams {
    /// On/off.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<bool>,
    /// Red channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r: Option<Channel>,
    /// Green channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub g: Option<Channel>,
    /// Blue channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub b: Option<Channel>,
    /// Cold white channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub c: Option<Channel>,
    /// Warm white channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub w: Option<Channel>,
    /// Brightness percent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dimming: Option<Dimming>,
    /// Colour temperature in Kelvin.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temp: Option<Kelvin>,
    /// Scene id.
    #[serde(rename = "sceneId", skip_serializing_if = "Option::is_none")]
    pub scene_id: Option<SceneId>,
    /// Scene animation speed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speed: Option<Speed>,
    /// Dual-head ratio.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ratio: Option<Ratio>,
    /// Dual-head device selector.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub devices: Option<Devices>,
}

/// The `result` of a successful `getPilot`, and the `params` of a `syncPilot`
/// push.
///
/// Every field is optional: the bulb only returns what the active mode needs,
/// and firmware revisions add keys. A missing field is `None`, never a parse
/// error. Values are the plain integers the bulb reported, not the validated
/// newtypes a request uses — a bulb may report what it would not accept.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct Pilot {
    /// Bulb MAC, lowercase hex with no separators.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mac: Option<String>,
    /// Received signal strength, dBm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rssi: Option<i32>,
    /// Whether the bulb is on.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<bool>,
    /// Red channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r: Option<u8>,
    /// Green channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub g: Option<u8>,
    /// Blue channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub b: Option<u8>,
    /// Cold white channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub c: Option<u8>,
    /// Warm white channel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub w: Option<u8>,
    /// Brightness percent. Present even when the bulb is off.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dimming: Option<u8>,
    /// Colour temperature in Kelvin, when in white mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temp: Option<u16>,
    /// Active scene. `0` means "no scene" while RGB is active; `248`
    /// ([`PULSE_SCENE_ID`]) is reported alongside `effect: "pulse"` while a
    /// [`Bulb::pulse`](crate::Bulb::pulse) is running.
    #[serde(rename = "sceneId", skip_serializing_if = "Option::is_none")]
    pub scene_id: Option<u16>,
    /// Active transient effect name (for example `"pulse"` while a
    /// [`Bulb::pulse`](crate::Bulb::pulse) is running).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effect: Option<String>,
    /// Scene animation speed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speed: Option<u8>,
    /// Dual-head ratio.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ratio: Option<u8>,
    /// Dual-head head tag. Zero-based on a `getPilot` answer, one-based in
    /// `syncPilot` push traffic.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub devices: Option<u8>,
    /// Where the state came from (`udp`, `hb`, `wizc1`, …). Push only.
    #[serde(rename = "src", skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
}

impl Pilot {
    /// The scene the bulb is playing, when the reported id names one.
    ///
    /// `None` covers several situations, which is why the raw
    /// [`scene_id`](Pilot::scene_id) is still there: no scene is running (the
    /// bulb reports `0` while colour or temperature is active), the field was
    /// absent, or the id is one the table does not carry — a `256..=265` custom
    /// mode made in the app, or a scene a newer firmware added.
    ///
    /// **A reported `41` or `248` is worth recognising.** `41` is a real scene,
    /// a ~6200 K white at about a third of normal brightness, and every id from
    /// `42` to `248` written via `setPilot` is clamped onto it — so a bulb
    /// driven by some other client with an out-of-range id ends up sitting
    /// there. `248` ([`PULSE_SCENE_ID`]) is reported alongside
    /// `"effect": "pulse"` while a [`Bulb::pulse`](crate::Bulb::pulse) is
    /// running. This crate refuses to *send* either via `setPilot`, for the
    /// reasons on [`SceneId::new`](super::SceneId::new), and so does not name
    /// them in the scene table.
    #[must_use]
    pub fn scene(&self) -> Option<Scene> {
        Scene::from_id(self.scene_id?)
    }

    /// Whether the bulb is currently running a transient [`pulse`](crate::Bulb::pulse)
    /// (`effect == "pulse"` or `sceneId == 248`).
    #[must_use]
    pub fn is_pulsing(&self) -> bool {
        self.effect.as_deref() == Some("pulse") || self.scene_id == Some(PULSE_SCENE_ID)
    }

    /// RGB triple when all three channels are present.
    #[must_use]
    pub fn rgb(&self) -> Option<(u8, u8, u8)> {
        Some((self.r?, self.g?, self.b?))
    }

    /// RGBW when `r`/`g`/`b`/`w` are all present.
    #[must_use]
    pub fn rgbw(&self) -> Option<(u8, u8, u8, u8)> {
        Some((self.r?, self.g?, self.b?, self.w?))
    }

    /// RGBWW when `r`/`g`/`b`/`c`/`w` are all present.
    #[must_use]
    pub fn rgbww(&self) -> Option<(u8, u8, u8, u8, u8)> {
        Some((self.r?, self.g?, self.b?, self.c?, self.w?))
    }
}

/// The `params` object of a `pulse` request.
///
/// Measured on `ESP25_SHRGB_01` fw 1.38.0: `{"method":"pulse","params":{"delta":-60,"duration":300}}`
/// fades the active light by `delta` over `duration` ms and fades back over
/// `duration` ms, reporting `"sceneId": 248` and `"effect": "pulse"` in
/// `getPilot` while active and automatically restoring the prior state when
/// finished.
///
/// ```
/// use wizlight::protocol::PulseParams;
///
/// let request = PulseParams::new(-60, 300)?.request()?;
/// assert_eq!(
///     serde_json::to_value(&request)?,
///     serde_json::json!({
///         "method": "pulse",
///         "params": {"delta": -60, "duration": 300},
///     }),
/// );
/// # Ok::<(), wizlight::Error>(())
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub struct PulseParams {
    /// Signed brightness delta (`-100..=-1` or `1..=100`).
    pub delta: PulseDelta,
    /// Half-cycle duration in milliseconds (`>= 1`).
    pub duration: u32,
}

impl PulseParams {
    /// Validates `delta` (`-100..=-1` or `1..=100`) and `duration_ms` (`>= 1`).
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidParam`] if `delta` is `0` or outside
    /// `-100..=100`, or if `duration_ms` is `0`.
    pub fn new(delta: i32, duration_ms: u32) -> Result<Self> {
        let delta = PulseDelta::new(delta)?;
        if duration_ms == 0 {
            return Err(Error::InvalidParam {
                message: "duration must be at least 1 ms, got 0".to_owned(),
            });
        }
        Ok(Self {
            delta,
            duration: duration_ms,
        })
    }

    /// Serialises into a `pulse` [`Request`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::Json`](crate::Error::Json) if serialisation fails.
    pub fn request(&self) -> Result<Request> {
        Request::with_params("pulse", self)
    }
}

/// `{"success": true}` — the usual write acknowledgement.
///
/// The convenience methods on [`Bulb`](crate::Bulb) check this and turn a
/// `false` into an error, so it is only interesting to callers driving
/// [`Response::parse_result`](super::Response::parse_result) themselves.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct Success {
    /// Whether the bulb accepted the write.
    pub success: bool,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn wire(request: &Request) -> serde_json::Value {
        serde_json::to_value(request).expect("a request always serialises")
    }

    #[test]
    fn conflicting_colour_modes_are_rejected() {
        let cases = [
            PilotBuilder::new().temp(Kelvin::new(2700).unwrap()).rgb(
                Channel::new(1),
                Channel::new(2),
                Channel::new(3),
            ),
            PilotBuilder::new()
                .rgb(Channel::new(1), Channel::new(2), Channel::new(3))
                .temp(Kelvin::new(4000).unwrap()),
            PilotBuilder::new()
                .temp(Kelvin::new(4000).unwrap())
                .scene(SceneId::new(4).unwrap()),
            PilotBuilder::new().scene(SceneId::new(4).unwrap()).rgb(
                Channel::new(1),
                Channel::new(2),
                Channel::new(3),
            ),
            // Standalone white channels are part of the channel mode, so they
            // clash with temp exactly as an RGB triple would.
            PilotBuilder::new()
                .temp(Kelvin::new(4000).unwrap())
                .warm_white(Channel::new(10)),
        ];

        for builder in cases {
            let err = builder.set_pilot().unwrap_err();
            assert!(
                matches!(&err, Error::InvalidParam { message } if message.contains("mutually exclusive")),
                "{err}"
            );
        }
    }

    #[test]
    fn the_conflict_message_names_both_modes() {
        let err = PilotBuilder::new()
            .temp(Kelvin::new(2700).unwrap())
            .scene(SceneId::new(4).unwrap())
            .set_pilot()
            .unwrap_err();
        let message = err.to_string();
        assert!(message.contains("`sceneId`"), "{message}");
        assert!(message.contains("`temp`"), "{message}");
    }

    #[test]
    fn resetting_the_same_mode_is_not_a_conflict() {
        let params = PilotBuilder::new()
            .temp(Kelvin::new(2700).unwrap())
            .temp(Kelvin::new(4000).unwrap())
            .params()
            .unwrap();
        assert_eq!(params.temp.unwrap().get(), 4000);

        let params = PilotBuilder::new()
            .rgb(Channel::new(1), Channel::new(2), Channel::new(3))
            .rgb(Channel::new(4), Channel::new(5), Channel::new(6))
            .params()
            .unwrap();
        assert_eq!(params.r.unwrap().get(), 4);
    }

    #[test]
    fn non_colour_fields_compose_with_a_scene() {
        let params = PilotBuilder::new()
            .scene(SceneId::new(4).unwrap())
            .speed(Speed::new(100).unwrap())
            .dimming(Dimming::new(40).unwrap())
            .state(true)
            .params()
            .unwrap();
        assert_eq!(params.scene_id.unwrap().get(), 4);
        assert_eq!(params.speed.unwrap().get(), 100);
        assert_eq!(params.dimming.unwrap().get(), 40);
        assert_eq!(params.state, Some(true));
    }

    /// `speed` is the one non-colour field that does not compose with
    /// everything, because it is a property of a running scene.
    #[test]
    fn speed_is_allowed_where_it_can_do_something() {
        let speed = Speed::new(100).unwrap();

        // Party animates.
        let params = PilotBuilder::new()
            .scene(SceneId::new(4).unwrap())
            .speed(speed)
            .params()
            .unwrap();
        assert_eq!(params.speed.unwrap().get(), 100);

        // Snowy sky is in no source that says either way, so it is not treated
        // as static: refusing on the strength of a missing row would hide a
        // control that probably works.
        assert!(
            PilotBuilder::new()
                .scene(SceneId::new(36).unwrap())
                .speed(speed)
                .params()
                .is_ok()
        );

        // On its own it retunes whatever scene the bulb is already running.
        let params = PilotBuilder::new().speed(speed).params().unwrap();
        assert_eq!(params.speed.unwrap().get(), 100);
        assert!(params.scene_id.is_none());
    }

    #[test]
    fn speed_is_refused_where_it_cannot() {
        let speed = Speed::new(100).unwrap();
        let cases = [
            // Warm white holds still, so the rate of nothing is nothing.
            (
                PilotBuilder::new()
                    .scene(SceneId::new(11).unwrap())
                    .speed(speed),
                "Warm white",
            ),
            (
                PilotBuilder::new()
                    .rgb(Channel::new(1), Channel::new(2), Channel::new(3))
                    .speed(speed),
                "r`/`g`/`b",
            ),
            (
                PilotBuilder::new()
                    .temp(Kelvin::new(2700).unwrap())
                    .speed(speed),
                "temp",
            ),
        ];

        for (builder, expected) in cases {
            let err = builder.set_pilot().unwrap_err();
            let message = err.to_string();
            assert!(message.contains("`speed`"), "{message}");
            assert!(message.contains(expected), "{message}");
        }
    }

    #[test]
    fn a_reported_scene_id_is_named_only_when_the_table_knows_it() {
        let named: Pilot = serde_json::from_str(r#"{"sceneId":23,"speed":100}"#).unwrap();
        assert_eq!(named.scene().map(Scene::name), Some("Deep dive"));

        // `0` is the bulb saying no scene is running, and 256 is a custom mode
        // made in the app. Neither is a scene this crate can name.
        for raw in [r#"{"sceneId":0}"#, r#"{"sceneId":256}"#, "{}"] {
            let pilot: Pilot = serde_json::from_str(raw).unwrap();
            assert_eq!(pilot.scene(), None, "{raw}");
        }
    }

    #[test]
    fn white_channels_compose_with_rgb_in_either_order() {
        let after = PilotBuilder::new()
            .rgb(Channel::new(1), Channel::new(2), Channel::new(3))
            .cold_white(Channel::new(4))
            .warm_white(Channel::new(5))
            .params()
            .unwrap();
        let before = PilotBuilder::new()
            .cold_white(Channel::new(4))
            .warm_white(Channel::new(5))
            .rgb(Channel::new(1), Channel::new(2), Channel::new(3))
            .params()
            .unwrap();
        assert_eq!(after, before);
        assert_eq!(after.c.unwrap().get(), 4);
        assert_eq!(after.w.unwrap().get(), 5);
        assert_eq!(after.r.unwrap().get(), 1);
    }

    #[test]
    fn rgbww_is_its_three_setters_and_nothing_more() {
        // Why the CLI spells the five emitters as `--rgb` plus `--cold` /
        // `--warm` instead of one five-value flag: the tuple is a shorthand,
        // not a mode of its own, so the two produce the same request and the
        // pair of flags also expresses what the tuple cannot.
        let tuple = PilotBuilder::new()
            .rgbww(
                Channel::new(255),
                Channel::new(80),
                Channel::new(0),
                Channel::new(12),
                Channel::new(34),
            )
            .params()
            .unwrap();
        let separately = PilotBuilder::new()
            .rgb(Channel::new(255), Channel::new(80), Channel::new(0))
            .cold_white(Channel::new(12))
            .warm_white(Channel::new(34))
            .params()
            .unwrap();
        assert_eq!(tuple, separately);
    }

    #[test]
    fn a_channel_write_with_nothing_lit_in_it_is_rejected() {
        // Measured: the bulb discards an all-zero channel group. Sent bare it
        // draws -32600, and sent with a `state` it is accepted, ignored and
        // acknowledged `success` — the case that makes refusing it here worth
        // the trouble, since the caller could never find out otherwise.
        let dark = [
            PilotBuilder::new().rgb(Channel::new(0), Channel::new(0), Channel::new(0)),
            PilotBuilder::new().warm_white(Channel::new(0)),
            PilotBuilder::new()
                .state(true)
                .rgb(Channel::new(0), Channel::new(0), Channel::new(0))
                .cold_white(Channel::new(0)),
        ];
        for builder in dark {
            let err = builder.set_pilot().unwrap_err();
            assert!(
                matches!(&err, Error::InvalidParam { message } if message.contains("all zero")),
                "{err}"
            );
        }

        // One lit channel is enough, and the zeroes beside it are ordinary
        // values — `{"r":255,"g":80,"b":0}` is the commonest request there is.
        let lit = PilotBuilder::new()
            .rgb(Channel::new(0), Channel::new(0), Channel::new(0))
            .warm_white(Channel::new(1))
            .params()
            .unwrap();
        assert_eq!(lit.r.unwrap().get(), 0);
        assert_eq!(lit.w.unwrap().get(), 1);
    }

    #[test]
    fn empty_builder_is_rejected() {
        let err = PilotBuilder::new().set_pilot().unwrap_err();
        assert!(matches!(err, Error::InvalidParam { .. }));
    }

    #[test]
    fn wire_format_matches_recorded_traffic() {
        let cases = [
            (
                PilotBuilder::new().state(true).set_pilot().unwrap(),
                json!({"method": "setPilot", "params": {"state": true}}),
            ),
            (
                PilotBuilder::new()
                    .dimming(Dimming::new(40).unwrap())
                    .set_pilot()
                    .unwrap(),
                json!({"method": "setPilot", "params": {"dimming": 40}}),
            ),
            (
                PilotBuilder::new()
                    .rgb(Channel::new(255), Channel::new(80), Channel::new(0))
                    .set_pilot()
                    .unwrap(),
                json!({"method": "setPilot", "params": {"r": 255, "g": 80, "b": 0}}),
            ),
            (
                PilotBuilder::new()
                    .rgbw(
                        Channel::new(255),
                        Channel::new(80),
                        Channel::new(0),
                        Channel::new(12),
                    )
                    .set_pilot()
                    .unwrap(),
                json!({"method": "setPilot", "params": {"r": 255, "g": 80, "b": 0, "w": 12}}),
            ),
            (
                PilotBuilder::new()
                    .rgbww(
                        Channel::new(0),
                        Channel::new(128),
                        Channel::new(255),
                        Channel::new(0),
                        Channel::new(0),
                    )
                    .set_pilot()
                    .unwrap(),
                json!({
                    "method": "setPilot",
                    "params": {"r": 0, "g": 128, "b": 255, "c": 0, "w": 0},
                }),
            ),
            (
                PilotBuilder::new()
                    .warm_white(Channel::new(200))
                    .set_pilot()
                    .unwrap(),
                json!({"method": "setPilot", "params": {"w": 200}}),
            ),
            (
                PilotBuilder::new()
                    .temp(Kelvin::new(5000).unwrap())
                    .set_pilot()
                    .unwrap(),
                json!({"method": "setPilot", "params": {"temp": 5000}}),
            ),
            (
                PilotBuilder::new()
                    .scene(SceneId::new(4).unwrap())
                    .speed(Speed::new(100).unwrap())
                    .set_pilot()
                    .unwrap(),
                json!({"method": "setPilot", "params": {"sceneId": 4, "speed": 100}}),
            ),
            (
                PilotBuilder::new()
                    .state(true)
                    .ratio(Ratio::new(75).unwrap())
                    .devices(Devices::new(2).unwrap())
                    .set_pilot()
                    .unwrap(),
                json!({
                    "method": "setPilot",
                    "params": {"state": true, "ratio": 75, "devices": 2},
                }),
            ),
            (
                PilotBuilder::new()
                    .rgb(Channel::new(255), Channel::new(0), Channel::new(0))
                    .set_state()
                    .unwrap(),
                json!({"method": "setState", "params": {"r": 255, "g": 0, "b": 0}}),
            ),
        ];

        for (request, expected) in cases {
            assert_eq!(wire(&request), expected);
        }
    }

    #[test]
    fn pilot_parses_partial_results() {
        let colour: Pilot = serde_json::from_str(
            r#"{"mac":"9877d5230f0a","rssi":-53,"state":true,"sceneId":0,"r":255,"g":0,"b":0,"c":0,"w":0,"dimming":40}"#,
        )
        .unwrap();
        assert_eq!(colour.rgb(), Some((255, 0, 0)));
        assert_eq!(colour.rgbw(), Some((255, 0, 0, 0)));
        assert_eq!(colour.rgbww(), Some((255, 0, 0, 0, 0)));
        assert!(colour.temp.is_none());

        let white: Pilot = serde_json::from_str(
            r#"{"mac":"9877d5230f0a","state":true,"sceneId":11,"temp":2700,"dimming":100}"#,
        )
        .unwrap();
        assert_eq!(white.temp, Some(2700));
        assert!(white.r.is_none());
        assert_eq!(white.scene_id, Some(11));
        assert_eq!(white.rgb(), None);
        assert_eq!(white.rgbw(), None);
    }

    #[test]
    fn a_reported_value_the_builder_would_refuse_still_parses() {
        // `Dimming` refuses 0, so parsing must not. The measured hardware
        // clamps and never reports 0 itself, but it does *accept* 0, so a
        // model that echoed it back would still be within the protocol —
        // results must not inherit the write-side bound.
        let pilot: Pilot = serde_json::from_str(r#"{"state":false,"dimming":0}"#).unwrap();
        assert_eq!(pilot.dimming, Some(0));
    }
}