fix:树莓派检测

This commit is contained in:
grabbit 2025-04-05 23:37:03 +08:00
parent 40f17315a9
commit f57506023f

View File

@ -4,15 +4,15 @@ use std::fs;
use std::path::Path; use std::path::Path;
fn main() { fn main() {
// 检测当前是否在树莓派或其他支持GPIO的Linux平台 // 检测当前是否在树莓派
let supports_gpio = detect_gpio_support(); let is_raspberry_pi = detect_raspberry_pi();
// 自动启用GPIO功能如果支持 // 自动启用GPIO功能仅当是树莓派时
if supports_gpio { if is_raspberry_pi {
println!("cargo:rustc-cfg=feature=\"gpio\""); println!("cargo:rustc-cfg=feature=\"gpio\"");
println!("cargo:warning=GPIO support detected, enabling gpio feature"); println!("cargo:warning=Raspberry Pi detected, enabling gpio feature");
} else { } else {
println!("cargo:warning=No GPIO support detected, gpio feature NOT enabled"); println!("cargo:warning=Not running on Raspberry Pi, gpio feature NOT enabled");
} }
// 通过包含的 OpenCV 库检测版本 // 通过包含的 OpenCV 库检测版本
@ -34,8 +34,8 @@ fn main() {
} }
} }
fn detect_gpio_support() -> bool { fn detect_raspberry_pi() -> bool {
// 方法1: 检查是否是Linux系统 // 方法1: 检查是否是Linux系统(必要条件)
let is_linux = env::consts::OS == "linux"; let is_linux = env::consts::OS == "linux";
if !is_linux { if !is_linux {
return false; return false;
@ -56,23 +56,14 @@ fn detect_gpio_support() -> bool {
} }
} }
// 方法3: 检查是否存在/dev/gpiochip*设备 // 方法3: 检查树莓派特有的设备树模型文件
if Path::new("/dev/gpiochip0").exists() || if let Ok(model) = fs::read_to_string("/sys/firmware/devicetree/base/model") {
fs::read_dir("/dev").ok() if model.contains("Raspberry Pi") {
.map(|entries| entries.filter_map(Result::ok) return true;
.any(|entry| entry.file_name() }
.to_string_lossy()
.starts_with("gpiochip")))
.unwrap_or(false) {
return true;
} }
// 方法4: 检查是否存在/sys/class/gpio目录 // 方法4: 检查是否存在树莓派特有的库
if Path::new("/sys/class/gpio").exists() {
return true;
}
// 方法5: 检查是否安装了librpgpio库树莓派特有
let lib_check = Command::new("ldconfig") let lib_check = Command::new("ldconfig")
.args(["-p"]) .args(["-p"])
.output() .output()
@ -80,7 +71,7 @@ fn detect_gpio_support() -> bool {
.and_then(|output| { .and_then(|output| {
if output.status.success() { if output.status.success() {
let libraries = String::from_utf8_lossy(&output.stdout); let libraries = String::from_utf8_lossy(&output.stdout);
if libraries.contains("librpgpio") { if libraries.contains("librpgpio") || libraries.contains("libraspberrypi") {
Some(true) Some(true)
} else { } else {
None None
@ -94,14 +85,13 @@ fn detect_gpio_support() -> bool {
return true; return true;
} }
// 回退到检查核心文件路径查找 // 方法5: 检查树莓派特有的配置文件
if let Ok(model) = fs::read_to_string("/sys/firmware/devicetree/base/model") { if Path::new("/boot/config.txt").exists() || Path::new("/boot/firmware/config.txt").exists() {
if model.contains("Raspberry Pi") { // 这个文件在大多数树莓派系统上存在
return true; return true;
}
} }
// 如果还没确定,检查是否在CARGO_FEATURE_GPIO环境变量中强制启用 // 检查是否在CARGO_FEATURE_GPIO环境变量中强制启用
// 这允许用户手动启用GPIO功能覆盖自动检测 // 这允许用户手动启用GPIO功能覆盖自动检测
if env::var("CARGO_FEATURE_GPIO").is_ok() { if env::var("CARGO_FEATURE_GPIO").is_ok() {
return true; return true;