更新眠花糖兼容wifi配置

This commit is contained in:
wyf
2025-10-28 14:51:28 +08:00
parent 7cfd3bf8f5
commit 3c5db3bdf2
14 changed files with 1259 additions and 882 deletions

View File

@@ -106,53 +106,53 @@ class _VitalSignsSensorState extends State<VitalSignsSensorPage> {
left: 0.rpx,
child: returnIconButtomNew(),
),
Positioned(
right: 0.rpx,
child: ClickableContainer(
backgroundColor: Colors.transparent,
highlightColor: Colors.transparent,
padding: EdgeInsets.symmetric(
horizontal: 30.rpx, vertical: 30.rpx),
onTap: () {
// TopSlideNotification.show(context);
//检测蓝牙是否开启,没有开启提示开启蓝牙
//如果已经开启则进行x秒的蓝牙扫描
BluetoothHelper.listenBluetoothState((isOn) {
mhtBlueToothController.model.bluetooth = isOn;
mhtBlueToothController.updateAll();
if (!isOn) {
mhtBlueToothController.model.blueRawData = [];
mhtBlueToothController
.model.deviceDataStatus = [];
mhtBlueToothController.updateAll();
_showBluetoothNotEnabledDialog();
}
});
_checkBluetoothPermission();
},
child: Obx(() {
return SizedBox(
width: 34.rpx,
height: mhtBlueToothController.isScanning.value
? 34.rpx
: 24.rpx,
child: mhtBlueToothController.isScanning.value
? CircularProgressIndicator(
strokeWidth: 2,
valueColor:
AlwaysStoppedAnimation<Color>(
themeController.currentColor.sc3,
),
)
: SvgPicture.asset(
'assets/img/icon/upgrade.svg',
fit: BoxFit.cover,
color: Colors.white,
),
);
}),
),
),
// Positioned(
// right: 0.rpx,
// child: ClickableContainer(
// backgroundColor: Colors.transparent,
// highlightColor: Colors.transparent,
// padding: EdgeInsets.symmetric(
// horizontal: 30.rpx, vertical: 30.rpx),
// onTap: () {
// // TopSlideNotification.show(context);
// //检测蓝牙是否开启,没有开启提示开启蓝牙
// //如果已经开启则进行x秒的蓝牙扫描
// BluetoothHelper.listenBluetoothState((isOn) {
// mhtBlueToothController.model.bluetooth = isOn;
// mhtBlueToothController.updateAll();
// if (!isOn) {
// mhtBlueToothController.model.blueRawData = [];
// mhtBlueToothController
// .model.deviceDataStatus = [];
// mhtBlueToothController.updateAll();
// _showBluetoothNotEnabledDialog();
// }
// });
// _checkBluetoothPermission();
// },
// child: Obx(() {
// return SizedBox(
// width: 34.rpx,
// height: mhtBlueToothController.isScanning.value
// ? 34.rpx
// : 24.rpx,
// child: mhtBlueToothController.isScanning.value
// ? CircularProgressIndicator(
// strokeWidth: 2,
// valueColor:
// AlwaysStoppedAnimation<Color>(
// themeController.currentColor.sc3,
// ),
// )
// : SvgPicture.asset(
// 'assets/img/icon/upgrade.svg',
// fit: BoxFit.cover,
// color: Colors.white,
// ),
// );
// }),
// ),
// ),
],
),
),
@@ -279,12 +279,16 @@ class _VitalSignsSensorState extends State<VitalSignsSensorPage> {
.toList();
//todo 过滤,跟远程的版本信息比对
// return macList.contains(d.mac) && d.version != null;
if (formatString(d.mac) == "48CA43B2E0B4") {
ef.log("");
if (macList.contains(formatString(d.mac))) {
ef.log("[待升级设备]:${d.mac}, 版本:${d.version}");
}
return macList.contains(formatString(d.mac));
// return macList.contains(formatString(d.mac)) &&
// d.version != null &&
// judgeNeedUpgrade(d.version);
return macList.contains(formatString(d.mac)) &&
judgeNeedUpgrade(d.version);
}).toList();
print("$filteredResults");
for (var item in filteredResults) {
// 如果不存在才加入,初始进度设为-1代表未开始升级
mhtBlueToothController.localUpgradeMac.putIfAbsent(
@@ -436,6 +440,42 @@ class _VitalSignsSensorState extends State<VitalSignsSensorPage> {
/// 格式化字符串:移除所有空格和冒号,并将小写字母转换为大写
return input.replaceAll(' ', '').replaceAll(':', '').toUpperCase();
}
bool judgeNeedUpgrade(int? version) {
return true;
try {
if (version == null) {
ef.log("[升级判断] 本地版本为空,不需要升级");
return false;
}
String? newestVersionStr = mhtBlueToothController.currentUpgradeVersion;
if (newestVersionStr == null || newestVersionStr.isEmpty) {
ef.log("[升级判断] 远程最新版本为空,不需要升级");
return false;
}
// 转为整数比较
int? newestVersion = int.tryParse(newestVersionStr);
if (newestVersion == null) {
ef.log("[升级判断] 远程版本格式错误: $newestVersionStr");
return false;
}
ef.log("[升级判断] 当前版本: $version,远程版本: $newestVersion");
if (newestVersion > version) {
ef.log("[升级判断] 检测到新版本,需要升级");
return true;
} else {
ef.log("[升级判断] 已是最新版本,无需升级");
return false;
}
} catch (e) {
ef.log("[升级判断] 异常: $e");
return false;
}
}
}
class VitalWidget extends StatelessWidget {
@@ -843,6 +883,7 @@ class VitalWidget extends StatelessWidget {
mac: data['mac'],
firmwareUrl: firmwareUrl,
);
} catch (e) {
print("升级失败: $e");
TopSlideNotification.show(context,
@@ -960,520 +1001,6 @@ class VitalWidget extends StatelessWidget {
}
}
// class VitalWidget extends StatelessWidget {
// final String title;
// final Map<String, dynamic> data;
// const VitalWidget({
// super.key,
// required this.title,
// required this.data,
// });
// @override
// Widget build(BuildContext context) {
// MHTBlueToothController mhtBlueToothController = Get.find();
// final String id = data['mac'.tr] ?? '--';
// final int? timestamp = data['status']['updateTime'];
// final String time = (timestamp != null)
// ? DateFormat('yyyy-MM-dd HH:mm')
// .format(DateTime.fromMillisecondsSinceEpoch(timestamp))
// : '--';
// return ClickableContainer(
// backgroundColor: Color(0xFF003058),
// highlightColor: Color(0xFF055466),
// borderRadius: 20.rpx,
// padding: EdgeInsetsDirectional.fromSTEB(30.rpx, 30.rpx, 30.rpx, 40.rpx),
// onTap: () {},
// child: Column(
// mainAxisSize: MainAxisSize.max,
// children: [
// Container(
// width: double.infinity,
// child: Align(
// alignment: AlignmentDirectional(-1, 0),
// child: Text(
// title,
// style: TextStyle(
// fontFamily: 'Inter',
// fontSize: 30.rpx,
// letterSpacing: 0.0,
// color: themeController.currentColor.sc3,
// ),
// ),
// ),
// ),
// Row(
// mainAxisAlignment: MainAxisAlignment.start,
// children: [
// Container(
// width: MediaQuery.sizeOf(context).width * 0.14,
// constraints: BoxConstraints(minWidth: 110.rpx),
// child: Text(
// "设备ID".tr,
// style: TextStyle(
// color: stringToColor("#929699"),
// fontSize: 26.rpx,
// ),
// maxLines: 2,
// overflow: TextOverflow.ellipsis,
// ),
// ),
// Text(
// id,
// style: TextStyle(fontSize: 26.rpx, color: Color(0xFFFFFFFF)),
// ),
// ].divide(SizedBox(width: 33.rpx)),
// ),
// Row(
// mainAxisAlignment: MainAxisAlignment.start,
// children: [
// Container(
// width: MediaQuery.sizeOf(context).width * 0.14,
// constraints: BoxConstraints(minWidth: 110.rpx),
// child: Text(
// "更新时间".tr,
// style: TextStyle(
// color: stringToColor("#929699"),
// fontSize: 26.rpx,
// ),
// maxLines: 2,
// overflow: TextOverflow.ellipsis,
// ),
// ),
// Text(
// time,
// style: TextStyle(fontSize: 26.rpx, color: Color(0xFFFFFFFF)),
// ),
// ].divide(SizedBox(width: 33.rpx)),
// ),
// Row(
// mainAxisSize: MainAxisSize.max,
// children: [
// Container(
// width: MediaQuery.sizeOf(context).width * 0.14,
// constraints: BoxConstraints(minWidth: 110.rpx),
// child: Text(
// "设备状态".tr,
// style: TextStyle(
// color: stringToColor("#929699"),
// fontSize: 26.rpx,
// ),
// maxLines: 2,
// overflow: TextOverflow.ellipsis,
// ),
// ),
// Expanded(
// child: Row(
// mainAxisSize: MainAxisSize.max,
// children: [
// if (data['status']['signal'] != null &&
// data['status']['signal'] != -1 &&
// data['status']['status'] != null &&
// data['status']['status'] == 1)
// ClickableContainer(
// backgroundColor: Colors.transparent,
// highlightColor: Colors.grey,
// padding: EdgeInsets.zero,
// borderRadius: 0,
// onTap: () {
// showTipDialog(
// context,
// Container(
// child: RichText(
// text: TextSpan(
// text: "信号强度".tr,
// style: TextStyle(
// color: Colors.black,
// fontSize:
// AppConstants().title_text_fontSize,
// ),
// children: [
// TextSpan(
// text: getBedSignal(
// data['status']['signal']),
// style: TextStyle(
// color: themeController.currentColor.sc2,
// fontSize:
// AppConstants().title_text_fontSize,
// ),
// ),
// ],
// ),
// ),
// ),
// backgroundColor: Color(0xFFFFFFFF),
// colors: [
// Color(0XFF1592AA),
// Color(0xFF0C83A7),
// Color(0xFF006FA3)
// ],
// );
// },
// child: Container(
// width: 30.rpx,
// height: 24.rpx,
// child: Image.asset(
// 'assets/img/signal${_getSignalLevel(data['status']['signal'])}.png'),
// ),
// ),
// if (data['status']['inBed'] != null &&
// data['status']['status'] != null &&
// data['status']['status'] == 1)
// ClickableContainer(
// backgroundColor: Colors.transparent,
// highlightColor: Colors.grey,
// padding: EdgeInsetsDirectional.fromSTEB(0, 0.rpx, 0, 0),
// borderRadius: 0,
// onTap: () {
// showTipDialog(
// context,
// Container(
// child: RichText(
// text: TextSpan(
// text: "是否在床".tr,
// style: TextStyle(
// color: Colors.black,
// fontSize:
// AppConstants().title_text_fontSize,
// ),
// children: [
// TextSpan(
// text:
// getBedStatus(data['status']['inBed']),
// style: TextStyle(
// color: themeController.currentColor.sc2,
// fontSize:
// AppConstants().title_text_fontSize,
// ),
// ),
// ],
// ),
// ),
// ),
// backgroundColor: Color(0xFFFFFFFF),
// colors: [
// Color(0XFF1592AA),
// Color(0xFF0C83A7),
// Color(0xFF006FA3)
// ],
// );
// },
// child: SizedBox(
// width: 16.rpx,
// height: 36.rpx,
// child: SvgPicture.asset(
// data['status']['inBed'] == 0
// ? 'assets/img/icon/not_bed.svg'
// : 'assets/img/icon/in_bed.svg',
// fit: BoxFit.fill,
// ),
// ),
// ),
// if (data['status']['failure'] != 0 &&
// data['status']['status'] != null &&
// data['status']['status'] == 1)
// ClickableContainer(
// backgroundColor: Colors.transparent,
// highlightColor: Colors.grey,
// padding: EdgeInsetsDirectional.fromSTEB(0, 0.rpx, 0, 0),
// borderRadius: 0,
// onTap: () {
// showTipDialog(
// context,
// Container(
// child: RichText(
// text: TextSpan(
// text: "设备故障".tr,
// style: TextStyle(
// color: Colors.black,
// fontSize:
// AppConstants().title_text_fontSize,
// ),
// children: const [],
// ),
// ),
// ),
// backgroundColor: Color(0xFFFFFFFF),
// colors: [
// Color(0XFF1592AA),
// Color(0xFF0C83A7),
// Color(0xFF006FA3)
// ],
// );
// },
// child: SizedBox(
// width: 27.rpx,
// height: 27.rpx,
// child: SvgPicture.asset(
// 'assets/img/icon/device_issue.svg',
// fit: BoxFit.cover,
// ),
// ),
// ),
// if (data['status']['status'] != null &&
// data['status']['status'] == 0)
// ClickableContainer(
// backgroundColor: Colors.transparent,
// highlightColor: Colors.grey,
// padding: EdgeInsetsDirectional.fromSTEB(0, 0.rpx, 0, 0),
// borderRadius: 0,
// onTap: () {
// showTipDialog(
// context,
// Container(
// child: RichText(
// text: TextSpan(
// text: "网络状态".tr,
// style: TextStyle(
// color: Colors.black,
// fontSize:
// AppConstants().title_text_fontSize,
// ),
// children: [
// TextSpan(
// text: data['status']['status'] == 1
// ? "在线".tr
// : "离线".tr,
// style: TextStyle(
// color: themeController.currentColor.sc2,
// fontSize:
// AppConstants().title_text_fontSize,
// ),
// ),
// ],
// ),
// ),
// ),
// backgroundColor: Color(0xFFFFFFFF),
// colors: [
// Color(0XFF1592AA),
// Color(0xFF0C83A7),
// Color(0xFF006FA3)
// ],
// );
// },
// child: SizedBox(
// width: 27.rpx,
// height: 27.rpx,
// child: SvgPicture.asset(
// 'assets/img/icon/device_issue.svg',
// fit: BoxFit.cover,
// ),
// ),
// ),
// Obx(() {
// final upgradeInfo =
// mhtBlueToothController.localUpgradeMac[data['mac']];
// if (upgradeInfo == null) {
// return Container();
// }
// final int progress = upgradeInfo?['progress'] ?? -1;
// final String status = upgradeInfo?['status'] ?? '';
// // 只有在有升级信息时才显示
// if (mhtBlueToothController.localUpgradeMac
// .containsKey(data['mac'])) {
// return ClickableContainer(
// backgroundColor: Colors.transparent,
// highlightColor: Colors.grey,
// padding:
// EdgeInsetsDirectional.fromSTEB(0, 0.rpx, 0, 0),
// borderRadius: 0,
// onTap: () {
// if (progress == -1) {
// _showUpgradeDialog(context, data['mac']);
// } else {
// _showCancelDialog(context, data['mac']);
// }
// },
// child: Row(
// children: [
// // 升级图标
// SizedBox(
// width: 34.rpx,
// height: 24.rpx,
// child: SvgPicture.asset(
// 'assets/img/icon/upgrade.svg',
// fit: BoxFit.cover,
// color: _getUpgradeIconColor(status),
// ),
// ),
// SizedBox(width: 10.rpx),
// // 进度数字和状态指示
// Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// mainAxisSize: MainAxisSize.min,
// children: [
// // 进度百分比
// if (progress >= 0 && progress <= 100)
// Text(
// "$progress%",
// style: TextStyle(
// color: _getProgressTextColor(progress),
// fontSize: 26.rpx,
// fontWeight: FontWeight.bold,
// ),
// ),
// ],
// ),
// ],
// ),
// );
// }
// return Container();
// }),
// ].divide(SizedBox(width: 50.rpx)), // 减少图标间距
// ),
// ),
// ].divide(SizedBox(width: 34.rpx)),
// ),
// ].divide(SizedBox(height: 20.rpx)),
// ),
// );
// }
// // 获取状态文本
// String _getStatusText(String status) {
// switch (status) {
// case 'waiting':
// return '等待'.tr;
// case 'downloading':
// return '下载'.tr;
// case 'upgrading':
// return '升级'.tr;
// case 'completed':
// return '完成'.tr;
// case 'failed':
// return '失败'.tr;
// case 'cancelled':
// return '取消'.tr;
// default:
// return status;
// }
// }
// // 获取状态文字颜色
// Color _getStatusTextColor(String status) {
// switch (status) {
// case 'completed':
// return Colors.green;
// case 'failed':
// return Colors.red;
// case 'cancelled':
// return Colors.orange;
// default:
// return Colors.blue;
// }
// }
// // 获取进度文字颜色
// Color _getProgressTextColor(int progress) {
// if (progress == 100) return Colors.green;
// if (progress < 0) return Colors.red;
// return Colors.white;
// }
// // 获取升级图标颜色
// Color _getUpgradeIconColor(String status) {
// switch (status) {
// case 'completed':
// return Colors.green;
// case 'failed':
// return Colors.red;
// case 'cancelled':
// return Colors.orange;
// default:
// return themeController.currentColor.sc3;
// }
// }
// // 显示升级对话框
// void _showUpgradeDialog(BuildContext context, String mac) {
// MHTBlueToothController mhtBlueToothController = Get.find();
// showConfirmUpDialog(
// context,
// Column(
// children: [
// SizedBox(
// width: 94.rpx,
// height: 70.rpx,
// child: SvgPicture.asset(
// 'assets/img/icon/upgrade.svg',
// fit: BoxFit.cover,
// ),
// ),
// Text(
// "设备升级".tr,
// style: TextStyle(
// color: stringToColor("#333333"),
// fontSize: AppConstants().title_text_fontSize,
// ),
// ),
// ].divide(SizedBox(height: 37.rpx)),
// ),
// "", onConfirm: () async {
// final deviceData = mhtBlueToothController.localUpgradeMac[mac]!;
// final firmwareUrl = mhtBlueToothController.currentUpgradeUrl;
// if (firmwareUrl == null) {
// TopSlideNotification.show(context, text: "未获取到固件下载地址".tr);
// return;
// }
// try {
// final scanResult = deviceData['device'].scanResult;
// final thapp = THapp(device: scanResult.device);
// if (!thapp.isConnected) {
// await thapp.device.connect();
// }
// await MultiDeviceFirmwareUpdater().startUpgrade(
// thapp: thapp,
// mac: mac,
// firmwareUrl: firmwareUrl,
// );
// } catch (e) {
// TopSlideNotification.show(context,
// text: "升级失败: ${e.toString()}".tr, textColor: Colors.red);
// }
// },
// onCancel: () {},
// backgroundColor: Colors.white,
// confirmText: "立即升级".tr,
// cancelText: "下次再说".tr);
// }
// // 显示取消对话框
// void _showCancelDialog(BuildContext context, String mac) {
// showConfirmCancelDialog(
// context,
// Column(
// children: [
// Text(
// "确认取消升级".tr,
// style: TextStyle(
// color: stringToColor("#333333"),
// fontSize: AppConstants().title_text_fontSize,
// ),
// ),
// Text(
// "确定要取消设备 $mac 的升级吗?".tr,
// style: TextStyle(
// color: stringToColor("#333333"),
// fontSize: AppConstants().normal_text_fontSize,
// ),
// ),
// ],
// ),
// "", onConfirm: () {
// MultiDeviceFirmwareUpdater().cancelUpgrade(mac);
// },
// onCancel: () {},
// backgroundColor: Colors.white,
// confirmText: "确认取消".tr,
// cancelText: "继续升级".tr,
// confirmButtonColor: Colors.red);
// }
// }
getBedSignal(signal) {
if (signal <= 1) {
return "较弱".tr;

View File

@@ -229,7 +229,7 @@ class MHTBlueToothController extends GetControllerEx<MHTBlueToothModel> {
'name': bleDevice.name,
},
};
EasyDartModule.logger.info("绑定传感器数据: $data");
var response =
await EasyDartModule.dio.post(queryUrl, data: jsonEncode(data));
if (response != null) {

View File

@@ -12,14 +12,16 @@ import 'package:vbvs_app/common/util/requestWithLog.dart';
import 'package:vbvs_app/component/tool/ClickableContainer.dart';
import 'package:vbvs_app/component/tool/CustomCard.dart';
import 'package:vbvs_app/component/tool/TopSlideNotification.dart';
import 'package:vbvs_app/controller/device/blueteeth_bind_controller.dart';
import 'package:vbvs_app/pages/device_bind/componnet/CalibrationProgressWidget.dart';
import 'package:vbvs_app/pages/mh_page/component/mht_bind_dialog.dart';
import 'package:vbvs_app/pages/mh_page/device/component/mht_device_calibration_controller.dart';
import 'package:vbvs_app/pages/mh_page/device/controller/mht_bluetooth_controller.dart';
import 'package:vbvs_app/pages/mh_page/device/model/BlueToothDataModel.dart';
class MHTCalibrationPage extends StatefulWidget {
const MHTCalibrationPage({super.key});
BlueToothDataModel deviceInfo;
MHTCalibrationPage({super.key, required this.deviceInfo});
@override
State<MHTCalibrationPage> createState() => _MHTCalibrationPageState();
}
@@ -114,6 +116,10 @@ class _MHTCalibrationPageState extends State<MHTCalibrationPage> {
onConfirm: () async {
exit = true;
_resetCalibrationState();
// Get.back();
initWifiData();
// Get.toNamed('/mHTwifiPage',
// arguments: widget.deviceInfo);
Get.back();
}, onCancel: () {
exit = false;
@@ -125,6 +131,9 @@ class _MHTCalibrationPageState extends State<MHTCalibrationPage> {
exit = true;
}
if (exit) {
initWifiData();
// Get.toNamed('/mHTwifiPage',
// arguments: widget.deviceInfo);
Get.back();
}
}, enableBack: exit),
@@ -741,7 +750,7 @@ class _MHTCalibrationPageState extends State<MHTCalibrationPage> {
}
void _requestProgress(
String serviceAddress, String progressApi, bool isSecondStep) {
String serviceAddress, String progressApi, bool isSecondStep) {
String cid = blueteethBindController.cid!.value;
String progressUrl = "$serviceAddress$progressApi?id=$cid";
@@ -1006,4 +1015,19 @@ class _MHTCalibrationPageState extends State<MHTCalibrationPage> {
onFailure: (res) {},
);
}
void initWifiData() {
BlueteethBindController blueteethBindController = Get.find();
blueteethBindController.shareDevice = widget.deviceInfo;
blueteethBindController.netType.value = 0;
blueteethBindController.connectStatus.value = 0;
blueteethBindController.wifiList = [].obs;
blueteethBindController.wifiStatus = 0.obs;
blueteethBindController.connect_wifi.value = {};
blueteethBindController.selectWifi.value = {};
blueteethBindController.wifiStatus.value = 0;
blueteethBindController.blueConnectFlag.value = 0;
blueteethBindController.wifiConnectStatus.value = 1;
blueteethBindController.updateAll();
}
}

View File

@@ -45,17 +45,23 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
Timer? _timeoutTimer;
StreamSubscription<List<ScanResult>>? _scanSubscription;
bool _isDisposed = false;
bool dealing = false; //是否正在刷新
DateTime _lastTapTime = DateTime.now();
bool haveSuccess = false;
@override
void initState() {
super.initState();
_initController();
dealWifi(widget.deviceInfo.macA).then((aa) {
WidgetsBinding.instance.addPostFrameCallback((_) async {
// _initController();
await dealWifi(widget.deviceInfo.macA);
print("object");
});
}
void _initController() {
dealing = false;
blueteethBindController.shareDevice = widget.deviceInfo;
blueteethBindController.netType.value = 0;
blueteethBindController.connectStatus.value = 0;
@@ -73,11 +79,11 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
void dispose() {
_isDisposed = true;
_cleanupResources();
_disconnectDevice();
// _disconnectDevice();
super.dispose();
}
void _cleanupResources() {
Future<void> _cleanupResources({bool needTip = true}) async {
// 取消监听器
lisObj?.cancel();
lisObj = null;
@@ -91,10 +97,11 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
_scanSubscription = null;
// 断开蓝牙连接
if (blueteethBindController.currentDevice != null) {
blueteethBindController.currentDevice!.disconnect();
blueteethBindController.currentDevice = null;
}
// if (blueteethBindController.currentDevice != null) {
// blueteethBindController.currentDevice!.disconnect();
// blueteethBindController.currentDevice = null;
// }
await _disconnectDevice();
// 停止扫描
FlutterBluePlus.stopScan();
@@ -105,24 +112,30 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
_cleanupResources();
if (_isDisposed) return;
// 导航到下一页
if (blueteethBindController.wifiStatus.value != 1) {
showConfirmDialog(context, Container(), "未配置网络提示".tr,
onConfirm: () async {
_cleanupResources();
await _disconnectDevice();
Get.toNamed("/calibrationPage");
Get.toNamed("/calibrationPage", arguments: widget.deviceInfo)!
.then((value) {
dealWifi(widget.deviceInfo.macA);
});
}, onCancel: () {});
} else {
_cleanupResources();
await _disconnectDevice();
Get.toNamed("/calibrationPage");
Get.toNamed("/calibrationPage", arguments: widget.deviceInfo)!
.then((value) {
dealWifi(widget.deviceInfo.macA);
});
}
}
@override
Widget build(BuildContext context) {
// _initController();
return LayoutBuilder(
builder: (context, bodySize) => GestureDetector(
// onTap: () => FocusScope.of(context).unfocus(),,
@@ -209,7 +222,13 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
),
Positioned(
left: 0,
child: returnIconButtom,
child: returnIconButtomNew(
onBack: () {
// Get.offAllNamed('/mHTBlueteethDevicePage',
// arguments: widget.deviceInfo.type);
Get.back();
},
),
),
Positioned(
right: 20.rpx,
@@ -279,6 +298,9 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
),
),
Obx(() {
var cc = blueteethBindController
.wifiStatus.value;
print("${cc}");
return Text(
blueteethBindController
.wifiStatus.value ==
@@ -552,6 +574,7 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
wifiItem['ssid'] ??
'未命名'.tr,
onConfirm: () async {
haveSuccess = false;
blueteethBindController
.selectWifi
.value = wifiItem;
@@ -561,14 +584,55 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
.model.wifiPass!,
blueteethBindController
.currentDevice!);
bool memoryFlag =
await queryMemory(
blueteethBindController
.currentDevice!);
if (!memoryFlag) {
await rebootDevice(
blueteethBindController
.currentDevice!);
await dealWifi(
widget
.deviceInfo.macA,
needSuccess: true);
// return;
}
if (!flag) {
blueteethBindController
.selectWifi
.value = {};
// TopSlideNotification.show(
// context,
// textColor:
// themeController
// .currentColor
// .sc9,
// text:
// '蓝牙已断开,请点击下方刷新按钮重试'
// .tr);
return;
}
if (flag) {
var aa = await getDeviceWifiStatus(
blueteethBindController
.currentDevice!,
1);
4,
link: true);
aa = await restoreWifi(
blueteethBindController
.currentDevice!,
aa);
if (!memoryFlag) {
aa = await rebootDeviceCurrent(
blueteethBindController
.currentDevice!,
aa);
}
blueteethBindController
.selectWifi
.value = {};
if (aa != null &&
aa is Map) {
blueteethBindController
@@ -578,30 +642,46 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
blueteethBindController
.connect_wifi
.value = {};
blueteethBindController
.wifiStatus
.value ==
0;
blueteethBindController
.updateAll();
}
blueteethBindController
.wifiStatus
.value =
aa != null ? 1 : 0;
if (aa != null&&
if (aa != null &&
aa != false) {
updateDeviceBindStatus(
blueteethBindController
.currentDeviceMac!
.value);
TopSlideNotification
.show(
context,
text: "配网成功".tr,
textColor:
themeController
.currentColor
.sc2,
);
if (!haveSuccess) {
TopSlideNotification
.show(
context,
text: "配网成功".tr,
textColor:
themeController
.currentColor
.sc2,
);
}
} else {
blueteethBindController
blueteethBindController
.connect_wifi
.value = {};
blueteethBindController
.selectWifi
.value = {};
blueteethBindController
.wifiStatus
.value = 0;
blueteethBindController
.updateAll();
TopSlideNotification
.show(
context,
@@ -613,9 +693,16 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
);
}
} else {
blueteethBindController
.connect_wifi
.value = {};
blueteethBindController
.selectWifi
.value = {};
blueteethBindController
.connect_wifi
.value = {};
blueteethBindController
.wifiStatus.value = 0;
blueteethBindController
.updateAll();
TopSlideNotification.show(
context,
text: "配网失败".tr,
@@ -626,7 +713,6 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
);
}
});
},
child: Row(
mainAxisSize:
@@ -678,6 +764,17 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
horizontal: 20.rpx, vertical: 10.rpx),
borderRadius: 20.rpx,
onTap: () async {
if (DateTime.now()
.difference(_lastTapTime) <
Duration(seconds: 2)) {
return; // 防止快速重复点击
}
_lastTapTime = DateTime.now();
blueteethBindController.netType.value = 0;
blueteethBindController
.blueConnectFlag.value = 0;
blueteethBindController.wifiList.value =
[];
var bluetoothState =
await FlutterBluePlus.isOn;
blueteethBindController.bluetoothStatus
@@ -694,13 +791,13 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
1) {
blueteethBindController
.blueConnectFlag.value = 0;
dealWifi(widget.deviceInfo.macA)
await dealWifi(widget.deviceInfo.macA,
needTip: false)
.then((aa) {
print("object");
});
return;
}
if (blueteethBindController
.netType.value ==
0) {
@@ -712,6 +809,7 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
blueteethBindController
.currentDevice!,
1);
if (aa == "4g") {
updateDeviceBindStatus(
blueteethBindController
@@ -731,7 +829,10 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
const Duration(seconds: 1), () {
_cleanupResources();
Get.toNamed("/calibrationPage",
arguments: 1);
arguments: 1)!
.then((value) {
dealWifi(widget.deviceInfo.macA);
});
});
} else if (aa == 'unknown') {
blueteethBindController.netType.value =
@@ -746,6 +847,7 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
.currentColor.sc9,
);
});
await initWifiStatusAndWifiList();
} else {
blueteethBindController.netType.value =
1;
@@ -798,24 +900,40 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
);
}
Future<void> initWifiStatusAndWifiList() async {
Future<void> initWifiStatusAndWifiList(
{int retryCount = 0, bool needSuccess = false}) async {
if (_isDisposed) return;
if (lisObj != null) {
lisObj!.cancel();
lisObj = null;
}
bool wifiStatus = false;
var aa =
await getDeviceWifiStatus(blueteethBindController.currentDevice!, 0);
if (aa != null && aa is Map) {
updateDeviceBindStatus(blueteethBindController.currentDeviceMac!.value);
wifiStatus = true;
blueteethBindController.connect_wifi.value = aa;
} else {
wifiStatus = false;
try {
// 获取WiFi状态
var aa =
await getDeviceWifiStatus(blueteethBindController.currentDevice!, 0);
if (aa != null && aa is Map) {
updateDeviceBindStatus(blueteethBindController.currentDeviceMac!.value);
wifiStatus = true;
blueteethBindController.connect_wifi.value = aa;
if (needSuccess) {
haveSuccess = true;
TopSlideNotification.show(
context,
text: "配网成功".tr,
textColor: themeController.currentColor.sc2,
);
}
} else {
wifiStatus = false;
}
blueteethBindController.wifiStatus.value = wifiStatus ? 1 : 0;
} catch (e) {
print("获取WiFi状态异常: $e");
blueteethBindController.wifiStatus.value = 0;
}
blueteethBindController.wifiStatus.value = wifiStatus ? 1 : 0;
List wifiList = [];
try {
@@ -836,19 +954,52 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
if (wifiList.isNotEmpty) {
blueteethBindController.connectStatus.value = 1;
blueteethBindController.updateAll();
TopSlideNotification.show(
context,
text: "获取wifi列表成功".tr,
textColor: themeController.currentColor.sc2,
);
// TopSlideNotification.show(
// context,
// text: "获取wifi列表成功".tr,
// textColor: themeController.currentColor.sc2,
// );
blueteethBindController.wifiList.value = wifiList;
blueteethBindController.updateAll();
} else {
// 获取WiFi列表失败尝试重新扫描
if (retryCount < 2) {
// 最多重试2次
print("${retryCount + 1}次获取WiFi列表失败尝试重新扫描...");
// TopSlideNotification.show(
// context,
// text: "正在重新扫描WiFi...".tr,
// textColor: themeController.currentColor.sc2,
// );
try {
// 发送关闭并重新打开WiFi扫描命令
await sendCloseAndOpenWscanCommand(
blueteethBindController.currentDevice!);
// 等待一段时间让设备重新扫描
await Future.delayed(Duration(seconds: 3));
// 递归调用自身进行重试
await initWifiStatusAndWifiList(retryCount: retryCount + 1);
return; // 重试后直接返回,避免执行后面的代码
} catch (e) {
print("重新扫描WiFi失败: $e");
// 继续执行下面的失败处理
}
}
// 重试次数用尽或重试失败,显示最终失败提示
TopSlideNotification.show(
context,
text: "获取wifi列表失败".tr,
textColor: themeController.currentColor.sc9,
);
// 可选重置WiFi连接状态
blueteethBindController.connectStatus.value = 0;
blueteethBindController.updateAll();
}
lisObj = blueteethBindController.currentDevice!.statusStream
@@ -859,6 +1010,21 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
edm.EasyDartModule.logger.info("[bleee]:" + line);
DailyLogUtils.writeLog("[bleee]:" + line);
}
if (onData.status == BleEventType.disconnected) {
print("蓝牙连接已断开");
blueteethBindController.blueConnectFlag.value = 1;
blueteethBindController.updateAll();
// 显示断开提示
// if (!_isDisposed) {
// TopSlideNotification.show(
// context,
// text: "蓝牙连接已断开,请重新连接".tr,
// textColor: themeController.currentColor.sc9,
// );
// }
_autoReconnect();
}
});
}
@@ -910,16 +1076,21 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
}
}
Future<void> dealWifi(String mac) async {
if (_isDisposed) return;
final blueteethBindController = Get.find<BlueteethBindController>();
final themeController = Get.find<ThemeController>();
// 清理之前的资源
_cleanupResources();
Future<void> dealWifi(String mac,
{bool needTip = true, bool needSuccess = false}) async {
if (dealing) {
return;
}
try {
dealing = true;
if (_isDisposed) return;
final blueteethBindController = Get.find<BlueteethBindController>();
final themeController = Get.find<ThemeController>();
// 清理之前的资源
_cleanupResources(needTip: needTip);
// 检查蓝牙状态
var bluetoothState = await FlutterBluePlus.isOn;
blueteethBindController.bluetoothStatus.value = bluetoothState;
@@ -938,6 +1109,7 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
_timeoutTimer = Timer(Duration(seconds: 20), () {
if (!isConnected && !_isDisposed) {
blueteethBindController.blueConnectFlag.value = 1;
blueteethBindController.netType.value = 3;
blueteethBindController.updateAll();
TopSlideNotification.show(
context,
@@ -945,6 +1117,7 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
textColor: themeController.currentColor.sc9,
);
FlutterBluePlus.stopScan();
blueteethBindController.updateAll();
}
});
@@ -971,34 +1144,76 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
isConnected = true;
_timeoutTimer?.cancel();
_scanSubscription?.cancel();
var streamlog;
try {
THapp bledevice = THapp(device: targetDevice.device);
await bledevice.device.connect();
var res2 = bledevice.isConnected;
THapp bledevice = THapp(device: targetDevice!.device);
if (res2 && !_isDisposed) {
blueteethBindController.currentDevice = bledevice;
streamlog = blueteethBindController.currentDevice!.logingStream
.listen((log) {
ef.log("[传感器设备日志]: $log");
edm.EasyDartModule.logger.info("[传感器设备日志]: $log");
});
bledevice.autoConnect = true;
const int maxRetry = 3;
int retryCount = 0;
bool connected = false;
while (retryCount < maxRetry && !_isDisposed) {
try {
await bledevice.device.connect();
connected = bledevice.isConnected;
if (connected) break;
} catch (e) {
retryCount++;
print("[蓝牙连接错误] 第${retryCount}次重试: $e");
edm.EasyDartModule.logger
.info("[蓝牙连接错误] 第${retryCount}次重试: $e");
DailyLogUtils.writeLog("[蓝牙连接错误] 第${retryCount}次重试: $e");
// 延迟重试
await Future.delayed(const Duration(seconds: 2));
}
}
if (connected && !_isDisposed) {
blueteethBindController.blueConnectFlag.value = 2;
TopSlideNotification.show(
context,
text: "连接成功".tr,
textColor: themeController.currentColor.sc2,
);
blueteethBindController.currentDevice = bledevice;
lisObj = blueteethBindController.currentDevice!.statusStream
.listen((onData) async {
// TopSlideNotification.show(
// context,
// text: "蓝牙连接成功".tr,
// textColor: themeController.currentColor.sc2,
// );
lisObj = bledevice.statusStream.listen((onData) async {
if (_isDisposed) return;
if (onData.status == BleEventType.recvLineLog) {
final line = onData.val;
print("[bleee]:" + line);
edm.EasyDartModule.logger.info("[bleee]:" + line);
DailyLogUtils.writeLog("[bleee]:" + line);
print("[bleee]: $line");
edm.EasyDartModule.logger.info("[bleee]: $line");
DailyLogUtils.writeLog("[bleee]: $line");
}
// 添加连接状态监听
if (onData.status == BleEventType.disconnected) {
print("蓝牙连接已断开");
blueteethBindController.blueConnectFlag.value = 1;
blueteethBindController.updateAll();
// 显示断开提示
// if (!_isDisposed) {
// TopSlideNotification.show(
// context,
// text: "蓝牙连接已断开,请重新连接".tr,
// textColor: themeController.currentColor.sc9,
// );
// }
_autoReconnect();
}
if (onData.status == BleEventType.ready) {
var aa = await getDeviceNetVersion(
blueteethBindController.currentDevice!, 0);
var aa = await getDeviceNetVersion(bledevice, 0);
if (aa == "4g") {
blueteethBindController.netType.value = 2;
blueteethBindController.updateAll();
@@ -1025,23 +1240,27 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
blueteethBindController.updateAll();
blueteethBindController.wifiConnectStatus.value = 0;
blueteethBindController.updateAll();
await initWifiStatusAndWifiList();
await initWifiStatusAndWifiList(needSuccess: needSuccess);
}
dealing = false;
}
});
} else {
TopSlideNotification.show(
context,
text: "蓝牙绑定.连接失败".tr,
text: "设备连接失败,请点击刷新重试".tr,
textColor: themeController.currentColor.sc9,
);
}
} catch (e) {
blueteethBindController.blueConnectFlag.value = 1;
TopSlideNotification.show(
context,
text: "设备连接失败".tr,
text: "设备连接失败,请点击刷新重试".tr,
textColor: themeController.currentColor.sc9,
);
} finally {
streamlog.close();
}
}
});
@@ -1054,10 +1273,12 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
text: "扫描过程中发生错误".tr,
textColor: themeController.currentColor.sc9,
);
dealing = false;
}
} finally {
_timeoutTimer?.cancel();
await FlutterBluePlus.stopScan();
dealing = false;
}
}
@@ -1123,11 +1344,73 @@ class _MHTWifiPageState extends State<MHTWifiPage> {
Future<void> _disconnectDevice() async {
try {
THapp bledevice = THapp(device: widget.deviceInfo.scanResult.device);
await bledevice.disconnect();
if (blueteethBindController.currentDevice != null) {
await blueteethBindController.currentDevice!.disconnect();
// blueteethBindController.currentDevice = null;
}
DailyLogUtils.writeLog("关闭蓝牙连接成功".tr);
} catch (e) {
DailyLogUtils.writeError("关闭蓝牙连接失败: $e");
} finally {
// dealing = false;
}
}
Future restoreWifi(THapp tHapp, aa) async {
if (aa != null && aa is Map) {
return aa;
}
await sendCloseAndOpenWscanCommand(tHapp);
return await getDeviceWifiStatus(blueteethBindController.currentDevice!, 4,
link: true);
}
Future rebootDeviceCurrent(THapp tHapp, aa) async {
if (aa != null && aa is Map) {
return aa;
}
await rebootDevice(
blueteethBindController.currentDevice!,
);
await dealWifi(
widget.deviceInfo.macA,
);
return await getDeviceWifiStatus(blueteethBindController.currentDevice!, 1,
link: true);
}
int _retryCount = 0;
final int _maxRetry = 3;
Future<void> _autoReconnect() async {
if (blueteethBindController.currentDevice == null) return;
while (_retryCount < _maxRetry) {
try {
print("[蓝牙重连] 第${_retryCount + 1}次尝试连接...");
await blueteethBindController.currentDevice!.connect();
// 检查是否连接成功
var isConnected =
await blueteethBindController.currentDevice!.isConnected;
if (isConnected) {
print("[蓝牙重连] 连接成功 ✅");
_retryCount = 0; // 重置重试次数
return;
} else {
throw Exception("连接失败");
}
} catch (e) {
_retryCount++;
print("[蓝牙重连] 第$_retryCount次连接失败$e");
if (_retryCount >= _maxRetry) {
print("[蓝牙重连] 已达到最大重试次数($_maxRetry),停止重连 ❌");
break;
}
// 等待 2 秒后重试
await Future.delayed(Duration(seconds: 2));
}
}
}
}

View File

@@ -44,6 +44,9 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
StreamSubscription<List<ScanResult>>? _scanSubscription;
bool _isDisposed = false;
ScanResult? targetDevice;
bool dealing = false; //是否正在刷新
DateTime _lastTapTime = DateTime.now();
bool haveSuccess = false;
@override
void initState() {
@@ -55,6 +58,7 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
}
void _initController() {
dealing = false;
blueteethBindController.netType.value = 0;
blueteethBindController.connectStatus.value = 0;
blueteethBindController.wifiList = [].obs;
@@ -71,11 +75,11 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
void dispose() {
_isDisposed = true;
_cleanupResources();
_disconnectDevice();
// _disconnectDevice();
super.dispose();
}
void _cleanupResources() {
Future<void> _cleanupResources() async {
// 取消监听器
lisObj?.cancel();
lisObj = null;
@@ -88,12 +92,7 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
_scanSubscription?.cancel();
_scanSubscription = null;
// 断开蓝牙连接
if (blueteethBindController.currentDevice != null) {
blueteethBindController.currentDevice!.disconnect();
blueteethBindController.currentDevice = null;
}
await _disconnectDevice();
// 停止扫描
FlutterBluePlus.stopScan();
}
@@ -183,7 +182,7 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
themeController.currentColor.sc1,
Colors.white,
),
),
);
@@ -196,7 +195,7 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
themeController.currentColor.sc1,
Colors.white,
),
),
);
@@ -526,12 +525,13 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
wifiItem['ssid'] ??
'未命名'.tr,
onConfirm: () async {
blueteethBindController
.currentDevice!
.logingStream
.listen((event) {
ef.log("[命令日志]:$event");
});
// blueteethBindController
// .currentDevice!
// .logingStream
// .listen((event) {
// ef.log("[命令日志]:$event");
// });
haveSuccess = false;
blueteethBindController
.selectWifi
.value = wifiItem;
@@ -541,11 +541,53 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
.model.wifiPass!,
blueteethBindController
.currentDevice!);
//todo 查询内存如果关键内存小于20000k重启设备
bool memoryFlag =
await queryMemory(
blueteethBindController
.currentDevice!);
if (!memoryFlag) {
await rebootDevice(
blueteethBindController
.currentDevice!);
await dealWifi(
widget.deviceInfo
.value[
'bind_mac_a'],
needSuccess: true);
// return;
}
if (!flag) {
blueteethBindController
.selectWifi
.value = {};
// TopSlideNotification.show(
// context,
// textColor:
// themeController
// .currentColor
// .sc9,
// text:
// '蓝牙已断开,请点击下方刷新按钮重试'
// .tr);
return;
}
if (flag) {
var aa = await getDeviceWifiStatus(
blueteethBindController
.currentDevice!,
1,link: true);
1,
link: true);
aa = await restoreWifi(
blueteethBindController
.currentDevice!,
aa);
if (!memoryFlag) {
aa = await rebootDeviceCurrent(
blueteethBindController
.currentDevice!,
aa);
}
blueteethBindController
.selectWifi
.value = {};
@@ -558,6 +600,10 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
blueteethBindController
.connect_wifi
.value = {};
blueteethBindController
.wifiStatus
.value ==
0;
}
blueteethBindController
.wifiStatus
@@ -572,19 +618,28 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
blueteethBindController
.currentDeviceMac!
.value);
TopSlideNotification
.show(
context,
text: "配网成功".tr,
textColor:
themeController
.currentColor
.sc2,
);
if (!haveSuccess) {
TopSlideNotification
.show(
context,
text: "配网成功".tr,
textColor:
themeController
.currentColor
.sc2,
);
}
} else {
//读取不到wifi信息
blueteethBindController
.connect_wifi
.value = {};
blueteethBindController
.selectWifi
.value = {};
blueteethBindController
.wifiStatus
.value = 0;
TopSlideNotification
.show(
context,
@@ -599,6 +654,11 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
blueteethBindController
.connect_wifi
.value = {};
blueteethBindController
.selectWifi
.value = {};
blueteethBindController
.wifiStatus.value = 0;
TopSlideNotification.show(
context,
text: "配网失败".tr,
@@ -639,9 +699,7 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
valueColor:
AlwaysStoppedAnimation<
Color>(
themeController
.currentColor
.sc1,
Colors.white,
),
),
)
@@ -662,6 +720,20 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
horizontal: 20.rpx, vertical: 10.rpx),
borderRadius: 20.rpx,
onTap: () async {
// if (dealing) {
// return;
// }
if (DateTime.now()
.difference(_lastTapTime) <
Duration(seconds: 2)) {
return; // 防止快速重复点击
}
_lastTapTime = DateTime.now();
blueteethBindController.netType.value = 0;
blueteethBindController
.blueConnectFlag.value = 0;
blueteethBindController.wifiList.value =
[];
var bluetoothState =
await FlutterBluePlus.isOn;
blueteethBindController.bluetoothStatus
@@ -678,10 +750,17 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
1) {
blueteethBindController
.blueConnectFlag.value = 0;
dealWifi(widget.deviceInfo.macA)
.then((aa) {
print("object");
});
try {
await dealWifi(
widget
.deviceInfo['bind_mac_a'],
needTip: false)
.then((aa) {
print("object");
});
} catch (e) {
ef.log("$e");
}
return;
}
@@ -730,6 +809,7 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
.currentColor.sc9,
);
});
await initWifiStatusAndWifiList();
} else {
blueteethBindController.netType.value =
1;
@@ -782,35 +862,54 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
);
}
Future<void> initWifiStatusAndWifiList() async {
Future<void> initWifiStatusAndWifiList(
{int retryCount = 0, bool needSuccess = false}) async {
if (_isDisposed) return;
// 取消之前的监听器
if (lisObj != null) {
lisObj!.cancel();
lisObj = null;
}
bool wifiStatus = false;
var aa =
await getDeviceWifiStatus(blueteethBindController.currentDevice!, 0);
if (aa != null && aa is Map) {
updateDeviceBindStatus(blueteethBindController.currentDeviceMac!.value);
wifiStatus = true;
blueteethBindController.connect_wifi.value = aa;
} else {
wifiStatus = false;
try {
// 获取WiFi状态
var aa =
await getDeviceWifiStatus(blueteethBindController.currentDevice!, 0);
if (aa != null && aa is Map) {
updateDeviceBindStatus(blueteethBindController.currentDeviceMac!.value);
wifiStatus = true;
blueteethBindController.connect_wifi.value = aa;
if (needSuccess) {
haveSuccess = true;
TopSlideNotification.show(
context,
text: "配网成功".tr,
textColor: themeController.currentColor.sc2,
);
}
} else {
wifiStatus = false;
}
blueteethBindController.wifiStatus.value = wifiStatus ? 1 : 0;
} catch (e) {
print("获取WiFi状态异常: $e");
blueteethBindController.wifiStatus.value = 0;
}
blueteethBindController.wifiStatus.value = wifiStatus ? 1 : 0;
List wifiList = [];
try {
// 获取WiFi列表
final result = await getWifiList(blueteethBindController.currentDevice!);
blueteethBindController.wifiConnectStatus.value = 1;
blueteethBindController.updateAll();
if (result is List) {
wifiList = result;
}
} catch (e) {
print("异常: $e");
print("获取WiFi列表异常: $e");
blueteethBindController.wifiConnectStatus.value = 0;
blueteethBindController.updateAll();
}
@@ -818,32 +917,87 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
if (_isDisposed) return;
if (wifiList.isNotEmpty) {
// 成功获取WiFi列表
blueteethBindController.connectStatus.value = 1;
blueteethBindController.updateAll();
TopSlideNotification.show(
context,
text: "获取wifi列表成功".tr,
textColor: themeController.currentColor.sc2,
);
// TopSlideNotification.show(
// context,
// text: "获取wifi列表成功".tr,
// textColor: themeController.currentColor.sc2,
// );
blueteethBindController.wifiList.value = wifiList;
blueteethBindController.updateAll();
} else {
// 获取WiFi列表失败尝试重新扫描
if (retryCount < 2) {
// 最多重试2次
print("${retryCount + 1}次获取WiFi列表失败尝试重新扫描...");
// TopSlideNotification.show(
// context,
// text: "正在重新扫描WiFi...".tr,
// textColor: themeController.currentColor.sc2,
// );
try {
// 发送关闭并重新打开WiFi扫描命令
await sendCloseAndOpenWscanCommand(
blueteethBindController.currentDevice!);
// 等待一段时间让设备重新扫描
await Future.delayed(Duration(seconds: 3));
// 递归调用自身进行重试
await initWifiStatusAndWifiList(retryCount: retryCount + 1);
return; // 重试后直接返回,避免执行后面的代码
} catch (e) {
print("重新扫描WiFi失败: $e");
// 继续执行下面的失败处理
}
}
// 重试次数用尽或重试失败,显示最终失败提示
TopSlideNotification.show(
context,
text: "获取wifi列表失败".tr,
textColor: themeController.currentColor.sc9,
);
// 可选重置WiFi连接状态
blueteethBindController.connectStatus.value = 0;
blueteethBindController.updateAll();
}
lisObj = blueteethBindController.currentDevice!.statusStream
.listen((onData) async {
if (onData.status == BleEventType.recvLineLog) {
final line = onData.val;
print("[bleee]:" + line);
edm.EasyDartModule.logger.info("[bleee]:" + line);
DailyLogUtils.writeLog("[bleee]:" + line);
}
});
// 设置日志监听器
if (!_isDisposed && blueteethBindController.currentDevice != null) {
lisObj = blueteethBindController.currentDevice!.statusStream
.listen((onData) async {
if (_isDisposed) return;
if (onData.status == BleEventType.recvLineLog) {
final line = onData.val;
print("[bleee]: $line");
edm.EasyDartModule.logger.info("[bleee]: $line");
DailyLogUtils.writeLog("[bleee]: $line");
}
// 添加连接状态监听
if (onData.status == BleEventType.disconnected) {
print("蓝牙连接已断开");
blueteethBindController.blueConnectFlag.value = 1;
blueteethBindController.updateAll();
// 显示断开提示
// if (!_isDisposed) {
// TopSlideNotification.show(
// context,
// text: "蓝牙连接已断开,请重新连接".tr,
// textColor: themeController.currentColor.sc9,
// );
// }
_autoReconnect();
}
});
}
}
Widget getWifiIconByRsso(wifiItem) {
@@ -894,16 +1048,20 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
}
}
Future<void> dealWifi(String mac) async {
if (_isDisposed) return;
final blueteethBindController = Get.find<BlueteethBindController>();
final themeController = Get.find<ThemeController>();
// 清理之前的资源
_cleanupResources();
Future<void> dealWifi(String mac,
{bool needTip = true, bool needSuccess = false}) async {
if (dealing) {
return;
}
try {
dealing = true;
if (_isDisposed) return;
final blueteethBindController = Get.find<BlueteethBindController>();
final themeController = Get.find<ThemeController>();
// 清理之前的资源
await _cleanupResources();
// 检查蓝牙状态
var bluetoothState = await FlutterBluePlus.isOn;
blueteethBindController.bluetoothStatus.value = bluetoothState;
@@ -922,13 +1080,14 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
_timeoutTimer = Timer(Duration(seconds: 20), () {
if (!isConnected && !_isDisposed) {
blueteethBindController.blueConnectFlag.value = 1;
blueteethBindController.updateAll();
blueteethBindController.netType.value = 3;
TopSlideNotification.show(
context,
text: "设备连接超时,请重试".tr,
text: "设备连接超时,请点击刷新重试".tr,
textColor: themeController.currentColor.sc9,
);
FlutterBluePlus.stopScan();
blueteethBindController.updateAll();
}
});
@@ -954,33 +1113,76 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
_timeoutTimer?.cancel();
_scanSubscription?.cancel();
var streamlog;
try {
THapp bledevice = THapp(device: targetDevice!.device);
await bledevice.device.connect();
var res2 = bledevice.isConnected;
blueteethBindController.currentDevice = bledevice;
streamlog = blueteethBindController.currentDevice!.logingStream
.listen((log) {
ef.log("[传感器设备日志]: $log");
edm.EasyDartModule.logger.info("[传感器设备日志]: $log");
});
bledevice.autoConnect = true;
if (res2 && !_isDisposed) {
const int maxRetry = 3;
int retryCount = 0;
bool connected = false;
while (retryCount < maxRetry && !_isDisposed) {
try {
await bledevice.device.connect();
connected = bledevice.isConnected;
if (connected) break;
} catch (e) {
retryCount++;
print("[蓝牙连接错误] 第${retryCount}次重试: $e");
edm.EasyDartModule.logger
.info("[蓝牙连接错误] 第${retryCount}次重试: $e");
DailyLogUtils.writeLog("[蓝牙连接错误] 第${retryCount}次重试: $e");
// 延迟重试
await Future.delayed(const Duration(seconds: 2));
}
}
if (connected && !_isDisposed) {
blueteethBindController.blueConnectFlag.value = 2;
TopSlideNotification.show(
context,
text: "连接成功".tr,
textColor: themeController.currentColor.sc2,
);
blueteethBindController.currentDevice = bledevice;
lisObj = blueteethBindController.currentDevice!.statusStream
.listen((onData) async {
// TopSlideNotification.show(
// context,
// text: "蓝牙连接成功".tr,
// textColor: themeController.currentColor.sc2,
// );
lisObj = bledevice.statusStream.listen((onData) async {
if (_isDisposed) return;
if (onData.status == BleEventType.recvLineLog) {
final line = onData.val;
print("[bleee]:" + line);
edm.EasyDartModule.logger.info("[bleee]:" + line);
DailyLogUtils.writeLog("[bleee]:" + line);
print("[bleee]: $line");
edm.EasyDartModule.logger.info("[bleee]: $line");
DailyLogUtils.writeLog("[bleee]: $line");
}
// 添加连接状态监听
if (onData.status == BleEventType.disconnected) {
print("蓝牙连接已断开");
blueteethBindController.blueConnectFlag.value = 1;
blueteethBindController.updateAll();
// 显示断开提示
// if (!_isDisposed) {
// TopSlideNotification.show(
// context,
// text: "蓝牙连接已断开,请重新连接".tr,
// textColor: themeController.currentColor.sc9,
// );
// }
_autoReconnect();
}
if (onData.status == BleEventType.ready) {
var aa = await getDeviceNetVersion(
blueteethBindController.currentDevice!, 0);
var aa = await getDeviceNetVersion(bledevice, 0);
if (aa == "4g") {
blueteethBindController.netType.value = 2;
blueteethBindController.updateAll();
@@ -1007,27 +1209,30 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
blueteethBindController.updateAll();
blueteethBindController.wifiConnectStatus.value = 0;
blueteethBindController.updateAll();
await initWifiStatusAndWifiList();
await initWifiStatusAndWifiList(needSuccess: needSuccess);
}
dealing = false;
}
});
} else {
TopSlideNotification.show(
context,
text: "蓝牙绑定.连接失败".tr,
text: "设备连接失败,请点击刷新重试".tr,
textColor: themeController.currentColor.sc9,
);
}
} catch (e) {
blueteethBindController.blueConnectFlag.value = 1;
TopSlideNotification.show(
context,
text: "设备连接失败".tr,
text: "设备连接失败,请点击刷新重试".tr,
textColor: themeController.currentColor.sc9,
);
} finally {
streamlog.close();
}
}
});
await Future.delayed(Duration(seconds: 20));
} catch (e) {
if (!_isDisposed) {
@@ -1036,10 +1241,12 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
text: "扫描过程中发生错误".tr,
textColor: themeController.currentColor.sc9,
);
dealing = false;
}
} finally {
_timeoutTimer?.cancel();
await FlutterBluePlus.stopScan();
dealing = false;
}
}
@@ -1105,12 +1312,74 @@ class _MHTWifiAfterPageState extends State<MHTWifiAfterPage> {
Future<void> _disconnectDevice() async {
try {
// THapp bledevice = THapp(device: widget.deviceInfo.scanResult.device);
THapp bledevice = THapp(device: targetDevice!.device);
await bledevice.disconnect();
if (blueteethBindController.currentDevice != null) {
await blueteethBindController.currentDevice!.disconnect();
// blueteethBindController.currentDevice = null;
}
DailyLogUtils.writeLog("关闭蓝牙连接成功".tr);
} catch (e) {
DailyLogUtils.writeError("关闭蓝牙连接失败: $e");
} finally {
// dealing = false;
}
}
Future restoreWifi(THapp tHapp, aa) async {
if (aa != null && aa is Map) {
return aa;
}
await sendCloseAndOpenWscanCommand(tHapp);
return await getDeviceWifiStatus(blueteethBindController.currentDevice!, 4,
link: true);
}
Future rebootDeviceCurrent(THapp tHapp, aa) async {
if (aa != null && aa is Map) {
return aa;
}
blueteethBindController.connect_wifi.value = {};
await rebootDevice(
blueteethBindController.currentDevice!,
);
await dealWifi(
widget.deviceInfo['bind_mac_a'],
);
return await getDeviceWifiStatus(blueteethBindController.currentDevice!, 1,
link: true);
}
int _retryCount = 0;
final int _maxRetry = 3;
Future<void> _autoReconnect() async {
if (blueteethBindController.currentDevice == null) return;
while (_retryCount < _maxRetry) {
try {
print("[蓝牙重连] 第${_retryCount + 1}次尝试连接...");
await blueteethBindController.currentDevice!.connect();
// 检查是否连接成功
var isConnected =
await blueteethBindController.currentDevice!.isConnected;
if (isConnected) {
print("[蓝牙重连] 连接成功 ✅");
_retryCount = 0; // 重置重试次数
return;
} else {
throw Exception("连接失败");
}
} catch (e) {
_retryCount++;
print("[蓝牙重连] 第$_retryCount次连接失败$e");
if (_retryCount >= _maxRetry) {
print("[蓝牙重连] 已达到最大重试次数($_maxRetry),停止重连 ❌");
break;
}
// 等待 2 秒后重试
await Future.delayed(Duration(seconds: 2));
}
}
}
}

View File

@@ -253,7 +253,7 @@ class _SettingPageState extends State<SettingPage> {
),
].divide(SizedBox(width: 22.rpx)),
),
Text('SWES2025.9.8',
Text('SWES2025.10.28',
style: TextStyle(
color: Colors.white,
fontSize: 26.rpx,