84 lines
2.6 KiB
Rust
84 lines
2.6 KiB
Rust
use std::process::Command;
|
||
use std::env;
|
||
use std::fs;
|
||
use std::path::Path;
|
||
|
||
fn main() {
|
||
// 检测当前是否在树莓派上
|
||
let is_raspberry_pi = detect_raspberry_pi();
|
||
|
||
// 自动启用GPIO功能(仅当是树莓派时)
|
||
if is_raspberry_pi {
|
||
println!("cargo:rustc-cfg=feature=\"gpio\"");
|
||
println!("cargo:warning=Raspberry Pi detected, enabling gpio feature for demos");
|
||
} else {
|
||
println!("cargo:warning=Not running on Raspberry Pi, gpio feature NOT enabled for demos");
|
||
}
|
||
}
|
||
|
||
fn detect_raspberry_pi() -> bool {
|
||
// 方法1: 检查是否是Linux系统(必要条件)
|
||
let is_linux = env::consts::OS == "linux";
|
||
if !is_linux {
|
||
return false;
|
||
}
|
||
|
||
// 方法2: 检查/proc/cpuinfo是否包含Raspberry Pi的特征
|
||
if let Ok(cpuinfo) = fs::read_to_string("/proc/cpuinfo") {
|
||
if cpuinfo.contains("Raspberry Pi") ||
|
||
cpuinfo.contains("BCM2708") ||
|
||
cpuinfo.contains("BCM2709") ||
|
||
cpuinfo.contains("BCM2710") ||
|
||
cpuinfo.contains("BCM2711") ||
|
||
cpuinfo.contains("BCM2835") ||
|
||
cpuinfo.contains("BCM2836") ||
|
||
cpuinfo.contains("BCM2837") ||
|
||
cpuinfo.contains("BCM2838") {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
// 方法3: 检查树莓派特有的设备树模型文件
|
||
if let Ok(model) = fs::read_to_string("/sys/firmware/devicetree/base/model") {
|
||
if model.contains("Raspberry Pi") {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
// 方法4: 检查是否存在树莓派特有的库
|
||
let lib_check = Command::new("ldconfig")
|
||
.args(["-p"])
|
||
.output()
|
||
.ok()
|
||
.and_then(|output| {
|
||
if output.status.success() {
|
||
let libraries = String::from_utf8_lossy(&output.stdout);
|
||
if libraries.contains("librpgpio") || libraries.contains("libraspberrypi") {
|
||
Some(true)
|
||
} else {
|
||
None
|
||
}
|
||
} else {
|
||
None
|
||
}
|
||
});
|
||
|
||
if lib_check.is_some() {
|
||
return true;
|
||
}
|
||
|
||
// 方法5: 检查树莓派特有的配置文件
|
||
if Path::new("/boot/config.txt").exists() || Path::new("/boot/firmware/config.txt").exists() {
|
||
// 这个文件在大多数树莓派系统上存在
|
||
return true;
|
||
}
|
||
|
||
// 检查是否在CARGO_FEATURE_GPIO环境变量中强制启用
|
||
// 这允许用户手动启用GPIO功能(覆盖自动检测)
|
||
if env::var("CARGO_FEATURE_GPIO").is_ok() {
|
||
return true;
|
||
}
|
||
|
||
// 否则默认为false
|
||
false
|
||
} |