想帶大家認識 Flutter Blue 套件 怎麼使用。
了解裡面的參數。
藍牙中具體有些哪些:藍牙名字(name)藍芽裝置(device)藍牙信號強度(riss)藍牙服務(service) 藍牙服務下麵又有小服務。
可以去監聽 Stream = FlutterBlue.instance.state
BluetoothState
可以去監聽 Stream = FlutterBlue.instance.scanResults
當搜尋到 ScanResult 拿到裡面的 device 後。
stream: device.services,
BluetoothService
可以每 2 秒監聽 Devices 這樣子。
Stream.periodic(Duration(seconds: 2)).asyncMap((_) => FlutterBlue.instance.connectedDevices),
FlutterBlue flutterBlue = FlutterBlue.instance;
// Start scanning
flutterBlue.startScan(timeout: Duration(seconds: 4));
// Listen to scan results
var subscription = flutterBlue.scanResults.listen((results) {
// do something with scan results
for (ScanResult r in results) {
print('${r.device.name} found! rssi: ${r.rssi}');
}
});
// Stop scanning
flutterBlue.stopScan();
// Connect to the device
await device.connect();
// Disconnect from device
device.disconnect();
List<BluetoothService> services = await device.discoverServices();
services.forEach((service) {
// do something with service
});
https://pub.dev/packages/flutter_blue#read-and-write-characteristics
var characteristics = service.characteristics;
for(BluetoothCharacteristic c in characteristics) {
List<int> value = await c.read();
print(value);
}
// Writes to a characteristic
await c.write([0x12, 0x34])
https://pub.dev/packages/flutter_blue#read-and-write-descriptors
// Reads all descriptors
var descriptors = characteristic.descriptors;
for(BluetoothDescriptor d in descriptors) {
List<int> value = await d.read();
print(value);
}
// Writes to a descriptor
await d.write([0x12, 0x34])
https://pub.dev/packages/flutter_blue#set-notifications-and-listen-to-changes
await characteristic.setNotifyValue(true);
characteristic.value.listen((value) {
// do something with new value
});
https://pub.dev/packages/flutter_blue#read-the-mtu-and-request-larger-size
final mtu = await device.mtu.first;
await device.requestMtu(512);