matroskin 0.1.0

whatsminer api client lib
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
//! Device error codes for WhatsMiner ASIC devices.
//!
//! This module defines [`DeviceErrorCode`] — an enum representing all known
//! error codes that a WhatsMiner device can report via the `get.device.info`
//! API command.
//!
//! Each variant carries:
//! - A numeric **code** (returned by [`DeviceErrorCode::code`])
//! - A human-readable **reason** (via [`Display`](std::fmt::Display) and
//!   [`DeviceErrorCode::reason`])
//! - A recommended **processing method** ([`DeviceErrorCode::processing_method`])
//!
//! # Source
//!
//! <https://www.whatsminer.com/src/views/firmware-download.html#Document>

use std::{collections::HashMap, fmt};

// ---------------------------------------------------------------------------
// ChipId type for BBB codes
// ---------------------------------------------------------------------------

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum ChipId {
    All,
    Id(u16),
}

impl ChipId {
    pub const fn from_code(code: u16) -> Self {
        if code == 999 {
            Self::All
        } else {
            Self::Id(code)
        }
    }

    pub const fn code(&self) -> u16 {
        match self {
            Self::All => 999,
            Self::Id(id) => *id,
        }
    }
}

impl fmt::Debug for ChipId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::All => write!(f, "All"),
            Self::Id(id) => write!(f, "{}", id),
        }
    }
}

// ---------------------------------------------------------------------------
// Declarative macro for defining device error code variants
// ---------------------------------------------------------------------------

macro_rules! define_device_errors {
    (
        exact {
            $(
                $e_variant:ident = $e_code:literal => {
                    reason: $e_reason:literal,
                    method: $e_method:literal,
                }
            ),* $(,)?
        }
        range {
            $(
                $r_variant:ident { $r_field:ident: $r_ty:ty } = $( $r_start:literal ..= $r_end:literal )|+ , base: $r_base:literal => {
                    reason: $r_reason:literal,
                    method: $r_method:literal,
                }
            ),* $(,)?
        }
        bbb {
            $(
                $b_variant:ident = $b_start:literal ..= $b_end:literal, base: $b_base:literal => {
                    reason: $b_reason:literal,
                    method: $b_method:literal,
                }
            ),* $(,)?
        }
    ) => {
        /// Device error codes for WhatsMiner ASIC devices.
        #[derive(Clone, Copy, PartialEq, Eq, Hash)]
        pub enum DeviceErrorCode {
            $(
                $e_variant,
            )*
            $(
                $r_variant { $r_field: $r_ty },
            )*
            $(
                $b_variant { board: u8, chip: ChipId },
            )*
            Unknown(u32),
        }

        impl DeviceErrorCode {
            /// Map numeric error code to typed [`DeviceErrorCode`].
            pub const fn from_code(code: u32) -> Self {
                match code {
                    $(
                        $e_code => Self::$e_variant,
                    )*
                    $(
                        $( $r_start ..= $r_end )|+ => Self::$r_variant {
                            $r_field: (code - $r_base) as $r_ty,
                        },
                    )*
                    $(
                        $b_start ..= $b_end => {
                            let offset = code - $b_base;
                            Self::$b_variant {
                                board: (offset / 1000) as u8,
                                chip: ChipId::from_code((offset % 1000) as u16),
                            }
                        }
                    )*
                    _ => Self::Unknown(code),
                }
            }

            /// Return the numeric code.
            pub const fn code(&self) -> u32 {
                match self {
                    $(
                        Self::$e_variant => $e_code,
                    )*
                    $(
                        Self::$r_variant { $r_field } => $r_base + (*$r_field as u32),
                    )*
                    $(
                        Self::$b_variant { board, chip } => {
                            $b_base + (*board as u32) * 1000 + chip.code() as u32
                        }
                    )*
                    Self::Unknown(code) => *code,
                }
            }

            /// Human-readable reason string.
            pub const fn reason(&self) -> &'static str {
                match self {
                    $(
                        Self::$e_variant => $e_reason,
                    )*
                    $(
                        Self::$r_variant { .. } => $r_reason,
                    )*
                    $(
                        Self::$b_variant { .. } => $b_reason,
                    )*
                    Self::Unknown(_) => "Unknown error",
                }
            }

            /// Recommended processing or troubleshooting method.
            pub const fn processing_method(&self) -> &'static str {
                match self {
                    $(
                        Self::$e_variant => $e_method,
                    )*
                    $(
                        Self::$r_variant { .. } => $r_method,
                    )*
                    $(
                        Self::$b_variant { .. } => $b_method,
                    )*
                    Self::Unknown(_) => "N/A",
                }
            }
        }

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

        impl fmt::Debug for DeviceErrorCode {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "E{}", self.code())
            }
        }
    };
}

define_device_errors! {
    exact {
        FaninDetectSpeedError = 110 => {
            reason: "Fanin detect speed error",
            method: "Check fan connection, replace PSU or fan",
        },
        FanoutDetectSpeedError = 111 => {
            reason: "Fanout detect speed error",
            method: "Check fan connection, replace PSU or fan",
        },
        FaninSpeedError2k = 120 => {
            reason: "Fanin speed error (deviation 2000+)",
            method: "Check fan connection, replace PSU or fan",
        },
        FanoutSpeedError2k = 121 => {
            reason: "Fanout speed error (deviation 2000+)",
            method: "Check fan connection, replace PSU or fan",
        },
        FaninSpeedError3k = 130 => {
            reason: "Fanin speed error (deviation 3000+)",
            method: "Check fan connection, replace PSU or fan",
        },
        FanoutSpeedError3k = 131 => {
            reason: "Fanout speed error (deviation 3000+)",
            method: "Check fan connection, replace PSU or fan",
        },
        FanSpeedTooHigh = 140 => {
            reason: "Fan speed is too high",
            method: "Check ambient temperature",
        },
        PowerProbingError = 200 => {
            reason: "Power probing error, no power found",
            method: "Detect PSU flat cable, update firmware, or replace PSU",
        },
        PowerConfigMismatch = 201 => {
            reason: "Power supply and configuration file mismatch",
            method: "Confirm PSU type, replace with correct PSU",
        },
        PowerOutputVoltageError = 202 => {
            reason: "Power output voltage error",
            method: "Upgrade to latest firmware or check PSU",
        },
        PowerProtecting = 203 => {
            reason: "Power protecting",
            method: "Check ambient temperature",
        },
        PowerCurrentProtecting = 204 => {
            reason: "Power current protecting",
            method: "Check ambient temperature",
        },
        PowerCurrentError = 205 => {
            reason: "Power current error",
            method: "Check power supply of power grid",
        },
        PowerInputVoltageLow = 206 => {
            reason: "Power input voltage is low",
            method: "Improve power supply conditions, increase input voltage or replace PSU",
        },
        PowerInputCurrentProtecting = 207 => {
            reason: "Power input current protecting",
            method: "Improve power supply conditions and increase input voltage",
        },
        PowerSupplyChangesTooMuch = 208 => {
            reason: "Power supply changes too much",
            method: "Replace PSU",
        },
        PowerVoltageDeviation = 209 => {
            reason: "Deviation between PSU setting voltage and actual voltage",
            method: "Replace PSU",
        },
        PowerErrorStatus = 210 => {
            reason: "Power error status",
            method: "Check PSU failure code",
        },
        PowerOutputCurrentDeviation = 211 => {
            reason: "Power output current deviation is too large",
            method: "Replace PSU",
        },
        PowerOutputVoltageMarginInsufficient = 212 => {
            reason: "Power output voltage margin is insufficient",
            method: "Consult after-sales personnel",
        },
        PowerVoltageCurrentMismatch = 213 => {
            reason: "Power input voltage and current do not match",
            method: "Replace PSU",
        },
        PowerPinDidNotChange = 214 => {
            reason: "Power pin did not change",
            method: "Contact after-sales personnel",
        },
        PowerVoutSetError = 215 => {
            reason: "Power vout set error",
            method: "Contact after-sales personnel",
        },
        PowerRemainedUnchanged = 216 => {
            reason: "Power remained unchanged for a long time",
            method: "Replace PSU",
        },
        PowerSetEnableError = 217 => {
            reason: "Power set enable error",
            method: "Replace PSU",
        },
        PowerInputVoltageBelow230v = 218 => {
            reason: "Power input voltage lower than 230V for high power mode",
            method: "Improve power supply conditions, increase input voltage or replace PSU",
        },
        PowerInputCurrentIncorrect = 219 => {
            reason: "Power input current is incorrect",
            method: "Replace PSU",
        },
        PowerOutputOvervoltageProtection = 239 => {
            reason: "Overvoltage protection of power output",
            method: "Check power supply of power grid",
        },
        PowerOutputUndervoltageProtection = 240 => {
            reason: "Low voltage protection for power output",
            method: "Check power supply of power grid",
        },
        PowerOutputCurrentImbalance = 241 => {
            reason: "Power output current imbalance",
            method: "Replace PSU",
        },
        PowerPrimarySideOvercurrent = 257 => {
            reason: "Input over current protection of PSU primary side",
            method: "Power off and restart, replace PSU if no effect",
        },
        PowerInputVoltageImbalanceWarning = 258 => {
            reason: "Power input three-phase voltage imbalance warning",
            method: "Check power supply of power grid",
        },
        PowerInputVoltageUnbalance = 259 => {
            reason: "Power input three-phase voltage unbalance protection",
            method: "Check power supply of power grid",
        },
        PowerCommunicationWarning = 263 => {
            reason: "Power communication warning",
            method: "Check if control board screws are locked",
        },
        PowerCommunicationError = 264 => {
            reason: "Power communication error",
            method: "Check if control board screws are locked",
        },
        PowerWatchdogProtection = 267 => {
            reason: "Power watchdog protection",
            method: "Contact after-sales personnel",
        },
        PowerOutputOverCurrent = 268 => {
            reason: "Power output over-current protection",
            method: "Check ambient temperature and screws of copper bar",
        },
        PowerInputOverCurrent = 269 => {
            reason: "Power input over-current protection",
            method: "Improve power supply conditions and increase input voltage",
        },
        PowerInputOverVoltage = 270 => {
            reason: "Power input over-voltage protection",
            method: "Check power supply of power grid",
        },
        PowerInputUnderVoltage = 271 => {
            reason: "Power input under-voltage protection",
            method: "Check power supply of power grid",
        },
        PowerOutputExcessiveWarning = 272 => {
            reason: "Warning of excessive power output",
            method: "Check ambient temperature",
        },
        PowerInputPowerTooHighWarning = 273 => {
            reason: "Power input power too high warning",
            method: "Check ambient temperature",
        },
        PowerFanWarning = 274 => {
            reason: "Power fan warning",
            method: "Check if PSU fan is blocked or replace PSU",
        },
        PowerOverTemperatureWarning = 275 => {
            reason: "Power over temperature warning",
            method: "Check ambient temperature",
        },
        AllTempSensorDetectionError = 309 => {
            reason: "All temperature sensor detection errors",
            method: "Check the wiring of the hashboard",
        },
        LiquidCoolingTempSensorError = 326 => {
            reason: "Liquid cooling temperature sensor communication error",
            method: "Replace PSU",
        },
        ControlBoardTempSensorError = 329 => {
            reason: "Control board temperature sensor communication error",
            method: "Replace PSU",
        },
        HashboardOverheating = 360 => {
            reason: "Hashboard temperature overheating",
            method: "Check ambient temperature",
        },
        EnvTempFluctuationTooMuch = 370 => {
            reason: "Environment temperature fluctuates too much",
            method: "Check ambient temperature, wind direction and speed",
        },
        NoSoftwareConfig = 500 => {
            reason: "No software configuration added for model",
            method: "Upgrade to latest firmware",
        },
        EnvTempHigh = 600 => {
            reason: "Environment temperature is high",
            method: "Check ambient temperature (below 35°C in normal mode)",
        },
        EnvTempTooHighPerfMode = 610 => {
            reason: "Ambient temperature too high in high performance mode",
            method: "Check ambient temperature (below 30°C in performance mode)",
        },
        LiquidCoolingTempProtection = 620 => {
            reason: "Liquid cooling liquid temperature protection",
            method: "Check liquid temperature",
        },
        LiquidTempFluctuationTooLarge = 652 => {
            reason: "Liquid temperature fluctuation is too large",
            method: "Check liquid temperature",
        },
        ControlBoardNoSupportChip = 701 => {
            reason: "Control board no support chip",
            method: "Upgrade firmware of corresponding type",
        },
        ControlBoardVersionUnknown = 702 => {
            reason: "Control board version unknown",
            method: "Contact after-sales personnel",
        },
        ControlBoardRebootedException0 = 710 => {
            reason: "Control board rebooted as exception",
            method: "Update firmware, check control board screws, replace if needed",
        },
        ControlBoardRebootedException1 = 712 => {
            reason: "Control board rebooted as exception",
            method: "Update firmware, check control board screws, replace if needed",
        },
        NetworkConnectionUnstable = 714 => {
            reason: "Network connection is seriously unstable",
            method: "Check network cable or replace control board",
        },
        CgminerChecksumError = 800 => {
            reason: "Cgminer checksum error",
            method: "Re-upgrade firmware",
        },
        SystemMonitorChecksumError = 801 => {
            reason: "System-monitor checksum error",
            method: "Re-upgrade firmware",
        },
        RemoteDaemonChecksumError = 802 => {
            reason: "Remote-daemon checksum error",
            method: "Re-upgrade firmware",
        },
        AirToLiquidPcbsnMismatch = 810 => {
            reason: "Air to liquid or frequency and PCBSN mismatch",
            method: "Re-upgrade air to liquid cooling firmware or re-adjust frequency",
        },
        AirToLiquidPsusnMismatch = 820 => {
            reason: "Air to liquid or frequency and PSUSN mismatch",
            method: "Re-upgrade air to liquid cooling firmware or re-adjust frequency",
        },
        PowerRateError = 901 => {
            reason: "Power rate error",
            method: "Check if miner has been modified",
        },
        NoPoolConfigured = 2000 => {
            reason: "No pool information configured",
            method: "Check pool configuration",
        },
        AllPoolsDisabled = 2010 => {
            reason: "All pools are disabled",
            method: "Check network environment or pool configuration",
        },
        Pool0ConnectFailed = 2020 => {
            reason: "Pool0 connect failed",
            method: "Check network environment or pool configuration",
        },
        Pool1ConnectFailed = 2021 => {
            reason: "Pool1 connect failed",
            method: "Check network environment or pool configuration",
        },
        Pool2ConnectFailed = 2022 => {
            reason: "Pool2 connect failed",
            method: "Check network environment or pool configuration",
        },
        PoolHighRejectionRate = 2030 => {
            reason: "High rejection rate of pool",
            method: "Check network, pool configuration, and mining currency",
        },
        PoolNoAsicboost = 2040 => {
            reason: "Pool does not support asicboost mode",
            method: "Check pool configuration",
        },
        PoolSwitchFailed = 2050 => {
            reason: "Failed to switch to new pool",
            method: "Check network environment or pool configuration",
        },
        HashRateTooLow0 = 2310 => {
            reason: "Hash rate is too low",
            method: "Check power supply, network, and ambient temperature",
        },
        HashRateTooLow1 = 2320 => {
            reason: "Hash rate is too low",
            method: "Check power supply, network, and ambient temperature",
        },
        HashRateLossTooHigh0 = 2340 => {
            reason: "Loss of hash rate is too high",
            method: "Check power supply, network, and ambient temperature",
        },
        HashRateLossTooHigh1 = 2350 => {
            reason: "Loss of hash rate is too high",
            method: "Check power supply, network, and ambient temperature",
        },
        ChipTempCalibrationAbnormal = 5090 => {
            reason: "Chip temperature calibration abnormality",
            method: "Stop miner, restart, or restore factory settings",
        },
        ToolVersionTooLow = 8000 => {
            reason: "WhatsminerTool version is too low",
            method: "Download latest WhatsminerTool",
        },
        FrequencyNotStandard = 8010 => {
            reason: "Frequency is not up to standard",
            method: "Upgrade firmware or restore factory settings",
        },
        HashrateNotStandard = 8020 => {
            reason: "Hashrate is not up to standard",
            method: "Upgrade firmware or restore factory settings",
        },
        WrongSoftwareVersion = 8400 => {
            reason: "Wrong software version",
            method: "Upgrade to correct official firmware",
        },
        WrongSoftwareVersionM2xM3x = 8410 => {
            reason: "Wrong software version (M2x/M3x mismatch)",
            method: "Upgrade to correct firmware version",
        },
        MinerPsuModelMismatch = 8700 => {
            reason: "Miner and PSU model mismatch",
            method: "Replace with correct PSU",
        },
        SecurityLibraryError = 100000 => {
            reason: "Security library error",
            method: "Upgrade firmware or burn card",
        },
        SecuritySignatureIllegal = 100001 => {
            reason: "/antiv/signature illegal",
            method: "Upgrade firmware or burn card",
        },
        SecurityDigInitdIllegal = 100002 => {
            reason: "/antiv/dig/initd.dig illegal",
            method: "Upgrade firmware or burn card",
        },
        SecurityDigPfPartialIllegal = 100003 => {
            reason: "/antiv/dig/pf_partial.dig illegal",
            method: "Upgrade firmware or burn card",
        },
        SecurityBtminerRemoved = 100100 => {
            reason: "Security btminer be removed",
            method: "Upgrade firmware or burn card",
        },
        SecurityIllegalFile = 110000 => {
            reason: "Security illegal file",
            method: "Upgrade firmware or burn card",
        },
        SecurityVirus0001 = 110001 => {
            reason: "Security virus 0001 is removed",
            method: "Upgrade firmware or burn card",
        },
    }
    range {
        PowerOutputOverTempProtection { index: u8 } = 233 ..= 235, base: 233 => {
            reason: "Power output over temperature protection",
            method: "Check ambient temperature",
        },
        PowerOutputOvercurrentProtection { index: u8 } = 236 ..= 238, base: 236 => {
            reason: "Overcurrent protection of power output",
            method: "Check ambient temperature and screws of copper bar",
        },
        PowerInputOverTempProtection { index: u8 } = 243 ..= 245, base: 243 => {
            reason: "Over-temperature protection for power input",
            method: "Check ambient temperature",
        },
        PowerInputOvercurrentProtection { index: u8 } = 246 ..= 247, base: 246 => {
            reason: "Overcurrent protection for power input",
            method: "Replace PSU",
        },
        PowerInputOvervoltageProtection { index: u8 } = 248 ..= 249, base: 248 => {
            reason: "Overvoltage protection for power input",
            method: "Check power supply of power grid",
        },
        PowerInputUndervoltageProtection { index: u8 } = 250 ..= 251, base: 250 => {
            reason: "Undervoltage protection for power input",
            method: "Check power supply of power grid",
        },
        PowerFanError { index: u8 } = 253 ..= 254, base: 253 => {
            reason: "Power fan error",
            method: "Replace PSU",
        },
        PowerOutputOverpowerProtection { index: u8 } = 255 ..= 256, base: 255 => {
            reason: "Protection of over power output",
            method: "Check ambient temperature",
        },
        PowerCustomRegisterError { index: u8 } = 280 ..= 299, base: 280 => {
            reason: "Power custom register error",
            method: "Contact after-sales personnel",
        },
        SmxTempSensorDetection { board: u8 } = 300 ..= 309, base: 300 => {
            reason: "SMX temperature sensor detection error",
            method: "Check the wiring of the hashboard",
        },
        SmxTempReadingError { board: u8 } = 320 ..= 325 | 327 ..= 328, base: 320 => {
            reason: "SMX temperature reading error",
            method: "Check control board screws and adapter board contact",
        },
        SmxTempProtecting { board: u8 } = 350 ..= 359, base: 350 => {
            reason: "SMX temperature protecting",
            method: "Check ambient temperature",
        },
        SmxDetectEepromError { board: u8 } = 410 ..= 419, base: 410 => {
            reason: "SMX detect eeprom error",
            method: "Check adapter board and flat cable contact",
        },
        SmxParserEepromError { board: u8 } = 420 ..= 429, base: 420 => {
            reason: "SMX parser eeprom error",
            method: "Upgrade to latest firmware",
        },
        SmxChipBinTypeError { board: u8 } = 430 ..= 439, base: 430 => {
            reason: "SMX chip bin type error",
            method: "Upgrade to latest firmware",
        },
        SmxEepromChipNumError { board: u8 } = 440 ..= 449, base: 440 => {
            reason: "SMX eeprom chip num error",
            method: "Upgrade to latest firmware",
        },
        SmxEepromXferError { board: u8 } = 450 ..= 459, base: 450 => {
            reason: "SMX eeprom xfer error",
            method: "Check adapter board contact and upgrade firmware",
        },
        SmxMinerTypeError { board: u8 } = 510 ..= 519, base: 510 => {
            reason: "SMX miner type error",
            method: "Replace with correct hashboard",
        },
        SmxBinTypeError { board: u8 } = 520 ..= 529, base: 520 => {
            reason: "SMX bin type error",
            method: "Replace with correct hashboard",
        },
        SmxNotFound { board: u8 } = 530 ..= 539, base: 530 => {
            reason: "SMX not found",
            method: "Check adapter board connection and flat cable",
        },
        SmxReadingChipIdError { board: u8 } = 540 ..= 549, base: 540 => {
            reason: "SMX reading chip id error",
            method: "Power off, re-plug adapter board or swap hashboards",
        },
        SmxBadChips { board: u8 } = 550 ..= 559, base: 550 => {
            reason: "SMX have bad chips",
            method: "Contact after-sales personnel",
        },
        SmxLossBalance { board: u8 } = 560 ..= 569, base: 560 => {
            reason: "SMX loss balance",
            method: "Power off, re-plug adapter board or swap hashboards",
        },
        SmxXferErrorChip { board: u8 } = 570 ..= 579, base: 570 => {
            reason: "SMX xfer error chip",
            method: "Contact after-sales personnel",
        },
        SmxResetError { board: u8 } = 580 ..= 589, base: 580 => {
            reason: "SMX reset error",
            method: "If hashrate is abnormal, consult after-sales",
        },
        SmxFrequencyTooLow { board: u8 } = 590 ..= 599, base: 590 => {
            reason: "SMX frequency too low",
            method: "Contact after-sales personnel",
        },
        SmxSerialPortCommError { board: u8 } = 720 ..= 729, base: 720 => {
            reason: "SMX serial port communication error",
            method: "Upgrade firmware or replace control board",
        },
        ProcessExitedAbnormally { process: u8 } = 9000 ..= 9099, base: 9000 => {
            reason: "The process exited abnormally",
            method: "Upgrade newest firmware, consult after-sales if needed",
        },
        SmxChipVoltageTooLow { board: u8 } = 5010 ..= 5019, base: 5010 => {
            reason: "SMX chip voltage too low",
            method: "Contact after-sales personnel",
        },
        ChipVoltageChange { board: u8 } = 5020 ..= 5029, base: 5020 => {
            reason: "Chip voltage change",
            method: "Replace PSU",
        },
        SmxChipTempDiffTooLarge { board: u8 } = 5030 ..= 5039, base: 5030 => {
            reason: "SMX chip max-min temperature difference too large",
            method: "Check heat dissipation of miner",
        },
        SmxTempMaxChipTempDiff { board: u8 } = 5040 ..= 5049, base: 5040 => {
            reason: "SMX temperature maximum chip temperature difference too large",
            method: "Check heat dissipation of miner",
        },
        SmxChipTempProtection { board: u8 } = 5050 ..= 5059, base: 5050 => {
            reason: "SMX chip temperature protection",
            method: "Check ambient temperature",
        },
        SmxLiquidVelocityAbnormal { board: u8 } = 5070 ..= 5078, base: 5070 => {
            reason: "SMX liquid velocity is abnormal",
            method: "Check if water flow is normal",
        },
        SmxChipTempCalibrationFailed { board: u8 } = 5080 ..= 5089, base: 5080 => {
            reason: "SMX chip temperature calibration failed",
            method: "Restore factory settings and recalibrate",
        },
        SmxFrequencyUpTimeout { board: u8 } = 5110 ..= 5119, base: 5110 => {
            reason: "SMX frequency up timeout",
            method: "Reboot, tighten copper bar screws, or upgrade firmware",
        },
    }
    bbb {
        SmxChipBbbErrorNonce = 520000 ..= 529999, base: 520000 => {
            reason: "SMX chip BBB error nonce",
            method: "Contact after-sales personnel",
        },
        SmxChipBbbFewNonce = 530000 ..= 539999, base: 530000 => {
            reason: "SMX chip BBB few nonce",
            method: "Contact after-sales personnel",
        },
        SmxChipBbbTempProtected = 540000 ..= 549999, base: 540000 => {
            reason: "SMX chip BBB temp protected",
            method: "Restart miner, contact after-sales if persists",
        },
        SmxChipBbbReset = 550000 ..= 559999, base: 550000 => {
            reason: "SMX chip BBB is reset",
            method: "Replace PSU, contact after-sales if persists",
        },
        SmxChipBbbNoNonce = 560000 ..= 569999, base: 560000 => {
            reason: "SMX chip BBB does not return nonce",
            method: "Replace PSU, contact after-sales if persists",
        },
    }
}

// ---------------------------------------------------------------------------
// PSU error flags
// ---------------------------------------------------------------------------

bitflags::bitflags! {
    /// PSU error flags reported as hexadecimal bit masks (for example `0x0001`).
    #[derive(Clone, Copy, PartialEq, Eq, Hash)]
    pub struct PsuErrorCode: u16 {
        const INPUT_VOLTAGE_LOW = 0x0001;
        const RADIATOR_OVER_TEMP_0 = 0x0002;
        const RADIATOR_OVER_TEMP_1 = 0x0004;
        const ENV_OVER_TEMP = 0x0008;
        const PRIMARY_SIDE_OVER_CURRENT_0 = 0x0010;
        const OUTPUT_UNDERVOLTAGE = 0x0020;
        const OUTPUT_OVER_CURRENT_320A = 0x0040;
        const PRIMARY_SIDE_OVER_CURRENT_1 = 0x0080;
        const SINGLE_CIRCUIT_OVER_CURRENT_0 = 0x0100;
        const SINGLE_CIRCUIT_OVER_CURRENT_1 = 0x0200;
        const SINGLE_CIRCUIT_OVER_CURRENT_2 = 0x0400;
        const FAN_FAILURE = 0x0800;
        const OUTPUT_OVER_CURRENT_310A = 0x1000;
        const OUTPUT_OVER_CURRENT_295A = 0x2000;
    }
}

impl PsuErrorCode {
    pub const fn from_code(code: u16) -> Self {
        Self::from_bits_retain(code)
    }

    pub const fn code(&self) -> u16 {
        self.bits()
    }

    pub fn reasons(&self) -> Vec<&'static str> {
        PSU_ERROR_DESCRIPTIONS
            .iter()
            .filter_map(|(flag, reason, _)| self.contains(*flag).then_some(*reason))
            .collect()
    }

    pub fn processing_methods(&self) -> Vec<&'static str> {
        PSU_ERROR_DESCRIPTIONS
            .iter()
            .filter_map(|(flag, _, method)| self.contains(*flag).then_some(*method))
            .collect()
    }

    pub fn reason(&self) -> String {
        join_descriptions(self.reasons(), "Unknown PSU error")
    }

    pub fn processing_method(&self) -> String {
        join_descriptions(self.processing_methods(), "N/A")
    }
}

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

impl fmt::Debug for PsuErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "E0x{:04X}", self.code())
    }
}

const PSU_ERROR_DESCRIPTIONS: &[(PsuErrorCode, &str, &str)] = &[
    (
        PsuErrorCode::INPUT_VOLTAGE_LOW,
        "Input voltage is too low, need improvement",
        "Check the power provided from the power supply",
    ),
    (
        PsuErrorCode::RADIATOR_OVER_TEMP_0,
        "Temperature sampling over temperature protection of power radiator",
        "Turn off the power for 10 minutes and then turn it back on. If the phenomenon recurs, replace the power supply",
    ),
    (
        PsuErrorCode::RADIATOR_OVER_TEMP_1,
        "Temperature sampling over temperature protection of power radiator",
        "Turn off the power for ten minutes and then turn it back on. If the phenomenon recurs, replace the power supply",
    ),
    (
        PsuErrorCode::ENV_OVER_TEMP,
        "Over temperature protection of environmental temperature sampling in power supply",
        "Turn off the power for ten minutes and then turn it back on. If the phenomenon recurs, replace the power supply",
    ),
    (
        PsuErrorCode::PRIMARY_SIDE_OVER_CURRENT_0,
        "Primary side over current",
        "Turn off the power for ten minutes and then turn it back on. If the phenomenon recurs, replace the power supply",
    ),
    (
        PsuErrorCode::OUTPUT_UNDERVOLTAGE,
        "Output undervoltage",
        "Check the power provided from the power supply",
    ),
    (
        PsuErrorCode::OUTPUT_OVER_CURRENT_320A,
        "Output over current (continuous load 320A for more than 2S)",
        "Tighten screws of the copper bar again",
    ),
    (
        PsuErrorCode::PRIMARY_SIDE_OVER_CURRENT_1,
        "Primary side over current",
        "Turn off the power for ten minutes and then turn it back on. If the phenomenon recurs, replace the power supply",
    ),
    (
        PsuErrorCode::SINGLE_CIRCUIT_OVER_CURRENT_0,
        "Single circuit overcurrent (protection point 120A)",
        "Tighten screws of the copper bar again",
    ),
    (
        PsuErrorCode::SINGLE_CIRCUIT_OVER_CURRENT_1,
        "Single circuit overcurrent (protection point 120A)",
        "Tighten screws of the copper bar again",
    ),
    (
        PsuErrorCode::SINGLE_CIRCUIT_OVER_CURRENT_2,
        "Single circuit overcurrent (protection point 120A)",
        "Tighten screws of the copper bar again",
    ),
    (
        PsuErrorCode::FAN_FAILURE,
        "Fan failure",
        "Replace the power supply",
    ),
    (
        PsuErrorCode::OUTPUT_OVER_CURRENT_310A,
        "Output over current (continuous load of 310A for more than 5min)",
        "Tighten screws of the copper bar again",
    ),
    (
        PsuErrorCode::OUTPUT_OVER_CURRENT_295A,
        "Output over current (continuous load 295A for more than 10min)",
        "Tighten screws of the copper bar again",
    ),
];

fn join_descriptions(parts: Vec<&'static str>, fallback: &'static str) -> String {
    if parts.is_empty() {
        fallback.to_string()
    } else {
        parts.join("; ")
    }
}

// ---------------------------------------------------------------------------
// Unified error code
// ---------------------------------------------------------------------------

/// Unified error code type for device decimal codes and PSU hexadecimal bit masks.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorCode {
    Device(DeviceErrorCode),
    Psu(PsuErrorCode),
}

impl ErrorCode {
    pub fn reason(&self) -> String {
        match self {
            Self::Device(code) => code.reason().to_string(),
            Self::Psu(code) => code.reason(),
        }
    }

    pub fn processing_method(&self) -> String {
        match self {
            Self::Device(code) => code.processing_method().to_string(),
            Self::Psu(code) => code.processing_method(),
        }
    }

    fn parse_str(value: &str) -> Result<Self, String> {
        let value = value.trim();
        // This is interesting behavior because the “E” prefix is not mentioned in the documentation, but it is present on the actual device
        let value = value
            .strip_prefix('E')
            .or_else(|| value.strip_prefix('e'))
            .unwrap_or(value);

        if let Some(hex) = value
            .strip_prefix("0x")
            .or_else(|| value.strip_prefix("0X"))
        {
            let code = u16::from_str_radix(hex, 16)
                .map_err(|err| format!("invalid PSU error code `{value}`: {err}"))?;
            return Ok(Self::Psu(PsuErrorCode::from_code(code)));
        }

        let code = value
            .parse::<u32>()
            .map_err(|err| format!("invalid device error code `{value}`: {err}"))?;
        Ok(Self::Device(DeviceErrorCode::from_code(code)))
    }
}

impl fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Device(code) => fmt::Display::fmt(code, f),
            Self::Psu(code) => fmt::Display::fmt(code, f),
        }
    }
}

impl fmt::Debug for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Device(code) => fmt::Debug::fmt(code, f),
            Self::Psu(code) => fmt::Debug::fmt(code, f),
        }
    }
}

impl<'de> serde::Deserialize<'de> for ErrorCode {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Visitor;

        struct ErrorCodeVisitor;

        impl Visitor<'_> for ErrorCodeVisitor {
            type Value = ErrorCode;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("decimal device error code or hexadecimal PSU error code")
            }

            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                let code = u32::try_from(value)
                    .map_err(|_| E::custom(format!("device error code out of range: {value}")))?;
                Ok(ErrorCode::Device(DeviceErrorCode::from_code(code)))
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                ErrorCode::parse_str(value).map_err(E::custom)
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                self.visit_str(&value)
            }
        }

        deserializer.deserialize_any(ErrorCodeVisitor)
    }
}

// ---------------------------------------------------------------------------
// DeviceErrorEntry — deserialized from API response
// ---------------------------------------------------------------------------

/// A single error entry returned by the `get.device.info` API.
///
/// The API returns each error as a flat JSON object:
///
/// ```json
/// { "E531": "2025-03-12 14:52:35", "reason": "Slot1 not found." }
/// ```
///
/// where the numeric key is the error code and its value is the timestamp.
#[derive(Debug, Clone, PartialEq)]
pub struct DeviceErrorEntry {
    /// The parsed error code.
    pub code: ErrorCode,
    /// When the error occurred.
    pub timestamp: String,
    /// Reason string from the API (may be more specific than
    /// [`ErrorCode::reason`]).
    pub reason: String,
}

impl<'de> serde::Deserialize<'de> for DeviceErrorEntry {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Error as _;

        let map = HashMap::<String, String>::deserialize(deserializer)?;

        let mut code: Option<ErrorCode> = None;
        let mut timestamp = None;
        let mut reason = None;

        for (key, value) in map {
            match key.as_str() {
                "reason" => reason = Some(value),
                _ => {
                    let code_deserializer =
                        serde::de::value::StrDeserializer::<D::Error>::new(&key);
                    code = Some(ErrorCode::deserialize(code_deserializer)?);
                    timestamp = Some(value);
                }
            }
        }

        Ok(Self {
            code: code.ok_or_else(|| D::Error::custom("missing error code key"))?,
            timestamp: timestamp.ok_or_else(|| D::Error::custom("missing timestamp"))?,
            reason: reason.ok_or_else(|| D::Error::custom("missing reason"))?,
        })
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn exact_code_roundtrip() {
        let err = DeviceErrorCode::from_code(110);
        assert_eq!(err.code(), 110);
        assert_eq!(err.reason(), "Fanin detect speed error");
        assert!(err.processing_method().contains("fan"));
        assert_eq!(format!("{err}"), "Fanin detect speed error");
        assert_eq!(format!("{err:?}"), "E110");
    }

    #[test]
    fn range_code_roundtrip() {
        let err = DeviceErrorCode::from_code(531);
        assert_eq!(err.code(), 531);
        assert_eq!(err.reason(), "SMX not found");
    }

    #[test]
    fn bbb_code_roundtrip() {
        let err = DeviceErrorCode::from_code(550999);
        assert_eq!(err.code(), 550999); // retains full BBB suffix
        assert!(err.reason().contains("BBB"));
    }

    #[test]
    fn range_boundaries_roundtrip() {
        // PowerOutputOverTempProtection 233..=235
        let start = DeviceErrorCode::from_code(233);
        assert_eq!(start.code(), 233);
        assert!(matches!(
            start,
            DeviceErrorCode::PowerOutputOverTempProtection { index: 0 }
        ));
        let end = DeviceErrorCode::from_code(235);
        assert_eq!(end.code(), 235);
        assert!(matches!(
            end,
            DeviceErrorCode::PowerOutputOverTempProtection { index: 2 }
        ));

        // Split range: SmxTempReadingError 320..=325 | 327..=328
        let s1 = DeviceErrorCode::from_code(320);
        assert_eq!(s1.code(), 320);
        assert!(matches!(
            s1,
            DeviceErrorCode::SmxTempReadingError { board: 0 }
        ));
        let e1 = DeviceErrorCode::from_code(325);
        assert_eq!(e1.code(), 325);
        assert!(matches!(
            e1,
            DeviceErrorCode::SmxTempReadingError { board: 5 }
        ));

        // In-between exact codes:
        assert_eq!(DeviceErrorCode::from_code(326).code(), 326);
        assert!(matches!(
            DeviceErrorCode::from_code(326),
            DeviceErrorCode::LiquidCoolingTempSensorError
        ));

        let s2 = DeviceErrorCode::from_code(327);
        assert_eq!(s2.code(), 327);
        assert!(matches!(
            s2,
            DeviceErrorCode::SmxTempReadingError { board: 7 }
        ));
        let e2 = DeviceErrorCode::from_code(328);
        assert_eq!(e2.code(), 328);
        assert!(matches!(
            e2,
            DeviceErrorCode::SmxTempReadingError { board: 8 }
        ));

        // ProcessExitedAbnormally 9000..=9008
        let p_start = DeviceErrorCode::from_code(9000);
        assert_eq!(p_start.code(), 9000);
        assert!(matches!(
            p_start,
            DeviceErrorCode::ProcessExitedAbnormally { process: 0 }
        ));
        let p_end = DeviceErrorCode::from_code(9008);
        assert_eq!(p_end.code(), 9008);
        assert!(matches!(
            p_end,
            DeviceErrorCode::ProcessExitedAbnormally { process: 8 }
        ));
    }

    #[test]
    fn bbb_boundaries_roundtrip() {
        // SmxChipBbbErrorNonce 520000..=529999
        let b0 = DeviceErrorCode::from_code(520000);
        assert_eq!(b0.code(), 520000);
        assert!(matches!(
            b0,
            DeviceErrorCode::SmxChipBbbErrorNonce {
                board: 0,
                chip: ChipId::Id(0)
            }
        ));

        let b_all = DeviceErrorCode::from_code(520999);
        assert_eq!(b_all.code(), 520999);
        assert!(matches!(
            b_all,
            DeviceErrorCode::SmxChipBbbErrorNonce {
                board: 0,
                chip: ChipId::All
            }
        ));

        let b1_chip42 = DeviceErrorCode::from_code(521042);
        assert_eq!(b1_chip42.code(), 521042);
        assert!(matches!(
            b1_chip42,
            DeviceErrorCode::SmxChipBbbErrorNonce {
                board: 1,
                chip: ChipId::Id(42)
            }
        ));

        // Last BBB: SmxChipBbbNoNonce 560000..=569999
        let b_last = DeviceErrorCode::from_code(569999);
        assert_eq!(b_last.code(), 569999);
        assert!(matches!(
            b_last,
            DeviceErrorCode::SmxChipBbbNoNonce {
                board: 9,
                chip: ChipId::All
            }
        ));
    }
    #[test]
    fn unknown_code() {
        let err = DeviceErrorCode::from_code(99999);
        assert_eq!(err.code(), 99999);
        assert_eq!(err.reason(), "Unknown error");
        assert_eq!(err.processing_method(), "N/A");
    }

    #[test]
    fn deserialize_error_entry() {
        let json = r#"{"531":"2025-03-12 14:52:35","reason":"Slot1 not found."}"#;
        let entry: DeviceErrorEntry = serde_json::from_str(json).unwrap();
        assert!(matches!(entry.code, ErrorCode::Device(code) if code.code() == 531));
        assert_eq!(entry.timestamp, "2025-03-12 14:52:35");
        assert_eq!(entry.reason, "Slot1 not found.");
    }

    #[test]
    fn deserialize_error_entry_with_e_prefix() {
        let json = r#"{"E2010":"2026-05-01 12:28:18","reason":"All pools disabled"}"#;
        let entry: DeviceErrorEntry = serde_json::from_str(json).unwrap();
        assert!(matches!(entry.code, ErrorCode::Device(code) if code.code() == 2010));
        assert_eq!(entry.timestamp, "2026-05-01 12:28:18");
        assert_eq!(entry.reason, "All pools disabled");
    }

    #[test]
    fn deserialize_psu_error_code_with_e_prefix() {
        let code: ErrorCode = serde_json::from_str(r#""E0x0001""#).unwrap();
        assert!(
            matches!(code, ErrorCode::Psu(psu) if psu.contains(PsuErrorCode::INPUT_VOLTAGE_LOW))
        );
    }

    #[test]
    fn deserialize_psu_error_code() {
        let code: ErrorCode = serde_json::from_str(r#""0x0001""#).unwrap();
        assert!(
            matches!(code, ErrorCode::Psu(psu) if psu.contains(PsuErrorCode::INPUT_VOLTAGE_LOW))
        );
        assert_eq!(format!("{code:?}"), "E0x0001");
        assert!(code.reason().contains("Input voltage"));
    }

    #[test]
    fn deserialize_combined_psu_flags() {
        let code: ErrorCode = serde_json::from_str(r#""0x0801""#).unwrap();
        let ErrorCode::Psu(psu) = code else {
            panic!("expected PSU code");
        };
        assert!(psu.contains(PsuErrorCode::INPUT_VOLTAGE_LOW));
        assert!(psu.contains(PsuErrorCode::FAN_FAILURE));
        assert!(code.reason().contains("Input voltage"));
        assert!(code.reason().contains("Fan failure"));
    }

    #[test]
    fn deserialize_psu_error_entry() {
        let json = r#"{"0x0001":"2025-03-12 14:52:35","reason":"code: 0x1"}"#;
        let entry: DeviceErrorEntry = serde_json::from_str(json).unwrap();
        assert!(
            matches!(entry.code, ErrorCode::Psu(psu) if psu.contains(PsuErrorCode::INPUT_VOLTAGE_LOW))
        );
        assert_eq!(entry.timestamp, "2025-03-12 14:52:35");
        assert_eq!(entry.reason, "code: 0x1");
    }
}