Files
tuiche/lib/pages/device_bind/wifi_page.dart
2025-11-13 09:56:02 +08:00

1694 lines
78 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:async';
import 'package:easydevice/easydevice.dart';
import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:vbvs_app/common/color/ServiceConstant.dart';
import 'package:vbvs_app/common/color/appConstants.dart';
import 'package:vbvs_app/common/util/DailyLogUtils.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
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/component/tool/cmd.dart';
import 'package:vbvs_app/controller/device/blueteeth_bind_controller.dart';
import 'package:vbvs_app/controller/main_bottom/global_controller.dart';
import 'package:vbvs_app/controller/person/person_controller.dart';
import 'package:vbvs_app/controller/theme_controller/ThemeController.dart';
import 'package:vbvs_app/controller/user_info_controller.dart';
import 'package:vbvs_app/model/BleDeviceData.dart';
import 'package:vbvs_app/pages/device_bind/blueteeth_device_page.dart';
import 'package:vbvs_app/pages/device_bind/componnet/bind_dialog.dart';
import 'package:EasyDartModule/EasyDartModule.dart' as edm;
class WifiPage extends StatefulWidget {
var type; //为空,首次绑定 不为空,从设备列表进入
WifiPage({super.key, required this.type});
@override
State<WifiPage> createState() => _WifiPageState();
}
class _WifiPageState extends State<WifiPage> {
GlobalController globalController = Get.find();
UserInfoController userInfoController = Get.find();
BlueteethBindController blueteethBindController = Get.find();
PersonController personController = Get.find();
ThemeController themeController = Get.find();
var lisObj;
bool haveSuccess = false;
bool dealing = false; //是否正在刷新
bool _isDisposed = false;
Timer? _timeoutTimer;
StreamSubscription<List<ScanResult>>? _scanSubscription;
ScanResult? targetDevice;
DateTime _lastTapTime = DateTime.now();
@override
void initState() {
super.initState();
blueteethBindController.netType.value = 0;
blueteethBindController.connectStatus.value = 0;
blueteethBindController.wifiList = [].obs;
blueteethBindController.wifiStatus = 0.obs;
blueteethBindController.connect_wifi.value = {};
blueteethBindController.selectWifi.value = {};
THapp bledevice = blueteethBindController.currentDevice!;
bledevice.device.connect().then((Value) {
var res2 = bledevice.isConnected;
if (res2) {
blueteethBindController.blueConnectFlag.value = 2;
blueteethBindController.currentDevice = bledevice;
if (lisObj != null) {
lisObj!.cancel();
}
var aa;
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 (onData.status == BleEventType.ready) {
aa = await getDeviceNetVersion(
blueteethBindController.currentDevice!, 2);
if (aa == "4g") {
TopSlideNotification.show(
context,
text: "4g设备配置wifi提示".tr,
textColor: themeController.currentColor.sc2,
);
blueteethBindController.netType.value = 2;
blueteethBindController.connectStatus.value = 1;
blueteethBindController.updateAll();
updateDeviceBindStatus(
blueteethBindController.currentDeviceMac!.value);
Future.delayed(const Duration(seconds: 1), () {
Get.toNamed("/calibrationPage", arguments: 1);
});
} else if (aa == 'unknown') {
blueteethBindController.netType.value = 3;
blueteethBindController.updateAll();
WidgetsBinding.instance.addPostFrameCallback((_) {
TopSlideNotification.show(
context,
text: "获取设备网络类型失败".tr,
textColor: themeController.currentColor.sc9,
);
});
} else {
blueteethBindController.netType.value = 1;
blueteethBindController.updateAll();
await initWifiStatusAndWifiList();
}
}
});
} else {
WidgetsBinding.instance.addPostFrameCallback((_) {
TopSlideNotification.show(
context,
text: "连接失败".tr,
textColor: themeController.currentColor.sc9,
);
});
}
});
}
// @override
// void dispose() {
// super.dispose();
// if (lisObj != null) {
// lisObj.cancel();
// }
// blueteethBindController.currentDevice!.disconnect();
// }
@override
void dispose() {
_isDisposed = true;
_cleanupResources();
// _disconnectDevice();
super.dispose();
}
@override
Widget build(BuildContext context) {
print("object");
return LayoutBuilder(
builder: (context, bodySize) => GestureDetector(
// onTap: () => FocusScope.of(context).unfocus(),,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/img/bgNoImg.png'), // 本地图片
fit: BoxFit.fill, // 填满整个 Container
),
),
child: Scaffold(
backgroundColor: Colors.transparent, // 加上这一行
appBar: AppBar(
backgroundColor: themeController.currentColor.sc17,
automaticallyImplyLeading: false,
iconTheme: IconThemeData(color: themeController.currentColor.sc3),
titleSpacing: 0,
// leading: returnIconButtom,
title: Container(
width: double.infinity,
height: 180.rpx,
child: Stack(
alignment: Alignment.center,
children: [
/// 居中标题
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'wifi页.标题'.tr,
style: TextStyle(
fontFamily: 'Readex Pro',
color: themeController.currentColor.sc3,
letterSpacing: 0,
fontSize: 30.rpx,
),
),
SizedBox(
width: 14.rpx,
),
if (widget.type == null)
Obx(() {
if (blueteethBindController.netType.value == 0) {
return SizedBox(
width: 24.rpx,
height: 24.rpx,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
themeController.currentColor.sc3,
),
),
);
}
if (blueteethBindController.connectStatus.value ==
0 &&
blueteethBindController.netType.value != 0) {
return SizedBox(
width: 24.rpx,
height: 24.rpx,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
themeController.currentColor.sc3,
),
),
);
}
return Container();
}),
],
),
/// 左边返回按钮
Positioned(
left: 0,
child: returnIconButtom,
),
if (widget.type == null)
Positioned(
right: 20.rpx,
child: CustomCard(
borderRadius: 20.rpx,
onTap: () async {
if (blueteethBindController.wifiStatus.value != 1) {
showConfirmDialog(
context, Container(), "未配置网络提示".tr,
onConfirm: () {
Get.toNamed("/calibrationPage", arguments: 1);
}, onCancel: () {});
} else {
Get.toNamed("/calibrationPage", arguments: 1);
}
},
colors: [
themeController.currentColor.sc1,
themeController.currentColor.sc2,
],
child: Container(
width: 140.rpx,
height: 60.rpx,
alignment: Alignment.center,
padding: EdgeInsetsDirectional.fromSTEB(
16.rpx, 0, 16.rpx, 0),
child: Text(
'下一步'.tr,
style: TextStyle(
fontFamily: 'Inter Tight',
color: themeController.currentColor.sc3,
letterSpacing: 0.0,
),
),
),
),
),
],
),
),
actions: [],
centerTitle: false,
),
body: SafeArea(
top: true,
child: Padding(
padding: EdgeInsetsDirectional.fromSTEB(30.rpx, 0, 30.rpx, 0),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Padding(
padding:
EdgeInsetsDirectional.fromSTEB(0, 30.rpx, 0, 0),
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Color(0xFF242835),
borderRadius: BorderRadius.circular(20.rpx),
),
child: Column(
children: [
Align(
alignment: AlignmentDirectional(0, 0),
child: Padding(
padding: EdgeInsetsDirectional.fromSTEB(
30.rpx, 30.rpx, 30.rpx, 30.rpx),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
"wifi页.WLAN".tr,
style: TextStyle(
color: themeController
.currentColor.sc3,
fontSize: AppConstants()
.title_text_fontSize,
),
),
Obx(() {
return Text(
blueteethBindController
.wifiStatus.value ==
0
? "wifi页.未连接".tr
: "wifi页.已连接".tr,
style: TextStyle(
color: blueteethBindController
.wifiStatus.value ==
0
? themeController
.currentColor.sc4
: themeController
.currentColor.sc2,
fontSize: AppConstants()
.normal_text_fontSize,
),
);
}),
],
),
),
),
Obx(() {
if (blueteethBindController
.connect_wifi.value ==
null ||
blueteethBindController
.connect_wifi.value.isEmpty) {
return Container();
} else {
return Padding(
padding: EdgeInsetsDirectional.fromSTEB(
30.rpx, 0.rpx, 30.rpx, 30.rpx),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
blueteethBindController.connect_wifi
.value['ssid'] ??
'未命名'.tr,
style: TextStyle(
color: themeController
.currentColor.sc3,
fontSize: AppConstants()
.title_text_fontSize,
),
),
getWifiIconByRsso(
blueteethBindController
.connect_wifi.value),
],
),
);
}
})
],
)),
),
Padding(
padding: EdgeInsetsDirectional.fromSTEB(
0.rpx, 25.rpx, 0.rpx, 0.rpx),
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: themeController.currentColor.sc5,
borderRadius: BorderRadius.circular(20.rpx),
),
child: Padding(
padding: EdgeInsetsDirectional.fromSTEB(
30.rpx, 30.rpx, 30.rpx, 30.rpx),
child: Container(
width: double.infinity,
decoration: BoxDecoration(),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Row(
mainAxisSize: MainAxisSize.max,
children: [
Text(
'可用WLAN'.tr,
style: TextStyle(
fontFamily: 'Inter',
fontSize: 30.rpx,
letterSpacing: 0.0,
color:
themeController.currentColor.sc3,
),
),
],
),
Obx(() {
final sortedList = [
...blueteethBindController.wifiList.value
]..sort((a, b) => b['rssi']
.compareTo(a['rssi'])); // 按 rssi 倒序
return Column(
mainAxisSize: MainAxisSize.max,
children: sortedList
.map((wifiItem) => ClickableContainer(
backgroundColor:
Colors.transparent,
highlightColor: themeController
.currentColor.sc3,
padding: EdgeInsets.symmetric(
vertical: 0.rpx,
horizontal: 0.rpx),
borderRadius: 16.rpx,
onTap: () {
showWifiDialog(
context,
Padding(
padding:
EdgeInsetsDirectional
.fromSTEB(
0.rpx,
41.rpx,
0.rpx,
0),
child: Container(
height: 80.rpx,
decoration:
BoxDecoration(
color: Colors.white,
borderRadius:
BorderRadius
.circular(12
.rpx), // 加圆角
),
child: Align(
alignment:
AlignmentDirectional(
-1, 0),
child: Obx(() {
return TextFormField(
onChanged:
(value) {
blueteethBindController
.model
.wifiPass =
value;
},
autofocus:
false,
obscureText:
blueteethBindController
.model
.wifiPassShow,
decoration:
InputDecoration(
isDense:
true,
labelStyle:
TextStyle(
fontFamily:
'Inter',
fontSize:
26.rpx,
letterSpacing:
0.0,
),
hintText:
'蓝牙绑定.输入wifi密码'
.tr,
hintStyle: TextStyle(
fontFamily:
'Inter',
fontSize: 26
.rpx,
letterSpacing:
0.0,
color: themeController
.currentColor
.sc4),
enabledBorder:
OutlineInputBorder(
borderSide:
BorderSide(
color: Color(
0x00000000),
width: 1
.rpx,
),
borderRadius:
BorderRadius.circular(
8.rpx),
),
focusedBorder:
OutlineInputBorder(
borderSide:
BorderSide(
color: Color(
0x00000000),
width: 1
.rpx,
),
borderRadius:
BorderRadius.circular(
8.rpx),
),
errorBorder:
OutlineInputBorder(
borderSide:
BorderSide(
width: 1
.rpx,
),
borderRadius:
BorderRadius.circular(
8.rpx),
),
focusedErrorBorder:
OutlineInputBorder(
borderSide:
BorderSide(
width: 1
.rpx,
),
borderRadius:
BorderRadius.circular(
8.rpx),
),
filled:
false,
fillColor:
Colors
.white,
suffixIcon:
InkWell(
onTap:
() {
blueteethBindController
.model
.wifiPassShow = !blueteethBindController.model.wifiPassShow;
blueteethBindController
.updateAll();
},
focusNode:
FocusNode(
skipTraversal: true),
child:
Icon(
blueteethBindController.model.wifiPassShow
? Icons.visibility_outlined
: Icons.visibility_off_outlined,
size: 30
.rpx,
),
),
),
style: TextStyle(
fontFamily:
'Inter',
fontSize: 26
.rpx,
letterSpacing:
0.0,
color: Colors
.black),
cursorColor:
themeController
.currentColor
.sc3,
);
})),
),
),
wifiItem['ssid'] ??
'未命名'.tr,
onConfirm: () async {
haveSuccess = false;
blueteethBindController
.selectWifi
.value = wifiItem;
bool flag = await sendWifiSetting(
wifiItem,
blueteethBindController
.model.wifiPass!,
blueteethBindController
.currentDevice!);
// Navigator.pop(context);
bool memoryFlag =
await queryMemory(
blueteethBindController
.currentDevice!);
if (!memoryFlag) {
await rebootDevice(
blueteethBindController
.currentDevice!);
await dealWifi(
blueteethBindController
.currentDeviceMac
.value,
needSuccess: true);
// return;
}
if (!flag) {
blueteethBindController
.selectWifi
.value = {};
return;
}
if (flag) {
var aa = await getDeviceWifiStatus(
blueteethBindController
.currentDevice!,
1,
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
.connect_wifi
.value = aa;
} else {
blueteethBindController
.connect_wifi
.value = {};
blueteethBindController
.wifiStatus
.value ==
0;
}
blueteethBindController
.wifiStatus
.value =
(aa != null &&
aa != false)
? 1
: 0;
if (aa != null &&
aa != false) {
updateDeviceBindStatus(
blueteethBindController
.currentDeviceMac!
.value);
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,
text: "配网失败".tr,
textColor:
themeController
.currentColor
.sc9,
);
}
} else {
blueteethBindController
.connect_wifi
.value = {};
blueteethBindController
.selectWifi
.value = {};
blueteethBindController
.wifiStatus.value = 0;
TopSlideNotification.show(
context,
text: "配网失败".tr,
textColor:
themeController
.currentColor
.sc9,
);
}
});
},
child: Row(
mainAxisSize:
MainAxisSize.max,
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
Text(
wifiItem['ssid'] ?? '',
style: TextStyle(
fontFamily: 'Inter',
fontSize: 30.rpx,
letterSpacing: 0.0,
color: themeController
.currentColor.sc3,
),
),
if (blueteethBindController
.selectWifi.value ==
wifiItem)
SizedBox(
width: 32.rpx,
height: 32.rpx,
child:
CircularProgressIndicator(
strokeWidth: 2,
valueColor:
AlwaysStoppedAnimation<
Color>(
themeController
.currentColor
.sc3,
),
),
)
else
getWifiIconByRsso(
wifiItem),
],
),
))
.toList()
.divide(SizedBox(height: 67.rpx)),
);
}),
ClickableContainer(
backgroundColor: Colors.transparent,
highlightColor: Colors.white,
padding: EdgeInsets.symmetric(
horizontal: 20.rpx, vertical: 10.rpx),
borderRadius: 20.rpx,
onTap: () async {
blueteethBindController
.connectStatus.value = 0;
blueteethBindController.updateAll();
print("点击刷新");
if (blueteethBindController
.netType.value ==
0) {
return;
}
if (blueteethBindController
.netType.value ==
3) {
var aa = await getDeviceNetVersion(
blueteethBindController
.currentDevice!,
0);
if (aa == "4g") {
TopSlideNotification.show(
context,
text: "4g设备配置wifi提示".tr,
textColor: themeController
.currentColor.sc2,
);
blueteethBindController
.netType.value = 2;
blueteethBindController
.connectStatus.value = 1;
blueteethBindController.updateAll();
updateDeviceBindStatus(
blueteethBindController
.currentDeviceMac!.value);
Future.delayed(
const Duration(seconds: 1), () {
Get.toNamed("/calibrationPage",
arguments: 1);
});
} else if (aa == 'unknown') {
// TopSlideNotification.show(
// context,
// text: "获取设备网络类型失败".tr,
// textColor: themeController.currentColor.sc9,
// );
blueteethBindController
.netType.value = 3;
blueteethBindController.updateAll();
WidgetsBinding.instance
.addPostFrameCallback((_) {
TopSlideNotification.show(
context,
text: "获取设备网络类型失败".tr,
textColor: themeController
.currentColor.sc9,
);
});
} else {
blueteethBindController
.netType.value = 1;
blueteethBindController.updateAll();
await initWifiStatusAndWifiList();
}
}
// await initWifiList();
// TopSlideNotification.show(
// context,
// text: "获取wifi列表成功".tr,
// textColor:
// themeController.currentColor.sc2,
// );
},
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Container(
width: 25.rpx,
height: 25.rpx,
decoration: BoxDecoration(),
child: SvgPicture.asset(
'assets/img/icon/refresh.svg',
fit: BoxFit.cover,
color: Colors.white, // 图标固定白色
),
),
Text(
'刷新'.tr,
style: TextStyle(
fontFamily: 'Inter',
fontSize: 30.rpx,
letterSpacing: 0.0,
color: themeController
.currentColor.sc3,
),
),
].divide(SizedBox(width: 26.rpx)),
),
),
].divide(SizedBox(height: 65.rpx)),
),
),
),
),
),
],
),
),
),
),
),
),
),
);
}
// Future<void> initWifiStatusAndWifiList() async {
// if (lisObj != null) {
// lisObj!.cancel();
// }
// bool wifiStatus = false;
// var aa =
// await getDeviceWifiStatus(blueteethBindController.currentDevice!, 1);
// if (aa != null && aa is Map) {
// wifiStatus = true;
// updateDeviceBindStatus(blueteethBindController.currentDeviceMac!.value);
// blueteethBindController.connect_wifi.value = aa;
// } else {
// wifiStatus = false;
// }
// blueteethBindController.wifiStatus.value = wifiStatus == true ? 1 : 0;
// List wifiList = [];
// try {
// final result = await getWifiList(blueteethBindController.currentDevice!);
// if (result is List) {
// wifiList = result;
// }
// } catch (e) {
// print("异常: $e");
// }
// if (wifiList.length > 0) {
// blueteethBindController.connectStatus.value = 1;
// blueteethBindController.updateAll();
// // Navigator.pop(context);
// TopSlideNotification.show(
// context,
// text: "获取wifi列表成功".tr,
// textColor: themeController.currentColor.sc2,
// );
// blueteethBindController.wifiList.value = wifiList;
// blueteethBindController.updateAll();
// } else {
// // Navigator.pop(context);
// TopSlideNotification.show(
// context,
// text: "获取wifi列表失败".tr,
// textColor: themeController.currentColor.sc9,
// );
// }
// 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 (onData.status == BleEventType.ready) {
// // // showLoadingDialog(context, title: "获取wifi列表中...".tr);
// // bool wifiStatus = false;
// // var aa = await getDeviceWifiStatus(
// // blueteethBindController.currentDevice!, 1);
// // if (aa != null && aa is Map) {
// // wifiStatus = true;
// // blueteethBindController.connect_wifi.value = aa;
// // }
// // blueteethBindController.wifiStatus.value = wifiStatus == true ? 1 : 0;
// // List wifiList = [];
// // try {
// // final result =
// // await getWifiList(blueteethBindController.currentDevice!);
// // if (result is List) {
// // wifiList = result;
// // }
// // } catch (e) {
// // print("异常: $e");
// // }
// // if (wifiList.length > 0) {
// // blueteethBindController.connectStatus.value = 1;
// // blueteethBindController.updateAll();
// // // Navigator.pop(context);
// // TopSlideNotification.show(
// // context,
// // text: "获取wifi列表成功".tr,
// // textColor: themeController.currentColor.sc2,
// // );
// // blueteethBindController.wifiList.value = wifiList;
// // blueteethBindController.updateAll();
// // } else {
// // Navigator.pop(context);
// // TopSlideNotification.show(
// // context,
// // text: "获取wifi列表失败".tr,
// // textColor: themeController.currentColor.sc9,
// // );
// // }
// // }
// });
// }
Future<void> initWifiStatusAndWifiList(
{int retryCount = 0, bool needSuccess = false}) async {
if (_isDisposed) return;
// 取消之前的监听器
if (lisObj != null) {
lisObj!.cancel();
lisObj = null;
}
bool 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;
if (needSuccess) {
haveSuccess = true;
TopSlideNotification.show(
context,
text: "配网失败".tr,
textColor: themeController.currentColor.sc9,
);
}
}
blueteethBindController.wifiStatus.value = wifiStatus ? 1 : 0;
} catch (e) {
print("获取WiFi状态异常: $e");
blueteethBindController.wifiStatus.value = 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("获取WiFi列表异常: $e");
blueteethBindController.wifiConnectStatus.value = 0;
blueteethBindController.updateAll();
}
if (_isDisposed) return;
if (wifiList.isNotEmpty) {
// 成功获取WiFi列表
blueteethBindController.connectStatus.value = 1;
blueteethBindController.updateAll();
// 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();
}
// 设置日志监听器
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();
}
});
}
}
initWifiList() async {
try {
var wifiList = await getWifiList(blueteethBindController.currentDevice!);
print(wifiList);
if (wifiList.length > 0) {
blueteethBindController.connectStatus.value = 1;
blueteethBindController.wifiList.value = wifiList;
blueteethBindController.updateAll();
}
return wifiList;
} catch (e) {
print(e);
TopSlideNotification.show(
context,
text: "获取wifi列表失败".tr,
textColor: themeController.currentColor.sc9,
);
}
}
getWifiIconByRsso(wifiItem) {
int? rssi = int.tryParse(wifiItem['rssi'].toString());
if (rssi != null) {
if (rssi >= AppConstants().wifi1) {
return Container(
width: 40.rpx,
height: 40.rpx,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(shape: BoxShape.circle),
child: Image.asset("assets/img/wifi4.png"),
);
} else if (rssi >= AppConstants().wifi2) {
return Container(
width: 40.rpx,
height: 40.rpx,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(shape: BoxShape.circle),
child: Image.asset("assets/img/wifi3.png"),
);
} else if (rssi >= AppConstants().wifi3) {
return Container(
width: 40.rpx,
height: 40.rpx,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(shape: BoxShape.circle),
child: Image.asset("assets/img/wifi3.png"),
);
} else {
return Container(
width: 40.rpx,
height: 40.rpx,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(shape: BoxShape.circle),
child: Image.asset("assets/img/wifi1.png"),
);
}
} else {
// RSSI 无法解析时的默认显示
return Container(
width: 40.rpx,
height: 40.rpx,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(shape: BoxShape.circle),
child: Image.asset("assets/img/wifi1.png"),
);
}
}
// Future<void> dealWifi(String mac) async {
// final blueteethBindController = Get.find<BlueteethBindController>();
// final themeController = Get.find<ThemeController>();
// // 显示加载对话框
// // showLoadingDialog(Get.context!, title: "连接中...".tr);
// // 设置超时定时器
// Timer? timeoutTimer;
// bool isConnected = false;
// try {
// // 开始扫描蓝牙设备
// await FlutterBluePlus.startScan(timeout: Duration(seconds: 10));
// // 设置超时20秒
// timeoutTimer = Timer(Duration(seconds: 20), () {
// try {
// if (!isConnected) {
// blueteethBindController.blueConnectFlag.value = 1;
// blueteethBindController.updateAll();
// // Navigator.of(context).pop(); // 先关闭 dialog
// WidgetsBinding.instance.addPostFrameCallback((_) {
// TopSlideNotification.show(
// context,
// text: "设备连接超时,请重试".tr,
// textColor: themeController.currentColor.sc9,
// );
// });
// FlutterBluePlus.stopScan();
// }
// } catch (e) {
// print(e);
// }
// });
// // 监听扫描结果
// StreamSubscription<List<ScanResult>>? scanSubscription;
// scanSubscription = FlutterBluePlus.scanResults.listen((results) async {
// // 过滤出符合条件的设备
// ScanResult? targetDevice;
// for (var r in results) {
// if (r.advertisementData.manufacturerData.containsKey(0xFFED)) {
// List<int> rawData = r.advertisementData.manufacturerData[0xFFED]!;
// BleDeviceData deviceData = parseBleData(rawData);
// String deviceMac =
// deviceData.deviceId.replaceAll(':', '').toLowerCase();
// if (deviceMac == mac.toLowerCase()) {
// targetDevice = r;
// break;
// }
// }
// }
// if (targetDevice != null && !isConnected) {
// isConnected = true;
// FlutterBluePlus.stopScan();
// scanSubscription?.cancel();
// timeoutTimer?.cancel();
// try {
// // 连接设备
// // await targetDevice.device.connect();
// THapp bledevice = THapp(device: targetDevice.device);
// await bledevice.device.connect();
// var res2 = bledevice.isConnected;
// if (res2) {
// // Navigator.pop(context);
// blueteethBindController.blueConnectFlag.value = 2;
// TopSlideNotification.show(
// context,
// text: "蓝牙绑定.连接成功".tr,
// textColor: themeController.currentColor.sc2,
// );
// blueteethBindController.currentDevice = bledevice;
// if (lisObj != null) {
// lisObj!.cancel();
// }
// var aa;
// lisObj = blueteethBindController.currentDevice!.statusStream
// .listen((onData) async {
// if (onData.status == BleEventType.recvLineLog) {
// final line = onData.val;
// print("[bleee]:" + line);
// }
// if (onData.status == BleEventType.ready) {
// aa = await getDeviceNetVersion(
// blueteethBindController.currentDevice!, 0);
// if (aa == "4g") {
// // TopSlideNotification.show(
// // Get.context!,
// // text: "4g设备配置wifi提示".tr,
// // textColor: themeController.currentColor.sc9,
// // );
// updateDeviceBindStatus(
// blueteethBindController.currentDeviceMac!.value);
// WidgetsBinding.instance.addPostFrameCallback((_) {
// TopSlideNotification.show(
// context,
// text: "4g设备配置wifi提示".tr,
// textColor: themeController.currentColor.sc9,
// );
// Get.back();
// });
// return;
// } else if (aa == 'unknown') {
// blueteethBindController.netType.value = 3;
// blueteethBindController.updateAll();
// WidgetsBinding.instance.addPostFrameCallback((_) {
// TopSlideNotification.show(
// context,
// text: "获取设备网络类型失败".tr,
// textColor: themeController.currentColor.sc9,
// );
// });
// } else {
// await initWifiStatusAndWifiList();
// }
// }
// });
// } else {
// // Navigator.pop(context);
// TopSlideNotification.show(
// context,
// text: "蓝牙绑定.连接失败".tr,
// textColor: themeController.currentColor.sc9,
// );
// }
// } catch (e) {
// // Navigator.of(Get.context!).pop(); // 关闭加载对话框
// TopSlideNotification.show(
// Get.context!,
// text: "设备连接失败".tr,
// textColor: themeController.currentColor.sc9,
// );
// }
// }
// });
// // 等待扫描完成
// await Future.delayed(Duration(seconds: 20));
// } catch (e) {
// timeoutTimer?.cancel();
// Navigator.of(Get.context!).pop(); // 关闭加载对话框
// TopSlideNotification.show(
// Get.context!,
// text: "扫描过程中发生错误".tr,
// textColor: themeController.currentColor.sc9,
// );
// } finally {
// timeoutTimer?.cancel();
// await FlutterBluePlus.stopScan();
// }
// }
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;
blueteethBindController.updateAll();
if (!bluetoothState) {
await _showBluetoothNotEnabledDialog();
return;
}
// 开始扫描
await FlutterBluePlus.startScan(timeout: Duration(seconds: 10));
bool isConnected = false;
// 设置超时定时器
_timeoutTimer = Timer(Duration(seconds: 20), () {
if (!isConnected && !_isDisposed) {
blueteethBindController.blueConnectFlag.value = 1;
blueteethBindController.netType.value = 3;
TopSlideNotification.show(
context,
text: "设备连接超时,请点击刷新重试".tr,
textColor: themeController.currentColor.sc9,
);
FlutterBluePlus.stopScan();
blueteethBindController.updateAll();
}
});
// 监听扫描结果
_scanSubscription = FlutterBluePlus.scanResults.listen((results) async {
if (_isDisposed) return;
for (var r in results) {
if (r.advertisementData.manufacturerData.containsKey(0xFFED)) {
List<int> rawData = r.advertisementData.manufacturerData[0xFFED]!;
BleDeviceData deviceData = parseBleData(rawData);
String deviceMac =
deviceData.deviceId.replaceAll(':', '').toLowerCase();
if (deviceMac == mac.toLowerCase()) {
targetDevice = r;
break;
}
}
}
if (targetDevice != null && !isConnected) {
isConnected = true;
_timeoutTimer?.cancel();
_scanSubscription?.cancel();
var streamlog;
try {
THapp bledevice = THapp(device: targetDevice!.device);
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,
// );
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");
}
// 添加连接状态监听
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(bledevice, 0);
if (aa == "4g") {
blueteethBindController.netType.value = 2;
blueteethBindController.updateAll();
updateDeviceBindStatus(
blueteethBindController.currentDeviceMac!.value);
await showTipDialog(
context,
Text(
"4g设备配置wifi提示".tr,
style: TextStyle(
color: themeController.currentColor.sc3,
fontSize: AppConstants().title_text_fontSize),
));
} else if (aa == 'unknown') {
blueteethBindController.netType.value = 3;
blueteethBindController.updateAll();
TopSlideNotification.show(
context,
text: "获取设备网络类型失败".tr,
textColor: themeController.currentColor.sc9,
);
} else {
blueteethBindController.netType.value = 1;
blueteethBindController.updateAll();
blueteethBindController.wifiConnectStatus.value = 0;
blueteethBindController.updateAll();
await initWifiStatusAndWifiList(needSuccess: needSuccess);
}
dealing = false;
}
});
} else {
TopSlideNotification.show(
context,
text: "设备连接失败,请点击刷新重试".tr,
textColor: themeController.currentColor.sc9,
);
}
} catch (e) {
blueteethBindController.blueConnectFlag.value = 1;
TopSlideNotification.show(
context,
text: "设备连接失败,请点击刷新重试".tr,
textColor: themeController.currentColor.sc9,
);
} finally {
streamlog.close();
}
}
});
await Future.delayed(Duration(seconds: 20));
} catch (e) {
if (!_isDisposed) {
TopSlideNotification.show(
context,
text: "扫描过程中发生错误".tr,
textColor: themeController.currentColor.sc9,
);
dealing = false;
}
} finally {
_timeoutTimer?.cancel();
await FlutterBluePlus.stopScan();
dealing = false;
}
}
void updateDeviceBindStatus(String mac) {
String serviceAddress = ServiceConstant.service_address;
String serviceName = ServiceConstant.server_service;
String serviceApi = ServiceConstant.user_setting;
String type = "device_bind_status_$mac";
String queryUrl =
"${serviceAddress}${serviceName}${serviceApi}?type=${type}";
requestWithLog(
logTitle: "查询绑定流程",
method: MyHttpMethod.get,
queryUrl: queryUrl,
onSuccess: (res) {
print(res);
Map<String, dynamic> data = {
"type": type,
"mac": mac,
"wifi": true,
"celibration": res.data['celibration'],
"person_info": res.data['person_info'],
"time": DateTime.now().millisecondsSinceEpoch,
};
requestWithLog(
logTitle: "更新绑定流程",
method: MyHttpMethod.put,
queryUrl: queryUrl,
data: data,
onSuccess: (res) {},
onFailure: (res) {},
);
},
onFailure: (res) {},
);
}
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(
blueteethBindController.currentDeviceMac.value,
);
return await getDeviceWifiStatus(blueteethBindController.currentDevice!, 1,
link: true);
}
Future<void> _cleanupResources() async {
// 取消监听器
lisObj?.cancel();
lisObj = null;
// 取消定时器
_timeoutTimer?.cancel();
_timeoutTimer = null;
// 取消扫描订阅
_scanSubscription?.cancel();
_scanSubscription = null;
await _disconnectDevice();
// 停止扫描
FlutterBluePlus.stopScan();
}
Future<void> _disconnectDevice() async {
try {
if (blueteethBindController.currentDevice != null) {
await blueteethBindController.currentDevice!.disconnect();
// blueteethBindController.currentDevice = null;
}
DailyLogUtils.writeLog("关闭蓝牙连接成功".tr);
} catch (e) {
DailyLogUtils.writeError("关闭蓝牙连接失败: $e");
} finally {
// dealing = false;
}
}
_showBluetoothNotEnabledDialog() async {
await showTipDialog(
context,
Column(
children: [
Text(
"蓝牙未开启".tr,
style: TextStyle(
fontSize: AppConstants().title_text_fontSize,
color: themeController.currentColor.sc3),
),
SizedBox(
height: 20.rpx,
),
Text(
"请先打开蓝牙在进行设备扫描".tr,
style: TextStyle(
fontSize: AppConstants().normal_text_fontSize,
color: themeController.currentColor.sc3),
),
],
));
}
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));
}
}
}
}