完成 远程控制页面的手机和服务器端网络状态的数值显示

This commit is contained in:
2026-04-02 16:40:18 +08:00
parent a9f21b6460
commit 507935166e
7 changed files with 74 additions and 25 deletions

View File

@@ -1,7 +1,9 @@
import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'package:dart_ping/dart_ping.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -68,7 +70,7 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
final controlMode = status.controlMode == '3' ? '远程模式' : '本地模式';
// final c = getPing('1.95.137.212'); // ⚠️ 替换为你的服务器 IP
final c = getNetworkDelay(); //
emit(state.copyWith(
runningStatusModel: state.runningStatusModel.copyWith(
voltage: voltage.toString(), // 更新电压
@@ -76,7 +78,7 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
controlMode: controlMode, // 更新控制模式
),
battery: int.tryParse(battery) ?? 0,
//ping: c, // 这里直接使用异步返回的数值
ping: await c, // 这里直接使用异步返回的数值
));
@@ -121,7 +123,7 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
// }
// });
// }
void _initPacketListener() {
Future<void> _initPacketListener() async {
print('>>> [RemoteControl] begin 初始化 0x12 监听器');
_kickOutSub?.cancel(); // 防止重复监听
@@ -191,7 +193,10 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
print('>>> [RemoteControl] ❌ 解析失败:$e');
}
});
final c = getNetworkDelay();
emit(state.copyWith(
ping: await c, // 这里直接使用异步返回的数值
));
print('>>> [RemoteControl] ✅ 0x12 监听器已建立完成');
}
@@ -362,30 +367,23 @@ class RemoteControlCubit extends Cubit<RemoteControlState> {
emit(state.copyWith(topRightIsExpanded: !state.topRightIsExpanded));
}
int getPing(String host) {
print('>>> [RemoteControl] 📡 开始 ping $host...');
Future<int> getNetworkDelay() async {
try {
// 直接 Ping 你的服务器 IP
final ping = Ping('1.95.137.212', count: 1, timeout: 1);
// 后台异步获取,不阻塞
platform.invokeMethod('ping', {
'host': host,
'count': 1,
'timeout': 2,
}).then((result) {
final success = result['success'] as bool? ?? false;
final delay = (result['delayMs'] as num?)?.toInt() ?? 100;
_currentPing = success ? delay.clamp(0, 100) : 100;
print('📶 [Ping 结果] $host - $_currentPing ms');
// 等待一次结果
final data = await ping.stream.first;
// 获取到新值后,再次 emit 更新 state
if (!isClosed) {
emit(state.copyWith(ping: _currentPing));
if (data.response != null && data.response!.time != null) {
// 返回和 cmd 一样的毫秒值
return data.response!.time!.inMilliseconds;
} else {
return 9999;
}
}).catchError((e) {
print('⚠️ [Ping 错误] $e');
_currentPing = 100;
});
return _currentPing; // 立即返回当前值
} catch (e) {
return 9999;
}
}