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
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
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
// 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/.

//! High-level device abstraction for Tasmota devices.
//!
//! This module provides a unified API for interacting with Tasmota devices
//! regardless of the underlying protocol (HTTP or MQTT).
//!
//! # Protocol Differences
//!
//! ## HTTP Devices
//!
//! HTTP devices are stateless - each command is an independent HTTP request.
//! They do not support real-time event subscriptions.
//!
//! ```no_run
//! use tasmor_lib::Device;
//!
//! # async fn example() -> tasmor_lib::Result<()> {
//! let (device, _initial_state) = Device::http("192.168.1.100")
//!     .with_credentials("admin", "password")
//!     .build()
//!     .await?;
//!
//! device.power_on().await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## MQTT Devices
//!
//! MQTT devices maintain a persistent connection through a broker and support
//! real-time event subscriptions via the [`Subscribable`](crate::subscription::Subscribable) trait.
//!
//! ```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, _initial_state) = broker.device("tasmota_bedroom")
//!     .build()
//!     .await?;
//!
//! // MQTT devices support subscriptions
//! device.on_power_changed(|index, state| {
//!     println!("Power {index} is now {:?}", state);
//! });
//!
//! device.power_on().await?;
//! # Ok(())
//! # }
//! ```

#[cfg(feature = "mqtt")]
mod broker_device_builder;
#[cfg(feature = "http")]
mod http_builder;

// Builders are used internally (Device::http, broker.device) and returned to users.
// They're pub(crate) because users access them via return types, not direct imports.
#[cfg(feature = "mqtt")]
pub(crate) use broker_device_builder::BrokerDeviceBuilder;
#[cfg(feature = "http")]
pub(crate) use http_builder::HttpDeviceBuilder;

use std::sync::Arc;

use crate::capabilities::Capabilities;
use crate::command::{
    ColorTemperatureCommand, Command, DimmerCommand, EnergyCommand, FadeCommand,
    FadeDurationCommand, HsbColorCommand, PowerCommand, SchemeCommand, StartupFadeCommand,
    StatusCommand, WakeupDurationCommand,
};
use crate::error::{DeviceError, Error};
#[cfg(feature = "http")]
use crate::protocol::HttpClient;
use crate::protocol::{CommandResponse, Protocol};
use crate::response::{
    ColorTemperatureResponse, DimmerResponse, EnergyResponse, FadeDurationResponse, FadeResponse,
    HsbColorResponse, PowerResponse, RgbColorResponse, SchemeResponse, StartupFadeResponse,
    StatusResponse, WakeupDurationResponse,
};
use crate::state::DeviceState;
use crate::subscription::CallbackRegistry;
use crate::types::{
    ColorTemperature, Dimmer, FadeDuration, HsbColor, PowerIndex, PowerState, RgbColor, Scheme,
    WakeupDuration,
};

/// A Tasmota device that can be controlled via HTTP or MQTT.
///
/// The `Device` struct provides a high-level API for controlling Tasmota devices,
/// abstracting away the underlying protocol details.
///
/// # Type Parameter
///
/// The type parameter `P` determines the underlying protocol:
/// - `HttpClient` for HTTP devices (no subscriptions)
/// - `SharedMqttClient` for MQTT devices (supports subscriptions)
///
/// # Thread Safety
///
/// `Device<P>` is `Send + Sync` when the protocol `P` is `Send + Sync`.
/// Both `HttpClient` and `SharedMqttClient` are `Send + Sync`, so devices can be
/// safely shared across threads and used in async contexts with Tokio.
///
/// ```
/// use tasmor_lib::Device;
/// use tasmor_lib::protocol::HttpClient;
///
/// fn assert_send_sync<T: Send + Sync>() {}
/// assert_send_sync::<Device<HttpClient>>();
/// ```
///
/// # Cloning
///
/// `Device<P>` implements [`Clone`] for any protocol `P`. Cloning a device
/// creates a new handle to the **same underlying connection and callbacks**.
/// This is useful for sharing a device across multiple async tasks:
///
/// ```
/// use tasmor_lib::Device;
/// use tasmor_lib::protocol::{HttpClient, SharedMqttClient};
///
/// fn assert_clone<T: Clone>() {}
/// assert_clone::<Device<HttpClient>>();
/// assert_clone::<Device<SharedMqttClient>>();
/// ```
///
/// All clones share:
/// - The same protocol connection (via `Arc`)
/// - The same callback registry (via `Arc`)
/// - The same device capabilities
///
/// This follows the pattern used by other Rust networking libraries like
/// `reqwest::Client` and `rumqttc::AsyncClient`.
///
/// # Creating a Device
///
/// Use [`Device::http`] for HTTP devices or [`crate::MqttBroker::device`] for MQTT devices:
///
/// ```no_run
/// use tasmor_lib::{Device, Capabilities};
///
/// # async fn example() -> tasmor_lib::Result<()> {
/// // HTTP device with auto-detection
/// let (device, _initial_state) = Device::http("192.168.1.100")
///     .build()
///     .await?;
///
/// // HTTP device with manual capabilities
/// let (device, _initial_state) = Device::http("192.168.1.100")
///     .with_capabilities(Capabilities::rgbcct_light())
///     .build_without_probe()
///     .await?;
/// # Ok(())
/// # }
/// ```
// Note: Clone and Debug are implemented manually below to avoid requiring
// P: Clone and P: Debug bounds. Since all fields use Arc<P>, we only need
// P: Protocol. This follows the pattern used by reqwest::Client, rumqttc::AsyncClient.
pub struct Device<P: Protocol> {
    protocol: Arc<P>,
    capabilities: Capabilities,
    callbacks: Arc<CallbackRegistry>,
}

impl<P: Protocol> Clone for Device<P> {
    fn clone(&self) -> Self {
        Self {
            protocol: Arc::clone(&self.protocol),
            capabilities: self.capabilities.clone(),
            callbacks: Arc::clone(&self.callbacks),
        }
    }
}

impl<P: Protocol> std::fmt::Debug for Device<P> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Device")
            .field("capabilities", &self.capabilities)
            .finish_non_exhaustive()
    }
}

impl<P: Protocol> Device<P> {
    /// Creates a new device with the specified protocol and capabilities.
    pub(crate) fn new(protocol: P, capabilities: Capabilities) -> Self {
        Self {
            protocol: Arc::new(protocol),
            capabilities,
            callbacks: Arc::new(CallbackRegistry::new()),
        }
    }

    /// Returns the device capabilities.
    #[must_use]
    pub fn capabilities(&self) -> &Capabilities {
        &self.capabilities
    }

    /// Sends a command to the device.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn send_command<C: Command + Sync>(
        &self,
        command: &C,
    ) -> Result<CommandResponse, Error> {
        self.protocol
            .send_command(command)
            .await
            .map_err(Error::Protocol)
    }

    // ========== Power Control ==========

    /// Turns on the first relay (POWER1).
    ///
    /// For multi-relay devices, use [`power_on_index`](Self::power_on_index) to
    /// control a specific relay.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Protocol`] if:
    /// - The device is unreachable (connection timeout, DNS failure)
    /// - The device returns an invalid response
    /// - For MQTT: the broker connection is lost
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::Device;
    ///
    /// # async fn example() -> tasmor_lib::Result<()> {
    /// let (device, _) = Device::http("192.168.1.100").build().await?;
    ///
    /// // Turn on the device
    /// let response = device.power_on().await?;
    /// println!("Power state: {:?}", response.first_power_state()?);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn power_on(&self) -> Result<PowerResponse, Error> {
        self.power_on_index(PowerIndex::one()).await
    }

    /// Turns on a specific relay by index.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Protocol`] if the device is unreachable or returns an invalid response.
    pub async fn power_on_index(&self, index: PowerIndex) -> Result<PowerResponse, Error> {
        self.set_power(index, PowerState::On).await
    }

    /// Turns off the first relay (POWER1).
    ///
    /// For multi-relay devices, use [`power_off_index`](Self::power_off_index) to
    /// control a specific relay.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Protocol`] if:
    /// - The device is unreachable (connection timeout, DNS failure)
    /// - The device returns an invalid response
    /// - For MQTT: the broker connection is lost
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::Device;
    ///
    /// # async fn example() -> tasmor_lib::Result<()> {
    /// let (device, _) = Device::http("192.168.1.100").build().await?;
    ///
    /// // Turn off the device
    /// device.power_off().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn power_off(&self) -> Result<PowerResponse, Error> {
        self.power_off_index(PowerIndex::one()).await
    }

    /// Turns off a specific relay by index.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Protocol`] if the device is unreachable or returns an invalid response.
    pub async fn power_off_index(&self, index: PowerIndex) -> Result<PowerResponse, Error> {
        self.set_power(index, PowerState::Off).await
    }

    /// Toggles the first relay (POWER1).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Protocol`] if the device is unreachable or returns an invalid response.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::Device;
    ///
    /// # async fn example() -> tasmor_lib::Result<()> {
    /// let (device, _) = Device::http("192.168.1.100").build().await?;
    ///
    /// // Toggle the device
    /// let response = device.power_toggle().await?;
    /// println!("Power is now: {:?}", response.first_power_state()?);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn power_toggle(&self) -> Result<PowerResponse, Error> {
        self.power_toggle_index(PowerIndex::one()).await
    }

    /// Toggles a specific relay by index.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Protocol`] if the device is unreachable or returns an invalid response.
    pub async fn power_toggle_index(&self, index: PowerIndex) -> Result<PowerResponse, Error> {
        let cmd = PowerCommand::Toggle { index };
        let response = self.send_command(&cmd).await?;
        let parsed: PowerResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        self.apply_power_response(&parsed);

        Ok(parsed)
    }

    /// Sets the power state of a specific relay.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn set_power(
        &self,
        index: PowerIndex,
        state: PowerState,
    ) -> Result<PowerResponse, Error> {
        let cmd = PowerCommand::Set { index, state };
        let response = self.send_command(&cmd).await?;
        let parsed: PowerResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        self.apply_power_response(&parsed);

        Ok(parsed)
    }

    /// Gets the current power state.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn get_power(&self) -> Result<PowerResponse, Error> {
        self.get_power_index(PowerIndex::one()).await
    }

    /// Gets the power state of a specific relay.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn get_power_index(&self, index: PowerIndex) -> Result<PowerResponse, Error> {
        let cmd = PowerCommand::Get { index };
        let response = self.send_command(&cmd).await?;
        let parsed: PowerResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        self.apply_power_response(&parsed);

        Ok(parsed)
    }

    /// Dispatches power state changes from a response to callbacks.
    fn apply_power_response(&self, response: &PowerResponse) {
        for idx in 1..=8 {
            if let Ok(Some(power_state)) = response.power_state(idx) {
                let change = crate::state::StateChange::power(idx, power_state);
                self.callbacks.dispatch(&change);
            }
        }
    }

    // ========== Status ==========

    /// Gets the full device status.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn status(&self) -> Result<StatusResponse, Error> {
        let cmd = StatusCommand::all();
        let response = self.send_command(&cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    /// Gets the abbreviated device status.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn status_abbreviated(&self) -> Result<StatusResponse, Error> {
        let cmd = StatusCommand::abbreviated();
        let response = self.send_command(&cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    // ========== Dimmer ==========

    /// Sets the dimmer level (brightness) for dimmable lights.
    ///
    /// The dimmer value must be between 0 and 100. Use the [`Dimmer`] type
    /// to ensure valid values at compile time.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Device`] with [`DeviceError::UnsupportedCapability`] if
    /// the device doesn't support dimming (check with
    /// [`capabilities().supports_dimmer_control()`](Capabilities::supports_dimmer_control)).
    ///
    /// Returns [`Error::Protocol`] if the device is unreachable or returns an invalid response.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::{Device, Dimmer};
    ///
    /// # async fn example() -> tasmor_lib::Result<()> {
    /// let (device, _) = Device::http("192.168.1.100").build().await?;
    ///
    /// // Set brightness to 75%
    /// let dimmer = Dimmer::new(75)?;
    /// let response = device.set_dimmer(dimmer).await?;
    /// println!("Dimmer set to {}%", response.dimmer());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`DeviceError::UnsupportedCapability`]: crate::error::DeviceError::UnsupportedCapability
    pub async fn set_dimmer(&self, value: Dimmer) -> Result<DimmerResponse, Error> {
        self.check_capability("dimmer", self.capabilities.supports_dimmer_control())?;
        let cmd = DimmerCommand::Set(value);
        let response = self.send_command(&cmd).await?;
        let parsed: DimmerResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        self.apply_dimmer_response(&parsed);

        Ok(parsed)
    }

    /// Gets the current dimmer level.
    ///
    /// This is a **point-in-time query** that fetches the current dimmer value
    /// from the device. For continuous monitoring, use MQTT subscriptions via
    /// [`on_dimmer_changed`](crate::subscription::Subscribable::on_dimmer_changed).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Device`] with [`DeviceError::UnsupportedCapability`] if
    /// the device doesn't support dimming.
    ///
    /// Returns [`Error::Protocol`] if the device is unreachable or returns an invalid response.
    ///
    /// [`DeviceError::UnsupportedCapability`]: crate::error::DeviceError::UnsupportedCapability
    pub async fn get_dimmer(&self) -> Result<DimmerResponse, Error> {
        self.check_capability("dimmer", self.capabilities.supports_dimmer_control())?;
        let cmd = DimmerCommand::Get;
        let response = self.send_command(&cmd).await?;
        let parsed: DimmerResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        self.apply_dimmer_response(&parsed);

        Ok(parsed)
    }

    /// Dispatches dimmer state changes from a response to callbacks.
    fn apply_dimmer_response(&self, response: &DimmerResponse) {
        if let Ok(dimmer) = Dimmer::new(response.dimmer()) {
            let change = crate::state::StateChange::dimmer(dimmer);
            self.callbacks.dispatch(&change);
        }

        if let Ok(Some(power)) = response.power_state() {
            let change = crate::state::StateChange::power(1, power);
            self.callbacks.dispatch(&change);
        }
    }

    // ========== Color Temperature ==========

    /// Sets the color temperature.
    ///
    /// Returns a typed response including the new color temperature and power state.
    ///
    /// # Errors
    ///
    /// Returns error if the device doesn't support color temperature or the command fails.
    pub async fn set_color_temperature(
        &self,
        value: ColorTemperature,
    ) -> Result<ColorTemperatureResponse, Error> {
        self.check_capability(
            "color temperature",
            self.capabilities.supports_color_temperature_control(),
        )?;
        let cmd = ColorTemperatureCommand::Set(value);
        let response = self.send_command(&cmd).await?;
        let parsed: ColorTemperatureResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        self.apply_color_temperature_response(&parsed);

        Ok(parsed)
    }

    /// Gets the current color temperature.
    ///
    /// Returns a typed response including the current color temperature and power state.
    ///
    /// # Errors
    ///
    /// Returns error if the device doesn't support color temperature or the command fails.
    pub async fn get_color_temperature(&self) -> Result<ColorTemperatureResponse, Error> {
        self.check_capability(
            "color temperature",
            self.capabilities.supports_color_temperature_control(),
        )?;
        let cmd = ColorTemperatureCommand::Get;
        let response = self.send_command(&cmd).await?;
        let parsed: ColorTemperatureResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        self.apply_color_temperature_response(&parsed);

        Ok(parsed)
    }

    /// Dispatches color temperature state changes from a response to callbacks.
    fn apply_color_temperature_response(&self, response: &ColorTemperatureResponse) {
        if let Ok(ct) = ColorTemperature::new(response.color_temperature()) {
            let change = crate::state::StateChange::color_temperature(ct);
            self.callbacks.dispatch(&change);
        }

        if let Ok(Some(power)) = response.power_state() {
            let change = crate::state::StateChange::power(1, power);
            self.callbacks.dispatch(&change);
        }
    }

    // ========== HSB Color ==========

    /// Sets the HSB color.
    ///
    /// Returns a typed response including the new HSB color, dimmer level, and power state.
    ///
    /// # Errors
    ///
    /// Returns error if the device doesn't support RGB or the command fails.
    pub async fn set_hsb_color(&self, color: HsbColor) -> Result<HsbColorResponse, Error> {
        self.check_capability("RGB color", self.capabilities.supports_rgb_control())?;
        let cmd = HsbColorCommand::Set(color);
        let response = self.send_command(&cmd).await?;
        let parsed: HsbColorResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        self.apply_hsb_color_response(&parsed);

        Ok(parsed)
    }

    /// Gets the current HSB color.
    ///
    /// Returns a typed response including the current HSB color, dimmer level, and power state.
    ///
    /// # Errors
    ///
    /// Returns error if the device doesn't support RGB or the command fails.
    pub async fn get_hsb_color(&self) -> Result<HsbColorResponse, Error> {
        self.check_capability("RGB color", self.capabilities.supports_rgb_control())?;
        let cmd = HsbColorCommand::Get;
        let response = self.send_command(&cmd).await?;
        let parsed: HsbColorResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        self.apply_hsb_color_response(&parsed);

        Ok(parsed)
    }

    /// Dispatches HSB color state changes from a response to callbacks.
    fn apply_hsb_color_response(&self, response: &HsbColorResponse) {
        if let Ok(color) = response.hsb_color() {
            let change = crate::state::StateChange::hsb_color(color);
            self.callbacks.dispatch(&change);
        }

        if let Some(dimmer_value) = response.dimmer()
            && let Ok(dimmer) = Dimmer::new(dimmer_value)
        {
            let change = crate::state::StateChange::dimmer(dimmer);
            self.callbacks.dispatch(&change);
        }

        if let Ok(Some(power)) = response.power_state() {
            let change = crate::state::StateChange::power(1, power);
            self.callbacks.dispatch(&change);
        }
    }

    // ========== RGB Color ==========

    /// Sets the RGB color.
    ///
    /// This is a convenience method that converts the RGB color to HSB internally
    /// and sends an `HSBColor` command to the device. The response contains both
    /// the RGB and HSB representations.
    ///
    /// # Errors
    ///
    /// Returns error if the device doesn't support RGB or the command fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::RgbColor;
    ///
    /// # async fn example(device: &tasmor_lib::Device<impl tasmor_lib::protocol::Protocol>) -> tasmor_lib::Result<()> {
    /// // Set color using hex string
    /// let color = RgbColor::from_hex("#FF5733")?;
    /// let response = device.set_rgb_color(color).await?;
    /// println!("Color set to: {}", response.to_hex_with_hash());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_rgb_color(&self, color: RgbColor) -> Result<RgbColorResponse, Error> {
        self.check_capability("RGB color", self.capabilities.supports_rgb_control())?;

        // Convert RGB to HSB and send the command
        let hsb = color.to_hsb();
        let cmd = HsbColorCommand::Set(hsb);
        let response = self.send_command(&cmd).await?;
        let hsb_response: HsbColorResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        self.apply_hsb_color_response(&hsb_response);

        // Create RGB response preserving the original RGB value
        let returned_hsb = hsb_response.hsb_color().unwrap_or(hsb);
        Ok(RgbColorResponse::new(color, returned_hsb))
    }

    // ========== Scheme ==========

    /// Sets the light scheme/effect.
    ///
    /// Tasmota supports several built-in light schemes:
    /// - 0: Single (fixed color, default)
    /// - 1: Wakeup (gradual brightness increase, uses [`WakeupDuration`])
    /// - 2: Cycle Up (color cycling with increasing brightness)
    /// - 3: Cycle Down (color cycling with decreasing brightness)
    /// - 4: Random (random color changes)
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::Scheme;
    ///
    /// # async fn example(device: &tasmor_lib::Device<impl tasmor_lib::protocol::Protocol>) -> tasmor_lib::Result<()> {
    /// // Set wakeup scheme
    /// device.set_scheme(Scheme::WAKEUP).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_scheme(&self, scheme: Scheme) -> Result<SchemeResponse, Error> {
        let cmd = SchemeCommand::Set(scheme);
        let response = self.send_command(&cmd).await?;
        let parsed: SchemeResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        if let Ok(s) = parsed.scheme() {
            let change = crate::state::StateChange::scheme(s);
            self.callbacks.dispatch(&change);
        }

        Ok(parsed)
    }

    /// Gets the current light scheme.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn get_scheme(&self) -> Result<SchemeResponse, Error> {
        let cmd = SchemeCommand::Get;
        let response = self.send_command(&cmd).await?;
        let parsed: SchemeResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        if let Ok(s) = parsed.scheme() {
            let change = crate::state::StateChange::scheme(s);
            self.callbacks.dispatch(&change);
        }

        Ok(parsed)
    }

    // ========== Wakeup Duration ==========

    /// Sets the wakeup duration.
    ///
    /// The wakeup duration controls how long Scheme 1 (Wakeup) takes to
    /// gradually increase brightness from 0 to the current dimmer level.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use tasmor_lib::WakeupDuration;
    ///
    /// # async fn example(device: &tasmor_lib::Device<impl tasmor_lib::protocol::Protocol>) -> tasmor_lib::Result<()> {
    /// // Set wakeup duration to 5 minutes
    /// let duration = WakeupDuration::new(Duration::from_secs(300))?;
    /// device.set_wakeup_duration(duration).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_wakeup_duration(
        &self,
        duration: WakeupDuration,
    ) -> Result<WakeupDurationResponse, Error> {
        let cmd = WakeupDurationCommand::Set(duration);
        let response = self.send_command(&cmd).await?;
        let parsed: WakeupDurationResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        if let Ok(d) = parsed.duration() {
            let change = crate::state::StateChange::wakeup_duration(d);
            self.callbacks.dispatch(&change);
        }

        Ok(parsed)
    }

    /// Gets the current wakeup duration.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn get_wakeup_duration(&self) -> Result<WakeupDurationResponse, Error> {
        let cmd = WakeupDurationCommand::Get;
        let response = self.send_command(&cmd).await?;
        let parsed: WakeupDurationResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes
        if let Ok(d) = parsed.duration() {
            let change = crate::state::StateChange::wakeup_duration(d);
            self.callbacks.dispatch(&change);
        }

        Ok(parsed)
    }

    // ========== Fade ==========

    /// Enables fade transitions.
    ///
    /// Returns a typed response indicating whether fade is now enabled.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn enable_fade(&self) -> Result<FadeResponse, Error> {
        let cmd = FadeCommand::Enable;
        let response = self.send_command(&cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    /// Disables fade transitions.
    ///
    /// Returns a typed response indicating whether fade is now disabled.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn disable_fade(&self) -> Result<FadeResponse, Error> {
        let cmd = FadeCommand::Disable;
        let response = self.send_command(&cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    /// Gets the current fade setting.
    ///
    /// Returns a typed response indicating whether fade is enabled.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn get_fade(&self) -> Result<FadeResponse, Error> {
        let cmd = FadeCommand::Get;
        let response = self.send_command(&cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    /// Sets the fade transition duration.
    ///
    /// Returns a typed response with the new duration value.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn set_fade_duration(
        &self,
        duration: FadeDuration,
    ) -> Result<FadeDurationResponse, Error> {
        let cmd = FadeDurationCommand::Set(duration);
        let response = self.send_command(&cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    /// Gets the current fade duration setting.
    ///
    /// Returns a typed response with the current duration value.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn get_fade_duration(&self) -> Result<FadeDurationResponse, Error> {
        let cmd = FadeDurationCommand::Get;
        let response = self.send_command(&cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    /// Enables fade at startup.
    ///
    /// Returns a typed response indicating whether startup fade is now enabled.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn enable_fade_at_startup(&self) -> Result<StartupFadeResponse, Error> {
        let cmd = StartupFadeCommand::Enable;
        let response = self.send_command(&cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    /// Disables fade at startup.
    ///
    /// Returns a typed response indicating whether startup fade is now disabled.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn disable_fade_at_startup(&self) -> Result<StartupFadeResponse, Error> {
        let cmd = StartupFadeCommand::Disable;
        let response = self.send_command(&cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    /// Gets the current fade at startup setting.
    ///
    /// Returns a typed response indicating whether startup fade is enabled.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub async fn get_fade_at_startup(&self) -> Result<StartupFadeResponse, Error> {
        let cmd = StartupFadeCommand::Get;
        let response = self.send_command(&cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    // ========== Energy Monitoring ==========

    /// Gets energy monitoring data (voltage, current, power consumption).
    ///
    /// Returns comprehensive energy data including instantaneous readings and
    /// accumulated totals. Only available on devices with energy monitoring
    /// capabilities (e.g., smart plugs with power metering).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Device`] with [`DeviceError::UnsupportedCapability`] if
    /// the device doesn't support energy monitoring (check with
    /// [`capabilities().supports_energy_monitoring()`](Capabilities::supports_energy_monitoring)).
    ///
    /// Returns [`Error::Protocol`] if the device is unreachable or returns an invalid response.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::Device;
    ///
    /// # async fn example() -> tasmor_lib::Result<()> {
    /// let (device, _) = Device::http("192.168.1.100").build().await?;
    ///
    /// if device.capabilities().supports_energy_monitoring() {
    ///     let response = device.energy().await?;
    ///     if let Some(energy) = response.energy() {
    ///         println!("Power: {} W", energy.power);
    ///         println!("Voltage: {} V", energy.voltage);
    ///         println!("Today: {} kWh", energy.today);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`DeviceError::UnsupportedCapability`]: crate::error::DeviceError::UnsupportedCapability
    pub async fn energy(&self) -> Result<EnergyResponse, Error> {
        self.check_capability(
            "energy monitoring",
            self.capabilities.supports_energy_monitoring(),
        )?;
        let cmd = EnergyCommand::Get;
        let response = self.send_command(&cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    /// Resets the total energy counter to zero and returns the updated energy data.
    ///
    /// This resets both the total energy value and the `TotalStartTime` to the current time,
    /// then queries the device to return the updated energy data.
    ///
    /// # Errors
    ///
    /// Returns error if the device doesn't support energy monitoring or the command fails.
    pub async fn reset_energy_total(&self) -> Result<EnergyResponse, Error> {
        self.check_capability(
            "energy monitoring",
            self.capabilities.supports_energy_monitoring(),
        )?;

        // Send the reset command
        let cmd = EnergyCommand::ResetTotal;
        self.send_command(&cmd).await?;

        // Query and return the updated energy data
        let query_cmd = EnergyCommand::Get;
        let response = self.send_command(&query_cmd).await?;
        response.parse().map_err(Error::Parse)
    }

    // ========== Routines ==========

    /// Runs a routine of actions atomically.
    ///
    /// Uses Tasmota's `Backlog0` functionality to execute multiple actions
    /// sequentially without inter-action delays (unless explicit delays are
    /// added to the routine).
    ///
    /// # Capability Checking
    ///
    /// This method does **not** automatically validate that all actions in the
    /// routine are supported by the device's capabilities. When building
    /// routines with actions that require specific capabilities (like dimmer
    /// or color control), ensure the device supports them by checking
    /// [`capabilities()`](Self::capabilities) beforehand.
    ///
    /// # Callback Dispatch
    ///
    /// After successful execution, state change callbacks are dispatched based
    /// on the response fields. The following field types trigger callbacks:
    /// - `POWER`, `POWER1`-`POWER8` → power callbacks
    /// - `Dimmer` → dimmer callbacks
    /// - `HSBColor` → color callbacks
    /// - `CT` → color temperature callbacks
    ///
    /// # Errors
    ///
    /// Returns error if the routine fails to execute or the response cannot
    /// be parsed.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::{Device, command::Routine};
    /// use tasmor_lib::types::{PowerIndex, Dimmer};
    /// use std::time::Duration;
    ///
    /// # async fn example(device: &Device<impl tasmor_lib::protocol::Protocol>) -> tasmor_lib::Result<()> {
    /// // Build a wake-up routine
    /// let routine = Routine::builder()
    ///     .power_on(PowerIndex::one())
    ///     .set_dimmer(Dimmer::new(10)?)
    ///     .delay(Duration::from_secs(2))
    ///     .set_dimmer(Dimmer::new(50)?)
    ///     .delay(Duration::from_secs(2))
    ///     .set_dimmer(Dimmer::new(100)?)
    ///     .build()?;
    ///
    /// // Run the routine
    /// let response = device.run(&routine).await?;
    ///
    /// // Check specific fields from the combined response
    /// if let Ok(dimmer) = response.get_as::<u8>("Dimmer") {
    ///     println!("Final dimmer level: {}", dimmer);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run(
        &self,
        routine: &crate::command::Routine,
    ) -> Result<crate::response::RoutineResponse, Error> {
        let backlog_cmd = routine.to_backlog_command();
        tracing::debug!(
            steps = routine.len(),
            raw = %backlog_cmd,
            "Running routine"
        );

        let response = self
            .protocol
            .send_raw(&backlog_cmd)
            .await
            .map_err(Error::Protocol)?;

        let parsed: crate::response::RoutineResponse = response.parse().map_err(Error::Parse)?;

        // Dispatch callbacks for state changes detected in the response
        self.apply_routine_response(&parsed);

        Ok(parsed)
    }

    /// Dispatches state change callbacks based on routine response fields.
    fn apply_routine_response(&self, response: &crate::response::RoutineResponse) {
        // Parse power states: POWER, POWER1-POWER8
        for idx in 1..=8u8 {
            let keys = if idx == 1 {
                vec!["POWER".to_string(), "POWER1".to_string()]
            } else {
                vec![format!("POWER{idx}")]
            };

            for key in keys {
                if let Some(state_str) = response.try_get_as::<String>(&key)
                    && let Ok(state) = state_str.parse::<PowerState>()
                {
                    let change = crate::state::StateChange::power(idx, state);
                    self.callbacks.dispatch(&change);
                    break; // Found state for this index, no need to check other keys
                }
            }
        }

        // Parse dimmer if present
        if let Some(dimmer_value) = response.try_get_as::<u8>("Dimmer")
            && let Ok(dimmer) = Dimmer::new(dimmer_value)
        {
            let change = crate::state::StateChange::dimmer(dimmer);
            self.callbacks.dispatch(&change);
        }

        // Parse HSBColor if present (format: "hue,sat,bri")
        if let Some(hsb_str) = response.try_get_as::<String>("HSBColor") {
            // Parse HSB string in format "hue,sat,bri"
            let parts: Vec<&str> = hsb_str.split(',').map(str::trim).collect();
            if parts.len() == 3 {
                if let (Ok(h), Ok(s), Ok(b)) = (
                    parts[0].parse::<u16>(),
                    parts[1].parse::<u8>(),
                    parts[2].parse::<u8>(),
                ) {
                    if let Ok(color) = HsbColor::new(h, s, b) {
                        let change = crate::state::StateChange::hsb_color(color);
                        self.callbacks.dispatch(&change);
                    } else {
                        tracing::warn!(value = %hsb_str, "HSBColor values out of range in sequence response");
                    }
                } else {
                    tracing::warn!(value = %hsb_str, "Failed to parse HSBColor components in sequence response");
                }
            } else {
                tracing::warn!(value = %hsb_str, "Invalid HSBColor format in sequence response (expected 3 parts)");
            }
        }

        // Parse CT (color temperature) if present
        if let Some(ct_value) = response.try_get_as::<u16>("CT")
            && let Ok(ct) = ColorTemperature::new(ct_value)
        {
            let change = crate::state::StateChange::color_temperature(ct);
            self.callbacks.dispatch(&change);
        }

        // Parse Scheme if present
        if let Some(scheme_value) = response.try_get_as::<u8>("Scheme")
            && let Ok(scheme) = Scheme::new(scheme_value)
        {
            let change = crate::state::StateChange::scheme(scheme);
            self.callbacks.dispatch(&change);
        }
    }

    // ========== Initial State Query ==========

    /// Queries the device for its complete current state.
    ///
    /// This method queries **all** supported capabilities and returns a complete
    /// [`DeviceState`] with current values. It's called automatically by the
    /// device builders to provide initial state.
    ///
    /// # `query_state()` vs `get_*` Methods
    ///
    /// | Method | Use Case |
    /// |--------|----------|
    /// | `query_state()` | Get full device state (all capabilities at once) |
    /// | `get_power()`, `get_dimmer()`, etc. | Get a single specific value |
    ///
    /// Use `query_state()` when you need a complete snapshot of the device.
    /// Use individual `get_*` methods when you only need one specific value
    /// and want to minimize network traffic.
    ///
    /// # System Info
    ///
    /// The returned state includes system info (`wifi_rssi`, `heap`) from the
    /// Status response. For HTTP devices, uptime is parsed from the
    /// `StatusPRM.Uptime` string. For MQTT devices, uptime can also come
    /// from telemetry messages. Use [`crate::state::SystemInfo::uptime()`] to get the
    /// uptime as a [`std::time::Duration`].
    ///
    /// # Errors
    ///
    /// Returns error if any of the queries fail.
    #[allow(clippy::too_many_lines)]
    pub async fn query_state(&self) -> Result<DeviceState, Error> {
        tracing::debug!(
            energy_monitoring = self.capabilities.supports_energy_monitoring(),
            dimmer = self.capabilities.supports_dimmer_control(),
            rgb = self.capabilities.supports_rgb_control(),
            cct = self.capabilities.supports_color_temperature_control(),
            "Querying device state"
        );

        let mut state = DeviceState::new();

        // Query power state
        match self.get_power().await {
            Ok(power_response) => {
                if let Ok(power_state) = power_response.first_power_state() {
                    tracing::debug!(?power_state, "Got power state");
                    state.set_power(1, power_state);
                }
            }
            Err(e) => tracing::debug!(error = %e, "Failed to get power state"),
        }

        // Query dimmer if supported
        if self.capabilities.supports_dimmer_control() {
            match self.get_dimmer().await {
                Ok(dimmer_response) => {
                    if let Ok(dimmer) = Dimmer::new(dimmer_response.dimmer()) {
                        tracing::debug!(dimmer = dimmer.value(), "Got dimmer");
                        state.set_dimmer(dimmer);
                    }
                }
                Err(e) => tracing::debug!(error = %e, "Failed to get dimmer"),
            }
        }

        // Query color temperature if supported
        if self.capabilities.supports_color_temperature_control() {
            match self.get_color_temperature().await {
                Ok(ct_response) => {
                    if let Ok(ct) = ColorTemperature::new(ct_response.color_temperature()) {
                        tracing::debug!(ct = ct.value(), "Got color temperature");
                        state.set_color_temperature(ct);
                    }
                }
                Err(e) => tracing::debug!(error = %e, "Failed to get color temperature"),
            }
        }

        // Query HSB color if supported
        if self.capabilities.supports_rgb_control() {
            match self.get_hsb_color().await {
                Ok(hsb_response) => {
                    if let Ok(hsb) = hsb_response.hsb_color() {
                        tracing::debug!(hue = hsb.hue(), sat = hsb.saturation(), "Got HSB color");
                        state.set_hsb_color(hsb);
                    }
                }
                Err(e) => tracing::debug!(error = %e, "Failed to get HSB color"),
            }
        }

        // Query energy data if supported
        if self.capabilities.supports_energy_monitoring() {
            tracing::debug!("Querying energy data");
            match self.energy().await {
                Ok(energy_response) => {
                    tracing::debug!(?energy_response, "Got energy response");
                    if let Some(energy) = energy_response.energy() {
                        tracing::debug!(
                            power = energy.power,
                            voltage = energy.voltage,
                            current = energy.current,
                            "Setting energy data"
                        );
                        state.set_power_consumption(energy.power);
                        state.set_voltage(energy.voltage);
                        state.set_current(energy.current);
                        state.set_energy_today(energy.today);
                        state.set_energy_yesterday(energy.yesterday);
                        state.set_energy_total(energy.total);
                        state.set_apparent_power(energy.apparent_power);
                        state.set_reactive_power(energy.reactive_power);
                        state.set_power_factor(energy.factor);
                        if let Some(start_time) = &energy.total_start_time {
                            state.set_total_start_time(start_time.clone());
                        }
                    } else {
                        tracing::debug!("Energy response has no energy data");
                    }
                }
                Err(e) => tracing::debug!(error = %e, "Failed to get energy data"),
            }
        }

        // Query fade state if dimmer is supported (fade is a light feature)
        if self.capabilities.supports_dimmer_control() {
            match self.get_fade().await {
                Ok(fade_response) => {
                    if let Ok(enabled) = fade_response.is_enabled() {
                        tracing::debug!(fade_enabled = enabled, "Got fade state");
                        state.set_fade_enabled(enabled);
                    }
                }
                Err(e) => tracing::debug!(error = %e, "Failed to get fade state"),
            }

            match self.get_fade_duration().await {
                Ok(duration_response) => {
                    if let Ok(duration) = duration_response.duration() {
                        tracing::debug!(fade_duration = ?duration.as_duration(), "Got fade duration");
                        state.set_fade_duration(duration);
                    }
                }
                Err(e) => tracing::debug!(error = %e, "Failed to get fade duration"),
            }
        }

        // Query system information via Status 0
        match self.status().await {
            Ok(status_response) => {
                let mut sys_info = crate::state::SystemInfo::new();

                // Get uptime from StatusPRM
                if let Some(prm) = &status_response.status_prm
                    && let Some(uptime) = prm.uptime()
                {
                    sys_info = sys_info.with_uptime(uptime);
                    tracing::debug!(uptime_secs = uptime.as_secs(), "Got uptime");
                }

                // Get heap from StatusMEM
                if let Some(mem) = &status_response.memory {
                    sys_info = sys_info.with_heap(mem.heap);
                    tracing::debug!(heap = mem.heap, "Got heap memory");
                }

                // Get WiFi RSSI from StatusNET
                if let Some(net) = &status_response.network {
                    sys_info = sys_info.with_wifi_rssi(net.rssi);
                    tracing::debug!(rssi = net.rssi, "Got WiFi RSSI");
                }

                if !sys_info.is_empty() {
                    state.set_system_info(sys_info);
                }
            }
            Err(e) => tracing::debug!(error = %e, "Failed to get status for system info"),
        }

        Ok(state)
    }

    // ========== Helpers ==========

    /// Checks if a capability is supported.
    // Uses &self for method call syntax consistency, even though it only needs the parameters.
    #[allow(clippy::unused_self)]
    fn check_capability(&self, name: &str, supported: bool) -> Result<(), Error> {
        if supported {
            Ok(())
        } else {
            Err(Error::Device(DeviceError::UnsupportedCapability {
                capability: name.to_string(),
            }))
        }
    }
}

// ========== HTTP Device Entry Point ==========

#[cfg(feature = "http")]
impl Device<HttpClient> {
    /// Creates a builder for an HTTP-based device from a host string.
    ///
    /// This is a convenience method equivalent to `Device::http_config(HttpConfig::new(host))`.
    ///
    /// # Arguments
    ///
    /// * `host` - The hostname or IP address of the Tasmota device
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::Device;
    ///
    /// # async fn example() -> tasmor_lib::Result<()> {
    /// let device = Device::http("192.168.1.100")
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn http(host: impl Into<String>) -> HttpDeviceBuilder {
        HttpDeviceBuilder::new(crate::protocol::HttpConfig::new(host))
    }

    /// Creates a builder for an HTTP-based device from an `HttpConfig`.
    ///
    /// Use this when you need to configure advanced options like port, HTTPS,
    /// or credentials at the configuration level.
    ///
    /// # Arguments
    ///
    /// * `config` - HTTP configuration including host, port, and credentials
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::Device;
    /// use tasmor_lib::protocol::HttpConfig;
    ///
    /// # async fn example() -> tasmor_lib::Result<()> {
    /// let config = HttpConfig::new("192.168.1.100")
    ///     .with_port(8080)
    ///     .with_credentials("admin", "password");
    ///
    /// let device = Device::http_config(config)
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn http_config(config: crate::protocol::HttpConfig) -> HttpDeviceBuilder {
        HttpDeviceBuilder::new(config)
    }
}

// ========== MQTT Device Subscriptions ==========

#[cfg(feature = "mqtt")]
use crate::protocol::SharedMqttClient;
#[cfg(feature = "mqtt")]
use crate::state::StateChange;
#[cfg(feature = "mqtt")]
use crate::subscription::{EnergyData, Subscribable, SubscriptionId};

#[cfg(feature = "mqtt")]
impl Device<SharedMqttClient> {
    /// Registers the device's callbacks with the shared MQTT client for message routing.
    ///
    /// This is called automatically by the builder after device creation.
    pub(crate) fn register_callbacks(&self) {
        self.protocol.register_callbacks(&self.callbacks);
    }

    /// Disconnects and cleans up MQTT subscriptions.
    ///
    /// This unsubscribes from device topics on the broker. The shared
    /// broker connection remains open for other devices.
    ///
    /// This method is idempotent - calling it multiple times is safe.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::MqttBroker;
    ///
    /// # async fn example() -> tasmor_lib::Result<()> {
    /// let broker = MqttBroker::builder()
    ///     .host("192.168.1.50")
    ///     .build()
    ///     .await?;
    ///
    /// let (device, _) = broker.device("tasmota").build().await?;
    ///
    /// device.power_on().await?;
    ///
    /// // Clean disconnect when done
    /// device.disconnect().await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn disconnect(&self) {
        self.protocol.disconnect().await;
    }

    /// Returns whether this device has been disconnected.
    #[must_use]
    pub fn is_disconnected(&self) -> bool {
        self.protocol.is_disconnected()
    }

    /// Returns the MQTT topic for this device.
    ///
    /// This is the base topic used for all MQTT communication with the device.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tasmor_lib::MqttBroker;
    ///
    /// # async fn example() -> tasmor_lib::Result<()> {
    /// let broker = MqttBroker::builder()
    ///     .host("192.168.1.50")
    ///     .build()
    ///     .await?;
    ///
    /// let (device, _) = broker.device("tasmota_bulb").build().await?;
    ///
    /// assert_eq!(device.topic(), "tasmota_bulb");
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn topic(&self) -> &str {
        self.protocol.topic()
    }
}

#[cfg(feature = "mqtt")]
impl Subscribable for Device<SharedMqttClient> {
    fn on_power_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(u8, PowerState) + Send + Sync + 'static,
    {
        self.callbacks.on_power_changed(callback)
    }

    fn on_dimmer_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(Dimmer) + Send + Sync + 'static,
    {
        self.callbacks.on_dimmer_changed(callback)
    }

    fn on_color_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(HsbColor) + Send + Sync + 'static,
    {
        self.callbacks.on_hsb_color_changed(callback)
    }

    fn on_color_temp_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(ColorTemperature) + Send + Sync + 'static,
    {
        self.callbacks.on_color_temp_changed(callback)
    }

    fn on_scheme_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(Scheme) + Send + Sync + 'static,
    {
        self.callbacks.on_scheme_changed(callback)
    }

    fn on_energy_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(EnergyData) + Send + Sync + 'static,
    {
        self.callbacks.on_energy_changed(callback)
    }

    fn on_connected<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(&DeviceState) + Send + Sync + 'static,
    {
        self.callbacks.on_connected(callback)
    }

    fn on_disconnected<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.callbacks.on_disconnected(callback)
    }

    fn on_reconnected<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.callbacks.on_reconnected(callback)
    }

    fn on_state_changed<F>(&self, callback: F) -> SubscriptionId
    where
        F: Fn(&StateChange) + Send + Sync + 'static,
    {
        self.callbacks.on_state_changed(callback)
    }

    fn unsubscribe(&self, id: SubscriptionId) -> bool {
        self.callbacks.unsubscribe(id)
    }
}

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

    #[test]
    fn http_device_builder_from_config() {
        let config = HttpConfig::new("192.168.1.100").with_credentials("admin", "pass");

        let builder = Device::<HttpClient>::http_config(config)
            .with_capabilities(Capabilities::neo_coolcam());

        assert!(builder.capabilities().is_some());
    }

    #[test]
    fn http_device_builder_from_host() {
        let builder = Device::<HttpClient>::http("192.168.1.100")
            .with_credentials("admin", "pass")
            .with_capabilities(Capabilities::neo_coolcam());

        assert!(builder.capabilities().is_some());
    }

    #[test]
    fn device_state_default() {
        // This test verifies the Device struct can hold state
        let state = DeviceState::new();
        assert!(state.power(1).is_none());
    }

    #[test]
    fn device_is_clone() {
        // Device<P> implements Clone without requiring P: Clone
        // This is because protocol is wrapped in Arc<P>
        fn assert_clone<T: Clone>() {}
        assert_clone::<Device<HttpClient>>();
    }

    #[test]
    fn device_is_debug() {
        // Device<P> implements Debug without requiring P: Debug
        fn assert_debug<T: std::fmt::Debug>() {}
        assert_debug::<Device<HttpClient>>();
    }

    #[cfg(feature = "mqtt")]
    #[test]
    fn device_shared_mqtt_client_is_clone_and_debug() {
        // This test verifies that Device<SharedMqttClient> implements Clone and Debug
        // even though SharedMqttClient does NOT implement Clone or Debug.
        // This works because we manually implement Clone and Debug for Device<P>
        // without requiring P: Clone or P: Debug bounds.
        use crate::protocol::SharedMqttClient;

        fn assert_clone<T: Clone>() {}
        fn assert_debug<T: std::fmt::Debug>() {}

        assert_clone::<Device<SharedMqttClient>>();
        assert_debug::<Device<SharedMqttClient>>();
    }

    #[test]
    fn device_clone_shares_callbacks() {
        let client = HttpClient::new("192.168.1.100").unwrap();
        let device = Device::new(client, Capabilities::basic());

        // Clone the device
        let device_clone = device.clone();

        // Both devices should share the same callbacks (Arc)
        assert!(Arc::ptr_eq(&device.callbacks, &device_clone.callbacks));
    }

    #[test]
    fn device_clone_shares_protocol() {
        let client = HttpClient::new("192.168.1.100").unwrap();
        let device = Device::new(client, Capabilities::basic());

        // Clone the device
        let device_clone = device.clone();

        // Both devices should share the same protocol (Arc)
        assert!(Arc::ptr_eq(&device.protocol, &device_clone.protocol));
    }
}