264 lines
10 KiB
Dart
264 lines
10 KiB
Dart
|
|
|
|||
|
|
import 'package:flutter/material.dart';
|
|||
|
|
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
|
|||
|
|
import 'package:star_lock/blue/sender_manage.dart';
|
|||
|
|
|
|||
|
|
import '../app_settings/app_settings.dart';
|
|||
|
|
import 'io_tool/io_tool.dart';
|
|||
|
|
import 'io_tool/manager_event_bus.dart';
|
|||
|
|
|
|||
|
|
typedef ScanResultCallBack = void Function(List<DiscoveredDevice> devices);
|
|||
|
|
|
|||
|
|
class BlueManage{
|
|||
|
|
FlutterReactiveBle? _flutterReactiveBle;
|
|||
|
|
List<DiscoveredDevice> _scanDevices = [];
|
|||
|
|
QualifiedCharacteristic? qualifiedCharacteristic;
|
|||
|
|
DiscoveredCharacteristic? getDiscoveredCharacteristic;
|
|||
|
|
Uuid serviceId = Uuid.parse('0000FFF0-0000-1000-8000-00805F9B34FB');
|
|||
|
|
final int _limitLen = 20;
|
|||
|
|
final int _sleepTimes = AppPlatform.isAndroid ? 6 : 0;
|
|||
|
|
|
|||
|
|
static BlueManage? _manager;
|
|||
|
|
BlueManage._init();
|
|||
|
|
|
|||
|
|
static BlueManage? shareManager(){
|
|||
|
|
_manager ??= BlueManage._init();
|
|||
|
|
_manager!._initBlue();
|
|||
|
|
return _manager;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
factory BlueManage() => shareManager()!;
|
|||
|
|
BlueManage? get manager => shareManager();
|
|||
|
|
|
|||
|
|
void _initBlue(){
|
|||
|
|
_flutterReactiveBle = FlutterReactiveBle();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// 开始扫描蓝牙设备
|
|||
|
|
void startScan(ScanResultCallBack scanResultCallBack) {
|
|||
|
|
_scanDevices.clear();
|
|||
|
|
_flutterReactiveBle!.scanForDevices(withServices: []).listen((device) {
|
|||
|
|
// 判断名字为空的直接剔除
|
|||
|
|
if(device.name.isEmpty){
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (((device.serviceUuids.isNotEmpty ? device.serviceUuids[0] : "").toString().contains("758824")) && (device.rssi >= -100)) {
|
|||
|
|
// print("11111111111111111:${device}");
|
|||
|
|
final knownDeviceIndex = _scanDevices.indexWhere((d) => d.id == device.id);
|
|||
|
|
|
|||
|
|
if (knownDeviceIndex >= 0) {
|
|||
|
|
_scanDevices[knownDeviceIndex] = device;
|
|||
|
|
} else {
|
|||
|
|
_scanDevices.add(device);
|
|||
|
|
}
|
|||
|
|
// EventBusManager().eventBusFir(_scanDevices);
|
|||
|
|
scanResultCallBack(_scanDevices);
|
|||
|
|
}
|
|||
|
|
// _pushState();
|
|||
|
|
}, onError: (Object e) {
|
|||
|
|
print('Device scan fails with error: $e');
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// 连接监听状态
|
|||
|
|
Future<void> connect(String deviceMAC) async {
|
|||
|
|
print("connect:$deviceMAC");
|
|||
|
|
_flutterReactiveBle!.connectToDevice(id: deviceMAC).listen((connectionStateUpdate) {
|
|||
|
|
print('ConnectionState for device $deviceMAC : ${connectionStateUpdate.connectionState}');
|
|||
|
|
// EventBusManager().eventBusFir(connectionStateUpdate);
|
|||
|
|
if(connectionStateUpdate.connectionState == DeviceConnectionState.connected){
|
|||
|
|
// getPublicKey(update.deviceId);
|
|||
|
|
// 如果状态是连接的开始发现服务
|
|||
|
|
discoverServices(deviceMAC);
|
|||
|
|
}
|
|||
|
|
}, onError: (Object e){
|
|||
|
|
print('Connecting to device $deviceMAC resulted in error $e');
|
|||
|
|
}
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Future<void> disconnect(String deviceMAC) async {
|
|||
|
|
try {
|
|||
|
|
print('disconnecting to device: $deviceMAC');
|
|||
|
|
} on Exception catch (e, _) {
|
|||
|
|
print("Error disconnecting from a device: $e");
|
|||
|
|
} finally {
|
|||
|
|
EventBusManager().eventBusFir(ConnectionStateUpdate(
|
|||
|
|
deviceId: deviceMAC,
|
|||
|
|
connectionState: DeviceConnectionState.disconnected,
|
|||
|
|
failure: null,
|
|||
|
|
));
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 扫描服务,并过滤服务
|
|||
|
|
Future<List<DiscoveredService>> discoverServices(String deviceId) async {
|
|||
|
|
try {
|
|||
|
|
print('Start discovering services for: $deviceId');
|
|||
|
|
List<DiscoveredService> result = await _flutterReactiveBle!.discoverServices(deviceId);
|
|||
|
|
print("mmmmmmmmm$result");
|
|||
|
|
if(result.isNotEmpty){
|
|||
|
|
for (var i = 0; i < result.length; i++) {
|
|||
|
|
DiscoveredService discoveredService = result[i];
|
|||
|
|
print("objectdiscoveredService.serviceId.toString() ${discoveredService.serviceId.toString()}");
|
|||
|
|
if (discoveredService.serviceId.toString() == "fff0"){
|
|||
|
|
// getDiscoveredService = discoveredService;
|
|||
|
|
for (var j = 0; j < discoveredService.characteristics.length; j++) {
|
|||
|
|
DiscoveredCharacteristic discoveredCharacteristic = discoveredService.characteristics[j];
|
|||
|
|
|
|||
|
|
// print("hhhhhhhhhh${result[i].characteristicIds[j].toString()}");
|
|||
|
|
if (discoveredCharacteristic.characteristicId.toString() == "fff1") {
|
|||
|
|
// 订阅用
|
|||
|
|
getDiscoveredCharacteristic = discoveredCharacteristic;
|
|||
|
|
// print("1111111111111111characteristicId:${result[i].characteristicIds[j].toString()} serviceId:${result[i].serviceId} deviceId:$deviceId");
|
|||
|
|
}
|
|||
|
|
if (discoveredCharacteristic.characteristicId.toString() == "fff2") {
|
|||
|
|
|
|||
|
|
print("1111111111111111characteristicId:${discoveredCharacteristic.characteristicId} serviceId:${serviceId} deviceId:$deviceId");
|
|||
|
|
qualifiedCharacteristic = QualifiedCharacteristic(characteristicId: discoveredCharacteristic.characteristicId, serviceId:serviceId , deviceId: deviceId);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
subScribeToCharacteristic(QualifiedCharacteristic(characteristicId: getDiscoveredCharacteristic!.characteristicId, serviceId: Uuid.parse("fff0"), deviceId: deviceId));
|
|||
|
|
print('Discovering services finished');
|
|||
|
|
|
|||
|
|
EventBusManager().eventBusFir(qualifiedCharacteristic);
|
|||
|
|
return result;
|
|||
|
|
} on Exception catch (e) {
|
|||
|
|
print('Error occurred when discovering services: $e');
|
|||
|
|
rethrow;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 听上报来的数据,参数来自前面扫描到的结果
|
|||
|
|
subScribeToCharacteristic(QualifiedCharacteristic characteristic) {
|
|||
|
|
print('Subscribing to characteristicId: ${characteristic.characteristicId} serviceId:${characteristic.serviceId} deviceId:${characteristic.deviceId}');
|
|||
|
|
_flutterReactiveBle!.subscribeToCharacteristic(characteristic).listen((data) {
|
|||
|
|
// code to handle incoming data
|
|||
|
|
print("subscribeToCharacteristic: deviceId = ${characteristic.deviceId} characteristicId =${characteristic.characteristicId}---上报来的数据data = $data");
|
|||
|
|
|
|||
|
|
}, onError: (dynamic error) {
|
|||
|
|
print("subscribeToCharacteristic error:$error");
|
|||
|
|
});
|
|||
|
|
// return _ble.subscribeToCharacteristic(characteristic);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 写入
|
|||
|
|
Future<void> writeCharacteristicWithResponse(QualifiedCharacteristic characteristic, List<int> value) async {
|
|||
|
|
print('Write with characteristicId:${characteristic.characteristicId} serviceId:${characteristic.serviceId} deviceId:${characteristic.deviceId} value : $value');
|
|||
|
|
try {
|
|||
|
|
// await _flutterReactiveBle!.writeCharacteristicWithResponse(characteristic, value: value).onError((error, stackTrace){
|
|||
|
|
// print("writeCharacteristicWithResponse:$characteristic $value, error:$error stackTrace:$stackTrace}");
|
|||
|
|
// });
|
|||
|
|
|
|||
|
|
List<int> oneList = [];
|
|||
|
|
List<int> twoList = [];
|
|||
|
|
List<int> threeList = [];
|
|||
|
|
int ctn = getPackageCount(value, averageLen: _limitLen);
|
|||
|
|
for (int i = 1; i <= ctn; i++){
|
|||
|
|
List<int> subData = getSubData(index: i, average: _limitLen, data: value);
|
|||
|
|
print("i:$i ctn:$ctn subData:$subData");
|
|||
|
|
print('Write with characteristicId:${characteristic.characteristicId} serviceId:${characteristic.serviceId} deviceId:${characteristic.deviceId} value : $subData');
|
|||
|
|
|
|||
|
|
switch (i) {
|
|||
|
|
case 1:
|
|||
|
|
{
|
|||
|
|
oneList.addAll(subData);
|
|||
|
|
}
|
|||
|
|
break;
|
|||
|
|
case 2:
|
|||
|
|
{
|
|||
|
|
twoList.addAll(subData);
|
|||
|
|
}
|
|||
|
|
break;
|
|||
|
|
case 3:
|
|||
|
|
{
|
|||
|
|
threeList.addAll(subData);
|
|||
|
|
}
|
|||
|
|
break;
|
|||
|
|
default:
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// await Future.delayed(Duration(
|
|||
|
|
// milliseconds: i == ctn ? 0 : _sleepTimes,
|
|||
|
|
// ),(){
|
|||
|
|
// // i++;
|
|||
|
|
// });
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
print("oneList:$oneList");
|
|||
|
|
_flutterReactiveBle!.writeCharacteristicWithResponse(characteristic, value: oneList).onError((error, stackTrace){
|
|||
|
|
// print("writeCharacteristicWithResponse:$characteristic $subData, error:$error stackTrace:$stackTrace}");
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
await Future.delayed(const Duration(milliseconds: 100,),(){
|
|||
|
|
print("twoList:$twoList");
|
|||
|
|
_flutterReactiveBle!.writeCharacteristicWithResponse(characteristic, value: twoList).onError((error, stackTrace){
|
|||
|
|
// print("writeCharacteristicWithResponse:$characteristic $subData, error:$error stackTrace:$stackTrace}");
|
|||
|
|
});
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
await Future.delayed(const Duration(milliseconds: 100,),(){
|
|||
|
|
print("threeList:$threeList");
|
|||
|
|
_flutterReactiveBle!.writeCharacteristicWithResponse(characteristic, value: threeList).onError((error, stackTrace){
|
|||
|
|
// print("writeCharacteristicWithResponse:$characteristic $subData, error:$error stackTrace:$stackTrace}");
|
|||
|
|
});
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// _flutterReactiveBle!.writeCharacteristicWithResponse(characteristic, value: subData).onError((error, stackTrace){
|
|||
|
|
// // print("writeCharacteristicWithResponse:$characteristic $subData, error:$error stackTrace:$stackTrace}");
|
|||
|
|
// });
|
|||
|
|
|
|||
|
|
// while(i <= ctn) {
|
|||
|
|
// print("object$i ");
|
|||
|
|
// List<int> subData = getSubData(index: i, average: _limitLen, data: value);
|
|||
|
|
// print('Write with characteristicId:${characteristic.characteristicId} serviceId:${characteristic.serviceId} deviceId:${characteristic.deviceId} value : $subData');
|
|||
|
|
// await _flutterReactiveBle!.writeCharacteristicWithResponse(characteristic, value: subData).onError((error, stackTrace){
|
|||
|
|
// // print("writeCharacteristicWithResponse:$characteristic $subData, error:$error stackTrace:$stackTrace}");
|
|||
|
|
// });
|
|||
|
|
// await Future.delayed(Duration(
|
|||
|
|
// milliseconds: i == ctn ? 0 : _sleepTimes,
|
|||
|
|
// ),(){
|
|||
|
|
// i++;
|
|||
|
|
// });
|
|||
|
|
// }
|
|||
|
|
// i = 1;
|
|||
|
|
// await readCharacteristic(characteristic);
|
|||
|
|
|
|||
|
|
} on Exception catch (e, s) {
|
|||
|
|
print('Error occurred when writing: $e',);
|
|||
|
|
// ignore: avoid_print
|
|||
|
|
print(s);
|
|||
|
|
rethrow;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 读取
|
|||
|
|
Future<List<int>> readCharacteristic(QualifiedCharacteristic characteristic) async {
|
|||
|
|
try {
|
|||
|
|
final result = await _flutterReactiveBle!.readCharacteristic(characteristic);
|
|||
|
|
print("readListresult$result");
|
|||
|
|
return result;
|
|||
|
|
} on Exception catch (e, s) {
|
|||
|
|
print('Error occurred when reading ${characteristic.characteristicId} : $e',);
|
|||
|
|
rethrow;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
Future<void> writeCharacteristicWithoutResponse(
|
|||
|
|
QualifiedCharacteristic characteristic, List<int> value) async {
|
|||
|
|
try {
|
|||
|
|
await _flutterReactiveBle!.writeCharacteristicWithoutResponse(characteristic,
|
|||
|
|
value: value);
|
|||
|
|
} on Exception catch (e, s) {
|
|||
|
|
// ignore: avoid_print
|
|||
|
|
print(s);
|
|||
|
|
rethrow;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
}
|