ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
//! Advanced Fan Monitoring and Control
//!
//! This module provides comprehensive fan monitoring capabilities including:
//! - PWM (Pulse Width Modulation) control
//! - RPM (Revolutions Per Minute) monitoring
//! - Fan profiles (quiet, cool, performance, manual)
//! - Thermal zone integration
//! - Multi-platform support (Linux hwmon, Windows WMI)
//!
//! # Example
//!
//! ```no_run
//! use ironmonitor::fan_control::{FanMonitor, FanProfile};
//!
//! let monitor = FanMonitor::new().unwrap();
//!
//! // List all fans
//! for fan in monitor.fans() {
//!     match (fan.speed_percent, fan.rpm) {
//!         (Some(pct), Some(rpm)) => println!("Fan: {} - {}% @ {} RPM", fan.name, pct, rpm),
//!         (Some(pct), None) => println!("Fan: {} - {}%, no tachometer", fan.name, pct),
//!         (None, Some(rpm)) => println!("Fan: {} - {} RPM, speed not read", fan.name, rpm),
//!         (None, None) => println!("Fan: {} - no readings", fan.name),
//!     }
//! }
//!
//! // Set fan profile
//! monitor.set_profile("cpu_fan", FanProfile::Quiet).unwrap();
//! ```

use crate::error::{IronError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::{Duration, Instant};

/// Fan profile presets
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FanProfile {
    /// Silent operation - minimum fan speed
    Silent,
    /// Quiet operation - balanced noise/cooling
    Quiet,
    /// Cool operation - prioritize cooling
    Cool,
    /// Performance - maximum cooling
    Performance,
    /// Manual - user-controlled speed
    Manual,
    /// Automatic - system-controlled based on temperature
    Auto,
    /// Temperature-controlled (legacy Jetson)
    TempControl,
}

impl std::fmt::Display for FanProfile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FanProfile::Silent => write!(f, "silent"),
            FanProfile::Quiet => write!(f, "quiet"),
            FanProfile::Cool => write!(f, "cool"),
            FanProfile::Performance => write!(f, "performance"),
            FanProfile::Manual => write!(f, "manual"),
            FanProfile::Auto => write!(f, "auto"),
            FanProfile::TempControl => write!(f, "temp_control"),
        }
    }
}

impl std::str::FromStr for FanProfile {
    type Err = IronError;

    fn from_str(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "silent" => Ok(FanProfile::Silent),
            "quiet" => Ok(FanProfile::Quiet),
            "cool" => Ok(FanProfile::Cool),
            "performance" => Ok(FanProfile::Performance),
            "manual" => Ok(FanProfile::Manual),
            "auto" | "automatic" => Ok(FanProfile::Auto),
            "temp_control" => Ok(FanProfile::TempControl),
            _ => Err(IronError::InvalidValue(format!(
                "Unknown fan profile: {}",
                s
            ))),
        }
    }
}

/// Fan control mode
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FanControlMode {
    /// PWM control (0-255 or 0-100%)
    Pwm,
    /// RPM target control
    Rpm,
    /// DC voltage control
    Dc,
    /// Automatic/thermal control
    Auto,
    /// No control: the chip runs the fan at full speed (hwmon `pwmN_enable` 0).
    ///
    /// This is not `Dc`. The hwmon DC-versus-PWM drive question is `pwmN_mode`,
    /// a separate attribute, and the old reader mapped enable 0 to `Dc`.
    FullSpeed,
}

/// Fan type classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FanType {
    /// CPU cooler fan
    Cpu,
    /// GPU cooler fan
    Gpu,
    /// Case/chassis fan
    Case,
    /// Power supply fan
    Psu,
    /// Chipset fan
    Chipset,
    /// System/generic fan
    System,
    /// Unknown type
    Unknown,
}

impl std::fmt::Display for FanType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FanType::Cpu => write!(f, "CPU"),
            FanType::Gpu => write!(f, "GPU"),
            FanType::Case => write!(f, "Case"),
            FanType::Psu => write!(f, "PSU"),
            FanType::Chipset => write!(f, "Chipset"),
            FanType::System => write!(f, "System"),
            FanType::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Detailed fan information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FanInfo {
    /// Fan name/identifier
    pub name: String,
    /// Fan type
    pub fan_type: FanType,
    /// Current speed percentage (0-100), or `None` where no speed was read.
    ///
    /// **Bare beside five `Option` siblings**, and `FanInfo::new` set it to
    /// `0.0`. The Windows WMI path pushes a `FanInfo::new` with no speed source
    /// at all -- `Win32_Fan` exposes no tachometer, as the comment there says --
    /// so every fan on that path reported a speed of exactly zero.
    ///
    /// The three predicates below are why this one is worse than a wrong
    /// number on a screen. See [`Self::is_potentially_stalled`].
    pub speed_percent: Option<f32>,
    /// Current PWM value (0-255)
    pub pwm_value: Option<u8>,
    /// Current RPM (if available)
    pub rpm: Option<u32>,
    /// Minimum RPM (if available)
    pub rpm_min: Option<u32>,
    /// Maximum RPM (if available)
    pub rpm_max: Option<u32>,
    /// Target RPM (if in RPM mode)
    pub rpm_target: Option<u32>,
    /// Current profile
    pub profile: FanProfile,
    /// Available profiles
    pub available_profiles: Vec<FanProfile>,
    /// Control mode
    pub control_mode: FanControlMode,
    /// Whether the fan can be commanded. `None` when the reader could not establish
    /// it: a failed metadata read on the PWM file used to report `false`, which
    /// read as a fact about the fan.
    pub controllable: Option<bool>,
    /// PWM enable state (for hwmon)
    pub pwm_enable: Option<u8>,
    /// Linked thermal zone
    pub thermal_zone: Option<String>,
    /// Current linked temperature (°C)
    pub linked_temp_celsius: Option<f32>,
    /// Sysfs path (Linux)
    #[serde(skip)]
    pub sysfs_path: Option<PathBuf>,
}

impl FanInfo {
    /// Create a new FanInfo
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            fan_type: FanType::Unknown,
            speed_percent: None,
            pwm_value: None,
            rpm: None,
            rpm_min: None,
            rpm_max: None,
            rpm_target: None,
            profile: FanProfile::Auto,
            // Empty until a reader establishes what the fan accepts. This used
            // to be `[Auto]` for every fan, including WMI fans that cannot be
            // controlled at all.
            available_profiles: Vec::new(),
            control_mode: FanControlMode::Auto,
            controllable: None,
            pwm_enable: None,
            thermal_zone: None,
            linked_temp_celsius: None,
            sysfs_path: None,
        }
    }

    /// Whether the fan is running, or `None` when neither speed nor RPM was
    /// read.
    ///
    /// A fan with an unread speed and an unread tachometer returned `false`
    /// here -- a positive claim that the fan is stopped, from two absent
    /// readings.
    pub fn is_running(&self) -> bool {
        self.is_running_opt().unwrap_or(false)
    }

    /// [`Self::is_running`] without the fabricated `false`.
    pub fn is_running_opt(&self) -> Option<bool> {
        match (self.speed_percent, self.rpm) {
            (None, None) => None,
            (speed, rpm) => Some(speed.is_some_and(|s| s > 0.0) || rpm.is_some_and(|r| r > 0)),
        }
    }

    /// Whether the fan is at full speed, or `None` without a speed reading.
    pub fn is_full_speed(&self) -> Option<bool> {
        Some(self.speed_percent? >= 95.0)
    }

    /// Whether the fan might be stalled -- commanded above 10% but reporting
    /// 0 RPM -- or `None` when the command level was not read.
    ///
    /// **The one that matters.** This returned `false` for a fan whose speed
    /// nobody read: a thermal-safety signal answering "no problem" about a fan
    /// that was never measured. `None` says the check could not be performed,
    /// which is a different thing to report and a different thing to act on.
    pub fn is_potentially_stalled(&self) -> Option<bool> {
        Some(self.speed_percent? > 10.0 && self.rpm == Some(0))
    }

    /// Get fan efficiency estimate (RPM per PWM%)
    pub fn efficiency(&self) -> Option<f32> {
        match (self.rpm, self.speed_percent?) {
            (Some(rpm), speed) if speed > 5.0 => Some(rpm as f32 / speed),
            _ => None,
        }
    }
}

/// Fan curve point for custom curves
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct FanCurvePoint {
    /// Temperature threshold (°C)
    pub temp_celsius: f32,
    /// Fan speed percentage (0-100)
    pub speed_percent: f32,
}

/// Custom fan curve
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FanCurve {
    /// Curve name
    pub name: String,
    /// Curve points (must be sorted by temperature)
    pub points: Vec<FanCurvePoint>,
    /// Hysteresis (temperature drop before speed decreases)
    pub hysteresis: f32,
}

impl FanCurve {
    /// Create a default quiet curve
    pub fn quiet() -> Self {
        Self {
            name: "Quiet".to_string(),
            points: vec![
                FanCurvePoint {
                    temp_celsius: 30.0,
                    speed_percent: 20.0,
                },
                FanCurvePoint {
                    temp_celsius: 50.0,
                    speed_percent: 30.0,
                },
                FanCurvePoint {
                    temp_celsius: 60.0,
                    speed_percent: 50.0,
                },
                FanCurvePoint {
                    temp_celsius: 70.0,
                    speed_percent: 70.0,
                },
                FanCurvePoint {
                    temp_celsius: 80.0,
                    speed_percent: 90.0,
                },
                FanCurvePoint {
                    temp_celsius: 90.0,
                    speed_percent: 100.0,
                },
            ],
            hysteresis: 5.0,
        }
    }

    /// Create a default performance curve
    pub fn performance() -> Self {
        Self {
            name: "Performance".to_string(),
            points: vec![
                FanCurvePoint {
                    temp_celsius: 30.0,
                    speed_percent: 40.0,
                },
                FanCurvePoint {
                    temp_celsius: 40.0,
                    speed_percent: 50.0,
                },
                FanCurvePoint {
                    temp_celsius: 50.0,
                    speed_percent: 70.0,
                },
                FanCurvePoint {
                    temp_celsius: 60.0,
                    speed_percent: 85.0,
                },
                FanCurvePoint {
                    temp_celsius: 70.0,
                    speed_percent: 95.0,
                },
                FanCurvePoint {
                    temp_celsius: 75.0,
                    speed_percent: 100.0,
                },
            ],
            hysteresis: 3.0,
        }
    }

    /// Create a silent curve (aggressive throttling)
    pub fn silent() -> Self {
        Self {
            name: "Silent".to_string(),
            points: vec![
                FanCurvePoint {
                    temp_celsius: 40.0,
                    speed_percent: 0.0,
                },
                FanCurvePoint {
                    temp_celsius: 55.0,
                    speed_percent: 20.0,
                },
                FanCurvePoint {
                    temp_celsius: 65.0,
                    speed_percent: 40.0,
                },
                FanCurvePoint {
                    temp_celsius: 75.0,
                    speed_percent: 60.0,
                },
                FanCurvePoint {
                    temp_celsius: 85.0,
                    speed_percent: 80.0,
                },
                FanCurvePoint {
                    temp_celsius: 90.0,
                    speed_percent: 100.0,
                },
            ],
            hysteresis: 8.0,
        }
    }

    /// Calculate target speed for given temperature
    pub fn calculate_speed(&self, temp_celsius: f32) -> f32 {
        if self.points.is_empty() {
            return 100.0;
        }

        // Below minimum temperature
        if temp_celsius <= self.points[0].temp_celsius {
            return self.points[0].speed_percent;
        }

        // Above maximum temperature
        if temp_celsius >= self.points.last().unwrap().temp_celsius {
            return self.points.last().unwrap().speed_percent;
        }

        // Interpolate between points
        for i in 0..self.points.len() - 1 {
            let p1 = &self.points[i];
            let p2 = &self.points[i + 1];

            if temp_celsius >= p1.temp_celsius && temp_celsius <= p2.temp_celsius {
                let temp_range = p2.temp_celsius - p1.temp_celsius;
                let speed_range = p2.speed_percent - p1.speed_percent;
                let temp_offset = temp_celsius - p1.temp_celsius;

                return p1.speed_percent + (speed_range * temp_offset / temp_range);
            }
        }

        100.0
    }
}

/// Thermal zone information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThermalZone {
    /// Zone name
    pub name: String,
    /// Zone type (CPU, GPU, etc.), `None` where the platform did not name one.
    ///
    /// This was the string `"unknown"` when the `type` file was unreadable, and
    /// on Windows the WMI instance path (a device identifier, not a type).
    pub zone_type: Option<String>,
    /// Current temperature (°C), `None` where the zone's temperature could
    /// not be read. It was 0 °C, a reading a zone near freezing would give.
    pub temp_celsius: Option<f32>,
    /// Trip points
    pub trip_points: Vec<TripPoint>,
    /// Cooling devices linked to this zone
    pub cooling_devices: Vec<String>,
    /// Policy type
    pub policy: Option<String>,
}

/// Thermal trip point
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TripPoint {
    /// Trip point type (active, passive, hot, critical)
    pub trip_type: String,
    /// Temperature threshold (°C), `None` where it could not be read; it was
    /// 0 °C, a threshold every running zone is already above.
    pub temp_celsius: Option<f32>,
    /// Hysteresis (°C)
    pub hysteresis: Option<f32>,
}

/// Fan monitoring and control
pub struct FanMonitor {
    /// Discovered fans
    fans: Vec<FanInfo>,
    /// Thermal zones
    thermal_zones: Vec<ThermalZone>,
    /// Last update time
    last_update: Instant,
    /// Custom fan curves
    custom_curves: HashMap<String, FanCurve>,
}

impl FanMonitor {
    /// Create a new fan monitor
    pub fn new() -> Result<Self> {
        let mut monitor = Self {
            fans: Vec::new(),
            thermal_zones: Vec::new(),
            last_update: Instant::now(),
            custom_curves: HashMap::new(),
        };

        monitor.discover_fans()?;
        monitor.discover_thermal_zones()?;

        Ok(monitor)
    }

    /// Get all discovered fans
    pub fn fans(&self) -> &[FanInfo] {
        &self.fans
    }

    /// Get fan by name
    pub fn get_fan(&self, name: &str) -> Option<&FanInfo> {
        self.fans.iter().find(|f| f.name == name)
    }

    /// Get all thermal zones
    pub fn thermal_zones(&self) -> &[ThermalZone] {
        &self.thermal_zones
    }

    /// Refresh fan data
    pub fn refresh(&mut self) -> Result<()> {
        self.discover_fans()?;
        self.last_update = Instant::now();
        Ok(())
    }

    /// Set fan speed (percentage 0-100)
    pub fn set_speed(&self, fan_name: &str, speed_percent: f32) -> Result<()> {
        if !(0.0..=100.0).contains(&speed_percent) {
            return Err(IronError::InvalidValue(format!(
                "Speed must be 0-100%, got {}",
                speed_percent
            )));
        }

        #[cfg(target_os = "linux")]
        {
            self.linux_set_fan_speed(fan_name, speed_percent)
        }

        #[cfg(target_os = "windows")]
        {
            self.windows_set_fan_speed(fan_name, speed_percent)
        }

        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            let _ = (fan_name, speed_percent);
            Err(IronError::UnsupportedPlatform(
                "Fan control not supported on this platform".to_string(),
            ))
        }
    }

    /// Set fan PWM value (0-255)
    pub fn set_pwm(&self, fan_name: &str, pwm_value: u8) -> Result<()> {
        let speed_percent = (pwm_value as f32 / 255.0) * 100.0;
        self.set_speed(fan_name, speed_percent)
    }

    /// Set fan profile
    pub fn set_profile(&self, fan_name: &str, profile: FanProfile) -> Result<()> {
        #[cfg(target_os = "linux")]
        {
            self.linux_set_fan_profile(fan_name, profile)
        }

        #[cfg(not(target_os = "linux"))]
        {
            let _ = (fan_name, profile);
            Err(IronError::UnsupportedPlatform(
                "Fan profile control not supported on this platform".to_string(),
            ))
        }
    }

    /// Set custom fan curve
    pub fn set_curve(&mut self, fan_name: &str, curve: FanCurve) {
        self.custom_curves.insert(fan_name.to_string(), curve);
    }

    /// Get custom fan curve
    pub fn get_curve(&self, fan_name: &str) -> Option<&FanCurve> {
        self.custom_curves.get(fan_name)
    }

    /// Apply fan curve based on current temperature
    pub fn apply_curve(&self, fan_name: &str, temp_celsius: f32) -> Result<()> {
        if let Some(curve) = self.custom_curves.get(fan_name) {
            let target_speed = curve.calculate_speed(temp_celsius);
            self.set_speed(fan_name, target_speed)?;
        }
        Ok(())
    }

    /// Get time since last update
    pub fn time_since_update(&self) -> Duration {
        self.last_update.elapsed()
    }

    /// Discover fans on the system
    fn discover_fans(&mut self) -> Result<()> {
        self.fans.clear();

        #[cfg(target_os = "linux")]
        {
            self.linux_discover_fans()?;
        }

        #[cfg(target_os = "windows")]
        {
            self.windows_discover_fans()?;
        }

        #[cfg(target_os = "macos")]
        {
            self.macos_discover_fans()?;
        }

        Ok(())
    }

    /// Discover thermal zones
    fn discover_thermal_zones(&mut self) -> Result<()> {
        self.thermal_zones.clear();

        #[cfg(target_os = "linux")]
        {
            self.linux_discover_thermal_zones()?;
        }

        Ok(())
    }

    // ==================== Linux Implementation ====================

    #[cfg(target_os = "linux")]
    fn linux_discover_fans(&mut self) -> Result<()> {
        use std::fs;

        let hwmon_path = std::path::Path::new("/sys/class/hwmon");
        if !hwmon_path.exists() {
            return Ok(());
        }

        for entry in fs::read_dir(hwmon_path)
            .map_err(|e| IronError::System(format!("Failed to read hwmon: {}", e)))?
        {
            let entry =
                entry.map_err(|e| IronError::System(format!("Failed to read entry: {}", e)))?;

            let path = entry.path();

            // Read device name
            let name_file = path.join("name");
            let device_name = if name_file.exists() {
                fs::read_to_string(&name_file)
                    .map(|s| s.trim().to_string())
                    .unwrap_or_else(|_| entry.file_name().to_string_lossy().to_string())
            } else {
                entry.file_name().to_string_lossy().to_string()
            };

            // Look for PWM files (pwm1, pwm2, etc.)
            for i in 1..=10 {
                let pwm_file = path.join(format!("pwm{}", i));
                if !pwm_file.exists() {
                    continue;
                }

                let fan_name = format!("{}_{}", device_name, i);
                let mut fan = FanInfo::new(&fan_name);
                fan.sysfs_path = Some(path.clone());

                // Read PWM value
                if let Ok(pwm_str) = fs::read_to_string(&pwm_file) {
                    if let Ok(pwm) = pwm_str.trim().parse::<u8>() {
                        fan.pwm_value = Some(pwm);
                        fan.speed_percent = Some((pwm as f32 / 255.0) * 100.0);
                    }
                }

                // Read PWM enable (control mode). Its value says what the chip
                // will accept; the file existing says nothing about that.
                let pwm_enable_file = path.join(format!("pwm{}_enable", i));
                if let Ok(enable_str) = fs::read_to_string(&pwm_enable_file) {
                    if let Ok(enable) = enable_str.trim().parse::<u8>() {
                        fan.pwm_enable = Some(enable);
                        fan.control_mode = hwmon_enable_mode(enable);
                        // An unreadable PWM file leaves controllability unknown (`None`),
                        // not false.
                        fan.controllable = fs::metadata(&pwm_file)
                            .ok()
                            .map(|m| hwmon_controllable(enable, !m.permissions().readonly()));
                        if fan.control_mode == FanControlMode::Pwm {
                            fan.profile = FanProfile::Manual;
                        }
                        if fan.controllable == Some(true) {
                            fan.available_profiles = vec![FanProfile::Manual, FanProfile::Auto];
                        }
                    }
                }

                // Read RPM (fan*_input)
                let rpm_file = path.join(format!("fan{}_input", i));
                if let Ok(rpm_str) = fs::read_to_string(&rpm_file) {
                    if let Ok(rpm) = rpm_str.trim().parse::<u32>() {
                        fan.rpm = Some(rpm);
                    }
                }

                // Read min/max RPM
                let rpm_min_file = path.join(format!("fan{}_min", i));
                if let Ok(rpm_str) = fs::read_to_string(&rpm_min_file) {
                    if let Ok(rpm) = rpm_str.trim().parse::<u32>() {
                        fan.rpm_min = Some(rpm);
                    }
                }

                let rpm_max_file = path.join(format!("fan{}_max", i));
                if let Ok(rpm_str) = fs::read_to_string(&rpm_max_file) {
                    if let Ok(rpm) = rpm_str.trim().parse::<u32>() {
                        fan.rpm_max = Some(rpm);
                    }
                }

                // Classify fan type
                fan.fan_type = classify_fan_type(&device_name, &fan_name);

                self.fans.push(fan);
            }
        }

        // Also check Jetson-specific fan paths
        self.linux_discover_jetson_fans()?;

        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn linux_discover_jetson_fans(&mut self) -> Result<()> {
        use std::fs;

        // Jetson fan paths
        let jetson_paths = ["/sys/devices/pwm-fan", "/sys/kernel/debug/tegra_fan"];

        for base_path in &jetson_paths {
            let path = std::path::Path::new(base_path);
            if !path.exists() {
                continue;
            }

            let mut fan = FanInfo::new("jetson_fan");
            fan.fan_type = FanType::System;
            fan.sysfs_path = Some(path.to_path_buf());

            // Read target PWM
            let target_pwm = path.join("target_pwm");
            if let Ok(pwm_str) = fs::read_to_string(&target_pwm) {
                if let Ok(pwm) = pwm_str.trim().parse::<u32>() {
                    fan.pwm_value = Some((pwm.min(255)) as u8);
                    fan.speed_percent = Some((pwm as f32 / 255.0) * 100.0);
                }
            }

            // Read RPM
            let rpm_file = path.join("rpm_measured");
            if let Ok(rpm_str) = fs::read_to_string(&rpm_file) {
                if let Ok(rpm) = rpm_str.trim().parse::<u32>() {
                    fan.rpm = Some(rpm);
                }
            }

            // Check temp control
            let temp_control = path.join("temp_control");
            if temp_control.exists() {
                if let Ok(tc_str) = fs::read_to_string(&temp_control) {
                    fan.profile = if tc_str.trim() == "1" {
                        FanProfile::TempControl
                    } else {
                        FanProfile::Manual
                    };
                }
                fan.available_profiles = vec![FanProfile::Manual, FanProfile::TempControl];
            }

            // Controllable only if the duty file takes writes, as the hwmon path
            // checks. This was a literal `true`, so every Jetson fan was offered
            // as controllable whether or not the file could be written. A failed
            // metadata read leaves it unknown (`None`), not false.
            fan.controllable = fs::metadata(path.join("target_pwm"))
                .ok()
                .map(|m| !m.permissions().readonly());
            self.fans.push(fan);
        }

        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn linux_discover_thermal_zones(&mut self) -> Result<()> {
        use std::fs;

        let thermal_path = std::path::Path::new("/sys/class/thermal");
        if !thermal_path.exists() {
            return Ok(());
        }

        for entry in fs::read_dir(thermal_path)
            .map_err(|e| IronError::System(format!("Failed to read thermal: {}", e)))?
        {
            let entry =
                entry.map_err(|e| IronError::System(format!("Failed to read entry: {}", e)))?;

            let path = entry.path();
            let name = entry.file_name().to_string_lossy().to_string();

            if !name.starts_with("thermal_zone") {
                continue;
            }

            // Read zone type
            // An unreadable `type` file is no type, not the type "unknown".
            let zone_type = fs::read_to_string(path.join("type"))
                .ok()
                .map(|s| s.trim().to_string());

            // Read temperature
            let temp = fs::read_to_string(path.join("temp"))
                .ok()
                .and_then(|s| s.trim().parse::<i32>().ok())
                .map(|t| t as f32 / 1000.0);

            // Read trip points
            let mut trip_points = Vec::new();
            for i in 0..10 {
                let trip_type_file = path.join(format!("trip_point_{}_type", i));
                let trip_temp_file = path.join(format!("trip_point_{}_temp", i));

                if !trip_type_file.exists() {
                    break;
                }

                let trip_type = fs::read_to_string(&trip_type_file)
                    .map(|s| s.trim().to_string())
                    .unwrap_or_default();

                let trip_temp = fs::read_to_string(&trip_temp_file)
                    .ok()
                    .and_then(|s| s.trim().parse::<i32>().ok())
                    .map(|t| t as f32 / 1000.0);

                let hyst_file = path.join(format!("trip_point_{}_hyst", i));
                let hysteresis = fs::read_to_string(&hyst_file)
                    .ok()
                    .and_then(|s| s.trim().parse::<i32>().ok())
                    .map(|t| t as f32 / 1000.0);

                trip_points.push(TripPoint {
                    trip_type,
                    temp_celsius: trip_temp,
                    hysteresis,
                });
            }

            // Read policy
            let policy = fs::read_to_string(path.join("policy"))
                .map(|s| s.trim().to_string())
                .ok();

            self.thermal_zones.push(ThermalZone {
                name,
                zone_type,
                temp_celsius: temp,
                trip_points,
                cooling_devices: Vec::new(), // Could enumerate cdev* links
                policy,
            });
        }

        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn linux_set_fan_speed(&self, fan_name: &str, speed_percent: f32) -> Result<()> {
        use std::fs;

        let fan = self
            .fans
            .iter()
            .find(|f| f.name == fan_name)
            .ok_or_else(|| IronError::DeviceNotFound(format!("Fan '{}' not found", fan_name)))?;

        let path = fan
            .sysfs_path
            .as_ref()
            .ok_or_else(|| IronError::System("No sysfs path for fan".to_string()))?;

        // Calculate PWM value
        let pwm = ((speed_percent / 100.0) * 255.0).round() as u8;

        // Try different PWM file patterns
        let pwm_files = [path.join("pwm1"), path.join("target_pwm")];

        for pwm_file in &pwm_files {
            if pwm_file.exists() {
                fs::write(pwm_file, format!("{}", pwm)).map_err(|e| {
                    IronError::System(format!("Failed to write PWM (need root?): {}", e))
                })?;
                return Ok(());
            }
        }

        Err(IronError::System("No writable PWM file found".to_string()))
    }

    #[cfg(target_os = "linux")]
    fn linux_set_fan_profile(&self, fan_name: &str, profile: FanProfile) -> Result<()> {
        use std::fs;

        let fan = self
            .fans
            .iter()
            .find(|f| f.name == fan_name)
            .ok_or_else(|| IronError::DeviceNotFound(format!("Fan '{}' not found", fan_name)))?;

        let path = fan
            .sysfs_path
            .as_ref()
            .ok_or_else(|| IronError::System("No sysfs path for fan".to_string()))?;

        // For standard hwmon, set pwm_enable
        // 0 = DC mode
        // 1 = PWM/manual mode
        // 2 = automatic mode
        let pwm_enable_file = path.join("pwm1_enable");
        if pwm_enable_file.exists() {
            let enable_value = match profile {
                FanProfile::Manual => 1,
                FanProfile::Auto
                | FanProfile::Quiet
                | FanProfile::Cool
                | FanProfile::Performance => 2,
                FanProfile::Silent => 1, // Manual with low speed
                FanProfile::TempControl => 2,
            };

            fs::write(&pwm_enable_file, format!("{}", enable_value)).map_err(|e| {
                IronError::System(format!("Failed to set fan profile (need root?): {}", e))
            })?;

            return Ok(());
        }

        // For Jetson temp_control
        let temp_control = path.join("temp_control");
        if temp_control.exists() {
            let value = match profile {
                FanProfile::TempControl | FanProfile::Auto => "1",
                FanProfile::Manual => "0",
                _ => "1",
            };

            fs::write(&temp_control, value)
                .map_err(|e| IronError::System(format!("Failed to set temp control: {}", e)))?;

            return Ok(());
        }

        Err(IronError::UnsupportedPlatform(
            "Fan profile control not available for this fan".to_string(),
        ))
    }

    // ==================== Windows Implementation ====================

    #[cfg(target_os = "windows")]
    fn windows_discover_fans(&mut self) -> Result<()> {
        use wmi::{COMLibrary, WMIConnection};

        // WMI Win32_Fan structure (rarely populated on consumer hardware)
        #[derive(serde::Deserialize, Debug)]
        #[serde(rename_all = "PascalCase")]
        #[allow(dead_code)]
        struct Win32Fan {
            device_id: Option<String>,
            name: Option<String>,
            active_cooling: Option<bool>,
            status: Option<String>,
        }

        // Try to query Win32_Fan
        if let Ok(com) = COMLibrary::new() {
            if let Ok(wmi) = WMIConnection::new(com) {
                let fans: Vec<Win32Fan> = wmi.query().unwrap_or_default();

                for wmi_fan in fans {
                    let name = wmi_fan
                        .name
                        .clone()
                        .or(wmi_fan.device_id.clone())
                        .unwrap_or_else(|| "System Fan".to_string());

                    let mut fan = FanInfo::new(&name);
                    fan.fan_type = FanType::System;
                    // Not read: this query does not check control. It used to be `false`.
                    fan.controllable = None;

                    // Win32_Fan exposes no tachometer reading, so `rpm` stays None.
                    //
                    // This previously reported a hardcoded 1000 RPM whenever
                    // ActiveCooling was true. That is indistinguishable from a real
                    // measurement on screen, and a fan pinned at exactly 1000 RPM
                    // while temperatures climb is actively misleading. An unknown
                    // speed is better represented as unknown.
                    //
                    // ActiveCooling only says the fan is participating in cooling,
                    // which FanInfo has no field to express, so it is not recorded.
                    self.fans.push(fan);
                }
            }
        }

        // Also try WMI CIM_Fan (more generic)
        self.windows_discover_cim_fans();

        // Try to detect thermal zones via WMI
        self.windows_discover_thermal_zones();

        Ok(())
    }

    #[cfg(target_os = "windows")]
    fn windows_discover_cim_fans(&mut self) {
        use wmi::{COMLibrary, WMIConnection};

        #[derive(serde::Deserialize, Debug)]
        #[serde(rename_all = "PascalCase")]
        #[allow(dead_code)]
        struct CimFan {
            device_id: Option<String>,
            name: Option<String>,
            description: Option<String>,
        }

        if let Ok(com) = COMLibrary::new() {
            if let Ok(wmi) = WMIConnection::new(com) {
                // Query CIM_Fan
                let query = "SELECT * FROM CIM_Fan";
                if let Ok(fans) = wmi.raw_query::<CimFan>(query) {
                    for cim_fan in fans {
                        // Skip if we already have this fan
                        let name = cim_fan
                            .name
                            .clone()
                            .or(cim_fan.device_id.clone())
                            .unwrap_or_else(|| "CIM Fan".to_string());

                        if !self.fans.iter().any(|f| f.name == name) {
                            let mut fan = FanInfo::new(&name);
                            fan.fan_type = FanType::System;
                            // Not read, as for the Win32_Fan entries above.
                            fan.controllable = None;
                            self.fans.push(fan);
                        }
                    }
                }
            }
        }
    }

    #[cfg(target_os = "windows")]
    fn windows_discover_thermal_zones(&mut self) {
        use wmi::{COMLibrary, WMIConnection};

        // MSAcpi_ThermalZoneTemperature from root\WMI namespace
        #[derive(serde::Deserialize, Debug)]
        #[serde(rename = "MSAcpi_ThermalZoneTemperature")]
        #[serde(rename_all = "PascalCase")]
        #[allow(dead_code)]
        struct MsAcpiThermalZone {
            instance_name: Option<String>,
            current_temperature: Option<u32>, // Tenths of Kelvin
            active: Option<bool>,
            critical_trip_point: Option<u32>,
            passive_trip_point: Option<u32>,
        }

        if let Ok(com) = COMLibrary::new() {
            // Connect to root\WMI namespace
            if let Ok(wmi) = WMIConnection::with_namespace_path("root\\WMI", com) {
                if let Ok(zones) = wmi.query::<MsAcpiThermalZone>() {
                    for (idx, zone) in zones.iter().enumerate() {
                        // The instance name is a device path (ACPI\ThermalZone\...),
                        // not a zone type. WMI does not say what the zone is, so the
                        // type is None. This used to copy the instance path, or a
                        // made-up "thermal_zone{idx}", into the type field.
                        let mut tz = ThermalZone {
                            name: format!("zone{}", idx),
                            zone_type: None,
                            temp_celsius: None,
                            trip_points: Vec::new(),
                            cooling_devices: Vec::new(),
                            policy: None,
                        };

                        // Convert from tenths of Kelvin to Celsius. Zero tenths of
                        // a kelvin is -273.15 °C, below absolute zero: a zone that
                        // reports 0 has no reading, and it is not published as one.
                        if let Some(temp_tenths_k) = zone.current_temperature.filter(|&t| t > 0) {
                            let temp_c = (temp_tenths_k as f32 / 10.0) - 273.15;
                            tz.temp_celsius = Some(temp_c);
                        }

                        // Add trip points if available
                        // 0 is firmware declaring no trip point, not one at
                        // absolute zero.
                        if let Some(crit) = zone.critical_trip_point.filter(|&t| t > 0) {
                            let crit_c = (crit as f32 / 10.0) - 273.15;
                            tz.trip_points.push(TripPoint {
                                trip_type: "critical".to_string(),
                                temp_celsius: Some(crit_c),
                                hysteresis: None,
                            });
                        }

                        if let Some(passive) = zone.passive_trip_point.filter(|&t| t > 0) {
                            let passive_c = (passive as f32 / 10.0) - 273.15;
                            tz.trip_points.push(TripPoint {
                                trip_type: "passive".to_string(),
                                temp_celsius: Some(passive_c),
                                hysteresis: None,
                            });
                        }

                        self.thermal_zones.push(tz);
                    }
                }
            }
        }
    }

    #[cfg(target_os = "windows")]
    fn windows_set_fan_speed(&self, _fan_name: &str, _speed_percent: f32) -> Result<()> {
        Err(IronError::UnsupportedPlatform(
            "Fan control on Windows requires vendor-specific tools or OpenHardwareMonitor"
                .to_string(),
        ))
    }

    // ==================== macOS Implementation ====================

    #[cfg(target_os = "macos")]
    fn macos_discover_fans(&mut self) -> Result<()> {
        // Fan speeds live in the SMC, which needs IOKit bindings this module
        // does not have. This used to push four fans named fan1..fan4 whenever
        // `system_profiler SPHardwareDataType` exited 0, a command whose output
        // was never parsed. Those were invented fans with no speed behind them.
        // Report the absence instead.
        Err(IronError::UnsupportedPlatform(
            "fan speeds on macOS are read from the SMC, which this build does not read".to_string(),
        ))
    }
}

/// What a `pwmN_enable` value says the fan is doing, per the hwmon sysfs ABI:
/// 0 is no control (the chip runs the fan at full speed), 1 is manual PWM, and
/// 2 or more is automatic control by the driver or chip.
#[cfg(any(target_os = "linux", test))]
fn hwmon_enable_mode(enable: u8) -> FanControlMode {
    match enable {
        0 => FanControlMode::FullSpeed,
        1 => FanControlMode::Pwm,
        _ => FanControlMode::Auto,
    }
}

/// Whether a fan can be commanded: the chip must be in a mode that takes a
/// PWM value (1 or 2 and up, never 0), and the `pwmN` file must be writable.
#[cfg(any(target_os = "linux", test))]
fn hwmon_controllable(enable: u8, pwm_writable: bool) -> bool {
    enable != 0 && pwm_writable
}

/// Classify fan type based on device/fan name
#[allow(dead_code)]
fn classify_fan_type(device_name: &str, fan_name: &str) -> FanType {
    let name_lower = format!("{} {}", device_name, fan_name).to_lowercase();
    // Whole words only: `sys` as a substring matched `system76_acpi`, which is
    // not a system fan.
    let words: Vec<&str> = name_lower
        .split(|c: char| !c.is_ascii_alphanumeric())
        .collect();

    if name_lower.contains("cpu") || name_lower.contains("processor") {
        FanType::Cpu
    } else if name_lower.contains("gpu")
        || name_lower.contains("nvidia")
        || name_lower.contains("amd")
    {
        FanType::Gpu
    } else if name_lower.contains("psu") || name_lower.contains("power") {
        FanType::Psu
    } else if name_lower.contains("case")
        || name_lower.contains("chassis")
        || words.contains(&"sys")
    {
        FanType::Case
    } else if name_lower.contains("chip") || name_lower.contains("pch") {
        FanType::Chipset
    } else {
        FanType::Unknown
    }
}

/// Summary of fan status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FanSummary {
    /// Total number of fans
    pub total_fans: usize,
    /// Number of running fans
    pub running_fans: usize,
    /// Average speed across the fans that reported one, or `None` if none
    /// did.
    ///
    /// Summing `0.0` for unread fans and dividing by the full fan count gave a
    /// mean that fell with each unreadable fan while still looking like a
    /// measurement -- the same arithmetic the NUMA and cpufreq summaries had.
    pub avg_speed_percent: Option<f32>,
    /// Maximum RPM detected
    pub max_rpm: Option<u32>,
    /// Any stalled fans detected
    pub stalled_fans: Vec<String>,
    /// Fans at full speed
    pub full_speed_fans: Vec<String>,
}

/// Get a summary of all fans
pub fn fan_summary() -> Result<FanSummary> {
    let monitor = FanMonitor::new()?;
    let fans = monitor.fans();

    // `== Some(true)` throughout: a fan whose check could not be performed is
    // counted in neither list. `stalled_fans` in particular must not silently
    // include or exclude a fan nobody measured -- see `is_potentially_stalled`.
    let running_fans: Vec<_> = fans
        .iter()
        .filter(|f| f.is_running_opt() == Some(true))
        .collect();
    let full_speed: Vec<_> = fans
        .iter()
        .filter(|f| f.is_full_speed() == Some(true))
        .collect();
    let stalled: Vec<_> = fans
        .iter()
        .filter(|f| f.is_potentially_stalled() == Some(true))
        .collect();

    // Averaged over the fans that reported a speed.
    let read: Vec<f32> = fans.iter().filter_map(|f| f.speed_percent).collect();
    let avg_speed = if read.is_empty() {
        None
    } else {
        Some(read.iter().sum::<f32>() / read.len() as f32)
    };

    let max_rpm = fans.iter().filter_map(|f| f.rpm).max();

    Ok(FanSummary {
        total_fans: fans.len(),
        running_fans: running_fans.len(),
        avg_speed_percent: avg_speed,
        max_rpm,
        stalled_fans: stalled.iter().map(|f| f.name.clone()).collect(),
        full_speed_fans: full_speed.iter().map(|f| f.name.clone()).collect(),
    })
}

/// Get list of all fans (convenience function)
pub fn list_fans() -> Result<Vec<FanInfo>> {
    let monitor = FanMonitor::new()?;
    Ok(monitor.fans.clone())
}

/// Get list of thermal zones
pub fn list_thermal_zones() -> Result<Vec<ThermalZone>> {
    let monitor = FanMonitor::new()?;
    Ok(monitor.thermal_zones.clone())
}

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

    // === FanProfile tests ===

    #[test]
    fn test_fan_profile_display() {
        assert_eq!(FanProfile::Silent.to_string(), "silent");
        assert_eq!(FanProfile::Quiet.to_string(), "quiet");
        assert_eq!(FanProfile::Cool.to_string(), "cool");
        assert_eq!(FanProfile::Performance.to_string(), "performance");
        assert_eq!(FanProfile::Manual.to_string(), "manual");
        assert_eq!(FanProfile::Auto.to_string(), "auto");
        assert_eq!(FanProfile::TempControl.to_string(), "temp_control");
    }

    #[test]
    fn test_fan_profile_from_str() {
        assert_eq!("silent".parse::<FanProfile>().unwrap(), FanProfile::Silent);
        assert_eq!("quiet".parse::<FanProfile>().unwrap(), FanProfile::Quiet);
        assert_eq!("cool".parse::<FanProfile>().unwrap(), FanProfile::Cool);
        assert_eq!(
            "performance".parse::<FanProfile>().unwrap(),
            FanProfile::Performance
        );
        assert_eq!("auto".parse::<FanProfile>().unwrap(), FanProfile::Auto);
        assert_eq!("automatic".parse::<FanProfile>().unwrap(), FanProfile::Auto);
        assert!("invalid".parse::<FanProfile>().is_err());
    }

    #[test]
    fn test_fan_profile_case_insensitive() {
        assert_eq!("QUIET".parse::<FanProfile>().unwrap(), FanProfile::Quiet);
        assert_eq!("Silent".parse::<FanProfile>().unwrap(), FanProfile::Silent);
    }

    // === FanType tests ===

    #[test]
    fn test_fan_type_display() {
        assert_eq!(FanType::Cpu.to_string(), "CPU");
        assert_eq!(FanType::Gpu.to_string(), "GPU");
        assert_eq!(FanType::Case.to_string(), "Case");
        assert_eq!(FanType::Unknown.to_string(), "Unknown");
    }

    // === FanInfo tests ===

    #[test]
    fn test_fan_info_new_defaults() {
        let fan = FanInfo::new("cpu_fan");
        assert_eq!(fan.name, "cpu_fan");
        assert_eq!(fan.fan_type, FanType::Unknown);
        assert_eq!(
            fan.speed_percent, None,
            "a fan with no speed source has no speed, not a speed of zero"
        );
        assert_eq!(fan.controllable, None);
    }

    #[test]
    fn test_fan_is_running_by_speed() {
        let mut fan = FanInfo::new("test");
        assert!(!fan.is_running());
        fan.speed_percent = Some(50.0);
        assert!(fan.is_running());
    }

    #[test]
    fn test_fan_is_running_by_rpm() {
        let mut fan = FanInfo::new("test");
        fan.rpm = Some(1000);
        assert!(fan.is_running());
    }

    #[test]
    fn test_fan_is_full_speed() {
        let mut fan = FanInfo::new("test");
        assert_eq!(
            fan.is_full_speed(),
            None,
            "an unread fan is not at full speed and is not below it either"
        );
        fan.speed_percent = Some(94.0);
        assert_eq!(fan.is_full_speed(), Some(false));
        fan.speed_percent = Some(95.0);
        assert_eq!(fan.is_full_speed(), Some(true));
        fan.speed_percent = Some(100.0);
        assert_eq!(fan.is_full_speed(), Some(true));
    }

    #[test]
    fn test_fan_is_potentially_stalled() {
        let mut fan = FanInfo::new("test");
        // Unknown, not "not stalled": nothing was read, so the check could not
        // be performed. This asserted `false` -- a thermal-safety signal
        // reporting no problem about a fan nobody measured.
        assert_eq!(fan.is_potentially_stalled(), None);
        // Not stalled: speed > 10 but rpm not zero
        fan.speed_percent = Some(50.0);
        fan.rpm = Some(1200);
        assert_eq!(fan.is_potentially_stalled(), Some(false));
        // Stalled: speed > 10 and rpm == 0
        fan.rpm = Some(0);
        assert_eq!(fan.is_potentially_stalled(), Some(true));
        // Not stalled: low speed
        fan.speed_percent = Some(5.0);
        assert_eq!(fan.is_potentially_stalled(), Some(false));
    }

    #[test]
    fn test_fan_efficiency() {
        let mut fan = FanInfo::new("test");
        // No rpm -> None
        assert!(fan.efficiency().is_none());
        // Low speed -> None
        fan.speed_percent = Some(3.0);
        fan.rpm = Some(500);
        assert!(fan.efficiency().is_none());
        // Normal case
        fan.speed_percent = Some(50.0);
        fan.rpm = Some(1000);
        let eff = fan.efficiency().unwrap();
        assert!((eff - 20.0).abs() < 0.01); // 1000 / 50 = 20
    }

    // === FanCurve tests ===

    #[test]
    fn test_fan_curve_quiet_has_points() {
        let curve = FanCurve::quiet();
        assert_eq!(curve.name, "Quiet");
        assert!(!curve.points.is_empty());
        assert!(curve.hysteresis > 0.0);
    }

    #[test]
    fn test_fan_curve_performance_has_points() {
        let curve = FanCurve::performance();
        assert_eq!(curve.name, "Performance");
        assert!(!curve.points.is_empty());
    }

    #[test]
    fn test_fan_curve_silent_has_points() {
        let curve = FanCurve::silent();
        assert_eq!(curve.name, "Silent");
        assert!(!curve.points.is_empty());
    }

    #[test]
    fn test_fan_curve_calculate_speed_below_min() {
        let curve = FanCurve::quiet();
        // Below minimum temp should return first point's speed
        let speed = curve.calculate_speed(0.0);
        assert_eq!(speed, curve.points[0].speed_percent);
    }

    #[test]
    fn test_fan_curve_calculate_speed_above_max() {
        let curve = FanCurve::quiet();
        let speed = curve.calculate_speed(200.0);
        assert_eq!(speed, curve.points.last().unwrap().speed_percent);
    }

    #[test]
    fn test_fan_curve_calculate_speed_interpolation() {
        let curve = FanCurve::quiet();
        // Quiet curve: 30°C=20%, 50°C=30%
        // At 40°C: 20 + (30-20)*(40-30)/(50-30) = 20 + 10*10/20 = 25
        let speed = curve.calculate_speed(40.0);
        assert!((speed - 25.0).abs() < 0.1);
    }

    #[test]
    fn test_fan_curve_calculate_speed_at_point() {
        let curve = FanCurve::quiet();
        // At exact point temperature
        let speed = curve.calculate_speed(30.0);
        assert_eq!(speed, 20.0);
    }

    #[test]
    fn test_fan_curve_empty_returns_100() {
        let curve = FanCurve {
            name: "empty".to_string(),
            points: vec![],
            hysteresis: 0.0,
        };
        assert_eq!(curve.calculate_speed(50.0), 100.0);
    }

    // === hwmon pwmN_enable tests ===

    /// The hwmon ABI: 0 is no control, 1 is manual PWM, 2 and up is automatic.
    #[test]
    fn test_hwmon_enable_mode_follows_abi() {
        assert_eq!(hwmon_enable_mode(0), FanControlMode::FullSpeed);
        assert_eq!(hwmon_enable_mode(1), FanControlMode::Pwm);
        assert_eq!(hwmon_enable_mode(2), FanControlMode::Auto);
        // Chip-specific values (smart fan modes) are automatic control too.
        assert_eq!(hwmon_enable_mode(5), FanControlMode::Auto);
    }

    #[test]
    fn test_hwmon_zero_is_never_controllable() {
        // Enable 0 is no control, whatever the pwm file's permissions say.
        assert!(!hwmon_controllable(0, true));
        assert!(!hwmon_controllable(0, false));
    }

    #[test]
    fn test_hwmon_controllable_needs_writable_pwm_in_a_commandable_mode() {
        assert!(hwmon_controllable(1, true));
        assert!(hwmon_controllable(2, true));
        assert!(!hwmon_controllable(1, false));
        assert!(!hwmon_controllable(2, false));
    }

    #[test]
    fn test_classify_sys_is_a_word_not_a_substring() {
        // `system76_acpi` contains "sys" but names no system fan.
        assert_eq!(
            classify_fan_type("system76_acpi", "system76_acpi_1"),
            FanType::Unknown
        );
        assert_eq!(classify_fan_type("nct6798", "sys_fan_2"), FanType::Case);
    }
}