fdp 1 year ago
parent
commit
84b0de987e
  1. 27
      lib/data/services/ble_manager.dart
  2. 146
      lib/data/services/speech_impl/volcano_tts_service.dart
  3. 4
      lib/modules/ota_upgrade/controllers/ota_upgrade_controller.dart
  4. 210
      lib/modules/settings/views/settings_view.dart
  5. 23
      local_plugins/ota/android/src/main/kotlin/com/example/ota/OtaPlugin.kt

27
lib/data/services/ble_manager.dart

@ -184,6 +184,19 @@ class BleManager extends GetxService {
state == BleConnectionState.error) { state == BleConnectionState.error) {
Logger.info('BLE设备已断开或发生错误'); Logger.info('BLE设备已断开或发生错误');
_isConnected.value = false; _isConnected.value = false;
// 更新设备信息Add commentMore actions
_updateDeviceInfoIfNeeded(
batteryLevel: 0,
leftEarBattery: 0,
rightEarBattery: 0,
caseBattery: 0,
leftEarCharging: false,
rightEarCharging: false,
caseCharging: false,
firmwareVersion: '',
firmwareProductId: '',
firmwareProductColor: '',
);
// 断开连接时不清除设备信息,保留最后的电量信息 // 断开连接时不清除设备信息,保留最后的电量信息
// 只有在需要完全清除设备时才重置信息 // 只有在需要完全清除设备时才重置信息
} }
@ -405,7 +418,7 @@ class BleManager extends GetxService {
// 使用保存的设备信息创建新的DeviceInfo对象 // 使用保存的设备信息创建新的DeviceInfo对象
String deviceAddress = _currentDeviceAddress ?? ""; String deviceAddress = _currentDeviceAddress ?? "";
String deviceName = _currentDeviceName ?? ""; String deviceName = _currentDeviceName ?? "";
Logger.info('创建新的设备信息对象: address=$deviceAddress, name=$deviceName'); Logger.info('创建新的设备信息对象: address=$deviceAddress, name=$deviceName');
deviceInfo.value = DeviceInfo( deviceInfo.value = DeviceInfo(
address: deviceAddress, address: deviceAddress,
@ -442,7 +455,7 @@ class BleManager extends GetxService {
// 创建初始设备信息对象 // 创建初始设备信息对象
String deviceAddress = _currentDeviceAddress ?? ""; String deviceAddress = _currentDeviceAddress ?? "";
String deviceName = _currentDeviceName ?? ""; String deviceName = _currentDeviceName ?? "";
Logger.info('初始化设备信息对象: address=$deviceAddress, name=$deviceName'); Logger.info('初始化设备信息对象: address=$deviceAddress, name=$deviceName');
deviceInfo.value = DeviceInfo( deviceInfo.value = DeviceInfo(
address: deviceAddress, address: deviceAddress,
@ -467,8 +480,9 @@ class BleManager extends GetxService {
_bleService.getProductId(), _bleService.getProductId(),
]); ]);
Logger.info('设备信息获取结果: 电池=${results[0]}, 版本=${results[1]}, 产品ID=${results[2]}'); Logger.info(
'设备信息获取结果: 电池=${results[0]}, 版本=${results[1]}, 产品ID=${results[2]}');
if (!results[0]) { if (!results[0]) {
Logger.warning('电池信息获取指令发送失败'); Logger.warning('电池信息获取指令发送失败');
} }
@ -788,9 +802,10 @@ class BleManager extends GetxService {
// 从蓝牙管理器获取设备名称 // 从蓝牙管理器获取设备名称
final bluetoothManager = Get.find<BluetoothManager>(); final bluetoothManager = Get.find<BluetoothManager>();
_currentDeviceName = bluetoothManager.currentDevice?.name ?? ""; _currentDeviceName = bluetoothManager.currentDevice?.name ?? "";
Logger.info('保存设备信息: address=$_currentDeviceAddress, name=$_currentDeviceName'); Logger.info(
'保存设备信息: address=$_currentDeviceAddress, name=$_currentDeviceName');
} }
return await _bleService.registerBackgroundScan(macAddress: macAddress); return await _bleService.registerBackgroundScan(macAddress: macAddress);
} catch (e) { } catch (e) {
Logger.error('注册后台扫描失败: ${e.toString()}'); Logger.error('注册后台扫描失败: ${e.toString()}');

146
lib/data/services/speech_impl/volcano_tts_service.dart

@ -9,82 +9,84 @@ import 'package:flutter_dotenv/flutter_dotenv.dart';
class VolcanoTtsService extends GetxService implements TtsService { class VolcanoTtsService extends GetxService implements TtsService {
/// 方法通道 /// 方法通道
static const MethodChannel _channel = MethodChannel('volcano_speech/tts'); static const MethodChannel _channel = MethodChannel('volcano_speech/tts');
/// 事件通道 /// 事件通道
static const EventChannel _eventChannel = EventChannel('volcano_speech/tts_events'); static const EventChannel _eventChannel =
EventChannel('volcano_speech/tts_events');
/// 音频数据通道 /// 音频数据通道
static const EventChannel _audioDataChannel = EventChannel('volcano_speech/tts_audio_data'); static const EventChannel _audioDataChannel =
EventChannel('volcano_speech/tts_audio_data');
/// 事件流控制器 /// 事件流控制器
final StreamController<TtsEvent> _eventStreamController = final StreamController<TtsEvent> _eventStreamController =
StreamController<TtsEvent>.broadcast(); StreamController<TtsEvent>.broadcast();
/// 音频数据流控制器 /// 音频数据流控制器
final StreamController<Uint8List> _audioDataStreamController = final StreamController<Uint8List> _audioDataStreamController =
StreamController<Uint8List>.broadcast(); StreamController<Uint8List>.broadcast();
/// 事件处理器 /// 事件处理器
StreamSubscription? _eventSubscription; StreamSubscription? _eventSubscription;
/// 音频数据处理器 /// 音频数据处理器
StreamSubscription? _audioDataSubscription; StreamSubscription? _audioDataSubscription;
/// 是否初始化完成 /// 是否初始化完成
bool _isInitialized = false; bool _isInitialized = false;
/// 当前语音名称 /// 当前语音名称
String _currentVoice = "zh_female_qingxin"; String _currentVoice = "zh_female_qingxin";
/// 是否启用音频回调 /// 是否启用音频回调
bool _isAudioCallbackEnabled = false; bool _isAudioCallbackEnabled = false;
@override @override
String get currentVoice => _currentVoice; String get currentVoice => _currentVoice;
@override @override
bool get isSpeaking => _isSpeaking; bool get isSpeaking => _isSpeaking;
/// 是否正在播放 /// 是否正在播放
bool _isSpeaking = false; bool _isSpeaking = false;
@override @override
Stream<TtsEvent> get onEvent => _eventStreamController.stream; Stream<TtsEvent> get onEvent => _eventStreamController.stream;
/// 音频数据流 /// 音频数据流
Stream<Uint8List> get onAudioData => _audioDataStreamController.stream; Stream<Uint8List> get onAudioData => _audioDataStreamController.stream;
/// 构造函数 /// 构造函数
VolcanoTtsService() { VolcanoTtsService() {
_setupEventListeners(); _setupEventListeners();
_setupAudioDataListeners(); _setupAudioDataListeners();
} }
/// 设置事件监听 /// 设置事件监听
void _setupEventListeners() { void _setupEventListeners() {
_eventSubscription = _eventChannel.receiveBroadcastStream().listen( _eventSubscription = _eventChannel.receiveBroadcastStream().listen(
(dynamic event) { (dynamic event) {
if (event is! Map) return; if (event is! Map) return;
final Map<dynamic, dynamic> eventMap = event; final Map<dynamic, dynamic> eventMap = event;
final String? type = eventMap['type'] as String?; final String? type = eventMap['type'] as String?;
switch (type) { switch (type) {
case 'started': case 'started':
_isSpeaking = true; _isSpeaking = true;
_eventStreamController.add(TtsEvent(type: TtsEventType.started)); _eventStreamController.add(TtsEvent(type: TtsEventType.started));
break; break;
case 'completed': case 'completed':
_isSpeaking = false; _isSpeaking = false;
_eventStreamController.add(TtsEvent(type: TtsEventType.completed)); _eventStreamController.add(TtsEvent(type: TtsEventType.completed));
break; break;
case 'canceled': case 'canceled':
_isSpeaking = false; _isSpeaking = false;
_eventStreamController.add(TtsEvent(type: TtsEventType.canceled)); _eventStreamController.add(TtsEvent(type: TtsEventType.canceled));
break; break;
case 'error': case 'error':
_isSpeaking = false; _isSpeaking = false;
final errorCode = eventMap['errorCode'] as String? ?? "-1"; final errorCode = eventMap['errorCode'] as String? ?? "-1";
@ -105,7 +107,7 @@ class VolcanoTtsService extends GetxService implements TtsService {
}, },
); );
} }
/// 设置音频数据监听 /// 设置音频数据监听
void _setupAudioDataListeners() { void _setupAudioDataListeners() {
_audioDataSubscription = _audioDataChannel.receiveBroadcastStream().listen( _audioDataSubscription = _audioDataChannel.receiveBroadcastStream().listen(
@ -119,32 +121,34 @@ class VolcanoTtsService extends GetxService implements TtsService {
}, },
); );
} }
@override @override
Future<bool> initialize({List<String>? supportedLanguages}) async { Future<bool> initialize({List<String>? supportedLanguages}) async {
if (_isInitialized) return true; if (_isInitialized) return true;
try { try {
// 从.env文件读取配置 // 从.env文件读取配置
final appId = dotenv.env['VOLCANO_SPEECH_APP_ID'] ?? ''; final appId = dotenv.env['VOLCANO_SPEECH_APP_ID'] ?? '';
final appToken = dotenv.env['VOLCANO_SPEECH_APP_TOKEN'] ?? ''; final appToken = dotenv.env['VOLCANO_SPEECH_APP_TOKEN'] ?? '';
if (appId.isEmpty || appToken.isEmpty) { if (appId.isEmpty || appToken.isEmpty) {
debugPrint('火山语音初始化失败:缺少VOLCANO_SPEECH_APP_ID或VOLCANO_SPEECH_APP_TOKEN环境变量'); debugPrint(
'火山语音初始化失败:缺少VOLCANO_SPEECH_APP_ID或VOLCANO_SPEECH_APP_TOKEN环境变量');
return false; return false;
} }
// 初始化火山语音TTS // 初始化火山语音TTS
final result = await _channel.invokeMethod<bool>('initialize', { final result = await _channel.invokeMethod<bool>('initialize', {
'appId': appId, 'appId': appId,
'appToken': appToken, 'appToken': appToken,
}) ?? false; }) ??
false;
if (!result) { if (!result) {
debugPrint('火山语音TTS初始化失败'); debugPrint('火山语音TTS初始化失败');
return false; return false;
} }
_isInitialized = true; _isInitialized = true;
return true; return true;
} catch (e) { } catch (e) {
@ -160,16 +164,17 @@ class VolcanoTtsService extends GetxService implements TtsService {
} }
return true; return true;
} }
@override @override
Future<bool> setVoice(String voiceName) async { Future<bool> setVoice(String voiceName) async {
if (!await _ensureInitialized()) return false; if (!await _ensureInitialized()) return false;
try { try {
final result = await _channel.invokeMethod<bool>('setVoice', { final result = await _channel.invokeMethod<bool>('setVoice', {
'voice': voiceName, 'voice': voiceName,
}) ?? false; }) ??
false;
if (result) { if (result) {
_currentVoice = voiceName; _currentVoice = voiceName;
} }
@ -179,16 +184,17 @@ class VolcanoTtsService extends GetxService implements TtsService {
return false; return false;
} }
} }
/// 设置是否启用音频数据回调 /// 设置是否启用音频数据回调
Future<bool> setEnableAudioCallback(bool enable) async { Future<bool> setEnableAudioCallback(bool enable) async {
if (!await _ensureInitialized()) return false; if (!await _ensureInitialized()) return false;
try { try {
final result = await _channel.invokeMethod<bool>('enableAudioCallback', { final result = await _channel.invokeMethod<bool>('enableAudioCallback', {
'enable': enable, 'enable': enable,
}) ?? false; }) ??
false;
if (result) { if (result) {
_isAudioCallbackEnabled = enable; _isAudioCallbackEnabled = enable;
} }
@ -198,17 +204,18 @@ class VolcanoTtsService extends GetxService implements TtsService {
return false; return false;
} }
} }
@override @override
Future<bool> speakOnce(String text) async { Future<bool> speakOnce(String text) async {
if (!await _ensureInitialized()) return false; if (!await _ensureInitialized()) return false;
try { try {
// 单次播放 // 单次播放
final result = await _channel.invokeMethod<bool>('speakOnce', { final result = await _channel.invokeMethod<bool>('speakOnce', {
'text': text, 'text': text,
}) ?? false; }) ??
false;
return result; return result;
} catch (e) { } catch (e) {
debugPrint('单次播放失败:$e'); debugPrint('单次播放失败:$e');
@ -216,17 +223,18 @@ class VolcanoTtsService extends GetxService implements TtsService {
return false; return false;
} }
} }
@override @override
Future<bool> speakStream(String text) async { Future<bool> speakStream(String text) async {
if (!await _ensureInitialized()) return false; if (!await _ensureInitialized()) return false;
try { try {
// 流式添加文本 // 流式添加文本
final result = await _channel.invokeMethod<bool>('speakStream', { final result = await _channel.invokeMethod<bool>('speakStream', {
'text': text, 'text': text,
}) ?? false; }) ??
false;
return result; return result;
} catch (e) { } catch (e) {
debugPrint('流式播放失败:$e'); debugPrint('流式播放失败:$e');
@ -234,11 +242,11 @@ class VolcanoTtsService extends GetxService implements TtsService {
return false; return false;
} }
} }
@override @override
Future<bool> flushStream() async { Future<bool> flushStream() async {
if (!await _ensureInitialized()) return false; if (!await _ensureInitialized()) return false;
try { try {
// 刷新流式文本 // 刷新流式文本
return await _channel.invokeMethod<bool>('flushStream') ?? false; return await _channel.invokeMethod<bool>('flushStream') ?? false;
@ -247,11 +255,11 @@ class VolcanoTtsService extends GetxService implements TtsService {
return false; return false;
} }
} }
@override @override
Future<bool> stop() async { Future<bool> stop() async {
if (!_isInitialized) return false; if (!_isInitialized) return false;
try { try {
return await _channel.invokeMethod<bool>('stop') ?? false; return await _channel.invokeMethod<bool>('stop') ?? false;
} catch (e) { } catch (e) {
@ -259,27 +267,33 @@ class VolcanoTtsService extends GetxService implements TtsService {
return false; return false;
} }
} }
@override @override
Future<void> dispose() async { Future<void> dispose() async {
if (_isSpeaking) { if (_isSpeaking) {
await stop(); await stop();
} }
await _eventSubscription?.cancel(); await _eventSubscription?.cancel();
await _audioDataSubscription?.cancel(); await _audioDataSubscription?.cancel();
if (!_eventStreamController.isClosed) { if (!_eventStreamController.isClosed) {
await _eventStreamController.close(); await _eventStreamController.close();
} }
if (!_audioDataStreamController.isClosed) { if (!_audioDataStreamController.isClosed) {
await _audioDataStreamController.close(); await _audioDataStreamController.close();
} }
if (_isInitialized) { if (_isInitialized) {
await _channel.invokeMethod<bool>('release'); await _channel.invokeMethod<bool>('release');
_isInitialized = false; _isInitialized = false;
} }
} }
}
@override
Future<bool> setAudioOutputDevice(int type) {
// TODO: implement setAudioOutputDevice
throw UnimplementedError();
}
}

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

@ -327,7 +327,7 @@ class OtaUpgradeController extends GetxController {
} }
if (existingSameFile) { if (existingSameFile) {
Get.snackbar('文件已存在', '跳过下载,直接更新'); //Get.snackbar('文件已存在', '跳过下载,直接更新');
startUpgrading(savePath); startUpgrading(savePath);
return; return;
@ -367,7 +367,7 @@ class OtaUpgradeController extends GetxController {
); );
File file = File(savePath); File file = File(savePath);
if (await file.exists()) { if (await file.exists()) {
Get.snackbar('下载完成', '文件已保存至: $savePath'); // Get.snackbar('下载完成', '文件已保存至: $savePath');
} else { } else {
Get.snackbar('错误', '文件未找到,请检查写入权限'); Get.snackbar('错误', '文件未找到,请检查写入权限');
} }

210
lib/modules/settings/views/settings_view.dart

@ -525,114 +525,114 @@ class SettingsView extends GetView<SettingsController> {
? Colors.white.withOpacity(0.1) ? Colors.white.withOpacity(0.1)
: Colors.grey[200]), : Colors.grey[200]),
// 杰理测试 // // 杰理测试
_buildSimpleNavigationSetting( // _buildSimpleNavigationSetting(
title: '杰理蓝牙测试', // title: '杰理蓝牙测试',
subtitle: '测试杰理蓝牙设备扫描、连接和功能', // subtitle: '测试杰理蓝牙设备扫描、连接和功能',
icon: Icons.bluetooth, // icon: Icons.bluetooth,
iconBgColor: isDarkMode // iconBgColor: isDarkMode
? Colors.blue[900]!.withOpacity(0.3) // ? Colors.blue[900]!.withOpacity(0.3)
: Colors.blue[100]!, // : Colors.blue[100]!,
iconColor: // iconColor:
isDarkMode ? Colors.blue[300]! : Colors.blue[600]!, // isDarkMode ? Colors.blue[300]! : Colors.blue[600]!,
titleColor: isDarkMode ? Colors.white : null, // titleColor: isDarkMode ? Colors.white : null,
subtitleColor: isDarkMode ? Colors.white70 : null, // subtitleColor: isDarkMode ? Colors.white70 : null,
onTap: () { // onTap: () {
Get.toNamed(Routes.jieliTest); // Get.toNamed(Routes.jieliTest);
}, // },
isDarkMode: isDarkMode, // isDarkMode: isDarkMode,
), // ),
Divider( // Divider(
height: 1, // height: 1,
color: isDarkMode // color: isDarkMode
? Colors.white.withOpacity(0.1) // ? Colors.white.withOpacity(0.1)
: Colors.grey[200]), // : Colors.grey[200]),
// 面对面翻译测试 // // 面对面翻译测试
_buildSimpleNavigationSetting( // _buildSimpleNavigationSetting(
title: '面对面翻译测试', // title: '面对面翻译测试',
subtitle: '测试面对面翻译', // subtitle: '测试面对面翻译',
icon: Icons.bluetooth_searching, // icon: Icons.bluetooth_searching,
iconBgColor: isDarkMode // iconBgColor: isDarkMode
? Colors.green[900]!.withOpacity(0.3) // ? Colors.green[900]!.withOpacity(0.3)
: Colors.green[100]!, // : Colors.green[100]!,
iconColor: // iconColor:
isDarkMode ? Colors.green[300]! : Colors.green[600]!, // isDarkMode ? Colors.green[300]! : Colors.green[600]!,
titleColor: isDarkMode ? Colors.white : null, // titleColor: isDarkMode ? Colors.white : null,
subtitleColor: isDarkMode ? Colors.white70 : null, // subtitleColor: isDarkMode ? Colors.white70 : null,
onTap: () { // onTap: () {
Get.toNamed(Routes.ftftranslation); // Get.toNamed(Routes.ftftranslation);
}, // },
isDarkMode: isDarkMode, // isDarkMode: isDarkMode,
), // ),
Divider( // Divider(
height: 1, // height: 1,
color: isDarkMode // color: isDarkMode
? Colors.white.withOpacity(0.1) // ? Colors.white.withOpacity(0.1)
: Colors.grey[200]), // : Colors.grey[200]),
// BLE测试 // // BLE测试
_buildSimpleNavigationSetting( // _buildSimpleNavigationSetting(
title: 'opus解码测试', // title: 'opus解码测试',
subtitle: '测试opus解码', // subtitle: '测试opus解码',
icon: Icons.bluetooth_searching, // icon: Icons.bluetooth_searching,
iconBgColor: isDarkMode // iconBgColor: isDarkMode
? Colors.green[900]!.withOpacity(0.3) // ? Colors.green[900]!.withOpacity(0.3)
: Colors.green[100]!, // : Colors.green[100]!,
iconColor: // iconColor:
isDarkMode ? Colors.green[300]! : Colors.green[600]!, // isDarkMode ? Colors.green[300]! : Colors.green[600]!,
titleColor: isDarkMode ? Colors.white : null, // titleColor: isDarkMode ? Colors.white : null,
subtitleColor: isDarkMode ? Colors.white70 : null, // subtitleColor: isDarkMode ? Colors.white70 : null,
onTap: () { // onTap: () {
Get.toNamed(Routes.opusTest); // Get.toNamed(Routes.opusTest);
}, // },
isDarkMode: isDarkMode, // isDarkMode: isDarkMode,
), // ),
Divider( // Divider(
height: 1, // height: 1,
color: isDarkMode // color: isDarkMode
? Colors.white.withOpacity(0.1) // ? Colors.white.withOpacity(0.1)
: Colors.grey[200]), // : Colors.grey[200]),
// BLE测试 // BLE测试
_buildSimpleNavigationSetting( // _buildSimpleNavigationSetting(
title: 'BLE蓝牙测试', // title: 'BLE蓝牙测试',
subtitle: '测试BLE蓝牙设备扫描、连接和功能', // subtitle: '测试BLE蓝牙设备扫描、连接和功能',
icon: Icons.bluetooth_searching, // icon: Icons.bluetooth_searching,
iconBgColor: isDarkMode // iconBgColor: isDarkMode
? Colors.green[900]!.withOpacity(0.3) // ? Colors.green[900]!.withOpacity(0.3)
: Colors.green[100]!, // : Colors.green[100]!,
iconColor: // iconColor:
isDarkMode ? Colors.green[300]! : Colors.green[600]!, // isDarkMode ? Colors.green[300]! : Colors.green[600]!,
titleColor: isDarkMode ? Colors.white : null, // titleColor: isDarkMode ? Colors.white : null,
subtitleColor: isDarkMode ? Colors.white70 : null, // subtitleColor: isDarkMode ? Colors.white70 : null,
onTap: () { // onTap: () {
Get.toNamed(Routes.bleTest); // Get.toNamed(Routes.bleTest);
}, // },
isDarkMode: isDarkMode, // isDarkMode: isDarkMode,
), // ),
Divider( // Divider(
height: 1, // height: 1,
color: isDarkMode // color: isDarkMode
? Colors.white.withOpacity(0.1) // ? Colors.white.withOpacity(0.1)
: Colors.grey[200]), // : Colors.grey[200]),
// 火山语音测试 // // 火山语音测试
_buildSimpleNavigationSetting( // _buildSimpleNavigationSetting(
title: '语音测试', // title: '语音测试',
subtitle: '测试语音识别和合成功能,支持多种服务实现', // subtitle: '测试语音识别和合成功能,支持多种服务实现',
icon: Icons.record_voice_over, // icon: Icons.record_voice_over,
iconBgColor: isDarkMode // iconBgColor: isDarkMode
? Colors.orange[900]!.withOpacity(0.3) // ? Colors.orange[900]!.withOpacity(0.3)
: Colors.orange[100]!, // : Colors.orange[100]!,
iconColor: // iconColor:
isDarkMode ? Colors.orange[300]! : Colors.orange[600]!, // isDarkMode ? Colors.orange[300]! : Colors.orange[600]!,
onTap: () => Get.toNamed(Routes.speechTest), // onTap: () => Get.toNamed(Routes.speechTest),
isDarkMode: isDarkMode, // isDarkMode: isDarkMode,
), // ),
Divider( // Divider(
height: 1, // height: 1,
color: isDarkMode // color: isDarkMode
? Colors.white.withOpacity(0.1) // ? Colors.white.withOpacity(0.1)
: Colors.grey[200]), // : Colors.grey[200]),
// 测试ble耳机固件版本升级 // 测试ble耳机固件版本升级
_buildSimpleNavigationSetting( _buildSimpleNavigationSetting(
title: 'ota升级', title: 'ota升级',

23
local_plugins/ota/android/src/main/kotlin/com/example/ota/OtaPlugin.kt

@ -146,9 +146,10 @@ class OtaPlugin : BleService.Callback, FlutterPlugin, MethodCallHandler {
private lateinit var channel: MethodChannel private lateinit var channel: MethodChannel
private lateinit var context: Context private lateinit var context: Context
private lateinit var otaDevice: BluetoothDevice private lateinit var otaDevice: BluetoothDevice
private lateinit var bluetoothHelper: BluetoothHelper private var bluetoothHelper: BluetoothHelper? = null
private var otaManager: OTAManager? = null
private lateinit var otaManager: OTAManager
private lateinit var filePath: String//升级文件路径 private lateinit var filePath: String//升级文件路径
private var isDisconnect = false//是否主动断开 private var isDisconnect = false//是否主动断开
private var streamSink: EventChannel.EventSink? = null private var streamSink: EventChannel.EventSink? = null
@ -216,8 +217,8 @@ class OtaPlugin : BleService.Callback, FlutterPlugin, MethodCallHandler {
private val bluetoothCallback = object : BtEventCallback() { private val bluetoothCallback = object : BtEventCallback() {
override fun onConnection(device: BluetoothDevice?, status: Int) { override fun onConnection(device: BluetoothDevice?, status: Int) {
if ((status == StateCode.CONNECTION_FAILED || status == StateCode.CONNECTION_DISCONNECT) && bluetoothHelper.getConnectedDevice() != null) { if ((status == StateCode.CONNECTION_FAILED || status == StateCode.CONNECTION_DISCONNECT) && bluetoothHelper?.getConnectedDevice() != null) {
bluetoothHelper.disconnectDevice(bluetoothHelper.getConnectedDevice()) bluetoothHelper?.disconnectDevice(bluetoothHelper?.getConnectedDevice())
} }
otaDevice = device!! otaDevice = device!!
@ -238,10 +239,10 @@ class OtaPlugin : BleService.Callback, FlutterPlugin, MethodCallHandler {
) )
) )
Log.d("TAG", "startUpgrade,filePath=${filePath}") Log.d("TAG", "startUpgrade,filePath=${filePath}")
otaManager.bluetoothOption.firmwareFilePath = filePath otaManager?.bluetoothOption?.firmwareFilePath = filePath
otaManager.startOTA( otaManager?.startOTA(
CustomUpdateCallback( CustomUpdateCallback(
otaManager.bluetoothHelper.getConnectedDevice(), streamSink otaManager?.bluetoothHelper?.getConnectedDevice(), streamSink
) )
) )
} }
@ -280,7 +281,7 @@ class OtaPlugin : BleService.Callback, FlutterPlugin, MethodCallHandler {
otaManager = OTAManager(context) otaManager = OTAManager(context)
bluetoothHelper = BluetoothHelper(context) bluetoothHelper = BluetoothHelper(context)
// 如果需要额外的初始化逻辑,请在这里添加 // 如果需要额外的初始化逻辑,请在这里添加
otaManager.registerBluetoothCallback(bluetoothCallback) otaManager!!.registerBluetoothCallback(bluetoothCallback)
// 初始化BleService // 初始化BleService
// 2. 初始化BleService并注册回调 // 2. 初始化BleService并注册回调
if (BleService.initialize(context)) { if (BleService.initialize(context)) {
@ -335,10 +336,12 @@ class OtaPlugin : BleService.Callback, FlutterPlugin, MethodCallHandler {
} else if (call.method == "onOtaClose") { } else if (call.method == "onOtaClose") {
BleService.isEnterOta = false BleService.isEnterOta = false
isDisconnect = false isDisconnect = false
if(otaManager!= null) {
otaManager?.bluetoothHelper?.stopScan() otaManager?.bluetoothHelper?.stopScan()
otaManager?.bluetoothHelper?.disconnectDevice(otaDevice) otaManager?.bluetoothHelper?.disconnectDevice(otaDevice)
}
result.success("") result.success("")
} else { } else {
result.notImplemented() result.notImplemented()
@ -370,7 +373,7 @@ class OtaPlugin : BleService.Callback, FlutterPlugin, MethodCallHandler {
if (state == BleConst.STATE_DISCONNECTED && isDisconnect) { if (state == BleConst.STATE_DISCONNECTED && isDisconnect) {
Log.d("TAG", "Ble设备已断开,onConnectionStateChanged") Log.d("TAG", "Ble设备已断开,onConnectionStateChanged")
Handler(Looper.getMainLooper()).postDelayed({ Handler(Looper.getMainLooper()).postDelayed({
otaManager.bluetoothHelper.startScan(otaDevice) otaManager?.bluetoothHelper?.startScan(otaDevice)
}, 2000) // 2000 毫秒 = 2 秒 }, 2000) // 2000 毫秒 = 2 秒
} }
} }

Loading…
Cancel
Save