diff --git a/images/lan/lan_en.json b/images/lan/lan_en.json index 630c677c..09fb7bec 100755 --- a/images/lan/lan_en.json +++ b/images/lan/lan_en.json @@ -680,7 +680,7 @@ "密码生成后,请在当日23:59前使用一次进行激活,否则过0点后未激活则失效。密码激活后,有效期内不限次数使用。": "After the password is generated, please use it once for activation before 23:59 on the same day, otherwise it will be invalid after 0 o'clock. After the password is activated, it can be used unlimited times within the validity period.", "密码生成后,请在当日23:59前使用,否则过0点后失效。清空码用于清空今天0点之前生成的所有密码。": "After the password is generated, please use it before 23:59 on the same day, otherwise it will be invalid after 0 o'clock. The clear code is used to clear all the passwords generated before 0 o'clock today.", "密码生成后,请在当日23:59前使用,否则过0点后失效。": "After the password is generated, please use it before 23:59 on the same day, otherwise it will be invalid after 0 o'clock.", - "清空密码底部提示": "The password is valid until 24 o 'clock on the day of emptying\nEmpty content 1: All passwords except custom generated before 0 o 'clock on the same day (passwords generated after 0 o 'clock on the same day are not affected by the empty password and can continue to be used) \nEmpty content 2: Clear passwords Clear all custom passwords (used and unused) immediately after use \nTo completely clear all passwords, use the Reset All Passwords feature", + "清空密码底部提示": "The password is valid until 24 o 'clock on the day of emptying\n Empty Content 1: All passwords generated before 0:00 of the day (Passwords generated after 0:00 of the day are not affected by clearing passwords and can continue to be used) \nEmpty content 2: Clear passwords Clear all custom passwords (used and unused) immediately after use \nTo completely clear all passwords, use the Reset All Passwords feature", "相机": "camera", "相册": "photos", "读写": "storage", diff --git a/images/lan/lan_zh.json b/images/lan/lan_zh.json index b83194c6..c8671034 100755 --- a/images/lan/lan_zh.json +++ b/images/lan/lan_zh.json @@ -683,7 +683,7 @@ "密码生成后,请在当日23:59前使用一次进行激活,否则过0点后未激活则失效。密码激活后,有效期内不限次数使用。": "密码生成后,请在当日23:59前使用一次进行激活,否则过0点后未激活则失效。密码激活后,有效期内不限次数使用。", "密码生成后,请在当日23:59前使用,否则过0点后失效。清空码用于清空今天0点之前生成的所有密码。": "密码生成后,请在当日23:59前使用,否则过0点后失效。清空码用于清空今天0点之前生成的所有密码。", "密码生成后,请在当日23:59前使用,否则过0点后失效。": "密码生成后,请在当日23:59前使用,否则过0点后失效。", - "清空密码底部提示": "清空密码当日24点前有效\n清空内容1:当日0点前生成的除自定义以外所有密码(当日0点后生成的密码,不受清空密码影响,可继续使用)\n清空内容2:清空密码使用后,立即清除所有自定义密码(含使用过和未使用过的)\n如需彻底清除所有密码,请使用重置所有密码功能", + "清空密码底部提示": "清空密码当日24点前有效\n清空内容1:当日0点前生成的所有密码(当日0点后生成的密码,不受清空密码影响,可继续使用)\n清空内容2:清空密码使用后,立即清除所有自定义密码(含使用过和未使用过的)\n如需彻底清除所有密码,请使用重置所有密码功能", "密码不一致哦": "密码不一致哦", "相机": "相机", "相册": "相册", diff --git a/images/main/icon_addFingerprint_fingerprint_six.png b/images/main/icon_addFingerprint_fingerprint_six.png new file mode 100644 index 00000000..a1e9b54c Binary files /dev/null and b/images/main/icon_addFingerprint_fingerprint_six.png differ diff --git a/lib/blue/blue_manage.dart b/lib/blue/blue_manage.dart index 5ae2f0df..dba9581c 100755 --- a/lib/blue/blue_manage.dart +++ b/lib/blue/blue_manage.dart @@ -144,12 +144,11 @@ class BlueManage { if (isAvailable) { if (_adapterState == BluetoothAdapterState.on) { try { - //android 扫描比较慢,取样只要 8 分之一 + //android 扫描比较慢,取样只要 3 分之一 final int divisor = Platform.isAndroid ? 3 : 1; FlutterBluePlus.startScan( continuousDivisor: divisor, continuousUpdates: true, - // withServiceData:[ServiceDataFilter()], withKeywords: [deviceName], timeout: Duration(seconds: timeout)); final Completer completer = Completer(); @@ -317,7 +316,7 @@ class BlueManage { if (isAddEquipment == false && isExistDevice == false) { //取消缓存直接使用,存在配对场景设备信息会更变 - startScanSingle(deviceName, 10, (List scanDevices) { + startScanSingle(deviceName, 15, (List scanDevices) { _connectDevice(scanDevices, deviceName, connectStateCallBack, isAddEquipment: isAddEquipment); }); diff --git a/lib/main/lockDetail/card/addICCard/addICCard_state.dart b/lib/main/lockDetail/card/addICCard/addICCard_state.dart index fd7f9a67..7129795f 100755 --- a/lib/main/lockDetail/card/addICCard/addICCard_state.dart +++ b/lib/main/lockDetail/card/addICCard/addICCard_state.dart @@ -20,14 +20,13 @@ class AddICCardState{ final startDate = "".obs; final weekDay = [].obs; final fromType = 0.obs; - final effectiveDateTime = "".obs;// 生效时间 - final failureDateTime = "".obs;// 失效时间 - final selectType = "0".obs;// 0永久 1显示 2循环 + final effectiveDateTime = "".obs; // 生效时间 + final failureDateTime = "".obs; // 失效时间 + final selectType = "0".obs; // 0永久 1显示 2循环 AddICCardState() { Map map = Get.arguments; lockId.value = map["lockId"]; - endDate.value = "${int.parse(map["endDate"]) + CommonDataManage().dayLatestTime}"; addType.value = map["addType"]; cardName.value = map["cardName"]; cardNumber.value = map["cardNumber"]; @@ -40,5 +39,12 @@ class AddICCardState{ effectiveDateTime.value = map["effectiveTime"]; failureDateTime.value = map["failureTime"]; selectType.value = map["selectType"]; + //循环类型下,结束时间加一天 + if (selectType.value == '2') { + endDate.value = + "${int.parse(map["endDate"]) + CommonDataManage().dayLatestTime}"; + } else { + endDate.value = map["endDate"]; + } } -} \ No newline at end of file +} diff --git a/lib/main/lockDetail/card/cardDetail/cardDetail_page.dart b/lib/main/lockDetail/card/cardDetail/cardDetail_page.dart index f5676497..d669b4b8 100755 --- a/lib/main/lockDetail/card/cardDetail/cardDetail_page.dart +++ b/lib/main/lockDetail/card/cardDetail/cardDetail_page.dart @@ -153,12 +153,15 @@ class _CardDetailPageState extends State with RouteAware { })))), Container(height: 10.h), Obx(() => CommonItem( - leftTitel: TranslationLoader.lanKeys!.additive!.tr, - rightTitle: state.adder.value,)), + leftTitel: TranslationLoader.lanKeys!.additive!.tr, + isHaveLine: true, + rightTitle: state.adder.value, + )), Obx(() => CommonItem( - leftTitel: TranslationLoader.lanKeys!.addTime!.tr, - rightTitle: DateTool().dateToYMDHNString(state.addTime.value.toString()), - )), + leftTitel: TranslationLoader.lanKeys!.addTime!.tr, + rightTitle: DateTool() + .dateToYMDHNString(state.addTime.value.toString()), + )), SizedBox(height: 10.h), Obx(() => CommonItem( leftTitel: TranslationLoader.lanKeys!.stressCard!.tr, diff --git a/lib/main/lockDetail/checkingIn/checkingInList/checkingInList_page.dart b/lib/main/lockDetail/checkingIn/checkingInList/checkingInList_page.dart index 17e73087..2e80f194 100755 --- a/lib/main/lockDetail/checkingIn/checkingInList/checkingInList_page.dart +++ b/lib/main/lockDetail/checkingIn/checkingInList/checkingInList_page.dart @@ -1,3 +1,4 @@ +import 'package:cached_network_image/cached_network_image.dart'; import 'package:date_format/date_format.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -409,10 +410,23 @@ class _CheckingInListPageState extends State { else ClipRRect( borderRadius: BorderRadius.circular(100.w), - child: Image.network( - headUrl, + child: CachedNetworkImage( width: 60.w, height: 60.w, + imageUrl: headUrl, + placeholder: (BuildContext context, String url) => + const SizedBox(), + errorWidget: + (BuildContext context, String url, Object error) => + Container( + color: const Color(0xffEBF4FF), + child: Center( + child: Text( + name!.substring(0, 2), + style: TextStyle( + fontSize: 22.sp, color: const Color(0xff7F9CF5)), + )), + ), ), ), SizedBox(width: 20.w), diff --git a/lib/main/lockDetail/checkingIn/checkingInStaff/checkingInSetStaffList/checkingInStaffList_page.dart b/lib/main/lockDetail/checkingIn/checkingInStaff/checkingInSetStaffList/checkingInStaffList_page.dart index 9f58f45e..b9d88109 100755 --- a/lib/main/lockDetail/checkingIn/checkingInStaff/checkingInSetStaffList/checkingInStaffList_page.dart +++ b/lib/main/lockDetail/checkingIn/checkingInStaff/checkingInSetStaffList/checkingInStaffList_page.dart @@ -1,3 +1,4 @@ +import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; @@ -154,10 +155,23 @@ class _CheckingInStaffListPageState extends State { else ClipRRect( borderRadius: BorderRadius.circular(100.w), - child: Image.network( - staffListItem.headurl!, + child: CachedNetworkImage( width: 60.w, height: 60.w, + imageUrl: staffListItem.headurl!, + placeholder: (BuildContext context, String url) => + const SizedBox(), + errorWidget: + (BuildContext context, String url, Object error) => + Container( + color: const Color(0xffEBF4FF), + child: Center( + child: Text( + staffListItem.staffName!.substring(0, 2), + style: TextStyle( + fontSize: 22.sp, color: const Color(0xff7F9CF5)), + )), + ), ), ), SizedBox( diff --git a/lib/main/lockDetail/face/addFace/addFace_state.dart b/lib/main/lockDetail/face/addFace/addFace_state.dart index 7cd2938a..dc8b6632 100755 --- a/lib/main/lockDetail/face/addFace/addFace_state.dart +++ b/lib/main/lockDetail/face/addFace/addFace_state.dart @@ -26,14 +26,13 @@ class AddFaceState { final startDate = "".obs; final weekDay = [].obs; final fromType = 0.obs; - final effectiveDateTime = "".obs;// 生效时间 - final failureDateTime = "".obs;// 失效时间 - final selectType = "0".obs;// 0永久 1显示 2循环 + final effectiveDateTime = "".obs; // 生效时间 + final failureDateTime = "".obs; // 失效时间 + final selectType = "0".obs; // 0永久 1显示 2循环 AddFaceState() { Map map = Get.arguments; lockId.value = map["lockId"]; - endDate.value = "${int.parse(map["endDate"]) + CommonDataManage().dayLatestTime}"; addType.value = map["addType"]; faceName.value = map["faceName"]; faceType.value = map["faceType"]; @@ -48,5 +47,12 @@ class AddFaceState { effectiveDateTime.value = map["effectiveTime"]; failureDateTime.value = map["failureTime"]; selectType.value = map["selectType"]; + //循环类型下,结束时间加一天 + if (selectType.value == '2') { + endDate.value = + "${int.parse(map["endDate"]) + CommonDataManage().dayLatestTime}"; + } else { + endDate.value = map["endDate"]; + } } } diff --git a/lib/main/lockDetail/fingerprint/addFingerprint/addFingerprint_page.dart b/lib/main/lockDetail/fingerprint/addFingerprint/addFingerprint_page.dart index b966d9df..85db4602 100755 --- a/lib/main/lockDetail/fingerprint/addFingerprint/addFingerprint_page.dart +++ b/lib/main/lockDetail/fingerprint/addFingerprint/addFingerprint_page.dart @@ -1,4 +1,3 @@ - import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; @@ -17,7 +16,8 @@ class AddFingerprintPage extends StatefulWidget { State createState() => _AddFingerprintPageState(); } -class _AddFingerprintPageState extends State with RouteAware { +class _AddFingerprintPageState extends State + with RouteAware { final logic = Get.put(AddFingerprintLogic()); final state = Get.find().state; @@ -26,7 +26,8 @@ class _AddFingerprintPageState extends State with RouteAware return Scaffold( backgroundColor: Colors.white, appBar: TitleAppBar( - barTitle: "${TranslationLoader.lanKeys!.addTip!.tr}${TranslationLoader.lanKeys!.fingerprint!.tr}", + barTitle: + "${TranslationLoader.lanKeys!.addTip!.tr}${TranslationLoader.lanKeys!.fingerprint!.tr}", haveBack: true, backgroundColor: AppColors.mainColor), body: ListView( @@ -35,62 +36,66 @@ class _AddFingerprintPageState extends State with RouteAware height: 50.h, ), Obx(() => Visibility( - visible:logic.state.ifConnectScuess.value, - child: Container( - padding: EdgeInsets.only(left: 20.w, right: 20.w), - child: Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.center, + visible: logic.state.ifConnectScuess.value, + child: Container( + padding: EdgeInsets.only(left: 20.w, right: 20.w), + child: Column( children: [ - Expanded( - child: Text( - "请将您的手指按下".tr, - // TranslationLoader.lanKeys!.lightTouchScreenTip!.tr, - textAlign: TextAlign.center, - maxLines:null, - style: TextStyle(fontSize: 24.sp, fontWeight: FontWeight.w600), - ), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Expanded( + child: Text( + "请将您的手指按下".tr, + // TranslationLoader.lanKeys!.lightTouchScreenTip!.tr, + textAlign: TextAlign.center, + maxLines: null, + style: TextStyle( + fontSize: 24.sp, fontWeight: FontWeight.w600), + ), + ), + ], + ), + SizedBox(height: 10.h), + Text( + "(${state.regIndex.value}/${state.maxRegCount.value})", + // TranslationLoader.lanKeys!.lightTouchScreenTip!.tr, + textAlign: TextAlign.center, + maxLines: null, + style: TextStyle(fontSize: 24.sp), ), ], ), - SizedBox(height: 10.h), - Text( - "(${state.regIndex.value}/${state.maxRegCount.value})", - // TranslationLoader.lanKeys!.lightTouchScreenTip!.tr, - textAlign: TextAlign.center, - maxLines:null, - style: TextStyle(fontSize: 24.sp), - ), - ], - ), - ), - )), - Obx(() => Visibility( - visible:!logic.state.ifConnectScuess.value, - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Expanded( - child: Text( - "尝试连接设备...".tr, - // TranslationLoader.lanKeys!.lightTouchScreenTip!.tr, - textAlign: TextAlign.center, - maxLines:null, - style: TextStyle(fontSize: 24.sp, fontWeight: FontWeight.w600), - ), ), - ], - ), - )), + )), + Obx(() => Visibility( + visible: !logic.state.ifConnectScuess.value, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Expanded( + child: Text( + "尝试连接设备...".tr, + // TranslationLoader.lanKeys!.lightTouchScreenTip!.tr, + textAlign: TextAlign.center, + maxLines: null, + style: TextStyle( + fontSize: 24.sp, fontWeight: FontWeight.w600), + ), + ), + ], + ), + )), SizedBox( height: 100.h, ), - Obx(() => Image.asset( - getIconNumber(state.regIndex.value), - width: 185.w, - height: 295.h, - ),), + Obx( + () => Image.asset( + getIconNumber(state.regIndex.value), + width: 185.w, + height: 295.h, + ), + ), SizedBox( height: 120.h, ), @@ -104,7 +109,7 @@ class _AddFingerprintPageState extends State with RouteAware "根据提示,抬起手指后再进行下一次指纹采集".tr, // TranslationLoader.lanKeys!.lightTouchScreenTip!.tr, textAlign: TextAlign.center, - maxLines:null, + maxLines: null, style: TextStyle(fontSize: 24.sp), ), ), @@ -116,9 +121,9 @@ class _AddFingerprintPageState extends State with RouteAware ); } - String getIconNumber(int number){ + String getIconNumber(int number) { String iconPath = ""; - switch(number){ + switch (number) { case 0: iconPath = 'images/main/icon_addFingerprint_fingerprint_one.png'; break; @@ -134,8 +139,11 @@ class _AddFingerprintPageState extends State with RouteAware case 4: iconPath = 'images/main/icon_addFingerprint_fingerprint_five.png'; break; + case 5: + iconPath = 'images/main/icon_addFingerprint_fingerprint_six.png'; + break; default: - iconPath = 'images/main/icon_addFingerprint_fingerprint_four.png'; + iconPath = 'images/main/icon_addFingerprint_fingerprint_six.png'; break; } return iconPath; @@ -172,7 +180,7 @@ class _AddFingerprintPageState extends State with RouteAware logic.cancelBlueConnetctToastTimer(); state.ifCurrentScreen.value = false; - if(state.ifAddState.value){ + if (state.ifAddState.value) { logic.senderCancelAddFingerprintCommand(); } } @@ -192,5 +200,4 @@ class _AddFingerprintPageState extends State with RouteAware state.ifCurrentScreen.value = false; } - } diff --git a/lib/main/lockDetail/fingerprint/addFingerprint/addFingerprint_state.dart b/lib/main/lockDetail/fingerprint/addFingerprint/addFingerprint_state.dart index 55fe1bf0..5579e8c2 100755 --- a/lib/main/lockDetail/fingerprint/addFingerprint/addFingerprint_state.dart +++ b/lib/main/lockDetail/fingerprint/addFingerprint/addFingerprint_state.dart @@ -22,14 +22,13 @@ class AddFingerprintState{ final startDate = "".obs; final weekDay = [].obs; final fromType = 1.obs; - final effectiveDateTime = "".obs;// 生效时间 - final failureDateTime = "".obs;// 失效时间 - final selectType = "0".obs;// 0永久 1显示 2循环 + final effectiveDateTime = "".obs; // 生效时间 + final failureDateTime = "".obs; // 失效时间 + final selectType = "0".obs; // 0永久 1显示 2循环 AddFingerprintState() { Map map = Get.arguments; lockId.value = map["lockId"]; - endDate.value = "${int.parse(map["endDate"]) + CommonDataManage().dayLatestTime}"; addType.value = map["addType"]; fingerprintName.value = map["fingerprintName"]; fingerprintType.value = map["fingerprintType"]; @@ -42,5 +41,12 @@ class AddFingerprintState{ effectiveDateTime.value = map["effectiveTime"]; failureDateTime.value = map["failureTime"]; selectType.value = map["selectType"]; + //循环类型下,结束时间加一天 + if (selectType.value == '2') { + endDate.value = + "${int.parse(map["endDate"]) + CommonDataManage().dayLatestTime}"; + } else { + endDate.value = map["endDate"]; + } } -} \ No newline at end of file +} diff --git a/lib/main/lockDetail/lockDetail/lockDetail_logic.dart b/lib/main/lockDetail/lockDetail/lockDetail_logic.dart index 50a4fa5b..c079f792 100755 --- a/lib/main/lockDetail/lockDetail/lockDetail_logic.dart +++ b/lib/main/lockDetail/lockDetail/lockDetail_logic.dart @@ -8,6 +8,7 @@ import 'package:permission_handler/permission_handler.dart'; import 'package:star_lock/common/XSConstantMacro/XSConstantMacro.dart'; import 'package:star_lock/main/lockDetail/electronicKey/electronicKeyList/entity/ElectronicKeyListEntity.dart'; import 'package:star_lock/main/lockDetail/lockSet/lockTime/getServerDatetime_entity.dart'; +import 'package:star_lock/tools/throttler.dart'; import 'package:star_lock/widget/permission/permission_dialog.dart'; @@ -33,6 +34,10 @@ import 'lockNetToken_entity.dart'; class LockDetailLogic extends BaseGetXController { final LockDetailState state = LockDetailState(); + //节流器,用来限制开锁按钮的触发频率 + FunctionBlocker functionBlocker = + FunctionBlocker(duration: const Duration(seconds: 2)); + // 监听设备返回的数据 void initReplySubscription() { state.replySubscription = @@ -114,10 +119,19 @@ class LockDetailLogic extends BaseGetXController { break; case 0x16: // 正在开锁中... + final int isOpen = reply.data[8]; + String? msg; + if (isOpen == 0) { + msg = '正在开锁中...'.tr; + } else if (isOpen == 32) { + msg = '正在闭锁中...'.tr; + } resetOpenDoorState(); - showToast('正在开锁中...'.tr, something: () { - cancelBlueConnetctToastTimer(); - }); + if (msg != null) { + showToast(msg, something: () { + cancelBlueConnetctToastTimer(); + }); + } break; case 0x0d: // 钥匙无效 @@ -161,14 +175,13 @@ class LockDetailLogic extends BaseGetXController { void openDoorError() { resetOpenDoorState(); state.animationController!.stop(); - cancelBlueConnetctToastTimer(); - BlueManage().disconnect(); + blueManageDisconnect(); } //清除开锁动画以及状态 void closeLuckStatus() { state.openLockBtnState.value = 0; - state.openDoorBtnisUneable.value = false; + state.openDoorBtnisUneable.value = true; state.animationController!.stop(canceled: true); cancelBlueConnetctToastTimer(); } @@ -225,29 +238,28 @@ class LockDetailLogic extends BaseGetXController { if (dataLength == state.logCountPage) { senderReferEventRecordTime(); } else { - await BlueManage().disconnect(); + await blueManageDisconnect(); } } break; case 0x06: //无权限 - BlueManage().disconnect(); - cancelBlueConnetctToastTimer(); + blueManageDisconnect(); break; default: - BlueManage().disconnect(); - cancelBlueConnetctToastTimer(); + blueManageDisconnect(); break; } } // 点击开门事件 Future openDoorAction() async { - showBlueConnetctToastTimer(action: () { - resetOpenDoorState(); - closeLuckStatus(); - BlueManage().disconnect(); - }); + showBlueConnetctToastTimer( + outTimer: 20, + action: () { + resetOpenDoorState(); + blueManageDisconnect(); + }); final List? privateKey = await Storage.getStringList(saveBluePrivateKey); final List getPrivateKeyList = changeStringListToIntList(privateKey!); @@ -285,13 +297,20 @@ class LockDetailLogic extends BaseGetXController { }); } + //蓝牙关闭 + Future blueManageDisconnect() async { + //顺便清除倒计时 + closeLuckStatus(); + cancelBlueConnetctToastTimer(); + await BlueManage().disconnect(); + } + // 查询事件记录(时间查询) void senderReferEventRecordTime() { showBlueConnetctToastTimer( isShowBlueConnetctToast: false, action: () { - closeLuckStatus(); - BlueManage().disconnect(); + blueManageDisconnect(); }); BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { @@ -325,7 +344,7 @@ class LockDetailLogic extends BaseGetXController { } // 从服务器获取锁的时间 开锁时传入 - void getServerDatetime() async { + Future getServerDatetime() async { final GetServerDatetimeEntity entity = await ApiRepository.to.getServerDatetimeData(); if (entity.errorCode!.codeIsSuccessful) { @@ -341,7 +360,7 @@ class LockDetailLogic extends BaseGetXController { } // 获取手机联网token,根据锁设置里面获取的开锁时是否联网来判断是否调用这个接口 - void getLockNetToken() async { + Future getLockNetToken() async { final LockNetTokenEntity entity = await ApiRepository.to .getLockNetToken(lockId: state.keyInfos.value.lockId.toString()); if (entity.errorCode!.codeIsSuccessful) { @@ -375,7 +394,7 @@ class LockDetailLogic extends BaseGetXController { } // 查询锁记录最后时间 - void getLockRecordLastUploadDataTime() async { + Future getLockRecordLastUploadDataTime() async { final LockOperatingRecordGetLastRecordTimeEntity entity = await ApiRepository.to.getLockRecordLastUploadDataTime( lockId: state.keyInfos.value.lockId.toString()); @@ -402,7 +421,7 @@ class LockDetailLogic extends BaseGetXController { } // 普通用户或者授权管理员删除钥匙 - void deletKeyData() async { + Future deletKeyData() async { final ElectronicKeyListEntity entity = await ApiRepository.to .deleteElectronicKey( keyId: state.keyInfos.value.keyId.toString(), includeUnderlings: 0); @@ -497,13 +516,6 @@ class LockDetailLogic extends BaseGetXController { await PermissionDialog.request(Permission.location); await PermissionDialog.requestBluetooth(); - - final String connectDeviceName = - state.keyInfos.value.bluetooth!.bluetoothDeviceName!; - if (!BlueManage().isExistScanDevices(connectDeviceName)) { - BlueManage().startScanSingle( - connectDeviceName, 15, (List p0) => null); - } } @override diff --git a/lib/main/lockDetail/lockDetail/lockDetail_page.dart b/lib/main/lockDetail/lockDetail/lockDetail_page.dart index ebbfa934..96a038ad 100755 --- a/lib/main/lockDetail/lockDetail/lockDetail_page.dart +++ b/lib/main/lockDetail/lockDetail/lockDetail_page.dart @@ -250,21 +250,27 @@ class _LockDetailPageState extends State ], ), child: Column( - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, children: [ const Spacer(), GestureDetector( - onTap: state.openDoorBtnisUneable.value == true - ? isNeedRealNameAuthThenOpenLock - : null, - onLongPressStart: state.openDoorBtnisUneable.value == true - ? (LongPressStartDetails details) { - setState(startUnLock); - } - : null, + onTap: () { + if (state.openDoorBtnisUneable.value == true) { + logic.functionBlocker.block(isNeedRealNameAuthThenOpenLock); + } + }, + onLongPressStart: (LongPressStartDetails details) { + if (state.openDoorBtnisUneable.value == true) { + void callback() { + setState(startUnLock); + } + + logic.functionBlocker.block(callback); + } + }, child: Container( - width: 100.r, - height: 100.r, + width: 200.r, + height: 200.r, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(100.w), @@ -276,51 +282,47 @@ class _LockDetailPageState extends State spreadRadius: 0, ), ]), - margin: EdgeInsets.only(left: 35.w, bottom: 15.h), + margin: EdgeInsets.only(top: 20.h), child: Stack( alignment: AlignmentDirectional.center, children: [ if (state.openDoorBtnisUneable.value == false) Icon( Icons.bluetooth_searching, - size: 48.r, - color: AppColors.mainColor, + size: 78.r, + color: AppColors.mainColor.withOpacity(0.6), ) else Image.asset( state.isOpenPassageMode.value == 1 ? 'images/icon_lock_err.png' : 'images/icon_lock_fill.png', - width: 38.r, - height: 38.r, + width: 68.r, + height: 68.r, color: AppColors.mainColor, ), - if (state.openDoorBtnisUneable.value == false) - Positioned( - child: Icon( - Icons.bluetooth_searching, - size: 96.r, - ), + if (state.openLockBtnState.value == 1) + xhjBuildRotationTransition( + width: 168.r, + height: 168.r, ) else - state.openLockBtnState.value == 1 - ? xhjBuildRotationTransition( - width: 88.r, - height: 88.r, - ) - : Positioned( - child: Image.asset( - 'images/icon_circle_dotted.png', - width: 88.r, - height: 88.r, - color: state.isOpenPassageMode.value == 1 - ? Colors.red - : AppColors.mainColor, - )), + Positioned( + child: Image.asset( + 'images/icon_circle_dotted.png', + width: 168.r, + height: 168.r, + color: state.openDoorBtnisUneable.value == false + ? AppColors.mainColor.withOpacity(0.6) + : state.isOpenPassageMode.value == 1 + ? Colors.red + : AppColors.mainColor, + )), ], ), ), ), + const Spacer(), Padding( padding: EdgeInsets.only(left: 15.w, right: 00.w, bottom: 15.h), child: Row( @@ -583,14 +585,20 @@ class _LockDetailPageState extends State children: [ Center( child: GestureDetector( - onTap: state.openDoorBtnisUneable.value == true - ? isNeedRealNameAuthThenOpenLock - : null, - onLongPressStart: state.openDoorBtnisUneable.value == true - ? (LongPressStartDetails details) { - setState(startUnLock); - } - : null, + onTap: () { + if (state.openDoorBtnisUneable.value == true) { + logic.functionBlocker.block(isNeedRealNameAuthThenOpenLock); + } + }, + onLongPressStart: (LongPressStartDetails details) { + if (state.openDoorBtnisUneable.value == true) { + void callback() { + setState(startUnLock); + } + + logic.functionBlocker.block(callback); + } + }, child: Stack( children: [ FlavorsImg( @@ -1347,7 +1355,7 @@ class _LockDetailPageState extends State state.iSOpenLock.value = false; state.openLockBtnState.value = 1; state.animationController!.forward(); - EasyLoading.showToast('正在尝试闭锁……'.tr, duration: 2000.milliseconds); + EasyLoading.showToast('正在尝试闭锁……'.tr, duration: 1000.milliseconds); AppLog.log('长按闭锁'); if (state.isOpenLockNeedOnline.value == 0) { // 不需要联网 diff --git a/lib/main/lockDetail/lockSet/lockEscalation/lockEscalation_logic.dart b/lib/main/lockDetail/lockSet/lockEscalation/lockEscalation_logic.dart index db0570b1..e1850e7a 100755 --- a/lib/main/lockDetail/lockSet/lockEscalation/lockEscalation_logic.dart +++ b/lib/main/lockDetail/lockSet/lockEscalation/lockEscalation_logic.dart @@ -48,16 +48,16 @@ class LockEscalationLogic extends BaseGetXController { //手动升级 Future otaUpdate() async { - var status = await PermissionDialog.requestStorage(); + final bool status = await PermissionDialog.requestStorage(); if (status != true) { return; } - FilePickerResult? result = await FilePicker.platform.pickFiles(); + final 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(); + final File file = File(result.files.single.path!); + final Uint8List data = await file.readAsBytes(); headJson = await getHeadFile(data); if (headJson is! Map) { return; @@ -66,15 +66,13 @@ class LockEscalationLogic extends BaseGetXController { if (otaBin == null) { return; } - String md5Str = md5.convert(otaBin!).toString(); + final String md5Str = md5.convert(otaBin!).toString(); headJson!['fwMd5'] = md5Str; - ShowTipView().showIosTipWithContentDialog("未避免异常情况,请在门打开时升级".tr, () async { + ShowTipView().showIosTipWithContentDialog('未避免异常情况,请在门打开时升级'.tr, () async { blueOTAUpgrade(headJson!, [0, 0, 0, 0]); EasyLoading.show( status: '设备连接中...'.tr, maskType: EasyLoadingMaskType.black); - Future.delayed(const Duration(seconds: 4), () { - EasyLoading.dismiss(); - }); + Future.delayed(const Duration(seconds: 4), EasyLoading.dismiss); }); } @@ -83,11 +81,11 @@ class LockEscalationLogic extends BaseGetXController { BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState deviceConnectionState) async { if (deviceConnectionState == BluetoothConnectionState.connected) { - var privateKey = await Storage.getStringList(saveBluePrivateKey); - List getPrivateKeyList = changeStringListToIntList(privateKey!); - var signKey = await Storage.getStringList(saveBlueSignKey); - List signKeyDataList = changeStringListToIntList(signKey!); - String uid = await Storage.getUid() ?? ''; + final privateKey = await Storage.getStringList(saveBluePrivateKey); + final List getPrivateKeyList = changeStringListToIntList(privateKey!); + final signKey = await Storage.getStringList(saveBlueSignKey); + final List signKeyDataList = changeStringListToIntList(signKey!); + final String uid = await Storage.getUid() ?? ''; BlueManage().writeCharacteristicWithResponse(OTAUpgradeCommand( lockID: BlueManage().connectDeviceName, userID: uid, @@ -113,30 +111,30 @@ class LockEscalationLogic extends BaseGetXController { if (!state.otaUpdateIng.value) { return; } - int length = otaBin?.length ?? 0; + final int length = otaBin?.length ?? 0; if (otaCount == 0) { //首次 - int difference = length % 240; + final int difference = length % 240; otaCount = length ~/ 240 + (difference > 0 ? 1 : 0); startSecond = DateTime.now().millisecondsSinceEpoch ~/ 1000; startOTAData(); } if (otaCount <= otaIndex) { - int now = DateTime.now().millisecondsSinceEpoch ~/ 1000; - String msg = + final int now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + final String msg = '传输完成 时间:${now - startSecond}秒 otaCount:$otaCount otaIndex:$otaIndex '; closeOTADAta(); AppLog.log(msg); // showToast(msg); return; } - int star = otaIndex * 240; + final int star = otaIndex * 240; int end = (otaIndex + 1) * 240; if (end > length) { end = length; } - int size = end - star; - List data = otaBin!.sublist(star, end); + final int size = end - star; + final List data = otaBin!.sublist(star, end); state.otaProgress.value = otaIndex / otaCount; await BlueManage().writeCharacteristicWithResponse( ProcessOtaUpgradeCommand(index: otaIndex, size: size, data: data) @@ -176,7 +174,8 @@ class LockEscalationLogic extends BaseGetXController { // 检查文件头 String header; try { - header = utf8.decode(data.sublist(0, 12)); + final Uint8List list = data.sublist(0, 12); + header = utf8.decode(list); } catch (e) { showToast('非SYD固件,请选择正确的文件'.tr); return null; @@ -210,7 +209,7 @@ class LockEscalationLogic extends BaseGetXController { return null; } AppLog.log(metaStr); - var meta = jsonDecode(metaStr); + final meta = jsonDecode(metaStr); if (meta is! Map) { showToast('解析元数据失败,请选择正确的文件'.tr); return null; @@ -220,11 +219,11 @@ class LockEscalationLogic extends BaseGetXController { //检测升级文件并读取 bin Future checkFile(Uint8List data, Map meta) async { - num binOffset = 16 + (meta['metaLen'] ?? 0); + final num binOffset = 16 + (meta['metaLen'] ?? 0); // 获取固件数据部分 - Uint8List bin = data.sublist(binOffset.toInt(), data.length); + final Uint8List bin = data.sublist(binOffset.toInt(), data.length); //md5 校验有问题,暂时不解析 - String md5Str = md5.convert(bin).toString().toUpperCase(); + final String md5Str = md5.convert(bin).toString().toUpperCase(); AppLog.log('固件 md5 检验md5:$md5Str 固件信息 md5:${meta['fwMd5']}'); if (md5Str != meta['fwMd5']) { showToast('文件校验失败 0x02'.tr); diff --git a/lib/main/lockDetail/lockSet/lockSet/lockSet_logic.dart b/lib/main/lockDetail/lockSet/lockSet/lockSet_logic.dart index e0b17943..b90056e3 100755 --- a/lib/main/lockDetail/lockSet/lockSet/lockSet_logic.dart +++ b/lib/main/lockDetail/lockSet/lockSet/lockSet_logic.dart @@ -1,4 +1,3 @@ - import 'dart:async'; import 'package:flutter/scheduler.dart'; @@ -24,7 +23,8 @@ import 'lockSetInfo_entity.dart'; import 'lockSet_state.dart'; typedef BlockSetStateCallback = void Function(); -typedef BlockSetCheckInCallback = void Function(CheckingInInfoDataEntity checkingInInfoDataEntity); +typedef BlockSetCheckInCallback = void Function( + CheckingInInfoDataEntity checkingInInfoDataEntity); class LockSetLogic extends BaseGetXController { final LockSetState state = LockSetState(); @@ -40,12 +40,14 @@ class LockSetLogic extends BaseGetXController { // } // 恢复出厂设置 - if (reply is FactoryDataResetReply && (state.ifCurrentScreen.value == true)) { + if (reply is FactoryDataResetReply && + (state.ifCurrentScreen.value == true)) { _replyFactoryDataResetKey(reply); } // 设置支持功能(不带参数) - if ((reply is SetSupportFunctionsNoParametersReply) && (state.ifCurrentScreen.value == true)) { + if ((reply is SetSupportFunctionsNoParametersReply) && + (state.ifCurrentScreen.value == true)) { _replySetSupportFunctionsWithParameters(reply); } @@ -124,7 +126,7 @@ class LockSetLogic extends BaseGetXController { IoSenderManage.senderFactoryDataReset( lockID: BlueManage().connectDeviceName, userID: await Storage.getUid(), - keyID: "1", + keyID: '1', needAuthor: 1, publicKey: publicKeyDataList, privateKey: getPrivateKeyList, @@ -241,11 +243,14 @@ class LockSetLogic extends BaseGetXController { // 恢复出厂设置 Future factoryDataResetAction() async { showEasyLoading(); - showBlueConnetctToastTimer(isShowBlueConnetctToast: false, action: (){ - dismissEasyLoading(); - showDeletAlertTipDialog(); - }); - BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { + showBlueConnetctToastTimer( + isShowBlueConnetctToast: false, + action: () { + dismissEasyLoading(); + showDeletAlertTipDialog(); + }); + BlueManage().blueSendData(BlueManage().connectDeviceName, + (BluetoothConnectionState connectionState) async { if (connectionState == BluetoothConnectionState.connected) { var privateKey = await Storage.getStringList(saveBluePrivateKey); List getPrivateKeyList = changeStringListToIntList(privateKey!); @@ -259,7 +264,7 @@ class LockSetLogic extends BaseGetXController { IoSenderManage.senderFactoryDataReset( lockID: BlueManage().connectDeviceName, userID: await Storage.getUid(), - keyID: "1", + keyID: '1', needAuthor: 1, publicKey: publicKeyDataList, privateKey: getPrivateKeyList, @@ -267,7 +272,7 @@ class LockSetLogic extends BaseGetXController { } else if (connectionState == BluetoothConnectionState.disconnected) { dismissEasyLoading(); cancelBlueConnetctToastTimer(); - if(state.ifCurrentScreen.value == true){ + if (state.ifCurrentScreen.value == true) { showDeletAlertTipDialog(); } } @@ -303,10 +308,11 @@ class LockSetLogic extends BaseGetXController { // 设置支持功能(带参数) Future sendBurglarAlarm(int type) async { showEasyLoading(); - showBlueConnetctToastTimer(action: (){ + showBlueConnetctToastTimer(action: () { dismissEasyLoading(); }); - BlueManage().blueSendData(BlueManage().connectDeviceName, (BluetoothConnectionState connectionState) async { + BlueManage().blueSendData(BlueManage().connectDeviceName, + (BluetoothConnectionState connectionState) async { if (connectionState == BluetoothConnectionState.connected) { var privateKey = await Storage.getStringList(saveBluePrivateKey); List getPrivateKeyList = changeStringListToIntList(privateKey!); @@ -345,7 +351,7 @@ class LockSetLogic extends BaseGetXController { } else if (connectionState == BluetoothConnectionState.disconnected) { dismissEasyLoading(); cancelBlueConnetctToastTimer(); - if(state.ifCurrentScreen.value == true){ + if (state.ifCurrentScreen.value == true) { showBlueConnetctToast(); } } @@ -360,23 +366,28 @@ class LockSetLogic extends BaseGetXController { if (entity.errorCode!.codeIsSuccessful) { state.lockSetInfoData.value = entity.data!; CommonDataManage().currentLockSetInfoData = entity.data!; - - state.lockSettingInfo.value = state.lockSetInfoData.value.lockSettingInfo!; + + state.lockSettingInfo.value = + state.lockSetInfoData.value.lockSettingInfo!; state.lockFeature.value = state.lockSetInfoData.value.lockFeature!; state.lockStatus.value = state.lockSetInfoData.value.lockStatus!; state.lockBasicInfo.value = state.lockSetInfoData.value.lockBasicInfo!; state.isAttendance.value = state.lockSettingInfo.value.attendance!; - state.isOpenLockNeedOnline.value = state.lockSettingInfo.value.appUnlockOnline!; + state.isOpenLockNeedOnline.value = + state.lockSettingInfo.value.appUnlockOnline!; - state.isOpenBlueBroadcast.value = state.lockSettingInfo.value.bluetoothBroadcast!; - state.isOpenExceptionWarnings.value = state.lockSettingInfo.value.bluetoothBroadcast!; + state.isOpenBlueBroadcast.value = + state.lockSettingInfo.value.bluetoothBroadcast!; + state.isOpenExceptionWarnings.value = + state.lockSettingInfo.value.bluetoothBroadcast!; } return entity; } // 开启考勤获取是否有公司 - void openCheckingInData(BlockSetCheckInCallback blockSetCheckInCallback) async { + void openCheckingInData( + BlockSetCheckInCallback blockSetCheckInCallback) async { var entity = await ApiRepository.to.openCheckingInData( lockId: state.lockSetInfoData.value.lockId.toString(), ); @@ -394,23 +405,26 @@ class LockSetLogic extends BaseGetXController { if (entity.errorCode!.codeIsSuccessful) { state.isAttendance.value = (state.isAttendance.value == 1 ? 0 : 1); state.lockSettingInfo.value.attendance = state.isAttendance.value; - showToast("设置成功".tr, something: (){ + showToast('设置成功'.tr, something: () { eventBus.fire(RefreshLockListInfoDataEvent()); - eventBus.fire(LockSetChangeSetRefreshLockDetailWithType(0, state.lockSettingInfo.value.attendance!.toString())); + eventBus.fire(LockSetChangeSetRefreshLockDetailWithType( + 0, state.lockSettingInfo.value.attendance!.toString())); }); } } // 设置是否打开开锁提醒 - void setLockPickingReminder() async { + Future setLockPickingReminder() async { var entity = await ApiRepository.to.setLockPickingReminderData( lockId: state.lockSetInfoData.value.lockId!, - unlockReminderPush: state.isLockPickingReminder.value == 1 ? 0 : 1, + unlockReminder: state.isLockPickingReminder.value == 1 ? 0 : 1, ); if (entity.errorCode!.codeIsSuccessful) { - state.isLockPickingReminder.value = (state.isLockPickingReminder.value == 1 ? 0 : 1); - state.lockSettingInfo.value.unlockReminderPush = state.isLockPickingReminder.value; - showToast("设置成功".tr, something: (){ + state.isLockPickingReminder.value = + (state.isLockPickingReminder.value == 1 ? 0 : 1); + state.lockSettingInfo.value.unlockReminderPush = + state.isLockPickingReminder.value; + showToast('设置成功'.tr, something: () { eventBus.fire(RefreshLockListInfoDataEvent()); }); } @@ -423,11 +437,14 @@ class LockSetLogic extends BaseGetXController { appUnlockOnline: state.isOpenLockNeedOnline.value == 1 ? 0 : 1, ); if (entity.errorCode!.codeIsSuccessful) { - state.isOpenLockNeedOnline.value = (state.isOpenLockNeedOnline.value == 1 ? 0 : 1); - state.lockSettingInfo.value.appUnlockOnline = state.isOpenLockNeedOnline.value; + state.isOpenLockNeedOnline.value = + (state.isOpenLockNeedOnline.value == 1 ? 0 : 1); + state.lockSettingInfo.value.appUnlockOnline = + state.isOpenLockNeedOnline.value; - showToast("设置成功".tr,something: (){ - eventBus.fire(LockSetChangeSetRefreshLockDetailWithType(1, state.lockSettingInfo.value.appUnlockOnline!.toString())); + showToast('设置成功'.tr, something: () { + eventBus.fire(LockSetChangeSetRefreshLockDetailWithType( + 1, state.lockSettingInfo.value.appUnlockOnline!.toString())); eventBus.fire(RefreshLockListInfoDataEvent()); }); } @@ -437,37 +454,42 @@ class LockSetLogic extends BaseGetXController { StreamSubscription? _passCurrentLockInformationEvent; void initLoadDataAction(BlockSetStateCallback blockSetStateCallback) { // 蓝牙协议通知传输跟蓝牙之外的数据传输类不一样 eventBus - _passCurrentLockInformationEvent = eventBus.on().listen((event) { + _passCurrentLockInformationEvent = + eventBus.on().listen((event) { getLockSettingInfoData(); }); } - void showDeletAlertTipDialog({String? showContent = ""}) { - var content = showContent!.isEmpty ? "${"删除设备失败,请确保在设备附近,设备未被连接,设备已打开".tr}${BlueManage().connectDeviceName!.contains("T9A") == true ? "。如果是全自动锁,请使屏幕变亮".tr : ""}" : showContent; + void showDeletAlertTipDialog({String? showContent = ''}) { + var content = showContent!.isEmpty + ? "${"删除设备失败,请确保在设备附近,设备未被连接,设备已打开".tr}${BlueManage().connectDeviceName!.contains("T9A") == true ? "。如果是全自动锁,请使屏幕变亮".tr : ""}" + : showContent; ShowTipView().showSureAlertDialog(content); } - -/// 以下为删除逻辑 - deleyLockLogicOfRoles(){ + /// 以下为删除逻辑 + deleyLockLogicOfRoles() { if (state.lockBasicInfo.value.isLockOwner == 1) { // 超级管理员必须通过连接蓝牙删除 - ShowTipView().showIosTipWithContentDialog("删除锁后,所有信息都会一起删除,确定删除锁吗?".tr, (){ + ShowTipView().showIosTipWithContentDialog('删除锁后,所有信息都会一起删除,确定删除锁吗?'.tr, + () { // 删除锁 - ShowTipView().showTFViewAlertDialog(state.passwordTF, "请输入登录密码".tr, "请输入登录密码".tr, (){ + ShowTipView().showTFViewAlertDialog( + state.passwordTF, '请输入登录密码'.tr, '请输入登录密码'.tr, () { checkLoginPassword(); }); }); - } else if (state.lockBasicInfo.value.keyRight == 1){ + } else if (state.lockBasicInfo.value.keyRight == 1) { // 授权管理员弹框提示 - ShowTipView().showDeleteAdministratorIsHaveAllDataDialog("同时删除其发送的所有钥匙,钥匙删除后不能恢复".tr, (a){ + ShowTipView().showDeleteAdministratorIsHaveAllDataDialog( + '同时删除其发送的所有钥匙,钥匙删除后不能恢复'.tr, (a) { // 授权管理员删除 state.deleteAdministratorIsHaveAllData.value = a; deletKeyData(); }); - } else{ + } else { // 普通用户直接删除 - ShowTipView().showIosTipWithContentDialog("是否删除钥匙?".tr, (){ + ShowTipView().showIosTipWithContentDialog('是否删除钥匙?'.tr, () { deletKeyData(); }); } diff --git a/lib/main/lockDetail/lockSet/lockSet/lockSet_page.dart b/lib/main/lockDetail/lockSet/lockSet/lockSet_page.dart index 9632b5e3..1734eaef 100755 --- a/lib/main/lockDetail/lockSet/lockSet/lockSet_page.dart +++ b/lib/main/lockDetail/lockSet/lockSet/lockSet_page.dart @@ -496,7 +496,7 @@ class _LockSetPageState extends State with RouteAware { child: CommonItem( leftTitel: TranslationLoader.lanKeys!.unlockReminder!.tr, rightTitle: "", - isHaveLine: false, + isHaveLine: true, isHaveRightWidget: true, rightWidget: _lockRemindSwitch())), ), @@ -661,7 +661,7 @@ class _LockSetPageState extends State with RouteAware { activeColor: CupertinoColors.activeBlue, trackColor: CupertinoColors.systemGrey5, thumbColor: CupertinoColors.white, - value: (state.isLockPickingReminder.value) == 1 ? true : false, + value: state.isLockPickingReminder.value == 1 ? true : false, onChanged: (value) { setState(() { logic.setLockPickingReminder(); diff --git a/lib/main/lockDetail/messageWarn/lockUser/lockUser_logic.dart b/lib/main/lockDetail/messageWarn/lockUser/lockUser_logic.dart index 94123019..411bae76 100755 --- a/lib/main/lockDetail/messageWarn/lockUser/lockUser_logic.dart +++ b/lib/main/lockDetail/messageWarn/lockUser/lockUser_logic.dart @@ -10,14 +10,15 @@ class LockUserLogic extends BaseGetXController { final LockUserState state = LockUserState(); // 锁用户列表 - void getLockKeysList() async { - LockUserEntity entity = await ApiRepository.to.getLockKeysList( + Future getLockKeysList() async { + final LockUserEntity entity = await ApiRepository.to.getLockKeysList( lockId: state.getLockId.value, + searchStr: state.searchController.text, ); if (entity.errorCode!.codeIsSuccessful) { //当前钥匙类型 1:电子钥匙 2:密码钥匙 3:指纹钥匙 4:卡钥匙 5:人脸钥匙 - LockUserData data1 = entity.data![0]; - data1.lockUserList?.forEach((element) { + final LockUserData data1 = entity.data![0]; + data1.lockUserList?.forEach((LockUserListKeys element) { element.currentKeyType = 1; element.currentKeyTypeStr = '电子钥匙'.tr; element.currentTypeImg = 'images/controls_user.png'; @@ -26,8 +27,8 @@ class LockUserLogic extends BaseGetXController { element.currentDateType = element.keyType; element.currentOpenDoorID = element.id; }); - LockUserData data2 = entity.data![1]; - data2.lockUserList?.forEach((element) { + final LockUserData data2 = entity.data![1]; + data2.lockUserList?.forEach((LockUserListKeys element) { element.currentKeyType = 2; element.currentKeyTypeStr = '密码'.tr; element.currentTypeImg = 'images/icon_password.png'; @@ -36,8 +37,8 @@ class LockUserLogic extends BaseGetXController { element.currentDateType = element.keyboardPwdType; element.currentOpenDoorID = element.keyboardPwdId; }); - LockUserData data3 = entity.data![2]; - data3.lockUserList?.forEach((element) { + final LockUserData data3 = entity.data![2]; + data3.lockUserList?.forEach((LockUserListKeys element) { element.currentKeyType = 3; element.currentKeyTypeStr = '指纹'.tr; element.currentTypeImg = 'images/icon_fingerprint.png'; @@ -45,8 +46,8 @@ class LockUserLogic extends BaseGetXController { element.isCurrentSelect = false; element.currentDateType = element.fingerprintType; }); - LockUserData data4 = entity.data![3]; - data4.lockUserList?.forEach((element) { + final LockUserData data4 = entity.data![3]; + data4.lockUserList?.forEach((LockUserListKeys element) { element.currentKeyType = 4; element.currentKeyTypeStr = '卡'.tr; element.currentTypeImg = 'images/icon_card.png'; @@ -54,8 +55,8 @@ class LockUserLogic extends BaseGetXController { element.isCurrentSelect = false; element.currentDateType = element.cardType; }); - LockUserData data5 = entity.data![4]; - data5.lockUserList?.forEach((element) { + final LockUserData data5 = entity.data![4]; + data5.lockUserList?.forEach((LockUserListKeys element) { element.currentKeyType = 5; element.currentKeyTypeStr = '人脸'.tr; element.currentTypeImg = 'images/icon_face.png'; @@ -64,18 +65,18 @@ class LockUserLogic extends BaseGetXController { element.currentDateType = element.faceType; }); - state.lockUserList.value.addAll(data1.lockUserList!); - state.lockUserList.value.addAll(data2.lockUserList!); - state.lockUserList.value.addAll(data3.lockUserList!); - state.lockUserList.value.addAll(data4.lockUserList!); - state.lockUserList.value.addAll(data5.lockUserList!); + state.lockUserList.addAll(data1.lockUserList!); + state.lockUserList.addAll(data2.lockUserList!); + state.lockUserList.addAll(data3.lockUserList!); + state.lockUserList.addAll(data4.lockUserList!); + state.lockUserList.addAll(data5.lockUserList!); state.lockUserList.refresh(); } } String getKeyUseDateStr(LockUserListKeys itemData) { - var keyDateTypeStr = ""; + String keyDateTypeStr = ''; switch (itemData.currentKeyType) { case 1: //电子钥匙 keyDateTypeStr = getElectronicKeyUseDateStr(itemData); @@ -91,7 +92,7 @@ class LockUserLogic extends BaseGetXController { keyDateTypeStr = getCardAndFaceDateType(itemData); break; default: - keyDateTypeStr = "".tr; + keyDateTypeStr = ''.tr; break; } @@ -103,18 +104,18 @@ class LockUserLogic extends BaseGetXController { String useDateStr = ''; if (indexEntity.keyType == XSConstantMacro.keyTypeTime) { //限期 - DateTime startDateStr = + final DateTime startDateStr = DateTime.fromMillisecondsSinceEpoch(indexEntity.startDate!); - DateTime endDateStr = + final DateTime endDateStr = DateTime.fromMillisecondsSinceEpoch(indexEntity.endDate!); useDateStr = '${startDateStr.toLocal().toString().substring(0, 16)}-${endDateStr.toLocal().toString().substring(0, 16)}'; } else if (indexEntity.keyType == XSConstantMacro.keyTypeLong) { //永久 - useDateStr = "永久".tr; + useDateStr = '永久'.tr; } else if (indexEntity.keyType == XSConstantMacro.keyTypeOnce) { //单次 - useDateStr = "单次".tr; + useDateStr = '单次'.tr; } else if (indexEntity.keyType == XSConstantMacro.keyTypeLoop) { //循环 useDateStr = '循环'.tr; @@ -125,25 +126,23 @@ class LockUserLogic extends BaseGetXController { //获取密码有效期 String getPasswordUseDateStr(LockUserListKeys itemData) { - int? getPwdType = itemData.keyboardPwdType; + final int? getPwdType = itemData.keyboardPwdType; String useDateStr = ''; - DateTime sendDateStr = - DateTime.fromMillisecondsSinceEpoch(itemData.sendDate!); - DateTime startDateStr = + final DateTime startDateStr = DateTime.fromMillisecondsSinceEpoch(itemData.startDate!); - DateTime endDateStr = + final DateTime endDateStr = DateTime.fromMillisecondsSinceEpoch(itemData.endDate!); - int starHour = startDateStr.hour; - int endHour = endDateStr.hour; + final int starHour = startDateStr.hour; + final int endHour = endDateStr.hour; switch (getPwdType) { case 1: //单次 1 只能在开始时间后6小时内使用一次 - useDateStr = "单次".tr; + useDateStr = '单次'.tr; break; case 2: //永久 2 从开始时间开始永久有效,必需在开始时间24小时内使用一次,否则将失效 - useDateStr = "永久".tr; + useDateStr = '永久'.tr; break; case 3: //限期 3 在开始和结束时间内有效,必需在开始时间24小时内使用一次,否则将失效 @@ -213,30 +212,30 @@ class LockUserLogic extends BaseGetXController { //获取指纹有效期 String getfingerprintUseDateStr(LockUserListKeys fingerprintItemData) { - var keyDateTypeStr = ""; // 永久:1;限时2,单次3,循环:4 + String keyDateTypeStr = ''; // 永久:1;限时2,单次3,循环:4 if (fingerprintItemData.fingerprintType! == 1) { - keyDateTypeStr = "永久".tr; + keyDateTypeStr = '永久'.tr; } else if (fingerprintItemData.fingerprintType! == 2) { keyDateTypeStr = - "${DateTool().dateToYMDHNString(fingerprintItemData.startDate.toString())} - ${DateTool().dateToYMDHNString(fingerprintItemData.endDate.toString())} 限时"; + '${DateTool().dateToYMDHNString(fingerprintItemData.startDate.toString())} - ${DateTool().dateToYMDHNString(fingerprintItemData.endDate.toString())} 限时'; } else if (fingerprintItemData.fingerprintType! == 4) { keyDateTypeStr = - "${DateTool().dateToYMDString(fingerprintItemData.startDate.toString())}-${DateTool().dateToYMDString(fingerprintItemData.endDate.toString())} 循环"; + '${DateTool().dateToYMDString(fingerprintItemData.startDate.toString())}-${DateTool().dateToYMDString(fingerprintItemData.endDate.toString())} 循环'; } return keyDateTypeStr; } //获取卡片/人脸有效期 String getCardAndFaceDateType(LockUserListKeys fingerprintItemData) { - var keyDateTypeStr = ""; // 永久:1;限时2,单次3,循环:4 + String keyDateTypeStr = ''; // 永久:1;限时2,单次3,循环:4 if (fingerprintItemData.cardType! == 1) { - keyDateTypeStr = "永久".tr; + keyDateTypeStr = '永久'.tr; } else if (fingerprintItemData.cardType! == 2) { keyDateTypeStr = - "${DateTool().dateToYMDHNString(fingerprintItemData.startDate.toString())} - ${DateTool().dateToYMDHNString(fingerprintItemData.endDate.toString())} 限时"; + '${DateTool().dateToYMDHNString(fingerprintItemData.startDate.toString())} - ${DateTool().dateToYMDHNString(fingerprintItemData.endDate.toString())} 限时'; } else if (fingerprintItemData.cardType! == 4) { keyDateTypeStr = - "${DateTool().dateToYMDString(fingerprintItemData.startDate.toString())}-${DateTool().dateToYMDString(fingerprintItemData.endDate.toString())} 循环"; + '${DateTool().dateToYMDString(fingerprintItemData.startDate.toString())}-${DateTool().dateToYMDString(fingerprintItemData.endDate.toString())} 循环'; } return keyDateTypeStr; } diff --git a/lib/main/lockDetail/messageWarn/lockUser/lockUser_page.dart b/lib/main/lockDetail/messageWarn/lockUser/lockUser_page.dart index 68b14f94..33dc6ba4 100755 --- a/lib/main/lockDetail/messageWarn/lockUser/lockUser_page.dart +++ b/lib/main/lockDetail/messageWarn/lockUser/lockUser_page.dart @@ -3,6 +3,7 @@ import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import 'package:star_lock/main/lockDetail/messageWarn/lockUser/lockUser_entity.dart'; import 'package:star_lock/main/lockDetail/messageWarn/lockUser/lockUser_logic.dart'; +import 'package:star_lock/main/lockDetail/messageWarn/lockUser/lockUser_state.dart'; import 'package:star_lock/tools/keySearchWidget.dart'; import '../../../../app_settings/app_colors.dart'; import '../../../../tools/submitBtn.dart'; @@ -16,8 +17,8 @@ class LockUserPage extends StatefulWidget { } class _LockUserPageState extends State { - final logic = Get.put(LockUserLogic()); - final state = Get.find().state; + final LockUserLogic logic = Get.put(LockUserLogic()); + final LockUserState state = Get.find().state; @override initState() { @@ -36,7 +37,7 @@ class _LockUserPageState extends State { backgroundColor: AppColors.mainColor, ), body: Column( - children: [ + children: [ KeySearchWidget( editingController: state.searchController, onSubmittedAction: () { @@ -51,9 +52,7 @@ class _LockUserPageState extends State { SubmitBtn( btnName: '确定'.tr, onClick: () { - Get.back( - result: - state.lockUserList.value[state.isSelectIndex.value]); + Get.back(result: state.lockUserList[state.isSelectIndex.value]); }, ), SizedBox( @@ -66,9 +65,9 @@ class _LockUserPageState extends State { Widget _buildMainUI() { return Obx(() => ListView.separated( shrinkWrap: true, - itemCount: state.lockUserList.value.length, - itemBuilder: (c, index) { - return _electronicKeyItem(state.lockUserList.value[index], index); + itemCount: state.lockUserList.length, + itemBuilder: (BuildContext c, int index) { + return _electronicKeyItem(state.lockUserList[index], index); }, separatorBuilder: (BuildContext context, int index) { return const Divider( @@ -82,8 +81,8 @@ class _LockUserPageState extends State { Widget _electronicKeyItem(LockUserListKeys lockUserKeys, int selectIndex) { return GestureDetector( onTap: () { - for (int i = 0; i < state.lockUserList.value.length; i++) { - LockUserListKeys item = state.lockUserList.value[i]; + for (int i = 0; i < state.lockUserList.length; i++) { + final LockUserListKeys item = state.lockUserList[i]; if (selectIndex == i) { item.isCurrentSelect = true; } else { @@ -99,7 +98,7 @@ class _LockUserPageState extends State { width: 1.sw, height: 90.h, child: Row( - children: [ + children: [ SizedBox( width: 30.w, ), @@ -114,9 +113,9 @@ class _LockUserPageState extends State { Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.center, - children: [ + children: [ Row( - children: [ + children: [ Text( lockUserKeys.currentKeyName ?? '', style: TextStyle( @@ -132,7 +131,7 @@ class _LockUserPageState extends State { SizedBox(height: 10.h), Row( mainAxisAlignment: MainAxisAlignment.start, - children: [ + children: [ Text( logic.getKeyUseDateStr(lockUserKeys), style: TextStyle( diff --git a/lib/mine/addLock/saveLock/saveLock_logic.dart b/lib/mine/addLock/saveLock/saveLock_logic.dart index 58f6c5aa..de4af74d 100755 --- a/lib/mine/addLock/saveLock/saveLock_logic.dart +++ b/lib/mine/addLock/saveLock/saveLock_logic.dart @@ -8,7 +8,9 @@ import 'package:get/get.dart'; import 'package:star_lock/blue/io_protocol/io_changeAdministratorPassword.dart'; import 'package:star_lock/blue/io_protocol/io_senderCustomPasswords.dart'; import 'package:star_lock/blue/io_type.dart'; +import 'package:star_lock/main/lockDetail/lockDetail/lockDetail_logic.dart'; import 'package:star_lock/main/lockMian/entity/lockListInfo_entity.dart'; +import 'package:star_lock/mine/addLock/saveLock/entity/SaveLockEntity.dart'; import 'package:star_lock/tools/commonDataManage.dart'; import '../../../app_settings/app_settings.dart'; @@ -33,7 +35,7 @@ class SaveLockLogic extends BaseGetXController { void _initReplySubscription() { _replySubscription = - EventBusManager().eventBus!.on().listen((reply) { + EventBusManager().eventBus!.on().listen((Reply reply) { if (reply is AddUserReply && state.ifCurrentScreen.value == true) { _replyAddUserKey(reply); } @@ -50,16 +52,16 @@ class SaveLockLogic extends BaseGetXController { // 添加用户 Future _replyAddUserKey(Reply reply) async { - var token = reply.data.sublist(42, 46); - List strTokenList = changeIntListToStringList(token); + final List token = reply.data.sublist(42, 46); + final List strTokenList = changeIntListToStringList(token); Storage.setStringList(saveBlueToken, strTokenList); - int status = reply.data[46]; + final int status = reply.data[46]; switch (status) { case 0x00: //成功 如果成功保存用户编号 state.lockUserNo = listChangInt(reply.data.sublist(47, 49)); - AppLog.log("state.lockUserNo:${state.lockUserNo}"); + AppLog.log('state.lockUserNo:${state.lockUserNo}'); // 关闭超时 cancelBlueConnetctToastTimer(); @@ -67,16 +69,20 @@ class SaveLockLogic extends BaseGetXController { break; case 0x06: //无权限 - var privateKey = await Storage.getStringList(saveBluePrivateKey); - List getPrivateKeyList = changeStringListToIntList(privateKey!); + final List? privateKey = + await Storage.getStringList(saveBluePrivateKey); + final List getPrivateKeyList = + changeStringListToIntList(privateKey!); - var publicKey = await Storage.getStringList(saveBluePublicKey); - List publicKeyDataList = changeStringListToIntList(publicKey!); + final List? publicKey = + await Storage.getStringList(saveBluePublicKey); + final List publicKeyDataList = + changeStringListToIntList(publicKey!); IoSenderManage.senderAddUser( lockID: BlueManage().connectDeviceName, authUserID: await Storage.getUid(), - keyID: "1", + keyID: '1', userID: await Storage.getUid(), openMode: 1, keyType: 1, @@ -216,21 +222,25 @@ class SaveLockLogic extends BaseGetXController { (BluetoothConnectionState deviceConnectionState) async { if (deviceConnectionState == BluetoothConnectionState.connected) { // 私钥 - var privateKey = await Storage.getStringList(saveBluePrivateKey); - List getPrivateKeyList = changeStringListToIntList(privateKey!); + final List? privateKey = + await Storage.getStringList(saveBluePrivateKey); + final List getPrivateKeyList = + changeStringListToIntList(privateKey!); - var publicKey = await Storage.getStringList(saveBluePublicKey); - List publicKeyDataList = changeStringListToIntList(publicKey!); + final List? publicKey = + await Storage.getStringList(saveBluePublicKey); + final List publicKeyDataList = + changeStringListToIntList(publicKey!); - var token = await Storage.getStringList(saveBlueToken); - List getTokenList = [0, 0, 0, 0]; + 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", + keyID: '1', userID: await Storage.getUid(), openMode: 1, keyType: 1, @@ -356,35 +366,37 @@ class SaveLockLogic extends BaseGetXController { // } void bindBlueAdmin() async { - state.lockInfo["adminPwd"] = state.adminPassword; + state.lockInfo['adminPwd'] = state.adminPassword; - var 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 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']; - var bluetooth = {}; + final Map bluetooth = {}; bluetooth['bluetoothDeviceId'] = BlueManage().connectDeviceMacAddress; bluetooth['bluetoothDeviceName'] = BlueManage().connectDeviceName; - var publicKey = await Storage.getStringList(saveBluePublicKey); - List publicKeyDataList = changeStringListToIntList(publicKey!); + final List? publicKey = + await Storage.getStringList(saveBluePublicKey); + final List publicKeyDataList = changeStringListToIntList(publicKey!); bluetooth['publicKey'] = publicKeyDataList; - var privateKey = await Storage.getStringList(saveBluePrivateKey); - List getPrivateKeyList = changeStringListToIntList(privateKey!); + final List? privateKey = + await Storage.getStringList(saveBluePrivateKey); + final List getPrivateKeyList = changeStringListToIntList(privateKey!); bluetooth['privateKey'] = getPrivateKeyList; - var signKey = await Storage.getStringList(saveBlueSignKey); - List signKeyDataList = changeStringListToIntList(signKey!); + final List? signKey = await Storage.getStringList(saveBlueSignKey); + final List signKeyDataList = changeStringListToIntList(signKey!); bluetooth['signKey'] = signKeyDataList; - var entity = await ApiRepository.to.bindingBlueAdmin( + final SaveLockEntity entity = await ApiRepository.to.bindingBlueAdmin( lockAlias: state.aliName.value, position: positionMap, bluetooth: bluetooth, @@ -464,11 +476,18 @@ class SaveLockLogic extends BaseGetXController { eventBus.fire(RefreshLockListInfoDataEvent(clearScanDevices: true)); BlueManage().disconnect(); Get.close(state.isFromMap == 1 ? 5 : 6); + //刚刚配对完,需要对开锁页锁死 2 秒 + Future.delayed(const Duration(milliseconds: 200), () { + if (Get.isRegistered()) { + Get.find() + .functionBlocker + .countdownProhibited(duration: const Duration(seconds: 2)); + } + }); } @override void onReady() { - // TODO: implement onReady super.onReady(); _initReplySubscription(); @@ -476,13 +495,11 @@ class SaveLockLogic extends BaseGetXController { @override void onInit() { - // TODO: implement onInit super.onInit(); } @override void onClose() { - // TODO: implement onClose _replySubscription.cancel(); super.onClose(); } diff --git a/lib/mine/valueAddedServices/advancedFunctionRecord/advancedFunctionRecord_entity.dart b/lib/mine/valueAddedServices/advancedFunctionRecord/advancedFunctionRecord_entity.dart index 72e4de70..5d36ca71 100755 --- a/lib/mine/valueAddedServices/advancedFunctionRecord/advancedFunctionRecord_entity.dart +++ b/lib/mine/valueAddedServices/advancedFunctionRecord/advancedFunctionRecord_entity.dart @@ -73,6 +73,7 @@ class RecordItem { String? createdAt; String? updatedAt; String? useDate; + String? buyDate; RecordItem( {this.id, @@ -88,7 +89,8 @@ class RecordItem { this.amount, this.createdAt, this.updatedAt, - this.useDate}); + this.useDate, + this.buyDate}); RecordItem.fromJson(Map json) { id = json['id']; @@ -105,6 +107,7 @@ class RecordItem { createdAt = json['created_at']; updatedAt = json['updated_at']; useDate = json['useDate']; + buyDate = json['buyDate']; } Map toJson() { @@ -123,6 +126,7 @@ class RecordItem { data['created_at'] = createdAt; data['updated_at'] = updatedAt; data['useDate'] = useDate; + data['buyDate'] = buyDate; return data; } } diff --git a/lib/mine/valueAddedServices/valueAddedServicesRecord/value_added_services_record_page.dart b/lib/mine/valueAddedServices/valueAddedServicesRecord/value_added_services_record_page.dart index b8aba35b..f7e7eadf 100755 --- a/lib/mine/valueAddedServices/valueAddedServicesRecord/value_added_services_record_page.dart +++ b/lib/mine/valueAddedServices/valueAddedServicesRecord/value_added_services_record_page.dart @@ -107,7 +107,7 @@ class _PurchaseRecords extends StatelessWidget { Row( children: [ Text( - itemData.createdAt?.substring(0, 10) ?? '', + itemData.buyDate ?? '', style: TextStyle( fontSize: 24.sp, color: AppColors.blackColor, diff --git a/lib/network/api_provider.dart b/lib/network/api_provider.dart index 499b1acc..74914665 100755 --- a/lib/network/api_provider.dart +++ b/lib/network/api_provider.dart @@ -891,13 +891,12 @@ class ApiProvider extends BaseProvider { isUnShowLoading: true); // 获取开锁提醒 - Future setLockPickingReminderData( - int lockId, int unlockReminderPush) => + Future setLockPickingReminderData(int lockId, int unlockReminder) => post( updateLockSettingUrl.toUrl, jsonEncode({ 'lockId': lockId, - 'unlockReminderPush': unlockReminderPush, + 'unlockReminder': unlockReminder, })); // 获取员工列表 @@ -1945,8 +1944,9 @@ class ApiProvider extends BaseProvider { })); // 锁用户列表 - Future getLockKeysList(int lockId) => - post(lockKeysListURL.toUrl, jsonEncode({'lockId': lockId})); + Future getLockKeysList(int lockId, String searchStr) => post( + lockKeysListURL.toUrl, + jsonEncode({'lockId': lockId, 'searchStr': searchStr})); // 添加开门通知 Future addLockNoticeSetting( diff --git a/lib/network/api_repository.dart b/lib/network/api_repository.dart index 7b3aabf4..1b839317 100755 --- a/lib/network/api_repository.dart +++ b/lib/network/api_repository.dart @@ -1095,10 +1095,10 @@ class ApiRepository { // 设置锁开锁提醒 Future setLockPickingReminderData({ required int lockId, - required int unlockReminderPush, + required int unlockReminder, }) async { - final res = await apiProvider.setLockPickingReminderData( - lockId, unlockReminderPush); + final res = + await apiProvider.setLockPickingReminderData(lockId, unlockReminder); return LoginEntity.fromJson(res.body); } @@ -1972,8 +1972,9 @@ class ApiRepository { } // 锁用户列表 - Future getLockKeysList({required int lockId}) async { - final res = await apiProvider.getLockKeysList(lockId); + Future getLockKeysList( + {required int lockId, required String searchStr}) async { + final res = await apiProvider.getLockKeysList(lockId, searchStr); return LockUserEntity.fromJson(res.body); } diff --git a/lib/talk/udp/udp_manage.dart b/lib/talk/udp/udp_manage.dart index 88dc1845..b5231292 100755 --- a/lib/talk/udp/udp_manage.dart +++ b/lib/talk/udp/udp_manage.dart @@ -62,14 +62,16 @@ class UDPManage { // AppLog.log('Udp ----> host:$host port:$port'); var addressIListenFrom = InternetAddress.anyIPv4; int portIListenOn = 62288; - RawDatagramSocket.bind(addressIListenFrom, portIListenOn) - .then((RawDatagramSocket socket) { - _udpSocket = socket; + if(addressIListenFrom.address != '0.0.0.0'){ + RawDatagramSocket.bind(addressIListenFrom, portIListenOn) + .then((RawDatagramSocket socket) { + _udpSocket = socket; - ///广播功能 - _udpSocket!.broadcastEnabled = true; - _onReceiveData(socket); - }); + ///广播功能 + _udpSocket!.broadcastEnabled = true; + _onReceiveData(socket); + }); + } } void _onReceiveData(RawDatagramSocket socket) { diff --git a/lib/tools/throttler.dart b/lib/tools/throttler.dart new file mode 100644 index 00000000..a5b6e96f --- /dev/null +++ b/lib/tools/throttler.dart @@ -0,0 +1,74 @@ +import 'dart:async'; + +import 'package:star_lock/app_settings/app_settings.dart'; + +/// +/// 节流器 可以防止一个函数在短时间内被重复调用 +// 创建一个1秒的节流器 +// Throttler throttler = Throttler(Duration(seconds: 1)); +// +// // 示例函数 +// void myFunction() { +// print("函数被调用"); +// } +// +// // 调用示例函数,会在1秒内只输出一次 +// throttler.throttle(myFunction); +// +// // 在自定义时间间隔内防止函数被重复调用 +// Throttler customThrottler = Throttler(Duration(milliseconds: 500)); // 自定义500毫秒的间隔 +// customThrottler.throttle(myFunction); // 在500毫秒内多次调用只会执行一次函数 +// +// // 在需要时取消节流器 +// customThrottler.cancel(); // 取消节流器,函数再次被调用会立即执行 + +class Throttler { + Throttler(this._delay); + + final Duration _delay; + Timer? _timer; + late Function _callback; + + void throttle(Function callback) { + if (_timer == null || !_timer!.isActive) { + _callback = callback; + _timer = Timer(_delay, () { + _callback(); + _timer?.cancel(); + }); + } + } + + void cancel() { + _timer?.cancel(); + } +} + +/// +/// 防止抖动 +/// +class FunctionBlocker { + FunctionBlocker({required this.duration}); + + bool _blocked = false; + Duration duration; + + //阻止函数执行 + void block(Function function) { + if (!_blocked) { + _blocked = true; + function(); + Timer(duration, () { + _blocked = false; + }); + } + } + + //倒计时禁止 + void countdownProhibited({required Duration duration}) { + _blocked = true; + Timer(duration, () { + _blocked = false; + }); + } +}