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
// Linux motherboard and system monitoring implementation
//
// Data sources:
// - /sys/class/hwmon/* - Hardware monitoring sensors
// - /sys/class/dmi/id/* - DMI/SMBIOS system information
// - /sys/firmware/efi - EFI/UEFI detection
// - /proc/cpuinfo - CPU information
// - /sys/module/*/version - Kernel module versions
// - lsmod - Loaded kernel modules

use super::traits::*;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

/// Linux motherboard sensor device
pub struct LinuxSensor {
    hwmon_path: PathBuf,
    /// Contents of the hwmon `name` file — the chip, e.g. `coretemp`.
    ///
    /// There used to be a `name` field alongside this holding the directory name
    /// (`hwmon0`). Nothing ever read it: `name()` returns the chip, which is what a
    /// reader can act on. Clippy flagged the getter as returning the wrong field;
    /// the getter was right and the field was dead.
    chip_name: String,
}

impl LinuxSensor {
    /// Create a new Linux sensor from a hwmon path
    pub fn new(hwmon_path: PathBuf) -> Result<Self, Error> {
        let name_path = hwmon_path.join("name");
        let chip_name = fs::read_to_string(&name_path)
            .map_err(|e| Error::InitializationFailed(format!("Failed to read sensor name: {}", e)))?
            .trim()
            .to_string();

        Ok(Self {
            hwmon_path,
            chip_name,
        })
    }

    /// Read a sensor input file
    fn read_input(&self, pattern: &str, index: u32) -> Option<i64> {
        let path = self.hwmon_path.join(format!("{}{}_input", pattern, index));
        fs::read_to_string(path).ok()?.trim().parse::<i64>().ok()
    }

    /// Read a sensor label file
    fn read_label(&self, pattern: &str, index: u32) -> Option<String> {
        let path = self.hwmon_path.join(format!("{}{}_label", pattern, index));
        fs::read_to_string(path).ok().map(|s| s.trim().to_string())
    }

    /// Read a sensor max file
    fn read_max(&self, pattern: &str, index: u32) -> Option<i64> {
        let path = self.hwmon_path.join(format!("{}{}_max", pattern, index));
        fs::read_to_string(path).ok()?.trim().parse::<i64>().ok()
    }

    /// Read a sensor critical file
    fn read_crit(&self, pattern: &str, index: u32) -> Option<i64> {
        let path = self.hwmon_path.join(format!("{}{}_crit", pattern, index));
        fs::read_to_string(path).ok()?.trim().parse::<i64>().ok()
    }

    /// Determine sensor type from label
    fn classify_sensor(label: &str) -> SensorType {
        let label_lower = label.to_lowercase();
        if label_lower.contains("cpu")
            || label_lower.contains("core")
            || label_lower.contains("package")
        {
            SensorType::Cpu
        } else if label_lower.contains("chipset") || label_lower.contains("pch") {
            SensorType::Chipset
        } else if label_lower.contains("vrm") || label_lower.contains("vcore") {
            SensorType::Vrm
        } else if label_lower.contains("ambient") || label_lower.contains("system") {
            SensorType::Ambient
        } else if label_lower.contains("m.2") || label_lower.contains("nvme") {
            SensorType::M2Slot
        } else {
            SensorType::Other
        }
    }
}

impl MotherboardDevice for LinuxSensor {
    // The chip name, not the hwmon directory: `coretemp` tells a reader what they
    // are looking at; `hwmon0` tells them where it happened to be enumerated.
    #[allow(clippy::misnamed_getters)]
    fn name(&self) -> &str {
        &self.chip_name
    }

    fn device_path(&self) -> Option<String> {
        Some(self.hwmon_path.to_string_lossy().to_string())
    }

    fn temperature_sensors(&self) -> Result<Vec<TemperatureSensor>, Error> {
        let mut sensors = Vec::new();

        // Try temperature inputs (temp1_input through temp32_input)
        for i in 1..=32 {
            if let Some(temp_millic) = self.read_input("temp", i) {
                let label = self
                    .read_label("temp", i)
                    .unwrap_or_else(|| format!("temp{}", i));

                let temperature = temp_millic as f32 / 1000.0;
                let max = self.read_max("temp", i).map(|v| v as f32 / 1000.0);
                let critical = self.read_crit("temp", i).map(|v| v as f32 / 1000.0);
                let sensor_type = Self::classify_sensor(&label);

                sensors.push(TemperatureSensor {
                    label,
                    // A real hwmon reading; the read above is already guarded.
                    temperature: Some(temperature),
                    max,
                    critical,
                    sensor_type,
                });
            }
        }

        Ok(sensors)
    }

    fn voltage_rails(&self) -> Result<Vec<VoltageRail>, Error> {
        let mut rails = Vec::new();

        // Try voltage inputs (in0_input through in32_input)
        for i in 0..=32 {
            if let Some(voltage_milliv) = self.read_input("in", i) {
                let label = self
                    .read_label("in", i)
                    .unwrap_or_else(|| format!("in{}", i));

                let voltage = voltage_milliv as f32 / 1000.0;
                let min = self.read_max("in", i).map(|v| v as f32 / 1000.0);
                let max = self.read_crit("in", i).map(|v| v as f32 / 1000.0);

                rails.push(VoltageRail {
                    label,
                    voltage: Some(voltage),
                    min,
                    max,
                });
            }
        }

        Ok(rails)
    }

    fn fans(&self) -> Result<Vec<FanInfo>, Error> {
        let mut fans = Vec::new();

        // Try fan inputs (fan1_input through fan16_input)
        for i in 1..=16 {
            if let Some(rpm) = self.read_input("fan", i) {
                let label = self
                    .read_label("fan", i)
                    .unwrap_or_else(|| format!("fan{}", i));

                // Try to read PWM value
                let pwm_path = self.hwmon_path.join(format!("pwm{}", i));
                let pwm = fs::read_to_string(&pwm_path)
                    .ok()
                    .and_then(|s| s.trim().parse::<u8>().ok());

                // Check if PWM is writable (controllable). A NotFound on
                // pwm<N>_enable is a reading: the driver exposes no control
                // interface, so Some(false). Any other metadata failure
                // leaves the value undetermined (None).
                let pwm_enable_path = self.hwmon_path.join(format!("pwm{}_enable", i));
                let controllable = match fs::metadata(&pwm_enable_path) {
                    Ok(m) => Some(!m.permissions().readonly()),
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(false),
                    Err(_) => None,
                };

                let rpm_value = if rpm > 0 { Some(rpm as u32) } else { None };

                fans.push(FanInfo {
                    label,
                    rpm: rpm_value,
                    pwm,
                    min_rpm: None,
                    max_rpm: None,
                    controllable,
                });
            }
        }

        Ok(fans)
    }

    fn set_fan_speed(&self, fan_index: usize, speed: FanControl) -> Result<(), Error> {
        let pwm_path = self.hwmon_path.join(format!("pwm{}", fan_index + 1));
        let pwm_enable_path = self.hwmon_path.join(format!("pwm{}_enable", fan_index + 1));

        if !pwm_path.exists() {
            return Err(Error::FanControlError(format!(
                "Fan {} does not support PWM control",
                fan_index
            )));
        }

        match speed {
            FanControl::Manual(pwm_value) => {
                // Set to manual mode (pwm_enable = 1)
                fs::write(&pwm_enable_path, "1\n").map_err(|e| {
                    Error::PermissionDenied(format!("Failed to set fan mode: {}", e))
                })?;

                // Set PWM value
                fs::write(&pwm_path, format!("{}\n", pwm_value)).map_err(|e| {
                    Error::PermissionDenied(format!("Failed to set fan speed: {}", e))
                })?;
            }
            FanControl::Automatic => {
                // Set to automatic mode (pwm_enable = 2 or 5 depending on chip)
                fs::write(&pwm_enable_path, "2\n").map_err(|e| {
                    Error::PermissionDenied(format!("Failed to set fan mode: {}", e))
                })?;
            }
        }

        Ok(())
    }
}

/// Enumerate all hwmon sensors
pub fn enumerate() -> Result<Vec<Box<dyn MotherboardDevice>>, Error> {
    let hwmon_dir = Path::new("/sys/class/hwmon");

    if !hwmon_dir.exists() {
        return Err(Error::NoSensorsFound);
    }

    let mut devices: Vec<Box<dyn MotherboardDevice>> = Vec::new();

    for entry in fs::read_dir(hwmon_dir).map_err(Error::IoError)? {
        let entry = entry.map_err(Error::IoError)?;
        let path = entry.path();

        // Skip if not a directory
        if !path.is_dir() {
            continue;
        }

        // Try to create a sensor device
        if let Ok(sensor) = LinuxSensor::new(path) {
            devices.push(Box::new(sensor));
        }
    }

    if devices.is_empty() {
        Err(Error::NoSensorsFound)
    } else {
        Ok(devices)
    }
}

/// Read DMI/SMBIOS information
fn read_dmi(path: &str) -> Option<String> {
    fs::read_to_string(Path::new("/sys/class/dmi/id").join(path))
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

/// Detect firmware type (BIOS or UEFI)
///
/// `/sys/firmware/efi` existing is UEFI. Its absence is Legacy only when the
/// firmware directory itself is there to say so. Without `/sys/firmware` (sysfs
/// not mounted, as in some containers) the question was not answered, and this
/// used to report Legacy BIOS regardless.
fn detect_firmware_type() -> FirmwareType {
    if Path::new("/sys/firmware/efi").exists() {
        FirmwareType::Uefi
    } else if Path::new("/sys/firmware").exists() {
        FirmwareType::Bios
    } else {
        FirmwareType::Unknown
    }
}

/// Machine hardware name from `uname(2)`, e.g. "x86_64" or "aarch64".
fn machine_architecture() -> Option<String> {
    // SAFETY: `utsname` is plain old data, all-zero is a valid value, and
    // `uname` fills the struct it is given.
    let mut buf: libc::utsname = unsafe { std::mem::zeroed() };
    if unsafe { libc::uname(&mut buf) } != 0 {
        return None;
    }
    let bytes: Vec<u8> = buf
        .machine
        .iter()
        .take_while(|&&c| c != 0)
        .map(|&c| c as u8)
        .collect();
    String::from_utf8(bytes).ok().filter(|s| !s.is_empty())
}

/// Get system information
pub fn get_system_info() -> Result<SystemInfo, Error> {
    // OS information
    let os_release = fs::read_to_string("/etc/os-release")
        .or_else(|_| fs::read_to_string("/usr/lib/os-release"))
        .unwrap_or_default();

    let mut os_info = HashMap::new();
    for line in os_release.lines() {
        if let Some((key, value)) = line.split_once('=') {
            os_info.insert(key.to_string(), value.trim_matches('"').to_string());
        }
    }

    // Absent from os-release means the name was not read. This used to fall back
    // to the literal "Linux", a platform label rather than a reading.
    let os_name = os_info
        .get("PRETTY_NAME")
        .or_else(|| os_info.get("NAME"))
        .filter(|s| !s.is_empty())
        .cloned();

    // Absent or empty in os-release means the version was not read.
    let os_version = ["VERSION", "VERSION_ID"]
        .iter()
        .filter_map(|key| os_info.get(*key))
        .find(|v| !v.is_empty())
        .cloned();

    // Kernel version
    let kernel_version = fs::read_to_string("/proc/version")
        .ok()
        .and_then(|v| v.split_whitespace().nth(2).map(String::from));

    // Architecture, from uname(2)'s `machine` field. This used to be
    // `std::env::consts::ARCH`, the architecture the binary was compiled for.
    let architecture = machine_architecture();

    // Hostname
    let hostname = fs::read_to_string("/etc/hostname")
        .ok()
        .map(|s| s.trim().to_string());

    // BIOS information
    let bios = BiosInfo {
        vendor: read_dmi("bios_vendor"),
        version: read_dmi("bios_version"),
        release_date: read_dmi("bios_date"),
        revision: None,
        firmware_type: detect_firmware_type(),
        secure_boot: None, // Would need to parse /sys/firmware/efi/efivars/SecureBoot-*
    };

    // Hardware information
    let manufacturer = read_dmi("sys_vendor");
    let product_name = read_dmi("product_name");
    let serial_number = read_dmi("product_serial");
    let uuid = read_dmi("product_uuid");

    let board_vendor = read_dmi("board_vendor");
    let board_name = read_dmi("board_name");
    let board_version = read_dmi("board_version");

    // CPU information
    let cpuinfo = fs::read_to_string("/proc/cpuinfo").unwrap_or_default();
    let cpu_name = cpuinfo
        .lines()
        .find(|line| line.starts_with("model name"))
        .and_then(|line| line.split(':').nth(1))
        .map(|s| s.trim().to_string());

    let cpu_cores = cpuinfo
        .lines()
        .find(|line| line.starts_with("cpu cores"))
        .and_then(|line| line.split(':').nth(1))
        .and_then(|s| s.trim().parse::<u32>().ok());

    let cpu_threads = cpuinfo
        .lines()
        .filter(|line| line.starts_with("processor"))
        .count() as u32;

    let cpu_threads = if cpu_threads > 0 {
        Some(cpu_threads)
    } else {
        None
    };

    Ok(SystemInfo {
        os_name,
        os_version,
        kernel_version,
        architecture,
        hostname,
        bios,
        manufacturer,
        product_name,
        serial_number,
        uuid,
        board_vendor,
        board_name,
        board_version,
        cpu_name,
        cpu_cores,
        cpu_threads,
    })
}

/// Get driver/module versions
pub fn get_driver_versions() -> Result<Vec<DriverInfo>, Error> {
    let mut drivers = Vec::new();

    // GPU drivers
    if let Ok(version) = fs::read_to_string("/sys/module/nvidia/version") {
        drivers.push(DriverInfo {
            name: "nvidia".to_string(),
            version: (!version.trim().is_empty()).then(|| version.trim().to_string()),
            driver_type: DriverType::Gpu,
            description: Some("NVIDIA GPU Driver".to_string()),
            vendor: Some("NVIDIA".to_string()),
            date: None,
        });
    }

    if let Ok(version) = fs::read_to_string("/sys/module/amdgpu/version") {
        drivers.push(DriverInfo {
            name: "amdgpu".to_string(),
            version: (!version.trim().is_empty()).then(|| version.trim().to_string()),
            driver_type: DriverType::Gpu,
            description: Some("AMD GPU Driver".to_string()),
            vendor: Some("AMD".to_string()),
            date: None,
        });
    }

    if let Ok(version) = fs::read_to_string("/sys/module/i915/version") {
        drivers.push(DriverInfo {
            name: "i915".to_string(),
            version: (!version.trim().is_empty()).then(|| version.trim().to_string()),
            driver_type: DriverType::Gpu,
            description: Some("Intel GPU Driver".to_string()),
            vendor: Some("Intel".to_string()),
            date: None,
        });
    }

    // Storage drivers
    for module in &["nvme", "ahci", "sata_nv", "megaraid_sas"] {
        let version_path = format!("/sys/module/{}/version", module);
        if let Ok(version) = fs::read_to_string(&version_path) {
            drivers.push(DriverInfo {
                name: module.to_string(),
                version: (!version.trim().is_empty()).then(|| version.trim().to_string()),
                driver_type: DriverType::Storage,
                description: Some(format!("{} Storage Driver", module.to_uppercase())),
                vendor: None,
                date: None,
            });
        }
    }

    // Network drivers (common ones)
    for module in &["e1000e", "igb", "ixgbe", "r8169", "bnx2x"] {
        let version_path = format!("/sys/module/{}/version", module);
        if let Ok(version) = fs::read_to_string(&version_path) {
            drivers.push(DriverInfo {
                name: module.to_string(),
                version: (!version.trim().is_empty()).then(|| version.trim().to_string()),
                driver_type: DriverType::Network,
                description: Some(format!("{} Network Driver", module.to_uppercase())),
                vendor: None,
                date: None,
            });
        }
    }

    Ok(drivers)
}

/// Get PCIe devices from /sys/bus/pci/devices
pub fn get_pcie_devices() -> Result<Vec<PcieDeviceInfo>, Error> {
    let pci_dir = Path::new("/sys/bus/pci/devices");
    if !pci_dir.exists() {
        return Ok(Vec::new());
    }

    let mut devices = Vec::new();

    for entry in fs::read_dir(pci_dir).map_err(Error::IoError)? {
        let entry = entry.map_err(Error::IoError)?;
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }

        let bus_id = entry.file_name().to_string_lossy().to_string();

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

        // Read vendor and device IDs
        let vendor_id = fs::read_to_string(path.join("vendor"))
            .ok()
            .map(|s| s.trim().to_string());
        let device_id = fs::read_to_string(path.join("device"))
            .ok()
            .map(|s| s.trim().to_string());

        // Classify device from PCI class code
        let device_class = class.as_deref().and_then(classify_pci_class);

        // Read link speed/width from /sys/bus/pci/devices/XXXX:XX:XX.X/
        let current_link_speed = fs::read_to_string(path.join("current_link_speed"))
            .ok()
            .map(|s| s.trim().to_string());
        let current_link_width = fs::read_to_string(path.join("current_link_width"))
            .ok()
            .and_then(|s| s.trim().parse::<u8>().ok());

        // Derive PCIe generation from the transfer rate, matched exactly. Rates
        // not in the table have no generation here rather than a guessed one.
        let pcie_version = current_link_speed.as_deref().and_then(|s| {
            let rate = s.split_whitespace().next().unwrap_or("");
            match rate {
                "2.5" => Some("PCIe 1.0".to_string()),
                "5" | "5.0" => Some("PCIe 2.0".to_string()),
                "8" | "8.0" => Some("PCIe 3.0".to_string()),
                "16" | "16.0" => Some("PCIe 4.0".to_string()),
                "32" | "32.0" => Some("PCIe 5.0".to_string()),
                "64" | "64.0" => Some("PCIe 6.0".to_string()),
                _ => None,
            }
        });

        // Try to get device name from uevent or modalias
        let name = fs::read_to_string(path.join("label"))
            .ok()
            .map(|s| s.trim().to_string())
            .unwrap_or_else(|| {
                // Fallback: construct from bus_id and class
                format!(
                    "PCI {} ({})",
                    bus_id,
                    device_class.as_deref().unwrap_or("Unknown")
                )
            });

        devices.push(PcieDeviceInfo {
            name,
            device_id,
            vendor: vendor_id,
            pcie_version,
            link_width: current_link_width,
            link_speed: current_link_speed,
            slot: Some(bus_id),
            device_class,
        });
    }

    Ok(devices)
}

/// Classify a PCI class code into a human-readable category
fn classify_pci_class(class_hex: &str) -> Option<String> {
    // PCI class codes: 0xCCSSPP (class, subclass, prog-if)
    // A class code that does not parse is unknown, not "Unclassified".
    let class_code = u32::from_str_radix(class_hex.trim_start_matches("0x"), 16).ok()?;
    let class_id = (class_code >> 16) & 0xFF;
    Some(match class_id {
        0x00 => "Unclassified".to_string(),
        0x01 => "Storage".to_string(),
        0x02 => "Network".to_string(),
        0x03 => "Display/VGA".to_string(),
        0x04 => "Multimedia".to_string(),
        0x05 => "Memory".to_string(),
        0x06 => "Bridge".to_string(),
        0x07 => "Communication".to_string(),
        0x08 => "System Peripheral".to_string(),
        0x09 => "Input Device".to_string(),
        0x0A => "Docking Station".to_string(),
        0x0B => "Processor".to_string(),
        0x0C => "Serial Bus".to_string(),
        0x0D => "Wireless".to_string(),
        0x0E => "Intelligent I/O".to_string(),
        0x0F => "Satellite Communication".to_string(),
        0x10 => "Encryption/Decryption".to_string(),
        0x11 => "Signal Processing".to_string(),
        0x12 => "Processing Accelerator".to_string(),
        0x13 => "Non-Essential Instrumentation".to_string(),
        0x40 => "Co-Processor".to_string(),
        _ => format!("Class 0x{:02X}", class_id),
    })
}

/// Get SATA/storage devices from /sys/class/block
pub fn get_sata_devices() -> Result<Vec<SataDeviceInfo>, Error> {
    let block_dir = Path::new("/sys/class/block");
    if !block_dir.exists() {
        return Ok(Vec::new());
    }

    let mut devices = Vec::new();

    for entry in fs::read_dir(block_dir).map_err(Error::IoError)? {
        let entry = entry.map_err(Error::IoError)?;
        let name = entry.file_name().to_string_lossy().to_string();

        // Skip partitions (sda1, nvme0n1p1) - only include whole disks
        if name.contains('p') && name.starts_with("nvme") {
            continue; // Skip NVMe partition
        }
        if name.chars().last().is_some_and(|c| c.is_ascii_digit()) && !name.starts_with("nvme") {
            // Check if it's a partition of sdX type
            let base: String = name.chars().take_while(|c| !c.is_ascii_digit()).collect();
            if base.len() < name.len()
                && (base.starts_with("sd") || base.starts_with("hd") || base.starts_with("vd"))
            {
                continue;
            }
        }

        let path = entry.path();
        let device_path = path.join("device");

        // Skip non-physical devices (loop, ram, dm)
        if name.starts_with("loop") || name.starts_with("ram") || name.starts_with("dm-") {
            continue;
        }

        // Read model
        let model = fs::read_to_string(device_path.join("model"))
            .ok()
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());

        // Read serial
        let serial = fs::read_to_string(device_path.join("serial"))
            .ok()
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());

        // Read firmware
        let firmware = fs::read_to_string(device_path.join("firmware_rev"))
            .or_else(|_| fs::read_to_string(device_path.join("rev")))
            .ok()
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());

        // Read size (in 512-byte sectors)
        let capacity_gb = fs::read_to_string(path.join("size"))
            .ok()
            .and_then(|s| s.trim().parse::<u64>().ok())
            .map(|sectors| (sectors * 512) as f64 / (1024.0 * 1024.0 * 1024.0));

        // Determine rotation rate to classify HDD vs SSD
        let rotation = fs::read_to_string(path.join("queue/rotational"))
            .ok()
            .and_then(|s| s.trim().parse::<u32>().ok());
        let media_type = match rotation {
            Some(0) => SataMediaType::Ssd,
            Some(1) => SataMediaType::Hdd,
            _ => SataMediaType::Unknown,
        };

        // Read temperature from hwmon if available
        let temperature = fs::read_dir(device_path.join("hwmon"))
            .ok()
            .and_then(|mut entries| entries.next())
            .and_then(|entry| entry.ok())
            .and_then(|entry| {
                fs::read_to_string(entry.path().join("temp1_input"))
                    .ok()
                    .and_then(|s| s.trim().parse::<f32>().ok())
                    .map(|t| t / 1000.0)
            });

        // Interface speed. A SATA disk's link is the one for its own ATA port,
        // taken from its sysfs path; reading link1 gave every disk port 1's speed.
        let ata_port = fs::canonicalize(&path).ok().and_then(|p| ata_port_of(&p));
        let interface_speed = if name.starts_with("nvme") {
            Some("NVMe".to_string())
        } else {
            ata_port
                .and_then(|n| {
                    fs::read_to_string(format!("/sys/class/ata_link/link{n}/sata_spd")).ok()
                })
                .map(|s| {
                    let s = s.trim();
                    match s {
                        "6.0 Gbps" | "6" => "SATA III (6 Gbps)".to_string(),
                        "3.0 Gbps" | "3" => "SATA II (3 Gbps)".to_string(),
                        "1.5 Gbps" | "1.5" => "SATA I (1.5 Gbps)".to_string(),
                        _ => format!("SATA ({})", s),
                    }
                })
        };

        devices.push(SataDeviceInfo {
            name,
            model,
            serial,
            firmware,
            capacity_gb,
            interface_speed,
            port: ata_port.and_then(|n| u8::try_from(n).ok()),
            temperature,
            media_type,
        });
    }

    Ok(devices)
}

/// The ATA port a block device hangs off, from the `ataN` component of its
/// canonical sysfs path (`/sys/devices/.../ata3/host2/.../block/sda`). `None` for
/// a disk not behind libata, such as USB or virtio.
fn ata_port_of(path: &Path) -> Option<u32> {
    path.components().find_map(|c| {
        c.as_os_str()
            .to_str()?
            .strip_prefix("ata")?
            .parse::<u32>()
            .ok()
    })
}

/// Get system temperatures from hwmon
pub fn get_system_temperatures() -> Result<SystemTemperatures, Error> {
    let sensors = enumerate()?;

    let mut cpu_temp: Option<f32> = None;
    let mut mb_temp: Option<f32> = None;
    let mut storage_temps: Vec<(String, f32)> = Vec::new();

    for sensor in &sensors {
        if let Ok(temp_sensors) = sensor.temperature_sensors() {
            for ts in &temp_sensors {
                match ts.sensor_type {
                    SensorType::Cpu => {
                        // Highest CPU temperature among sensors that produced
                        // one. A sensor with no reading cannot be the hottest.
                        if let Some(celsius) = ts.temperature {
                            if cpu_temp.is_none_or(|t| celsius > t) {
                                cpu_temp = Some(celsius);
                            }
                        }
                    }
                    SensorType::Chipset | SensorType::Ambient | SensorType::Vrm => {
                        if let Some(celsius) = ts.temperature {
                            if mb_temp.is_none_or(|t| celsius > t) {
                                mb_temp = Some(celsius);
                            }
                        }
                    }
                    SensorType::M2Slot => {
                        if let Some(celsius) = ts.temperature {
                            storage_temps.push((ts.label.clone(), celsius));
                        }
                    }
                    _ => {}
                }
            }
        }
    }

    // Also check block device temperatures
    let block_dir = Path::new("/sys/class/block");
    if block_dir.exists() {
        if let Ok(entries) = fs::read_dir(block_dir) {
            for entry in entries.flatten() {
                let name = entry.file_name().to_string_lossy().to_string();
                if name.starts_with("sd") || name.starts_with("nvme") {
                    let hwmon_path = entry.path().join("device/hwmon");
                    if let Ok(mut hwmon_entries) = fs::read_dir(&hwmon_path) {
                        if let Some(Ok(hwmon_entry)) = hwmon_entries.next() {
                            if let Ok(temp_str) =
                                fs::read_to_string(hwmon_entry.path().join("temp1_input"))
                            {
                                if let Ok(temp_millic) = temp_str.trim().parse::<f32>() {
                                    let temp_c = temp_millic / 1000.0;
                                    if temp_c > 0.0 && temp_c < 150.0 {
                                        storage_temps.push((name, temp_c));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    Ok(SystemTemperatures {
        cpu: cpu_temp,
        gpu: None, // GPU temps come from GPU module
        motherboard: mb_temp,
        storage: storage_temps,
        network: Vec::new(),
    })
}

/// Get all peripheral devices on Linux
pub fn get_peripherals() -> Result<PeripheralsInfo, Error> {
    let mut info = PeripheralsInfo::default();

    // USB devices from /sys/bus/usb/devices
    let usb_dir = Path::new("/sys/bus/usb/devices");
    if usb_dir.exists() {
        if let Ok(entries) = fs::read_dir(usb_dir) {
            for entry in entries.flatten() {
                let path = entry.path();

                // Only process actual devices (not interfaces)
                let name_str = entry.file_name().to_string_lossy().to_string();
                if name_str.contains(':') {
                    continue; // Skip interface entries
                }

                let product = fs::read_to_string(path.join("product"))
                    .ok()
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty());
                let manufacturer = fs::read_to_string(path.join("manufacturer"))
                    .ok()
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty());
                let vendor_id = fs::read_to_string(path.join("idVendor"))
                    .ok()
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty());
                let product_id = fs::read_to_string(path.join("idProduct"))
                    .ok()
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty());
                let speed = fs::read_to_string(path.join("speed"))
                    .ok()
                    .and_then(|s| s.trim().parse::<u32>().ok());
                let dev_class = fs::read_to_string(path.join("bDeviceClass"))
                    .ok()
                    .map(|s| s.trim().to_string());

                // Skip root hubs and devices with no product info
                if dev_class.as_deref() == Some("09") {
                    continue; // Hub
                }

                let name = product.unwrap_or_else(|| format!("USB Device {}", name_str));

                let usb_version = match speed {
                    Some(s) if s >= 10000 => UsbVersion::Usb3_1,
                    Some(s) if s >= 5000 => UsbVersion::Usb3_0,
                    Some(s) if s >= 480 => UsbVersion::Usb2_0,
                    Some(s) if s >= 12 => UsbVersion::Usb1_1,
                    _ => UsbVersion::Unknown,
                };

                info.usb_devices.push(UsbDeviceInfo {
                    name,
                    device_id: None,
                    vendor: manufacturer,
                    product_id,
                    vendor_id,
                    usb_version,
                    device_class: dev_class,
                    status: Some("Connected".to_string()),
                    hub_port: None,
                });
            }
        }
    }

    // Display outputs from /sys/class/drm
    let drm_dir = Path::new("/sys/class/drm");
    if drm_dir.exists() {
        if let Ok(entries) = fs::read_dir(drm_dir) {
            for entry in entries.flatten() {
                let name = entry.file_name().to_string_lossy().to_string();
                // Only connector entries (card0-HDMI-A-1, card0-DP-1, etc)
                if !name.contains('-') || name == "version" {
                    continue;
                }

                let status = fs::read_to_string(entry.path().join("status"))
                    .ok()
                    .map(|s| s.trim().to_string());

                let output_type = if name.contains("HDMI") {
                    DisplayOutputType::Hdmi
                // eDP must be tested before DP: "eDP-1" contains "DP", so the
                // DisplayPort arm would claim every internal panel and the eDP arm
                // below could never be reached. The enum has no `Edp`; an embedded
                // DisplayPort *is* the internal panel, which is what `Internal`
                // means.
                } else if name.contains("eDP") {
                    DisplayOutputType::Internal
                } else if name.contains("DP") || name.contains("DisplayPort") {
                    DisplayOutputType::DisplayPort
                } else if name.contains("VGA") {
                    DisplayOutputType::Vga
                } else if name.contains("DVI") {
                    DisplayOutputType::Dvi
                } else {
                    DisplayOutputType::Unknown
                };

                info.display_outputs.push(DisplayOutputInfo {
                    name: name.clone(),
                    output_type,
                    connected: status.as_deref() == Some("connected"),
                    resolution: None,
                    refresh_rate: None,
                    // sysfs exposes the connector, not which GPU drives it; that
                    // needs a DRM query this path does not make.
                    adapter: None,
                });
            }
        }
    }

    // Audio devices from /proc/asound/cards
    if let Ok(content) = fs::read_to_string("/proc/asound/cards") {
        for line in content.lines() {
            let line = line.trim();
            // Lines like: " 0 [HDA-Intel     ]: HDA-Intel - HDA NVidia"
            if line.starts_with(|c: char| c.is_ascii_digit()) {
                let parts: Vec<&str> = line.splitn(2, ':').collect();
                if parts.len() == 2 {
                    let name = parts[1].trim().to_string();
                    // The card's PCM entries say which directions it carries. With
                    // none readable the direction is unknown; it used to be a
                    // constant `Output` for every card.
                    let pcm_names: Vec<String> = line
                        .split_whitespace()
                        .next()
                        .and_then(|n| n.parse::<u32>().ok())
                        .and_then(|card| fs::read_dir(format!("/proc/asound/card{card}")).ok())
                        .into_iter()
                        .flatten()
                        .flatten()
                        .map(|e| e.file_name().to_string_lossy().into_owned())
                        .collect();
                    info.audio_devices.push(AudioDeviceInfo {
                        name,
                        device_type: alsa_card_type(pcm_names.iter().map(String::as_str)),
                        // The struct has `manufacturer`, not `driver`. ALSA is the
                        // subsystem this was read through, not who made the device,
                        // so claiming it as the manufacturer would be wrong.
                        manufacturer: None,
                        status: Some("Available".to_string()),
                        is_default: false,
                    });
                }
            }
        }
    }

    // Bluetooth from /sys/class/bluetooth
    let bt_dir = Path::new("/sys/class/bluetooth");
    if bt_dir.exists() {
        if let Ok(entries) = fs::read_dir(bt_dir) {
            for entry in entries.flatten() {
                let name = entry.file_name().to_string_lossy().to_string();
                let address = fs::read_to_string(entry.path().join("address"))
                    .ok()
                    .map(|s| s.trim().to_string());
                info.bluetooth_devices.push(BluetoothDeviceInfo {
                    name: format!("Bluetooth Adapter ({})", name),
                    address,
                    connected: true,
                    device_type: Some("Adapter".to_string()),
                    // This enumerates adapters under /sys/class/bluetooth, not
                    // remote devices; an adapter is not paired with anything.
                    paired: false,
                });
            }
        }
    }

    // Network ports from /sys/class/net
    let net_dir = Path::new("/sys/class/net");
    if net_dir.exists() {
        if let Ok(entries) = fs::read_dir(net_dir) {
            for entry in entries.flatten() {
                let name = entry.file_name().to_string_lossy().to_string();
                if name == "lo" {
                    continue; // Skip loopback
                }

                let speed = fs::read_to_string(entry.path().join("speed"))
                    .ok()
                    .and_then(|s| s.trim().parse::<u32>().ok());
                let operstate = fs::read_to_string(entry.path().join("operstate"))
                    .ok()
                    .map(|s| s.trim().to_string());
                let port_type = if name.starts_with("wl") || name.starts_with("wlan") {
                    NetworkPortType::WiFi
                } else if name.starts_with("eth") || name.starts_with("en") {
                    NetworkPortType::Ethernet
                } else {
                    NetworkPortType::Other
                };

                info.network_ports.push(NetworkPortInfo {
                    name,
                    port_type,
                    // The field is `speed: Option<String>`, and sysfs reports Mbit/s;
                    // keep the unit in the text rather than dropping it silently.
                    speed: speed.map(|mbps| format!("{mbps} Mb/s")),
                    // Only `up`, `down` and `lowerlayerdown` are a reading of the link.
                    // Other states such as `unknown` or `dormant`, or an unreadable
                    // file, leave it unread.
                    connected: match operstate.as_deref() {
                        Some("up") => Some(true),
                        Some("down" | "lowerlayerdown") => Some(false),
                        _ => None,
                    },
                    mac_address: fs::read_to_string(entry.path().join("address"))
                        .ok()
                        .map(|s| s.trim().to_string()),
                });
            }
        }
    }

    Ok(info)
}

/// Direction an ALSA card carries, from the `pcmNp` and `pcmNc` entries under its
/// `/proc/asound/cardN` directory. `None` when it has neither. This mirrors
/// `audio::alsa_pcm_directions`, which is private to that module.
fn alsa_card_type<'a>(entries: impl IntoIterator<Item = &'a str>) -> Option<AudioDeviceType> {
    let mut playback = false;
    let mut capture = false;
    for entry in entries {
        let Some(rest) = entry.strip_prefix("pcm") else {
            continue;
        };
        let Some(direction) = rest.chars().last() else {
            continue;
        };
        let digits = &rest[..rest.len() - direction.len_utf8()];
        if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
            continue;
        }
        match direction {
            'p' => playback = true,
            'c' => capture = true,
            _ => {}
        }
    }
    match (playback, capture) {
        (true, true) => Some(AudioDeviceType::OutputInput),
        (true, false) => Some(AudioDeviceType::Output),
        (false, true) => Some(AudioDeviceType::Input),
        (false, false) => None,
    }
}

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

    #[test]
    fn a_card_is_its_directions_from_any_pcm_number() {
        assert_eq!(
            alsa_card_type(["pcm0p", "pcm3p", "pcm0c"]),
            Some(AudioDeviceType::OutputInput)
        );
        // An HDMI card whose playback lives on device 7, not 0.
        assert_eq!(alsa_card_type(["pcm7p"]), Some(AudioDeviceType::Output));
        assert_eq!(alsa_card_type(["pcm0c"]), Some(AudioDeviceType::Input));
    }

    #[test]
    fn a_card_with_no_pcm_entries_has_no_direction() {
        assert_eq!(alsa_card_type(std::iter::empty()), None);
        assert_eq!(alsa_card_type(["id", "pcmp", "pcmx"]), None);
    }

    #[test]
    fn ata_port_comes_from_the_disks_own_sysfs_path() {
        let sda = Path::new(
            "/sys/devices/pci0000:00/0000:00:17.0/ata3/host2/target2:0:0/2:0:0:0/block/sda",
        );
        assert_eq!(ata_port_of(sda), Some(3));
        let usb = Path::new("/sys/devices/pci0000:00/0000:00:14.0/usb2/2-1/host6/block/sdb");
        assert_eq!(ata_port_of(usb), None);
    }
}