介紹
FlutterBlue是一款flutter對藍牙插件,旨在提供來自兩個平臺(iOS和Android)的最大功能。 使用FlutterBlue實例,您能夠掃描並鏈接到附近的設備(BluetoothDevice)。一旦鏈接到設備,BluetoothDevice對象就能夠發現服務(BluetoothService),特徵(BluetoothCharacteristic)和描述符(BluetoothDescriptor)。而後,BluetoothDevice對象用於直接與特徵和描述符交互。markdown
基本用法
生成實例
FlutterBlue flutterBlue = FlutterBlue.instance;
複製代碼
掃描設備操做
var scanSubscription = flutterBlue.scan().listen((scanResult) {
device = scanResult.device;
print('${device.name} found! rssi: ${scanResult.rssi}');
});
scanSubscription.cancel();
複製代碼
鏈接設備
await device.connect();
device.disconnect();
複製代碼
搜索設備
List<BluetoothService> services = await device.discoverServices();
services.forEach((service) {
});
複製代碼
讀寫特徵值characteristics
相信有些小夥伴不太瞭解characteristics是幹什麼用的,BLE的基本關係是:
一個藍牙4.0的終端device能夠包含多個Service,
一個Service能夠包含多個Characteristic,一個Characteristic包含一個Value和多個Descriptor,
一個Descriptor包含一個Value。
簡單的說藍牙設備正是經過Characteristic來進行設備間的交互的(如讀、寫、訂閱等操做),
詳細介紹能夠參考 [https://www.jianshu.com/p/d991f0fdec63]
複製代碼
var characteristics = service.characteristics;
for(BluetoothCharacteristic c in characteristics) {
List<int> value = await c.read();
print(value);
}
await c.write([0x12, 0x34])
複製代碼
讀寫描述符descriptors
var descriptors = characteristic.descriptors;
for(BluetoothDescriptor d in descriptors) {
List<int> value = await d.read();
print(value);
}
await d.write([0x12, 0x34])
複製代碼
設置通知和監聽特徵值characterisic的value變化
await characteristic.setNotifyValue(true);
characteristic.value.listen((value) {
});
複製代碼
經常使用API
FlutterBlue API
|
Android |
iOS |
Description |
scan |
:white_check_mark: |
:white_check_mark: |
開始藍牙低功耗設備的掃描 |
state |
:white_check_mark: |
:white_check_mark: |
獲取藍牙適配器的當前狀態 |
onStateChanged |
:white_check_mark: |
:white_check_mark: |
藍牙適配器的狀態變化流 |
BluetoothDevice API
|
Android |
iOS |
Description |
connect |
:white_check_mark: |
:white_check_mark: |
創建設備鏈接 |
disconnect |
:white_check_mark: |
:white_check_mark: |
取消一個激活active的或者掛起pending的設備device鏈接 |
discoverServices |
:white_check_mark: |
:white_check_mark: |
經過提供的遠程設備device儘量的搜索服務services,及它的特徵值characteristics和描述符descriptors |
services |
:white_check_mark: |
:white_check_mark: |
獲取設備device列表,要求discoverServices()已經執行完成. |
state |
:white_check_mark: |
:white_check_mark: |
獲取設備的當前狀態. |
onStateChanged |
:white_check_mark: |
:white_check_mark: |
監聽設備狀態改變的回調 |
BluetoothCharacteristic API
|
Android |
iOS |
Description |
read |
:white_check_mark: |
:white_check_mark: |
檢索特徵值characteristic的value |
write |
:white_check_mark: |
:white_check_mark: |
寫入修改特徵值characteristic的value. |
setNotifyValue |
:white_check_mark: |
:white_check_mark: |
設置特徵值characteristic的通知和指示. |
value |
:white_check_mark: |
:white_check_mark: |
當發生改變時,特徵值characteristic的value流. |
BluetoothDescriptor API
|
Android |
iOS |
Description |
read |
:white_check_mark: |
:white_check_mark: |
檢索描述符descriptor的value. |
write |
:white_check_mark: |
:white_check_mark: |
寫入修改描述符descriptor的value. |