From ac1e447eca52e89482fd6d7f9354300186546f1b Mon Sep 17 00:00:00 2001 From: liyi Date: Mon, 8 Sep 2025 17:14:15 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=A2=9E=E5=8A=A0=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E8=AE=BE=E5=A4=87=E5=85=AC=E9=92=A5=E3=80=81=E7=A7=81=E9=92=A5?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/ble/ble_service.dart | 49 ++++++++++++------- lib/ble/command/ble_command_manager.dart | 4 +- .../request/ble_cmd_get_private_key.dart | 10 +--- .../ble_cmd_get_private_key_parser.dart | 5 -- lib/common/constant/cache_keys.dart | 4 +- .../utils/shared_preferences_utils.dart | 15 ++++++ .../search_device_controller.dart | 6 ++- 7 files changed, 57 insertions(+), 36 deletions(-) diff --git a/lib/ble/ble_service.dart b/lib/ble/ble_service.dart index 72d747b..83e01c9 100644 --- a/lib/ble/ble_service.dart +++ b/lib/ble/ble_service.dart @@ -5,7 +5,9 @@ import 'package:starwork_flutter/base/app_logger.dart'; import 'package:starwork_flutter/ble/ble_config.dart'; import 'package:starwork_flutter/ble/command/base/base_ble_command.dart'; import 'package:starwork_flutter/ble/command/ble_command_manager.dart'; +import 'package:starwork_flutter/ble/command/request/ble_cmd_get_private_key.dart'; import 'package:starwork_flutter/ble/command/request/ble_cmd_get_public_key.dart'; +import 'package:starwork_flutter/ble/command/response/ble_cmd_get_private_key_parser.dart'; import 'package:starwork_flutter/ble/command/response/ble_cmd_get_public_key_parser.dart'; import 'package:starwork_flutter/ble/model/scan_device_info.dart'; import 'package:starwork_flutter/common/constant/device_type.dart'; @@ -104,6 +106,9 @@ class BleService { /// 搜索状态 bool get isScanningNow => FlutterBluePlus.isScanningNow; + /// 获取当前连接的设备 + BluetoothDevice? get connectedDevice => _connectedDevice; + /// 初始化服务时执行的 Future _initialize() async { AppLogger.highlight('🚀 BleService 正在初始化...'); @@ -286,11 +291,6 @@ class BleService { if (result != null) { // 触发命令响应等待器 _triggerCommandResponseWaiters(result); - - // 如果是获取公钥的应答,可以进行类型转换 - // if (result is GetPublicKeyResponse) { - // GetPublicKeyResponse response = result; - // } } else { AppLogger.warn('⚠️ 数据包解析失败或不匹配任何命令'); } @@ -303,9 +303,6 @@ class BleService { void _triggerCommandResponseWaiters(dynamic response) { // 遍历所有等待中的命令,找到匹配的进行响应 List completedKeys = []; - - // 如果响应是GetPublicKeyResponse类型,尝试提取命令ID进行匹配 - int commandId = response.commandId; String? commandKey = _commandIdToKeyMap[commandId]; @@ -378,17 +375,7 @@ class BleService { _commandResponseWaiters[commandKey] = responseCompleter; // 5. 如果命令有cmdId静态字段,将其与命令键关联 - try { - // 对于特定类型的命令,手动检查cmdId字段 - if (command is BleCmdGetPublicKey) { - int commandId = BleCmdGetPublicKey.cmdId; - _commandIdToKeyMap[commandId] = commandKey; - AppLogger.debug('📝 命令ID映射: 0x${commandId.toRadixString(16).padLeft(4, '0')} -> $commandKey'); - } - // 可以为其他命令类型添加类似的检查 - } catch (e) { - AppLogger.warn('⚠️ 无法获取命令ID: $e'); - } + _registerCommandId(command, commandKey); // 6. 设置超时定时器 Timer timeoutTimer = Timer(timeout, () { @@ -425,6 +412,30 @@ class BleService { } } + /// 将命令对象映射到 commandKey,特定命令需手动注册 cmdId + void _registerCommandId(dynamic command, String commandKey) { + try { + final int? commandId = switch (command) { + BleCmdGetPublicKey() => BleCmdGetPublicKey.cmdId, + BleCmdGetPrivateKey() => BleCmdGetPrivateKey.cmdId, + // 可在此添加更多命令类型 + // BleCmdAnother() => BleCmdAnother.cmdId, + _ => null, // 默认情况:无法识别的命令类型 + }; + + if (commandId != null) { + _commandIdToKeyMap[commandId] = commandKey; + AppLogger.debug( + '📝 命令ID映射: 0x${commandId.toRadixString(16).padLeft(4, '0')} -> $commandKey', + ); + } else { + AppLogger.debug('❓ 未知命令类型,无法注册 commandId: $commandKey'); + } + } catch (e) { + AppLogger.warn('⚠️ 无法获取命令ID: $e'); + } + } + void cancel() { /// 销毁蓝牙适配器监听 _adapterStateSubscription?.cancel(); diff --git a/lib/ble/command/ble_command_manager.dart b/lib/ble/command/ble_command_manager.dart index df6e734..d0861b4 100644 --- a/lib/ble/command/ble_command_manager.dart +++ b/lib/ble/command/ble_command_manager.dart @@ -145,9 +145,11 @@ class BleCommandManager { return _decryptAES128(parsedPacket.data); case BaseBleCommand.ENCRYPT_TYPE_SM4_PRESET: + var connectedDevice = BleService().connectedDevice; + var platformName = connectedDevice?.platformName; var decrypt = SM4.decrypt( parsedPacket.data, - key: utf8.encode('TMH_190068d76ae8'), + key: utf8.encode(platformName!), mode: SM4CryptoMode.ECB, ); return decrypt; diff --git a/lib/ble/command/request/ble_cmd_get_private_key.dart b/lib/ble/command/request/ble_cmd_get_private_key.dart index 682a166..93431ed 100644 --- a/lib/ble/command/request/ble_cmd_get_private_key.dart +++ b/lib/ble/command/request/ble_cmd_get_private_key.dart @@ -126,15 +126,12 @@ class BleCmdGetPrivateKey extends BaseBleCommand { data.addAll(utf8.encode(keyId)); data = getFixedLengthList(data, 40 - keyIDLength); - //authUserID 40 + //authUserID 20 final int authUserIDLength = utf8.encode(authUserID!).length; data.addAll(utf8.encode(authUserID)); data = getFixedLengthList(data, 20 - authUserIDLength); //NowTime 4 - // DateTime now = DateTime.now(); - // int timestamp = now.millisecondsSinceEpoch; - // var d1 = 0x11223344; data.add((nowTime & 0xff000000) >> 24); data.add((nowTime & 0xff0000) >> 16); data.add((nowTime & 0xff00) >> 8); @@ -149,9 +146,6 @@ class BleCmdGetPrivateKey extends BaseBleCommand { authCodeData.addAll(utf8.encode(keyId!)); //NowTime 4 - // DateTime now = DateTime.now(); - // int timestamp = now.millisecondsSinceEpoch; - // var d1 = 0x11223344; authCodeData.add((nowTime & 0xff000000) >> 24); authCodeData.add((nowTime & 0xff0000) >> 16); authCodeData.add((nowTime & 0xff00) >> 8); @@ -159,7 +153,7 @@ class BleCmdGetPrivateKey extends BaseBleCommand { authCodeData.addAll(publicKey); - // 把KeyID、authUserID、时间戳、公钥通过md5加密之后就是authCode + // 把authUserID、KeyID、时间戳、公钥通过md5加密之后就是authCode var authCode = md5.convert(authCodeData); data.add(authCode.bytes.length); diff --git a/lib/ble/command/response/ble_cmd_get_private_key_parser.dart b/lib/ble/command/response/ble_cmd_get_private_key_parser.dart index 284c62a..271f921 100644 --- a/lib/ble/command/response/ble_cmd_get_private_key_parser.dart +++ b/lib/ble/command/response/ble_cmd_get_private_key_parser.dart @@ -65,11 +65,6 @@ class BleCmdGetPrivateKeyParser extends BaseBleResponseParser { @override GetPrivateKeyResponse parseResponse(ParsedPacket parsedPacket, List rawResponseData) { try { - // 数据包格式分析: - // 字节 0-1: 命令ID (0x3090, 大端序) - // 字节 2: 状态码 (0x00=成功, 其他=失败) - // 字节 3-N: 私钥数据 (长度可变) - if (rawResponseData.length < 3) { throw ArgumentError('应答数据长度不足: ${rawResponseData.length}字节 < 3字节'); } diff --git a/lib/common/constant/cache_keys.dart b/lib/common/constant/cache_keys.dart index 0858bd9..373b584 100644 --- a/lib/common/constant/cache_keys.dart +++ b/lib/common/constant/cache_keys.dart @@ -1,7 +1,9 @@ class CacheKeys { static const String isSendValidationCode = 'isSendValidationCode'; static const String token = 'token'; - static const String publicKeyHex = 'publicKeyHex'; + static const String lockPublicKey = 'lockPublicKey'; + static const String lockCommKey = 'lockCommKey'; + static const String lockSignKey = 'lockSignKey'; static const String starCloudUserInfo = 'starCloudUserInfo'; static const String starCloudUserLoginInfo = 'starCloudUserLoginInfo'; diff --git a/lib/common/utils/shared_preferences_utils.dart b/lib/common/utils/shared_preferences_utils.dart index 90b2323..60de3ad 100644 --- a/lib/common/utils/shared_preferences_utils.dart +++ b/lib/common/utils/shared_preferences_utils.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import 'package:shared_preferences/shared_preferences.dart'; import 'dart:async'; @@ -83,4 +85,17 @@ class SharedPreferencesUtils { static Future getBool(String key) async { return _prefs?.getBool(key); } + + // 保存 List + static Future saveIntList(String key, List list) async { + final base64String = base64Encode(list); + await _prefs?.setString(key, base64String); + } + + // 读取 List + static Future?> getIntList(String key) async { + final base64String = _prefs?.getString(key); + if (base64String == null) return null; + return base64Decode(base64String); + } } diff --git a/lib/views/device/searchDevice/search_device_controller.dart b/lib/views/device/searchDevice/search_device_controller.dart index 19f52c8..648b3c7 100644 --- a/lib/views/device/searchDevice/search_device_controller.dart +++ b/lib/views/device/searchDevice/search_device_controller.dart @@ -182,7 +182,7 @@ class SearchDeviceController extends BaseController { ); if (publicKeyResponse != null && publicKeyResponse.isSuccess) { AppLogger.info('🎯 获取公钥成功: ${publicKeyResponse.publicKeyHex}'); - SharedPreferencesUtils.setString(CacheKeys.publicKeyHex, publicKeyResponse.publicKeyHex); + await SharedPreferencesUtils.saveIntList(CacheKeys.lockPublicKey, publicKeyResponse.publicKey); BleCmdGetPrivateKey getPrivateKeyCmd = BleCmdGetPrivateKey( lockId: device.advName, keyId: '1', @@ -201,7 +201,9 @@ class SearchDeviceController extends BaseController { autoConnectIfNeeded: true, ); if (privateKeyResponse != null && privateKeyResponse.isSuccess) { - AppLogger.info('🎯 获取私钥成功: ${privateKeyResponse.commKeyHex}'); + await SharedPreferencesUtils.saveIntList(CacheKeys.lockCommKey, privateKeyResponse.commKey); + await SharedPreferencesUtils.saveIntList(CacheKeys.lockSignKey, privateKeyResponse.signKey); + AppLogger.info('🎯 获取私钥成功: ${privateKeyResponse.toString()}'); } } else { AppLogger.warn('⚠️ 命令发送完成,但未收到有效响应');