Rust蓝牙低功耗开发库bluenrg的使用,bluenrg提供高效蓝牙协议栈与硬件交互功能
Rust蓝牙低功耗开发库bluenrg的使用
BlueNRG是一个为STMicro的BlueNRG系列蓝牙射频模块提供特定厂商蓝牙HCI接口的Rust库。它扩展了bluetooth-hci库,添加了厂商特定的命令、事件和相关错误处理。
支持版本
该库支持两个版本:
- 旧版BlueNRG HCI
- 新版BlueNRG-MS HCI
默认情况下,库实现的是BlueNRG-MS版本。
安装
在项目目录中运行以下Cargo命令:
cargo add bluenrg
或者在Cargo.toml中添加:
bluenrg = "0.1.0"
示例代码
以下是一个使用bluenrg库进行蓝牙低功耗开发的完整示例:
use bluenrg::{
BlueNRG,
BlueNRGError,
commands::*,
events::*,
};
use bluetooth_hci::HostController;
fn main() -> Result<(), BlueNRGError> {
// 初始化BlueNRG设备
let mut bluenrg = BlueNRG::new()?;
// 重置设备
bluenrg.send_command(&Reset {})?;
// 设置设备名称
bluenrg.send_command(&SetLocalName {
name: "MyDevice".into(),
})?;
// 设置广播数据
bluenrg.send_command(&SetAdvertisingData {
data: vec![
0x02, // 长度
0x01, // 标志类型
0x06, // 通用可发现标志
],
})?;
// 启用广播
bluenrg.send_command(&SetAdvertisingParameters {
interval_min: 0x0800, // 最小广播间隔
interval_max: 0x0800, // 最大广播间隔
adv_type: AdvertisingType::ConnectableUndirected,
own_address_type: OwnAddressType::Public,
direct_address_type: PeerAddressType::Public,
direct_address: [0; 6],
channel_map: 0x7, // 使用所有3个广播信道
filter_policy: AdvertisingFilterPolicy::AllowAll,
})?;
bluenrg.send_command(&SetAdvertiseEnable { enable: true })?;
// 处理事件
loop {
if let Some(event) = bluenrg.read_event()? {
match event {
Event::DisconnectionComplete(evt) => {
println!("设备断开连接: {:?}", evt);
}
Event::ConnectionComplete(evt) => {
println!("新连接: {:?}", evt);
}
_ => {} // 忽略其他事件
}
}
}
}
代码说明
- 首先导入所需模块和类型
- 初始化BlueNRG设备
- 发送标准HCI命令(如Reset)和厂商特定命令
- 配置设备名称、广播数据和广播参数
- 启用广播
- 在主循环中处理蓝牙事件
这个示例展示了如何:
- 初始化BlueNRG设备
- 配置蓝牙广播参数
- 处理连接和断开事件
注意事项
- 该库目前(2018年4月)仍在积极开发中,文档可能不够完善
- 使用时需要根据实际硬件调整参数
- 错误处理是必须的,因为蓝牙操作可能会失败
该库适用于嵌入式开发和硬件支持场景,并且支持无标准库(no-std)环境。
1 回复
Rust蓝牙低功耗开发库bluenrg使用指南
简介
bluenrg是一个Rust库,用于与STMicroelectronics的BlueNRG系列蓝牙低功耗(BLE)芯片进行交互。它提供了高效的蓝牙协议栈实现和硬件抽象层,使开发者能够轻松构建BLE应用。
主要特性
- 支持BlueNRG-MS和BlueNRG-LP系列芯片
- 提供完整的BLE协议栈实现
- 异步/同步API支持
- 硬件抽象层简化设备交互
- 符合Rust安全编程模型
安装
在Cargo.toml中添加依赖:
[dependencies]
bluenrg = "0.3"
完整示例代码
下面是一个完整的BLE外设示例,包含设备初始化、广播设置、GATT服务和事件处理:
use bluenrg::{BlueNRG, SpiInterface};
use bluenrg::gap::{GapRole, GapParameters, AdvertisingData, AdvertisingParameters, AdvertisingType};
use bluenrg::gatt::{Attribute, AttributePermissions, AttributeProperties, Service};
use bluenrg::events::Event;
use embedded_hal::spi::SpiDevice;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 初始化SPI接口
let spi = ...; // 替换为你的SPI设备实例
// 创建BlueNRG实例
let interface = SpiInterface::new(spi);
let mut bluenrg = BlueNRG::new(interface)?;
// 重置设备
bluenrg.reset()?;
// 配置GAP参数
let gap_params = GapParameters {
device_name: Some("RustBLE"),
appearance: 0x1234,
role: GapRole::Peripheral,
..Default::default()
};
bluenrg.set_gap_parameters(&gap_params)?;
// 设置广播数据
let adv_data = AdvertisingData {
flags: Some(0x06),
complete_local_name: Some("RustDevice"),
service_uuids_16bit: Some(&[0x180F]), // 仅包含电池服务
..Default::default()
};
// 设置广播参数
let adv_params = AdvertisingParameters {
interval_min: 160, // 100ms
interval_max: 160,
adv_type: AdvertisingType::ConnectableUndirected,
..Default::default()
};
bluenrg.set_advertising_data(&adv_data)?;
bluenrg.set_advertising_parameters(&adv_params)?;
// 添加GATT服务
let battery_service = Service {
uuid: 0x180F, // 电池服务
attributes: &[
Attribute {
uuid: 0x2A19, // 电池等级特性
properties: AttributeProperties::READ | AttributeProperties::NOTIFY,
permissions: AttributePermissions::NONE,
value: &[100], // 初始值100%
}
],
};
bluenrg.add_service(&battery_service)?;
// 开始广播
bluenrg.start_advertising()?;
// 主事件循环
loop {
if let Some(event) = bluenrg.get_event()? {
match event {
Event::GapConnected(conn_handle, peer_addr, _) => {
println!("设备已连接: {:?}, 连接句柄: {}", peer_addr, conn_handle);
}
Event::GapDisconnected(conn_handle, _) => {
println!("设备断开连接, 句柄: {}", conn_handle);
bluenrg.start_advertising()?; // 重新开始广播
}
Event::GattAttributeModified(conn_handle, attr_handle, data) => {
println!("属性修改: 连接={}, 属性={}, 值={:?}",
conn_handle, attr_handle, data);
}
_ => {} // 忽略其他事件
}
}
}
}
注意事项
- 确保SPI接口配置正确,BlueNRG芯片需要特定的SPI模式
- 初始化后需要等待设备就绪(通常需要几毫秒)
- 广播和连接参数需要符合BLE规范
- 事件处理应尽可能快速,避免丢失事件
通过bluenrg库,开发者可以充分利用Rust的安全性和高性能特性来构建可靠的BLE应用程序。