import 'dart:async'; 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/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/commonDataManage.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 _replySubscription; void _initReplySubscription() { _replySubscription = EventBusManager().eventBus!.on().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); // } }); } // 添加用户 Future _replyAddUserKey(Reply reply) async { final List token = reply.data.sublist(42, 46); final List 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? privateKey = await Storage.getStringList(saveBluePrivateKey); final List getPrivateKeyList = changeStringListToIntList(privateKey!); final List? publicKey = await Storage.getStringList(saveBluePublicKey); final List 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 _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 getPrivateKeyList = changeStringListToIntList(privateKey!); // // var signKey = await Storage.getStringList(saveBlueSignKey); // List 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 _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 signKeyDataList = changeStringListToIntList(signKey!); // // var privateKey = await Storage.getStringList(saveBluePrivateKey); // List 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 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? privateKey = await Storage.getStringList(saveBluePrivateKey); final List getPrivateKeyList = changeStringListToIntList(privateKey!); final List? publicKey = await Storage.getStringList(saveBluePublicKey); final List publicKeyDataList = changeStringListToIntList(publicKey!); final List? token = await Storage.getStringList(saveBlueToken); List getTokenList = [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: 255, 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 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 signKeyDataList = changeStringListToIntList(signKey!); // // var privateKey = await Storage.getStringList(saveBluePrivateKey); // List getPrivateKeyList = changeStringListToIntList(privateKey!); // // var token = await Storage.getStringList(saveBlueToken); // List 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 changeAdministratorPasswordCommand() async { // showEasyLoading(); // showBlueConnetctToastTimer(action: (){ // dismissEasyLoading(); // }); // BlueManage().bludSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { // if (deviceConnectionState == BluetoothConnectionState.connected) { // var signKey = await Storage.getStringList(saveBlueSignKey); // List signKeyDataList = changeStringListToIntList(signKey!); // // var privateKey = await Storage.getStringList(saveBluePrivateKey); // List getPrivateKeyList = changeStringListToIntList(privateKey!); // // var token = await Storage.getStringList(saveBlueToken); // List 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 positionMap = {}; // 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 bluetooth = {}; bluetooth['bluetoothDeviceId'] = BlueManage().connectDeviceMacAddress; bluetooth['bluetoothDeviceName'] = BlueManage().connectDeviceName; final List? publicKey = await Storage.getStringList(saveBluePublicKey); final List publicKeyDataList = changeStringListToIntList(publicKey!); bluetooth['publicKey'] = publicKeyDataList; final List? privateKey = await Storage.getStringList(saveBluePrivateKey); final List getPrivateKeyList = changeStringListToIntList(privateKey!); bluetooth['privateKey'] = getPrivateKeyList; final List? signKey = await Storage.getStringList(saveBlueSignKey); final List 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.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.delayed(const Duration(milliseconds: 200), () { if (Get.isRegistered()) { Get.find() .functionBlocker .countdownProhibited(duration: const Duration(seconds: 2)); } }); } } else { eventBus.fire(RefreshLockListInfoDataEvent( clearScanDevices: true, isUnShowLoading: true)); Future.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.delayed(const Duration(milliseconds: 200), () { if (Get.isRegistered()) { Get.find() .functionBlocker .countdownProhibited(duration: const Duration(seconds: 2)); } }); } } @override void onReady() { super.onReady(); _initReplySubscription(); } @override void onInit() { super.onInit(); } @override void onClose() { _replySubscription.cancel(); super.onClose(); } }