huesmith-core 0.1.0

Platform-agnostic core for Hue-compatible Zigbee lights: color math, ZCL light state machine, and scene parsing
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
use crate::color;
use crate::light::command::LightCommand;
use crate::light::LightOutput;

/// Color mode of the light, matching ZCL color modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorMode {
    HueSaturation,
    XY,
    ColorTemperature,
}

/// Complete raw light state handed to [`LightOutput::state_update`] after every
/// render pass.
///
/// Unlike [`SceneState`] (a *partial* snapshot for Zigbee scene storage, where
/// absent fields mean "don't touch"), every field here is always present — no
/// `Option`s to unwrap. All values are raw ZCL domains.
///
/// `#[non_exhaustive]`: backends receive this by reference and read its fields,
/// so new state (e.g. a future color-loop phase) can be added without a breaking
/// release. It does mean the struct can't be constructed with a literal outside
/// this crate — not a use case, since only the state machine produces it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct LightSnapshot {
    pub on: bool,
    /// Logical level (0-254): the target the light is at or heading to. Stays
    /// put during an on/off fade.
    pub brightness: u8,
    /// The level actually being driven right now (0-254): ramps frame by frame
    /// during fades and transitions — key effects off this one to follow what
    /// the LED is visibly doing.
    pub rendered_brightness: u8,
    pub color_mode: ColorMode,
    pub hue: u8,
    pub saturation: u8,
    pub enhanced_hue: u16,
    pub color_x: u16,
    pub color_y: u16,
    pub color_temp_mireds: u16,
}

/// Partial light-state snapshot stored by the Zigbee Scenes cluster.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SceneState {
    pub on: Option<bool>,
    pub brightness: Option<u8>,
    pub color_mode: Option<ColorMode>,
    pub hue: Option<u8>,
    pub saturation: Option<u8>,
    pub enhanced_hue: Option<u16>,
    pub color_x: Option<u16>,
    pub color_y: Option<u16>,
    pub color_temp_mireds: Option<u16>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq)]
struct TransitionFields {
    brightness: bool,
    render_brightness: bool,
    color_x: bool,
    color_y: bool,
    color_temp_mireds: bool,
    hue: bool,
    saturation: bool,
}

impl TransitionFields {
    fn any(self) -> bool {
        self.brightness
            || self.render_brightness
            || self.color_x
            || self.color_y
            || self.color_temp_mireds
            || self.hue
            || self.saturation
    }
}

/// Complete light state machine.
pub struct LightState {
    pub on: bool,
    pub brightness: u8,
    pub color_mode: ColorMode,
    pub hue: u8,
    pub saturation: u8,
    pub color_x: u16,
    pub color_y: u16,
    pub color_temp_mireds: u16,
    render_brightness: u8,
    output: Box<dyn LightOutput>,

    /// Coalesces split XY color attribute updates that arrive in separate
    /// SET_ATTR callbacks from the Hue Bridge.
    pending_color_x: Option<u16>,
    pending_color_y: Option<u16>,

    /// Identify blinking state. ZCL spec: blink at 0.5 Hz for `duration` seconds.
    /// `identify_blink_count` counts remaining half-cycles; 0 = not identifying.
    identify_blink_count: u32,
    identify_blink_phase: bool,

    transition_active: bool,
    transition_duration_ms: u32,
    transition_elapsed_ms: u32,
    transition_step_interval_ms: u16,
    transition_fields: TransitionFields,
    transition_final_on: Option<bool>,
    start_brightness: u8,
    start_render_brightness: u8,
    start_color_x: u16,
    start_color_y: u16,
    start_color_temp_mireds: u16,
    start_hue: u8,
    start_saturation: u8,

    target_brightness: u8,
    target_render_brightness: u8,
    target_color_x: u16,
    target_color_y: u16,
    target_color_temp_mireds: u16,
    target_hue: u8,
    target_saturation: u8,
}

impl LightState {
    pub fn new(output: Box<dyn LightOutput>) -> Self {
        Self {
            on: false,
            brightness: 254,
            color_mode: ColorMode::ColorTemperature,
            hue: 0,
            saturation: 0,
            color_x: 20495,
            color_y: 21561,
            color_temp_mireds: 370,
            render_brightness: 0,
            output,
            pending_color_x: None,
            pending_color_y: None,
            identify_blink_count: 0,
            identify_blink_phase: false,
            transition_active: false,
            transition_duration_ms: 0,
            transition_elapsed_ms: 0,
            transition_step_interval_ms: 50,
            transition_fields: TransitionFields::default(),
            transition_final_on: None,
            start_brightness: 254,
            start_render_brightness: 0,
            start_color_x: 20495,
            start_color_y: 21561,
            start_color_temp_mireds: 370,
            start_hue: 0,
            start_saturation: 0,
            target_brightness: 254,
            target_render_brightness: 0,
            target_color_x: 20495,
            target_color_y: 21561,
            target_color_temp_mireds: 370,
            target_hue: 0,
            target_saturation: 0,
        }
    }

    /// Create a state machine that starts physically on.
    pub fn new_powered_on(output: Box<dyn LightOutput>) -> Self {
        let mut state = Self::new(output);
        state.on = true;
        state.render_brightness = state.brightness;
        state.output.set_on(true);
        state.render_output();
        state.sync_transition_targets_to_current();
        state
    }

    /// The complete raw state, as delivered to [`LightOutput::state_update`].
    pub fn light_snapshot(&self) -> LightSnapshot {
        LightSnapshot {
            on: self.on,
            brightness: self.brightness,
            rendered_brightness: if self.on { self.render_brightness } else { 0 },
            color_mode: self.color_mode,
            hue: self.hue,
            saturation: self.saturation,
            enhanced_hue: color::hue_to_enhanced_hue(self.hue),
            color_x: self.color_x,
            color_y: self.color_y,
            color_temp_mireds: self.color_temp_mireds,
        }
    }

    /// Capture all light attributes that this firmware supports in Zigbee scenes.
    pub fn scene_snapshot(&self) -> SceneState {
        SceneState {
            on: Some(self.on),
            brightness: Some(self.brightness),
            color_mode: Some(self.color_mode),
            hue: Some(self.hue),
            saturation: Some(self.saturation),
            enhanced_hue: Some(color::hue_to_enhanced_hue(self.hue)),
            color_x: Some(self.color_x),
            color_y: Some(self.color_y),
            color_temp_mireds: Some(self.color_temp_mireds),
        }
    }

    pub fn apply_scene_state(&mut self, scene: &SceneState) {
        self.apply_scene_state_with_transition(scene, 0);
    }

    pub fn apply_scene_state_with_transition(
        &mut self,
        scene: &SceneState,
        transition_time_tenths: u16,
    ) {
        self.cancel_transition();

        if transition_time_tenths > 0 {
            self.pending_color_x = None;
            self.pending_color_y = None;

            if scene.on == Some(true) && !self.on {
                self.on = true;
                self.output.set_on(true);
                self.render_brightness = 0;
            }

            let final_on = if scene.on == Some(false) {
                Some(false)
            } else {
                None
            };
            let render_target = if scene.on == Some(false) {
                Some(0)
            } else if scene.on == Some(true) || scene.brightness.is_some() {
                Some(scene.brightness.unwrap_or(self.brightness))
            } else {
                None
            };

            self.start_transition_with_render(
                scene.brightness,
                scene.color_x,
                scene.color_y,
                scene.color_temp_mireds,
                scene
                    .enhanced_hue
                    .map(color::enhanced_hue_to_hue)
                    .or(scene.hue),
                scene.saturation,
                render_target,
                final_on,
                transition_time_tenths,
            );

            if let Some(mode) = scene.color_mode {
                // start_transition_with_render auto-detects the mode from the
                // animated fields and has already rendered one frame with it.
                // Re-render only when the explicit mode disagrees (a
                // HueSaturation scene's wire format also carries X/Y, fooling
                // the presence-based auto-detect into XY); an unconditional
                // re-render would send a second identical full-strip frame on
                // every recall.
                if mode != self.color_mode {
                    self.color_mode = mode;
                    self.render_output();
                }
            }

            #[cfg(debug_assertions)]
            self.validate_color_state();
            return;
        }

        if let Some(level) = scene.brightness {
            self.brightness = level.min(254);
        }

        if let Some(x) = scene.color_x {
            self.color_x = x;
            self.color_mode = ColorMode::XY;
            self.pending_color_x = None;
            self.pending_color_y = None;
        }
        if let Some(y) = scene.color_y {
            self.color_y = y;
            self.color_mode = ColorMode::XY;
            self.pending_color_x = None;
            self.pending_color_y = None;
        }

        if let Some(temp) = scene.color_temp_mireds {
            self.color_temp_mireds = temp;
            self.color_mode = ColorMode::ColorTemperature;
            self.pending_color_x = None;
            self.pending_color_y = None;
        }

        if let Some(enhanced_hue) = scene.enhanced_hue {
            self.hue = color::enhanced_hue_to_hue(enhanced_hue);
            self.color_mode = ColorMode::HueSaturation;
            self.pending_color_x = None;
            self.pending_color_y = None;
        } else if let Some(hue) = scene.hue {
            self.hue = hue.min(254);
            self.color_mode = ColorMode::HueSaturation;
            self.pending_color_x = None;
            self.pending_color_y = None;
        }

        if let Some(saturation) = scene.saturation {
            self.saturation = saturation.min(254);
            self.color_mode = ColorMode::HueSaturation;
            self.pending_color_x = None;
            self.pending_color_y = None;
        }

        if let Some(mode) = scene.color_mode {
            self.color_mode = mode;
            if mode != ColorMode::XY {
                self.pending_color_x = None;
                self.pending_color_y = None;
            }
        }

        if let Some(on) = scene.on {
            self.on = on;
            if on {
                self.render_brightness = self.brightness;
                self.output.set_on(true);
            } else {
                self.render_brightness = 0;
            }
        }
        if scene.on.is_none() && self.on && scene.brightness.is_some() {
            self.render_brightness = self.brightness;
        }

        self.render_output();
        if !self.on {
            self.output.set_on(false);
        }
        self.sync_transition_targets_to_current();

        #[cfg(debug_assertions)]
        self.validate_color_state();
    }

    pub fn apply_command(&mut self, cmd: &LightCommand) {
        match cmd {
            LightCommand::On => {
                self.fade_on(crate::light::command::DEFAULT_ON_OFF_TRANSITION_TENTHS);
            }
            LightCommand::Off => {
                self.fade_off(crate::light::command::DEFAULT_ON_OFF_TRANSITION_TENTHS);
            }
            LightCommand::Toggle => {
                if self.on {
                    self.fade_off(crate::light::command::DEFAULT_ON_OFF_TRANSITION_TENTHS);
                } else {
                    self.fade_on(crate::light::command::DEFAULT_ON_OFF_TRANSITION_TENTHS);
                }
            }
            LightCommand::SetLevel {
                level,
                transition_time,
            } => {
                if *level > 0 && !self.on {
                    self.on = true;
                    self.output.set_on(true);
                    self.render_brightness = 0;
                }
                self.start_transition(Some(*level), None, None, None, None, None, *transition_time);
            }
            LightCommand::MoveToColor {
                x,
                y,
                transition_time,
            } => {
                if let Some(x) = x {
                    self.pending_color_x = Some(*x);
                }
                if let Some(y) = y {
                    self.pending_color_y = Some(*y);
                }

                let have_both = self.pending_color_x.is_some() && self.pending_color_y.is_some();
                let command_had_both = x.is_some() && y.is_some();

                if have_both || command_had_both {
                    self.start_transition(
                        None,
                        self.pending_color_x,
                        self.pending_color_y,
                        None,
                        None,
                        None,
                        *transition_time,
                    );
                    self.pending_color_x = None;
                    self.pending_color_y = None;
                }
            }
            LightCommand::MoveToColorTemp {
                mireds,
                transition_time,
            } => {
                self.pending_color_x = None;
                self.pending_color_y = None;
                self.start_transition(
                    None,
                    None,
                    None,
                    Some(*mireds),
                    None,
                    None,
                    *transition_time,
                );
            }
            LightCommand::MoveToHueAndSaturation {
                hue,
                saturation,
                transition_time,
            } => {
                self.pending_color_x = None;
                self.pending_color_y = None;
                self.start_transition(None, None, None, None, *hue, *saturation, *transition_time);
            }
            LightCommand::EnhancedMoveToHueAndSaturation {
                enhanced_hue,
                saturation,
                transition_time,
            } => {
                self.pending_color_x = None;
                self.pending_color_y = None;
                let hue = color::enhanced_hue_to_hue(*enhanced_hue);
                self.start_transition(
                    None,
                    None,
                    None,
                    None,
                    Some(hue),
                    *saturation,
                    *transition_time,
                );
            }
            LightCommand::Identify { duration } => {
                self.pending_color_x = None;
                self.pending_color_y = None;
                if *duration == 0 {
                    if self.identify_blink_count > 0 {
                        self.identify_blink_count = 0;
                        self.output.set_on(self.on);
                    }
                } else {
                    // ZCL spec: blink at 0.5 Hz for duration seconds = 2 half-cycles/s.
                    // u32 math: `duration` can be up to 0xFFFF, so `* 2` overflows u16.
                    let half_cycles = u32::from(*duration) * 2;
                    log::info!(
                        "Identify: {} seconds ({} half-cycles)",
                        duration,
                        half_cycles
                    );
                    self.identify_blink_count = half_cycles;
                    self.identify_blink_phase = false;
                    self.output.set_on(false);
                }
            }
            LightCommand::TriggerEffect { effect_id, .. } => {
                // Reuse the identify blink timer for all visual effects.
                // All effects run at 0.5 Hz (500 ms half-cycle) via the existing identify alarm.
                match effect_id {
                    0xFF => {
                        // StopEffect: cancel immediately and restore light state
                        if self.identify_blink_count > 0 {
                            self.identify_blink_count = 0;
                            self.output.set_on(self.on);
                        }
                    }
                    0xFE => {
                        // FinishEffect: let current identify run to completion
                    }
                    0x00 => {
                        // Blink: ZCL defines it as "light is turned on/off
                        // once" — exactly one cycle (2 half-cycles).
                        self.identify_blink_count = 2;
                        self.identify_blink_phase = false;
                        self.output.set_on(false);
                    }
                    _ => {
                        // Remaining "which light is this?" effects — Breathe
                        // (0x01), Okay (0x02, ZCL: "flash twice"), Channel
                        // Change (0x0B), and unknowns — blink twice
                        // (4 half-cycles at 0.5 Hz ≈ 2 s). The Hue app sends
                        // 0x01 on tap to identify a light; a long animation
                        // just looks like it never stops, and a re-tap
                        // restarts it anyway.
                        self.identify_blink_count = 4;
                        self.identify_blink_phase = false;
                        self.output.set_on(false);
                    }
                }
            }
            LightCommand::StopMoveStep => {
                self.cancel_transition();
                self.pending_color_x = None;
                self.pending_color_y = None;
            }
        }

        #[cfg(debug_assertions)]
        self.validate_color_state();
    }

    fn apply_current_color_at(&mut self, brightness: u8) {
        if !self.on {
            return;
        }

        let (r, g, b) = match self.color_mode {
            ColorMode::XY => color::xy_to_rgb(self.color_x, self.color_y, brightness),
            ColorMode::ColorTemperature => {
                color::scale_rgb(color::mireds_to_rgb(self.color_temp_mireds), brightness)
            }
            ColorMode::HueSaturation => color::hsv_to_rgb(self.hue, self.saturation, brightness),
        };

        self.output.set_rgb(r, g, b);
    }

    fn render_output(&mut self) {
        let brightness = if self.on { self.render_brightness } else { 0 };
        self.output.set_brightness(brightness);
        if brightness == 0 {
            self.output.set_rgb(0, 0, 0);
        } else if self.color_mode == ColorMode::ColorTemperature {
            self.output.set_color_temp(self.color_temp_mireds);
        } else {
            self.apply_current_color_at(brightness);
        }

        // Raw-state observation hook for custom backends (default no-op).
        let snapshot = self.light_snapshot();
        self.output.state_update(&snapshot);
    }

    #[cfg(debug_assertions)]
    fn validate_color_state(&self) {
        match self.color_mode {
            ColorMode::XY => {
                if self.color_x == 0 && self.color_y == 0 {
                    log::warn!("validate: XY mode but both color_x/y are zero");
                }
            }
            ColorMode::ColorTemperature => {
                if self.color_temp_mireds < 153 || self.color_temp_mireds > 500 {
                    log::warn!(
                        "validate: ColorTemperature mireds out of range: {}",
                        self.color_temp_mireds
                    );
                }
            }
            ColorMode::HueSaturation => {}
        }
    }

    // Each argument is an independent, optional ZCL transition target; bundling
    // them into a struct would not improve clarity and would churn every caller.
    #[allow(clippy::too_many_arguments)]
    pub fn start_transition(
        &mut self,
        brightness: Option<u8>,
        color_x: Option<u16>,
        color_y: Option<u16>,
        color_temp: Option<u16>,
        hue: Option<u8>,
        saturation: Option<u8>,
        transition_time_tenths: u16,
    ) {
        self.start_transition_with_render(
            brightness,
            color_x,
            color_y,
            color_temp,
            hue,
            saturation,
            None,
            None,
            transition_time_tenths,
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn start_transition_with_render(
        &mut self,
        brightness: Option<u8>,
        color_x: Option<u16>,
        color_y: Option<u16>,
        color_temp: Option<u16>,
        hue: Option<u8>,
        saturation: Option<u8>,
        render_brightness: Option<u8>,
        final_on: Option<bool>,
        transition_time_tenths: u16,
    ) {
        // Single normalization chokepoint for the ZCL 0-254 domains: every
        // command and scene-transition path funnels through here, so a raw
        // wire value of 255 (reserved in ZCL) can never enter the state fields
        // and later wrap 8-bit scaling math or the enhanced-hue encoding.
        let brightness = brightness.map(|b| b.min(254));
        let hue = hue.map(|h| h.min(254));
        let saturation = saturation.map(|s| s.min(254));
        let render_brightness = render_brightness.map(|b| b.min(254));

        let render_brightness = render_brightness.or_else(|| {
            if brightness.is_some() && self.on {
                brightness
            } else {
                None
            }
        });
        let fields = TransitionFields {
            brightness: brightness.is_some(),
            render_brightness: render_brightness.is_some(),
            color_x: color_x.is_some(),
            color_y: color_y.is_some(),
            color_temp_mireds: color_temp.is_some(),
            hue: hue.is_some(),
            saturation: saturation.is_some(),
        };

        if !fields.any() {
            if let Some(final_on) = final_on {
                self.on = final_on;
                self.output.set_on(final_on);
            }
            return;
        }

        self.cancel_transition();

        if transition_time_tenths == 0 {
            if let Some(b) = brightness {
                self.brightness = b;
            }
            if let Some(b) = render_brightness {
                self.render_brightness = b;
            }
            if let Some(x) = color_x {
                self.color_x = x;
                self.color_mode = ColorMode::XY;
            }
            if let Some(y) = color_y {
                self.color_y = y;
                self.color_mode = ColorMode::XY;
            }
            if let Some(t) = color_temp {
                self.color_temp_mireds = t;
                self.color_mode = ColorMode::ColorTemperature;
            }
            if let Some(h) = hue {
                self.hue = h;
                self.color_mode = ColorMode::HueSaturation;
            }
            if let Some(s) = saturation {
                self.saturation = s;
                self.color_mode = ColorMode::HueSaturation;
            }

            if final_on == Some(true) && !self.on {
                self.on = true;
                self.output.set_on(true);
            }
            self.render_output();
            if final_on == Some(false) {
                self.on = false;
                self.output.set_on(false);
            }
            self.sync_transition_targets_to_current();
            return;
        }

        self.start_brightness = self.brightness;
        self.start_render_brightness = self.render_brightness;
        self.start_color_x = self.color_x;
        self.start_color_y = self.color_y;
        self.start_color_temp_mireds = self.color_temp_mireds;
        self.start_hue = self.hue;
        self.start_saturation = self.saturation;

        self.sync_transition_targets_to_current();

        if let Some(b) = brightness {
            self.target_brightness = b;
        }
        if let Some(b) = render_brightness {
            self.target_render_brightness = b;
        }
        if let Some(x) = color_x {
            self.target_color_x = x;
        }
        if let Some(y) = color_y {
            self.target_color_y = y;
        }
        if let Some(t) = color_temp {
            self.target_color_temp_mireds = t;
        }
        if let Some(h) = hue {
            self.target_hue = h;
        }
        if let Some(s) = saturation {
            self.target_saturation = s;
        }

        if color_x.is_some() || color_y.is_some() {
            self.color_mode = ColorMode::XY;
        } else if color_temp.is_some() {
            self.color_mode = ColorMode::ColorTemperature;
        } else if hue.is_some() || saturation.is_some() {
            self.color_mode = ColorMode::HueSaturation;
        }

        let duration_ms = u32::from(transition_time_tenths) * 100;
        self.transition_duration_ms = duration_ms;
        self.transition_elapsed_ms = 0;
        self.transition_step_interval_ms = Self::step_interval_for_duration(duration_ms);
        self.transition_fields = fields;
        self.transition_final_on = final_on;
        self.transition_active = true;

        self.render_output();
    }

    pub fn transition_step_interval_ms(&self) -> u16 {
        self.transition_step_interval_ms
    }

    pub fn transition_active(&self) -> bool {
        self.transition_active
    }

    pub fn identify_active(&self) -> bool {
        self.identify_blink_count > 0
    }

    /// Advance one identify blink half-cycle (~500 ms). Returns true if more
    /// blinks remain and the caller should schedule another 500 ms alarm.
    #[must_use]
    pub fn step_identify(&mut self) -> bool {
        if self.identify_blink_count == 0 {
            return false;
        }
        self.identify_blink_count -= 1;
        self.identify_blink_phase = !self.identify_blink_phase;
        if self.identify_blink_count == 0 {
            self.output.set_on(self.on);
            false
        } else {
            self.output.set_on(self.identify_blink_phase);
            true
        }
    }

    #[must_use]
    pub fn step_transition(&mut self) -> bool {
        if !self.transition_active {
            return false;
        }

        if self.transition_duration_ms == 0 {
            self.cancel_transition();
            return false;
        }

        let step_ms = u32::from(self.transition_step_interval_ms);
        self.transition_elapsed_ms =
            (self.transition_elapsed_ms + step_ms).min(self.transition_duration_ms);

        if self.transition_elapsed_ms >= self.transition_duration_ms {
            self.apply_transition_targets();
            let final_on = self.transition_final_on.take();
            self.transition_active = false;
            self.transition_duration_ms = 0;
            self.transition_elapsed_ms = 0;
            self.transition_fields = TransitionFields::default();
            self.sync_transition_targets_to_current();
            self.render_output();
            if let Some(final_on) = final_on {
                self.on = final_on;
                self.output.set_on(final_on);
            }
        } else {
            // Integer progress in units of 1/1_000_000 to avoid f32 precision loss.
            let progress_micro = (self.transition_elapsed_ms as u64 * 1_000_000
                / self.transition_duration_ms as u64) as u32;
            self.apply_transition_progress(progress_micro);
            self.render_output();
        }

        #[cfg(debug_assertions)]
        self.validate_color_state();

        self.transition_active
    }

    fn step_interval_for_duration(duration_ms: u32) -> u16 {
        if duration_ms <= 300 {
            20
        } else {
            33
        }
    }

    fn fade_on(&mut self, transition_time_tenths: u16) {
        if !self.on {
            self.on = true;
            self.output.set_on(true);
            self.render_brightness = 0;
        }

        let target = self.brightness.max(1);
        self.start_transition_with_render(
            None,
            None,
            None,
            None,
            None,
            None,
            Some(target),
            None,
            transition_time_tenths,
        );
    }

    fn fade_off(&mut self, transition_time_tenths: u16) {
        if !self.on {
            return;
        }

        self.start_transition_with_render(
            None,
            None,
            None,
            None,
            None,
            None,
            Some(0),
            Some(false),
            transition_time_tenths,
        );
    }

    fn cancel_transition(&mut self) {
        self.transition_active = false;
        self.transition_duration_ms = 0;
        self.transition_elapsed_ms = 0;
        self.transition_fields = TransitionFields::default();
        self.transition_final_on = None;
        self.sync_transition_targets_to_current();
    }

    fn sync_transition_targets_to_current(&mut self) {
        self.target_brightness = self.brightness;
        self.target_render_brightness = self.render_brightness;
        self.target_color_x = self.color_x;
        self.target_color_y = self.color_y;
        self.target_color_temp_mireds = self.color_temp_mireds;
        self.target_hue = self.hue;
        self.target_saturation = self.saturation;
    }

    fn apply_transition_targets(&mut self) {
        let fields = self.transition_fields;
        if fields.brightness {
            self.brightness = self.target_brightness;
        }
        if fields.render_brightness {
            self.render_brightness = self.target_render_brightness;
        }
        if fields.color_x {
            self.color_x = self.target_color_x;
        }
        if fields.color_y {
            self.color_y = self.target_color_y;
        }
        if fields.color_temp_mireds {
            self.color_temp_mireds = self.target_color_temp_mireds;
        }
        if fields.hue {
            self.hue = self.target_hue;
        }
        if fields.saturation {
            self.saturation = self.target_saturation;
        }
    }

    fn apply_transition_progress(&mut self, progress_micro: u32) {
        let fields = self.transition_fields;
        if fields.brightness {
            self.brightness = Self::lerp_u8(
                self.start_brightness,
                self.target_brightness,
                progress_micro,
            );
        }
        if fields.render_brightness {
            self.render_brightness = Self::lerp_u8(
                self.start_render_brightness,
                self.target_render_brightness,
                progress_micro,
            );
        }
        if fields.color_x {
            self.color_x = Self::lerp_u16(self.start_color_x, self.target_color_x, progress_micro);
        }
        if fields.color_y {
            self.color_y = Self::lerp_u16(self.start_color_y, self.target_color_y, progress_micro);
        }
        if fields.color_temp_mireds {
            self.color_temp_mireds = Self::lerp_u16(
                self.start_color_temp_mireds,
                self.target_color_temp_mireds,
                progress_micro,
            );
        }
        if fields.hue {
            self.hue = Self::lerp_hue(self.start_hue, self.target_hue, progress_micro);
        }
        if fields.saturation {
            self.saturation = Self::lerp_u8(
                self.start_saturation,
                self.target_saturation,
                progress_micro,
            );
        }
    }

    /// Round-to-nearest integer linear interpolation. `progress_micro` is in
    /// the range 0..=1_000_000 (0 = start, 1_000_000 = target).
    fn lerp_u8(start: u8, target: u8, progress_micro: u32) -> u8 {
        let s = start as u32;
        let t = target as u32;
        if t >= s {
            (s + ((t - s) * progress_micro + 500_000) / 1_000_000) as u8
        } else {
            (s - ((s - t) * progress_micro + 500_000) / 1_000_000) as u8
        }
    }

    /// Round-to-nearest integer linear interpolation for u16.
    /// Uses u64 internally to avoid overflow (max diff 65535 × 1_000_000).
    fn lerp_u16(start: u16, target: u16, progress_micro: u32) -> u16 {
        let s = start as u64;
        let t = target as u64;
        let p = progress_micro as u64;
        if t >= s {
            (s + ((t - s) * p + 500_000) / 1_000_000) as u16
        } else {
            (s - ((s - t) * p + 500_000) / 1_000_000) as u16
        }
    }

    /// Wrap-aware hue interpolation on the circular ZCL hue wheel.
    ///
    /// ZCL `CurrentHue` runs 0..=254 and wraps (254 is adjacent to 0, modulus
    /// 255). A plain linear lerp from 240 to 10 would sweep the long way
    /// through green; real Hue bulbs take the shortest arc, so we do too.
    fn lerp_hue(start: u8, target: u8, progress_micro: u32) -> u8 {
        const WHEEL: i64 = 255;
        let s = i64::from(start);
        let t = i64::from(target);

        // Signed shortest-arc delta in (-127..=127].
        let mut delta = (t - s).rem_euclid(WHEEL);
        if delta > WHEEL / 2 {
            delta -= WHEEL;
        }

        let p = i64::from(progress_micro);
        let offset = if delta >= 0 {
            (delta * p + 500_000) / 1_000_000
        } else {
            -((-delta * p + 500_000) / 1_000_000)
        };

        (s + offset).rem_euclid(WHEEL) as u8
    }
}

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

    #[test]
    fn lerp_hue_endpoints_are_exact() {
        assert_eq!(LightState::lerp_hue(240, 10, 0), 240);
        assert_eq!(LightState::lerp_hue(240, 10, 1_000_000), 10);
    }

    #[test]
    fn lerp_hue_takes_the_shortest_arc_across_the_wrap() {
        // 240 -> 10 is 25 steps forward across the 254/0 seam, not 230 steps
        // backward through the middle of the wheel. A regression to a plain
        // linear lerp would land near 125 (the long way); the wrap-aware path
        // stays up in the 240s/low single digits.
        let mid = LightState::lerp_hue(240, 10, 500_000);
        assert!(
            !(15..=240).contains(&mid),
            "midpoint {mid} left the wrap region — long-way regression"
        );
        assert!(
            !(60..=195).contains(&mid),
            "midpoint {mid} is in the far half of the wheel"
        );

        // Same seam from the other side: 10 -> 240 goes 25 steps backward.
        let mid_rev = LightState::lerp_hue(10, 240, 500_000);
        assert!(
            !(15..=240).contains(&mid_rev),
            "reverse midpoint {mid_rev} left the wrap region"
        );
    }
}