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
// 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/.

//! Integration tests for HTTP protocol using wiremock.

use approx::assert_abs_diff_eq;
use std::time::Duration;

use tasmor_lib::command::{
    ColorTemperatureCommand, DimmerCommand, EnergyCommand, FadeCommand, FadeDurationCommand,
    HsbColorCommand, PowerCommand, StartupFadeCommand, StatusCommand,
};
use tasmor_lib::protocol::{HttpClient, HttpClientBuilder, Protocol};
use tasmor_lib::types::{ColorTemperature, Dimmer, FadeDuration, HsbColor, PowerIndex, PowerState};
use tasmor_lib::{Capabilities, Device};
use wiremock::matchers::{method, query_param, query_param_contains};
use wiremock::{Mock, MockServer, ResponseTemplate};

// ============================================================================
// HttpClient Tests
// ============================================================================

mod http_client {
    use super::*;

    #[tokio::test]
    async fn send_power_on_command() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param_contains("cmnd", "Power1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "POWER1": "ON"
            })))
            .mount(&mock_server)
            .await;

        let client = HttpClientBuilder::new()
            .host(mock_server.uri().replace("http://", ""))
            .build()
            .unwrap();

        let cmd = PowerCommand::Set {
            index: PowerIndex::one(),
            state: PowerState::On,
        };

        let response = client.send_command(&cmd).await.unwrap();
        assert!(response.body().contains("ON"));
    }

    #[tokio::test]
    async fn send_power_query_command() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "POWER1": "OFF"
            })))
            .mount(&mock_server)
            .await;

        let client = HttpClientBuilder::new()
            .host(mock_server.uri().replace("http://", ""))
            .build()
            .unwrap();

        let cmd = PowerCommand::Get {
            index: PowerIndex::one(),
        };

        let response = client.send_command(&cmd).await.unwrap();
        assert!(response.body().contains("OFF"));
    }

    #[tokio::test]
    async fn send_status_command() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Status 0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "Status": {
                    "Module": 18,
                    "DeviceName": "Tasmota",
                    "FriendlyName": ["Light"],
                    "Topic": "tasmota",
                    "Power": 1
                },
                "StatusFWR": {
                    "Version": "13.1.0",
                    "BuildDateTime": "2024-01-01T00:00:00"
                },
                "StatusNET": {
                    "Hostname": "tasmota-device",
                    "IPAddress": "192.168.1.100"
                }
            })))
            .mount(&mock_server)
            .await;

        let client = HttpClientBuilder::new()
            .host(mock_server.uri().replace("http://", ""))
            .build()
            .unwrap();

        let cmd = StatusCommand::all();
        let response = client.send_command(&cmd).await.unwrap();

        assert!(response.body().contains("Tasmota"));
        assert!(response.body().contains("13.1.0"));
    }

    #[tokio::test]
    async fn send_dimmer_command() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Dimmer 75"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "Dimmer": 75
            })))
            .mount(&mock_server)
            .await;

        let client = HttpClientBuilder::new()
            .host(mock_server.uri().replace("http://", ""))
            .build()
            .unwrap();

        let cmd = DimmerCommand::Set(Dimmer::new(75).unwrap());
        let response = client.send_command(&cmd).await.unwrap();

        assert!(response.body().contains("75"));
    }

    #[tokio::test]
    async fn send_color_temp_command() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "CT 250"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "CT": 250
            })))
            .mount(&mock_server)
            .await;

        let client = HttpClientBuilder::new()
            .host(mock_server.uri().replace("http://", ""))
            .build()
            .unwrap();

        let cmd = ColorTemperatureCommand::Set(ColorTemperature::new(250).unwrap());
        let response = client.send_command(&cmd).await.unwrap();

        assert!(response.body().contains("250"));
    }

    #[tokio::test]
    async fn send_hsb_color_command() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "HSBColor 120,100,80"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "HSBColor": "120,100,80"
            })))
            .mount(&mock_server)
            .await;

        let client = HttpClientBuilder::new()
            .host(mock_server.uri().replace("http://", ""))
            .build()
            .unwrap();

        let cmd = HsbColorCommand::Set(HsbColor::new(120, 100, 80).unwrap());
        let response = client.send_command(&cmd).await.unwrap();

        assert!(response.body().contains("120,100,80"));
    }

    #[tokio::test]
    async fn send_energy_command() {
        let mock_server = MockServer::start().await;

        // EnergyCommand::Get sends "Status 10" to get energy sensor data
        // (Status 10 replaces deprecated Status 8)
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Status 10"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "StatusSNS": {
                    "ENERGY": {
                        "TotalStartTime": "2024-01-01T00:00:00",
                        "Total": 123.456,
                        "Yesterday": 1.234,
                        "Today": 0.567,
                        "Power": 45,
                        "Voltage": 230,
                        "Current": 0.196
                    }
                }
            })))
            .mount(&mock_server)
            .await;

        let client = HttpClientBuilder::new()
            .host(mock_server.uri().replace("http://", ""))
            .build()
            .unwrap();

        let cmd = EnergyCommand::Get;
        let response = client.send_command(&cmd).await.unwrap();

        assert!(response.body().contains("45"));
        assert!(response.body().contains("230"));
    }

    #[tokio::test]
    async fn send_fade_command() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Fade 1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "Fade": "ON"
            })))
            .mount(&mock_server)
            .await;

        let client = HttpClientBuilder::new()
            .host(mock_server.uri().replace("http://", ""))
            .build()
            .unwrap();

        let cmd = FadeCommand::Enable;
        let response = client.send_command(&cmd).await.unwrap();

        assert!(response.body().contains("ON"));
    }

    #[tokio::test]
    async fn send_speed_command() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Speed 20"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "Speed": 20
            })))
            .mount(&mock_server)
            .await;

        let client = HttpClientBuilder::new()
            .host(mock_server.uri().replace("http://", ""))
            .build()
            .unwrap();

        let cmd = FadeDurationCommand::Set(FadeDuration::new(Duration::from_secs(10)).unwrap());
        let response = client.send_command(&cmd).await.unwrap();

        assert!(response.body().contains("20"));
    }

    #[tokio::test]
    async fn send_startup_fade_command() {
        let mock_server = MockServer::start().await;

        // StartupFadeCommand uses SetOption91 in Tasmota
        Mock::given(method("GET"))
            .and(query_param("cmnd", "SetOption91 1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "SetOption91": "ON"
            })))
            .mount(&mock_server)
            .await;

        let client = HttpClientBuilder::new()
            .host(mock_server.uri().replace("http://", ""))
            .build()
            .unwrap();

        let cmd = StartupFadeCommand::Enable;
        let response = client.send_command(&cmd).await.unwrap();

        assert!(response.body().contains("ON"));
    }

    #[tokio::test]
    async fn client_with_authentication() {
        let mock_server = MockServer::start().await;

        // The auth is passed as query params in Tasmota
        Mock::given(method("GET"))
            .and(query_param("user", "admin"))
            .and(query_param("password", "secret"))
            .and(query_param_contains("cmnd", "Power1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "POWER1": "ON"
            })))
            .mount(&mock_server)
            .await;

        let client = HttpClientBuilder::new()
            .host(mock_server.uri().replace("http://", ""))
            .credentials("admin", "secret")
            .build()
            .unwrap();

        let cmd = PowerCommand::Set {
            index: PowerIndex::one(),
            state: PowerState::On,
        };

        let response = client.send_command(&cmd).await.unwrap();
        assert!(response.body().contains("ON"));
    }
}

// ============================================================================
// Device with Auto-Detection Tests
// ============================================================================

mod device_auto_detection {
    use super::*;

    fn create_full_status_response() -> serde_json::Value {
        serde_json::json!({
            "Status": {
                "Module": 18,
                "DeviceName": "Tasmota RGB Bulb",
                "FriendlyName": ["Living Room Light"],
                "Topic": "tasmota_bulb",
                "Power": 1
            },
            "StatusFWR": {
                "Version": "13.1.0",
                "BuildDateTime": "2024-01-01T00:00:00"
            },
            "StatusNET": {
                "Hostname": "tasmota-bulb",
                "IPAddress": "192.168.1.100"
            }
        })
    }

    fn mock_power_response() -> serde_json::Value {
        serde_json::json!({"POWER1": "OFF"})
    }

    #[tokio::test]
    async fn build_device_with_auto_detection() {
        let mock_server = MockServer::start().await;

        // Mock Status 0 for capability detection
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Status 0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(create_full_status_response()))
            .mount(&mock_server)
            .await;

        // Mock Power1 for initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(mock_power_response()))
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _state) = Device::http(&host).build().await.unwrap();

        assert_eq!(device.capabilities().power_channels(), 1);
    }

    #[tokio::test]
    async fn build_device_detects_neo_coolcam() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Status 0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "Status": {
                    "Module": 49,
                    "DeviceName": "Neo Coolcam Plug",
                    "FriendlyName": ["Smart Plug"],
                    "Topic": "tasmota_plug"
                },
                "StatusSTS": {
                    "ENERGY": {
                        "Power": 45,
                        "Voltage": 230
                    }
                }
            })))
            .mount(&mock_server)
            .await;

        // Mock Power1 for initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(mock_power_response()))
            .mount(&mock_server)
            .await;

        // Mock Status 10 for energy query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Status 10"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "StatusSNS": {
                    "ENERGY": {
                        "Power": 45,
                        "Voltage": 230,
                        "Current": 0.2,
                        "Today": 1.0,
                        "Yesterday": 2.0,
                        "Total": 100.0,
                        "ApparentPower": 46,
                        "ReactivePower": 10,
                        "Factor": 0.98
                    }
                }
            })))
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _state) = Device::http(&host).build().await.unwrap();

        assert!(device.capabilities().supports_energy_monitoring());
    }

    #[tokio::test]
    async fn build_device_without_probe() {
        let mock_server = MockServer::start().await;

        // Mock Power1 for initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(mock_power_response()))
            .mount(&mock_server)
            .await;

        // Mock Dimmer for initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Dimmer"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"Dimmer": 50})),
            )
            .mount(&mock_server)
            .await;

        // Mock CT for initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "CT"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"CT": 300})))
            .mount(&mock_server)
            .await;

        // Mock HSBColor for initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "HSBColor"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"HSBColor": "0,100,100"})),
            )
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _state) = Device::http(&host)
            .with_capabilities(Capabilities::rgbcct_light())
            .build_without_probe()
            .await
            .unwrap();

        assert!(device.capabilities().supports_dimmer_control());
        assert!(device.capabilities().supports_color_temperature_control());
        assert!(device.capabilities().supports_rgb_control());
    }
}

// ============================================================================
// Device Power Commands Tests
// ============================================================================

mod device_power_commands {
    use super::*;

    async fn create_device_with_mock(mock_server: &MockServer) -> Device<HttpClient> {
        // Mock Power1 for initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"POWER1": "OFF"})),
            )
            .mount(mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _) = Device::http(&host)
            .with_capabilities(Capabilities::basic())
            .build_without_probe()
            .await
            .unwrap();
        device
    }

    #[tokio::test]
    async fn power_on() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param_contains("cmnd", "Power1 ON"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "POWER1": "ON"
            })))
            .mount(&mock_server)
            .await;

        let device = create_device_with_mock(&mock_server).await;
        let response = device.power_on().await.unwrap();

        assert_eq!(response.first_power_state().unwrap(), PowerState::On);
    }

    #[tokio::test]
    async fn power_off() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param_contains("cmnd", "Power1 OFF"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "POWER1": "OFF"
            })))
            .mount(&mock_server)
            .await;

        let device = create_device_with_mock(&mock_server).await;
        let response = device.power_off().await.unwrap();

        assert_eq!(response.first_power_state().unwrap(), PowerState::Off);
    }

    #[tokio::test]
    async fn power_toggle() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param_contains("cmnd", "Power1 TOGGLE"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "POWER1": "ON"
            })))
            .mount(&mock_server)
            .await;

        let device = create_device_with_mock(&mock_server).await;
        let response = device.power_toggle().await.unwrap();

        assert_eq!(response.first_power_state().unwrap(), PowerState::On);
    }

    #[tokio::test]
    async fn power_query() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "POWER1": "OFF"
            })))
            .mount(&mock_server)
            .await;

        let device = create_device_with_mock(&mock_server).await;
        let response = device.get_power().await.unwrap();

        assert_eq!(response.first_power_state().unwrap(), PowerState::Off);
    }

    #[tokio::test]
    async fn set_power_specific_relay() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param_contains("cmnd", "Power2 ON"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "POWER2": "ON"
            })))
            .mount(&mock_server)
            .await;

        // Mock Power1 for initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"POWER1": "OFF"})),
            )
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let caps = tasmor_lib::CapabilitiesBuilder::new()
            .power_channels(4)
            .build();

        let (device, _) = Device::http(&host)
            .with_capabilities(caps)
            .build_without_probe()
            .await
            .unwrap();

        let response = device
            .set_power(PowerIndex::new(2).unwrap(), PowerState::On)
            .await
            .unwrap();

        assert_eq!(response.power_state(2).unwrap().unwrap(), PowerState::On);
    }
}

// ============================================================================
// Device Light Commands Tests
// ============================================================================

mod device_light_commands {
    use super::*;

    async fn create_light_device(mock_server: &MockServer) -> Device<HttpClient> {
        // Mock queries for initial state
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"POWER1": "OFF"})),
            )
            .mount(mock_server)
            .await;
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Dimmer"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"Dimmer": 50})),
            )
            .mount(mock_server)
            .await;
        Mock::given(method("GET"))
            .and(query_param("cmnd", "CT"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"CT": 300})))
            .mount(mock_server)
            .await;
        Mock::given(method("GET"))
            .and(query_param("cmnd", "HSBColor"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"HSBColor": "0,100,100"})),
            )
            .mount(mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _) = Device::http(&host)
            .with_capabilities(Capabilities::rgbcct_light())
            .build_without_probe()
            .await
            .unwrap();
        device
    }

    #[tokio::test]
    async fn set_dimmer() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Dimmer 75"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "Dimmer": 75
            })))
            .mount(&mock_server)
            .await;

        let device = create_light_device(&mock_server).await;
        device.set_dimmer(Dimmer::new(75).unwrap()).await.unwrap();
    }

    #[tokio::test]
    async fn set_color_temperature() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "CT 300"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "CT": 300
            })))
            .mount(&mock_server)
            .await;

        let device = create_light_device(&mock_server).await;
        device
            .set_color_temperature(ColorTemperature::new(300).unwrap())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn set_hsb_color() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "HSBColor 240,100,50"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "HSBColor": "240,100,50"
            })))
            .mount(&mock_server)
            .await;

        let device = create_light_device(&mock_server).await;
        device
            .set_hsb_color(HsbColor::new(240, 100, 50).unwrap())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn enable_fade() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Fade 1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "Fade": "ON"
            })))
            .mount(&mock_server)
            .await;

        let device = create_light_device(&mock_server).await;
        device.enable_fade().await.unwrap();
    }

    #[tokio::test]
    async fn disable_fade() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Fade 0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "Fade": "OFF"
            })))
            .mount(&mock_server)
            .await;

        let device = create_light_device(&mock_server).await;
        device.disable_fade().await.unwrap();
    }

    #[tokio::test]
    async fn set_fade_duration() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Speed 15"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "Speed": 15
            })))
            .mount(&mock_server)
            .await;

        let device = create_light_device(&mock_server).await;
        device
            .set_fade_duration(FadeDuration::new(Duration::from_millis(7500)).unwrap())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn dimmer_fails_without_capability() {
        let mock_server = MockServer::start().await;

        // Mock Power1 for initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"POWER1": "OFF"})),
            )
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _) = Device::http(&host)
            .with_capabilities(Capabilities::basic()) // No dimmer
            .build_without_probe()
            .await
            .unwrap();

        let result = device.set_dimmer(Dimmer::new(50).unwrap()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn color_temperature_fails_without_capability() {
        let mock_server = MockServer::start().await;

        // Mock queries for initial state (rgb_light has dimmer and rgb, no cct)
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"POWER1": "OFF"})),
            )
            .mount(&mock_server)
            .await;
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Dimmer"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"Dimmer": 50})),
            )
            .mount(&mock_server)
            .await;
        Mock::given(method("GET"))
            .and(query_param("cmnd", "HSBColor"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"HSBColor": "0,100,100"})),
            )
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _) = Device::http(&host)
            .with_capabilities(Capabilities::rgb_light()) // No CCT
            .build_without_probe()
            .await
            .unwrap();

        let result = device
            .set_color_temperature(ColorTemperature::NEUTRAL)
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn hsb_color_fails_without_capability() {
        let mock_server = MockServer::start().await;

        // Mock queries for initial state (cct_light has dimmer and cct, no rgb)
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"POWER1": "OFF"})),
            )
            .mount(&mock_server)
            .await;
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Dimmer"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"Dimmer": 50})),
            )
            .mount(&mock_server)
            .await;
        Mock::given(method("GET"))
            .and(query_param("cmnd", "CT"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"CT": 300})))
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _) = Device::http(&host)
            .with_capabilities(Capabilities::cct_light()) // No RGB
            .build_without_probe()
            .await
            .unwrap();

        let result = device.set_hsb_color(HsbColor::red()).await;
        assert!(result.is_err());
    }
}

// ============================================================================
// Device Energy Commands Tests
// ============================================================================

mod device_energy_commands {
    use super::*;

    async fn create_energy_device(mock_server: &MockServer) -> Device<HttpClient> {
        // Mock queries for initial state
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"POWER1": "OFF"})),
            )
            .mount(mock_server)
            .await;
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Status 10"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "StatusSNS": {
                    "ENERGY": {
                        "Power": 45,
                        "Voltage": 230,
                        "Current": 0.2,
                        "Today": 1.0,
                        "Yesterday": 2.0,
                        "Total": 100.0,
                        "ApparentPower": 46,
                        "ReactivePower": 10,
                        "Factor": 0.98
                    }
                }
            })))
            .mount(mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _) = Device::http(&host)
            .with_capabilities(Capabilities::neo_coolcam())
            .build_without_probe()
            .await
            .unwrap();
        device
    }

    #[tokio::test]
    async fn get_energy_0() {
        let mock_server = MockServer::start().await;

        // Energy command uses "Status 10" in Tasmota (replaces deprecated Status 8)
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Status 10"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "StatusSNS": {
                    "ENERGY": {
                        "TotalStartTime": "2024-01-01T00:00:00",
                        "Total": 123.456,
                        "Yesterday": 1.234,
                        "Today": 0.567,
                        "Power": 45,
                        "Voltage": 230,
                        "Current": 0.196
                    }
                }
            })))
            .mount(&mock_server)
            .await;

        let device = create_energy_device(&mock_server).await;
        let response = device.energy().await.unwrap();

        let energy = response.energy().unwrap();
        assert_eq!(energy.power, 45.0);
        assert_eq!(energy.voltage, 230.0);
    }

    #[tokio::test]
    async fn get_energy_1() {
        let mock_server = MockServer::start().await;

        // Energy command uses "Status 10" in Tasmota (replaces deprecated Status 8)
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Status 10"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "StatusSNS": {
                    "ENERGY": {
                        "TotalStartTime": "2024-01-01T00:00:00",
                        "Total": 123.45678,
                        "Yesterday": 1.23456,
                        "Today": 0.56789,
                        "Power": 45.123,
                        "Voltage": 230.234,
                        "Current": 0.19678
                    }
                }
            })))
            .mount(&mock_server)
            .await;

        let device = create_energy_device(&mock_server).await;
        let response = device.energy().await.unwrap();

        let energy = response.energy().unwrap();
        assert_abs_diff_eq!(energy.power, 45.123, epsilon = 0.001);
        assert_abs_diff_eq!(energy.voltage, 230.234, epsilon = 0.001);
    }

    #[tokio::test]
    async fn energy_fails_without_capability() {
        let mock_server = MockServer::start().await;

        // Mock Power1 for initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"POWER1": "OFF"})),
            )
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _) = Device::http(&host)
            .with_capabilities(Capabilities::basic()) // No energy
            .build_without_probe()
            .await
            .unwrap();

        let result = device.energy().await;
        assert!(result.is_err());
    }
}

// ============================================================================
// Device Status Commands Tests
// ============================================================================

mod device_status_commands {
    use super::*;

    #[tokio::test]
    async fn get_status() {
        let mock_server = MockServer::start().await;

        // Mock Power1 for initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"POWER1": "OFF"})),
            )
            .mount(&mock_server)
            .await;

        Mock::given(method("GET"))
            .and(query_param("cmnd", "Status 0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "Status": {
                    "Module": 18,
                    "DeviceName": "Test Device",
                    "FriendlyName": ["Light"],
                    "Topic": "tasmota"
                },
                "StatusFWR": {
                    "Version": "13.1.0"
                },
                "StatusNET": {
                    "Hostname": "tasmota",
                    "IPAddress": "192.168.1.100"
                }
            })))
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _) = Device::http(&host)
            .with_capabilities(Capabilities::basic())
            .build_without_probe()
            .await
            .unwrap();

        let status = device.status().await.unwrap();

        assert_eq!(status.module_id(), Some(18));
        assert_eq!(status.device_name(), Some("Test Device"));
        assert_eq!(status.firmware_version(), Some("13.1.0"));
        assert_eq!(status.ip_address(), Some("192.168.1.100"));
    }
}

// ============================================================================
// Error Handling Tests
// ============================================================================

mod error_handling {
    use super::*;

    // Note: build_without_probe() is designed to be resilient - it ignores errors
    // during initial state query and returns an empty state. This is intentional
    // because the device might not respond to all capability queries.
    //
    // The build() method (with probe) WILL fail if the device is unreachable,
    // because capability detection requires a response.

    #[tokio::test]
    async fn build_with_probe_fails_on_server_error() {
        let mock_server = MockServer::start().await;

        // Server returns 500 for all requests - build with probe should fail
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(500))
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let result = Device::http(&host).build().await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn build_with_probe_fails_on_connection_refused() {
        // Use a port that's definitely not listening - build with probe should fail
        let result = Device::http("127.0.0.1:59999").build().await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn build_without_probe_succeeds_with_empty_state_on_error() {
        let mock_server = MockServer::start().await;

        // Server returns 500 for all requests
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(500))
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let result = Device::http(&host)
            .with_capabilities(Capabilities::basic())
            .build_without_probe()
            .await;

        // build_without_probe is designed to succeed even if state query fails
        assert!(result.is_ok());

        // But state should be empty/default
        let (_device, state) = result.unwrap();
        assert!(state.power(1).is_none());
    }

    #[tokio::test]
    async fn handles_server_error_during_command() {
        let mock_server = MockServer::start().await;

        // Mock successful initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"POWER1": "OFF"})),
            )
            .expect(1)
            .mount(&mock_server)
            .await;

        // Mock server error for subsequent requests
        Mock::given(method("GET"))
            .and(query_param_contains("cmnd", "Power1 ON"))
            .respond_with(ResponseTemplate::new(500))
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _) = Device::http(&host)
            .with_capabilities(Capabilities::basic())
            .build_without_probe()
            .await
            .unwrap();

        let result = device.power_on().await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn handles_invalid_json_response_during_command() {
        let mock_server = MockServer::start().await;

        // Mock successful initial state query
        Mock::given(method("GET"))
            .and(query_param("cmnd", "Power1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"POWER1": "OFF"})),
            )
            .expect(1)
            .mount(&mock_server)
            .await;

        // Mock invalid JSON for subsequent requests
        Mock::given(method("GET"))
            .and(query_param_contains("cmnd", "Power1 ON"))
            .respond_with(ResponseTemplate::new(200).set_body_string("not json"))
            .mount(&mock_server)
            .await;

        let host = mock_server.uri().replace("http://", "");
        let (device, _) = Device::http(&host)
            .with_capabilities(Capabilities::basic())
            .build_without_probe()
            .await
            .unwrap();

        let result = device.power_on().await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn handles_connection_refused_during_command() {
        // build_without_probe with connection refused still succeeds (resilient)
        let result = Device::http("127.0.0.1:59999")
            .with_capabilities(Capabilities::basic())
            .build_without_probe()
            .await;

        assert!(result.is_ok());

        // But commands should fail
        let (device, _) = result.unwrap();
        let cmd_result = device.power_on().await;
        assert!(cmd_result.is_err());
    }
}