import 'package:logger/web.dart'; import '../../../data/services/ble_manager.dart'; import '../../../data/models/appconfig.dart'; import '../../../data/models/appconfig_model.dart'; import 'package:get/get.dart'; /// 版本管理服务 /// 负责处理设备版本信息获取、版本比较等功能 class VersionManager { final BleManager _bleManager = Get.find(); final int maxRetryAttempts = 3; int currentRetryCount = 0; /// 获取当前设备版本信息 /// 返回包含当前版本、产品ID和设备信息的Map /// 抛出异常如果获取失败 Future> getCurrentVersionInfo() async { DeviceInfo? deviceInfo = _bleManager.deviceInfo.value; // 重试机制获取设备信息 while (currentRetryCount < maxRetryAttempts) { deviceInfo = _bleManager.deviceInfo.value; if (deviceInfo != null && deviceInfo.firmwareVersion.isNotEmpty && deviceInfo.firmwareProductId.isNotEmpty) { break; } await _bleManager.fetchDeviceInfo(); await Future.delayed(const Duration(seconds: 5)); currentRetryCount++; } if (deviceInfo == null || deviceInfo.firmwareVersion.isEmpty || deviceInfo.firmwareProductId.isEmpty) { throw "获取设备信息失败,请检查连接"; } // 验证固件版本格式 final firmwareParts = deviceInfo.firmwareVersion.split('.'); final firstPart = firmwareParts.sublist(0, 3).join('.'); final secondPart = firmwareParts.sublist(3).join('.'); Logger().d("firstPart: $firstPart, secondPart: $secondPart"); if (firstPart != secondPart) { throw "固件版本格式错误:${deviceInfo.firmwareVersion}"; } return { 'currentVersion': firstPart, 'productId': deviceInfo.firmwareProductId, 'deviceInfo': deviceInfo, }; } /// 获取最新版本信息 /// 返回包含最新版本、更新描述和更新包地址的Map /// 抛出异常如果获取失败 Future> getLatestVersionInfo() async { DBProduct? product = AppConfig.getproduct("DeapSound"); if (product == null) { throw "无法获取产品信息"; } return { 'latestVersion': product.version ?? "", 'updateDescription': product.updatedescription ?? "", 'updatePackageAddress': product.updatepackageaddress ?? "", }; } /// 比较版本号,判断是否有新版本可用 /// [currentVersion] 当前版本号 /// [latestVersion] 最新版本号 /// 返回true表示有新版本可用(支持升级和降级) bool isNewVersionAvailable(String currentVersion, String latestVersion) { try { List currentParts = currentVersion .split('.') .map((e) => int.parse(e.trim())) .toList(); List latestParts = latestVersion.split('.').map((e) => int.parse(e.trim())).toList(); // 确保两个版本号长度一致,短的用0补齐 int maxLength = currentParts.length > latestParts.length ? currentParts.length : latestParts.length; while (currentParts.length < maxLength) { currentParts.add(0); } while (latestParts.length < maxLength) { latestParts.add(0); } // 比较每一段,只要有不同就返回true(支持升级和降级) for (int i = 0; i < maxLength; i++) { if (latestParts[i] != currentParts[i]) { return true; } } return false; } catch (e) { Logger().d('版本比较错误: $e'); return false; } } }