fix:梳理配网逻辑

This commit is contained in:
liyi 2025-04-26 15:15:27 +08:00
parent 1784f75c47
commit 2a89d0110c
5 changed files with 626 additions and 255 deletions

View File

@ -37,15 +37,24 @@ import 'configuringWifi_state.dart';
class ConfiguringWifiLogic extends BaseGetXController { class ConfiguringWifiLogic extends BaseGetXController {
final ConfiguringWifiState state = ConfiguringWifiState(); final ConfiguringWifiState state = ConfiguringWifiState();
final int _configurationTimeout = 60; //
/// WiFi锁服务IP和端口
Future<void> getWifiLockServiceIpAndPort() async { Future<void> getWifiLockServiceIpAndPort() async {
final ConfiguringWifiEntity entity = try {
await ApiRepository.to.getWifiLockServiceIpAndPort(); final ConfiguringWifiEntity entity =
if (entity.errorCode! == 0) { await ApiRepository.to.getWifiLockServiceIpAndPort();
state.configuringWifiEntity.value = entity; if (entity.errorCode! == 0) {
state.configuringWifiEntity.value = entity;
} else {
AppLog.log('获取WiFi锁服务IP和端口失败${entity.errorCode}');
}
} catch (e) {
AppLog.log('获取WiFi锁服务IP和端口异常$e');
} }
} }
///
void updateNetworkInfo({ void updateNetworkInfo({
required String peerId, required String peerId,
required String wifiName, required String wifiName,
@ -53,24 +62,36 @@ class ConfiguringWifiLogic extends BaseGetXController {
required String deviceMac, required String deviceMac,
required String networkMac, required String networkMac,
}) async { }) async {
final LoginEntity entity = await ApiRepository.to.settingDeviceNetwork( try {
deviceType: 2, final LoginEntity entity = await ApiRepository.to.settingDeviceNetwork(
deviceMac: deviceMac, deviceType: 2,
wifiName: wifiName, deviceMac: deviceMac,
networkMac: networkMac,
secretKey: secretKey,
peerId: peerId,
);
if (entity.errorCode!.codeIsSuccessful) {
// peerID
StartChartManage().lockNetworkInfo = DeviceNetworkInfo(
wifiName: wifiName, wifiName: wifiName,
networkMac: networkMac, networkMac: networkMac,
secretKey: secretKey, secretKey: secretKey,
peerId: peerId, peerId: peerId,
); );
await _getUploadLockSet(); if (entity.errorCode!.codeIsSuccessful) {
// peerID
StartChartManage().lockNetworkInfo = DeviceNetworkInfo(
wifiName: wifiName,
networkMac: networkMac,
secretKey: secretKey,
peerId: peerId,
);
await _getUploadLockSet();
} else {
dismissEasyLoading();
showToast('网络配置失败,请重试'.tr);
state.sureBtnState.value = 0;
}
} catch (e) {
dismissEasyLoading();
showToast('网络配置异常:${e.toString()}'.tr);
state.sureBtnState.value = 0;
AppLog.log('网络配置异常:$e');
} }
} }
@ -84,81 +105,138 @@ class ConfiguringWifiLogic extends BaseGetXController {
if (reply is GatewayConfiguringWifiResultReply) { if (reply is GatewayConfiguringWifiResultReply) {
_replySenderConfiguringWifiResult(reply); _replySenderConfiguringWifiResult(reply);
} }
// wifi配网命令应答结果
if (reply is GatewayConfiguringWifiReply) { if (reply is GatewayConfiguringWifiReply) {
_replySenderConfiguringWifiResult(reply); _replySenderConfiguringWifi(reply);
} }
if (reply is GatewayGetStatusReply) { if (reply is GatewayGetStatusReply) {
_replyGatewayGetStatusReply(reply); _replyGatewayGetStatusReply(reply);
} }
// if (reply is GatewayGetStatusReply) {
// _replyStatusInfo(reply);
// }
// //
if (reply is UpdataLockSetReply) { if (reply is UpdataLockSetReply) {
_replyUpdataLockSetReply(reply); _replyUpdataLockSetReply(reply);
} }
AppLog.log('蓝牙回调处理完毕${EasyLoading.isShow}');
}); });
} }
// WIFI配网结果 // WIFI配网操作结果处理
Future<void> _replySenderConfiguringWifiResult(Reply reply) async { Future<void> _replySenderConfiguringWifi(Reply reply) async {
final int status = reply.data[2]; final int status = reply.data[2];
// state.sureBtnState.value = 0;
// loading超时定时器
state.loadingTimer?.cancel();
state.loadingTimer = null;
switch (status) { switch (status) {
case 0x00: case 0x00:
await Storage.removeLockNetWorkInfoCache(); AppLog.log('wifi配网命令回复结果:成功');
final int secretKeyJsonLength = (reply.data[4] << 8) + reply.data[3];
final List<int> secretKeyList =
reply.data.sublist(5, 5 + secretKeyJsonLength);
String result = utf8String(secretKeyList);
// JSON Map
Map<String, dynamic> jsonMap = json.decode(result);
// peerId
String? peerId = jsonMap['peerId'];
String? wifiName = jsonMap['wifiName'];
String? secretKey = jsonMap['secretKey'];
String? deviceMac = jsonMap['deviceMac'];
String? networkMac = jsonMap['networkMac'];
/// ,peerId
StartChartManage().lockPeerId = peerId ?? '';
state.isLoading.value = false;
//
await Storage.saveLockNetWorkInfo(jsonMap);
//
updateNetworkInfo(
peerId: peerId ?? '',
wifiName: wifiName ?? '',
secretKey: secretKey ?? '',
deviceMac: deviceMac ?? '',
networkMac: networkMac ?? '');
break; break;
default: default:
// //
dismissEasyLoading(); // loading dismissEasyLoading(); // loading
cancelBlueConnetctToastTimer();
if (state.loadingTimer != null) {
state.loadingTimer!.cancel();
state.loadingTimer = null;
}
showToast('配网失败'.tr); showToast('配网失败'.tr);
state.isLoading.value = false; state.isLoading.value = false;
break; break;
} }
} }
// JSON // WIFI配网结果处理
Future<void> _replySenderConfiguringWifiResult(Reply reply) async {
final int status = reply.data[2];
//
cancelBlueConnetctToastTimer();
switch (status) {
case 0x00:
// - loading
await Storage.removeLockNetWorkInfoCache();
try {
final int secretKeyJsonLength = (reply.data[4] << 8) + reply.data[3];
final List<int> secretKeyList =
reply.data.sublist(5, 5 + secretKeyJsonLength);
String result = utf8String(secretKeyList);
AppLog.log('解析配网信息: $result');
// JSON Map
Map<String, dynamic> jsonMap = json.decode(result);
//
String? peerId = jsonMap['peerId'];
String? wifiName = jsonMap['wifiName'];
String? secretKey = jsonMap['secretKey'];
String? deviceMac = jsonMap['deviceMac'];
String? networkMac = jsonMap['networkMac'];
//
if (peerId == null ||
peerId.isEmpty ||
secretKey == null ||
secretKey.isEmpty) {
throw Exception('Missing required network information');
}
/// ,peerId
StartChartManage().lockPeerId = peerId;
//
await Storage.saveLockNetWorkInfo(jsonMap);
// - : sureBtnState updateNetworkInfo
updateNetworkInfo(
peerId: peerId,
wifiName: wifiName ?? '',
secretKey: secretKey,
deviceMac: deviceMac ?? '',
networkMac: networkMac ?? '');
} catch (e) {
if (EasyLoading.isShow) {
dismissEasyLoading();
}
showToast('解析配网信息失败,请重试'.tr);
state.sureBtnState.value = 0; //
AppLog.log('解析配网信息失败: $e');
return; // return阻止后续流程
}
break;
case 0x01:
// WiFi密码错误
if (EasyLoading.isShow) {
dismissEasyLoading();
}
showToast('WiFi密码错误请重新输入'.tr);
state.sureBtnState.value = 0; //
break;
case 0x02:
// WiFi
if (EasyLoading.isShow) {
dismissEasyLoading();
}
showToast('找不到该WiFi网络请确认WiFi名称正确'.tr);
state.sureBtnState.value = 0; //
break;
case 0x03:
//
if (EasyLoading.isShow) {
dismissEasyLoading();
}
showToast('连接WiFi超时请确保网络信号良好'.tr);
state.sureBtnState.value = 0; //
break;
default:
//
if (EasyLoading.isShow) {
dismissEasyLoading();
}
showToast('配网失败 (错误码: $status),请重试'.tr);
state.sureBtnState.value = 0; //
break;
}
}
// JSON
String prettyPrintJson(String jsonString) { String prettyPrintJson(String jsonString) {
var jsonObject = json.decode(jsonString); var jsonObject = json.decode(jsonString);
return JsonEncoder.withIndent(' ').convert(jsonObject); return JsonEncoder.withIndent(' ').convert(jsonObject);
@ -168,63 +246,80 @@ class ConfiguringWifiLogic extends BaseGetXController {
Future<void> senderConfiguringWifiAction() async { Future<void> senderConfiguringWifiAction() async {
AppLog.log('开始配网${EasyLoading.isShow}'); AppLog.log('开始配网${EasyLoading.isShow}');
if (state.isLoading.isTrue) { if (state.sureBtnState.value == 1) {
AppLog.log('正在配网中请勿重复点击'); AppLog.log('正在配网中请勿重复点击');
return; return;
} }
if (state.wifiNameController.text.isEmpty) {
showToast('请输入wifi名称'.tr); //
try {
final GetGatewayConfigurationEntity entity = await ApiRepository.to
.getGatewayConfigurationNotLoading(timeout: _configurationTimeout);
if (entity.errorCode!.codeIsSuccessful) {
state.getGatewayConfigurationStr = entity.data ?? '';
} else {
// showToast('获取网关配置失败,请重试'.tr);
AppLog.log('获取网关配置失败,请重试');
return;
}
//
final loginData = await Storage.getLoginData();
if (loginData == null) {
AppLog.log('未检测到登录信息,请重新登录'.tr);
return;
}
// app用户的peerId
String appPeerId = loginData.starchart?.starchartId ?? '';
if (appPeerId.isEmpty) {
AppLog.log('用户ID获取失败请重新登录'.tr);
return;
}
//
if (state.getGatewayConfigurationStr.isNotEmpty) {
// JSON Map
Map<String, dynamic> jsonMap =
json.decode(state.getGatewayConfigurationStr);
//
jsonMap.remove("starCloudUrl");
jsonMap.remove("starLockPeerId");
//
jsonMap['userPeerld'] = appPeerId;
// Map JSON
state.getGatewayConfigurationStr =
json.encode(jsonMap).replaceAll(',', ',\n');
//
state.getGatewayConfigurationStr =
prettyPrintJson(state.getGatewayConfigurationStr);
} else {
//
state.getGatewayConfigurationStr = "{\"userPeerld\": \"$appPeerId\"}";
}
} catch (e) {
AppLog.log('网关配置准备失败:${e.toString()}'.tr);
return; return;
} }
if (state.wifiPWDController.text.isEmpty) { // sureBtnState状态
showToast('请输入WiFi密码'.tr); state.sureBtnState.value = 1;
return;
}
// if (state.sureBtnState.value == 1) {
// return;
// }
// state.sureBtnState.value = 1;
final GetGatewayConfigurationEntity entity = // loading
await ApiRepository.to.getGatewayConfigurationNotLoading(timeout: 60); if (!EasyLoading.isShow) {
if (entity.errorCode!.codeIsSuccessful) { showEasyLoading();
state.getGatewayConfigurationStr = entity.data ?? '';
} }
// //
final loginData = await Storage.getLoginData();
// app用户的peerId
String appPeerId = loginData?.starchart?.starchartId ?? '';
//
if (state.getGatewayConfigurationStr.isNotEmpty) {
// JSON Map
Map<String, dynamic> jsonMap =
json.decode(state.getGatewayConfigurationStr);
//
jsonMap.remove("starCloudUrl");
jsonMap.remove("starLockPeerId");
//
jsonMap['userPeerld'] = appPeerId;
// Map JSON
state.getGatewayConfigurationStr =
json.encode(jsonMap).replaceAll(',', ',\n');
//
state.getGatewayConfigurationStr =
prettyPrintJson(state.getGatewayConfigurationStr);
} else {
//
state.getGatewayConfigurationStr = "{\"userPeerld\": \"$appPeerId\"}";
}
showEasyLoading();
showBlueConnetctToastTimer(action: () { showBlueConnetctToastTimer(action: () {
dismissEasyLoading(); if (EasyLoading.isShow) {
state.isLoading.value = false; dismissEasyLoading();
}
state.sureBtnState.value = 0; //
}); });
// //
@ -232,16 +327,27 @@ class ConfiguringWifiLogic extends BaseGetXController {
BlueManage().connectDeviceName, BlueManage().connectDeviceName,
(BluetoothConnectionState connectionState) async { (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
IoSenderManage.gatewayConfiguringWifiCommand( try {
ssid: state.wifiNameController.text, IoSenderManage.gatewayConfiguringWifiCommand(
password: state.wifiPWDController.text, ssid: state.wifiNameController.text,
gatewayConfigurationStr: state.getGatewayConfigurationStr, password: state.wifiPWDController.text,
); gatewayConfigurationStr: state.getGatewayConfigurationStr,
);
// sureBtnState状态
} catch (e) {
if (EasyLoading.isShow) {
dismissEasyLoading();
}
cancelBlueConnetctToastTimer();
state.sureBtnState.value = 0; //
showToast('发送配网指令失败:${e.toString()}'.tr);
}
} else if (connectionState == BluetoothConnectionState.disconnected) { } else if (connectionState == BluetoothConnectionState.disconnected) {
dismissEasyLoading(); if (EasyLoading.isShow) {
dismissEasyLoading();
}
cancelBlueConnetctToastTimer(); cancelBlueConnetctToastTimer();
state.isLoading.value = false; state.sureBtnState.value = 0; //
// state.sureBtnState.value = 0;
if (state.ifCurrentScreen.value == true) { if (state.ifCurrentScreen.value == true) {
showBlueConnetctToast(); showBlueConnetctToast();
} }
@ -249,7 +355,6 @@ class ConfiguringWifiLogic extends BaseGetXController {
}, },
isAddEquipment: false, isAddEquipment: false,
); );
state.isLoading.value = true;
} }
// //
@ -278,11 +383,15 @@ class ConfiguringWifiLogic extends BaseGetXController {
final NetworkInfo _networkInfo = NetworkInfo(); final NetworkInfo _networkInfo = NetworkInfo();
Future<String> getWifiName() async { Future<String> getWifiName() async {
String ssid = ''; try {
ssid = (await _networkInfo.getWifiName())!; String? ssid = await _networkInfo.getWifiName();
ssid = ssid ?? ''; ssid = ssid ?? '';
ssid = ssid.replaceAll(r'"', ''); ssid = ssid.replaceAll(r'"', '');
return ssid ?? ''; return ssid;
} catch (e) {
AppLog.log('获取WiFi名称失败: $e');
return '';
}
} }
/// ///
@ -308,17 +417,12 @@ class ConfiguringWifiLogic extends BaseGetXController {
getWifiLockServiceIpAndPort(); getWifiLockServiceIpAndPort();
_initReplySubscription(); _initReplySubscription();
// getDevicesStatusAction();
}
@override
void onInit() {
super.onInit();
} }
@override @override
void onClose() { void onClose() {
_replySubscription.cancel(); _replySubscription.cancel();
cancelBlueConnetctToastTimer(); //
super.onClose(); super.onClose();
} }
@ -330,8 +434,6 @@ class ConfiguringWifiLogic extends BaseGetXController {
switch (status) { switch (status) {
case 0x00: case 0x00:
// //
// state.sureBtnState.value = 0;
final GetGatewayInfoModel gatewayModel = GetGatewayInfoModel(); final GetGatewayInfoModel gatewayModel = GetGatewayInfoModel();
// MAC地址 // MAC地址
int index = 3; int index = 3;
@ -372,70 +474,108 @@ class ConfiguringWifiLogic extends BaseGetXController {
default: default:
// //
dismissEasyLoading(); dismissEasyLoading();
showToast('配网失败'.tr); showToast('获取设备状态失败'.tr);
if (state.loadingTimer != null) {
state.loadingTimer!.cancel();
state.loadingTimer = null;
}
break; break;
} }
} }
// //
Future<void> _getUploadLockSet() async { Future<void> _getUploadLockSet() async {
showEasyLoading(); // loading状态loading
showBlueConnetctToastTimer(action: () { showBlueConnetctToastTimer(action: () {
dismissEasyLoading(); if (EasyLoading.isShow) {
dismissEasyLoading();
}
state.sureBtnState.value = 0;
}); });
final List<String>? token = await Storage.getStringList(saveBlueToken); try {
final List<int> getTokenList = changeStringListToIntList(token!); final List<String>? token = await Storage.getStringList(saveBlueToken);
if (token == null || token.isEmpty) {
await _uploadLockSet(getTokenList); throw Exception('Token is empty');
}
final List<int> getTokenList = changeStringListToIntList(token);
await _uploadLockSet(getTokenList);
} catch (e) {
if (EasyLoading.isShow) {
dismissEasyLoading();
}
cancelBlueConnetctToastTimer();
showToast('获取设置失败:${e.toString()}'.tr);
state.sureBtnState.value = 0;
}
} }
// //
Future<void> _uploadLockSet(List<int> token) async { Future<void> _uploadLockSet(List<int> token) async {
final List<String>? privateKey = try {
await Storage.getStringList(saveBluePrivateKey); final List<String>? privateKey =
final List<int> getPrivateKeyList = changeStringListToIntList(privateKey!); await Storage.getStringList(saveBluePrivateKey);
if (privateKey == null || privateKey.isEmpty) {
throw Exception('Private key is empty');
}
final List<int> getPrivateKeyList = changeStringListToIntList(privateKey);
final List<String>? signKey = await Storage.getStringList(saveBlueSignKey); final List<String>? signKey =
final List<int> signKeyDataList = changeStringListToIntList(signKey!); await Storage.getStringList(saveBlueSignKey);
if (signKey == null || signKey.isEmpty) {
throw Exception('Sign key is empty');
}
final List<int> signKeyDataList = changeStringListToIntList(signKey);
IoSenderManage.updataLockSetCommand( IoSenderManage.updataLockSetCommand(
lockID: BlueManage().connectDeviceName, lockID: BlueManage().connectDeviceName,
userID: await Storage.getUid(), userID: await Storage.getUid(),
token: token, token: token,
needAuthor: 1, needAuthor: 1,
signKey: signKeyDataList, signKey: signKeyDataList,
privateKey: getPrivateKeyList); privateKey: getPrivateKeyList);
} catch (e) {
if (EasyLoading.isShow) {
dismissEasyLoading();
}
cancelBlueConnetctToastTimer();
showToast('上传设置失败:${e.toString()}'.tr);
state.sureBtnState.value = 0;
}
} }
// //
Future<void> _replyUpdataLockSetReply(Reply reply) async { Future<void> _replyUpdataLockSetReply(Reply reply) async {
final int status = reply.data[2]; final int status = reply.data[2];
dismissEasyLoading(); // loading // loading状态直到整个过程完成
cancelBlueConnetctToastTimer(); cancelBlueConnetctToastTimer();
switch (status) { switch (status) {
case 0x00: case 0x00:
await _lockDataUpload( await _lockDataUpload(
uploadType: 1, uploadType: 1,
recordType: 0, recordType: 0,
records: reply.data.sublist(7, reply.data.length)); records: reply.data.sublist(7, reply.data.length));
break; break;
case 0x06: case 0x06:
// //token
final List<int> token = reply.data.sublist(3, 7); try {
final List<String> saveStrList = changeIntListToStringList(token); final List<int> token = reply.data.sublist(3, 7);
Storage.setStringList(saveBlueToken, saveStrList); final List<String> saveStrList = changeIntListToStringList(token);
await Storage.setStringList(saveBlueToken, saveStrList);
_uploadLockSet(token); _uploadLockSet(token);
} catch (e) {
if (EasyLoading.isShow) {
dismissEasyLoading(); // loading
}
showToast('获取设置权限失败:${e.toString()}'.tr);
state.sureBtnState.value = 0; //
}
break; break;
default: default:
dismissEasyLoading(); if (EasyLoading.isShow) {
cancelBlueConnetctToastTimer(); dismissEasyLoading(); // loading
}
showToast('获取锁设置失败 (错误码: $status)'.tr);
state.sureBtnState.value = 0; //
break; break;
} }
} }
@ -445,25 +585,43 @@ class ConfiguringWifiLogic extends BaseGetXController {
{required int uploadType, {required int uploadType,
required int recordType, required int recordType,
required List records}) async { required List records}) async {
final LoginEntity entity = await ApiRepository.to.lockDataUpload( try {
lockId: state.lockBasicInfo.value.lockId ?? -1, final LoginEntity entity = await ApiRepository.to.lockDataUpload(
uploadType: uploadType, lockId: state.lockBasicInfo.value.lockId ?? -1,
recordType: recordType, uploadType: uploadType,
records: records, recordType: recordType,
isUnShowLoading: true); records: records,
if (entity.errorCode!.codeIsSuccessful) { isUnShowLoading: true);
showToast('配网成功'.tr, something: () {
state.isLoading.value = false;
if (state.pageName.value == 'lockSet') {
Get.close(2);
} else {
Get.offAllNamed(Routers.starLockMain);
}
eventBus if (entity.errorCode!.codeIsSuccessful) {
.fire(PassCurrentLockInformationEvent(state.lockSetInfoData.value)); if (EasyLoading.isShow) {
eventBus.fire(SuccessfulDistributionNetwork()); dismissEasyLoading();
}); }
showToast('配网成功'.tr, something: () {
state.sureBtnState.value = 0; //
if (state.pageName.value == 'lockSet') {
Get.close(2);
} else {
Get.offAllNamed(Routers.starLockMain);
}
eventBus.fire(
PassCurrentLockInformationEvent(state.lockSetInfoData.value));
eventBus.fire(SuccessfulDistributionNetwork());
});
} else {
if (EasyLoading.isShow) {
dismissEasyLoading();
}
showToast('数据上传失败:${entity.errorCode}'.tr);
state.sureBtnState.value = 0; //
}
} catch (e) {
if (EasyLoading.isShow) {
dismissEasyLoading();
}
showToast('数据上传异常:${e.toString()}'.tr);
state.sureBtnState.value = 0; //
} }
} }
} }

View File

@ -25,6 +25,9 @@ class _ConfiguringWifiPageState extends State<ConfiguringWifiPage>
final ConfiguringWifiLogic logic = Get.put(ConfiguringWifiLogic()); final ConfiguringWifiLogic logic = Get.put(ConfiguringWifiLogic());
final ConfiguringWifiState state = Get.find<ConfiguringWifiLogic>().state; final ConfiguringWifiState state = Get.find<ConfiguringWifiLogic>().state;
//
final RxBool _obscureText = true.obs;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
@ -39,19 +42,36 @@ class _ConfiguringWifiPageState extends State<ConfiguringWifiPage>
'WiFi名称'.tr, '请输入WiFi名字'.tr, state.wifiNameController), 'WiFi名称'.tr, '请输入WiFi名字'.tr, state.wifiNameController),
Container( Container(
width: 1.sw, height: 1.h, color: AppColors.mainBackgroundColor), width: 1.sw, height: 1.h, color: AppColors.mainBackgroundColor),
configuringWifiTFWidget( configuringWifiPasswordTFWidget(
'WiFi密码'.tr, '请输入WiFi密码'.tr, state.wifiPWDController), 'WiFi密码'.tr, '请输入WiFi密码'.tr, state.wifiPWDController),
SizedBox( SizedBox(
height: 50.h, height: 50.h,
), ),
Obx( Obx(
() => SubmitBtn( () => SubmitBtn(
btnName: '确定'.tr, btnName: state.sureBtnState.value == 1 ? '配置中...'.tr : '确定'.tr,
isDisabled: state.isLoading.isFalse, // sureBtnState为1时按钮不可用
onClick: state.isLoading.isTrue isDisabled: state.sureBtnState.value == 1,
onClick: state.sureBtnState.value == 1
? null ? null
: () { : () {
FocusScope.of(context).requestFocus(FocusNode()); FocusScope.of(context).requestFocus(FocusNode());
//
if (state.wifiNameController.text.isEmpty) {
logic.showToast('请输入WiFi名称'.tr);
return;
}
if (state.wifiPWDController.text.isEmpty) {
logic.showToast('请输入WiFi密码'.tr);
return;
}
// WiFi名称是否包含5G关键字
if (state.wifiNameController.text
.toLowerCase()
.contains('5g')) {
logic.showToast('请确保使用2.4GHz WiFi网络'.tr);
return;
}
logic.senderConfiguringWifiAction(); logic.senderConfiguringWifiAction();
}, },
), ),
@ -86,7 +106,22 @@ class _ConfiguringWifiPageState extends State<ConfiguringWifiPage>
); );
} }
// Widget configuringWifiPasswordTFWidget(
String titleStr, String rightTitle, TextEditingController controller) {
return Column(
children: <Widget>[
Container(height: 10.h),
CommonItem(
leftTitel: titleStr,
rightTitle: '',
isHaveRightWidget: true,
rightWidget: getPasswordTFWidget(rightTitle, controller)),
Container(height: 10.h),
],
);
}
//
Widget getTFWidget(String tfStr, TextEditingController controller) { Widget getTFWidget(String tfStr, TextEditingController controller) {
return Container( return Container(
height: 65.h, height: 65.h,
@ -95,18 +130,14 @@ class _ConfiguringWifiPageState extends State<ConfiguringWifiPage>
children: <Widget>[ children: <Widget>[
Expanded( Expanded(
child: TextField( child: TextField(
//
maxLines: 1, maxLines: 1,
inputFormatters: <TextInputFormatter>[ inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.deny('\n'), FilteringTextInputFormatter.deny('\n'),
// LengthLimitingTextInputFormatter(30),
], ],
controller: controller, controller: controller,
autofocus: false, autofocus: false,
textAlign: TextAlign.end, textAlign: TextAlign.end,
decoration: InputDecoration( decoration: InputDecoration(
//
// contentPadding: const EdgeInsets.only(top: 12.0, bottom: 8.0),
hintText: tfStr, hintText: tfStr,
hintStyle: TextStyle(fontSize: 22.sp), hintStyle: TextStyle(fontSize: 22.sp),
focusedBorder: const OutlineInputBorder( focusedBorder: const OutlineInputBorder(
@ -135,6 +166,61 @@ class _ConfiguringWifiPageState extends State<ConfiguringWifiPage>
); );
} }
//
Widget getPasswordTFWidget(String tfStr, TextEditingController controller) {
return Container(
height: 65.h,
width: 300.w,
child: Row(
children: <Widget>[
Expanded(
child: Obx(
() => TextField(
maxLines: 1,
obscureText: _obscureText.value,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.deny('\n'),
],
controller: controller,
autofocus: false,
textAlign: TextAlign.end,
decoration: InputDecoration(
hintText: tfStr,
hintStyle: TextStyle(fontSize: 22.sp),
focusedBorder: const OutlineInputBorder(
borderSide:
BorderSide(width: 0, color: Colors.transparent)),
disabledBorder: const OutlineInputBorder(
borderSide:
BorderSide(width: 0, color: Colors.transparent)),
enabledBorder: const OutlineInputBorder(
borderSide:
BorderSide(width: 0, color: Colors.transparent)),
border: const OutlineInputBorder(
borderSide:
BorderSide(width: 0, color: Colors.transparent)),
contentPadding: const EdgeInsets.symmetric(vertical: 0),
),
style: TextStyle(
fontSize: 22.sp, textBaseline: TextBaseline.alphabetic),
),
),
),
IconButton(
icon: Icon(
_obscureText.value ? Icons.visibility_off : Icons.visibility,
color: Colors.grey,
size: 24.sp,
),
onPressed: () {
_obscureText.value = !_obscureText.value;
},
),
],
),
);
}
@override @override
void didChangeDependencies() { void didChangeDependencies() {
super.didChangeDependencies(); super.didChangeDependencies();

View File

@ -1,5 +1,3 @@
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:network_info_plus/network_info_plus.dart'; import 'package:network_info_plus/network_info_plus.dart';
@ -33,5 +31,4 @@ class ConfiguringWifiState {
String getGatewayConfigurationStr = ''; String getGatewayConfigurationStr = '';
RxBool isLoading = false.obs; RxBool isLoading = false.obs;
Timer? loadingTimer;
} }

View File

@ -2,6 +2,7 @@ import 'dart:async';
import 'package:flutter_blue_plus/flutter_blue_plus.dart'; import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:star_lock/app_settings/app_settings.dart';
import 'package:star_lock/blue/io_gateway/io_gateway_getWifiList.dart'; import 'package:star_lock/blue/io_gateway/io_gateway_getWifiList.dart';
import 'package:star_lock/blue/io_protocol/io_getWifiList.dart'; import 'package:star_lock/blue/io_protocol/io_getWifiList.dart';
import 'package:star_lock/talk/starChart/star_chart_manage.dart'; import 'package:star_lock/talk/starChart/star_chart_manage.dart';
@ -20,7 +21,9 @@ class WifiListLogic extends BaseGetXController {
// //
late StreamSubscription<Reply> _replySubscription; late StreamSubscription<Reply> _replySubscription;
Timer? _connectionTimer;
///
void _initReplySubscription() { void _initReplySubscription() {
_replySubscription = _replySubscription =
EventBusManager().eventBus!.on<Reply>().listen((Reply reply) { EventBusManager().eventBus!.on<Reply>().listen((Reply reply) {
@ -31,78 +34,130 @@ class WifiListLogic extends BaseGetXController {
if (reply is GatewayGetWifiListReply) { if (reply is GatewayGetWifiListReply) {
_replyGetWifiListParameters(reply); _replyGetWifiListParameters(reply);
} }
}, onError: (error) {
// CRC校验失败等错误
AppLog.log('WiFi列表获取过程中发生错误: $error');
// loading状态
dismissEasyLoading();
cancelBlueConnetctToastTimer();
//
state.sureBtnState.value = 0;
// CRC校验失败
if (error.toString().contains('CRC')) {
showToast('数据校验失败,请重新扫描'.tr);
} else {
showToast('扫描WiFi失败请重试'.tr);
}
}); });
} }
// wifi列表数据解析 /// wifi列表数据解析
Future<void> _replySendGetWifiParameters(Reply reply) async { Future<void> _replySendGetWifiParameters(Reply reply) async {
final int status = reply.data[2]; final int status = reply.data[2];
switch (status) { switch (status) {
case 0x00: case 0x00:
// // - loading框UI中已经有进度指示器
showEasyLoading();
cancelBlueConnetctToastTimer(); cancelBlueConnetctToastTimer();
Future.delayed(5.seconds, dismissEasyLoading);
break; break;
case 0x06: case 0x06:
// //
dismissEasyLoading();
AppLog.log('需要设备鉴权,请重试'.tr);
state.sureBtnState.value = 0;
break; break;
default: default:
//
dismissEasyLoading();
AppLog.log('获取WiFi列表失败错误码$status'.tr);
state.sureBtnState.value = 0;
break; break;
} }
} }
// WiFi数据解析 /// WiFi数据解析
Future<void> _replyGetWifiListParameters(Reply reply) async { Future<void> _replyGetWifiListParameters(Reply reply) async {
final int status = reply.data[2]; final int status = reply.data[2];
switch (status) { switch (status) {
case 0x00: case 0x00:
// //
// showEasyLoading();
dismissEasyLoading(); dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
if (reply.data[3] > 0) { if (reply.data[3] > 0) {
reply.data.removeRange(0, 4); reply.data.removeRange(0, 4);
// 33 // 33
final List<List<int>> getList = splitList(reply.data, 33); final List<List<int>> getList = splitList(reply.data, 33);
final List<Map<String, String>> uploadList = <Map<String, String>>[]; final List<Map<String, String>> uploadList = <Map<String, String>>[];
for (int i = 0; i < getList.length; i++) { for (int i = 0; i < getList.length; i++) {
final List<int> indexList = getList[i]; final List<int> indexList = getList[i];
final Map<String, String> indexMap = <String, String>{}; final Map<String, String> indexMap = <String, String>{};
final List<int> wifiName = indexList.sublist(0, 32); final List<int> wifiName = indexList.sublist(0, 32);
indexMap['wifiName'] = utf8String(wifiName); final String wifiNameStr = utf8String(wifiName).trim();
// WiFi名称
if (wifiNameStr.isEmpty) {
continue;
}
indexMap['wifiName'] = wifiNameStr;
indexMap['rssi'] = (indexList.last - 255).toString(); indexMap['rssi'] = (indexList.last - 255).toString();
uploadList.add(indexMap); uploadList.add(indexMap);
state.wifiNameDataList.value = uploadList;
} }
// WiFi列表 ()
uploadList.sort((a, b) =>
int.parse(b['rssi']!).compareTo(int.parse(a['rssi']!)));
state.wifiNameDataList.value = uploadList;
if (uploadList.isEmpty) {
showToast('未检测到可用的WiFi网络'.tr);
}
} else {
// WiFi列表为空的情况
state.wifiNameDataList.clear();
showToast('未检测到可用的WiFi网络'.tr);
} }
break; break;
default: default:
//
dismissEasyLoading();
showToast('解析WiFi列表失败错误码$status'.tr);
state.sureBtnState.value = 0;
break; break;
} }
} }
// wifi列表 /// WiFi列表
Future<void> senderGetWifiListWifiAction() async { Future<void> senderGetWifiListWifiAction() async {
if (state.sureBtnState.value == 1) { if (state.sureBtnState.value == 1) {
return; return;
} }
state.sureBtnState.value = 1; state.sureBtnState.value = 1;
state.wifiNameDataList.clear(); //
showEasyLoading(); // loading框UI中已经有进度指示器
showBlueConnetctToastTimer(action: () { showBlueConnetctToastTimer(action: () {
dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
}); });
BlueManage().blueSendData(BlueManage().connectDeviceName, BlueManage().blueSendData(BlueManage().connectDeviceName,
(BluetoothConnectionState connectionState) async { (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) { if (connectionState == BluetoothConnectionState.connected) {
IoSenderManage.gatewayGetWifiCommand( try {
userID: await Storage.getUid(), IoSenderManage.gatewayGetWifiCommand(
); userID: await Storage.getUid(),
);
} catch (e) {
state.sureBtnState.value = 0;
cancelBlueConnetctToastTimer();
showToast('发送获取WiFi列表请求失败${e.toString()}'.tr);
}
} else if (connectionState == BluetoothConnectionState.disconnected) { } else if (connectionState == BluetoothConnectionState.disconnected) {
dismissEasyLoading();
state.sureBtnState.value = 0; state.sureBtnState.value = 0;
cancelBlueConnetctToastTimer(); cancelBlueConnetctToastTimer();
if (state.ifCurrentScreen.value == true) { if (state.ifCurrentScreen.value == true) {
@ -113,22 +168,26 @@ class WifiListLogic extends BaseGetXController {
} }
@override @override
void onReady() { void onReady() async {
super.onReady(); super.onReady();
_initReplySubscription(); _initReplySubscription();
await senderGetWifiListWifiAction();
} }
@override @override
void onInit() { void onInit() {
super.onInit(); super.onInit();
//
senderGetWifiListWifiAction(); state.ifCurrentScreen.value = true;
} }
@override @override
void onClose() { void onClose() {
super.onClose(); //
_replySubscription.cancel(); _replySubscription.cancel();
_connectionTimer?.cancel();
cancelBlueConnetctToastTimer();
state.ifCurrentScreen.value = false;
super.onClose();
} }
} }

View File

@ -23,6 +23,32 @@ class _WifiListPageState extends State<WifiListPage> {
final WifiListLogic logic = Get.put(WifiListLogic()); final WifiListLogic logic = Get.put(WifiListLogic());
final WifiListState state = Get.find<WifiListLogic>().state; final WifiListState state = Get.find<WifiListLogic>().state;
/// WiFi信号强度图标
IconData _getWifiSignalIcon(String rssi) {
final int rssiValue = int.parse(rssi);
if (rssiValue >= -50) {
return Icons.signal_wifi_4_bar;
} else if (rssiValue >= -70) {
return Icons.network_wifi;
} else if (rssiValue >= -80) {
return Icons.network_wifi_2_bar_rounded;
} else {
return Icons.signal_wifi_0_bar;
}
}
@override
void initState() {
super.initState();
state.ifCurrentScreen.value = true;
}
@override
void dispose() {
state.ifCurrentScreen.value = false;
super.dispose();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return WillPopScope( return WillPopScope(
@ -38,13 +64,15 @@ class _WifiListPageState extends State<WifiListPage> {
barTitle: 'WIFI列表'.tr, barTitle: 'WIFI列表'.tr,
haveBack: state.pageName.value == 'lockSet', haveBack: state.pageName.value == 'lockSet',
actionsList: <Widget>[ actionsList: <Widget>[
TextButton( Obx(() => TextButton(
child: Text( child: Text(
'刷新'.tr, '刷新'.tr,
style: TextStyle(color: Colors.white, fontSize: 24.sp), style: TextStyle(color: Colors.white, fontSize: 24.sp),
), ),
onPressed: logic.senderGetWifiListWifiAction, onPressed: state.sureBtnState.value == 0
), ? logic.senderGetWifiListWifiAction
: null,
)),
], ],
backgroundColor: AppColors.mainColor, backgroundColor: AppColors.mainColor,
), ),
@ -52,26 +80,56 @@ class _WifiListPageState extends State<WifiListPage> {
children: <Widget>[ children: <Widget>[
Expanded( Expanded(
child: Obx(() => state.wifiNameDataList.value.isNotEmpty child: Obx(() => state.wifiNameDataList.value.isNotEmpty
? ListView.builder( ? RefreshIndicator(
itemCount: state.wifiNameDataList.value.length, onRefresh: () async {
itemBuilder: (BuildContext c, int index) { if (state.sureBtnState.value == 0) {
Map wifiNameStr = state.wifiNameDataList.value[index]; await logic.senderGetWifiListWifiAction();
return _messageListItem( }
wifiNameStr['wifiName'], wifiNameStr['rssi'], () { },
Get.toNamed(Routers.configuringWifiPage, child: ListView.builder(
arguments: { itemCount: state.wifiNameDataList.value.length,
'lockSetInfoData': itemBuilder: (BuildContext c, int index) {
state.lockSetInfoData.value, Map wifiNameStr =
'wifiName': wifiNameStr['wifiName'], state.wifiNameDataList.value[index];
'pageName': state.pageName.value, return _messageListItem(
}); wifiNameStr['wifiName'], wifiNameStr['rssi'],
}); () {
}) Get.toNamed(Routers.configuringWifiPage,
: NoData( arguments: {
noDataHeight: 1.sh - 'lockSetInfoData':
ScreenUtil().statusBarHeight - state.lockSetInfoData.value,
ScreenUtil().bottomBarHeight - 'wifiName': wifiNameStr['wifiName'],
64.h)), 'pageName': state.pageName.value,
});
});
}),
)
: Obx(() => state.sureBtnState.value == 1
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 50.w,
height: 50.w,
child: CircularProgressIndicator(
strokeWidth: 4.w,
valueColor: AlwaysStoppedAnimation<Color>(
AppColors.mainColor,
),
backgroundColor: Colors.grey[200],
),
),
SizedBox(height: 20.h),
Text('正在扫描WiFi网络...\n请确保设备处于正常状态'.tr,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 24.sp,
color: AppColors.blackColor))
],
),
)
: NoData())),
), ),
state.pageName.value == 'saveLock' state.pageName.value == 'saveLock'
? SubmitBtn( ? SubmitBtn(
@ -140,24 +198,37 @@ class _WifiListPageState extends State<WifiListPage> {
height: 79.h, height: 79.h,
width: 1.sw - 20.w * 2, width: 1.sw - 20.w * 2,
child: Row( child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[ children: <Widget>[
Flexible( Flexible(
flex: 4,
child: Text( child: Text(
'$wifiName(${rssi}db)', wifiName,
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: TextStyle( style: TextStyle(
fontSize: 22.sp, color: AppColors.blackColor), fontSize: 24.sp, color: AppColors.blackColor),
), ),
), ),
// Text( Flexible(
// rssi, flex: 1,
// maxLines: 1, child: Row(
// overflow: TextOverflow.ellipsis, mainAxisAlignment: MainAxisAlignment.end,
// style: TextStyle( children: [
// fontSize: 22.sp, color: AppColors.blackColor), Icon(
// ) _getWifiSignalIcon(rssi),
color: AppColors.mainColor,
size: 24.sp,
),
SizedBox(width: 8.w),
Text(
'$rssi dB',
style:
TextStyle(fontSize: 18.sp, color: Colors.black),
),
],
),
)
], ],
), ),
), ),