feat:完成未配对 ota 升级

This commit is contained in:
anfe 2024-05-07 16:45:59 +08:00
parent edb46d0080
commit 6b0e459829
13 changed files with 515 additions and 153 deletions

View File

@ -796,4 +796,14 @@
"购买":"Buy", "购买":"Buy",
"实名认证为付费功能,请购买后再使用":"Real-name authentication is a paid function, please use it after purchase" "实名认证为付费功能,请购买后再使用":"Real-name authentication is a paid function, please use it after purchase"
"密码不一致哦":"The passwords are inconsistent", "密码不一致哦":"The passwords are inconsistent",
"点击返回设备配对":"Tap Back to device pairing",
"无法连接?尝试升级":"Can't connect?Upgrade attempted",
"固件升级提示":"Firmware upgrade prompt",
"请先获取固件文件到手机本地,再选择升级":"Please obtain the firmware file to the local phone first, and then select Upgrade",
"固件升级中":"The firmware is being upgraded",
"取消升级":"Cancel the upgrade",
"固件传输中":"Firmware in transit",
"关闭":"Shut down",
"传输中'":"In transit"
} }

View File

@ -822,5 +822,14 @@
"实名认证":"实名认证", "实名认证":"实名认证",
"当前剩余数量":"当前剩余数量", "当前剩余数量":"当前剩余数量",
"购买":"购买", "购买":"购买",
"实名认证为付费功能,请购买后再使用":"实名认证为付费功能,请购买后再使用" "实名认证为付费功能,请购买后再使用":"实名认证为付费功能,请购买后再使用",
"点击返回设备配对":"点击返回设备配对",
"无法连接?尝试升级":"无法连接?尝试升级",
"固件升级提示":"固件升级提示",
"请先获取固件文件到手机本地,再选择升级":"请先获取固件文件到手机本地,再选择升级",
"固件升级中":"固件升级中",
"取消升级":"取消升级",
"固件传输中":"固件传输中",
"关闭":"关闭",
"传输中'":"传输中"
} }

View File

@ -825,5 +825,16 @@
"实名认证":"实名认证", "实名认证":"实名认证",
"当前剩余数量":"当前剩余数量", "当前剩余数量":"当前剩余数量",
"购买":"购买", "购买":"购买",
"实名认证为付费功能,请购买后再使用":"实名认证为付费功能,请购买后再使用" "实名认证为付费功能,请购买后再使用":"实名认证为付费功能,请购买后再使用",
"点击返回设备配对":"点击返回设备配对",
"无法连接?尝试升级":"无法连接?尝试升级",
"固件升级提示":"固件升级提示",
"请先获取固件文件到手机本地,再选择升级":"请先获取固件文件到手机本地,再选择升级",
"固件升级中":"固件升级中",
"取消升级":"取消升级",
"固件传输中":"固件传输中",
"关闭":"关闭",
"传输中'":"传输中"
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

View File

@ -21,6 +21,6 @@
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>1.0</string> <string>1.0</string>
<key>MinimumOSVersion</key> <key>MinimumOSVersion</key>
<string>11.0</string> <string>12.0</string>
</dict> </dict>
</plist> </plist>

View File

@ -145,7 +145,8 @@ class BlueManage {
_connectionStateSubscription?.cancel(); _connectionStateSubscription?.cancel();
_connectionStateSubscription = null; _connectionStateSubscription = null;
_connectionStateSubscription = bluetoothConnectDevice!.connectionState.listen((state) async { _connectionStateSubscription =
bluetoothConnectDevice!.connectionState.listen((state) async {
bluetoothConnectionState = state; bluetoothConnectionState = state;
// AppLog.log("蓝牙连接状态:$state"); // AppLog.log("蓝牙连接状态:$state");
}); });
@ -214,7 +215,9 @@ class BlueManage {
completer.complete(); completer.complete();
} }
}, onError: (e) { }, onError: (e) {
AppLog.log("扫描失败:$e",); AppLog.log(
"扫描失败:$e",
);
}); });
FlutterBluePlus.cancelWhenScanComplete(subscription); FlutterBluePlus.cancelWhenScanComplete(subscription);
await completer.future; await completer.future;
@ -281,7 +284,9 @@ class BlueManage {
// EventBusManager().eventBusFir(scanDevices); // EventBusManager().eventBusFir(scanDevices);
// FlutterBluePlus.stopScan(); // FlutterBluePlus.stopScan();
}, onError: (e) { }, onError: (e) {
AppLog.log("扫描失败:$e",); AppLog.log(
"扫描失败:$e",
);
}); });
FlutterBluePlus.cancelWhenScanComplete(subscription); FlutterBluePlus.cancelWhenScanComplete(subscription);
@ -304,7 +309,9 @@ class BlueManage {
} }
/// List senderData, /// List senderData,
Future<void> bludSendData(String deviceName, ConnectStateCallBack stateCallBack, {bool isAddEquipment = false}) async { Future<void> bludSendData(
String deviceName, ConnectStateCallBack stateCallBack,
{bool isAddEquipment = false}) async {
FlutterBluePlus.isSupported.then((isAvailable) async { FlutterBluePlus.isSupported.then((isAvailable) async {
if (isAvailable) { if (isAvailable) {
if (_adapterState == BluetoothAdapterState.on) { if (_adapterState == BluetoothAdapterState.on) {
@ -336,21 +343,13 @@ class BlueManage {
{bool isAddEquipment = false}) async { {bool isAddEquipment = false}) async {
connectDeviceName = deviceName; connectDeviceName = deviceName;
List<ScanResult> devicesList = scanDevices; List<ScanResult> devicesList = scanDevices;
// if (isAddEquipment == false) {
bool isExistDevice = scanDevices.any((element) => //使
element.device.platformName == connectDeviceName || startScan(10, (List<ScanResult> scanDevices) {
element.advertisementData.advName == connectDeviceName);
if (isAddEquipment == false && isExistDevice == false) {
// AppLog.log("需要开启扫描");
// startScan(10, (scanDevices){
startScanSingle(deviceName, 10, (List<ScanResult> scanDevices) {
// AppLog.log("扫描到的设备:$scanDevices");
devicesList = scanDevices;
_connectDevice(devicesList, deviceName, connectStateCallBack, _connectDevice(devicesList, deviceName, connectStateCallBack,
isAddEquipment: isAddEquipment); isAddEquipment: isAddEquipment);
}); });
} else { } else {
// AppLog.log("不需要开启扫描");
_connectDevice(devicesList, deviceName, connectStateCallBack, _connectDevice(devicesList, deviceName, connectStateCallBack,
isAddEquipment: isAddEquipment); isAddEquipment: isAddEquipment);
} }
@ -364,6 +363,7 @@ class BlueManage {
final knownDeviceIndex = devicesList.indexWhere((d) => final knownDeviceIndex = devicesList.indexWhere((d) =>
(d.device.platformName == deviceName) || (d.device.platformName == deviceName) ||
(d.advertisementData.advName == deviceName)); (d.advertisementData.advName == deviceName));
if (knownDeviceIndex >= 0) { if (knownDeviceIndex >= 0) {
// //
connectDeviceMacAddress = connectDeviceMacAddress =
@ -375,6 +375,7 @@ class BlueManage {
// AppLog.log('bluetoothConnectDevice: $bluetoothConnectDevice'); // AppLog.log('bluetoothConnectDevice: $bluetoothConnectDevice');
scanResult = devicesList[knownDeviceIndex]; scanResult = devicesList[knownDeviceIndex];
_initGetMtuSubscription(); _initGetMtuSubscription();
_initListenConnectionState(); _initListenConnectionState();
} }
@ -446,7 +447,8 @@ class BlueManage {
} on Exception catch (e) { } on Exception catch (e) {
bluetoothConnectionState = BluetoothConnectionState.disconnected; bluetoothConnectionState = BluetoothConnectionState.disconnected;
connectStateCallBack(bluetoothConnectionState!); connectStateCallBack(bluetoothConnectionState!);
AppLog.log('发现设备时失败 e:$e bluetoothConnectionState:$bluetoothConnectionState'); AppLog.log(
'发现设备时失败 e:$e bluetoothConnectionState:$bluetoothConnectionState');
rethrow; rethrow;
} }
} }
@ -461,7 +463,7 @@ class BlueManage {
_subScribeToCharacteristic(BluetoothCharacteristic characteristic) async { _subScribeToCharacteristic(BluetoothCharacteristic characteristic) async {
final subscription = characteristic.onValueReceived.listen((data) { final subscription = characteristic.onValueReceived.listen((data) {
// AppLog.log("订阅获取的数据:$data"); AppLog.log("订阅获取的数据:$data");
if (data == lastTimeData || data.isEmpty) { if (data == lastTimeData || data.isEmpty) {
return; return;
} else { } else {
@ -477,7 +479,7 @@ class BlueManage {
// //
dataLen = data[8] * 256 + data[9]; // 16 dataLen = data[8] * 256 + data[9]; // 16
// AppLog.log("dataLen1111:$dataLen getDataLength:${data.length} data:$data"); // AppLog.log("dataLen1111:$dataLen getDataLength:${data.length} data:$data");
if (dataLen! + 12 > data.length) { if (dataLen! + 14 > data.length) {
// //
allData.addAll(data); allData.addAll(data);
} else { } else {
@ -555,15 +557,16 @@ class BlueManage {
// //
Future<void> writeCharacteristicWithResponse(List<int> value) async { Future<void> writeCharacteristicWithResponse(List<int> value) async {
List<BluetoothService> services =
List<BluetoothService> services = await bluetoothConnectDevice!.discoverServices(); await bluetoothConnectDevice!.discoverServices();
for (BluetoothService service in services) { for (BluetoothService service in services) {
// AppLog.log("33333 service.remoteId:${service.remoteId}" // AppLog.log("33333 service.remoteId:${service.remoteId}"
// " service.uuid:${service.uuid}\n\n" // " service.uuid:${service.uuid}\n\n"
// " service.characteristics:${service.characteristics}\n\n" // " service.characteristics:${service.characteristics}\n\n"
// " service.includedServices:${service.includedServices}"); // " service.includedServices:${service.includedServices}");
if (service.uuid == _serviceIdConnect) { if (service.uuid == _serviceIdConnect) {
for (BluetoothCharacteristic characteristic in service.characteristics) { for (BluetoothCharacteristic characteristic
in service.characteristics) {
// AppLog.log("44444 characteristic.remoteId:${characteristic.remoteId}" // AppLog.log("44444 characteristic.remoteId:${characteristic.remoteId}"
// " characteristic.uuid:${characteristic.uuid}\n\n" // " characteristic.uuid:${characteristic.uuid}\n\n"
// " characteristic.secondaryServiceUuid:${characteristic // " characteristic.secondaryServiceUuid:${characteristic
@ -578,7 +581,9 @@ class BlueManage {
for (int i = 0; i < subData.length; i++) { for (int i = 0; i < subData.length; i++) {
if (characteristic.properties.writeWithoutResponse) { if (characteristic.properties.writeWithoutResponse) {
// 使WRITE_NO_RESPONSE属性写入值 // 使WRITE_NO_RESPONSE属性写入值
await characteristic.write(subData[i],withoutResponse: true).then((value) async { await characteristic
.write(subData[i], withoutResponse: true)
.then((value) async {
// await Future.delayed(const Duration(milliseconds: 1)).then(( // await Future.delayed(const Duration(milliseconds: 1)).then((
// value) async { // value) async {
// AppLog.log('分包发送成功了'); // AppLog.log('分包发送成功了');
@ -594,7 +599,8 @@ class BlueManage {
}); });
} else { } else {
// //
throw Exception('This characteristic does not support writing.'); throw Exception(
'This characteristic does not support writing.');
} }
} }
} on Exception catch (e, s) { } on Exception catch (e, s) {

View File

@ -26,6 +26,7 @@ class OTAUpgradeCommand extends SenderProtocol {
List<int>? signKey; List<int>? signKey;
List<int>? privateKey; List<int>? privateKey;
List<int>? token; List<int>? token;
bool encrypt;
OTAUpgradeCommand( OTAUpgradeCommand(
{this.lockID, {this.lockID,
@ -40,10 +41,10 @@ class OTAUpgradeCommand extends SenderProtocol {
this.needAuthor, this.needAuthor,
this.signKey, this.signKey,
this.privateKey, this.privateKey,
this.token}) this.token,
this.encrypt = true})
: super(CommandType.startOATUpgrade); : super(CommandType.startOATUpgrade);
@override @override
String toString() { String toString() {
return 'OTAUpgradeCommand{lockID: $lockID, userID: $userID, ' return 'OTAUpgradeCommand{lockID: $lockID, userID: $userID, '
@ -53,6 +54,15 @@ class OTAUpgradeCommand extends SenderProtocol {
'privateKey: $privateKey, token: $token}'; 'privateKey: $privateKey, token: $token}';
} }
@override
int identifierValue() {
if (encrypt) {
return super.identifierValue();
} else {
return 0x20;
}
}
@override @override
List<int> messageDetail() { List<int> messageDetail() {
List<int> data = []; List<int> data = [];
@ -66,21 +76,18 @@ class OTAUpgradeCommand extends SenderProtocol {
data.add(type1); data.add(type1);
data.add(type2); data.add(type2);
AppLog.log('---> 指令 : $type1 $type2' );
// id 40 // id 40
int lockIDLength = utf8.encode(lockID!).length; int lockIDLength = utf8.encode(lockID!).length;
data.addAll(utf8.encode(lockID!)); data.addAll(utf8.encode(lockID!));
data = getFixedLengthList(data, 40 - lockIDLength); data = getFixedLengthList(data, 40 - lockIDLength);
AppLog.log('---> 锁id :${utf8.encode(lockID!)}');
//userID 20 //userID 20
int userIDLength = utf8.encode(userID!).length; int userIDLength = utf8.encode(userID!).length;
data.addAll(utf8.encode(userID!)); data.addAll(utf8.encode(userID!));
data = getFixedLengthList(data, 20 - userIDLength); data = getFixedLengthList(data, 20 - userIDLength);
AppLog.log('---> userID :${utf8.encode(userID!)}');
//platform 2 //platform 2
int platform0 = (platform! & 0xFF00) >> 8; int platform0 = (platform! & 0xFF00) >> 8;
@ -88,36 +95,31 @@ class OTAUpgradeCommand extends SenderProtocol {
data.add(platform0); data.add(platform0);
data.add(platform1); data.add(platform1);
AppLog.log('---> platform : $platform0 $platform1');
//product 2 //product 2
// int product0 = (product! & 0xFF00) >> 8; // int product0 = (product! & 0xFF00) >> 8;
// int product1 = product! & 0xFF; // int product1 = product! & 0xFF;
// data.add(product0); // data.add(product0);
// data.add(product1); // data.add(product1);
data.addAll([0,1]);// 01 data.addAll([0, 1]); // 01
AppLog.log('---> platform : ${[0,1]}');
//HwVersion 20 //HwVersion 20
int hwVersionLength = utf8.encode(hwVersion!).length; int hwVersionLength = utf8.encode(hwVersion!).length;
data.addAll(utf8.encode(hwVersion!)); data.addAll(utf8.encode(hwVersion!));
data = getFixedLengthList(data, 20 - hwVersionLength); data = getFixedLengthList(data, 20 - hwVersionLength);
//FwVersion 20 //FwVersion 20
int fwVersionLength = utf8.encode(fwVersion!).length; int fwVersionLength = utf8.encode(fwVersion!).length;
data.addAll(utf8.encode(fwVersion!)); data.addAll(utf8.encode(fwVersion!));
data = getFixedLengthList(data, 20 - fwVersionLength); data = getFixedLengthList(data, 20 - fwVersionLength);
//fwSize 4 //fwSize 4
ByteData bytes = ByteData(4); // 4 ByteData bytes = ByteData(4); // 4
bytes.setInt32(0, fwSize!); bytes.setInt32(0, fwSize!);
List<int> byteList = bytes.buffer.asUint8List(); List<int> byteList = bytes.buffer.asUint8List();
data.addAll(byteList); data.addAll(byteList);
// 16 // 16
Uint8List result = Uint8List(16); Uint8List result = Uint8List(16);
// 4 // 4
@ -142,11 +144,9 @@ class OTAUpgradeCommand extends SenderProtocol {
authCodeData.addAll(utf8.encode(userID!)); authCodeData.addAll(utf8.encode(userID!));
//token 4 Token 0 //token 4 Token 0
authCodeData.addAll(token!); authCodeData.addAll(token??[]);
authCodeData.addAll(signKey!); authCodeData.addAll(signKey??[]);
AppLog.log('---> ${utf8.encode(keyID!)} ${utf8.encode(userID!)} $token $signKey');
// KeyIDauthUserIDmd5加密之后就是authCode // KeyIDauthUserIDmd5加密之后就是authCode
var authCode = crypto.md5.convert(authCodeData); var authCode = crypto.md5.convert(authCodeData);
@ -161,11 +161,17 @@ class OTAUpgradeCommand extends SenderProtocol {
data.add(0); data.add(0);
} }
} }
printLog(data); printLog(data);
// LockId进行SM4 ECB加密 key:544d485f633335373034383064613864
ebcData = SM4.encrypt(data, key: privateKey, mode: SM4CryptoMode.ECB); if (encrypt) {
return ebcData;
// LockId进行SM4 ECB加密 key:544d485f633335373034383064613864
ebcData = SM4.encrypt(data, key: privateKey, mode: SM4CryptoMode.ECB);
return ebcData;
} else {
data.add(0);
return data;
}
} }
} }

View File

@ -33,8 +33,9 @@ abstract class SenderProtocol extends IOData {
_commandIndex = IoManager().commandIndex; _commandIndex = IoManager().commandIndex;
} }
void printLog(List<int> data){ void printLog(List<int> data) {
AppLog.log("App -> 锁,指令类型:${commandType!.typeName} \n\n参数是:\n${toString()} \n\n加密之前数据是:\n$data"); AppLog.log(
"App -> 锁,指令类型:${commandType!.typeName} \n\n参数是:\n${toString()} \n\n加密之前数据是:\n$data");
} }
//TODO:Ï //TODO:Ï
@ -58,7 +59,8 @@ abstract class SenderProtocol extends IOData {
// //
// 4 4 1 01AES1282SM43SM4 // 4 4 1 01AES1282SM43SM4
commandList.add(commandType!.identifierValue); int value = identifierValue();
commandList.add(value);
// //
int dataLen = dataSourceLength(); int dataLen = dataSourceLength();
@ -84,6 +86,10 @@ abstract class SenderProtocol extends IOData {
return commandList; return commandList;
} }
//
// 4 4 1 01AES1282SM43SM4
int identifierValue() => commandType!.identifierValue;
//TODO: //TODO:
int dataSourceLength() => commandData!.length; int dataSourceLength() => commandData!.length;

View File

@ -20,9 +20,7 @@ FutureOr<void> main() async {
// //
await _initTranslation(); await _initTranslation();
DebugConsole.listen(() { runApp(const MyApp());
runApp(const MyApp());
});
if (AppPlatform.isAndroid) { if (AppPlatform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle systemUiOverlayStyle =

View File

@ -1,10 +1,20 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart'; import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:star_lock/blue/io_protocol/io_getPrivateKey.dart'; import 'package:star_lock/blue/io_protocol/io_getPrivateKey.dart';
import 'package:star_lock/blue/io_protocol/io_getPublicKey.dart'; import 'package:star_lock/blue/io_protocol/io_getPublicKey.dart';
import 'package:star_lock/blue/io_protocol/io_otaUpgrade.dart';
import 'package:star_lock/blue/io_protocol/io_processOtaUpgrade.dart';
import 'package:star_lock/mine/addLock/nearbyLock/nearbyLock_page.dart';
import 'package:star_lock/permission/permission_dialog.dart';
import 'package:star_lock/tools/baseGetXController.dart'; import 'package:star_lock/tools/baseGetXController.dart';
import '../../../appRouters.dart'; import '../../../appRouters.dart';
@ -21,6 +31,15 @@ import 'nearbyLock_state.dart';
class NearbyLockLogic extends BaseGetXController { class NearbyLockLogic extends BaseGetXController {
final NearbyLockState state = NearbyLockState(); final NearbyLockState state = NearbyLockState();
int otaCount = 0;
int otaIndex = 0;
Uint8List? otaBin;
int startSecond = 0;
Map? headJson;
String? deviceName;
StreamSubscription<Reply>? _replySubscription;
// //
void connect(String deviceName) { void connect(String deviceName) {
showTitleEasyLoading("获取锁信息 1/3"); showTitleEasyLoading("获取锁信息 1/3");
@ -30,11 +49,12 @@ class NearbyLockLogic extends BaseGetXController {
// state.sureBtnState.value = 1; // state.sureBtnState.value = 1;
// showEasyLoading(); // showEasyLoading();
showBlueConnetctToastTimer(action: (){ showBlueConnetctToastTimer(action: () {
dismissEasyLoading(); dismissEasyLoading();
// state.sureBtnState.value = 0; // state.sureBtnState.value = 0;
}); });
BlueManage().bludSendData(deviceName, (BluetoothConnectionState state) async { BlueManage().bludSendData(deviceName,
(BluetoothConnectionState state) async {
AppLog.log("点击要添加的设备了"); AppLog.log("点击要添加的设备了");
if (state == BluetoothConnectionState.connected) { if (state == BluetoothConnectionState.connected) {
AppLog.log("开始获取公钥"); AppLog.log("开始获取公钥");
@ -45,12 +65,11 @@ class NearbyLockLogic extends BaseGetXController {
}, isAddEquipment: true); }, isAddEquipment: true);
} }
//
late StreamSubscription<Reply> _replySubscription;
void _initReplySubscription() { void _initReplySubscription() {
_replySubscription = EventBusManager().eventBus!.on<Reply>().listen((reply) { _replySubscription =
EventBusManager().eventBus!.on<Reply>().listen((reply) {
if (reply is GetPublicKeyReply) { if (reply is GetPublicKeyReply) {
_replyGetPublicKey(reply); _replyGetPublicKey(reply);
} }
if (reply is GetPrivateKeyReply) { if (reply is GetPrivateKeyReply) {
@ -61,6 +80,23 @@ class NearbyLockLogic extends BaseGetXController {
if (reply is GetStarLockStatuInfoReply) { if (reply is GetStarLockStatuInfoReply) {
_replyGetStarLockStatusInfo(reply); _replyGetStarLockStatusInfo(reply);
} }
if (reply is OTAUpgradeReply) {
if (reply.status == 0x00) {
//
dismissEasyLoading();
startOTAData();
processOtaUpgrade();
} else if (reply.status == 0x06) {
blueOTAUpgrade(headJson!, reply.token);
}
} else if (reply is ProcessOtaUpgradeReply && reply.status == 0x00) {
otaIndex++;
processOtaUpgrade();
} else if (reply is ConfirmationOTAUpgradeReply && reply.status == 0x00) {
showToast('固件升级完成'.tr);
closeOTADAta();
}
}); });
} }
@ -197,8 +233,10 @@ class NearbyLockLogic extends BaseGetXController {
// //
var restoreCounter = reply.data.sublist(133, 135); var restoreCounter = reply.data.sublist(133, 135);
state.lockInfo["restoreCount"] = restoreCounter[0] * 256 + restoreCounter[1]; state.lockInfo["restoreCount"] =
AppLog.log("重置次数 restoreCounter:${restoreCounter[0] * 256 + restoreCounter[1]}"); restoreCounter[0] * 256 + restoreCounter[1];
AppLog.log(
"重置次数 restoreCounter:${restoreCounter[0] * 256 + restoreCounter[1]}");
// //
var restoreDate = reply.data.sublist(135, 139); var restoreDate = reply.data.sublist(135, 139);
@ -312,21 +350,6 @@ class NearbyLockLogic extends BaseGetXController {
} }
} }
// List charListChangeIntList(List<int> featureValue){
// // 16
// String featureValueStr = asciiString(featureValue);
// // 162 0 57 60
// String featureValueTwoStr = int.parse(featureValueStr,radix: 16).toRadixString(2);
// List<int> featureValueTwoList = [];
// for(int i = 0;i<featureValueTwoStr.length;i++){
// featureValueTwoList.add(int.parse(featureValueTwoStr[i]));
// }
// //
// featureValueTwoList = featureValueTwoList.reversed.toList();
// List allFeatureValueTwoList = getFixedLengthList(featureValueTwoList, 60 - featureValueTwoList.length);
// return allFeatureValueTwoList;
// }
// //
Future<void> _getStarLockStatus() async { Future<void> _getStarLockStatus() async {
// //
@ -334,39 +357,26 @@ class NearbyLockLogic extends BaseGetXController {
// if (state == BluetoothConnectionState.connected) { // if (state == BluetoothConnectionState.connected) {
// dismissEasyLoading(); // dismissEasyLoading();
AppLog.log("开始获取锁状态"); AppLog.log("开始获取锁状态");
var privateKey = await Storage.getStringList(saveBluePrivateKey); var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
// IoSenderManage.senderGetLockStatu( // IoSenderManage.senderGetLockStatu(
// lockID:BlueManage().connectDeviceName, // lockID:BlueManage().connectDeviceName,
// userID:await Storage.getUid(), // userID:await Storage.getUid(),
// privateKey:getPrivateKeyList, // privateKey:getPrivateKeyList,
// ); // );
IoSenderManage.senderGetStarLockStatuInfo( IoSenderManage.senderGetStarLockStatuInfo(
lockID: BlueManage().connectDeviceName, lockID: BlueManage().connectDeviceName,
userID: await Storage.getUid(), userID: await Storage.getUid(),
isBeforeAddUser: true, isBeforeAddUser: true,
privateKey: getPrivateKeyList, privateKey: getPrivateKeyList,
); );
// } else if (state == BluetoothConnectionState.disconnected) { // } else if (state == BluetoothConnectionState.disconnected) {
// dismissEasyLoading(); // dismissEasyLoading();
// } // }
// }, isAddEquipment: true); // }, isAddEquipment: true);
} }
// late StreamSubscription<List<ScanResult>>_scanListDiscoveredDeviceSubscription;
// void _scanListDiscoveredDeviceSubscriptionAction() {
// _scanListDiscoveredDeviceSubscription = EventBusManager().eventBus!.on<List<ScanResult>>().listen((List<ScanResult> list) {
// state.devices.clear();
// for (int i = 0; i < list.length; i++) {
// ScanResult device = list[i];
// if (((device.advertisementData.serviceUuids.isNotEmpty ? device.advertisementData.serviceUuids[0] : "").toString()[31] != "1")) {
// state.devices.add(list[i]);
// }
// }
// });
// }
void startScanBlueList() { void startScanBlueList() {
BlueManage().startScan(2000, (List<ScanResult> list) { BlueManage().startScan(2000, (List<ScanResult> list) {
state.devices.clear(); state.devices.clear();
@ -388,30 +398,234 @@ class NearbyLockLogic extends BaseGetXController {
BlueManage().stopScan(); BlueManage().stopScan();
} }
// , ota
void oTAUpgrade(String deviceName) {
showTitleEasyLoading("连接设备中...");
this.deviceName = deviceName;
BlueManage().bludSendData(deviceName,
(BluetoothConnectionState state) async {
AppLog.log("连接设备");
if (state == BluetoothConnectionState.connected) {
AppLog.log("连接成功");
dismissEasyLoading();
otaUpdate();
} else if (state == BluetoothConnectionState.disconnected) {
AppLog.log("连接失败");
dismissEasyLoading();
}
}, isAddEquipment: true);
}
//
Future<void> otaUpdate() async {
var status = await PermissionDialog.request(
Permission.storage, '需要访问读写权限才能使用手动升级固件'.tr);
if (status != true) {
return;
}
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result == null || result.files.single.path is! String) {
return;
}
File file = File(result.files.single.path!);
Uint8List data = await file.readAsBytes();
headJson = await getHeadFile(data);
if (headJson is! Map) {
return;
}
otaBin = await checkFile(data, headJson!);
if (otaBin == null) {
return;
}
String md5Str = md5.convert(otaBin!).toString();
headJson!['fwMd5'] = md5Str;
blueOTAUpgrade(headJson!, [0, 0, 0, 0]);
}
// ota
void blueOTAUpgrade(Map data, List<int> token) {
if (deviceName == null) {
AppLog.log('blueOTAUpgrade:设备名字为 null');
return;
}
BlueManage().bludSendData(deviceName!,
(BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) {
String uid = await Storage.getUid() ?? '';
BlueManage().writeCharacteristicWithResponse(OTAUpgradeCommand(
lockID: deviceName,
userID: uid,
keyID: deviceName,
platform: int.tryParse(data['platform']) ?? 0,
product: int.tryParse(data['product']) ?? 0,
hwVersion: data['hwVersion'],
fwVersion: data['fwVersion'],
fwSize: data['fwSize'],
fwMD5: data['fwMd5'],
needAuthor: 1,
token: token,
encrypt: false,
).packageData());
showTitleEasyLoading("连接设备中...");
} else if (deviceConnectionState ==
BluetoothConnectionState.disconnected) {}
},isAddEquipment: true);
}
//
Future<void> processOtaUpgrade() async {
if (!state.otaUpdateIng.value) {
return;
}
int length = otaBin?.length ?? 0;
if (otaCount == 0) {
//
int difference = length % 240;
otaCount = length ~/ 240 + (difference > 0 ? 1 : 0);
startSecond = DateTime.now().millisecondsSinceEpoch ~/ 1000;
}
if (otaCount <= otaIndex) {
int now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
String msg =
'传输完成 时间:${now - startSecond}秒 otaCount:$otaCount otaIndex:$otaIndex ';
closeOTADAta();
AppLog.log(msg);
// showToast(msg);
return;
}
int star = otaIndex * 240;
int end = (otaIndex + 1) * 240;
if (end > length) {
end = length;
}
int size = end - star;
List<int> data = otaBin!.sublist(star, end);
state.otaProgress.value = otaIndex / otaCount;
await BlueManage().writeCharacteristicWithResponse(
ProcessOtaUpgradeCommand(index: otaIndex, size: size, data: data)
.packageData());
}
// ota升级
void startOTAData() {
state.otaUpdateIng.value = true;
state.oTAProgressDialog = true;
Get.dialog(
OTAProgressDialog(
logic: this,
),
barrierDismissible: false)
.then((value) => state.oTAProgressDialog = false);
}
// ata
void closeOTADAta() {
if (state.oTAProgressDialog) {
Get.back();
}
state.otaUpdateIng.value = false;
state.otaProgress.value = 0;
otaIndex = 0;
otaCount = 0;
startSecond = 0;
otaBin = null;
}
//
void getBack() {
if (state.otaUpdateIng.value) {
closeOTADAta();
} else {
Get.back();
}
}
//
Future<Map?> getHeadFile(Uint8List data) async {
if (data.length <= 16) {
showToast('错误固件,请选择正确的文件'.tr);
return null;
}
//
String header;
try {
header = utf8.decode(data.sublist(0, 12));
} catch (e) {
showToast('非SYD固件请选择正确的文件'.tr);
return null;
}
if (header != 'SYD-BIN-DATA') {
showToast('非SYD固件请选择正确的文件'.tr);
return null;
}
//
Uint8List metaLenList;
int metaLen;
try {
metaLenList = data.sublist(12, 16);
metaLen = ByteData.sublistView(metaLenList).getUint32(0);
} catch (e) {
showToast('文件校验失败 0x01'.tr);
return null;
}
if (metaLen < 2 || metaLen > 10240) {
showToast('文件校验失败 0x01'.tr);
return null;
}
//
Uint8List metaStrList;
String metaStr;
try {
metaStrList = data.sublist(16, 16 + metaLen);
metaStr = utf8.decode(metaStrList);
} catch (e) {
showToast('解析元数据失败,请选择正确的文件'.tr);
return null;
}
AppLog.log(metaStr);
var meta = jsonDecode(metaStr);
if (meta is! Map) {
showToast('解析元数据失败,请选择正确的文件'.tr);
return null;
}
return meta..['metaLen'] = metaLen;
}
// bin
Future<Uint8List?> checkFile(Uint8List data, Map meta) async {
num binOffset = 16 + (meta['metaLen'] ?? 0);
//
Uint8List bin = data.sublist(binOffset.toInt(), data.length);
//md5
String md5Str = md5.convert(bin).toString().toUpperCase();
AppLog.log('---> $md5Str ${meta['fwMd5']}');
if (md5Str != meta['fwMd5']) {
showToast('文件校验失败 0x02'.tr);
return null;
}
if (bin.length != meta['fwSize']) {
showToast('文件校验失败 0x03'.tr);
return null;
}
return bin;
}
@override @override
void onReady() { void onReady() {
// TODO: implement onReady
super.onReady(); super.onReady();
_initReplySubscription(); _initReplySubscription();
// _scanListDiscoveredDeviceSubscriptionAction();
state.ifCurrentScreen.value = true; state.ifCurrentScreen.value = true;
startScanBlueList(); startScanBlueList();
} }
@override @override
void onInit() { void onInit() {
// TODO: implement onInit
super.onInit(); super.onInit();
} }
@override @override
void onClose() { void onClose() {
// TODO: implement onClose
super.onClose(); super.onClose();
_replySubscription.cancel(); _replySubscription?.cancel();
// _scanListDiscoveredDeviceSubscription.cancel();
} }
} }

View File

@ -23,12 +23,6 @@ class _NearbyLockPageState extends State<NearbyLockPage> with RouteAware {
final logic = Get.put(NearbyLockLogic()); final logic = Get.put(NearbyLockLogic());
final state = Get.find<NearbyLockLogic>().state; final state = Get.find<NearbyLockLogic>().state;
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
@ -60,32 +54,62 @@ class _NearbyLockPageState extends State<NearbyLockPage> with RouteAware {
]), ]),
), ),
body: Obx(() { body: Obx(() {
return ListView.separated( return listView();
itemCount: state.devices.length,
itemBuilder: (c, index) {
return nearbyLockItem(
'images/icon_lockGroup_item.png', state.devices[index], () {
// Navigator.pushNamed(context, Routers.lockAddressPage);
// logic.getPublicKey(state.devices[index].serviceUuids[0].toString());
state.selectLockName.value =
state.devices[index].advertisementData.advName;
logic.connect(state.devices[index].advertisementData.advName);
// Get.toNamed(Routers.lockAddressGaoDePage);
});
},
separatorBuilder: (BuildContext context, int index) {
return Divider(
height: 1,
color: AppColors.greyLineColor,
indent: 20.w,
endIndent: 0,
);
},
);
}), }),
); );
} }
Widget listView() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: ListView.separated(
itemCount: state.devices.length,
itemBuilder: (c, index) {
return nearbyLockItem(
'images/icon_lockGroup_item.png', state.devices[index], () {
String advName = state.devices[index].advertisementData.advName;
state.selectLockName.value = advName;
if (state.otaState.value) {
logic.oTAUpgrade(advName);
} else {
logic.connect(advName);
}
});
},
separatorBuilder: (BuildContext context, int index) {
return Divider(
height: 1,
color: AppColors.greyLineColor,
indent: 20.w,
endIndent: 0,
);
},
),
),
Padding(
padding: EdgeInsets.only(left: 15.w, bottom: 10.h),
child: TextButton(
onPressed: () async {
bool skip = false;
if (!state.otaState.value) {
skip = await Get.dialog(
const _TipDialog(),
);
}
state.otaState.value = skip;
},
child: Text(
state.otaState.value ? '点击返回设备配对'.tr : '无法连接?尝试升级'.tr,
style: TextStyle(fontSize: 22.sp),
),
),
),
],
);
}
Widget nearbyLockItem( Widget nearbyLockItem(
String lockTypeIcon, ScanResult scanResult, Function() action) { String lockTypeIcon, ScanResult scanResult, Function() action) {
return GestureDetector( return GestureDetector(
@ -97,7 +121,6 @@ class _NearbyLockPageState extends State<NearbyLockPage> with RouteAware {
? action ? action
: null, : null,
child: Column( child: Column(
// mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Container( Container(
height: 89.h, height: 89.h,
@ -141,9 +164,12 @@ class _NearbyLockPageState extends State<NearbyLockPage> with RouteAware {
), ),
Expanded(child: SizedBox(width: 20.w)), Expanded(child: SizedBox(width: 20.w)),
Image.asset( Image.asset(
'images/main/icon_main_addLock.png', state.otaState.value
? 'images/ota_upgrade_icon.png'
: 'images/main/icon_main_addLock.png',
width: 36.w, width: 36.w,
height: 36.w, height: 36.w,
color: AppColors.mainColor,
), ),
SizedBox(width: 30.w), SizedBox(width: 30.w),
], ],
@ -156,7 +182,6 @@ class _NearbyLockPageState extends State<NearbyLockPage> with RouteAware {
@override @override
void didChangeDependencies() { void didChangeDependencies() {
// TODO: implement didChangeDependencies
super.didChangeDependencies(); super.didChangeDependencies();
/// ///
@ -165,7 +190,6 @@ class _NearbyLockPageState extends State<NearbyLockPage> with RouteAware {
@override @override
void dispose() { void dispose() {
// TODO: implement dispose
/// ///
AppRouteObserver().routeObserver.unsubscribe(this); AppRouteObserver().routeObserver.unsubscribe(this);
super.dispose(); super.dispose();
@ -183,11 +207,9 @@ class _NearbyLockPageState extends State<NearbyLockPage> with RouteAware {
super.didPop(); super.didPop();
EasyLoading.isShow ? EasyLoading.dismiss() : null; EasyLoading.isShow ? EasyLoading.dismiss() : null;
state.ifCurrentScreen.value = false; state.ifCurrentScreen.value = false;
logic.cancelBlueConnetctToastTimer(); logic.cancelBlueConnetctToastTimer();
logic.stopScanBlueList(); logic.stopScanBlueList();
BlueManage().disconnect();
} }
/// ///
@ -203,10 +225,88 @@ class _NearbyLockPageState extends State<NearbyLockPage> with RouteAware {
@override @override
void didPushNext() { void didPushNext() {
super.didPushNext(); super.didPushNext();
if (!logic.state.otaState.value) {
state.ifCurrentScreen.value = false; state.ifCurrentScreen.value = false;
logic.cancelBlueConnetctToastTimer(); logic.cancelBlueConnetctToastTimer();
logic.stopScanBlueList(); logic.stopScanBlueList();
BlueManage().disconnect(); }
}
}
class _TipDialog extends StatelessWidget {
const _TipDialog({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return CupertinoAlertDialog(
title: Text(
'固件升级提示'.tr,
),
content: Text('请先获取固件文件到手机本地,再选择升级'.tr),
actions: [
TextButton(
onPressed: () {
Get.back();
},
child: Text(
'取消'.tr,
style: TextStyle(fontSize: 22.sp, color: AppColors.blackColor),
),
),
TextButton(
onPressed: () async {
Get.back(result: true);
},
child: Text(
'确定'.tr,
style: TextStyle(fontSize: 22.sp, color: AppColors.blackColor),
),
),
],
);
}
}
class OTAProgressDialog extends StatelessWidget {
NearbyLockLogic logic;
OTAProgressDialog({required this.logic, Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Obx(() {
return CupertinoAlertDialog(
title: Text(
'固件升级中'.tr,
),
content: Row(
children: [
Text(
'传输中'.tr,
style: TextStyle(fontSize: 22.sp, color: AppColors.mainColor),
),
SizedBox(
width: 15.w,
),
Expanded(
child: LinearProgressIndicator(
value: logic.state.otaProgress.value,
color: AppColors.mainColor,
)),
],
),
actions: [
TextButton(
onPressed: () {
logic.closeOTADAta();
},
child: Text(
'取消升级'.tr,
style: TextStyle(fontSize: 22.sp, color: AppColors.blackColor),
),
),
],
);
});
} }
} }

View File

@ -1,9 +1,7 @@
import 'package:flutter_blue_plus/flutter_blue_plus.dart'; import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
class NearbyLockState { class NearbyLockState {
RxList<ScanResult> devices = <ScanResult>[].obs; RxList<ScanResult> devices = <ScanResult>[].obs;
var ifCurrentScreen = true.obs; // , var ifCurrentScreen = true.obs; // ,
// var sureBtnState = 0.obs;// 0 1 // var sureBtnState = 0.obs;// 0 1
@ -16,4 +14,8 @@ class NearbyLockState {
var featureSettingValue = ''; var featureSettingValue = '';
var featureSettingParams = []; var featureSettingParams = [];
var otaState = false.obs; //ota
var otaUpdateIng = false.obs;
var otaProgress = 0.00.obs;
bool oTAProgressDialog = false;
} }

View File

@ -99,7 +99,7 @@ dependencies:
url_launcher: ^6.1.10 url_launcher: ^6.1.10
#蓝牙 #蓝牙
# flutter_reactive_ble: ^5.1.1 # flutter_reactive_ble: ^5.1.1
flutter_blue_plus: ^1.31.16 flutter_blue_plus: 1.31.16
# #
event_bus: ^2.0.0 event_bus: ^2.0.0
#菊花 #菊花