app-starlock/lib/mine/addLock/saveLock/saveLock_logic.dart

638 lines
24 KiB
Dart
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:async';
import 'dart:math';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:star_lock/apm/apm_helper.dart';
import 'package:star_lock/appRouters.dart';
import 'package:star_lock/blue/io_protocol/io_readAdminPassword.dart';
import 'package:star_lock/main/lockDetail/lockDetail/lockDetail_logic.dart';
import 'package:star_lock/main/lockDetail/lockSet/lockSet/lockSetInfo_entity.dart';
import 'package:star_lock/mine/addLock/saveLock/entity/SaveLockEntity.dart';
import '../../../app_settings/app_settings.dart';
import '../../../blue/blue_manage.dart';
import '../../../blue/io_protocol/io_addUser.dart';
import '../../../blue/io_reply.dart';
import '../../../blue/io_tool/io_tool.dart';
import '../../../blue/io_tool/manager_event_bus.dart';
import '../../../blue/sender_manage.dart';
import '../../../network/api_repository.dart';
import '../../../tools/baseGetXController.dart';
import '../../../tools/dateTool.dart';
import '../../../tools/eventBusEventManage.dart';
import '../../../tools/storage.dart';
import 'saveLock_state.dart';
class SaveLockLogic extends BaseGetXController {
final SaveLockState state = SaveLockState();
// 获取解析后的数据
late StreamSubscription<Reply> _replySubscription;
void _initReplySubscription() {
_replySubscription = EventBusManager().eventBus!.on<Reply>().listen((Reply reply) {
if (reply is AddUserReply && state.ifCurrentScreen.value == true) {
_replyAddUserKey(reply);
}
// if (reply is SenderCustomPasswordsReply) {
// _replySenderCustomPasswords(reply);
// }
// if (reply is ChangeAdministratorPasswordReply) {
// _replyChangeAdministratorPassword(reply);
// }
// 新增----m 获取锁管理员密码
if (reply is SenderReadAdminPasswordReply && (state.ifCurrentScreen.value == true)) {
_replySenderReadAdminPasswordReply(reply);
}
});
}
// 新增----m 获取锁管理员密码
Future<void> _replySenderReadAdminPasswordReply(Reply reply) async {
AppLog.log('响应获取管理员密码: ${reply.data}');
var token = reply.data.sublist(5, 9);
var saveStrList = changeIntListToStringList(token);
Storage.setStringList(saveBlueToken, saveStrList);
int status = reply.data[2];
switch (status) {
case 0x00:
//成功
dismissEasyLoading();
cancelBlueConnetctToastTimer();
if(reply.data[5] > 0){
reply.data.removeRange(0, 6);
// 把得到的数据按8位分割成数组 然后塞进一个新的数组里面
var getList = splitList(reply.data, 13);
for(int i = 0; i<getList.length; i++){
var indexList = getList[i];
var pwd = indexList.sublist(1, 11);
var pwdStr = utf8String(pwd);
state.adminPassword = pwdStr;
AppLog.log('管理员密码:${state.adminPassword}');
}
}
if(state.adminPassword == ''){
final Random rng = Random();
final int number = rng.nextInt(900000) + 100000;
state.adminPassword = number.toString();
} else {
state.role = 1;
}
break;
case 0x06:
//无权限
var privateKey = await Storage.getStringList(saveBluePrivateKey);
List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
var token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = changeStringListToIntList(token!);
var publicKey = await Storage.getStringList(saveBluePublicKey);
List<int> getPublicKeyList = changeStringListToIntList(publicKey!);
IoSenderManage.senderReadAdminPasswordCommand(
keyID: state.lockSetInfoData.value.lockBasicInfo!.keyId.toString(),
userID: await Storage.getUid(),
role:0xff,
pwdNum:1,
pwdNo: 0,
token: getTokenList,
needAuthor: 1,
publicKey: getPublicKeyList,
privateKey: getPrivateKeyList
);
break;
default:
//失败
break;
}
}
void senderReadAdminPassword() async {
BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async {
AppLog.log('开始读取管理员密码,蓝牙状态是否链接:${connectionState == BluetoothConnectionState.connected}');
if (connectionState == BluetoothConnectionState.connected) {
final List<String>? privateKey = await Storage.getStringList(saveBluePrivateKey);
final List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
final List<String>? token = await Storage.getStringList(saveBlueToken);
final List<int> getTokenList = changeStringListToIntList(token!);
final List<String>? publicKey = await Storage.getStringList(saveBluePublicKey);
final List<int> getPublicKeyList = changeStringListToIntList(publicKey!);
AppLog.log('发送获取管理员密码指令:${BlueManage().connectDeviceName}');
IoSenderManage.senderReadAdminPasswordCommand(
keyID: '1',
userID: await Storage.getUid(),
role:1,
pwdNum:1,
pwdNo: 0,
token: getTokenList,
needAuthor: 1,
publicKey: getPublicKeyList,
privateKey: getPrivateKeyList
);
}
});
}
// 添加用户
Future<void> _replyAddUserKey(Reply reply) async {
final List<int> token = reply.data.sublist(42, 46);
final List<String> strTokenList = changeIntListToStringList(token);
Storage.setStringList(saveBlueToken, strTokenList);
final int status = reply.data[46];
switch (status) {
case 0x00:
//成功 如果成功保存用户编号
state.lockUserNo = listChangInt(reply.data.sublist(47, 49));
AppLog.log('state.lockUserNo:${state.lockUserNo}');
// 关闭超时
cancelBlueConnetctToastTimer();
bindBlueAdmin();
break;
case 0x06:
//无权限
final List<String>? privateKey = await Storage.getStringList(saveBluePrivateKey);
final List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
final List<String>? publicKey = await Storage.getStringList(saveBluePublicKey);
final List<int> publicKeyDataList = changeStringListToIntList(publicKey!);
IoSenderManage.senderAddUser(
lockID: BlueManage().connectDeviceName,
authUserID: await Storage.getUid(),
keyID: '1',
userID: await Storage.getUid(),
openMode: 1,
keyType: 1,
startDate: DateTime.now().millisecondsSinceEpoch,
expireDate: 0x11223344,
useCountLimit: 0xFFFF,
isRound: 0,
weekRound: 0,
startHour: 0,
startMin: 0,
endHour: 0,
endMin: 0,
role: 255,
password: state.adminPassword,
needAuthor: 1,
publicKey: publicKeyDataList,
privateKey: getPrivateKeyList,
token: token,
isBeforeAddUser: true);
break;
default:
//失败 关闭loading
state.sureBtnState.value = 0;
dismissEasyLoading();
break;
}
}
// 添加管理员密码
// Future<void> _replySenderCustomPasswords(Reply reply) async {
// int status = reply.data[2];
//
// switch (status) {
// case 0x00:
// //成功
// state.sureBtnState.value = 0;
// dismissEasyLoading();
// addLockAdminPassword(true);
// break;
// case 0x06:
// //无权限
// var privateKey = await Storage.getStringList(saveBluePrivateKey);
// List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
//
// var signKey = await Storage.getStringList(saveBlueSignKey);
// List<int> signKeyDataList = changeStringListToIntList(signKey!);
//
// var token = reply.data.sublist(5, 9);
// var saveStrList = changeIntListToStringList(token);
// Storage.setStringList(saveBlueToken, saveStrList);
//
// IoSenderManage.senderCustomPasswordsCommand(
// keyID: "1",
// userID: await Storage.getUid(),
// pwdNo: 0,
// pwd: state.adminPassword,
// operate: 0,
// isAdmin: 1,
// useCountLimit: 0xffff,
// startTime: 0x11223344,
// endTime: 0x11223344,
// needAuthor: 1,
// isBeforeAddUser: true,
// signKey: signKeyDataList,
// privateKey: getPrivateKeyList,
// token: token);
// break;
// default:
// state.sureBtnState.value = 0;
// dismissEasyLoading();
// backAction();
// // AppLog.log("添加管理员密码失败 消失");
// break;
// }
// }
// 修改管理员密码
// Future<void> _replyChangeAdministratorPassword(Reply reply) async {
// var token = reply.data.sublist(5, 9);
// var saveStrList = changeIntListToStringList(token);
// Storage.setStringList(saveBlueToken, saveStrList);
//
// int status = reply.data[2];
//
// switch (status) {
// case 0x00:
// //成功
// cancelBlueConnetctToastTimer();
// addLockAdminPassword(false);
// break;
// case 0x06:
// //无权限
// var signKey = await Storage.getStringList(saveBlueSignKey);
// List<int> signKeyDataList = changeStringListToIntList(signKey!);
//
// var privateKey = await Storage.getStringList(saveBluePrivateKey);
// List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
//
// IoSenderManage.changeAdministratorPasswordCommand(
// keyID: "1",
// userID: await Storage.getUid(),
// pwdNo: 254,
// pwd:state.adminPasswordTF.text,
// useCountLimit: 0xff,
// startTime: 0x11223344,
// endTime: 0x11223344,
// needAuthor: 1,
// isBeforeAddUser: true,
// signKey: signKeyDataList,
// privateKey: getPrivateKeyList,
// token: token);
// break;
// default:
// break;
// }
// }
// 添加用户
Future<void> addUserConnectBlue() async {
// 进来之后首先连接
if (state.sureBtnState.value == 1) {
return;
}
state.sureBtnState.value = 1;
// showTitleEasyLoading("添加锁进行中 1/2");
showEasyLoading();
// 判断超时
showBlueConnetctToastTimer(action: () {
dismissEasyLoading();
state.sureBtnState.value = 0;
if (state.ifCurrentScreen.value == true) {
showBlueConnetctToast();
}
});
BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
if (deviceConnectionState == BluetoothConnectionState.connected) {
// 私钥
final List<String>? privateKey = await Storage.getStringList(saveBluePrivateKey);
final List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
final List<String>? publicKey = await Storage.getStringList(saveBluePublicKey);
final List<int> publicKeyDataList = changeStringListToIntList(publicKey!);
final List<String>? token = await Storage.getStringList(saveBlueToken);
List<int> getTokenList = <int>[0, 0, 0, 0];
if (token != null) {
getTokenList = changeStringListToIntList(token);
}
IoSenderManage.senderAddUser(
lockID: BlueManage().connectDeviceName,
authUserID: await Storage.getUid(),
keyID: '1',
userID: await Storage.getUid(),
openMode: 1,
keyType: 1,
startDate: DateTime.now().millisecondsSinceEpoch ~/ 1000,
expireDate: 0x11223344,
useCountLimit: 0xFFFF,
isRound: 0,
weekRound: 0,
startHour: 0,
startMin: 0,
endHour: 0,
endMin: 0,
role: state.role,
password: state.adminPassword,
needAuthor: 1,
publicKey: publicKeyDataList,
privateKey: getPrivateKeyList,
token: getTokenList,
isBeforeAddUser: true);
} else if (deviceConnectionState == BluetoothConnectionState.disconnected) {
dismissEasyLoading();
cancelBlueConnetctToastTimer();
state.sureBtnState.value = 0;
if (state.ifCurrentScreen.value == true) {
showBlueConnetctToast();
}
}
}, isAddEquipment: true);
}
// 设置管理员密码(同添加自定义开锁密码,指纹/密码/卡片前5个是管理员)
// Future<void> senderCustomPasswords() async {
//
// showTitleEasyLoading("添加锁进行中 2/2");
// // showEasyLoading();
// showBlueConnetctToastTimer(isShowBlueConnetctToast: false, action: (){
// // AppLog.log("添加管理员密码超时");
// dismissEasyLoading();
// state.sureBtnState.value = 0;
// if(state.ifCurrentScreen.value == true){
// showBlueConnetctToast();
// }
// // backAction();
// });
// BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
// if (deviceConnectionState == BluetoothConnectionState.connected) {
// var signKey = await Storage.getStringList(saveBlueSignKey);
// List<int> signKeyDataList = changeStringListToIntList(signKey!);
//
// var privateKey = await Storage.getStringList(saveBluePrivateKey);
// List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
//
// var token = await Storage.getStringList(saveBlueToken);
// List<int> getTokenList = changeStringListToIntList(token!);
//
// IoSenderManage.senderCustomPasswordsCommand(
// keyID: "1",
// // userID: await Storage.getUid(),
// userID: "0",
// pwdNo: 0,
// pwd: state.adminPassword,
// operate: 0,
// isAdmin: 1,
// useCountLimit: 0xffff,
// startTime: 0x11223344,
// endTime: 0x11223344,
// needAuthor: 1,
// isBeforeAddUser: true,
// signKey: signKeyDataList,
// privateKey: getPrivateKeyList,
// token: getTokenList);
// } else if (deviceConnectionState == BluetoothConnectionState.disconnected) {
// dismissEasyLoading();
// state.sureBtnState.value = 0;
// if(state.ifCurrentScreen.value == true){
// showBlueConnetctToast();
// }
// // backAction();
// }
// }, isAddEquipment: true);
// }
// 修改管理员密码(同添加自定义开锁密码,指纹/密码/卡片前5个是管理员)
// Future<void> changeAdministratorPasswordCommand() async {
// showEasyLoading();
// showBlueConnetctToastTimer(action: (){
// dismissEasyLoading();
// });
// BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async {
// if (deviceConnectionState == BluetoothConnectionState.connected) {
// var signKey = await Storage.getStringList(saveBlueSignKey);
// List<int> signKeyDataList = changeStringListToIntList(signKey!);
//
// var privateKey = await Storage.getStringList(saveBluePrivateKey);
// List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
//
// var token = await Storage.getStringList(saveBlueToken);
// List<int> getTokenList = changeStringListToIntList(token!);
//
// IoSenderManage.changeAdministratorPasswordCommand(
// keyID: "1",
// userID: await Storage.getUid(),
// pwdNo: 254,
// pwd:state.adminPasswordTF.text,
// useCountLimit: 0xff,
// startTime: 0x11223344,
// endTime: 0x11223344,
// needAuthor: 1,
// isBeforeAddUser: true,
// signKey: signKeyDataList,
// privateKey: getPrivateKeyList,
// token: getTokenList);
// } else if (deviceConnectionState == BluetoothConnectionState.disconnected) {
// dismissEasyLoading();
// cancelBlueConnetctToastTimer();
// state.saveBtnIsUsable.value = true;
// if(state.ifCurrentScreen.value == true){
// showBlueConnetctToast();
// }
// }
// }, isAddEquipment: true);
// }
void bindBlueAdmin() async {
state.lockInfo['adminPwd'] = state.adminPassword;
// final Map<String, dynamic> positionMap = <String, dynamic>{};
// positionMap['longitude'] = state.addressInfo['longitude'];
// positionMap['latitude'] = state.addressInfo['latitude'];
// positionMap['country'] = state.addressInfo['country'];
// positionMap['province'] = state.addressInfo['province'];
// positionMap['city'] = state.addressInfo['city'];
// positionMap['district'] = state.addressInfo['district'];
// positionMap['township'] = state.addressInfo['street'];
// positionMap['address'] = state.addressInfo['address'];
final Map<String, dynamic> bluetooth = <String, dynamic>{};
bluetooth['bluetoothDeviceId'] = state.lockInfo['mac'];
bluetooth['bluetoothDeviceName'] = BlueManage().connectDeviceName;
final List<String>? publicKey = await Storage.getStringList(saveBluePublicKey);
final List<int> publicKeyDataList = changeStringListToIntList(publicKey!);
bluetooth['publicKey'] = publicKeyDataList;
final List<String>? privateKey = await Storage.getStringList(saveBluePrivateKey);
final List<int> getPrivateKeyList = changeStringListToIntList(privateKey!);
bluetooth['privateKey'] = getPrivateKeyList;
final List<String>? signKey = await Storage.getStringList(saveBlueSignKey);
final List<int> signKeyDataList = changeStringListToIntList(signKey!);
bluetooth['signKey'] = signKeyDataList;
final SaveLockEntity entity = await ApiRepository.to.bindingBlueAdmin(
lockAlias: state.aliName.value,
position: {},
bluetooth: bluetooth,
lockInfo: state.lockInfo,
lockUserNo: state.lockUserNo.toString(),
pwdTimestamp: state.pwdTimestamp.value.toString(),
featureValue: state.featureValue,
featureSettingValue: state.featureSettingValue,
featureSettingParams: state.featureSettingParams,
);
if (entity.errorCode!.codeIsSuccessful) {
state.lockId = entity.data!.lockId!;
final String getMobile = (await Storage.getMobile())!;
ApmHelper.instance.trackEvent('save_lock_result', {
'lock_name': BlueManage().connectDeviceName,
'account': getMobile.isNotEmpty ? getMobile : (await Storage.getEmail())!,
'date': DateTool().getNowDateWithType(1),
'save_lock_result': '成功',
});
backAction();
// await senderCustomPasswords();
// BlueManage().disconnect(BlueManage().connectDeviceMacAddress);
// eventBus.fire(RefreshLockListInfoDataEvent());
// Get.close(state.isFromMap == 1 ? 5 : 6);
} else {
state.sureBtnState.value = 0;
final String getMobile = (await Storage.getMobile())!;
ApmHelper.instance.trackEvent('save_lock_result', {
'lock_name': BlueManage().connectDeviceName,
'account': getMobile.isNotEmpty ? getMobile : (await Storage.getEmail())!,
'date': DateTool().getNowDateWithType(1),
'save_lock_result': '${entity.errorCode}--${entity.errorMsg}',
});
}
}
// 更新管理员密码
// void addLockAdminPassword(bool isAddLockAdminPassword) async {
// var entity = await ApiRepository.to.setAdminPasswordData(
// lockId: state.lockId,
// adminPwd: state.adminPassword,
// );
// // if (entity.errorCode!.codeIsSuccessful) {
// // if(isAddLockAdminPassword == true){
// // showDeletPasswordAlertDialog();
// // }else{
// backAction();
// // }
// // }
// }
// void showDeletPasswordAlertDialog() {
// showDialog(
// context: Get.context!,
// builder: (BuildContext context) {
// return ShowTFView(
// title: "管理员密码",
// tipTitle: "如需修改,请输入新的管理员密码(6位),点击确定即可修改",
// leftBtnTitle: "确定".tr,
// rightBtnTitle: "修改",
// keyboardType: TextInputType.number,
// inputFormatters: [
// FilteringTextInputFormatter.allow(RegExp('[0-9]')),
// LengthLimitingTextInputFormatter(6),
// ],
// controller: state.adminPasswordTF,
// sureClick: () {
// if(state.adminPasswordTF.text.length < 6){
// showToast("请输入6位管理员密码".tr);
// return;
// }
//
// if(state.adminPasswordTF.text == state.adminPassword){
// showToast("请输入新的管理员密码".tr);
// return;
// }
// changeAdministratorPasswordCommand();
// },
// cancelClick: () {
// backAction();
// },
// );
// },
// );
// }
void backAction() async {
// BlueManage().disconnect();
// 查询锁设置信息
final LockSetInfoEntity entity = await ApiRepository.to.getLockSettingInfoData(
lockId: state.lockId.toString(),
);
if (entity.errorCode!.codeIsSuccessful) {
state.lockSetInfoData.value = entity.data!;
if (state.lockSetInfoData.value.lockFeature?.wifi == 1) {
// 如果是wifi锁需要配置WIFI
Get.toNamed(Routers.wifiListPage, arguments: {'lockSetInfoData': state.lockSetInfoData.value, 'pageName': 'saveLock'});
} else if (state.lockSetInfoData.value.lockFeature?.languageSpeech == 1) {
Get.toNamed(Routers.lockVoiceSettingPage, arguments: {'lockSetInfoData': state.lockSetInfoData.value, 'pageName': 'saveLock'});
} else {
eventBus.fire(RefreshLockListInfoDataEvent(clearScanDevices: true, isUnShowLoading: true));
Future<void>.delayed(const Duration(seconds: 1), () {
// Get.close(state.isFromMap == 1
// ? (CommonDataManage().seletLockType == 0 ? 4 : 5)
// : (CommonDataManage().seletLockType == 0 ? 5 : 6));
Get.until((route) => route.isFirst);
});
//刚刚配对完,需要对开锁页锁死 2 秒
Future<void>.delayed(const Duration(milliseconds: 200), () {
if (Get.isRegistered<LockDetailLogic>()) {
Get.find<LockDetailLogic>().functionBlocker.countdownProhibited(duration: const Duration(seconds: 2));
}
});
}
} else {
eventBus.fire(RefreshLockListInfoDataEvent(clearScanDevices: true, isUnShowLoading: true));
Future<void>.delayed(const Duration(seconds: 1), () {
// Get.close(state.isFromMap == 1
// ? (CommonDataManage().seletLockType == 0 ? 4 : 5)
// : (CommonDataManage().seletLockType == 0 ? 5 : 6));
Get.until((route) => route.isFirst);
});
//刚刚配对完,需要对开锁页锁死 2 秒
Future<void>.delayed(const Duration(milliseconds: 200), () {
if (Get.isRegistered<LockDetailLogic>()) {
Get.find<LockDetailLogic>().functionBlocker.countdownProhibited(duration: const Duration(seconds: 2));
}
});
}
}
@override
void onReady() {
super.onReady();
_initReplySubscription();
senderReadAdminPassword();
}
@override
void onInit() {
super.onInit();
}
@override
void onClose() {
_replySubscription.cancel();
super.onClose();
}
}