diff --git a/lib/blue/blue_manage.dart b/lib/blue/blue_manage.dart index 359758b9..70d9bc45 100755 --- a/lib/blue/blue_manage.dart +++ b/lib/blue/blue_manage.dart @@ -775,7 +775,7 @@ class BlueManage { } } - // 写入 + /// 写入蓝牙特征值,并等待响应 Future writeCharacteristicWithResponse(List value) async { final List services = await bluetoothConnectDevice!.discoverServices(); @@ -785,30 +785,64 @@ class BlueManage { in service.characteristics) { if (characteristic.characteristicUuid == _characteristicIdWrite) { try { + // 添加重试机制 + int retryCount = 0; + const int maxRetries = 3; + const int retryDelayMs = 500; + final List 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) { - // 使用WRITE_NO_RESPONSE属性写入值 - await characteristic.write(subData[i], withoutResponse: true); - } else if (characteristic.properties.write) { - // 使用WRITE属性写入值 - await characteristic.write(subData[i]); - } else { - // 特性不支持写入 - throw Exception( - 'This characteristic does not support writing.'); + // 对每个数据包都应用重试逻辑 + bool packetSent = false; + retryCount = 0; + + while (!packetSent && retryCount < maxRetries) { + try { + if (characteristic.properties.writeWithoutResponse) { + await characteristic.write(subData[i], withoutResponse: true); + } else if (characteristic.properties.write) { + await characteristic.write(subData[i]); + } else { + // 特性不支持写入 + throw Exception('This characteristic does not support writing.'); + } + + // 如果到这里没有异常,则包发送成功 + packetSent = true; + } catch (e) { + if (e.toString().contains('UNKNOWN_GATT_ERROR (133)') && retryCount < maxRetries - 1) { + // GATT错误133,尝试重试 + retryCount++; + AppLog.log('蓝牙写入失败(GATT 133),数据包 ${i+1}/${subData.length} 正在重试 $retryCount/$maxRetries...'); + await Future.delayed(Duration(milliseconds: retryDelayMs)); + continue; + } else { + // 其他错误或已达到最大重试次数,抛出异常 + AppLog.log('APP写入失败: $e'); + throw e; + } + } + } + + if (!packetSent) { + throw Exception('蓝牙写入失败,数据包 ${i+1}/${subData.length} 已达到最大重试次数'); } } + + return; // 所有数据包都发送成功 } on Exception catch (e, s) { - AppLog.log('APP写入失败: $e $s'); + AppLog.log('APP写入失败: $e $s'); rethrow; } } } } } + + // 如果找不到合适的特性用于写入 + throw Exception('未找到适合写入的蓝牙特性'); } // 停止扫描蓝牙设备