feat:添加蓝牙 debug 日志

This commit is contained in:
anfe 2024-05-20 16:37:49 +08:00
parent 3da93adfb5
commit 23f0a19fb8

View File

@ -1,13 +1,9 @@
import 'dart:async';
import 'dart:io';
import 'package:app_settings/app_settings.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:star_lock/app_settings/app_settings.dart';
import 'package:star_lock/tools/showTipView.dart';
import 'package:star_lock/widget/permission/permission_dialog.dart';
import 'package:url_launcher/url_launcher.dart';
import 'io_tool/io_model.dart';
import 'io_tool/io_tool.dart';
@ -21,19 +17,19 @@ typedef ConnectStateCallBack = Function(
typedef ScanDevicesCallBack = Function(List<ScanResult>);
class BlueManage {
final List<ScanResult> scanDevices = [];
final List<ScanResult> scanDevices = <ScanResult>[];
// id
final Guid _serviceIdConnect = Guid("fff0");
final Guid _serviceIdConnect = Guid('fff0');
// id
final Guid _serviceIdWrite = Guid('0000FFF0-0000-1000-8000-00805F9B34FB');
// id
final Guid _characteristicIdSubscription = Guid("fff1");
final Guid _characteristicIdSubscription = Guid('fff1');
// id
final Guid _characteristicIdWrite = Guid("fff2");
final Guid _characteristicIdWrite = Guid('fff2');
//
StreamSubscription<EventSendModel>? _sendStreamSubscription;
@ -50,10 +46,10 @@ class BlueManage {
int? _mtuSize = 20;
//
String connectDeviceName = "";
String connectDeviceName = '';
// mac地址
String connectDeviceMacAddress = "";
String connectDeviceMacAddress = '';
//
BluetoothDevice? bluetoothConnectDevice;
@ -93,7 +89,7 @@ class BlueManage {
}
void _initGetMtuSubscription() {
_mtuSubscription ??= bluetoothConnectDevice!.mtu.listen((value) {
_mtuSubscription ??= bluetoothConnectDevice!.mtu.listen((int value) {
_mtuSize = value - 3;
AppLog.log('_mtuSizeValue:$value mtuSize:$_mtuSize');
});
@ -101,7 +97,7 @@ class BlueManage {
void _initAdapterStateStateSubscription() {
_adapterStateStateSubscription ??=
FlutterBluePlus.adapterState.listen((state) {
FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) {
_adapterState = state;
});
}
@ -149,8 +145,8 @@ class BlueManage {
_connectionStateSubscription?.cancel();
_connectionStateSubscription = null;
_connectionStateSubscription =
bluetoothConnectDevice!.connectionState.listen((state) async {
_connectionStateSubscription = bluetoothConnectDevice!.connectionState
.listen((BluetoothConnectionState state) async {
bluetoothConnectionState = state;
// AppLog.log("蓝牙连接状态:$state");
});
@ -162,18 +158,18 @@ class BlueManage {
.on<EventSendModel>()
.listen((EventSendModel model) {
if (model.sendChannel == DataChannel.ble) {
FlutterBluePlus.isSupported.then((isAvailable) async {
FlutterBluePlus.isSupported.then((bool isAvailable) async {
if (isAvailable) {
if (_adapterState == BluetoothAdapterState.on) {
//
writeCharacteristicWithResponse(model.data);
} else {
try {} catch (e) {
AppLog.log("蓝牙打开失败");
AppLog.log('蓝牙打开失败');
}
}
} else {
AppLog.log("写入数据 蓝牙不可用,不能进行蓝牙操作");
AppLog.log('写入数据 蓝牙不可用,不能进行蓝牙操作');
}
});
}
@ -183,31 +179,33 @@ class BlueManage {
///
Future<void> startScanSingle(String deviceName, int timeout,
ScanDevicesCallBack scanDevicesCallBack) async {
FlutterBluePlus.isSupported.then((isAvailable) async {
FlutterBluePlus.isSupported.then((bool isAvailable) async {
if (isAvailable) {
if (_adapterState == BluetoothAdapterState.on) {
try {
FlutterBluePlus.startScan(timeout: Duration(seconds: timeout));
Completer<dynamic> completer = Completer<dynamic>();
var subscription = FlutterBluePlus.scanResults.listen((results) {
// AppLog.log("startScanSingle扫描到的设备:$results");
bool isExit = results.any((element) =>
final Completer<dynamic> completer = Completer<dynamic>();
final StreamSubscription<List<ScanResult>> subscription =
FlutterBluePlus.scanResults.listen((List<ScanResult> results) {
final bool isExit = results.any((ScanResult element) =>
(element.device.platformName == deviceName) ||
(element.advertisementData.advName == deviceName));
AppLog.log('扫描到的设备数:${results.length} 是否查找到 $isExit');
if (isExit) {
for (var scanResult in results) {
for (final ScanResult scanResult in results) {
if (((scanResult.advertisementData.serviceUuids.isNotEmpty
? scanResult.advertisementData.serviceUuids[0]
: "")
: '')
.toString()
.contains("758824")) &&
.contains('758824')) &&
(scanResult.rssi >= -100)) {
// id相同的元素
final knownDeviceIndex = scanDevices.indexWhere((d) =>
(d.device.platformName ==
scanResult.device.platformName) ||
(d.advertisementData.advName ==
scanResult.advertisementData.advName));
final int knownDeviceIndex = scanDevices.indexWhere(
(ScanResult d) =>
(d.device.platformName ==
scanResult.device.platformName) ||
(d.advertisementData.advName ==
scanResult.advertisementData.advName));
// -1
if (knownDeviceIndex >= 0) {
scanDevices[knownDeviceIndex] = scanResult;
@ -220,7 +218,7 @@ class BlueManage {
}
}, onError: (e) {
AppLog.log(
"扫描失败:$e",
'扫描失败:$e',
);
});
FlutterBluePlus.cancelWhenScanComplete(subscription);
@ -228,7 +226,7 @@ class BlueManage {
scanDevicesCallBack(scanDevices);
subscription.cancel();
} catch (e) {
AppLog.log("扫描失败");
AppLog.log('扫描失败');
}
} else {
try {
@ -236,11 +234,11 @@ class BlueManage {
await FlutterBluePlus.turnOn();
}
} catch (e) {
AppLog.log("蓝牙打开失败");
AppLog.log('蓝牙打开失败');
}
}
} else {
AppLog.log("开始扫描 蓝牙不可用,不能进行蓝牙操作");
AppLog.log('开始扫描 蓝牙不可用,不能进行蓝牙操作');
}
});
}
@ -248,15 +246,16 @@ class BlueManage {
///
Future<void> startScan(int timeout, ScanDevicesCallBack scanDevicesCallBack,
{List<Guid>? idList}) async {
FlutterBluePlus.isSupported.then((isAvailable) async {
FlutterBluePlus.isSupported.then((bool isAvailable) async {
if (isAvailable) {
if (_adapterState == BluetoothAdapterState.on) {
try {
FlutterBluePlus.startScan(timeout: Duration(seconds: timeout));
var subscription = FlutterBluePlus.scanResults.listen((results) {
final StreamSubscription<List<ScanResult>> subscription =
FlutterBluePlus.scanResults.listen((List<ScanResult> results) {
scanDevices.clear();
for (var scanResult in results) {
for (final ScanResult scanResult in results) {
//
// if (scanResult.device.advName.isEmpty) {
// return;
@ -266,16 +265,17 @@ class BlueManage {
// " rssi:${scanResult.rssi}");
if (((scanResult.advertisementData.serviceUuids.isNotEmpty
? scanResult.advertisementData.serviceUuids[0]
: "")
: '')
.toString()
.contains("758824")) &&
.contains('758824')) &&
(scanResult.rssi >= -100)) {
// id相同的元素
final knownDeviceIndex = scanDevices.indexWhere((d) =>
(d.device.platformName ==
scanResult.device.platformName) ||
(d.advertisementData.advName ==
scanResult.advertisementData.advName));
final int knownDeviceIndex = scanDevices.indexWhere(
(ScanResult d) =>
(d.device.platformName ==
scanResult.device.platformName) ||
(d.advertisementData.advName ==
scanResult.advertisementData.advName));
// -1
if (knownDeviceIndex >= 0) {
scanDevices[knownDeviceIndex] = scanResult;
@ -303,13 +303,13 @@ class BlueManage {
// FlutterBluePlus.stopScan();
}, onError: (e) {
AppLog.log(
"扫描失败:$e",
'扫描失败:$e',
);
});
FlutterBluePlus.cancelWhenScanComplete(subscription);
} catch (e) {
AppLog.log("扫描失败");
AppLog.log('扫描失败');
}
} else {
try {
@ -317,11 +317,11 @@ class BlueManage {
await FlutterBluePlus.turnOn();
}
} catch (e) {
AppLog.log("蓝牙打开失败");
AppLog.log('蓝牙打开失败');
}
}
} else {
AppLog.log("开始扫描 蓝牙不可用,不能进行蓝牙操作");
AppLog.log('开始扫描 蓝牙不可用,不能进行蓝牙操作');
}
});
}
@ -330,12 +330,13 @@ class BlueManage {
Future<void> bludSendData(
String deviceName, ConnectStateCallBack stateCallBack,
{bool isAddEquipment = false}) async {
FlutterBluePlus.isSupported.then((isAvailable) async {
FlutterBluePlus.isSupported.then((bool isAvailable) async {
if (isAvailable) {
AppLog.log('蓝牙状态 系统蓝牙状态:$_adapterState 蓝牙连接状态:$bluetoothConnectionState');
if (_adapterState == BluetoothAdapterState.on) {
//
if (bluetoothConnectionState != BluetoothConnectionState.connected) {
_connect(deviceName, (state) {
_connect(deviceName, (BluetoothConnectionState state) {
stateCallBack(bluetoothConnectionState!);
}, isAddEquipment: isAddEquipment);
} else {
@ -346,11 +347,11 @@ class BlueManage {
stateCallBack(BluetoothConnectionState.disconnected);
openBlue();
} catch (e) {
AppLog.log("蓝牙打开失败");
AppLog.log('蓝牙打开失败');
}
}
} else {
AppLog.log("开始扫描 蓝牙不可用,不能进行蓝牙操作");
AppLog.log('开始扫描 蓝牙不可用,不能进行蓝牙操作');
}
});
}
@ -360,9 +361,9 @@ class BlueManage {
String deviceName, ConnectStateCallBack connectStateCallBack,
{bool isAddEquipment = false}) async {
connectDeviceName = deviceName;
List<ScanResult> devicesList = scanDevices;
final List<ScanResult> devicesList = scanDevices;
bool isExistDevice = scanDevices.any((element) =>
final bool isExistDevice = scanDevices.any((ScanResult element) =>
element.device.platformName == connectDeviceName ||
element.advertisementData.advName == connectDeviceName);
@ -383,7 +384,7 @@ class BlueManage {
{bool isAddEquipment = false}) async {
//
// AppLog.log("devicesList:$devicesList");
final knownDeviceIndex = devicesList.indexWhere((d) =>
final int knownDeviceIndex = devicesList.indexWhere((ScanResult d) =>
(d.device.platformName == deviceName) ||
(d.advertisementData.advName == deviceName));
@ -412,15 +413,15 @@ class BlueManage {
// AppLog.log("调用了停止扫描的方法");
await stopScan();
if ((scanResult.advertisementData.serviceUuids[0].toString()[31] == "0") &&
if ((scanResult.advertisementData.serviceUuids[0].toString()[31] == '0') &&
isAddEquipment == false) {
connectStateCallBack(BluetoothConnectionState.disconnected);
EasyLoading.showToast("该锁已被重置".tr, duration: 2000.milliseconds);
EasyLoading.showToast('该锁已被重置'.tr, duration: 2000.milliseconds);
return;
}
//
int maxAttempts = 3;
final int maxAttempts = 3;
int attempt = 0;
while (attempt < maxAttempts) {
try {
@ -443,14 +444,16 @@ class BlueManage {
// await bluetoothConnectDevice!.connect();
if (bluetoothConnectionState == BluetoothConnectionState.connected) {
try {
bluetoothConnectDevice!.discoverServices().then((services) {
for (BluetoothService service in services) {
bluetoothConnectDevice!
.discoverServices()
.then((List<BluetoothService> services) {
for (final BluetoothService service in services) {
// AppLog.log("11111service.remoteId:${service.remoteId}"
// " service.uuid:${service.uuid}"
// " service.characteristics:${service.characteristics}"
// " service.includedServices:${service.includedServices}");
if (service.uuid == _serviceIdConnect) {
for (BluetoothCharacteristic characteristic
for (final BluetoothCharacteristic characteristic
in service.characteristics) {
// Get.log("22222characteristic.remoteId:${characteristic.remoteId}"
// " characteristic.uuid:${characteristic.uuid}"
@ -478,14 +481,15 @@ class BlueManage {
}
// ,
var allData = <int>[];
List<int> allData = <int>[];
//
var lastTimeData = <int>[];
List<int> lastTimeData = <int>[];
int? dataLen;
_subScribeToCharacteristic(BluetoothCharacteristic characteristic) async {
final subscription = characteristic.onValueReceived.listen((data) {
final StreamSubscription<List<int>> subscription =
characteristic.onValueReceived.listen((List<int> data) {
// AppLog.log("订阅获取的数据:$data");
if (data == lastTimeData || data.isEmpty) {
return;
@ -580,15 +584,15 @@ class BlueManage {
//
Future<void> writeCharacteristicWithResponse(List<int> value) async {
List<BluetoothService> services =
final List<BluetoothService> services =
await bluetoothConnectDevice!.discoverServices();
for (BluetoothService service in services) {
for (final BluetoothService service in services) {
// AppLog.log("33333 service.remoteId:${service.remoteId}"
// " service.uuid:${service.uuid}\n\n"
// " service.characteristics:${service.characteristics}\n\n"
// " service.includedServices:${service.includedServices}");
if (service.uuid == _serviceIdConnect) {
for (BluetoothCharacteristic characteristic
for (final BluetoothCharacteristic characteristic
in service.characteristics) {
// AppLog.log("44444 characteristic.remoteId:${characteristic.remoteId}"
// " characteristic.uuid:${characteristic.uuid}\n\n"
@ -598,8 +602,8 @@ class BlueManage {
// .characteristicUuid}");
if (characteristic.characteristicUuid == _characteristicIdWrite) {
try {
List<int> valueList = value;
List subData = splitList(valueList, _mtuSize!);
final List<int> valueList = value;
final List subData = splitList(valueList, _mtuSize!);
// AppLog.log('writeCharacteristicWithResponse _mtuSize:$_mtuSize 得到的分割数据:$subData');
for (int i = 0; i < subData.length; i++) {
if (characteristic.properties.writeWithoutResponse) {
@ -660,15 +664,15 @@ class BlueManage {
//
Future<void> writeNull() async {
List<BluetoothService> services =
final List<BluetoothService> services =
await bluetoothConnectDevice!.discoverServices();
for (BluetoothService service in services) {
for (final BluetoothService service in services) {
if (service.uuid == _serviceIdConnect) {
for (BluetoothCharacteristic characteristic
for (final BluetoothCharacteristic characteristic
in service.characteristics) {
if (characteristic.characteristicUuid == _characteristicIdWrite) {
try {
List<int> valueList = [1];
final List<int> valueList = <int>[1];
AppLog.log('APP写入 writeNull ');
await characteristic.write(valueList);
} on Exception catch (e, s) {
@ -713,7 +717,7 @@ class BlueManage {
try {
await FlutterBluePlus.stopScan();
} catch (e) {
AppLog.log("停止扫描失败");
AppLog.log('停止扫描失败');
}
}
@ -721,17 +725,17 @@ class BlueManage {
Future<void> disconnect() async {
try {
// if(bluetoothConnectDevice != null && bluetoothConnectDevice!.connectionState == BluetoothConnectionState.connected){
connectDeviceMacAddress = "";
connectDeviceMacAddress = '';
if (bluetoothConnectionState == BluetoothConnectionState.connected) {
// await writeNull();
// await Future.delayed(const Duration(milliseconds: 1000));
//
await bluetoothConnectDevice!.disconnect(timeout: 2);
AppLog.log("断开连接成功");
AppLog.log('断开连接成功');
}
// }
} on Exception catch (e, _) {
AppLog.log("断开连接失败: $e");
AppLog.log('断开连接失败: $e');
} finally {
bluetoothConnectionState = BluetoothConnectionState.disconnected;
}
@ -742,7 +746,7 @@ class BlueManage {
await FlutterBluePlus.turnOn();
}
if (Platform.isIOS) {
EasyLoading.showToast("请开启蓝牙".tr, duration: 2000.milliseconds);
EasyLoading.showToast('请开启蓝牙'.tr, duration: 2000.milliseconds);
}
}