bluetooth_low_energy 蓝牙插件使用说明
文档介绍了在Flutter使用bluetooth_low_energy插件监听蓝牙状态,扫描蓝牙设备,连接蓝牙设备,订阅蓝牙消息等功能。
1. 引入插件
dependencies:
bluetooth_low_energy: ^6.0.2
2.初始化中心设备
import 'package:bluetooth_low_energy/bluetooth_low_energy.dart';
// 中心设备实例
final CentralManager centralManager = CentralManager();
// 符合特点的蓝牙设备
String deviceNameReg = "";
// 自定义蓝牙设备列表
List<CustomBlutooth> devices = [];
/// 设备扫描
discovered = centralManager.discovered.listen((DiscoveredEventArgs event){
final Advertisement advertisement = event.advertisement;
String name = advertisement.name ?? "";
// 使用name查找符合条件的设备
if(name.isNotEmpty && name.toUpperCase().startsWith(deviceNameReg)){
// 添加进 devices
}
});
/// 监听设备蓝牙状态
stateChanged = centralManager.stateChanged.listen((BluetoothLowEnergyStateChangedEventArgs event){
if(BluetoothLowEnergyState.poweredOn == event.state){
// 蓝牙状态正常,开始扫描
}else{
// 清空 devices
}
});
/// 连接状态回调
connectionStateChanged = centralManager.connectionStateChanged.listen((PeripheralConnectionStateChangedEventArgs event){
CustomBlutooth? select = devices.firstWhereOrNull((device)=>device.peripheral == event.peripheral);
if(select != null){
if(event.state == ConnectionState.connected){
// 连接成功、更改连接状态、订阅通知
}else{
// 标记设备连接状态
}
}
});
/// 订阅消息回调
characteristicNotified = centralManager.characteristicNotified.listen((GATTCharacteristicNotifiedEventArgs event){
final Uint8List text = event.value;
CustomBlutooth? select = devices.firstWhereOrNull((device)=>device.peripheral == event.peripheral);
if(select != null){
// 转码接收信息
int? value = int.tryParse(
String.fromCharCodes(text.toList()).replaceAll("\r\n", "")
);
// 添加蓝牙数据
if(value is int){
select.setValue(value);
}
}
});
3.启动程序
bool state = await centralManager.authorize();
if(state){
if(centralManager.state != BluetoothLowEnergyState.poweredOn){
// 蓝牙未打开
}else{
// 蓝牙正常 开始扫描
centralManager.startDiscovery();
}
}else{
// 没有蓝牙权限
}
4.连接蓝牙
// 一般定义在 CustomBlutooth 中,内部维护连接状态等蓝牙数据
// 查看是否在已连接
List<Peripheral> list = await centralManager.retrieveConnectedPeripherals();
if(list.firstWhereOrNull((d)=>d == peripheral) != null){
// 已在连接中
}else{
// 连接断开 -再次连接
// Timer - 定义超时处理
try{
await centralManager.connect(peripheral);
} on PlatformException catch(error){
// 连接出错
}
}
5.订阅蓝牙消息
// 蓝牙设备连接成功后,订阅消息
// 订阅特征 -这里连接满足deviceNameReg特征的设备
const Map BLE_CONFIG = {
serviceId: "XXXX",
characteristicId: "XXXX"
};
List<GATTService> services = await centralManager.discoverGATT(peripheral);
GATTService? service;
GATTCharacteristic? characteristic;
for (var element in services) {
if(element.uuid == UUID.fromString(BLE_CONFIG["serviceId"])){
service = element;
characteristic = element
.characteristics
.toList()
.firstWhereOrNull((tag)=>tag.uuid == UUID.fromString(BLE_CONFIG["characteristicId"]));
}
}
if(service != null && characteristic != null){
// 订阅成功后就能接收到消息了
centralManager.setCharacteristicNotifyState(peripheral, characteristic, state: true);
}