From 2ce3b1162892f39963481b0ea196339aa59ea8ab Mon Sep 17 00:00:00 2001 From: grabbit Date: Sat, 5 Apr 2025 15:10:21 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20gpio=20feature=E6=A0=B9=E6=8D=AE?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E7=B3=BB=E7=BB=9F=E8=87=AA=E5=8A=A8=E5=88=A4?= =?UTF-8?q?=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.toml | 8 ++++++++ build.rs | 18 ++++++++++++------ src/lib.rs | 7 +++---- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 43c29f7..87f1f7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,15 @@ authors = ["Meteor Detection Team"] description = "A Raspberry Pi based meteor detection system" [features] +# 默认features,在Linux上自动包含gpio 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 opencv-4-11-plus = [] # For OpenCV 4.11 and newer versions diff --git a/build.rs b/build.rs index 1a45be8..34d4e5c 100644 --- a/build.rs +++ b/build.rs @@ -7,12 +7,19 @@ fn main() { // 检测当前是否在树莓派或其他支持GPIO的Linux平台上 let supports_gpio = detect_gpio_support(); - // 自动启用GPIO功能(如果支持) + // 设置环境变量,告诉lib.rs是否有实际的GPIO支持 + // 注意:这只影响PLATFORM_SUPPORTS_GPIO的值,不影响依赖的启用 if supports_gpio { - println!("cargo:rustc-cfg=feature=\"gpio\""); - println!("cargo:warning=GPIO support detected, enabling gpio feature"); + // 设置编译器配置,lib.rs会使用它 + 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 { - 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 库检测版本 @@ -101,8 +108,7 @@ fn detect_gpio_support() -> bool { } } - // 如果还没确定,检查是否在CARGO_FEATURE_GPIO环境变量中强制启用 - // 这允许用户手动启用GPIO功能(覆盖自动检测) + // 如果还没确定,检查是否在环境变量中强制启用 if env::var("CARGO_FEATURE_GPIO").is_ok() { return true; } diff --git a/src/lib.rs b/src/lib.rs index c81427f..0251ecc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,8 +1,7 @@ -// 这里的常量将在编译时由build.rs设置 -// 通过rustc-cfg设置的cfg特性可以在代码中使用 -// 将PLATFORM_SUPPORTS_GPIO基于实际检测到的GPIO支持来设置 +// 使用由build.rs设置的环境变量来确定是否有GPIO支持 +// 这让代码可以区分"有依赖但没有实际GPIO"和"有依赖且有实际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"))] pub const PLATFORM_SUPPORTS_GPIO: bool = false;