tasmor_lib 0.6.0

Rust library to control Tasmota devices via MQTT and HTTP
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
// SPDX-License-Identifier: MPL-2.0
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Callback management for device state subscriptions.
//!
//! This module provides the core types for managing subscription callbacks:
//!
//! - [`SubscriptionId`] - Unique identifier for unsubscribing
//! - [`CallbackRegistry`] - Internal registry for storing and dispatching callbacks

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use parking_lot::RwLock;

use crate::state::{DeviceState, StateChange};
use crate::types::{ColorTemperature, Dimmer, HsbColor, PowerState, Scheme};

/// Unique identifier for a subscription.
///
/// This ID is returned when creating a subscription and can be used to
/// unsubscribe later. IDs are unique within a device's lifetime.
///
/// # Examples
///
/// ```no_run
/// use tasmor_lib::MqttBroker;
/// use tasmor_lib::subscription::Subscribable;
///
/// # async fn example() -> tasmor_lib::Result<()> {
/// let broker = MqttBroker::builder()
///     .host("192.168.1.50")
///     .build()
///     .await?;
///
/// let (device, _) = broker.device("tasmota_device")
///     .build()
///     .await?;
///
/// let sub_id = device.on_power_changed(|idx, state| {
///     println!("Relay {idx} changed to {state:?}");
/// });
///
/// // Later, unsubscribe
/// device.unsubscribe(sub_id);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SubscriptionId(u64);

impl SubscriptionId {
    /// Creates a new subscription ID with the given value.
    #[must_use]
    pub(crate) fn new(id: u64) -> Self {
        Self(id)
    }

    /// Returns the raw ID value.
    #[must_use]
    pub fn value(&self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for SubscriptionId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Sub({})", self.0)
    }
}

/// Type alias for power state callbacks.
type PowerCallback = Arc<dyn Fn(u8, PowerState) + Send + Sync>;

/// Type alias for dimmer callbacks.
type DimmerCallback = Arc<dyn Fn(Dimmer) + Send + Sync>;

/// Type alias for HSB color callbacks.
type HsbColorCallback = Arc<dyn Fn(HsbColor) + Send + Sync>;

/// Type alias for color temperature callbacks.
type ColorTempCallback = Arc<dyn Fn(ColorTemperature) + Send + Sync>;

/// Type alias for scheme callbacks.
type SchemeCallback = Arc<dyn Fn(Scheme) + Send + Sync>;

/// Type alias for energy callbacks.
type EnergyCallback = Arc<dyn Fn(EnergyData) + Send + Sync>;

/// Type alias for connected callbacks (receives initial state).
type ConnectedCallback = Arc<dyn Fn(&DeviceState) + Send + Sync>;

/// Type alias for disconnected callbacks.
type DisconnectedCallback = Arc<dyn Fn() + Send + Sync>;

/// Type alias for reconnected callbacks (called after broker reconnection).
type ReconnectedCallback = Arc<dyn Fn() + Send + Sync>;

/// Type alias for generic state change callbacks.
type StateChangedCallback = Arc<dyn Fn(&StateChange) + Send + Sync>;

/// Energy data passed to energy callbacks.
#[derive(Debug, Clone)]
pub struct EnergyData {
    /// Power consumption in Watts.
    pub power: Option<f32>,
    /// Voltage in Volts.
    pub voltage: Option<f32>,
    /// Current in Amperes.
    pub current: Option<f32>,
    /// Energy consumed today in kWh.
    pub energy_today: Option<f32>,
    /// Total energy consumed in kWh.
    pub energy_total: Option<f32>,
    /// AC frequency in Hz. `None` for DC monitors or devices that do not report it.
    pub frequency: Option<f32>,
}

/// Registry for managing device subscription callbacks.
///
/// This is an internal type used by devices to store and dispatch callbacks.
/// It uses thread-safe interior mutability via `parking_lot::RwLock` for
/// high performance in async contexts.
///
/// # Thread Safety
///
/// The registry is fully thread-safe and can be accessed from multiple tasks
/// concurrently. Callbacks are wrapped in `Arc` so they can be cloned cheaply.
pub struct CallbackRegistry {
    /// Counter for generating unique subscription IDs.
    next_id: AtomicU64,
    /// Power state change callbacks.
    power_callbacks: RwLock<HashMap<SubscriptionId, PowerCallback>>,
    /// Dimmer change callbacks.
    dimmer_callbacks: RwLock<HashMap<SubscriptionId, DimmerCallback>>,
    /// HSB color change callbacks.
    hsb_color_callbacks: RwLock<HashMap<SubscriptionId, HsbColorCallback>>,
    /// Color temperature change callbacks.
    color_temp_callbacks: RwLock<HashMap<SubscriptionId, ColorTempCallback>>,
    /// Scheme change callbacks.
    scheme_callbacks: RwLock<HashMap<SubscriptionId, SchemeCallback>>,
    /// Energy update callbacks.
    energy_callbacks: RwLock<HashMap<SubscriptionId, EnergyCallback>>,
    /// Connected callbacks (called when device becomes available).
    connected_callbacks: RwLock<HashMap<SubscriptionId, ConnectedCallback>>,
    /// Disconnected callbacks (called when device becomes unavailable).
    disconnected_callbacks: RwLock<HashMap<SubscriptionId, DisconnectedCallback>>,
    /// Reconnected callbacks (called when broker connection is restored).
    reconnected_callbacks: RwLock<HashMap<SubscriptionId, ReconnectedCallback>>,
    /// Generic state change callbacks (receives all changes).
    state_changed_callbacks: RwLock<HashMap<SubscriptionId, StateChangedCallback>>,
}

impl CallbackRegistry {
    /// Creates a new empty callback registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            next_id: AtomicU64::new(1),
            power_callbacks: RwLock::new(HashMap::new()),
            dimmer_callbacks: RwLock::new(HashMap::new()),
            hsb_color_callbacks: RwLock::new(HashMap::new()),
            color_temp_callbacks: RwLock::new(HashMap::new()),
            scheme_callbacks: RwLock::new(HashMap::new()),
            energy_callbacks: RwLock::new(HashMap::new()),
            connected_callbacks: RwLock::new(HashMap::new()),
            disconnected_callbacks: RwLock::new(HashMap::new()),
            reconnected_callbacks: RwLock::new(HashMap::new()),
            state_changed_callbacks: RwLock::new(HashMap::new()),
        }
    }

    /// Generates a new unique subscription ID.
    fn next_id(&self) -> SubscriptionId {
        SubscriptionId::new(self.next_id.fetch_add(1, Ordering::Relaxed))
    }

    // =========================================================================
    // Registration methods
    // =========================================================================

    /// Registers a callback for power state changes.
    ///
    /// The callback receives the relay index (1-8) and the new power state.
    pub fn on_power_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(u8, PowerState) + Send + Sync + 'static,
    {
        let id = self.next_id();
        self.power_callbacks.write().insert(id, Arc::new(callback));
        id
    }

    /// Registers a callback for dimmer changes.
    pub fn on_dimmer_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(Dimmer) + Send + Sync + 'static,
    {
        let id = self.next_id();
        self.dimmer_callbacks.write().insert(id, Arc::new(callback));
        id
    }

    /// Registers a callback for HSB color changes.
    pub fn on_hsb_color_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(HsbColor) + Send + Sync + 'static,
    {
        let id = self.next_id();
        self.hsb_color_callbacks
            .write()
            .insert(id, Arc::new(callback));
        id
    }

    /// Registers a callback for color temperature changes.
    pub fn on_color_temp_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(ColorTemperature) + Send + Sync + 'static,
    {
        let id = self.next_id();
        self.color_temp_callbacks
            .write()
            .insert(id, Arc::new(callback));
        id
    }

    /// Registers a callback for scheme changes.
    pub fn on_scheme_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(Scheme) + Send + Sync + 'static,
    {
        let id = self.next_id();
        self.scheme_callbacks.write().insert(id, Arc::new(callback));
        id
    }

    /// Registers a callback for energy changes.
    pub fn on_energy_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(EnergyData) + Send + Sync + 'static,
    {
        let id = self.next_id();
        self.energy_callbacks.write().insert(id, Arc::new(callback));
        id
    }

    /// Registers a callback for when the device becomes connected.
    ///
    /// The callback receives the initial device state.
    pub fn on_connected<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(&DeviceState) + Send + Sync + 'static,
    {
        let id = self.next_id();
        self.connected_callbacks
            .write()
            .insert(id, Arc::new(callback));
        id
    }

    /// Registers a callback for when the device becomes disconnected.
    pub fn on_disconnected<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn() + Send + Sync + 'static,
    {
        let id = self.next_id();
        self.disconnected_callbacks
            .write()
            .insert(id, Arc::new(callback));
        id
    }

    /// Registers a callback for when the broker connection is restored.
    ///
    /// This callback is triggered after the MQTT broker reconnects and topics
    /// are automatically resubscribed. Unlike `on_connected`, this callback
    /// does not receive a device state since the library does not retain state.
    ///
    /// After receiving this callback, the application should call `query_state()`
    /// to refresh the device state if needed, as the state may have changed
    /// during the disconnection period.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use tasmor_lib::MqttBroker;
    /// use tasmor_lib::subscription::Subscribable;
    ///
    /// # async fn example() -> tasmor_lib::Result<()> {
    /// let broker = MqttBroker::builder()
    ///     .host("192.168.1.50")
    ///     .build()
    ///     .await?;
    ///
    /// let (device, _) = broker.device("tasmota_device")
    ///     .build()
    ///     .await?;
    ///
    /// device.on_reconnected(|| {
    ///     println!("Broker reconnected! Consider calling query_state()");
    /// });
    /// # Ok(())
    /// # }
    /// ```
    pub fn on_reconnected<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn() + Send + Sync + 'static,
    {
        let id = self.next_id();
        self.reconnected_callbacks
            .write()
            .insert(id, Arc::new(callback));
        id
    }

    /// Registers a callback for all state changes.
    ///
    /// This is useful for logging or debugging, as it receives every change.
    pub fn on_state_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(&StateChange) + Send + Sync + 'static,
    {
        let id = self.next_id();
        self.state_changed_callbacks
            .write()
            .insert(id, Arc::new(callback));
        id
    }

    // =========================================================================
    // Unsubscription
    // =========================================================================

    /// Unregisters a callback by its subscription ID.
    ///
    /// Returns `true` if a callback was found and removed.
    pub fn unsubscribe(&self, id: SubscriptionId) -> bool {
        // Try each callback map until we find and remove the ID
        if self.power_callbacks.write().remove(&id).is_some() {
            return true;
        }
        if self.dimmer_callbacks.write().remove(&id).is_some() {
            return true;
        }
        if self.hsb_color_callbacks.write().remove(&id).is_some() {
            return true;
        }
        if self.color_temp_callbacks.write().remove(&id).is_some() {
            return true;
        }
        if self.scheme_callbacks.write().remove(&id).is_some() {
            return true;
        }
        if self.energy_callbacks.write().remove(&id).is_some() {
            return true;
        }
        if self.connected_callbacks.write().remove(&id).is_some() {
            return true;
        }
        if self.disconnected_callbacks.write().remove(&id).is_some() {
            return true;
        }
        if self.reconnected_callbacks.write().remove(&id).is_some() {
            return true;
        }
        if self.state_changed_callbacks.write().remove(&id).is_some() {
            return true;
        }
        false
    }

    /// Clears all callbacks.
    pub fn clear(&self) {
        self.power_callbacks.write().clear();
        self.dimmer_callbacks.write().clear();
        self.hsb_color_callbacks.write().clear();
        self.color_temp_callbacks.write().clear();
        self.scheme_callbacks.write().clear();
        self.energy_callbacks.write().clear();
        self.connected_callbacks.write().clear();
        self.disconnected_callbacks.write().clear();
        self.reconnected_callbacks.write().clear();
        self.state_changed_callbacks.write().clear();
    }

    // =========================================================================
    // Dispatch methods
    // =========================================================================

    /// Dispatches a state change to relevant callbacks.
    ///
    /// This method calls all registered callbacks that match the change type.
    /// Callbacks are called synchronously in an arbitrary order.
    pub fn dispatch(&self, change: &StateChange) {
        // Always dispatch to generic state_changed callbacks
        {
            let callbacks = self.state_changed_callbacks.read();
            for callback in callbacks.values() {
                callback(change);
            }
        }

        // Dispatch to specific callbacks based on change type
        match change {
            StateChange::Power { index, state } => {
                let callbacks = self.power_callbacks.read();
                for callback in callbacks.values() {
                    callback(*index, *state);
                }
            }
            StateChange::Dimmer(dimmer) => {
                let callbacks = self.dimmer_callbacks.read();
                for callback in callbacks.values() {
                    callback(*dimmer);
                }
            }
            StateChange::HsbColor(color) => {
                let callbacks = self.hsb_color_callbacks.read();
                for callback in callbacks.values() {
                    callback(*color);
                }
            }
            StateChange::ColorTemperature(ct) => {
                let callbacks = self.color_temp_callbacks.read();
                for callback in callbacks.values() {
                    callback(*ct);
                }
            }
            StateChange::Scheme(scheme) => {
                let callbacks = self.scheme_callbacks.read();
                for callback in callbacks.values() {
                    callback(*scheme);
                }
            }
            StateChange::WakeupDuration(_)
            | StateChange::FadeEnabled(_)
            | StateChange::FadeDuration(_) => {
                // These have no specific callbacks; changes are captured
                // by generic state_changed callbacks
            }
            StateChange::Energy {
                power,
                voltage,
                current,
                energy_today,
                energy_total,
                frequency,
                ..
            } => {
                let data = EnergyData {
                    power: *power,
                    voltage: *voltage,
                    current: *current,
                    energy_today: *energy_today,
                    energy_total: *energy_total,
                    frequency: *frequency,
                };
                let callbacks = self.energy_callbacks.read();
                for callback in callbacks.values() {
                    callback(data.clone());
                }
            }
            StateChange::Batch(changes) => {
                // Recursively dispatch each change in the batch
                for nested_change in changes {
                    self.dispatch(nested_change);
                }
            }
        }
    }

    /// Dispatches the connected event with the initial device state.
    pub fn dispatch_connected(&self, state: &DeviceState) {
        let callbacks = self.connected_callbacks.read();
        for callback in callbacks.values() {
            callback(state);
        }
    }

    /// Dispatches the disconnected event.
    pub fn dispatch_disconnected(&self) {
        let callbacks = self.disconnected_callbacks.read();
        for callback in callbacks.values() {
            callback();
        }
    }

    /// Dispatches the reconnected event.
    ///
    /// Called when the MQTT broker connection is restored after a disconnection.
    pub fn dispatch_reconnected(&self) {
        let callbacks = self.reconnected_callbacks.read();
        for callback in callbacks.values() {
            callback();
        }
    }

    // =========================================================================
    // Statistics
    // =========================================================================

    /// Returns the total number of registered callbacks.
    #[must_use]
    pub fn callback_count(&self) -> usize {
        self.power_callbacks.read().len()
            + self.dimmer_callbacks.read().len()
            + self.hsb_color_callbacks.read().len()
            + self.color_temp_callbacks.read().len()
            + self.scheme_callbacks.read().len()
            + self.energy_callbacks.read().len()
            + self.connected_callbacks.read().len()
            + self.disconnected_callbacks.read().len()
            + self.reconnected_callbacks.read().len()
            + self.state_changed_callbacks.read().len()
    }

    /// Returns `true` if there are no registered callbacks.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.callback_count() == 0
    }
}

impl Default for CallbackRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for CallbackRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CallbackRegistry")
            .field("callback_count", &self.callback_count())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::AtomicU32;

    #[test]
    fn subscription_id_display() {
        let id = SubscriptionId::new(42);
        assert_eq!(id.to_string(), "Sub(42)");
    }

    #[test]
    fn subscription_id_equality() {
        let id1 = SubscriptionId::new(1);
        let id2 = SubscriptionId::new(1);
        let id3 = SubscriptionId::new(2);

        assert_eq!(id1, id2);
        assert_ne!(id1, id3);
    }

    #[test]
    fn subscription_id_hash() {
        use std::collections::HashSet;

        let mut set = HashSet::new();
        set.insert(SubscriptionId::new(1));
        set.insert(SubscriptionId::new(2));
        set.insert(SubscriptionId::new(1)); // Duplicate

        assert_eq!(set.len(), 2);
    }

    #[test]
    fn registry_new_is_empty() {
        let registry = CallbackRegistry::new();
        assert!(registry.is_empty());
        assert_eq!(registry.callback_count(), 0);
    }

    #[test]
    fn registry_power_callback() {
        let registry = CallbackRegistry::new();
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        let id = registry.on_power_changed(move |_idx, _state| {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        });

        assert!(!registry.is_empty());
        assert_eq!(registry.callback_count(), 1);

        // Dispatch a power change
        registry.dispatch(&StateChange::power(1, PowerState::On));
        assert_eq!(counter.load(Ordering::SeqCst), 1);

        // Unsubscribe
        assert!(registry.unsubscribe(id));
        assert!(registry.is_empty());

        // Dispatch again - counter should not change
        registry.dispatch(&StateChange::power(1, PowerState::Off));
        assert_eq!(counter.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn registry_dimmer_callback() {
        let registry = CallbackRegistry::new();
        let received = Arc::new(RwLock::new(None::<Dimmer>));
        let received_clone = received.clone();

        registry.on_dimmer_changed(move |dimmer| {
            *received_clone.write() = Some(dimmer);
        });

        let dimmer = Dimmer::new(75).unwrap();
        registry.dispatch(&StateChange::Dimmer(dimmer));

        assert_eq!(*received.read(), Some(dimmer));
    }

    #[test]
    fn registry_energy_changed_callback() {
        let registry = CallbackRegistry::new();
        let received = Arc::new(RwLock::new(None::<EnergyData>));
        let received_clone = received.clone();

        let id = registry.on_energy_changed(move |data| {
            *received_clone.write() = Some(data);
        });

        assert!(!registry.is_empty());
        assert_eq!(registry.callback_count(), 1);

        // Dispatch an energy change
        registry.dispatch(&StateChange::Energy {
            power: Some(150.0),
            voltage: Some(230.0),
            current: Some(0.65),
            power_factor: None,
            apparent_power: None,
            reactive_power: None,
            energy_today: None,
            energy_yesterday: None,
            energy_total: None,
            total_start_time: None,
            frequency: None,
        });

        let received_data = received.read().clone();
        assert!(received_data.is_some());
        let data = received_data.unwrap();
        assert_eq!(data.power, Some(150.0));
        assert_eq!(data.voltage, Some(230.0));

        // Unsubscribe
        assert!(registry.unsubscribe(id));
        assert!(registry.is_empty());
    }

    #[test]
    fn registry_state_changed_callback() {
        let registry = CallbackRegistry::new();
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        registry.on_state_changed(move |_change| {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        });

        // Different types of changes all trigger the generic callback
        registry.dispatch(&StateChange::power_on());
        registry.dispatch(&StateChange::Dimmer(Dimmer::MAX));
        registry.dispatch(&StateChange::HsbColor(HsbColor::red()));

        assert_eq!(counter.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn registry_batch_dispatch() {
        let registry = CallbackRegistry::new();
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        registry.on_state_changed(move |_| {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        });

        let batch = StateChange::batch(vec![
            StateChange::power_on(),
            StateChange::Dimmer(Dimmer::new(50).unwrap()),
        ]);

        registry.dispatch(&batch);

        // Should be called for batch + each item = 3
        assert_eq!(counter.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn registry_multiple_callbacks_same_type() {
        let registry = CallbackRegistry::new();
        let counter1 = Arc::new(AtomicU32::new(0));
        let counter2 = Arc::new(AtomicU32::new(0));
        let c1 = counter1.clone();
        let c2 = counter2.clone();

        registry.on_power_changed(move |_, _| {
            c1.fetch_add(1, Ordering::SeqCst);
        });
        registry.on_power_changed(move |_, _| {
            c2.fetch_add(1, Ordering::SeqCst);
        });

        registry.dispatch(&StateChange::power_on());

        assert_eq!(counter1.load(Ordering::SeqCst), 1);
        assert_eq!(counter2.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn registry_unsubscribe_nonexistent() {
        let registry = CallbackRegistry::new();
        let fake_id = SubscriptionId::new(999);

        assert!(!registry.unsubscribe(fake_id));
    }

    #[test]
    fn registry_clear() {
        let registry = CallbackRegistry::new();

        registry.on_power_changed(|_, _| {});
        registry.on_dimmer_changed(|_| {});
        registry.on_connected(|_| {});

        assert_eq!(registry.callback_count(), 3);

        registry.clear();
        assert!(registry.is_empty());
    }

    #[test]
    fn registry_connected_callback() {
        let registry = CallbackRegistry::new();
        let was_called = Arc::new(AtomicU32::new(0));
        let was_called_clone = was_called.clone();

        registry.on_connected(move |_state| {
            was_called_clone.fetch_add(1, Ordering::SeqCst);
        });

        registry.dispatch_connected(&DeviceState::new());
        assert_eq!(was_called.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn registry_disconnected_callback() {
        let registry = CallbackRegistry::new();
        let was_called = Arc::new(AtomicU32::new(0));
        let was_called_clone = was_called.clone();

        registry.on_disconnected(move || {
            was_called_clone.fetch_add(1, Ordering::SeqCst);
        });

        registry.dispatch_disconnected();
        assert_eq!(was_called.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn registry_reconnected_callback() {
        let registry = CallbackRegistry::new();
        let was_called = Arc::new(AtomicU32::new(0));
        let was_called_clone = was_called.clone();

        registry.on_reconnected(move || {
            was_called_clone.fetch_add(1, Ordering::SeqCst);
        });

        registry.dispatch_reconnected();
        assert_eq!(was_called.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn registry_reconnected_multiple_callbacks() {
        let registry = CallbackRegistry::new();
        let counter = Arc::new(AtomicU32::new(0));
        let c1 = counter.clone();
        let c2 = counter.clone();

        registry.on_reconnected(move || {
            c1.fetch_add(1, Ordering::SeqCst);
        });
        registry.on_reconnected(move || {
            c2.fetch_add(1, Ordering::SeqCst);
        });

        registry.dispatch_reconnected();
        assert_eq!(counter.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn registry_unique_ids() {
        let registry = CallbackRegistry::new();

        let id1 = registry.on_power_changed(|_, _| {});
        let id2 = registry.on_dimmer_changed(|_| {});
        let id3 = registry.on_connected(|_| {});

        assert_ne!(id1, id2);
        assert_ne!(id2, id3);
        assert_ne!(id1, id3);
    }

    #[test]
    fn registry_debug() {
        let registry = CallbackRegistry::new();
        registry.on_power_changed(|_, _| {});

        let debug = format!("{registry:?}");
        assert!(debug.contains("CallbackRegistry"));
        assert!(debug.contains("callback_count"));
    }

    #[test]
    fn energy_data_debug() {
        let data = EnergyData {
            power: Some(100.0),
            voltage: Some(230.0),
            current: Some(0.5),
            energy_today: Some(1.5),
            energy_total: Some(150.0),
            frequency: None,
        };

        let debug = format!("{data:?}");
        assert!(debug.contains("EnergyData"));
        assert!(debug.contains("100.0"));
    }
}