Adding Rust Language Support for RT-Thread #10910
ToolsCI / Tools (push) Has been cancelled
RT-Thread BSP Static Build Check / 🔍 Summary of Git Diff Changes (push) Has been cancelled
RT-Thread BSP Static Build Check / ${{ matrix.legs.RTT_BSP }} (push) Has been cancelled
RT-Thread BSP Static Build Check / collect-artifacts (push) Has been cancelled
pkgs_test / change (push) Has been cancelled
utest_auto_run / A9 :components/dfs.cfg (push) Has been cancelled
utest_auto_run / A9 :components/lwip.cfg (push) Has been cancelled
utest_auto_run / A9 :components/netdev.cfg (push) Has been cancelled
utest_auto_run / A9 :components/sal.cfg (push) Has been cancelled
utest_auto_run / A9 :cpp11/cpp11.cfg (push) Has been cancelled
utest_auto_run / AARCH64-rtsmart :default.cfg (push) Has been cancelled
utest_auto_run / A9-rtsmart :default.cfg (push) Has been cancelled
utest_auto_run / RISCV-rtsmart :default.cfg (push) Has been cancelled
utest_auto_run / XUANTIE-rtsmart :default.cfg (push) Has been cancelled
utest_auto_run / AARCH64 :default.cfg (push) Has been cancelled
utest_auto_run / AARCH64-smp :default.cfg (push) Has been cancelled
utest_auto_run / A9 :default.cfg (push) Has been cancelled
utest_auto_run / A9-smp :default.cfg (push) Has been cancelled
utest_auto_run / RISCV :default.cfg (push) Has been cancelled
utest_auto_run / RISCV-smp :default.cfg (push) Has been cancelled
utest_auto_run / A9 :kernel/atomic_c11.cfg (push) Has been cancelled
utest_auto_run / RISCV :kernel/atomic_c11.cfg (push) Has been cancelled
utest_auto_run / A9 :kernel/ipc.cfg (push) Has been cancelled
utest_auto_run / A9 :kernel/kernel_basic.cfg (push) Has been cancelled
utest_auto_run / A9 :kernel/mem.cfg (push) Has been cancelled
Weekly CI Scheduler / Trigger and Monitor CIs (push) Has been cancelled
Weekly CI Scheduler / Create Discussion Report (push) Has been cancelled

This commit is contained in:
zhang san
2025-12-08 18:34:25 +08:00
committed by GitHub
parent cd1d47b87c
commit 69980f8b9d
88 changed files with 6734 additions and 4 deletions
+86
View File
@@ -0,0 +1,86 @@
# RT-Thread to Rust Feature Configuration System
This document explains how to use example configuration files to manage the mapping relationship between RT-Thread component configurations and Rust features.
## Overview
The configuration system allows you to extend the mapping relationship between RT-Thread component configuration items and Rust features through example configuration files, ensuring that only applications that depend on related components will enable corresponding features. Users can add new component configuration mappings as needed. This makes the system more modular and extensible.
## Core Components
### 1. Configuration Mapping Table (CONFIG_FEATURE_MAP)
The `CONFIG_FEATURE_MAP` located in `tools/feature_config_examples.py` defines the basic mapping relationship from RT-Thread component configuration items to Rust features:
```python
CONFIG_FEATURE_MAP = {
'RUST_LOG_COMPONENT': {
'feature': 'enable-log',
'dependencies': ['em_component_log'],
'description': 'Enable Rust logging component integration'
},
}
```
### 2. Dependency Check Mechanism
The system automatically checks the application's `Cargo.toml` file to ensure that only applications that depend on related components will enable corresponding features.
## How to Add New Components
### Using Example Configuration Files
1. View the example configurations in `feature_config_examples.py`
2. Modify the example configuration file as needed, adding the component configuration mappings you require
3. The system will automatically load the mappings from the example configuration file
4. Ensure that related component dependencies are added to the application's `Cargo.toml`
## Configuration Item Format
Each configuration item contains the following fields:
- `feature`: The name of the Rust feature to enable
- `dependencies`: Optional, list of components that the application must depend on
- `description`: Optional, description of the configuration item
## Example Scenario
1. Add the `RUST_LOG_COMPONENT` configuration item in RT-Thread's Kconfig
2. Add the corresponding mapping in `feature_config_examples.py`:
```python
CONFIG_FEATURE_MAP.update({
'RUST_LOG_COMPONENT': {
'feature': 'enable-log',
'dependencies': ['em_component_log'],
'description': 'Enable Rust logging component integration'
},
})
```
3. In the `Cargo.toml` of a Rust application that needs logging functionality:
```toml
[features]
enable-log = ["em_component_log/enable-log"]
[dependencies]
em_component_log = { path = "PATH/TO/components/log" }
```
## Troubleshooting
### Common Issues
1. **Feature not enabled**: Check if the application depends on the related components
2. **Build failure**: Ensure that the corresponding features are defined in the application's `Cargo.toml`
3. **Configuration not taking effect**: Verify that the RT-Thread configuration item is correctly enabled
4. **Example configuration not loaded**: Check if the `feature_config_examples.py` file exists and has correct syntax
### Debugging Steps
1. Check the configuration loading information in the build logs
2. Verify the syntax of the example configuration file
3. Check the feature enabling information in the build logs
4. Verify the application's `Cargo.toml` configuration
5. Confirm the RT-Thread configuration item status
+87
View File
@@ -0,0 +1,87 @@
# RT-Thread to Rust Feature Configuration System
这个文档说明如何使用示例配置文件来管理 RT-Thread 组件配置与 Rust features 之间的映射关系。
## 概述
配置系统允许你通过示例配置文件来扩展 RT-Thread 组件配置项与 Rust features 的映射关系,并确保只有依赖了相关组件的应用才会启用对应的 features,用户可以根据需要添加新的组件配置映射。这使得系统更加模块化和可扩展。
## 核心组件
### 1. 配置映射表 (CONFIG_FEATURE_MAP)
位于 `tools/feature_config_examples.py` 中的 `CONFIG_FEATURE_MAP` 定义了 RT-Thread 组件配置项到 Rust features 的基础映射关系:
```python
CONFIG_FEATURE_MAP = {
'RUST_LOG_COMPONENT': {
'feature': 'enable-log',
'dependencies': ['em_component_log'],
'description': 'Enable Rust logging component integration'
},
}
```
### 2. 依赖检查机制
系统会自动检查应用程序的 `Cargo.toml` 文件,确保只有依赖了相关组件的应用才会启用对应的 features。
## 如何添加新的组件
### 使用示例配置文件
1. 查看 `feature_config_examples.py` 中的示例配置
2. 根据需要修改示例配置文件,添加你需要的组件配置映射
3. 系统会自动加载示例配置文件中的映射
4. 确保在应用程序的 `Cargo.toml` 中添加了相关组件的依赖
## 配置项格式
每个配置项包含以下字段:
- `feature`: 要启用的 Rust feature 名称
- `dependencies`: 可选,应用程序必须依赖的组件列表
- `description`: 可选,配置项的描述
## 示例场景
1. 在 RT-Thread 的 Kconfig 中添加 `RUST_LOG_COMPONENT` 配置项
2. 在 `feature_config_examples.py` 中添加对应的映射:
```python
CONFIG_FEATURE_MAP.update({
'RUST_LOG_COMPONENT': {
'feature': 'enable-log',
'dependencies': ['em_component_log'],
'description': 'Enable Rust logging component integration'
},
})
```
3. 在需要日志功能的 Rust 应用的 `Cargo.toml` 中:
```toml
[features]
enable-log = ["em_component_log/enable-log"]
[dependencies]
em_component_log = { path = "PATH/TO/components/log" }
```
## 故障排除
### 常见问题
1. **Feature 未启用**: 检查应用是否依赖了相关组件
2. **构建失败**: 确保应用的 `Cargo.toml` 中定义了相应的 features
3. **配置不生效**: 验证 RT-Thread 配置项是否正确启用
4. **示例配置未加载**: 检查 `feature_config_examples.py` 文件是否存在且语法正确
### 调试步骤
1. 检查构建日志中的配置加载信息
2. 验证示例配置文件的语法
3. 检查构建日志中的 feature 启用信息
4. 验证应用的 `Cargo.toml` 配置
5. 确认 RT-Thread 配置项状态
@@ -0,0 +1,123 @@
# RT-Thread Rust Example User Applications
This directory contains a series of example user applications and components that demonstrate Rust programming capabilities in RT-Thread. These examples showcase how to use the Rust programming language for system programming in the RT-Thread real-time operating system.
## Directory Structure
```
example_usrapp/
├── SConscript # SCons build script
├── fs/ # File system operation examples
├── loadlib/ # Dynamic library loading examples
├── mutex/ # Mutex synchronization examples
├── param/ # Parameter handling examples
├── queue/ # Message queue examples
├── semaphore/ # Semaphore synchronization examples
└── thread/ # Thread management examples
```
## Build and Run
### Prerequisites
1. Ensure Rust support is enabled in RT-Thread configuration (`RT_USING_RUST`), and enable examples compilation (`RT_USING_RUST_EXAMPLES`) and application examples compilation (`RT_RUST_BUILD_APPLICATIONS`).
2. Install Rust toolchain and related dependencies
3. Configure the correct cross-compilation environment
### Build Steps
1. Execute in the RT-Thread project root directory:
```bash
scons -j$(nproc)
```
2. The build system will automatically:
- Detect enabled RT-Thread configurations
- Enable corresponding Rust features based on configuration
- Compile all example applications as static libraries
- Link to the final firmware image
### Running Examples
After RT-Thread system startup, you can run various examples through the command line:
```bash
# View all available examples
help
# Run thread example
rust_thread_demo
# Run file system example
rust_file_demo
# Other examples similarly...
```
## Technical Features
### Dependency Management
All example applications depend on the following core components:
- `rt-rust`: RT-Thread Rust binding library
- `macro_main`: Main function macro support
The `fs` example also depends on the logging component:
- `em_component_log`: Logging component
### Feature Configuration
- Support for conditional compilation features
- Automatic feature detection and enabling
- Modular functionality configuration
### Build System Integration
- Fully integrated with SCons build system
- Support for clean and incremental builds
- Automatic dependency management
## Development Guide
### Adding New Examples
1. Create a new directory under `example_usrapp/`
2. Add `Cargo.toml` configuration file
3. Implement example code in `src/lib.rs`
4. Use `#[macro_main_use]` macro to define entry point
### Example Template
```rust
#![no_std]
use macro_main::macro_main_use;
use rt_rust::param::Param;
use rt_rust::println;
#[macro_main_use(
name = "your_demo_name",
component = "Whether it's a component example",
app = "Whether it's a user application example",
cmd = true,
desc = "Your demo description."
)]
fn main(_param: Param) {
println!("Hello from your demo!");
// Your example code...
}
```
## Troubleshooting
### Common Issues
1. **Compilation failure**: Check if Rust toolchain is correctly installed
2. **Linking errors**: Confirm cross-compilation target configuration is correct
3. **Runtime errors**: Check stack size and memory configuration
### Debugging Suggestions
1. Use `println!` for basic debug output
2. Enable logging features to get detailed information
3. Check if RT-Thread configuration items are correctly enabled
@@ -0,0 +1,123 @@
# RT-Thread Rust 示例用户应用程序
这个目录包含了一系列用于演示 RT-Thread 中 Rust 编程功能的示例用户应用程序和组件。这些示例展示了如何在 RT-Thread 实时操作系统中使用 Rust 语言进行系统编程。
## 目录结构
```
example_usrapp/
├── SConscript # SCons 构建脚本
├── fs/ # 文件系统操作示例
├── loadlib/ # 动态库加载示例
├── mutex/ # 互斥锁同步示例
├── param/ # 参数处理示例
├── queue/ # 消息队列示例
├── semaphore/ # 信号量同步示例
└── thread/ # 线程管理示例
```
## 构建和运行
### 前提条件
1. 确保 RT-Thread 配置中启用了 Rust 支持 (`RT_USING_RUST`),并且开启 examples 编译(`RT_USING_RUST_EXAMPLES`)中的应用(`RT_RUST_BUILD_APPLICATIONS`)
2. 安装 Rust 工具链和相关依赖
3. 配置正确的交叉编译环境
### 构建步骤
1. 在 RT-Thread 项目根目录执行:
```bash
scons -j$(nproc)
```
2. 构建系统会自动:
- 检测启用的 RT-Thread 配置
- 根据配置启用相应的 Rust 特性
- 编译所有示例应用为静态库
- 链接到最终的固件镜像
### 运行示例
在 RT-Thread 系统启动后,可以通过命令行运行各个示例:
```bash
# 查看所有可用示例
help
# 运行线程示例
rust_thread_demo
# 运行文件系统示例
rust_file_demo
# 其他示例类似...
```
## 技术特性
### 依赖管理
所有示例应用都依赖以下核心组件:
- `rt-rust`: RT-Thread Rust 绑定库
- `rt-macro`: 主函数宏支持
`fs`示例还依赖日志组件:
- `em_component_log`: 日志组件
### 特性配置
- 支持条件编译特性
- 自动特性检测和启用
- 模块化的功能配置
### 构建系统集成
- 与 SCons 构建系统完全集成
- 支持清理和增量构建
- 自动依赖管理
## 开发指南
### 添加新示例
1. 在 `example_usrapp/` 下创建新目录
2. 添加 `Cargo.toml` 配置文件
3. 在 `src/lib.rs` 中实现示例代码
4. 使用 `#[macro_main_use]` 宏定义入口点
### 示例模板
```rust
#![no_std]
use macro_main::macro_main_use;
use rt_rust::param::Param;
use rt_rust::println;
#[macro_main_use(
name = "your_demo_name",
component = "是否为组件示例",
app = "是否为用户应用示例",
cmd = true,
desc = "Your demo description."
)]
fn main(_param: Param) {
println!("Hello from your demo!");
// 你的示例代码...
}
```
## 故障排除
### 常见问题
1. **编译失败**: 检查 Rust 工具链是否正确安装
2. **链接错误**: 确认交叉编译目标配置正确
3. **运行时错误**: 检查栈大小和内存配置
### 调试建议
1. 使用 `println!` 进行基本调试输出
2. 启用日志特性获取详细信息
3. 检查 RT-Thread 配置项是否正确启用
@@ -0,0 +1,226 @@
# Example Component - RT-Thread Rust Component Example
## Overview
`example_component` is a Rust component example based on RT-Thread, demonstrating how to implement, register, and manage Rust components in RT-Thread systems. This project adopts a unified component registration architecture that avoids component duplicate registration issues and supports conditional compilation based on RT-Thread configuration.
## Project Structure
```
example_component/
├── SConscript # SCons build script
├── component_registry/ # Unified component registry
│ ├── Cargo.toml # Registry configuration
│ └── src/
│ └── lib.rs # Registry implementation
├── log/ # Log component example
│ ├── Cargo.toml # Log component configuration
│ └── src/
│ ├── lib.rs # Log component implementation
│ └── logging.rs # Logging functionality module
└── tools/ # Build tools
├── build_component.py # Component build tool
└── feature_config_component.py # Feature configuration
```
## Core Features
### 1. Unified Component Registration Architecture
- **Avoid Duplicate Registration**: Unified management of all component registrations through `component_registry`, avoiding conflicts caused by multiple component duplicate registrations
- **Conditional Compilation Support**: Selectively compile and register components based on RT-Thread configuration
- **Modular Design**: Each component is implemented independently and managed uniformly through the registry
### 2. Feature Configuration System
- **Based on RT-Thread Configuration**: Feature enablement is entirely based on RT-Thread configuration items, requiring no additional configuration
- **Automatic Feature Mapping**: Build system automatically maps RT-Thread configuration to Rust features
- **Dependency Checking**: Automatically checks component dependencies to ensure build consistency
### 3. Build System Integration
- **SCons Integration**: Fully integrated with RT-Thread's SCons build system
- **Incremental Build**: Supports clean and incremental builds
- **Cross Compilation**: Supports cross-compilation for target architectures like RISC-V
## Component Details
### Component Registry
`component_registry` is the core of the entire architecture, responsible for unified management of all component registrations.
#### Main Functions
1. **Unified Entry Point**: Provides `rust_component_registry` as the unified registration entry for all components
2. **Conditional Compilation**: Only includes and registers corresponding components when respective features are enabled
3. **Avoid Conflicts**: Ensures each component is registered only once
### Log Component
The `log` component provides Rust-style logging functionality, including multiple log levels and command-line interface.
#### Main Functions
1. **Multi-level Logging**: Supports INFO, WARN, ERROR, DEBUG, TRACE and other log levels
2. **Command-line Interface**: Provides commands like `log_info`, `log_warn`, `log_error`
3. **Conditional Compilation**: Only compiles when `enable-log` feature is enabled
#### Usage Examples
```rust
// Using log macros in code
info!("This is an info log");
warn!("This is a warning log");
error!("This is an error log");
```
#### Command-line Usage
```bash
# Using in RT-Thread command line
msh> log_info # Print info log
msh> log_warn # Print warning log
msh> log_error # Print error log
```
## Feature Configuration
### Configuration Mapping
The mapping from RT-Thread configuration to Rust features is defined in `tools/feature_config_component.py`:
```python
CONFIG_COMPONENT_FEATURE_MAP = {
'RUST_LOG_COMPONENT': {
'feature': 'enable-log',
'dependency': 'em_component_log',
'description': 'Enable Rust log component integration'
}
}
```
### Enabling Components
To enable the log component, set in RT-Thread configuration:
```c
// Set through menuconfig
Enable Rust component support -> Auto-initialize Rust log component
```
## Development Guide
### Adding New Components
1. **Create Component Directory**
```bash
cargo new --lib example_component/new_component
cd example_component/new_component
```
2. **Create Cargo.toml**
```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 = []
```
3. **Implement Component Functionality**
```rust
// src/new.rs
// New component implementation code
// src/lib.rs
#![no_std]
// Export required libraries
```
4. **Update Feature Configuration**
```python
# Add to tools/feature_config_component.py
CONFIG_COMPONENT_FEATURE_MAP = {
# ... existing configuration ...
'RUST_NEW_COMPONENT': {
'feature': 'enable-new',
'dependency': 'em_component_new',
'description': 'Enable new component integration'
}
}
```
5. **Update Registry**
```toml
# Add to component_registry/Cargo.toml
[dependencies]
em_component_new = { path = "../new_component", optional = true }
[features]
enable-new = ["em_component_new", "em_component_new/enable-new"]
```
```rust
// Register in 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");
}
// ... other components ...
}
```
### Component Development Best Practices
1. **Use Conditional Compilation**: All functionality should be wrapped with `#[cfg(feature = "...")]`
2. **Avoid Direct Registration**: Don't use component registration macros directly in components, let `component_registry` manage uniformly
3. **Provide Command Interface**: Provide command-line interfaces for component functionality for easy testing and usage
4. **Complete Documentation**: Provide detailed documentation and usage examples for each component
## Troubleshooting
### Common Issues
1. **Compilation Failure**
- Check if Rust toolchain is correctly installed
- Confirm target architecture (e.g., `riscv64imac-unknown-none-elf`) is installed
- Check if dependency paths are correct
2. **Features Not Enabled**
- Confirm corresponding macro definitions are set in RT-Thread configuration
- Check mapping configuration in `feature_config_component.py`
- Review feature enablement information in build logs
3. **Linking Errors**
- Confirm all dependent components are correctly built
- Check dependency configuration in `Cargo.toml`
- Verify library file paths and names
## Dependency Relationships
```
RT-Thread Config
↓
Feature Mapping
↓
Rust Features
↓
Component Registry ← Individual Components
↓
RT-Thread System
```
@@ -0,0 +1,227 @@
# Example Component - RT-Thread Rust 组件示例
## 概述
`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 # 特性配置
```
## 核心特性
### 1. 统一组件注册架构
- **避免重复注册**: 通过 `component_registry` 统一管理所有组件的注册,避免多个组件重复注册导致的冲突
- **条件编译支持**: 根据 RT-Thread 配置选择性编译和注册组件
- **模块化设计**: 每个组件独立实现,通过注册程序统一管理
### 2. 特性配置系统
- **基于 RT-Thread 配置**: 特性启用完全基于 RT-Thread 的配置项,无需额外配置
- **自动特性映射**: 构建系统自动将 RT-Thread 配置映射为 Rust 特性
- **依赖检查**: 自动检查组件依赖关系,确保构建一致性
### 3. 构建系统集成
- **SCons 集成**: 与 RT-Thread 的 SCons 构建系统完全集成
- **增量构建**: 支持清理和增量构建
- **交叉编译**: 支持 RISC-V 等目标架构的交叉编译
## 组件详解
### Component Registry (组件注册程序)
`component_registry` 是整个架构的核心,负责统一管理所有组件的注册。
#### 主要功能
1. **统一入口点**: 提供 `rust_component_registry` 作为所有组件的统一注册入口
2. **条件编译**: 只在相应特性启用时才包含和注册对应组件
3. **避免冲突**: 确保每个组件只被注册一次
### Log Component (日志组件)
`log` 组件提供了 Rust 风格的日志功能,包括多个日志级别和命令行接口。
#### 主要功能
1. **多级别日志**: 支持 INFO、WARN、ERROR、DEBUG、TRACE 等日志级别
2. **命令行接口**: 提供 `log_info`、`log_warn`、`log_error` 等命令
3. **条件编译**: 只在 `enable-log` 特性启用时编译
#### 使用示例
```rust
// 在代码中使用日志宏
info!("这是一条信息日志");
warn!("这是一条警告日志");
error!("这是一条错误日志");
```
#### 命令行使用
```bash
# 在 RT-Thread 命令行中使用
msh> log_info # 打印信息日志
msh> log_warn # 打印警告日志
msh> log_error # 打印错误日志
```
## 特性配置
### 配置映射
在 `tools/feature_config_component.py` 中定义了 RT-Thread 配置到 Rust 特性的映射:
```python
CONFIG_COMPONENT_FEATURE_MAP = {
'RUST_LOG_COMPONENT': {
'feature': 'enable-log',
'dependency': 'em_component_log',
'description': 'Enable Rust log component integration'
}
}
```
### 启用组件
要启用日志组件,需要在 RT-Thread 配置中设置:
```c
// 通过 menuconfig 设置
Enable Rust component support -> Auto-initialize Rust log component
```
## 开发指南
### 添加新组件
1. **创建组件目录**
```bash
cargo new --lib example_component/new_component
cd example_component/new_component
```
2. **创建 Cargo.toml**
```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 = []
```
3. **实现组件功能**
```rust
// src/new.rs
// 新组件的实现代码
// src/lib.rs
#![no_std]
// 导出需要的库
```
4. **更新特性配置**
```python
# 在 tools/feature_config_component.py 中添加
CONFIG_COMPONENT_FEATURE_MAP = {
# ... 现有配置 ...
'RUST_NEW_COMPONENT': {
'feature': 'enable-new',
'dependency': 'em_component_new',
'description': 'Enable new component integration'
}
}
```
5. **更新注册程序**
```toml
# 在 component_registry/Cargo.toml 中添加
[dependencies]
em_component_new = { path = "../new_component", optional = true }
[features]
enable-new = ["em_component_new", "em_component_new/enable-new"]
```
```rust
// 在 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");
}
// ... 其他组件 ...
}
```
### 组件开发最佳实践
1. **使用条件编译**: 所有功能都应该用 `#[cfg(feature = "...")]` 包装
2. **避免直接注册**: 不要在组件中直接使用组件注册宏,让 `component_registry` 统一管理
3. **提供命令接口**: 为组件功能提供命令行接口,方便测试和使用
4. **文档完整**: 为每个组件提供详细的文档和使用示例
## 故障排除
### 常见问题
1. **编译失败**
- 检查 Rust 工具链是否正确安装
- 确认目标架构 (如 `riscv64imac-unknown-none-elf`) 已安装
- 检查依赖路径是否正确
2. **特性未启用**
- 确认 RT-Thread 配置中已设置相应的宏定义
- 检查 `feature_config_component.py` 中的映射配置
- 查看构建日志中的特性启用信息
3. **链接错误**
- 确认所有依赖组件都已正确构建
- 检查 `Cargo.toml` 中的依赖配置
- 验证库文件路径和名称
## 依赖关系
```
RT-Thread Config
↓
Feature Mapping
↓
Rust Features
↓
Component Registry ← Individual Components
↓
RT-Thread System
```
+47
View File
@@ -0,0 +1,47 @@
# Writing a Rust Dynamic Library Usable by RT-Thread
1. Set up the project
Create a new `cargo` project as usual. There are some flags to tell `cargo` to generate a system library instead of a regular Rust target.
```toml
[lib]
name = "your_crate"
crate-type = ["cdylib"] # generate a dynamic library
# crate-type = ["staticlib"] # generate a static library
```
Add the following to `config.toml` to specify the target platform:
```toml
[build]
target = "your_target"
```
2. Enable RT-Thread dynamic module loading
To load dynamic modules in RT-Thread, enable it in `Kconfig`:
```
RT-Thread Components → C/C++ and POSIX layer
→ POSIX (Portable Operating System Interface) layer
→ Enable dynamic module APIs, dlopen()/dlsym()/dlclose() etc
```
3. Enable the filesystem
To place dynamic modules into RT-Thread, enable a filesystem in `Kconfig`:
```
RT-Thread online packages → system packages
→ lwext4: an excellent choice of ext2/3/4 filesystem for microcontrollers.
```
## Using the rust library
Add `rt_rust` dependency in `Cargo.toml`:
```toml
[dependencies]
rt_rust = { path = "PATH/TO/rust/rt-rust" }
```
Currently the macro-main library is not supported because it causes entry detection issues.
## References
- [The Embedded Rust Book](https://xxchang.github.io/book/interoperability/rust-with-c.html#extern-c)
@@ -0,0 +1,47 @@
# 编写RT-Thread可以使用的rust动态库
1. 设置项目
像往常一样创建一个新的`cargo`项目。有一些标志可以告诉`cargo`去生成一个系统库,而不是常规的rust目标文件。
```toml
[lib]
name = "your_crate"
crate-type = ["cdylib"] # 生成动态链接库
# crate-type = ["staticlib"] # 生成静态链接库
```
在 `config.toml` 中添加以下内容,以指定目标平台
```toml
[build]
target = "your_target
```
2. 开启 RT-Thread 加载动态模块功能
为了能够在 RT-Thread 中加载动态模块,需要在 `Kconfig` 中开启
```
RT-Thread Components → C/C++ and POSIX layer
→ POSIX (Portable Operating System Interface) layer
→ Enable dynamic module APIs, dlopen()/dlsym()/dlclose() etc
```
3. 打开文件系统
为了能够将动态模块放入 RT-Thread 中,需要在 `Kconfig` 中开启文件系统。
```
RT-Thread online packages → system packages
→ lwext4: an excellent choice of ext2/3/4 filesystem for microcontrollers.
```
## rust库的使用
在 `Cargo.toml` 中添加 `rt_rust` 依赖
```toml
[dependencies]
rt_rust = { path = "PATH/TO/rust/rt-rust" }
```
目前不支持macro-main库的使用,因为它会导致入口识别错误。
## 参考资料
- [The Embedded Rust Book](https://xxchang.github.io/book/interoperability/rust-with-c.html#extern-c)
@@ -0,0 +1,103 @@
# rt_macros Usage Guide
rt_macros is a collection of Rust procedural macros for RT-Thread. It helps export Rust functions as system entry points, initialization entries, or shell commands in a `no_std` environment, so they integrate cleanly with RT-Thread’s startup and command mechanisms.
## Background and Goals
In `no_std` mode, the traditional `main` function is not directly available. rt_macros generates C-ABI-compatible wrapper entries and the required link-section items so RT-Thread can discover and invoke the corresponding Rust logic during startup or shell command scanning.
## Provided Macros (aligned with RT-Thread conventions)
- `rt_thread_main!`: Marks the Rust main-thread entry.
- Function signature: `fn()` (no parameters, no return value).
- Constraints: no `const`, `unsafe`, `async`, varargs; no explicit ABI; no generics; default visibility (non-`pub`).
- Purpose: exports an entry that RT-Thread can recognize and call as the main thread.
- `rt_component_export!`: Exports a component initialization entry.
- Function signature: `fn()`.
- Same constraints; optional parameter: `name = "..."` (used to generate internal symbol names).
- Link section: places the function pointer into `.rti_fn.4`, executed during the component initialization phase.
- `rt_app_export!`: Exports an application initialization entry.
- Function signature: `fn()`.
- Same constraints; optional parameter: `name = "..."`.
- Link section: places the function pointer into `.rti_fn.6`, executed during the application initialization phase.
- `msh_cmd_export!`: Exports an RT-Thread shell command.
- Function signature: `fn(args: vec::IntoIter<rt_rust::param::ParamItem>)`.
- Attributes: `name` (required, command name), `desc` (optional, command description).
- Link sections and data:
- Generates a command descriptor struct placed into `FSymTab`.
- Command name and description are `\0`-terminated byte arrays placed into `.rodata.name`.
- Invocation wrapper: generates an `extern "C"` wrapper `(argc, argv)`, converts `argv` to `Vec<ParamItem>`, and calls the original Rust command function.
## Link Sections and Startup Flow
- Component init entries: `.rti_fn.4`
- Application init entries: `.rti_fn.6`
- Shell command table: `FSymTab`
- Shell name/description strings: `.rodata.name`
During startup or shell scanning, RT-Thread traverses these sections to register or invoke the corresponding Rust logic.
## Usage Examples
### Main-thread entry
```rust
use rt_macros::rt_thread_main;
#[rt_thread_main]
fn main() {
// Main thread logic here
}
```
### Component export
```rust
use rt_macros::rt_component_export;
#[rt_component_export(name = "rust_component_registry")]
fn my_component_init() {
// Component init logic
}
```
### Application export
```rust
use rt_macros::rt_app_export;
#[rt_app_export(name = "rust_app_example")]
fn my_app_init() {
// Application init logic
}
```
### Shell command export
```rust
use rt_macros::msh_cmd_export;
#[msh_cmd_export(name = "hello", desc = "Say hello")]
fn hello_cmd(args: vec::IntoIter<rt_rust::param::ParamItem>) {
// Handle args and print output, etc.
}
```
## Interacting with C Code
When calling exported Rust entries from C, declare the prototype and use `extern "C"` for the calling convention, for example:
```c
extern "C" void rust_function_name(void);
```
The command export macro generates a wrapper with `(argc, argv)`; RT-Thread’s command system calls this wrapper and passes the arguments to the original Rust function.
## Common Issues and Diagnostics
- Compile-time errors: the macros produce explicit diagnostics if the function signature does not match (e.g., must be `fn()` or a specific parameter shape). Adjust the function to meet the requirements above.
- Visibility requirement: keep the entry function at default (non-`pub`) visibility to satisfy macro constraints.
- `alloc` dependency: the shell command macro uses `alloc::vec::Vec`, ensure an allocator is available at runtime (RT-Thread usually provides one).
## References
- [RUST support for rt-thread](https://github.com/rust-for-rtthread/rtt_rust)
@@ -0,0 +1,103 @@
# rt_macros 使用说明
rt_macros 是为 RT-Thread 提供的 Rust 过程宏集合,帮助在 `no_std` 环境下将 Rust 函数以约定的方式导出为系统入口、初始化段或 Shell 命令,从而与 RT-Thread 的启动与命令机制顺畅对接。
## 背景与目标
在 `no_std` 模式下不能直接使用传统的 `main` 函数。rt_macros 通过过程宏生成符合 C ABI 的包装入口,以及必要的链接段条目,让 RT-Thread 能在启动期或命令扫描阶段发现并调用对应的 Rust 逻辑。
## 提供的宏(参考RT-Thread的声明)
- `rt_thread_main!`:标记 Rust 主线程入口。
- 函数签名:`fn()`(无参数、无返回值)。
- 约束:不支持 `const`、`unsafe`、`async`、变参;不可使用显式 ABI;不可含泛型;函数可见性需为默认(非 `pub`)。
- 作用:导出可由 RT-Thread 识别和调用的主线程入口。
- `rt_component_export!`:导出为组件初始化入口。
- 函数签名:`fn()`。
- 约束同上;可选参数:`name = "..."`(用于生成内部符号名称)。
- 链接段:将函数指针落入 `.rti_fn.4` 段,供组件初始化阶段调用。
- `rt_app_export!`:导出为应用初始化入口。
- 函数签名:`fn()`。
- 约束同上;可选参数:`name = "..."`。
- 链接段:将函数指针落入 `.rti_fn.6` 段,供应用初始化阶段调用。
- `msh_cmd_export!`:导出为 RT-Thread Shell 命令。
- 函数签名:`fn(args: vec::IntoIter<rt_rust::param::ParamItem>)`。
- 属性参数:`name`(必填,命令名),`desc`(可选,命令描述)。
- 链接段与数据:
- 生成命令描述结构体并落入 `FSymTab` 段。
- 命令名与描述以以 `\0` 结尾的字节数组形式落入 `.rodata.name` 段。
- 调用封装:生成 `extern "C"` 包装函数 `(argc, argv)`,把 `argv` 转换为 `Vec<ParamItem>`,再调用原始 Rust 命令函数。
## 链接段与启动流程
- 组件初始化入口:`.rti_fn.4`
- 应用初始化入口:`.rti_fn.6`
- Shell 命令表:`FSymTab`
- Shell 名称/描述字符串:`.rodata.name`
RT-Thread 在启动或命令表扫描时,会遍历对应段的条目并完成调用或注册,从而将 Rust 编写的逻辑纳入系统。
## 使用示例
### 主线程入口
```rust
use rt_macros::rt_thread_main;
#[rt_thread_main]
fn main() {
// 在此编写主线程逻辑
}
```
### 组件导出
```rust
use rt_macros::rt_component_export;
#[rt_component_export(name = "rust_component_registry")]
fn my_component_init() {
// 组件初始化逻辑
}
```
### 应用导出
```rust
use rt_macros::rt_app_export;
#[rt_app_export(name = "rust_app_example")]
fn my_app_init() {
// 应用初始化逻辑
}
```
### Shell 命令导出
```rust
use rt_macros::msh_cmd_export;
#[msh_cmd_export(name = "hello", desc = "Say hello")]
fn hello_cmd(args: vec::IntoIter<rt_rust::param::ParamItem>) {
// 命令处理逻辑,例如解析 args 并打印输出
}
```
## 与 C 代码的交互
当需要从 C 调用导出的 Rust 入口时,应在 C 侧声明原型并使用 `extern "C"` 指定调用约定,例如:
```c
extern "C" void rust_function_name(void);
```
命令导出宏会生成 `(argc, argv)` 形式的包装函数,RT-Thread 的命令系统会调用该包装函数并将参数传递给原始 Rust 函数。
## 常见问题与诊断
- 编译期报错:宏会在函数签名不符合约束时给出明确的错误信息(例如必须为 `fn()` 或必须为特定的参数形式)。请按上文的签名要求调整。
- 可见性要求:入口函数应保持默认(非 `pub`),以满足宏的约束。
- `alloc` 依赖:Shell 命令宏内部使用 `alloc::vec::Vec`,需确保运行环境提供分配器(RT-Thread 通常可满足)。
## 参考实现
- [RUST support for rt-thread](https://github.com/rust-for-rtthread/rtt_rust)