FlutterBlue

FlutterBlue 是 Flutter 的蓝牙插件,一个帮助开发者为 iOS 和 Android 构建现代应用的新的移动 SDK。

跨平台蓝牙 LE

FlutterBlue 旨在提供 iOS 和 Android 平台上的最佳功能。

通过 FlutterBlue 实例,您可以扫描并连接到附近的设备(BluetoothDevice)。连接到设备后,BluetoothDevice 对象可以发现服务(BluetoothService)、特性(BluetoothCharacteristic)和描述符(BluetoothDescriptor)。然后,BluetoothDevice 对象用于直接与特性和描述符进行交互。

用法

获取实例

FlutterBlue flutterBlue = FlutterBlue.instance;

扫描设备

/// Start scanning
var scanSubscription = flutterBlue.scan().listen((scanResult) {
    // do something with scan result
});

/// Stop scanning
scanSubscription.cancel();

连接设备

/// Create a connection to the device
var deviceConnection = flutterBlue.connect(device).listen((s) {
    if(s == BluetoothDeviceState.connected) {
        // device is connected, do something
    }
});

/// Disconnect from device
deviceConnection.cancel();

发现服务

List<BluetoothService> services = await device.discoverServices();
services.forEach((service) {
    // do something with service
});

读写特性

// Reads all characteristics
var characteristics = service.characteristics;
for(BluetoothCharacteristic c in characteristics) {
    List<int> value = await device.readCharacteristic(c);
    print(value);
}

// Writes to a characteristic
await device.writeCharacteristic(c, [0x12, 0x34])

读写描述符

// Reads all descriptors
var descriptors = characteristic.descriptors;
for(BluetoothDescriptor d in descriptors) {
    List<int> value = await device.readDescriptor(d);
    print(value);
}

// Writes to a descriptor
await device.writeDescriptor(d, [0x12, 0x34])

设置通知

await device.setNotifyValue(characteristic, true);
device.onValueChanged(characteristic).listen((value) {
    // do something with new value
});

参考

FlutterBlue API

Android iOS 描述
scan :white_check_mark :white_check_mark 开始扫描低功耗蓝牙设备。
connect :white_check_mark :white_check_mark 与蓝牙设备建立连接。
state :white_check_mark :white_check_mark 获取蓝牙适配器的当前状态。
onStateChanged :white_check_mark :white_check_mark 蓝牙适配器状态变化的流。

BluetoothDevice API

Android iOS 描述
discoverServices :white_check_mark :white_check_mark 发现远程设备提供的服务及其特性和描述符。
services :white_check_mark :white_check_mark 获取服务列表。需要 discoverServices() 已完成。
readCharacteristic :white_check_mark :white_check_mark 检索指定特性的值。
readDescriptor :white_check_mark :white_check_mark 检索指定描述符的值。
writeCharacteristic :white_check_mark :white_check_mark 写入特性的值。
writeDescriptor :white_check_mark :white_check_mark 写入描述符的值。
setNotifyValue :white_check_mark :white_check_mark 为指定的特性设置通知或指示。
onValueChanged :white_check_mark :white_check_mark 当特性的值发生变化时通知。
state :white_check_mark :white_check_mark 获取蓝牙设备的当前状态。
onStateChanged :white_check_mark :white_check_mark 通知蓝牙设备的状态变化。

故障排除

扫描服务 UUIDs 没有返回任何结果

确保设备正在广播它支持的服务 UUIDs。这可以在广告数据包中的 **16 位 UUID 完整列表** 或 **128 位 UUID 完整列表** 中找到。
数据包中的 UUID 16 位完整列表UUID 128 位完整列表

GitHub

https://github.com/pauldemarco/flutter_blue