example_component 是一个基于 RT-Thread 的 Rust 组件示例,展示了如何在 RT-Thread 系统中实现、注册和管理 Rust 组件。该项目采用统一的组件注册架构,避免了组件重复注册问题,并支持基于 RT-Thread 配置的条件编译。
example_component/
├── SConscript # SCons 构建脚本
├── component_registry/ # 统一组件注册程序
│ ├── Cargo.toml # 注册程序配置
│ └── src/
│ └── lib.rs # 注册程序实现
├── log/ # 日志组件示例
│ ├── Cargo.toml # 日志组件配置
│ └── src/
│ ├── lib.rs # 日志组件实现
│ └── logging.rs # 日志功能模块
└── tools/ # 构建工具
├── build_component.py # 组件构建工具
└── feature_config_component.py # 特性配置
component_registry 统一管理所有组件的注册,避免多个组件重复注册导致的冲突component_registry 是整个架构的核心,负责统一管理所有组件的注册。
rust_component_registry 作为所有组件的统一注册入口log 组件提供了 Rust 风格的日志功能,包括多个日志级别和命令行接口。
log_info、log_warn、log_error 等命令enable-log 特性启用时编译// 在代码中使用日志宏
info!("这是一条信息日志");
warn!("这是一条警告日志");
error!("这是一条错误日志");
# 在 RT-Thread 命令行中使用
msh> log_info # 打印信息日志
msh> log_warn # 打印警告日志
msh> log_error # 打印错误日志
在 tools/feature_config_component.py 中定义了 RT-Thread 配置到 Rust 特性的映射:
CONFIG_COMPONENT_FEATURE_MAP = {
'RUST_LOG_COMPONENT': {
'feature': 'enable-log',
'dependency': 'em_component_log',
'description': 'Enable Rust log component integration'
}
}
要启用日志组件,需要在 RT-Thread 配置中设置:
// 通过 menuconfig 设置
Enable Rust component support -> Auto-initialize Rust log component
创建组件目录
cargo new --lib example_component/new_component
cd example_component/new_component
创建 Cargo.toml
[package]
name = "em_component_new"
version = "0.1.0"
edition = "2021"
[lib]
name = "em_component_new"
crate-type = ["staticlib"]
[dependencies]
rt-rust = { path = "../../rust" }
macro_main = { path = "../../rust/macro-main" }
[features]
default = []
enable-new = []
实现组件功能
// src/new.rs
// 新组件的实现代码
// src/lib.rs
#![no_std]
// 导出需要的库
更新特性配置
# 在 tools/feature_config_component.py 中添加
CONFIG_COMPONENT_FEATURE_MAP = {
# ... 现有配置 ...
'RUST_NEW_COMPONENT': {
'feature': 'enable-new',
'dependency': 'em_component_new',
'description': 'Enable new component integration'
}
}
更新注册程序
# 在 component_registry/Cargo.toml 中添加
[dependencies]
em_component_new = { path = "../new_component", optional = true }
[features]
enable-new = ["em_component_new", "em_component_new/enable-new"]
// 在 component_registry/src/lib.rs 中注册
#[cfg(feature = "enable-new")]
use em_component_new;
fn component_registry_main() {
#[cfg(feature = "enable-new")]
{
println!("Component registry: New component enabled");
}
// ... 其他组件 ...
}
#[cfg(feature = "...")] 包装component_registry 统一管理编译失败
riscv64imac-unknown-none-elf) 已安装特性未启用
feature_config_component.py 中的映射配置链接错误
Cargo.toml 中的依赖配置RT-Thread Config
↓
Feature Mapping
↓
Rust Features
↓
Component Registry ← Individual Components
↓
RT-Thread System