更新分享

This commit is contained in:
wyf
2025-04-28 15:37:58 +08:00
parent 850c34b408
commit eae7a2284d
116 changed files with 12143 additions and 3017 deletions

View File

@@ -1,7 +1,6 @@
import 'dart:async';
import 'package:ef/ef.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_svg/svg.dart';
@@ -14,19 +13,17 @@ import 'package:vbvs_app/controller/main_bottom/global_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/common/selectDialog.dart';
import 'package:vbvs_app/pages/device_bind/componnet/SingleBlueteethDeviceCompoentWidget.dart';
import 'package:vbvs_app/common/util/Ble.dart' as ble;
class BlueteethDevicePage extends StatefulWidget {
int tid = -1;
BlueteethDevicePage({super.key, this.tid = -1});
@override
State<BlueteethDevicePage> createState() => _EPageState();
State<BlueteethDevicePage> createState() => _BlueteethDevicePageState();
}
class _EPageState extends State<BlueteethDevicePage> {
class _BlueteethDevicePageState extends State<BlueteethDevicePage> {
GlobalController globalController = Get.find();
UserInfoController userInfoController = Get.find();
BlueteethBindController blueteethBindController = Get.find();
@@ -49,6 +46,8 @@ class _EPageState extends State<BlueteethDevicePage> {
@override
void initState() {
super.initState();
blueteethBindController.model.devicelist = [];
blueteethBindController.model.betDevicelist = [];
flutterBlue = FlutterBluePlus(); // 初始化flutterBlue实例
_checkBluetoothPermission(); // 检查蓝牙权限
Get.find<BlueteethBindController>().startStatusPolling();
@@ -114,6 +113,7 @@ class _EPageState extends State<BlueteethDevicePage> {
// 开始扫描蓝牙设备
void _startScanning() async {
if (!mounted) return;
var bluetoothState = await FlutterBluePlus.isOn;
if (!bluetoothState && !_isDialogShowing) {
_isDialogShowing = true;
@@ -128,8 +128,9 @@ class _EPageState extends State<BlueteethDevicePage> {
});
await FlutterBluePlus.startScan(timeout: Duration(seconds: 10));
// await FlutterBluePlus.startScan(timeout: Duration(minutes: 30));
FlutterBluePlus.scanResults.listen((results) {
_scanSubscription = FlutterBluePlus.scanResults.listen((results) {
final signalThreshold = blueteethBindController.model.singal!;
final filteredResults = results
.where((r) =>
@@ -149,6 +150,9 @@ class _EPageState extends State<BlueteethDevicePage> {
deviceData.rssi = r.rssi;
deviceData.mac = deviceData.deviceId.replaceAll(':', '');
parsedDeviceList.add(deviceData);
if (deviceData.mac!.toLowerCase() == 'b43a45c3dfa0') {
print('匹配设备数据: ${deviceData.mac}-->sn:${deviceData.sn}');
}
} catch (e) {
print("设备数据解析失败: $e");
}
@@ -188,13 +192,15 @@ class _EPageState extends State<BlueteethDevicePage> {
// 等待扫描完成
await Future.delayed(Duration(seconds: 10));
// await Future.delayed(Duration(minutes: 30));
await FlutterBluePlus.stopScan();
setState(() {
isScanning = false;
});
print("扫描完成");
if (mounted) {
setState(() {
isScanning = false;
});
}
// print("扫描完成");
}
}
@@ -210,10 +216,13 @@ class _EPageState extends State<BlueteethDevicePage> {
// 停止扫描
void _stopScanning() {
if (isScanning) {
FlutterBluePlus.stopScan(); // 停止扫描
setState(() {
isScanning = false; // 更新扫描状态
});
FlutterBluePlus.stopScan();
_scanSubscription?.cancel(); // 取消订阅
if (mounted) {
setState(() {
isScanning = false;
});
}
}
}
@@ -222,396 +231,15 @@ class _EPageState extends State<BlueteethDevicePage> {
_timer?.cancel();
}
StreamSubscription<List<ScanResult>>? _scanSubscription; // 添加扫描订阅变量
@override
void dispose() {
super.dispose();
_stopPeriodicScan(); // 停止定时扫描
_stopScanning(); // 确保离开页面时停止扫描
}
connectToDevice(device, {int time = 5}) {
ble.connectToDevice(
{
"device": device,
'success': (ble.ConnectedDeviceProp deviceProp) {
if (deviceProp.connectedDevicePropType ==
ble.ConnectedDevicePropType.JunHe) {
currentConnectedDeviceProp = deviceProp;
deviceProp.write3OfString("blog enable");
deviceProp.write3OfString("blog rlmax=128");
Timer(const Duration(microseconds: 100), () async {
String log = "";
Function logAdd = (l) {
log += l;
};
deviceProp.receiveLogArr.add(logAdd);
deviceProp.encodeType = 1;
deviceProp.deviceType = 1;
Timer.periodic(const Duration(milliseconds: 300), (timer) async {
if (timer.tick > 20) {
ble.disconnect(currentConnectedDeviceProp);
failSelectDialog();
timer.cancel();
}
if (log.contains("GB2312") || log.contains("UTF-8")) {
timer.cancel();
if (log.contains('CHARSET:UTF-8')) {
deviceProp.encodeType = 2;
}
if (log.contains('TARGET:ESPXX')) {
deviceProp.deviceType = 2;
}
log = "";
bool isSuccess = false;
for (var i = 0; i < 4; i++) {
deviceProp.write3OfString("at+system info");
await Future.delayed(const Duration(milliseconds: 400));
RegExp regExp = RegExp(r"Target Mac:(\S*)");
RegExpMatch? regExpMatch = regExp.firstMatch(log);
if (regExpMatch != null && regExpMatch.group(1) != null) {
String? mac = regExpMatch.group(1);
if (mac?.length == 12 && mac != "000000000000") {
bindArr[2] = "$mac".toUpperCase();
}
isSuccess = true;
break;
}
}
deviceProp.receiveLogArr.remove(logAdd);
print("$bindArr");
RegExp regExp = RegExp(
r"WIFI CONNECTED INFO:SSID=([^\t\n]*)\s*,RSSI=(\S*)\s*,");
RegExpMatch? regExpMatch = regExp.firstMatch(log);
if (regExpMatch != null && log.contains("Status=connect")) {
blueteethBindController.model.connectedWifiName =
regExpMatch.group(1) ?? "";
if (int.tryParse("${regExpMatch.group(2)}") != null) {
blueteethBindController.model.connectedRssi =
int.parse("${regExpMatch.group(2)}");
}
blueteethBindController.updateAll();
}
ble.bleParse();
if (bindArr[0] != null &&
bindArr[0] != "" &&
bindArr[1] != "") {
setState(() {
currentMsg = "绑定中...";
});
blueteethBindController.bindDevice({
"tid": widget.tid,
"name": blueteethBindController.model.deviceName,
"mac": bindArr[0],
"macA": bindArr[1],
"macB": bindArr[2]
}).then((d) {
blueteethBindController.model.bindArr = bindArr;
globalController.getDeviceList();
LoadingDialog.hide();
showCustomConfirmDialog(context, "设备添加成功!",
btnName: "打开WIFI配置",
icon: ConfirmDialogIcon.success)
.then((d) {
if (d == "confirm") {
Get.offAndToNamed("/wifi", arguments: deviceProp);
}
});
}).catchError((d) {
print("$d");
currentMsg = "绑定失败: ${d.message}";
ble.disconnect(currentConnectedDeviceProp);
failSelectDialog(title: "${d.message}");
});
} else {
LoadingDialog.hide();
Get.offAndToNamed("/wifi", arguments: deviceProp);
}
} else {
deviceProp.read6();
}
});
});
} else if (deviceProp.connectedDevicePropType ==
ble.ConnectedDevicePropType.QuanShi) {
List receive = [];
Function fun = (d) {
receive.add(d);
};
deviceProp.receiveLogArr.add(fun);
List<int> head = [
255,
255,
255,
255,
1,
0,
12,
17,
];
Timer.periodic(const Duration(seconds: 1), (timer) {
if (timer.tick > 20) {
timer.cancel();
currentMsg = "错误未能获取到MAC";
failSelectDialog();
}
deviceProp.write(
Uint8List.fromList([
0xFF,
0xFF,
0xFF,
0xFF,
0x01,
0x00,
0x0C,
0x0B,
0x0F,
0x23,
0x04
]),
null,
null);
if (receive.length > 0) {
receive.forEach((data) {
if (data.length != 17) {
return;
}
bool r = true;
for (var i = 0; i < head.length; i++) {
if (head[i] != data[i]) {
r = false;
}
}
if (r == false) {
return;
}
bindArr[1] = ble.ab2str(data.sublist(9, 15)).toUpperCase();
timer.cancel();
deviceProp.receiveLogArr.remove(fun);
blueteethBindController.model.deviceName =
deviceProp.connectDevice?.advName;
ble.disconnect(deviceProp);
toFindJunhe();
});
}
});
} else {
List receive = [];
Function fun = (d) {
receive.add(d);
};
deviceProp.receiveLogArr.add(fun);
List<int> head = [255, 255, 255, 255, 0x00, 0x08, 0x40, 0x01];
Timer.periodic(const Duration(seconds: 1), (timer) {
if (timer.tick > 20) {
timer.cancel();
currentMsg = "错误未能获取到MAC";
failSelectDialog();
}
deviceProp.write(
Uint8List.fromList([
255,
255,
255,
255,
0x00,
0x03,
0x40,
0x01,
0x01,
0x00,
0x45,
0xfd
]),
null,
null);
if (receive.length > 0) {
receive.forEach((data) {
if (data.length != 17) {
return;
}
bool r = true;
for (var i = 0; i < head.length; i++) {
if (head[i] != data[i]) {
r = false;
}
}
if (r == false) {
return;
}
bindArr[1] = ble.ab2str(data.sublist(8, 14)).toUpperCase();
print("$bindArr");
timer.cancel();
deviceProp.receiveLogArr.remove(fun);
blueteethBindController.model.deviceName =
deviceProp.connectDevice?.advName;
ble.disconnect(deviceProp);
toFindJunhe();
});
}
});
}
},
'fail': (e) {
print(e);
if (time > 0) {
connectToDevice(device, time: time - 1);
} else {
currentMsg = "蓝牙无法连接上设备";
failSelectDialog(title: currentMsg);
}
}
},
);
}
isBind() {
return !(blueteethBindController.model.bindArr[1]?.length == 12);
}
failSelectDialog({String title = ""}) {
LoadingDialog.hide();
setState(() {});
showCustomConfirmAndCancelDialog(
context, title == "" ? (isBind() ? "绑定失败" : "连接失败") : title,
confirmName: "重试", cancelName: "返回")
.then((d) {
if (d == "confirm") {
if (connectDeviceCurrent != null) {
ble.bleParse();
ble.start((List d) {
setState(() {
bleDevice = d;
});
}, bleOnCall: () {
LoadingDialog.show("连接中...\n靠近设备2米内",
icon:
isBind() ? LoadingDialogIcon.ble : LoadingDialogIcon.wifi);
setState(() {
currentMsg = "连接设备中...";
});
connectToDevice(connectDeviceCurrent);
});
} else {
bleExec();
}
} else if (d == "cancel") {
Get.back();
}
});
}
bleExec() {
ble.bleParse();
connectTimer?.cancel();
int index = 0;
bool isCloseLoadingDialog = false;
isFind = false;
blueteethBindController.model.bindArr = bindArrBackup;
bindArr = ["", "", ""];
ble.start((List d) {
setState(() {
bleDevice = d;
});
if (isBind()) {
if (isCloseLoadingDialog == false &&
bleDevice.indexWhere((item) {
if (widget.tid == 1) {
return ble.isQuanShiDevice(item["name"]);
} else {
return ble.isMHTSWES(item["name"]);
}
}) !=
-1) {
isCloseLoadingDialog = true;
LoadingDialog.hide();
}
}
}, bleOnCall: () {
if (isBind()) {
LoadingDialog.show("搜索蓝牙设备中...\n请打开蓝牙开关、定位开关\n与设备距离在2米内",
icon: isBind() ? LoadingDialogIcon.ble : LoadingDialogIcon.wifi);
Timer.periodic(const Duration(seconds: 1), (t) {
if (t.tick > 15) {
t.cancel();
isCloseLoadingDialog = true;
LoadingDialog.hide();
showCustomConfirmAndCancelDialog(context, "未发现设备",
confirmName: "重试", cancelName: "返回")
.then((d) {
if (d == "confirm") {
bleExec();
} else if (d == "cancel") {
Get.back();
}
});
} else {
if (isCloseLoadingDialog == true) {
t.cancel();
}
}
});
return;
}
LoadingDialog.show(
"${isBind() ? "绑定中...\n与设备距离在2米内" : "连接中...\n请打开蓝牙开关、定位开关\n与设备距离在2米内"}",
icon: isBind() ? LoadingDialogIcon.ble : LoadingDialogIcon.wifi);
connectTimer = Timer.periodic(const Duration(seconds: 1), (t) {
index++;
if (index > 15) {
connectTimer = null;
t.cancel();
failSelectDialog();
}
var d = bleDevice;
if (d != null && d.length > 0) {
if (isBind()) {
var deviceble = d.firstWhere((item) {
bool isFF = false;
if (widget.tid == 1) {
isFF = ble.isQuanShiDevice(item["name"]);
} else {
isFF = ble.isMHTSWES(item["name"]);
}
if (isFF) {
isFF = globalController.model.deviceList.indexWhere(
(d) => d["mac"] == item["adData"]["deviceId"]) ==
-1
? true
: false;
}
return isFF;
}, orElse: () => null);
if (!isFind && deviceble != null) {
print("quanshidevice");
isFind = true;
setState(() {
currentMsg = "连接设备中...";
});
t.cancel();
connectToDevice(deviceble["device"]);
bindArr[0] = deviceble["adData"]["deviceId"];
}
} else {
var deviceble = d.firstWhere(
(item) =>
item["adData"]["deviceId"] ==
blueteethBindController.model.bindArr[1],
orElse: () => null);
if (!isFind && deviceble != null) {
print("junhedevice");
isFind = true;
t.cancel();
setState(() {
currentMsg = "连接设备中...";
});
connectToDevice(deviceble["device"]);
bindArr[1] = deviceble["adData"]["deviceId"];
}
}
}
});
});
_stopScanning(); // 停止扫描
_scanSubscription?.cancel(); // 取消扫描订阅
connectTimer?.cancel(); // 取消连接定时器
blueteethBindController.stopStatusPolling(); // 停止状态轮询
super.dispose();
}
@override
@@ -679,7 +307,7 @@ class _EPageState extends State<BlueteethDevicePage> {
padding: EdgeInsetsDirectional.fromSTEB(
0, 30.rpx, 0, 30.rpx),
child: Text(
'蓝牙绑定.扫描蓝牙设备中…'.tr,
'蓝牙绑定.扫描'.tr,
style: FlutterFlowTheme.of(context)
.bodyMedium
.override(
@@ -917,42 +545,48 @@ class _EPageState extends State<BlueteethDevicePage> {
child: Padding(
padding:
EdgeInsetsDirectional.fromSTEB(19.rpx, 0, 0, 0),
child: Text(
'匹配出的外围设备(${blueteethBindController.model.devicelist!.length}',
style: FlutterFlowTheme.of(context)
.bodyMedium
.override(
fontFamily: 'Inter',
fontSize: 30.rpx,
letterSpacing: 0.0,
color: themeController.currentColor.sc3,
),
),
child: Obx(() {
return Text(
'匹配出的外围设备(${blueteethBindController.model.betDevicelist!.length}',
style: FlutterFlowTheme.of(context)
.bodyMedium
.override(
fontFamily: 'Inter',
fontSize: 30.rpx,
letterSpacing: 0.0,
color: themeController.currentColor.sc3,
),
);
}),
),
),
),
Obx(() {
return Expanded(
child: Container(
width: double.infinity,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
...blueteethBindController.model.blelist!
.map((device) =>
SingleBlueteethDeviceCompoentWidget(
// device: device,
bleDevice: device,
))
.toList()
.divide(SizedBox(height: 30.rpx))
.addToEnd(SizedBox(height: 30.rpx)),
],
if (blueteethBindController
.model.betDevicelist!.isNotEmpty) {
return Expanded(
child: Container(
width: double.infinity,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
...blueteethBindController.model.blelist!
.map((device) =>
SingleBlueteethDeviceCompoentWidget(
// device: device,
bleDevice: device,
))
.toList()
.divide(SizedBox(height: 30.rpx))
.addToEnd(SizedBox(height: 30.rpx)),
],
),
),
),
),
);
);
}
return Container();
}),
].divide(SizedBox(height: 30.rpx)),
),
@@ -979,38 +613,6 @@ class _EPageState extends State<BlueteethDevicePage> {
),
);
}
toFindJunhe() {
bool isSuccess = false;
int i = 0;
Timer.periodic(const Duration(seconds: 1), (t) async {
i++;
if (isSuccess) {
return;
}
if (i > 8) {
if (!isSuccess) {
currentMsg = "错误:未找到关联设备";
failSelectDialog(title: "绑定失败:未找到关联设备");
}
t.cancel();
return;
}
bleDevice.forEach((item) {
if (isSuccess) {
return;
}
if (item['adData']['deviceId'] == bindArr[1]) {
isSuccess = true;
t.cancel();
setState(() {
currentMsg = "寻找关联设备中...";
});
connectToDevice(item["device"]);
}
});
});
}
}
BleDeviceData parseBleData(List<int> data) {