feat: gpio feature根据操作系统自动判断

This commit is contained in:
grabbit 2025-04-05 15:10:21 +08:00
parent 0763a9e1d5
commit 2ce3b11628
3 changed files with 23 additions and 10 deletions

View File

@ -6,7 +6,15 @@ authors = ["Meteor Detection Team"]
description = "A Raspberry Pi based meteor detection system" description = "A Raspberry Pi based meteor detection system"
[features] [features]
# 默认features在Linux上自动包含gpio
default = [] default = []
# 如果在Linux上运行则默认启用GPIO support
# 这确保rppal和embedded-hal依赖会被编译进来
[target.'cfg(target_os = "linux")'.features]
default = ["gpio"]
# 定义常规的features (全平台通用)
gpio = ["rppal", "embedded-hal"] # Feature to enable GPIO functionality gpio = ["rppal", "embedded-hal"] # Feature to enable GPIO functionality
opencv-4-11-plus = [] # For OpenCV 4.11 and newer versions opencv-4-11-plus = [] # For OpenCV 4.11 and newer versions

View File

@ -7,12 +7,19 @@ fn main() {
// 检测当前是否在树莓派或其他支持GPIO的Linux平台上 // 检测当前是否在树莓派或其他支持GPIO的Linux平台上
let supports_gpio = detect_gpio_support(); let supports_gpio = detect_gpio_support();
// 自动启用GPIO功能如果支持 // 设置环境变量告诉lib.rs是否有实际的GPIO支持
// 注意这只影响PLATFORM_SUPPORTS_GPIO的值不影响依赖的启用
if supports_gpio { if supports_gpio {
println!("cargo:rustc-cfg=feature=\"gpio\""); // 设置编译器配置lib.rs会使用它
println!("cargo:warning=GPIO support detected, enabling gpio feature"); println!("cargo:rustc-env=HAS_GPIO_SUPPORT=true");
println!("cargo:warning=GPIO support detected, PLATFORM_SUPPORTS_GPIO will be true");
} else if cfg!(target_os = "linux") {
// 特殊情况Linux但没有GPIO支持
println!("cargo:rustc-env=HAS_GPIO_SUPPORT=false");
println!("cargo:warning=Running on Linux but no GPIO support detected, PLATFORM_SUPPORTS_GPIO will be false");
} else { } else {
println!("cargo:warning=No GPIO support detected, gpio feature NOT enabled"); println!("cargo:rustc-env=HAS_GPIO_SUPPORT=false");
println!("cargo:warning=No GPIO support detected, PLATFORM_SUPPORTS_GPIO will be false");
} }
// 通过包含的 OpenCV 库检测版本 // 通过包含的 OpenCV 库检测版本
@ -101,8 +108,7 @@ fn detect_gpio_support() -> bool {
} }
} }
// 如果还没确定检查是否在CARGO_FEATURE_GPIO环境变量中强制启用 // 如果还没确定,检查是否在环境变量中强制启用
// 这允许用户手动启用GPIO功能覆盖自动检测
if env::var("CARGO_FEATURE_GPIO").is_ok() { if env::var("CARGO_FEATURE_GPIO").is_ok() {
return true; return true;
} }

View File

@ -1,8 +1,7 @@
// 这里的常量将在编译时由build.rs设置 // 使用由build.rs设置的环境变量来确定是否有GPIO支持
// 通过rustc-cfg设置的cfg特性可以在代码中使用 // 这让代码可以区分"有依赖但没有实际GPIO"和"有依赖且有实际GPIO"的情况
// 将PLATFORM_SUPPORTS_GPIO基于实际检测到的GPIO支持来设置
#[cfg(feature = "gpio")] #[cfg(feature = "gpio")]
pub const PLATFORM_SUPPORTS_GPIO: bool = true; pub const PLATFORM_SUPPORTS_GPIO: bool = option_env!("HAS_GPIO_SUPPORT").map_or(false, |v| v == "true");
#[cfg(not(feature = "gpio"))] #[cfg(not(feature = "gpio"))]
pub const PLATFORM_SUPPORTS_GPIO: bool = false; pub const PLATFORM_SUPPORTS_GPIO: bool = false;