flutter_ttc_ble 0.0.4
flutter_ttc_ble: ^0.0.4 copied to clipboard
A BLE(Bluetooth Low Energy) Flutter plugin for Android and iOS.
flutter_ttc_ble #
A BLE(Bluetooth Low Energy) Flutter plugin for Android and iOS.
Getting Started #
准备 #
- Android版本高于5.0(包含),Android扫描蓝牙需要用到位置权限并打开位置服务,位置权限可借助其他库,如 permission_handler
- iOS版本高于10.0,在ios的Info.plist增加 Privacy - Bluetooth Always Usage Description
扫描设备 #
- 插件初始化
FlutterTtcBle.init();
- 扫描设备
//开启扫描
FlutterTtcBle.startLeScan((device) {
//处理数据
});
//停止扫描
FlutterTtcBle.stopLeScan();
- 连接设备 / 断开连接
//连接设备
FlutterTtcBle.connect(deviceId: device.deviceId);
//断开连接
FlutterTtcBle.disconnect(device.deviceId);
- 发送数据
//与蓝牙设备通信的UUID
const UUID_SERVICE = '00001000-0000-1000-8000-00805f9b34fb';
const UUID_WRITE = '00001001-0000-1000-8000-00805f9b34fb';
const UUID_NOTIFY = '00001002-0000-1000-8000-00805f9b34fb';
FlutterTtcBle.writeCharacteristic(
deviceId: deviceId,
serviceUuid: UUID_SERVICE,
characteristicUuid: UUID_WRITE,
value: data,
writeType: CharacteristicWriteType.writeNoResponse);
- 接收数据
//通知事件中获取数据
BleCallback bleCallback = (message) {
if (message is Map<dynamic, dynamic>) {
if (message.containsKey('event')) {
switch (message['event']) {
case BLEEvent.CONNECTED: //与设备建立连接
//开启数据通知,这样才能实时接收设备端的数据
FlutterTtcBle.setCharacteristicNotification(
deviceId: message['deviceId'],
serviceUuid: UUID_SERVICE,
characteristicUuid: UUID_NOTIFY,
enable: true);
break;
case BLEEvent.DATA_AVAILABLE: //收到数据
Uint8List data = (message['value'] as Uint8List);
break;
}
}
}
};