hardware-query 0.2.1

Cross-platform Rust library for comprehensive hardware detection, real-time monitoring, power management, and AI/ML optimization
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
use crate::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[cfg(target_arch = "aarch64")]
use std::process::Command;

/// ARM-based system type
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ARMSystemType {
    RaspberryPi,
    NVIDIAJetson,
    AppleSilicon,
    QualcommSnapdragon,
    MediaTekDimensity,
    SamsungExynos,
    HiSiliconKirin,
    AmazonGraviton,
    AmpereAltra,
    Unknown(String),
}

impl std::fmt::Display for ARMSystemType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ARMSystemType::RaspberryPi => write!(f, "Raspberry Pi"),
            ARMSystemType::NVIDIAJetson => write!(f, "NVIDIA Jetson"),
            ARMSystemType::AppleSilicon => write!(f, "Apple Silicon"),
            ARMSystemType::QualcommSnapdragon => write!(f, "Qualcomm Snapdragon"),
            ARMSystemType::MediaTekDimensity => write!(f, "MediaTek Dimensity"),
            ARMSystemType::SamsungExynos => write!(f, "Samsung Exynos"),
            ARMSystemType::HiSiliconKirin => write!(f, "HiSilicon Kirin"),
            ARMSystemType::AmazonGraviton => write!(f, "Amazon Graviton"),
            ARMSystemType::AmpereAltra => write!(f, "Ampere Altra"),
            ARMSystemType::Unknown(name) => write!(f, "{name}"),
        }
    }
}

/// ARM hardware information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ARMHardwareInfo {
    /// System type
    pub system_type: ARMSystemType,
    
    /// Board model
    pub board_model: String,
    
    /// Board revision
    pub board_revision: Option<String>,
    
    /// Serial number
    pub serial_number: Option<String>,
    
    /// CPU architecture
    pub cpu_architecture: String,
    
    /// CPU cores
    pub cpu_cores: u32,
    
    /// GPU information (if available)
    pub gpu_info: Option<String>,
    
    /// Available acceleration features
    pub acceleration_features: Vec<String>,
    
    /// AI/ML capabilities
    pub ml_capabilities: HashMap<String, String>,
    
    /// Memory configuration
    pub memory_mb: Option<u64>,
    
    /// Available interfaces
    pub interfaces: Vec<String>,
    
    /// Power information
    pub power_info: Option<PowerInfo>,
}

/// Power consumption and thermal information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PowerInfo {
    /// Current power consumption in watts
    pub power_consumption: Option<f32>,
    
    /// CPU temperature in Celsius
    pub cpu_temperature: Option<f32>,
    
    /// GPU temperature in Celsius (if available)
    pub gpu_temperature: Option<f32>,
    
    /// Throttling status
    pub throttling: bool,
    
    /// Power supply voltage
    pub voltage: Option<f32>,
}

impl ARMHardwareInfo {
    /// Detect ARM-based hardware information
    pub fn detect() -> Result<Option<ARMHardwareInfo>> {
        #[cfg(target_arch = "aarch64")]
        {
            // Only detect on ARM64 systems
            if let Some(hardware_info) = Self::detect_raspberry_pi()? {
                return Ok(Some(hardware_info));
            }
            
            if let Some(hardware_info) = Self::detect_nvidia_jetson()? {
                return Ok(Some(hardware_info));
            }
            
            if let Some(hardware_info) = Self::detect_apple_silicon()? {
                return Ok(Some(hardware_info));
            }
            
            if let Some(hardware_info) = Self::detect_qualcomm_snapdragon()? {
                return Ok(Some(hardware_info));
            }
            
            // Generic ARM detection
            if let Some(hardware_info) = Self::detect_generic_arm()? {
                return Ok(Some(hardware_info));
            }
        }
        
        #[cfg(not(target_arch = "aarch64"))]
        {
            // On non-ARM systems, still try to detect if we're in an emulated environment
            // or if there's ARM hardware information available
        }
        
        Ok(None)
    }
    
    #[cfg(target_arch = "aarch64")]
    fn detect_raspberry_pi() -> Result<Option<ARMHardwareInfo>> {
        // Check for Raspberry Pi specific files
        if let Ok(model) = std::fs::read_to_string("/proc/device-tree/model") {
            if model.to_lowercase().contains("raspberry pi") {
                let mut hardware_info = ARMHardwareInfo {
                    system_type: ARMSystemType::RaspberryPi,
                    board_model: model.trim_end_matches('\0').to_string(),
                    board_revision: Self::get_pi_revision(),
                    serial_number: Self::get_pi_serial(),
                    cpu_architecture: Self::get_cpu_architecture(),
                    cpu_cores: Self::get_cpu_cores(),
                    gpu_info: Some("VideoCore GPU".to_string()),
                    acceleration_features: Self::get_pi_acceleration_features(),
                    ml_capabilities: Self::get_pi_ml_capabilities(),
                    memory_mb: Self::get_memory_size(),
                    interfaces: Self::get_pi_interfaces(),
                    power_info: Self::get_pi_power_info(),
                };
                
                // Determine specific Pi model for better capabilities
                if model.contains("Pi 5") {
                    hardware_info.acceleration_features.push("VideoCore VII GPU".to_string());
                    hardware_info.ml_capabilities.insert(
                        "inference_performance".to_string(),
                        "High (ARM Cortex-A76)".to_string(),
                    );
                } else if model.contains("Pi 4") {
                    hardware_info.acceleration_features.push("VideoCore VI GPU".to_string());
                    hardware_info.ml_capabilities.insert(
                        "inference_performance".to_string(),
                        "Medium (ARM Cortex-A72)".to_string(),
                    );
                }
                
                return Ok(Some(hardware_info));
            }
        }
        
        // Alternative detection via /proc/cpuinfo
        if let Ok(cpuinfo) = std::fs::read_to_string("/proc/cpuinfo") {
            if cpuinfo.contains("BCM") && cpuinfo.contains("Raspberry Pi") {
                // Extract model from hardware line
                for line in cpuinfo.lines() {
                    if line.starts_with("Model") {
                        return Ok(Some(ARMHardwareInfo {
                            system_type: ARMSystemType::RaspberryPi,
                            board_model: line.split(':').nth(1).unwrap_or("Unknown").trim().to_string(),
                            board_revision: Self::get_pi_revision(),
                            serial_number: Self::get_pi_serial(),
                            cpu_architecture: Self::get_cpu_architecture(),
                            cpu_cores: Self::get_cpu_cores(),
                            gpu_info: Some("VideoCore GPU".to_string()),
                            acceleration_features: Self::get_pi_acceleration_features(),
                            ml_capabilities: Self::get_pi_ml_capabilities(),
                            memory_mb: Self::get_memory_size(),
                            interfaces: Self::get_pi_interfaces(),
                            power_info: Self::get_pi_power_info(),
                        }));
                    }
                }
            }
        }
        
        Ok(None)
    }
    
    #[cfg(target_arch = "aarch64")]
    fn detect_nvidia_jetson() -> Result<Option<ARMHardwareInfo>> {
        // Check for Jetson-specific files
        if let Ok(model) = std::fs::read_to_string("/proc/device-tree/model") {
            let model_lower = model.to_lowercase();
            if model_lower.contains("jetson") || model_lower.contains("tegra") {
                let jetson_model = if model_lower.contains("nano") {
                    "NVIDIA Jetson Nano"
                } else if model_lower.contains("xavier") {
                    if model_lower.contains("nx") {
                        "NVIDIA Jetson Xavier NX"
                    } else {
                        "NVIDIA Jetson AGX Xavier"
                    }
                } else if model_lower.contains("orin") {
                    if model_lower.contains("nx") {
                        "NVIDIA Jetson Orin NX"
                    } else if model_lower.contains("nano") {
                        "NVIDIA Jetson Orin Nano"
                    } else {
                        "NVIDIA Jetson AGX Orin"
                    }
                } else {
                    "NVIDIA Jetson"
                };
                
                return Ok(Some(ARMHardwareInfo {
                    system_type: ARMSystemType::NVIDIAJetson,
                    board_model: jetson_model.to_string(),
                    board_revision: Self::get_jetson_revision(),
                    serial_number: Self::get_jetson_serial(),
                    cpu_architecture: Self::get_cpu_architecture(),
                    cpu_cores: Self::get_cpu_cores(),
                    gpu_info: Some("NVIDIA GPU with CUDA support".to_string()),
                    acceleration_features: Self::get_jetson_acceleration_features(jetson_model),
                    ml_capabilities: Self::get_jetson_ml_capabilities(jetson_model),
                    memory_mb: Self::get_memory_size(),
                    interfaces: Self::get_jetson_interfaces(),
                    power_info: Self::get_jetson_power_info(),
                }));
            }
        }
        
        // Check via lshw or nvidia-smi if available
        if let Ok(output) = Command::new("nvidia-smi").arg("-L").output() {
            if output.status.success() {
                let output_str = String::from_utf8_lossy(&output.stdout);
                if output_str.contains("Tegra") || output_str.contains("Jetson") {
                    return Ok(Some(ARMHardwareInfo {
                        system_type: ARMSystemType::NVIDIAJetson,
                        board_model: "NVIDIA Jetson (detected via nvidia-smi)".to_string(),
                        board_revision: None,
                        serial_number: None,
                        cpu_architecture: Self::get_cpu_architecture(),
                        cpu_cores: Self::get_cpu_cores(),
                        gpu_info: Some(output_str.trim().to_string()),
                        acceleration_features: vec!["CUDA".to_string(), "TensorRT".to_string()],
                        ml_capabilities: HashMap::from([
                            ("cuda_support".to_string(), "true".to_string()),
                            ("tensorrt_support".to_string(), "true".to_string()),
                        ]),
                        memory_mb: Self::get_memory_size(),
                        interfaces: vec!["USB".to_string(), "Ethernet".to_string(), "WiFi".to_string()],
                        power_info: None,
                    }));
                }
            }
        }
        
        Ok(None)
    }
    
    #[cfg(target_arch = "aarch64")]
    fn detect_apple_silicon() -> Result<Option<ARMHardwareInfo>> {
        #[cfg(target_os = "macos")]
        {
            if let Ok(output) = Command::new("sysctl")
                .args(["-n", "machdep.cpu.brand_string"])
                .output()
            {
                let cpu_brand = String::from_utf8_lossy(&output.stdout);
                if cpu_brand.contains("Apple M") {
                    let chip_name = cpu_brand.trim().to_string();
                    return Ok(Some(ARMHardwareInfo {
                        system_type: ARMSystemType::AppleSilicon,
                        board_model: format!("Apple Silicon ({})", chip_name),
                        board_revision: None,
                        serial_number: None,
                        cpu_architecture: "ARM64".to_string(),
                        cpu_cores: Self::get_cpu_cores(),
                        gpu_info: Some("Apple GPU".to_string()),
                        acceleration_features: vec![
                            "Apple Neural Engine".to_string(),
                            "Metal".to_string(),
                            "AMX".to_string(),
                        ],
                        ml_capabilities: HashMap::from([
                            ("neural_engine".to_string(), "true".to_string()),
                            ("core_ml".to_string(), "true".to_string()),
                            ("metal_performance_shaders".to_string(), "true".to_string()),
                        ]),
                        memory_mb: Self::get_memory_size(),
                        interfaces: vec!["Thunderbolt".to_string(), "USB-C".to_string(), "WiFi".to_string()],
                        power_info: None,
                    }));
                }
            }
        }
        Ok(None)
    }
    
    // Helper functions for hardware detection
    #[cfg(target_arch = "aarch64")]
    fn get_pi_revision() -> Option<String> {
        std::fs::read_to_string("/proc/cpuinfo")
            .ok()?
            .lines()
            .find(|line| line.starts_with("Revision"))
            .and_then(|line| line.split(':').nth(1))
            .map(|s| s.trim().to_string())
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_pi_serial() -> Option<String> {
        std::fs::read_to_string("/proc/cpuinfo")
            .ok()?
            .lines()
            .find(|line| line.starts_with("Serial"))
            .and_then(|line| line.split(':').nth(1))
            .map(|s| s.trim().to_string())
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_cpu_architecture() -> String {
        std::env::consts::ARCH.to_string()
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_cpu_cores() -> u32 {
        num_cpus::get() as u32
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_memory_size() -> Option<u64> {
        if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") {
            for line in meminfo.lines() {
                if line.starts_with("MemTotal:") {
                    if let Some(kb_str) = line.split_whitespace().nth(1) {
                        if let Ok(kb) = kb_str.parse::<u64>() {
                            return Some(kb / 1024); // Convert KB to MB
                        }
                    }
                }
            }
        }
        None
    }
    
    // Placeholder implementations - would be expanded with real detection
    #[cfg(target_arch = "aarch64")]
    fn detect_qualcomm_snapdragon() -> Result<Option<ARMHardwareInfo>> {
        Ok(None)
    }
    
    #[cfg(target_arch = "aarch64")]
    fn detect_generic_arm() -> Result<Option<ARMHardwareInfo>> {
        Ok(None)
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_pi_acceleration_features() -> Vec<String> {
        vec!["VideoCore GPU".to_string(), "Hardware Video Decode".to_string()]
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_pi_ml_capabilities() -> HashMap<String, String> {
        HashMap::from([
            ("cpu_inference".to_string(), "true".to_string()),
            ("frameworks".to_string(), "TensorFlow Lite, PyTorch".to_string()),
        ])
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_pi_interfaces() -> Vec<String> {
        vec!["GPIO".to_string(), "I2C".to_string(), "SPI".to_string(), "UART".to_string()]
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_pi_power_info() -> Option<PowerInfo> {
        // Try to read Pi-specific thermal info
        let cpu_temp = std::fs::read_to_string("/sys/class/thermal/thermal_zone0/temp")
            .ok()
            .and_then(|temp_str| temp_str.trim().parse::<f32>().ok())
            .map(|temp| temp / 1000.0); // Convert millidegrees to degrees
        
        Some(PowerInfo {
            power_consumption: None, // Pi doesn't expose this easily
            cpu_temperature: cpu_temp,
            gpu_temperature: None,
            throttling: false, // Would need to check throttling flags
            voltage: None,
        })
    }
    
    // Jetson-specific helper functions
    #[cfg(target_arch = "aarch64")]
    fn get_jetson_revision() -> Option<String> {
        None // Placeholder
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_jetson_serial() -> Option<String> {
        None // Placeholder
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_jetson_acceleration_features(model: &str) -> Vec<String> {
        let mut features = vec!["CUDA".to_string(), "TensorRT".to_string()];
        
        if model.contains("Orin") {
            features.push("Ampere GPU".to_string());
            features.push("NVENC/NVDEC".to_string());
        } else if model.contains("Xavier") {
            features.push("Volta GPU".to_string());
            features.push("Deep Learning Accelerator".to_string());
        }
        
        features
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_jetson_ml_capabilities(model: &str) -> HashMap<String, String> {
        let mut capabilities = HashMap::from([
            ("cuda_support".to_string(), "true".to_string()),
            ("tensorrt_support".to_string(), "true".to_string()),
            ("deep_learning_accelerator".to_string(), "true".to_string()),
        ]);
        
        if model.contains("Orin") {
            capabilities.insert("inference_performance".to_string(), "Very High".to_string());
            capabilities.insert("training_support".to_string(), "Yes".to_string());
        } else if model.contains("Xavier") {
            capabilities.insert("inference_performance".to_string(), "High".to_string());
            capabilities.insert("training_support".to_string(), "Limited".to_string());
        }
        
        capabilities
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_jetson_interfaces() -> Vec<String> {
        vec![
            "USB".to_string(),
            "Ethernet".to_string(),
            "WiFi".to_string(),
            "GPIO".to_string(),
            "I2C".to_string(),
            "SPI".to_string(),
            "UART".to_string(),
            "CSI Camera".to_string(),
            "HDMI".to_string(),
        ]
    }
    
    #[cfg(target_arch = "aarch64")]
    fn get_jetson_power_info() -> Option<PowerInfo> {
        None // Placeholder - would read from Jetson power monitoring
    }
}