Files
tuiche/lib/pages/device_bind/wifi_page.dart
2025-08-20 17:47:46 +08:00

1182 lines
60 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/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';
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;
@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);
}
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') {
// 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();
}
}
});
} 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
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: 1,
valueColor: AlwaysStoppedAnimation<Color>(
themeController.currentColor.sc1,),
),
);
}
if (blueteethBindController.connectStatus.value ==
0 &&
blueteethBindController.netType.value != 0) {
return SizedBox(
width: 24.rpx,
height: 24.rpx,
child: CircularProgressIndicator(
strokeWidth: 1,
valueColor: AlwaysStoppedAnimation<Color>(
themeController.currentColor.sc1,),
),
);
}
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 {
// showLoadingDialog(
// context); // 显示 loading
blueteethBindController
.selectWifi
.value = wifiItem;
bool flag = await sendWifiSetting(
wifiItem,
blueteethBindController
.model.wifiPass!,
blueteethBindController
.currentDevice!);
// Navigator.pop(context);
if (flag) {
// bool wifiStatus =
// await getWifiStatus(
// blueteethBindController
// .currentDevice!);
bool wifiStatus = false;
var aa = await getDeviceWifiStatus(
blueteethBindController
.currentDevice!,
1);
blueteethBindController
.selectWifi
.value = {};
if (aa != null &&
aa is Map) {
wifiStatus = true;
blueteethBindController
.connect_wifi
.value = aa;
} else {
blueteethBindController
.connect_wifi
.value = {};
}
blueteethBindController
.wifiStatus
.value =
wifiStatus == true
? 1
: 0;
blueteethBindController
.wifiStatus
.value =
wifiStatus == true
? 1
: 0;
if (wifiStatus) {
updateDeviceBindStatus(
blueteethBindController
.currentDeviceMac!
.value);
// Navigator.pop(context);
TopSlideNotification
.show(
context,
text: "wifi页.配网成功".tr,
textColor:
themeController
.currentColor
.sc2,
);
blueteethBindController
.wifiStatus
.value = 1;
blueteethBindController
.updateAll();
} else {
// Navigator.pop(context);
TopSlideNotification
.show(
context,
text: "wifi页.配网失败".tr,
textColor:
themeController
.currentColor
.sc9,
);
blueteethBindController
.wifiStatus
.value = 0;
blueteethBindController
.updateAll();
}
} else {
// Navigator.pop(context);
TopSlideNotification.show(
context,
text: "wifi页.配网失败".tr,
textColor:
themeController
.currentColor
.sc9,
);
blueteethBindController
.wifiStatus.value = 0;
blueteethBindController
.updateAll();
}
});
},
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: 1,
valueColor:
AlwaysStoppedAnimation<
Color>(
themeController.currentColor.sc1,),
),
)
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);
}
// 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,
// );
// }
// }
});
}
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 >= -30) {
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 >= -45) {
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 >= -60) {
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();
}
}
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) {},
);
}
}