Browse Source

ota升级代码加入,目前报错设备认证失败

newdev_shunjiawei
fdp 1 year ago
parent
commit
0256946573
  1. 6
      lib/data/services/ble_manager.dart
  2. 124
      lib/modules/ota_upgrade/controllers/ota_upgrade_controller.dart
  3. 1
      local_plugins/ble_service/android/build.gradle.kts
  4. BIN
      local_plugins/ble_service/android/libs/jl_audio_decode_V2.0.0_20005.aar
  5. BIN
      local_plugins/ble_service/android/libs/jl_bt_ota_V1.9.2-release.aar
  6. 113
      local_plugins/ble_service/android/src/main/kotlin/com/yunqiinnovation/ble_service/BleService.kt
  7. 116
      local_plugins/ble_service/android/src/main/kotlin/com/yunqiinnovation/ble_service/OTAManager.kt
  8. 9
      local_plugins/jl_ota/android/build.gradle
  9. BIN
      local_plugins/jl_ota/android/libs/jl_bt_ota_V1.9.0-release.aar
  10. 2
      local_plugins/jl_ota/android/settings.gradle
  11. 255
      local_plugins/jl_ota/android/src/main/kotlin/com/yunqiinnovation/jl_ota/JlOtaPlugin.kt

6
lib/data/services/ble_manager.dart

@ -54,7 +54,7 @@ class DeviceInfo {
this.rightEarCharging = false,
this.caseCharging = false,
this.firmwareVersion = '',
this.firmwareProductId = 's3',
this.firmwareProductId = '',
this.firmwareProductColor = '',
DateTime? lastUpdated,
}) : lastUpdated = lastUpdated ?? DateTime.now();
@ -168,7 +168,7 @@ class BleManager extends GetxService {
Future.delayed(const Duration(milliseconds: 300), () {
// 可选:检查是否仍处于连接状态
if (_isConnected.value) {
fetchDeviceInfo();
// fetchDeviceInfo();
}
});
} else if (state == BleConnectionState.disconnected ||
@ -531,7 +531,7 @@ class BleManager extends GetxService {
// 如果设备信息存在,则获取详细信息
if (deviceInfo.value != null) {
// 获取详细设备信息
fetchDeviceInfo();
// fetchDeviceInfo();
}
}
} else {

124
lib/modules/ota_upgrade/controllers/ota_upgrade_controller.dart

@ -22,7 +22,7 @@ class OtaUpgradeController extends GetxController {
final isUpdateAvailable = true.obs;
final RxDouble progress = 0.0.obs;
final JlOta jla = JlOta();
// 蓝牙服务
final _bleManager = Get.find<BleManager>();
@override
@ -53,68 +53,65 @@ class OtaUpgradeController extends GetxController {
}
Future<void> _getCurrentVersion() async {
JlOta().getPlatformVersion();
//try {
// // 添加获取设备信息的重试机制
// DeviceInfo? deviceInfo = _bleManager.deviceInfo.value;
// // 第一次检查设备信息
// if (deviceInfo == null) {
// // 显示加载提示
// isFetchingDeviceInfo.value = true;
// // 尝试重新获取设备信息
// await _bleManager.fetchDeviceInfo();
// // 等待后再次获取设备信息
// deviceInfo = _bleManager.deviceInfo.value;
// isFetchingDeviceInfo.value = false;
// // 仍然为空则抛出异常
// if (deviceInfo == null) {
// throw const FormatException('无法获取设备信息,请检查设备连接');
// }
// }
// // 检查固件信息有效性
// if (deviceInfo.firmwareVersion.isEmpty
// // ||
// // deviceInfo.firmwareProductId.isEmpty
// ) {
// throw const FormatException('设备固件信息不完整');
// }
// // 正常流程
// currentVersion.value = "0"; //deviceInfo.firmwareVersion;
// // API请求
// final response = await Api.getequipmentinfo({
// "id": "s3",
// });
// // 处理API响应
// if (response['info'] == null) {
// throw const FormatException('API 响应格式错误');
// }
// final resp = OtaConfigResp.fromJson(response);
// latestVersion.value = resp.systemversion!;
// updatepackageaddress = resp.updatepackageaddress!;
// // 版本检查
// isUpdateAvailable.value = _isNewVersionAvailable(resp.systemversion!);
// } catch (e) {
// // 统一错误处理
// errorMessage.value = e.toString();
// Get.snackbar('错误', e.toString(),
// snackPosition: SnackPosition.BOTTOM,
// backgroundColor: Colors.red,
// colorText: Colors.white);
// // 重要:重新抛出异常以便上层处理(可选)
// } finally {
// isFetchingDeviceInfo.value = false;
// }
try {
// 添加获取设备信息的重试机制
DeviceInfo? deviceInfo = _bleManager.deviceInfo.value;
// 第一次检查设备信息
if (deviceInfo == null) {
// 显示加载提示
isFetchingDeviceInfo.value = true;
// 尝试重新获取设备信息
await _bleManager.fetchDeviceInfo();
// 等待后再次获取设备信息
deviceInfo = _bleManager.deviceInfo.value;
isFetchingDeviceInfo.value = false;
// 仍然为空则抛出异常
if (deviceInfo == null) {
throw const FormatException('无法获取设备信息,请检查设备连接');
}
}
// 检查固件信息有效性
if (deviceInfo.firmwareVersion.isEmpty ||
deviceInfo.firmwareProductId.isEmpty) {
throw const FormatException('设备固件信息不完整');
}
// 正常流程
currentVersion.value = deviceInfo.firmwareVersion;
print('getequipmentinfo,id: ${deviceInfo.firmwareProductId}');
// API请求
final response = await Api.getequipmentinfo({
"id": deviceInfo.firmwareProductId,
});
// 处理API响应
if (response['info'] == null) {
throw const FormatException('API 响应格式错误');
}
final resp = OtaConfigResp.fromJson(response);
print('getequipmentinfo,resp.systemversion: ${resp.systemversion}');
latestVersion.value = "1";
updatepackageaddress = resp.updatepackageaddress!;
// 版本检查
isUpdateAvailable.value = _isNewVersionAvailable(resp.systemversion!);
} catch (e) {
// 统一错误处理
errorMessage.value = e.toString();
Get.snackbar('错误', e.toString(),
snackPosition: SnackPosition.BOTTOM,
backgroundColor: Colors.red,
colorText: Colors.white);
// 重要:重新抛出异常以便上层处理(可选)
} finally {
isFetchingDeviceInfo.value = false;
}
}
// 版本比较方法优化
@ -295,6 +292,7 @@ class OtaUpgradeController extends GetxController {
// 开始升级
void _installApp(String path) async {
jla.getPlatformVersion();
// JlOtaPlugin()
// final File file = File(path);
// if (await file.exists()) {

1
local_plugins/ble_service/android/build.gradle.kts

@ -30,5 +30,6 @@ dependencies {
implementation("androidx.core:core-ktx:1.13.1")
// 使用从本地Maven仓库引用的AAR依赖
implementation("com.jieli.audio:jl_audio_decode:2.0.0")
implementation("com.jieli.jl_bt_ota:jl_bt_ota:1.9.2")
implementation(project(":deepvoice_utils"))
}

BIN
local_plugins/ble_service/android/libs/jl_audio_decode_V2.0.0_20005.aar

Binary file not shown.

BIN
local_plugins/ble_service/android/libs/jl_bt_ota_V1.9.2-release.aar

Binary file not shown.

113
local_plugins/ble_service/android/src/main/kotlin/com/yunqiinnovation/ble_service/BleService.kt

@ -30,6 +30,10 @@ import com.jieli.jl_audio_decode.callback.OnStateCallback
import com.jieli.jl_audio_decode.opus.OpusManager
import com.jieli.jl_audio_decode.exceptions.OpusException
import com.yunqiinnovation.ble_service.BleCompanionManager
import com.yunqiinnovation.ble_service.OTAManager
import com.jieli.jl_bt_ota.model.BluetoothOTAConfigure;
import com.jieli.jl_bt_ota.constant.ErrorCode;
import com.jieli.jl_bt_ota.constant.StateCode;
/**
* BLE服务类:提供蓝牙低功耗设备的扫描、连接和通信功能
@ -96,6 +100,8 @@ object BleService {
private var opusManager: OpusManager? = null
private val mainHandler = Handler(Looper.getMainLooper())
// ota解码器实例
var otaManager: OTAManager? = null
// 初始化状态
private var isInitialized = false
@ -111,6 +117,19 @@ object BleService {
try {
this.context = appContext.applicationContext
otaManager = OTAManager(this.context).apply {
// 设置数据回调
setDataCallback(object : OTAManager.DataCallback {
override fun onDataReceived(device: BluetoothDevice?, data: ByteArray?) {
data?.let {
FileLogger.i("BleService", "收到数据:${it.size} 字节")
FileLogger.i("BleService", "认证交互数据${it.contentToString()}")
// 移除次数限制,除非明确需要
otaManager?.onReceiveDeviceData(device, it)
}
}
})
}
// 初始化蓝牙管理器和适配器
bluetoothManager =
context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
@ -120,11 +139,13 @@ object BleService {
// 初始化Handler
scanHandler = Handler(Looper.getMainLooper())
// 初始化OpusManager
// 初始化OpusManager和OTAManager
try {
opusManager = OpusManager()
startOpusStreamDecoding()
FileLogger.d(TAG, "OpusManager初始化成功")
} catch (e: OpusException) {
FileLogger.e(TAG, "OpusManager初始化失败: ${e.message}", e)
// 根据需要决定是否因为Opus初始化失败而返回false
@ -326,17 +347,17 @@ object BleService {
try {
// 创建 BleCompanionManager 实例
val companionManager = BleCompanionManager(context)
// 获取已配对的 MAC 地址
val pairedMac = companionManager.getPairedMacAddress()
if (pairedMac.isNullOrEmpty()) {
FileLogger.w(TAG, "未找到已配对的设备 MAC 地址")
return
}
FileLogger.i(TAG, "检测到已配对设备,MAC: $pairedMac,尝试连接")
// 调用现有的 connect 方法
connect(pairedMac)
} catch (e: Exception) {
@ -344,7 +365,8 @@ object BleService {
updateConnectionState(BleConst.STATE_ERROR)
}
}
/**
* 连接到指定地址的BLE设备
* @param address 设备MAC地址
@ -365,6 +387,8 @@ object BleService {
disconnectGatt()
try {
// 创建新连接
val device = adapter.getRemoteDevice(address)
updateConnectionState(BleConst.STATE_CONNECTING)
@ -372,6 +396,8 @@ object BleService {
bluetoothGatt = device.connectGatt(
context, false, gattCallback, BluetoothDevice.TRANSPORT_LE
)
} catch (e: Exception) {
FileLogger.e(TAG, "连接设备失败: ${e.message}", e)
updateConnectionState(BleConst.STATE_ERROR)
@ -404,6 +430,45 @@ object BleService {
}
}
fun startOTA() {
try {
otaManager?.startOTA(CustomUpdateCallback(context, null))
FileLogger.i(TAG, "OTA 升级已启动")
} catch (e: IllegalStateException) {
FileLogger.e(TAG, "OTA 启动失败: ${e.message}")
disconnectGatt()
}
}
// 配置OTA
fun configureOTA() {
try {
val firmwarePath =
context.getExternalFilesDir("downloads/ota_upgrades")?.path + "/1.ufw"
val file = File(firmwarePath)
if (!file.exists()) {
// throw IOException("Firmware file not found")
FileLogger.i(TAG, "Firmware file not found")
}
val bluetoothOption = BluetoothOTAConfigure().apply {
priority = BluetoothOTAConfigure.PREFER_BLE
isUseReconnect = true
isUseAuthDevice = true
mtu = 512
isNeedChangeMtu = false // 确保MTU请求生效
isUseJLServer = false
firmwareFilePath = firmwarePath
}
otaManager?.configure(bluetoothOption) ?: run {
FileLogger.e(TAG, "OTA Manager未初始化")
}
} catch (e: Exception) {
FileLogger.e(TAG, "OTA配置失败: ${e.message}")
// 处理错误
}
}
/**
* 更新连接状态并通知回调
*/
@ -416,16 +481,37 @@ object BleService {
* GATT回调
*/
private val gattCallback = object : BluetoothGattCallback() {
override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) {
if (status == BluetoothGatt.GATT_SUCCESS) {
FileLogger.i(TAG, "MTU 更新成功: $mtu")
configureOTA()
startOTA()
} else {
FileLogger.e(TAG, "MTU 更新失败: status=$status")
}
}
override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
when {
status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED -> {
updateConnectionState(BleConst.STATE_CONNECTED)
g.discoverServices()
FileLogger.i(TAG, "连接成功,开始 MTU 协商")
otaManager?.onBtDeviceConnection(g.device, StateCode.CONNECTION_OK)
g.requestMtu(512) // 触发 MTU 修改流程
}
newState == BluetoothProfile.STATE_DISCONNECTED -> {
updateConnectionState(BleConst.STATE_DISCONNECTED)
disconnectGatt()
otaManager?.onBtDeviceConnection(g.device, StateCode.CONNECTION_CONNECTING)
g.close()
otaManager?.release();
}
else -> {
@ -480,10 +566,12 @@ object BleService {
when (c.uuid) {
// 音频特征数据
BleConst.RECEIVE_AUDIO_CHAR_UUID -> {
FileLogger.i(TAG, "收到音频特征数据")
processAudioData(data)
}
// 通知特征数据(命令和控制)
BleConst.NOTIFY_CHAR_UUID -> {
FileLogger.i(TAG, "收到通知特征数据(命令和控制)")
// 判断数据类型
when {
// 设备响应 (0xBB开头)
@ -505,6 +593,7 @@ object BleService {
}
// 其他未知特征
else -> {
FileLogger.i(TAG, "收到其他未知特征")
FileLogger.d(
TAG,
"收到未知特征数据: ${c.uuid}, 数据=${
@ -529,8 +618,10 @@ object BleService {
override fun onDescriptorWrite(
g: BluetoothGatt, d: BluetoothGattDescriptor, status: Int
) {
if (status == BluetoothGatt.GATT_SUCCESS)
if (status == BluetoothGatt.GATT_SUCCESS) {
FileLogger.i(TAG, "通知描述符写入成功: ${d.characteristic.uuid}")
}
}
}
@ -646,18 +737,22 @@ object BleService {
if (responseData.isNotEmpty()) {
// 转换为字符串前,确认是否是有效的ASCII字符
val version =
responseData.joinToString(".") { (it.toInt() and 0xFF).toString() }
responseData
.map { it.toInt() and 0xFF } // 转为无符号整数 (0-255)
.dropWhile { it == 0xFF } // 仅丢弃开头的连续 255
.joinToString(".") { it.toString() }
resultMap["version"] = version
FileLogger.i(TAG, "接收到目标版本号: $version")
}
notifyDeviceInfoReceived(cmdType, resultMap)
}
BleConst.CMD_GET_PRODUCT_ID -> {
val resultMap = mutableMapOf<String, Any>(
"success" to true,
"command" to "productInfo",
"command" to "productId",
"rawData" to responseData
)

116
local_plugins/ble_service/android/src/main/kotlin/com/yunqiinnovation/ble_service/OTAManager.kt

@ -0,0 +1,116 @@
package com.yunqiinnovation.ble_service
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothProfile
import android.content.Context
import com.jieli.jl_bt_ota.constant.ErrorCode;
import com.jieli.jl_bt_ota.constant.StateCode;
import com.jieli.jl_bt_ota.impl.BluetoothOTAManager;
import com.jieli.jl_bt_ota.interfaces.BtEventCallback;
import com.jieli.jl_bt_ota.interfaces.IActionCallback;
import com.jieli.jl_bt_ota.interfaces.IUpgradeCallback;
import com.jieli.jl_bt_ota.model.BluetoothOTAConfigure;
import com.jieli.jl_bt_ota.model.base.BaseError;
import com.jieli.jl_bt_ota.model.response.TargetInfoResponse;
import android.util.Log
import java.util.*
class CustomUpdateCallback(
val context: Context,
val device: BluetoothDevice?
) : IUpgradeCallback {
companion object {
private const val TAG = "JlOtaPlugin"
private const val CHANNEL_NAME = "com.yunqiinnovation.jl_ota"
private const val EVENT_CHANNEL_NAME = "com.yunqiinnovation.jl_ota/events"
}
override fun onStartOTA() {
Log.d(TAG, "onStartOTA开始升级")
// viewModel.otaStateMLD.value = OTAStart(device)
}
override fun onNeedReconnect(addr: String?, isNewReconnectWay: Boolean) {
Log.d(TAG, "onNeedReconnect需要重新链接")
}
override fun onProgress(type: Int, progress: Float) {
Log.d(TAG, "onProgress正在进展")
//viewModel.otaStateMLD.value = OTAWorking(device, type, progress)
}
override fun onStopOTA() {
Log.d(TAG, "onStartOTA停止升级")
}
override fun onCancelOTA() {
Log.d(TAG, "onCancelOTA取消升级")
}
override fun onError(error: BaseError?) {
val errorMessage = error?.message ?: "Unknown error"
Log.e(TAG, "升级失败: ${error?.message ?: "未知错误"}")
// 如果需要打印完整错误对象信息(假设BaseError有重写toString())
Log.d(TAG, "完整错误对象: ${error ?: "null"}")
}
}
class OTAManager(context: Context) : BluetoothOTAManager(context) {
// 定义回调接口
interface DataCallback {
fun onDataReceived(device: BluetoothDevice?, data: ByteArray?)
}
// 保存回调的实例
private var dataCallback: DataCallback? = null
// 设置回调的方法
fun setDataCallback(callback: DataCallback) {
this.dataCallback = callback
}
override fun getConnectedDevice(): BluetoothDevice? {
// 这里可以添加空实现的注释说明
Log.i(TAG, "ota数据发送getConnectedDevice")
return null
}
override fun getConnectedBluetoothGatt(): BluetoothGatt? {
// 这里可以添加空实现的注释说明
Log.i(TAG, "ota数据发送getConnectedBluetoothGatt")
return null
}
override fun connectBluetoothDevice(bluetoothDevice: BluetoothDevice?) {
// 这里可以添加空实现的注释说明
Log.i(TAG, "ota数据发送connectBluetoothDevice")
}
override fun disconnectBluetoothDevice(bluetoothDevice: BluetoothDevice?) {
// 这里可以添加空实现的注释说明
Log.i(TAG, "ota数据发送disconnectBluetoothDevice")
}
/** 数据发送方法(协议无关) */
override fun sendDataToDevice(
bluetoothDevice: BluetoothDevice?,
bytes: ByteArray?
): Boolean {
Log.i(TAG, "ota数据发送${bluetoothDevice},${bytes?.size}")
// 触发回调,将数据回传给调用者
dataCallback?.onDataReceived(bluetoothDevice, bytes)
// context.onReceiveDeviceData(device, data);
return true
}
}

9
local_plugins/jl_ota/android/build.gradle

@ -18,9 +18,6 @@ allprojects {
repositories {
google()
mavenCentral()
flatDir {
dirs 'libs'
}
}
}
@ -51,8 +48,8 @@ android {
}
dependencies {
implementation(name: 'jl_bt_ota_V1.9.0-release', ext: 'aar')
implementation(project(":ble_service"))
// implementation project(':ble_service')
testImplementation("org.jetbrains.kotlin:kotlin-test")
testImplementation("org.mockito:mockito-core:5.0.0")
}
@ -68,4 +65,4 @@ android {
}
}
}
}
}

BIN
local_plugins/jl_ota/android/libs/jl_bt_ota_V1.9.0-release.aar

Binary file not shown.

2
local_plugins/jl_ota/android/settings.gradle

@ -1 +1 @@
rootProject.name = 'jl_ota'
rootProject.name = 'jl_ota'

255
local_plugins/jl_ota/android/src/main/kotlin/com/yunqiinnovation/jl_ota/JlOtaPlugin.kt

@ -14,32 +14,18 @@ import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.annotation.NonNull
//import com.yunqiinnovation.ble_service.BleService
import com.jieli.jl_bt_ota.constant.ErrorCode;
import com.jieli.jl_bt_ota.constant.StateCode;
import com.jieli.jl_bt_ota.impl.BluetoothOTAManager;
import com.jieli.jl_bt_ota.interfaces.BtEventCallback;
import com.jieli.jl_bt_ota.interfaces.IActionCallback;
import com.jieli.jl_bt_ota.interfaces.IUpgradeCallback;
import com.jieli.jl_bt_ota.model.BluetoothOTAConfigure;
import com.jieli.jl_bt_ota.model.base.BaseError;
import com.jieli.jl_bt_ota.model.response.TargetInfoResponse;
import com.yunqiinnovation.ble_service.BleService
/** JlOtaPlugin */
class JlOtaPlugin(): FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel : MethodChannel
private lateinit var context: Context
private lateinit var eventChannel: EventChannel
private var streamSink: EventChannel.EventSink? = null
/// BLE服务实例
private var otaManager: OTAManager? = null
class JlOtaPlugin() : FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel: MethodChannel
private lateinit var context: Context
private lateinit var eventChannel: EventChannel
private var streamSink: EventChannel.EventSink? = null
companion object {
private const val TAG = "JlOtaPlugin"
@ -48,10 +34,11 @@ class JlOtaPlugin(): FlutterPlugin, MethodCallHandler {
}
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
context = flutterPluginBinding.applicationContext
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "jl_ota")
channel.setMethodCallHandler(this)
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
context = flutterPluginBinding.applicationContext
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "jl_ota")
channel.setMethodCallHandler(this)
eventChannel = EventChannel(flutterPluginBinding.binaryMessenger, EVENT_CHANNEL_NAME)
@ -65,215 +52,25 @@ class JlOtaPlugin(): FlutterPlugin, MethodCallHandler {
}
})
otaManager = OTAManager(context)
// otaManager.getBluetoothOption().setFirmwareFilePath(filePath);
// otaManager.startOTA(new IUpgradeCallback() {
// }
}
override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "getPlatformVersion") {
val bluetoothOption = BluetoothOTAConfigure()
//选择通讯方式
bluetoothOption.priority = BluetoothOTAConfigure.PREFER_BLE
//是否需要自定义回连方式(默认不需要,如需要自定义回连方式,需要客户自行实现)
bluetoothOption.isUseReconnect = true
//是否启用设备认证流程(与固件工程师确认)
bluetoothOption.isUseAuthDevice = true
//设置BLE的MTU
bluetoothOption.mtu = 500
//是否需要改变BLE的MTU
bluetoothOption.isNeedChangeMtu = false
//是否启用杰理服务器(暂时不支持)
bluetoothOption.isUseJLServer = false
Log.d(TAG, "bluetoothOTAManager初始化成功")
//配置OTA参数
otaManager?.configure(bluetoothOption)
var filePath= "/storage/emulated/0/Android/data/com.yunqiinnovation.deepsound/files/downloads/ota_upgrades/1.ufw"
otaManager?.bluetoothOption?.firmwareFilePath = filePath
Log.d(TAG, "OpusManager路径成功${filePath}")
// Add ?. after bluetoothOption ^
otaManager?.startOTA(
CustomUpdateCallback(
context, null, this
)
)
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}
class OTAManager(context: Context) : BluetoothOTAManager(context) {
override fun getConnectedDevice(): BluetoothDevice? {
// 这里可以添加空实现的注释说明
return null
}
override fun getConnectedBluetoothGatt(): BluetoothGatt? {
// 这里可以添加空实现的注释说明
return null
}
override fun connectBluetoothDevice(bluetoothDevice: BluetoothDevice?) {
// 这里可以添加空实现的注释说明
override fun onMethodCall(call: MethodCall, result: Result) {
}
override fun disconnectBluetoothDevice
(bluetoothDevice: BluetoothDevice?) {
// 这里可以添加空实现的注释说明
if (call.method == "getPlatformVersion") {
}
/** 数据发送方法(协议无关) */
override fun sendDataToDevice(
bluetoothDevice: BluetoothDevice?,
bytes: ByteArray?
): Boolean {return true}
}
// BleService.otaManager?.configureOTA()
private class CustomUpdateCallback(
val context: Context,
val device: BluetoothDevice?,
val viewModel: JlOtaPlugin
) : IUpgradeCallback{
companion object {
private const val TAG = "JlOtaPlugin"
private const val CHANNEL_NAME = "com.yunqiinnovation.jl_ota"
private const val EVENT_CHANNEL_NAME = "com.yunqiinnovation.jl_ota/events"
}
override fun onStartOTA() {
Log.d(TAG, "onStartOTA开始升级")
// viewModel.otaStateMLD.value = OTAStart(device)
}
override fun onNeedReconnect(addr: String?, isNewReconnectWay: Boolean) {
Log.d(TAG, "onNeedReconnect需要重新链接")
// viewModel.otaStateMLD.value = OTAReconnect(device, addr, isNewReconnectWay)
// if (viewModel.isUseReconnectWay()) {
// viewModel.reconnectDev(addr, isNewReconnectWay)
// }
}
override fun onProgress(type: Int, progress: Float) {
Log.d(TAG, "onProgress正在进展")
//viewModel.otaStateMLD.value = OTAWorking(device, type, progress)
}
override fun onStopOTA() {
Log.d(TAG, "onStartOTA停止升级")
// viewModel.otaStateMLD.value =
// OTAEnd(device, ErrorCode.ERR_NONE, context.getString(R.string.ota_complete))
// val handler = Handler(Looper.getMainLooper())
// handler.postDelayed({
// // Log.d("ZHM", "onStopOTA: disconnectDevice connected : "+viewModel.bluetoothHelper.isConnected()+ " getConnectedDevice: "+viewModel.bluetoothHelper.getConnectedDevice())
// //变地址导致无法判断device是否一致
// if (viewModel.bluetoothHelper.isConnected()/* && BluetoothUtil.deviceEquals(
// device,
// viewModel.bluetoothHelper.getConnectedDevice()
// )*/
// ) {
// Log.d("ZHM", "onStopOTA: disconnectDevice")
// viewModel.bluetoothHelper.disconnectDevice(viewModel.otaManager.connectedDevice)
// }
// }, 500)
}
override fun onCancelOTA() {
Log.d(TAG, "onCancelOTA取消升级")
// viewModel.otaStateMLD.value =
// OTAEnd(
// device,
// ErrorCode.ERR_UNKNOWN,
// context.getString(R.string.ota_upgrade_cancel)
// )
}
override fun onError(error: BaseError?) {
Log.d(TAG, "onError升级错误")
// error?.let {
// viewModel.otaStateMLD.value = OTAEnd(device, it.subCode, it.message)
// }
// viewModel.bluetoothHelper.disconnectDevice(viewModel.otaManager.connectedDevice)//升级失败,断开设备,方便自动化继续升级
// BleService.otaManager?.startOTA()
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else {
result.notImplemented()
}
}
// class OtaDemo {
// private val otaManager = OTAManager(MainApplication.getInstance())
// fun initOTA(context: Context, firmwarePath: String) {
// val otaManager = JlOtaPlugin()
// val bluetoothOption = BluetoothOTAConfigure.createDefault().apply {
// priority = BluetoothOTAConfigure.PREFER_BLE
// useAuthDevice = true
// bleIntervalMs = 500
// timeoutMs = 3000
// mtu = 500
// needChangeMtu = false
// useReconnect = false
// setFirmwareFilePath(firmwarePath)
// }
// otaManager.configure(bluetoothOption)
// }
// fun otaFirmware(filePath: String) { // 方法名改为小写开头
// val otaManager = JlOtaPlugin()
// otaManager.registerBluetoothCallback(object : BtEventCallback {
// override fun onConnection(device: BluetoothDevice, status: Int) {
// if (status == StateCode.CONNECTION_OK) {
// if (otaManager.isOTA) return
// otaManager.queryMandatoryUpdate(object : IActionCallback<TargetInfoResponse> {
// override fun onSuccess(deviceInfo: TargetInfoResponse) {
// // 处理设备信息
// deviceInfo.versionCode
// deviceInfo.versionName
// deviceInfo.projectCode
// deviceInfo.uid
// deviceInfo.pid
// }
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
// override fun onError(baseError: BaseError) {
// if (baseError.code == ErrorCode.ERR_NONE &&
// baseError.subCode == ErrorCode.ERR_NONE) {
// val deviceInfo = otaManager.deviceInfo
// deviceInfo?.let {
// it.versionCode
// it.versionName
// it.projectCode
// it.uid
// it.pid
// }
// }
// }
// })
// }
// }
// })
// otaManager.bluetoothOption?.setFirmwareFilePath(filePath)
// otaManager.startOTA(object : IUpgradeCallback {
// override fun onStartOTA() = Unit
// override fun onNeedReconnect(addr: String, isNewReconnectWay: Boolean) {
// if (otaManager.bluetoothOption?.useReconnect == true) {
// // 处理自定义回连
// }
// }
// override fun onProgress(type: Int, progress: Float) = Unit
// override fun onStopOTA() = Unit
// override fun onCancelOTA() = Unit
// override fun onError(error: BaseError) = Unit
// })
}
// otaManager.release()
// }
//}
Loading…
Cancel
Save