From 9bab2cde568ad38e8ecc61b2baf73301454bf69d Mon Sep 17 00:00:00 2001 From: liyi Date: Tue, 9 Sep 2025 16:51:29 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=9A=82=E7=BC=93=EF=BC=8C=E6=94=B9?= =?UTF-8?q?=E4=B8=BAsdk=E6=8E=A5=E5=85=A5=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ios/Podfile.lock | 6 + lib/base/app_initialization.dart | 7 + .../command/base/retryable_ble_command.dart | 0 lib/common/constant/cache_keys.dart | 4 +- .../search_device_controller.dart | 182 ++++-------------- .../searchDevice/search_device_view.dart | 3 +- .../input_verification_code_controller.dart | 3 + pubspec.lock | 9 +- pubspec.yaml | 5 +- 9 files changed, 72 insertions(+), 147 deletions(-) create mode 100644 lib/ble/command/base/retryable_ble_command.dart diff --git a/ios/Podfile.lock b/ios/Podfile.lock index 451ed7f..ada2532 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -8,12 +8,15 @@ PODS: - shared_preferences_foundation (0.0.1): - Flutter - FlutterMacOS + - starcloud (0.0.1): + - Flutter DEPENDENCIES: - Flutter (from `Flutter`) - flutter_blue_plus_darwin (from `.symlinks/plugins/flutter_blue_plus_darwin/darwin`) - permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`) - shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`) + - starcloud (from `.symlinks/plugins/starcloud/ios`) EXTERNAL SOURCES: Flutter: @@ -24,12 +27,15 @@ EXTERNAL SOURCES: :path: ".symlinks/plugins/permission_handler_apple/ios" shared_preferences_foundation: :path: ".symlinks/plugins/shared_preferences_foundation/darwin" + starcloud: + :path: ".symlinks/plugins/starcloud/ios" SPEC CHECKSUMS: Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7 flutter_blue_plus_darwin: 20a08bfeaa0f7804d524858d3d8744bcc1b6dbc3 permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7 + starcloud: 0d2034397e2a0d81b8c187b99bd2de7371ea5b2d PODFILE CHECKSUM: 41883e5e56033ab6e4e0f607734d753c5bb7c460 diff --git a/lib/base/app_initialization.dart b/lib/base/app_initialization.dart index d517b8d..d549d1c 100644 --- a/lib/base/app_initialization.dart +++ b/lib/base/app_initialization.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:get/get.dart'; +import 'package:starcloud/sdk/starcloud.dart'; import 'package:starwork_flutter/api/base_api_service.dart'; import 'package:starwork_flutter/api/service/common_api_service.dart'; @@ -23,6 +24,12 @@ class AppInitialization { await SharedPreferencesUtils.init(); initEasyLoading(); + StarCloudSDK.init( + clientId: F.starCloudClientId, + clientSecret: F.starCloudSecret, + environmentUrl: F.starCloudUrl, + ); + Get.put(BaseApiService()); Get.put(StarCloudBaseApiService()); Get.put(CommonApiService(Get.find())); diff --git a/lib/ble/command/base/retryable_ble_command.dart b/lib/ble/command/base/retryable_ble_command.dart new file mode 100644 index 0000000..e69de29 diff --git a/lib/common/constant/cache_keys.dart b/lib/common/constant/cache_keys.dart index 373b584..e26af58 100644 --- a/lib/common/constant/cache_keys.dart +++ b/lib/common/constant/cache_keys.dart @@ -4,7 +4,9 @@ class CacheKeys { static const String lockPublicKey = 'lockPublicKey'; static const String lockCommKey = 'lockCommKey'; static const String lockSignKey = 'lockSignKey'; - static const String starCloudUserInfo = 'starCloudUserInfo'; + static const String starCloudUserName = 'starCloudUserName'; + static const String starCloudPassword = 'starCloudPassword'; + static const String starCloudUid = 'starCloudUid'; static const String starCloudUserLoginInfo = 'starCloudUserLoginInfo'; } diff --git a/lib/views/device/searchDevice/search_device_controller.dart b/lib/views/device/searchDevice/search_device_controller.dart index db92a01..32afc6d 100644 --- a/lib/views/device/searchDevice/search_device_controller.dart +++ b/lib/views/device/searchDevice/search_device_controller.dart @@ -1,6 +1,10 @@ import 'dart:math'; import 'package:get/get.dart'; +import 'package:starcloud/entity/star_cloud_lock_list.dart'; +import 'package:starcloud/entity/star_cloud_scan_result.dart'; +import 'package:starcloud/sdk/sdk_device_operate_extension.dart'; +import 'package:starcloud/sdk/starcloud.dart'; import 'package:starwork_flutter/base/app_logger.dart'; import 'package:starwork_flutter/base/app_permission.dart'; import 'package:starwork_flutter/base/base_controller.dart'; @@ -24,7 +28,7 @@ class SearchDeviceController extends BaseController { final RxBool isSearching = false.obs; // 设备列表管理 - final RxList deviceList = [].obs; + final RxList deviceList = [].obs; // 权限状态标识 final RxBool permissionsGranted = false.obs; @@ -34,13 +38,20 @@ class SearchDeviceController extends BaseController { super.onInit(); // 异步初始化权限 - _initializePermissions(); + // await _initializePermissions(); + } + + @override + void onReady() { + super.onReady(); + // 开始搜索 + _startBluetoothSearch(); } @override void onClose() { - // 停止搜索 - BleService().stopBluetoothSearch(); + StarCloudSDK.instance.stopScan(onError: (err) {}); + isSearching.value = false; super.onClose(); } @@ -74,25 +85,17 @@ class SearchDeviceController extends BaseController { /// 启动蓝牙搜索 Future _startBluetoothSearch() async { - if (!permissionsGranted.value) { - AppLogger.warn('⚠️ 权限未就绪,无法开始搜索'); - return; - } - try { - AppLogger.highlight('🔍 开始启动蓝牙搜索...'); - // 清空设备列表 deviceList.clear(); // 更新搜索状态 isSearching.value = true; - // 启动搜索 - BleService().enableBluetoothSearch(onDeviceFound: _onDeviceFound); - - // 定期更新搜索状态 - _updateSearchingStatus(); + // 启动搜索设备 + StarCloudSDK.instance.scanDeviceList(onScan: (List deviceListResult) { + deviceList.value = deviceListResult; + }); } catch (e, stackTrace) { AppLogger.error('启动蓝牙搜索失败', error: e, stackTrace: stackTrace); isSearching.value = false; @@ -100,44 +103,6 @@ class SearchDeviceController extends BaseController { } } - /// 定期更新搜索状态 - void _updateSearchingStatus() { - // 每秒检查一次搜索状态 - Future.delayed(const Duration(seconds: 1), () { - if (isSearching.value) { - bool actuallyScanning = BleService().isScanningNow; - if (isSearching.value != actuallyScanning) { - isSearching.value = actuallyScanning; - if (!actuallyScanning) { - AppLogger.highlight('🔍 搜索已停止'); - isSearching.value = false; - } - } - - // 如果还在搜索,继续检查 - if (actuallyScanning) { - _updateSearchingStatus(); - } - } - }); - } - - /// 搜索结果回调 - void _onDeviceFound(ScanDeviceInfo device) { - AppLogger.highlight('📲 发现新设备: ${device.advName}'); - - // 检查是否已存在相同设备(避免重复添加) - bool exists = deviceList.any((existingDevice) => existingDevice.rawDeviceInfo.device.remoteId == device.rawDeviceInfo.device.remoteId); - - if (!exists) { - deviceList.add(device); - deviceList.refresh(); - AppLogger.debug('✅ 设备已添加到列表,当前设备数量: ${deviceList.length},设备信息:${deviceList.toString()}'); - } else { - AppLogger.debug('⚠️ 设备已存在,跳过添加'); - } - } - // 刷新设备数据 Future refreshDevices() async { AppLogger.highlight('🔄 开始刷新设备列表'); @@ -149,8 +114,7 @@ class SearchDeviceController extends BaseController { } try { - // 停止当前搜索 - BleService().stopBluetoothSearch(); + StarCloudSDK.instance.stopScan(onError: (err) {}); isSearching.value = false; // 清空设备列表 @@ -173,95 +137,29 @@ class SearchDeviceController extends BaseController { /// 1.获取锁公钥 /// 2.获取锁私钥 /// 3.注册管理员密码 - void connectingDevices(ScanDeviceInfo device) async { + void connectingDevices(StarCloudScanResult device) async { + showLoading(); try { - showLoading(); - // 停止搜索 - BleService().stopBluetoothSearch(); - isSearching.value = false; - - // 创建命令 - BleCmdGetPublicKey getPublicKeyCmd = BleCmdGetPublicKey(lockId: device.advName); - - // 发送命令,允许自动连接和搜索设备 - GetPublicKeyResponse? publicKeyResponse = await BleService().sendCommand( - command: getPublicKeyCmd, - targetDeviceName: device.advName, - // 通过名称搜索设备 - autoConnectIfNeeded: true, - ); - if (publicKeyResponse != null && publicKeyResponse.isSuccess) { - AppLogger.info('🎯 获取公钥成功: ${publicKeyResponse.publicKeyHex}'); - await SharedPreferencesUtils.saveIntList(CacheKeys.lockPublicKey, publicKeyResponse.publicKey); - BleCmdGetPrivateKey getPrivateKeyCmd = BleCmdGetPrivateKey( - lockId: device.advName, - keyId: '1', - authUserID: '1', - nowTime: DateTime.now().millisecondsSinceEpoch ~/ 1000, - publicKey: publicKeyResponse.publicKey, + var cacheStarCloudUserName = await SharedPreferencesUtils.getString(CacheKeys.starCloudUserName); + var starCloudPassword = await SharedPreferencesUtils.getString(CacheKeys.starCloudPassword); + var starCloudUid = await SharedPreferencesUtils.getString(CacheKeys.starCloudUid); + if (cacheStarCloudUserName == null || starCloudPassword == null || starCloudUid == null) { + StarCloudSDK.instance.createCloudUser( + onError: (err) {}, + onSuccess: (userInfo) { + SharedPreferencesUtils.setString(CacheKeys.starCloudUserName, userInfo.username); + SharedPreferencesUtils.setString(CacheKeys.starCloudPassword, userInfo.password); + SharedPreferencesUtils.setString(CacheKeys.starCloudUid, userInfo.uid.toString()); + }, ); - - // 发送命令,允许自动连接和搜索设备 - GetPrivateKeyResponse? privateKeyResponse = await BleService().sendCommand( - command: getPrivateKeyCmd, - targetDeviceName: device.advName, - // 通过名称搜索设备 - autoConnectIfNeeded: true, - ); - if (privateKeyResponse != null && privateKeyResponse.isSuccess) { - await SharedPreferencesUtils.saveIntList(CacheKeys.lockCommKey, privateKeyResponse.commKey); - await SharedPreferencesUtils.saveIntList(CacheKeys.lockSignKey, privateKeyResponse.signKey); - AppLogger.info('🎯 获取私钥成功: ${privateKeyResponse.toString()}'); - - // 更新缓存的私钥,以便在解密时使用 - BleService.setCachedPrivateKey(privateKeyResponse.commKey); - - //读取锁状态 - BleCmdReadLockStatus readLockStatusCmd = BleCmdReadLockStatus( - lockId: device.advName, - userId: '1', - timeStamp: DateTime.now().millisecondsSinceEpoch ~/ 1000, - localUnix: 0, - privateKey: privateKeyResponse.commKey, - ); - // 发送命令,允许自动连接和搜索设备 - ReadLockStatusResponse? readLockStatusResponse = await BleService().sendCommand( - command: readLockStatusCmd, - targetDeviceName: device.advName, - // 通过名称搜索设备 - autoConnectIfNeeded: true, - ); - if (readLockStatusResponse != null && readLockStatusResponse.isSuccess) { - AppLogger.highlight('readLockStatusResponse:${readLockStatusResponse}'); - final Random rng = Random(); - // 生成 100000 到 999999 之间的随机整数 - final int number = rng.nextInt(900000) + 100000; - //读取锁状态 - BleCmdAddAdmin addAdminCmd = BleCmdAddAdmin( - lockId: device.advName, - userId: '13655', - privateKey: privateKeyResponse.commKey, - authUserId: '13655', - keyId: '1', - startDate: DateTime.now().millisecondsSinceEpoch, - expireDate: 0x11223344, - password: number.toString(), - token: [0, 0, 0, 0], - publicKey: publicKeyResponse.publicKey, - ); - // 发送命令,允许自动连接和搜索设备 - BleAddAdminResponse? addAdminResponse = await BleService().sendCommand( - command: addAdminCmd, - targetDeviceName: device.advName, - // 通过名称搜索设备 - autoConnectIfNeeded: true, - ); - AppLogger.highlight('addAdminResponse:${addAdminResponse}'); - } - } - } else { - AppLogger.warn('⚠️ 命令发送完成,但未收到有效响应'); } + StarCloudSDK.instance.pairDevice( + onError: (err) {}, + onSuccess: (StarCloudLock lockInfo) { + AppLogger.highlight('lockInfo:${lockInfo.toString()}'); + }, + scanResult: device, + ); } catch (e, stackTrace) { AppLogger.error('连接设备失败', error: e, stackTrace: stackTrace); showToast('连接失败,请重试'); diff --git a/lib/views/device/searchDevice/search_device_view.dart b/lib/views/device/searchDevice/search_device_view.dart index 8e7a2f5..1e14906 100644 --- a/lib/views/device/searchDevice/search_device_view.dart +++ b/lib/views/device/searchDevice/search_device_view.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; +import 'package:starcloud/entity/star_cloud_scan_result.dart'; import 'package:starwork_flutter/ble/model/scan_device_info.dart'; import 'package:starwork_flutter/views/device/searchDevice/search_device_controller.dart'; @@ -171,7 +172,7 @@ class SearchDeviceView extends GetView { ); } - _buildItem({required ScanDeviceInfo device, required int index}) { + _buildItem({required StarCloudScanResult device, required int index}) { return GestureDetector( onTap: () { controller.connectingDevices(device); diff --git a/lib/views/login/inputVerificationCode/input_verification_code_controller.dart b/lib/views/login/inputVerificationCode/input_verification_code_controller.dart index 887b568..1d86f5a 100644 --- a/lib/views/login/inputVerificationCode/input_verification_code_controller.dart +++ b/lib/views/login/inputVerificationCode/input_verification_code_controller.dart @@ -1,6 +1,8 @@ import 'dart:async'; import 'package:get/get.dart'; +import 'package:starcloud/sdk/entity/cloud_user_info.dart'; +import 'package:starcloud/sdk/starcloud.dart'; import 'package:starwork_flutter/api/api_response.dart'; import 'package:starwork_flutter/api/model/common/request/send_validation_code_request.dart'; import 'package:starwork_flutter/api/model/starcloud/request/starcloud_create_user_request.dart'; @@ -92,6 +94,7 @@ class InputVerificationCodeController extends BaseController { CacheKeys.token, validationCodeLoginResult.data!.token, ); + Get.offAllNamed(AppRoutes.main); } else { showError(message: validationCodeLoginResult.errorMsg!); diff --git a/pubspec.lock b/pubspec.lock index 6b9ce98..a8d21f4 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -151,7 +151,7 @@ packages: source: sdk version: "0.0.0" flutter_blue_plus: - dependency: "direct main" + dependency: transitive description: name: flutter_blue_plus sha256: "1901a42ade7a8f9793a3655983ef0899565294b12a2a57a2c3e33813930f4a34" @@ -578,6 +578,13 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "1.11.1" + starcloud: + dependency: "direct main" + description: + path: "../starcloud-sdk-flutter" + relative: true + source: path + version: "0.1.2" stream_channel: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 429d4b2..5d48235 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -36,8 +36,9 @@ dependencies: carousel_slider: ^5.1.1 # 气泡提示框 super_tooltip: ^2.0.8 - # 蓝牙库 - flutter_blue_plus: ^1.35.7 + # 星云sdk + starcloud: + path: ../starcloud-sdk-flutter # 加解密库 crypto: ^3.0.3