foxess 1.1.0

Rust library for communication with FoxESS Cloud
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
//! Unit tests for async client functionality using httpmock.
//!

#[cfg(feature = "async")]
use httpmock::prelude::*;
#[cfg(feature = "async")]
use md5::{Digest, Md5};
#[cfg(feature = "async")]
use serde_json::json;

/// Generates the expected MD5 signature for a given API request.
///
/// The signature is calculated based on the request path, API key, and timestamp.
/// It mimics the signature generation logic used in the library.
///
/// # Arguments
/// * `path` - The API endpoint path.
/// * `api_key` - The user's API key.
/// * `timestamp_millis` - The request timestamp in milliseconds.
///
/// # Returns
/// * `String` - The hex-encoded MD5 signature.
#[cfg(feature = "async")]
fn expected_signature(path: &str, api_key: &str, timestamp_millis: i64) -> String {
    // Must match the library logic exactly (note the literal "\r\n" sequences).
    let signature = format!("{}\\r\\n{}\\r\\n{}", path, api_key, timestamp_millis);

    let mut hasher = Md5::new();
    hasher.update(signature.as_bytes());
    hasher.finalize().iter().map(|x| format!("{:02x}", x)).collect()
}

/// Verifies that `get_settings` correctly fetches and parses multiple settings from the API.
///
/// This test mocks a successful API response for a settings query and asserts that
/// the returned values are correctly converted to their expected types.
#[cfg(feature = "async")]
#[tokio::test]
async fn async_get_settings() {
    use crate::{Fox, FoxSettings};

    const API_KEY: &str = "TEST_API_KEY";
    const SN: &str = "TEST_SN";
    const TS: i64 = 1_700_000_000_000; // fixed timestamp for deterministic tests
    const PATH: &str = "/op/v0/device/setting/get";

    fn fixed_now() -> i64 { TS }


    let server = MockServer::start();
    let sig = expected_signature(PATH, API_KEY, TS);

    let _m = server.mock(|when, then| {
        when.method(POST)
            .path(PATH)
            .header("token", API_KEY)
            .header("timestamp", &TS.to_string())
            .header("signature", &sig)
            .header("lang", "en")
            .header("content-type", "application/json")
            .json_body_includes(&format!(r#"{{"sn":"{}"}}"#, SN))
            .json_body_includes(r#"{"key":"MaxSetChargeCurrent"}"#);

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": { "value": "12.34" }
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let res = fox.get_settings(vec![FoxSettings::MaxSetChargeCurrent]).await.unwrap();

    assert_eq!(res.get_f64(FoxSettings::MaxSetChargeCurrent).unwrap(), Some(12.34));
}

/// Verifies that `get_setting_typed` correctly fetches and parses a single setting into a specific type.
///
/// This test ensures that the generic `get_setting_typed` method works as expected for
/// settings that have a numeric representation in the API response.
#[cfg(feature = "async")]
#[tokio::test]
async fn async_get_setting_typed() {
    use crate::Fox;
    use crate::fox_settings::MinSocOnGrid;

    const SN: &str = "TEST_SN";
    const TS: i64 = 1_700_000_000_000; // fixed timestamp for deterministic tests
    const PATH: &str = "/op/v0/device/setting/get";

    fn fixed_now() -> i64 { TS }


    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST)
            .path(PATH)
            .json_body_includes(&format!(r#"{{"sn":"{}"}}"#, SN))
            .json_body_includes(r#"{"key":"MinSocOnGrid"}"#);

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": { "value": "55" }
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let res = fox.get_setting_typed::<MinSocOnGrid>().await.unwrap();

    assert_eq!(res, 55);
}

/// Verifies that `set_setting_typed` correctly sends a request to update a setting.
///
/// This test mocks a successful setting update and ensures that the request body
/// contains the correct serial number, key, and value.
#[cfg(feature = "async")]
#[tokio::test]
async fn async_set_setting_typed() {
    use crate::Fox;
    use crate::fox_settings::MinSocOnGrid;

    const SN: &str = "TEST_SN";
    const TS: i64 = 1_700_000_000_000; // fixed timestamp for deterministic tests
    const PATH: &str = "/op/v0/device/setting/set";

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST)
            .path(PATH)
            .json_body_includes(&format!(r#"{{"sn":"{}","key":"MinSocOnGrid","value":"55"}}"#, SN));

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": null
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let _ = fox.set_setting_typed::<MinSocOnGrid>(55).await.unwrap();
}

/// Verifies that real-time variables can be parsed even when the API returns values in scientific notation.
///
/// This ensures robustness against different numeric formats that might be returned by the FoxESS API.
#[cfg(feature = "async")]
#[tokio::test]
async fn async_get_variables_parses_scientific_notation() {
    use crate::{Fox, FoxVariables};

    const SN: &str = "TEST_SN";
    const TS: i64 = 1_700_000_000_000;
    const PATH: &str = "/op/v1/device/real/query";

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST)
            .path(PATH)
            .json_body_includes(&format!(r#"{{"sns":["{}"]}}"#, SN));

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": [{
                    "datas": [
                        { "variable": "SoC", "value": "9.90E1" },
                        { "variable": "pvPower", "value": 123.0 }
                    ]
                }]
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let res = fox.get_variables(vec![FoxVariables::SoC, FoxVariables::PvPower]).await.unwrap();

    assert_eq!(res.get_u8_percent(FoxVariables::SoC), Some(99));
    assert_eq!(res.get(FoxVariables::PvPower), Some(123.0));
}

/// Verifies that `get_variable_typed` correctly handles scientific notation for a single variable.
#[cfg(feature = "async")]
#[tokio::test]
async fn async_get_variable_typed_parses_scientific_notation() {
    use crate::Fox;
    use crate::fox_variables::SoC;

    const SN: &str = "TEST_SN";
    const TS: i64 = 1_700_000_000_000;
    const PATH: &str = "/op/v1/device/real/query";

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST)
            .path(PATH)
            .json_body_includes(&format!(r#"{{"sns":["{}"]}}"#, SN));

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": [{
                    "datas": [
                        { "variable": "SoC", "value": "9.90E1" }
                    ]
                }]
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let res = fox.get_variable_typed::<SoC>().await.unwrap();

    assert_eq!(res, 99);
}

/// Verifies that `get_variable_typed` returns an error when the value is outside the valid range.
///
/// For example, an SoC value of 110% should trigger a validation error during parsing.
#[cfg(feature = "async")]
#[tokio::test]
async fn async_get_variable_typed_outside_valid_range() {
    use crate::Fox;
    use crate::fox_variables::SoC;

    const SN: &str = "TEST_SN";
    const TS: i64 = 1_700_000_000_000;
    const PATH: &str = "/op/v1/device/real/query";

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST)
            .path(PATH)
            .json_body_includes(&format!(r#"{{"sns":["{}"]}}"#, SN));

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": [{
                    "datas": [
                        { "variable": "SoC", "value": "110" }
                    ]
                }]
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let err = fox.get_variable_typed::<SoC>().await
        .err()
        .expect("get_variable_typed should fail");

    let msg = format!("{err}");
    assert!(msg.contains("value out of range for u8 percentage after rounding"));
}

/// Verifies that `get_variables_history` correctly retrieves and parses historical data points.
///
/// This test mocks a historical data response and checks that the timestamps and values
/// are correctly processed into the resulting map.
#[cfg(feature = "async")]
#[tokio::test]
async fn async_get_variables_history() {
    use chrono::{TimeZone, Utc};
    use crate::{Fox, FoxVariables};

    const SN: &str = "TEST_SN";
    const TS: i64 = 1_700_000_000_000;
    const PATH: &str = "/op/v0/device/history/query";

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST)
            .path(PATH)
            .json_body_includes(&format!(r#"{{"sn": "{}","variables": ["pvPower"],"begin": 0,"end": 1}}"#, SN));

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": [{
                    "datas": [{
                        "variable": "pvPower",
                        "data": [
                            { "time": "2025-12-03 00:08:51 CET+0100", "value": 42.0 },
                            { "time": "2025-12-03 00:09:51 CET+0100", "value": 43.0 }
                        ]
                    }]
                }]
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let start = Utc.timestamp_millis_opt(0).unwrap();
    let end = Utc.timestamp_millis_opt(1).unwrap();

    let res = fox.get_variables_history(start, end, vec![FoxVariables::PvPower]).await.unwrap();

    let series = res.get(FoxVariables::PvPower).unwrap();
    assert_eq!(series.len(), 2);
    assert_eq!(series[0].data, 42.0);
    assert_eq!(series[0].date_time, Utc.with_ymd_and_hms(2025, 12, 2, 23, 8, 51).unwrap());
    assert_eq!(series[1].data, 43.0);
    assert_eq!(series[1].date_time, Utc.with_ymd_and_hms(2025, 12, 2, 23, 9, 51).unwrap());
}

/// Verifies that `set_battery_charging_time_schedule` correctly configures a charging schedule.
///
/// This test checks that the complex JSON structure required for setting schedules is
/// correctly generated and sent to the API.
#[cfg(feature = "async")]
#[tokio::test]
async fn async_set_battery_charging_time_schedule() {
    use chrono::{TimeZone, Utc, Local};
    use crate::Fox;

    const SN: &str = "TEST_SN";
    const TS: i64 = 1_700_000_000_000;
    const PATH: &str = "/op/v0/device/battery/forceChargeTime/set";

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST)
            .path(PATH)
            .json_body(json!(
                {
                    "sn": SN,
                    "enable1": true,
                    "enable2": false,
                    "startTime1": {
                        "hour": 3,
                        "minute": 15
                    },
                    "endTime1": {
                        "hour": 5,
                        "minute": 29
                    },
                    "startTime2": {
                        "hour": 0,
                        "minute": 0
                    },
                    "endTime2": {
                        "hour": 0,
                        "minute": 0
                    }
                }));

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": null
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let start = Local.with_ymd_and_hms(2026, 2, 9, 3, 15, 0).unwrap().with_timezone(&Utc);
    let end = Local.with_ymd_and_hms(2026, 2, 9, 5, 30, 0).unwrap().with_timezone(&Utc);

    let _ = fox.set_battery_charging_time_schedule(true, start, end).await.unwrap();
}

/// Verifies that setting a charging schedule with an end time before the start time results in an error.
///
/// Validation should happen locally before the request is even sent to the API.
#[cfg(feature = "async")]
#[tokio::test]
async fn async_set_battery_charging_time_schedule_end_before_start() {
    use chrono::{TimeZone, Utc, Local};
    use crate::Fox;

    const TS: i64 = 1_700_000_000_000;

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST);
        then.status(500);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let start = Local.with_ymd_and_hms(2026, 2, 9, 5, 30, 0).unwrap().with_timezone(&Utc);
    let end = Local.with_ymd_and_hms(2026, 2, 9, 3, 15, 0).unwrap().with_timezone(&Utc);

    let err = fox.set_battery_charging_time_schedule(true, start, end).await
        .err()
        .expect("set_battery_charging_time_schedule should fail");

    let msg = format!("{err}");
    assert!(msg.contains("charge schedule 1 start time is after end time"));
}

/// Verifies that available variables are correctly parsed from the API response, including enumeration values.
///
#[cfg(feature = "async")]
#[tokio::test]
async fn async_get_available_variables() {
    use crate::Fox;

    const TS: i64 = 1_700_000_000_000;

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(GET);
        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": [
                    {
                        "pvPower": {
                            "unit": "kW",
                            "Grid-tied inverter": true,
                            "name": {
                                "de": "PV Leistung",
                                "pt": "Potência PV",
                                "en": "PVPower",
                                "zh_CN": "PV功率",
                                "pl": "Moc PV",
                                "fr": "PV Puissance"
                            },
                            "Energy-storage inverter": true
                        }
                    },
                    {
                        "SoC": {
                            "unit": "%",
                            "Grid-tied inverter": false,
                            "name": {
                                "de": "SoC",
                                "pt": "SoC",
                                "en": "SoC",
                                "zh_CN": "SoC",
                                "pl": "SoC",
                                "fr": "SoC"
                            },
                            "Energy-storage inverter": true
                        }
                    },
                    {
                        "runningState": {
                            "Grid-tied inverter": true,
                            "name": {
                                "de": "Running State",
                                "pt": "Running State",
                                "en": "Running State",
                                "zh_CN": "运行状态",
                                "pl": "Running State",
                                "fr": "Running State"
                            },
                            "Energy-storage inverter": true,
                            "enum": {
                                "165": "fault",
                                "166": "permanent-fault",
                                "167": "standby",
                                "168": "upgrading",
                                "169": "fct",
                                "170": "illegal",
                                "160": "self-test",
                                "161": "waiting",
                                "162": "checking",
                                "163": "on-grid",
                                "164": "off-grid"
                            }
                        }
                    }
                ]
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let res = fox.get_available_variables().await.unwrap();

    assert_eq!(res.variables.len(), 3);
    assert!(res.variables.iter().filter_map(|v| v.enumeration.as_ref()).any(|e| e.contains_key("163")));
}

/// Verifies that error code information is correctly parsed from the API response.
///
#[cfg(feature = "async")]
#[tokio::test]
async fn blocking_get_error_code_information() {
    use crate::Fox;

    const TS: i64 = 1_700_000_000_000;

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(GET);
        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": {
                    "1461": {
                        "en": "Battery 3 Input Fault",
                        "zh_CN": "电池3输入故障"
                    },
                    "1460": {
                        "en": "Battery 2 Input Fault",
                        "zh_CN": "电池2输入故障"
                    },
                    "1459": {
                        "en": "Battery 1 Input Fault",
                        "zh_CN": "电池1输入故障"
                    },
                    "1458": {
                        "en": "Battery 3 Self-Check Fault",
                        "zh_CN": "电池3自检故障"
                    },
                    "1457": {
                        "en": "Battery 2 Self-Check Fault",
                        "zh_CN": "电池2自检故障"
                    },
                    "1456": {
                        "en": "Battery 1 Self-Check Fault",
                        "zh_CN": "电池1自检故障"
                    },
                    "1455": {
                        "en": "未知1455",
                        "zh_CN": "TBD1455"
                    },
                    "1454": {
                        "en": "未知1454",
                        "zh_CN": "TBD1454"
                    },
                    "1453": {
                        "en": "未知1453",
                        "zh_CN": "TBD1453"
                    },
                    "1": {
                        "de": "Keine Netzspannung verfügbar",
                        "en": "No Utility",
                        "zh_CN": "电网无电压",
                        "pl": "Brak napięcia w sieci energetycznej"
                    }
                }
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let res = fox.get_error_code_information().await.unwrap();

    assert_eq!(res.len(), 10);
    assert_eq!(res.iter().filter(|e| *e.0 == 1 && e.1.eq("No Utility")).count(), 1);
}

/// Verifies that scheduler time segments are correctly parsed from the API response, including enumeration values.
///
#[cfg(feature = "async")]
#[tokio::test]
async fn async_get_scheduler_time_segments() {
    use crate::Fox;
    use crate::FoxWorkModes;

    const TS: i64 = 1_700_000_000_000;

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST);
        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": {
                    "enable": 1,
                    "maxGroupCount": 24,
                    "groups": [
                        {
                            "endHour": 8,
                            "workMode": "SelfUse",
                            "startHour": 0,
                            "extraParam": {
                                "fdPwr": 100.0,
                                "minSocOnGrid": 10.0,
                                "fdSoc": 10.0,
                                "maxSoc": 100.0
                            },
                            "startMinute": 0,
                            "endMinute": 29
                        },
                        {
                            "endHour": 8,
                            "workMode": "ForceCharge",
                            "startHour": 8,
                            "extraParam": {
                                "fdPwr": 12000.0,
                                "minSocOnGrid": 10.0,
                                "fdSoc": 20.0,
                                "maxSoc": 100.0
                            },
                            "startMinute": 30,
                            "endMinute": 59
                        },
                        {
                            "endHour": 9,
                            "workMode": "SelfUse",
                            "startHour": 9,
                            "extraParam": {
                                "fdPwr": 100.0,
                                "minSocOnGrid": 10.0,
                                "fdSoc": 10.0,
                                "maxSoc": 100.0
                            },
                            "startMinute": 0,
                            "endMinute": 29
                        },
                        {
                            "endHour": 9,
                            "workMode": "ForceCharge",
                            "startHour": 9,
                            "extraParam": {
                                "fdPwr": 12000.0,
                                "minSocOnGrid": 10.0,
                                "fdSoc": 30.0,
                                "maxSoc": 100.0
                            },
                            "startMinute": 30,
                            "endMinute": 59
                        },
                        {
                            "endHour": 10,
                            "workMode": "SelfUse",
                            "startHour": 10,
                            "extraParam": {
                                "fdPwr": 0.0,
                                "minSocOnGrid": 10.0,
                                "fdSoc": 10.0,
                                "maxSoc": 100.0
                            },
                            "startMinute": 0,
                            "endMinute": 59
                        },
                        {
                            "endHour": 11,
                            "workMode": "Backup",
                            "startHour": 11,
                            "extraParam": {
                                "fdPwr": 0.0,
                                "minSocOnGrid": 30.0,
                                "fdSoc": 10.0,
                                "maxSoc": 100.0
                            },
                            "startMinute": 0,
                            "endMinute": 59
                        },
                        {
                            "endHour": 23,
                            "workMode": "SelfUse",
                            "startHour": 12,
                            "extraParam": {
                                "fdPwr": 0.0,
                                "minSocOnGrid": 10.0,
                                "fdSoc": 10.0,
                                "maxSoc": 100.0
                            },
                            "startMinute": 0,
                            "endMinute": 59
                        }
                    ],
                    "properties": {
                        "startminute": {
                            "unit": "",
                            "precision": 1.0,
                            "range": {
                                "min": 0.0,
                                "max": 59.0
                            }
                        },
                        "fdpwr": {
                            "unit": "W",
                            "precision": 1.0,
                            "range": {
                                "min": 0.0,
                                "max": 12000.0
                            }
                        },
                        "endhour": {
                            "unit": "",
                            "precision": 1.0,
                            "range": {
                                "min": 0.0,
                                "max": 23.0
                            }
                        },
                        "endminute": {
                            "unit": "",
                            "precision": 1.0,
                            "range": {
                                "min": 0.0,
                                "max": 59.0
                            }
                        },
                        "fdsoc": {
                            "unit": "%",
                            "precision": 1.0,
                            "range": {
                                "min": 10.0,
                                "max": 100.0
                            }
                        },
                        "starthour": {
                            "unit": "",
                            "precision": 1.0,
                            "range": {
                                "min": 0.0,
                                "max": 23.0
                            }
                        },
                        "workmode": {
                            "enumList": [
                                "ForceDischarge",
                                "PeakShaving",
                                "Feedin",
                                "Backup",
                                "SelfUse",
                                "ForceCharge"
                            ],
                            "unit": "",
                            "precision": 1.0
                        },
                        "minsocongrid": {
                            "unit": "%",
                            "precision": 1.0,
                            "range": {
                                "min": 10.0,
                                "max": 100.0
                            }
                        },
                        "maxsoc": {
                            "unit": "%",
                            "precision": 1.0,
                            "range": {
                                "min": 10.0,
                                "max": 100.0
                            }
                        }
                    }
                }
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let res = fox.get_scheduler_time_segments().await.unwrap();

    assert_eq!(res.groups.len(), 7);
    assert_eq!(res.properties.work_mode.enum_list.len(), 6);
    assert_eq!(res.properties.work_mode.enum_list.contains(&FoxWorkModes::Unknown), false);
}

/// Verifies that scheduler time segments are correctly formatted to the API response, including enumeration values.
///
#[cfg(feature = "async")]
#[tokio::test]
async fn async_set_scheduler_time_segments() {
    use crate::Fox;
    use crate::FoxWorkModes;
    use crate::{ExtraParam, Group, TimeSegmentsDataRequest};

    const SN: &str = "TEST_SN";
    const TS: i64 = 1_700_000_000_000;
    const PATH: &str = "/op/v3/device/scheduler/enable";

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST)
            .path(PATH)
            .json_body(json!(
                {
                    "deviceSN": SN,
                    "isDefault": false,
                    "groups": [
                        {
                            "startHour": 0,
                            "startMinute": 0,
                            "endHour": 2,
                            "endMinute": 59,
                            "workMode": "ForceCharge",
                            "extraParam": {
                                "minSocOnGrid": 10.0,
                                "fdSoc": 80.0,
                                "fdPwr": 12000.0,
                                "maxSoc": 100.0
                            }
                        },
                        {
                            "startHour": 3,
                            "startMinute": 0,
                            "endHour": 7,
                            "endMinute": 59,
                            "workMode": "Backup"
                        },
                        {
                            "startHour": 8,
                            "startMinute": 0,
                            "endHour": 23,
                            "endMinute": 59,
                            "workMode": "SelfUse"
                        }
                    ]
                }));

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": null
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let ts = TimeSegmentsDataRequest {
        is_default: None,
        groups: vec![
            Group {
                start_hour: 0,
                start_minute: 0,
                end_hour: 2,
                end_minute: 59,
                work_mode: FoxWorkModes::ForceCharge,
                extra_param: Some(ExtraParam {
                    fd_pwr: Some(12000.0),
                    min_soc_on_grid: Some(10.0),
                    fd_soc: Some(80.0),
                    max_soc: Some(100.0),
                    import_limit: None,
                    export_limit: None,
                    pv_limit: None,
                    reactive_power: None,
                }),
            },
            Group {
                start_hour: 3,
                start_minute: 0,
                end_hour: 7,
                end_minute: 59,
                work_mode: FoxWorkModes::Backup,
                extra_param: None,
            },
            Group {
                start_hour: 8,
                start_minute: 0,
                end_hour: 23,
                end_minute: 59,
                work_mode: FoxWorkModes::SelfUse,
                extra_param: None,
            },
        ],
    };

    let _ = fox.set_scheduler_time_segments(&ts).await.unwrap();
}

/// Verifies that get main switch status is correctly parsed from the API response.
///
#[cfg(feature = "async")]
#[tokio::test]
async fn async_get_main_switch_status() {
    use crate::Fox;

    const SN: &str = "TEST_SN";
    const TS: i64 = 1_700_000_000_000;
    const PATH: &str = "/op/v1/device/scheduler/get/flag";

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST)
            .path(PATH)
            .json_body(json!(
                {
                    "deviceSN": SN,
                }));

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": {
                    "support": true,
                    "enable": false
                    }
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let res = fox.get_main_switch_status().await.unwrap();

    assert_eq!(res.support, true);
    assert_eq!(res.enable, false);
}

/// Verifies that set main switch status is correctly formatted to the API response.
///
#[cfg(feature = "async")]
#[tokio::test]
async fn async_set_main_switch_status() {
    use crate::Fox;

    const SN: &str = "TEST_SN";
    const TS: i64 = 1_700_000_000_000;
    const PATH: &str = "/op/v1/device/scheduler/set/flag";

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST)
            .path(PATH)
            .json_body(json!(
                {
                    "deviceSN": SN,
                    "enable": 1
                }));

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 0,
                "msg": "Operation successful",
                "result": null
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();

    let _ = fox.set_main_switch_status(true).await.unwrap();
}

/// Verifies that non-zero `errno` values in the API response are correctly mapped to `FoxError`.
#[cfg(feature = "async")]
#[tokio::test]
async fn async_errno_nonzero_maps_to_error() {
    use crate::{Fox, FoxSettings};

    const TS: i64 = 1_700_000_000_000;
    const PATH: &str = "/op/v0/device/setting/get";

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST).path(PATH);

        then.status(200)
            .header("Content-Type", "application/json")
            .body(r#"{
                "errno": 40256,
                "msg": "The request header parameters are missing",
                "result": null
            }"#);
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let err = fox.get_settings(vec![FoxSettings::MaxSetChargeCurrent]).await
        .err()
        .expect("get_settings should fail");

    let msg = format!("{err}");
    assert!(msg.contains("40256"));
    assert!(msg.contains("The request header parameters are missing"));
}

/// Verifies that HTTP status errors (e.g., 500 Internal Server Error) are correctly mapped to `FoxError`.
#[cfg(feature = "async")]
#[tokio::test]
async fn async_http_status_error_maps_to_error() {
    use crate::{Fox, FoxSettings};

    const TS: i64 = 1_700_000_000_000;
    const PATH: &str = "/op/v0/device/setting/get";

    fn fixed_now() -> i64 { TS }

    let server = MockServer::start();

    let _m = server.mock(|when, then| {
        when.method(POST).path(PATH);
        then.status(500).body("oops");
    });

    let fox = Fox::new_with_base_url_and_clock("TEST_API_KEY", "TEST_SN", 5, &server.base_url(), fixed_now).unwrap();
    let err = fox.get_settings(vec![FoxSettings::MaxSetChargeCurrent]).await
        .err()
        .expect("get_settings should fail");

    let msg = format!("{err}");
    assert!(msg.contains("500"));
}