943 lines
37 KiB
Dart
943 lines
37 KiB
Dart
import 'dart:async';
|
||
import 'package:maibu_satabot_v2/features/device_control_mode/domain/entities/device_control_mode.dart';
|
||
import 'package:maibu_satabot_v2/features/device_control_mode/presentation/widgets/control_mode_entry_gate.dart';
|
||
import 'dart:io';
|
||
import 'dart:ui' as ui;
|
||
|
||
import 'package:flutter/material.dart';
|
||
import 'package:flutter/rendering.dart';
|
||
import 'package:flutter/services.dart';
|
||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||
import 'package:path_provider/path_provider.dart';
|
||
|
||
import 'package:maibu_satabot_v2/components/capsule_toast.dart';
|
||
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
|
||
import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart';
|
||
import 'package:maibu_satabot_v2/core/di/injection.dart';
|
||
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
|
||
import 'package:maibu_satabot_v2/features/auth/presentation/bloc/auth_cubit.dart';
|
||
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_bloc.dart';
|
||
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/device_status_state.dart';
|
||
import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_cubit.dart';
|
||
import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_state.dart';
|
||
import 'package:maibu_satabot_v2/features/v2/local_camera/presentation/cubit/local_camera_cubit.dart';
|
||
import 'package:maibu_satabot_v2/features/v2/usb_camera/data/uvc_camera_service.dart';
|
||
import 'package:maibu_satabot_v2/features/v2/usb_camera/presentation/cubit/usb_camera_cubit.dart';
|
||
import 'package:maibu_satabot_v2/features/v2/device_list/domain/usecases/search_device_usecase.dart';
|
||
|
||
import '../models/pv_telemetry.dart';
|
||
import '../channel/pv_robot_command_channel.dart';
|
||
import '../models/pv_video_fit.dart';
|
||
import '../models/pv_video_source.dart';
|
||
import '../theme/pv_colors.dart';
|
||
import '../widgets/pv_control_bar.dart';
|
||
import '../widgets/pv_info_column.dart';
|
||
import '../widgets/pv_manual_control_view.dart';
|
||
import '../widgets/pv_settings_sheet.dart';
|
||
import '../widgets/pv_video_area.dart';
|
||
import '../widgets/pv_work_map.dart';
|
||
|
||
/// 页面视图模式:普通态 / 手动控制全屏态
|
||
enum PvViewMode { normal, manualControl }
|
||
|
||
/// 光伏电站机器人远程控制(横屏大屏)页面。
|
||
///
|
||
/// 布局弹性可变:顶部导航固定,下方第一行(视频 + 右侧列)随空间伸缩,
|
||
/// 第二行控制栏固定高度。右侧列可在「信息」与「地图」间切换;
|
||
/// 「手动控制」进入视频铺满全屏 + 摇杆的形态,底部折叠图标返回。
|
||
class PvControlPage extends StatefulWidget {
|
||
const PvControlPage({
|
||
super.key,
|
||
required this.deviceId,
|
||
this.deviceName,
|
||
this.initialMode = PvViewMode.normal,
|
||
this.initialShowJoysticks = true,
|
||
});
|
||
|
||
final String deviceId;
|
||
final String? deviceName;
|
||
|
||
/// 初始视图模式:默认先进普通态大屏;设备详情「远程遥控」入口传
|
||
/// [PvViewMode.manualControl],进页直接是手动控制 HUD(不再经过大屏)。
|
||
final PvViewMode initialMode;
|
||
|
||
/// 进页时是否显示全屏 HUD 的两侧方向摇杆(默认显示)。
|
||
/// 从「进入实时视频」那条链路(先看画面再转遥控)进来时传 false,
|
||
/// 摇杆默认收起,用户在设置里需要时再手动打开。
|
||
final bool initialShowJoysticks;
|
||
|
||
@override
|
||
State<PvControlPage> createState() => _PvControlPageState();
|
||
}
|
||
|
||
class _PvControlPageState extends State<PvControlPage> {
|
||
/// 截图用的视频区 RepaintBoundary key
|
||
final GlobalKey _videoKey = GlobalKey();
|
||
|
||
/// 本批次使用 Mock 遥测数据
|
||
final PvTelemetry _telemetry = const PvTelemetry();
|
||
|
||
/// 遥控指令传输通道:当前为 TCP 实现(委托 `RemoteControlCubit`),
|
||
/// 以后接蓝牙 / 下位机只换一个实现类,HUD 与本页面代码零改动。
|
||
final PvRobotCommandChannel _channel = const RemoteControlRobotChannel();
|
||
|
||
/// 控制态是否已激活:进入「手动控制」才 activate,退出 / 页面销毁 deactivate。
|
||
bool _controlActive = false;
|
||
|
||
/// deactivate 是否正在进行中(内部含 await 归零全停 + HTTP 释放,约 0.5~1s)。
|
||
/// 🔥 这段时间里若用户立刻重新点「手动控制」,不能马上 activate:
|
||
/// 尾部那次 stopControlLoop() 会把刚起来的循环又关掉,HUD 就变成
|
||
/// “摇杆推了没反应”。故延后到 deactivate 收尾再起循环。
|
||
bool _deactivating = false;
|
||
|
||
/// deactivate 期间收到过重新进入控制态的请求。
|
||
bool _restartAfterDeactivate = false;
|
||
|
||
/// 急停开关态:HUD 急停钮每点一次翻转,经通道下发 updateEmergency。
|
||
bool _emergencyOn = false;
|
||
|
||
/// 远程控制单例(HUD 与原远程遥控页共用它,指令通道内部也委托它)。
|
||
RemoteControlCubit get _cubit => sl<RemoteControlCubit>();
|
||
|
||
/// 「权限交接」监听订阅:监听其它端请求控制权的推送并弹确认框。
|
||
StreamSubscription? _permissionSubscription;
|
||
|
||
/// 防止权限弹窗重复弹出(与远程遥控页一致)。
|
||
bool _isShowingPermissionDialog = false;
|
||
|
||
/// 记录上次弹窗显示态,用于检测 false→true 的上升沿。
|
||
bool? _lastPermissionDialogState;
|
||
|
||
late PvViewMode _mode = widget.initialMode;
|
||
|
||
/// 右侧列是否显示地图(点击「查看地图」切换)
|
||
bool _showMap = false;
|
||
|
||
String _streamUrl = '';
|
||
|
||
/// 当前视频链路(多源可扩展):在设置面板「视频源」行切换,
|
||
/// 切换即重建对应链路 cubit(_wrapVideoProvider 挂了 ValueKey)。
|
||
PvVideoSource _videoSource = PvVideoSource.usbCamera;
|
||
|
||
/// 视频展示方式(设置面板「视频展示」行切换):
|
||
/// contain 完整显示(可能留黑边)/ cover 等比铺满(裁掉边缘)。
|
||
PvVideoFit _videoFit = PvVideoFit.contain;
|
||
|
||
/// 模拟开关(真实推送未接入前在设置面板手动触发)。
|
||
bool _simObstacle = false;
|
||
|
||
/// 「倒车影像」:控制手动控制主画面中间那组导向路径 + 黄色/绿色车道线
|
||
/// (带流动箭头)的显隐,同时决定左下后视卡是否叠倒车引导线。
|
||
/// 默认开启 = 保持原有视觉;关掉后画面回到干净视频。
|
||
bool _simReverse = true;
|
||
|
||
/// 是否显示手动控制 HUD 的左右两个方向摇杆(设置面板可关掉):
|
||
/// 关掉后摇杆与回中按钮一起隐藏,底部操作条自动向两侧展开。
|
||
/// 初始值由入口决定([PvControlPage.initialShowJoysticks])。
|
||
late bool _showJoysticks = widget.initialShowJoysticks;
|
||
|
||
/// 当前控制设备名:优先用页面入参(就是入口点选的那台,带别名),
|
||
/// 缺失时回退 RemoteControlCubit 的 targetDevice,都没有则显示占位。
|
||
String _resolveDeviceName(RemoteControlState? remote) {
|
||
final passed = (widget.deviceName ?? '').trim();
|
||
if (passed.isNotEmpty) return passed;
|
||
final target = (remote?.targetDevice?.deviceName ?? '').trim();
|
||
return target.isNotEmpty
|
||
? target
|
||
: AppLocalizations.of(context).translate('pv_control.no_device');
|
||
}
|
||
|
||
/// 实际下发的遥测:真实字段来自全局 [DeviceStatusBloc] 的 host 实时数据
|
||
/// (电量/巡检里程/设备温度),未收到时置 null 由 UI 显示"未知";
|
||
/// 开启「模拟障碍物信息」相当于收到机器告警推送,叠加 obstacleAlert。
|
||
PvTelemetry _resolveTelemetry(DeviceStatusState dsState, String deviceName) {
|
||
double? battery;
|
||
double? mileage;
|
||
double? temp;
|
||
int? fixStatus;
|
||
int? satelliteCount;
|
||
String? controlMode;
|
||
if (dsState is DeviceStatusUpdated) {
|
||
final s = dsState.status;
|
||
// 定位质量:来自 location/post 的 fix_status(qual)
|
||
fixStatus = s.qual;
|
||
// 控制模式:与“设备数据监控”同一口径,只要收到状态就跟随,不加 host 门控
|
||
controlMode = s.controlMode;
|
||
// 卫星数:realtime/post 尚未推送,无数据源时保持 null 显示"未知"
|
||
if (s.satelliteCnt > 0) satelliteCount = s.satelliteCnt;
|
||
// 以下三项来自 host 实时话题(device/{sn}/host/realTime/message)
|
||
if (s.hostDataReceived) {
|
||
battery = double.tryParse(s.battery);
|
||
mileage = s.totalWorkDistance;
|
||
temp = s.chipTemp;
|
||
}
|
||
}
|
||
return _telemetry.copyWith(
|
||
// 设备名用真实选中的设备,不再用 PvTelemetry 里写死的占位名
|
||
deviceName: deviceName,
|
||
obstacleAlert: _simObstacle,
|
||
battery: battery,
|
||
mileage: mileage,
|
||
temperature: temp,
|
||
fixStatus: fixStatus,
|
||
satelliteCount: satelliteCount,
|
||
controlMode: controlMode,
|
||
);
|
||
}
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
_enterLandscape();
|
||
_initVideoUrl();
|
||
_ensureRealtimeListening();
|
||
// 进入安全模式:防止异地登录推送把控制踢下线(与远程遥控页一致)。
|
||
sl<AuthCubit>().enterSafeMode();
|
||
// 监听「权限交接」:其它端请求控制权时弹确认框,整页生命周期常驻。
|
||
_initPermissionHandoverListener();
|
||
// 控制会话由模式确认完成后的回调建立。
|
||
}
|
||
|
||
/// 本页的视频、地图、遥测都是围绕 `deviceId` 这一台设备,所以进页时确保
|
||
/// MQTT 实时定位/路线订阅就指向它(全局单例 bloc,数据源内部同 SN 去重、
|
||
/// 自动退旧订新,重复调用无副作用)。退出页面不切回去:语义与设备列表
|
||
/// 正常切设备一致,切回去反而会让别处(如路径规划)突然断流。
|
||
void _ensureRealtimeListening() {
|
||
if (widget.deviceId.isEmpty) return;
|
||
context.read<DeviceStatusBloc>().startMqttRealtimeListening(
|
||
widget.deviceId,
|
||
);
|
||
}
|
||
|
||
/// 进入页面强制横屏
|
||
void _enterLandscape() {
|
||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
|
||
SystemChrome.setPreferredOrientations([
|
||
DeviceOrientation.landscapeLeft,
|
||
DeviceOrientation.landscapeRight,
|
||
]);
|
||
}
|
||
|
||
/// 离开页面恢复竖屏 + 系统栏
|
||
void _restoreOrientation() {
|
||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
|
||
SystemChrome.setPreferredOrientations(DeviceOrientation.values);
|
||
}
|
||
|
||
void _initVideoUrl() {
|
||
final userState = context.read<AppUserCubit>().state;
|
||
final token = userState.user?.token;
|
||
if (widget.deviceId.isNotEmpty && token != null) {
|
||
setState(() {
|
||
_streamUrl =
|
||
'webrtc://${TCPConsts.TCP_IP}/live/livestream/${widget.deviceId}?token=$token';
|
||
});
|
||
} else {
|
||
debugPrint('❌ [PvControl] 视频URL初始化失败:deviceId 或 token 为空');
|
||
}
|
||
}
|
||
|
||
@override
|
||
void dispose() {
|
||
// 离开安全模式:启动 90 秒倒计时(与远程遥控页一致)。
|
||
sl<AuthCubit>().exitSafeMode();
|
||
// 取消「权限交接」弹窗监听,避免回调打到已销毁的 State。
|
||
_permissionSubscription?.cancel();
|
||
_permissionSubscription = null;
|
||
// 退出控制态:归零、停循环、释放权限(type=2)、解除急停、复位权限态。
|
||
_stopControl();
|
||
_restoreOrientation();
|
||
super.dispose();
|
||
}
|
||
|
||
// ===== 交互回调 =====
|
||
|
||
void _onViewMap() {
|
||
setState(() => _showMap = !_showMap);
|
||
}
|
||
|
||
void _onManualControl() {
|
||
setState(() => _mode = PvViewMode.manualControl);
|
||
// 🔥 折叠会退出控制态(见 _onCollapseManual),重新进 HUD 必须重新进入:
|
||
// _startControl 有 _controlActive 幂等保护,首次进页(initState)重复调也不会起两份循环。
|
||
_startControl();
|
||
}
|
||
|
||
void _onCollapseManual() {
|
||
// 🔥 折叠 = 退出控制态,不只是一次归零:大屏上没有摇杆,却留着
|
||
// activate() 起着的 200ms 循环与控制权,既持续向设备发零速帧、又挤占
|
||
// 同一条 TCP 上的业务指令;而 HUD 被卸载那一瞬,摇杆的 onPanEnd /
|
||
// Listener.onPointerUp 三重兜底会随 State 一起消失,若另一只手仍按着
|
||
// 摇杆,轴值就残留在非零 —— 大屏上没东西可归零,相当于“一直走”。
|
||
// deactivate() 内部顺序已是:解除急停 → await 归零+全停 → 停循环 → 释放权限。
|
||
// 不弹 toast:折叠是常规视图切换,不是“退出遥控”,每次弹释放提示很噪。
|
||
_stopControl(notify: false);
|
||
setState(() => _mode = PvViewMode.normal);
|
||
}
|
||
|
||
/// 一键寻车:视频区 person_search 按钮,直连后端 searchDevice 接口。
|
||
///
|
||
/// deviceId 用 widget.deviceId(即设备编码 deviceName,MC700- 开头),
|
||
/// 不是 getSiteList 的数字主键;下发结果以胶囊 Toast 反馈。
|
||
Future<void> _onLocate() async {
|
||
final code = widget.deviceId.trim();
|
||
final tr = AppLocalizations.of(context);
|
||
if (code.isEmpty) {
|
||
CapsuleToast.show(
|
||
tr.translate('device_list_v2.fr_toast_start_failed'),
|
||
showCheck: false,
|
||
);
|
||
return;
|
||
}
|
||
final result = await sl<SearchDeviceUseCase>().execute(deviceCode: code);
|
||
if (!mounted) return;
|
||
result.fold(
|
||
(failure) => CapsuleToast.show(
|
||
failure.message.isEmpty
|
||
? tr.translate('device_list_v2.fr_toast_start_failed')
|
||
: failure.message,
|
||
showCheck: false,
|
||
),
|
||
(_) =>
|
||
CapsuleToast.show(tr.translate('device_list_v2.fr_toast_start_sent')),
|
||
);
|
||
}
|
||
|
||
void _onPauseTask() {
|
||
CapsuleToast.show(
|
||
AppLocalizations.of(context).translate('pv_control.toast_paused'),
|
||
showCheck: false,
|
||
);
|
||
}
|
||
|
||
void _onEmergencyStop() {
|
||
// HUD 急停钮为“点一下急停 / 再点一下恢复”的切换态(按钮自身不携带 on/off)。
|
||
_emergencyOn = !_emergencyOn;
|
||
_channel.sendEmergencyStop(_emergencyOn);
|
||
final tr = AppLocalizations.of(context);
|
||
CapsuleToast.show(
|
||
_emergencyOn
|
||
? tr.translate('pv_control.toast_emergency_sent')
|
||
: tr.translate('pv_control.toast_emergency_released'),
|
||
showCheck: false,
|
||
);
|
||
}
|
||
|
||
/// 进入控制态:查询权限 + 启动控制循环(与远程遥控页生命周期一致)。
|
||
void _startControl() {
|
||
if (_controlActive) return;
|
||
if (_cubit.state.targetDevice?.deviceName != widget.deviceId) {
|
||
debugPrint('❌ [PV遥控] targetDevice 为空,跳过控制循环与权限查询');
|
||
return;
|
||
}
|
||
// 🔥 上一轮折叠的 deactivate 还在收尾:先记需求,等它结束后再起循环,
|
||
// 否则会被它尾部的 stopControlLoop() 把新循环一并关掉。
|
||
if (_deactivating) {
|
||
_restartAfterDeactivate = true;
|
||
debugPrint('⚠️ [PV遥控] 退出控制态尚未完成,推迟进入控制态');
|
||
return;
|
||
}
|
||
_controlActive = true;
|
||
// deactivate 会清除急停态,重新进入从“未急停”开始,与通道保持同步。
|
||
_emergencyOn = false;
|
||
_channel.activate();
|
||
}
|
||
|
||
/// 退出控制态:归零、停循环、释放权限(通道内部完成,不阻塞 UI)。
|
||
///
|
||
/// [notify] 是否弹“释放控制权”结果提示:退页(dispose)需要,
|
||
/// HUD 折叠回大屏属常规视图切换,不打扰。
|
||
void _stopControl({bool notify = true}) {
|
||
if (!_controlActive) return;
|
||
_controlActive = false;
|
||
_deactivating = true;
|
||
_restartAfterDeactivate = false;
|
||
// dispose 不能 await,fire-and-forget;拿到释放结果后弹与远程遥控页一致的提示
|
||
//(CapsuleToast 走根 Overlay,页面销毁瞬间也能显示);无设备未发起释放则不弹。
|
||
_channel.deactivate().then((released) {
|
||
// 🔥 收尾:先解除“正在退出”标记,若期间用户已重新进入 HUD 就补起一次控制态。
|
||
_deactivating = false;
|
||
if (_restartAfterDeactivate) {
|
||
_restartAfterDeactivate = false;
|
||
// 页面已销毁(退页与折叠竞态)时绝不能再起循环:那会留下一个无主的控制循环。
|
||
if (mounted) _startControl();
|
||
}
|
||
if (released == null || !mounted || !notify) return;
|
||
final tr = AppLocalizations.of(context);
|
||
CapsuleToast.show(
|
||
released
|
||
? tr.translate('pv_control.toast_permission_released')
|
||
: tr.translate('pv_control.toast_permission_release_failed'),
|
||
showCheck: released,
|
||
);
|
||
});
|
||
}
|
||
|
||
/// 监听「权限交接」:订阅 Cubit 状态流,仅当 `updateType=='permission_dialog'`
|
||
/// 且 `showPermissionRequestDialog` 由 false→true 的上升沿时弹一次确认框(防重复),
|
||
/// 逻辑与远程遥控页 `didChangeDependencies` 完全一致。
|
||
void _initPermissionHandoverListener() {
|
||
_permissionSubscription = _cubit.stream.listen((state) {
|
||
// 设备状态更新(500ms)不触发弹窗,只重置记录。
|
||
if (state.updateType != 'permission_dialog') {
|
||
if (!state.showPermissionRequestDialog) {
|
||
_lastPermissionDialogState = false;
|
||
}
|
||
return;
|
||
}
|
||
final wasFalseBefore =
|
||
_lastPermissionDialogState == null ||
|
||
_lastPermissionDialogState == false;
|
||
final shouldShow =
|
||
state.showPermissionRequestDialog &&
|
||
!_isShowingPermissionDialog &&
|
||
wasFalseBefore;
|
||
if (mounted && shouldShow) {
|
||
_lastPermissionDialogState = true;
|
||
_isShowingPermissionDialog = true;
|
||
debugPrint('🔔 [PV遥控][权限交接] 检测到请求控制权,准备弹窗');
|
||
Future.microtask(() {
|
||
_showPermissionDialog(state).then((_) {
|
||
_isShowingPermissionDialog = false;
|
||
_lastPermissionDialogState = false;
|
||
});
|
||
});
|
||
} else if (!state.showPermissionRequestDialog) {
|
||
_lastPermissionDialogState = false;
|
||
}
|
||
});
|
||
}
|
||
|
||
/// 权限交接弹窗:某端请求控制权 → 同意/拒绝 → `confirmPermissionResponse`
|
||
/// 发 TCP 响应,关闭前复位 `showPermissionRequestDialog`(与远程遥控页同款)。
|
||
Future<void> _showPermissionDialog(RemoteControlState state) async {
|
||
final tr = AppLocalizations.of(context);
|
||
final requestingDeviceId =
|
||
state.requestingDeviceId ??
|
||
tr.translate('pv_control.perm_unknown_device');
|
||
final requestingPlatform =
|
||
state.requestingPlatform ??
|
||
tr.translate('pv_control.perm_unknown_platform');
|
||
final dialogContent = tr
|
||
.translate('pv_control.perm_request_body')
|
||
.replaceAll('{platform}', requestingPlatform)
|
||
.replaceAll('{deviceId}', requestingDeviceId);
|
||
final cubit = _cubit;
|
||
return showDialog<void>(
|
||
context: context,
|
||
barrierDismissible: false,
|
||
// 深色遮罩:贴合本页深蓝科技风大屏(不透默认 Material 黑半透)。
|
||
barrierColor: PvColors.bgDeepest.withValues(alpha: 0.55),
|
||
builder: (dialogContext) {
|
||
Future<void> respond(bool agreed) async {
|
||
final targetDevice = cubit.state.targetDevice;
|
||
if (targetDevice != null) {
|
||
await cubit.confirmPermissionResponse(
|
||
targetDevice.deviceName,
|
||
'app',
|
||
agreed,
|
||
);
|
||
} else {
|
||
debugPrint('❌ [PV遥控][权限交接] targetDevice 为空,无法响应');
|
||
}
|
||
// 先复位标志位再关闭,避免 pop 后上下文失效。
|
||
cubit.resetPermissionCoolDown();
|
||
cubit.togglePermissionDialog(false);
|
||
if (dialogContext.mounted && Navigator.canPop(dialogContext)) {
|
||
Navigator.pop(dialogContext);
|
||
}
|
||
}
|
||
|
||
final title = AppLocalizations.of(
|
||
dialogContext,
|
||
).translate('remote_control.permission_request_title');
|
||
final refuseText = AppLocalizations.of(
|
||
dialogContext,
|
||
).translate('remote_control.refuse');
|
||
final agreeText = AppLocalizations.of(
|
||
dialogContext,
|
||
).translate('remote_control.agree');
|
||
// 样式适配本页大屏:深蓝卡片 + 青色描边 + 科技青主按钮(与远程
|
||
// 遥控页同一交互/文案,仅视觉风格跟随 pv 主题)。
|
||
return Dialog(
|
||
backgroundColor: PvColors.card,
|
||
surfaceTintColor: Colors.transparent,
|
||
shape: RoundedRectangleBorder(
|
||
borderRadius: BorderRadius.circular(16),
|
||
side: const BorderSide(color: PvColors.cardBorder, width: 1),
|
||
),
|
||
insetPadding: const EdgeInsets.symmetric(
|
||
horizontal: 60,
|
||
vertical: 24,
|
||
),
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(22, 20, 22, 12),
|
||
child: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Row(
|
||
children: [
|
||
const Icon(
|
||
Icons.swap_horiz,
|
||
color: PvColors.accent,
|
||
size: 20,
|
||
),
|
||
const SizedBox(width: 8),
|
||
Expanded(
|
||
child: Text(
|
||
title,
|
||
style: PvType.cardTitle.copyWith(fontSize: 16),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
const SizedBox(height: 12),
|
||
Text(
|
||
dialogContent,
|
||
style: PvType.body.copyWith(color: PvColors.textSecondary),
|
||
),
|
||
const SizedBox(height: 16),
|
||
Row(
|
||
mainAxisAlignment: MainAxisAlignment.end,
|
||
children: [
|
||
TextButton(
|
||
onPressed: () => respond(false),
|
||
child: Text(
|
||
refuseText,
|
||
style: PvType.body.copyWith(
|
||
color: PvColors.textSecondary,
|
||
),
|
||
),
|
||
),
|
||
const SizedBox(width: 6),
|
||
TextButton(
|
||
onPressed: () => respond(true),
|
||
style: TextButton.styleFrom(
|
||
backgroundColor: PvColors.accent,
|
||
foregroundColor: PvColors.bgDeepest,
|
||
padding: const EdgeInsets.symmetric(horizontal: 18),
|
||
shape: RoundedRectangleBorder(
|
||
borderRadius: BorderRadius.circular(8),
|
||
),
|
||
),
|
||
child: Text(
|
||
agreeText,
|
||
style: PvType.body.copyWith(
|
||
color: PvColors.bgDeepest,
|
||
fontWeight: FontWeight.w700,
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
},
|
||
);
|
||
}
|
||
|
||
/// 设置面板(底部弹出,遮罩半透明可透视下方视频边调边看):
|
||
/// 视频源 / 视频展示 / 模拟障碍物信息 / 倒车影像。
|
||
void _openSettings() {
|
||
showModalBottomSheet<void>(
|
||
context: context,
|
||
backgroundColor: Colors.transparent,
|
||
// 面板内部自带 maxHeight + 滚动,这里放开模态默认高度限制
|
||
isScrollControlled: true,
|
||
// 横屏底部有手势条 / 虚拟键:避开安全区,否则最后一行会被压住
|
||
useSafeArea: true,
|
||
// 薄遮罩:能看见底下视频与告警/倒车效果的变化
|
||
barrierColor: Colors.black.withValues(alpha: 0.35),
|
||
builder: (_) {
|
||
// 模态挂在 Overlay 上,页面 setState 不会刷新它,
|
||
// 用 StatefulBuilder 让药丸/开关的选中态即时回显。
|
||
return StatefulBuilder(
|
||
builder: (sheetCtx, setSheetState) {
|
||
void update(void Function() fn) {
|
||
setState(fn); // 页面状态:视频链路 / 成套特效开关立即生效
|
||
setSheetState(() {}); // 面板选中态回显
|
||
}
|
||
|
||
return PvSettingsSheet(
|
||
// 手动控制 HUD 用浅色玻璃皮肤,普通态大屏仍用原深色面板
|
||
light: _mode == PvViewMode.manualControl,
|
||
videoSource: _videoSource,
|
||
videoFit: _videoFit,
|
||
simObstacle: _simObstacle,
|
||
simReverse: _simReverse,
|
||
showJoysticks: _showJoysticks,
|
||
onVideoSourceChanged: (v) => update(() => _videoSource = v),
|
||
onVideoFitChanged: (v) => update(() => _videoFit = v),
|
||
onSimObstacleChanged: (v) => update(() => _simObstacle = v),
|
||
// 倒车影像:不靠面板回传的 value 取反(面板是独立 Route,
|
||
// value 可能是上一帧的旧值,会导致点了“关”实际又传回 true),
|
||
// 直接按页面当前状态取反,保证每次点击一定翻转。
|
||
onSimReverseChanged: (_) =>
|
||
update(() => _simReverse = !_simReverse),
|
||
onShowJoysticksChanged: (v) => update(() => _showJoysticks = v),
|
||
);
|
||
},
|
||
);
|
||
},
|
||
);
|
||
}
|
||
|
||
Future<void> _onScreenshot() async {
|
||
final bytes = await _captureVideoBytes();
|
||
if (bytes == null) {
|
||
if (mounted) {
|
||
CapsuleToast.show(
|
||
AppLocalizations.of(
|
||
context,
|
||
).translate('pv_control.toast_screenshot_failed'),
|
||
showCheck: false,
|
||
);
|
||
}
|
||
return;
|
||
}
|
||
final path = await _saveToAppDir(bytes);
|
||
if (!mounted) return;
|
||
if (path != null) {
|
||
CapsuleToast.show(
|
||
AppLocalizations.of(
|
||
context,
|
||
).translate('pv_control.toast_screenshot_saved'),
|
||
);
|
||
}
|
||
// 截图后弹出预览
|
||
await showDialog<void>(
|
||
context: context,
|
||
builder: (ctx) => _ScreenshotPreviewDialog(imageBytes: bytes, path: path),
|
||
);
|
||
}
|
||
|
||
/// 截取视频区像素
|
||
Future<Uint8List?> _captureVideoBytes() async {
|
||
try {
|
||
final boundary =
|
||
_videoKey.currentContext?.findRenderObject()
|
||
as RenderRepaintBoundary?;
|
||
if (boundary == null) return null;
|
||
final ui.Image image = await boundary.toImage(pixelRatio: 2.0);
|
||
final ByteData? byteData = await image.toByteData(
|
||
format: ui.ImageByteFormat.png,
|
||
);
|
||
image.dispose();
|
||
return byteData?.buffer.asUint8List();
|
||
} catch (e) {
|
||
debugPrint('❌ [PvControl] 截图异常: $e');
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/// 保存到应用文档目录(无需相册权限,稳定可用)
|
||
Future<String?> _saveToAppDir(Uint8List bytes) async {
|
||
try {
|
||
final dir = await getApplicationDocumentsDirectory();
|
||
final ts = DateTime.now().millisecondsSinceEpoch;
|
||
final file = File('${dir.path}/pv_capture_$ts.png');
|
||
await file.writeAsBytes(bytes);
|
||
return file.path;
|
||
} catch (e) {
|
||
debugPrint('❌ [PvControl] 保存截图失败: $e');
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/// 按当前视频链路挂载对应的 cubit:页面级**单实例**,普通态与全屏 HUD 共用
|
||
/// (RTSP/UVC 都是独占硬件会话,禁止双实例)。新增链路在这里注册一个分支。
|
||
Widget _wrapVideoProvider(Widget child) {
|
||
switch (_videoSource) {
|
||
case PvVideoSource.usbCamera:
|
||
return BlocProvider(
|
||
// key:视频源切换时强制重建 cubit(新 UVC 会话 / 重新发现拉流)
|
||
key: const ValueKey('videoProvider_usbCamera'),
|
||
create: (_) => UsbCameraCubit(UvcCameraService())..start(),
|
||
child: child,
|
||
);
|
||
case PvVideoSource.localRtsp:
|
||
return BlocProvider(
|
||
key: const ValueKey('videoProvider_localRtsp'),
|
||
// autoPlayFirst=发现后自动拉第一路(不展示步骤),
|
||
// autoRecover=缓冲卡死(0%)/断流时自动重拉流。
|
||
create: (_) =>
|
||
LocalCameraCubit(autoPlayFirst: true, autoRecover: true)..start(),
|
||
child: child,
|
||
);
|
||
case PvVideoSource.webrtc:
|
||
return child;
|
||
}
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) => ControlModeEntryGate(
|
||
key: ValueKey('remote-mode/${widget.deviceId}'),
|
||
deviceId: widget.deviceId,
|
||
deviceName: widget.deviceName,
|
||
target: ControlModeTarget.remote,
|
||
onReady: _startControl,
|
||
child: _buildPage(context),
|
||
);
|
||
|
||
Widget _buildPage(BuildContext context) {
|
||
return Scaffold(
|
||
backgroundColor: PvColors.bgDeepest,
|
||
body: DecoratedBox(
|
||
decoration: const BoxDecoration(gradient: PvColors.pageGradient),
|
||
child: SafeArea(
|
||
// 左上只是圆形摄像头挖孔,无实质内容,直接占用:
|
||
// 去掉左右安全区内边距,内容铺满整宽、在物理屏幕正中,不再被挖孔顶出一段空白。
|
||
left: false,
|
||
right: false,
|
||
child: _wrapVideoProvider(
|
||
StreamBuilder<RemoteControlState>(
|
||
initialData: _cubit.state,
|
||
stream: _cubit.stream,
|
||
builder: (context, remoteSnap) {
|
||
// 当前选中的设备名(顶栏 / 信息卡 / HUD 同源)
|
||
final deviceName = _resolveDeviceName(remoteSnap.data);
|
||
return BlocBuilder<DeviceStatusBloc, DeviceStatusState>(
|
||
builder: (context, dsState) {
|
||
final telemetry = _resolveTelemetry(dsState, deviceName);
|
||
return _mode == PvViewMode.manualControl
|
||
? PvManualControlView(
|
||
streamUrl: _streamUrl,
|
||
telemetry: telemetry,
|
||
onCollapse: _onCollapseManual,
|
||
onEmergencyStop: _onEmergencyStop,
|
||
videoSource: _videoSource,
|
||
videoFit: _videoFit,
|
||
simReverse: _simReverse,
|
||
showJoysticks: _showJoysticks,
|
||
deviceSn: widget.deviceId,
|
||
deviceName: deviceName,
|
||
onSettings: _openSettings,
|
||
channel: _channel,
|
||
)
|
||
: _buildNormalLayout(telemetry, deviceName);
|
||
},
|
||
);
|
||
},
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _buildNormalLayout(PvTelemetry telemetry, String deviceName) {
|
||
// ===== 三行高度比例:顶部导航 : 第一行(视频+右列) : 第二行(控制栏) =====
|
||
// 三行高度比例:顶部导航 : 第一行 : 第二行。Expanded 的 flex 只能是整数,
|
||
// 这里写成 2 : 14 : 6(即 1 : 7 : 3)。第二行比 2.5 份再多一点,
|
||
// 好让较大的急停圆钮 + 文字竖着也能放得下,不再底部溢出。想要更矮就把 6 调回 5。
|
||
const navFlex = 2;
|
||
const rowFlex = 14;
|
||
const barFlex = 6;
|
||
// =================================================================
|
||
return Column(
|
||
children: [
|
||
// ① 顶部导航
|
||
Expanded(
|
||
flex: navFlex,
|
||
child: _PvTopNav(
|
||
deviceName: deviceName,
|
||
onBack: () => Navigator.of(context).pop(),
|
||
onSettings: _openSettings,
|
||
),
|
||
),
|
||
// ② 第一行:实时视频 + 右侧列(信息 / 地图)
|
||
Expanded(
|
||
flex: rowFlex,
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(14, 6, 14, 6),
|
||
child: LayoutBuilder(
|
||
builder: (context, constraints) {
|
||
// 右侧列宽度:约占 34%,并限制在 260~460 之间
|
||
final rightWidth = (constraints.maxWidth * 0.34).clamp(
|
||
260.0,
|
||
460.0,
|
||
);
|
||
return Row(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
// 第一行左:实时视频(可截图)
|
||
Expanded(
|
||
child: RepaintBoundary(
|
||
key: _videoKey,
|
||
child: PvVideoArea(
|
||
streamUrl: _streamUrl,
|
||
telemetry: telemetry,
|
||
onScreenshot: _onScreenshot,
|
||
onFullscreen: _onManualControl,
|
||
onLocate: _onLocate,
|
||
videoSource: _videoSource,
|
||
videoFit: _videoFit,
|
||
),
|
||
),
|
||
),
|
||
const SizedBox(width: 8),
|
||
// 第一行右:信息列 / 地图(可切换)
|
||
SizedBox(
|
||
width: rightWidth,
|
||
child: _showMap
|
||
? PvWorkMap(deviceSn: widget.deviceId)
|
||
: PvInfoColumn(telemetry: telemetry),
|
||
),
|
||
],
|
||
);
|
||
},
|
||
),
|
||
),
|
||
),
|
||
// ③ 第二行:控制栏
|
||
Expanded(
|
||
flex: barFlex,
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(14, 6, 14, 10),
|
||
child: PvControlBar(
|
||
onManualControl: _onManualControl,
|
||
onPauseTask: _onPauseTask,
|
||
onEmergencyStop: _onEmergencyStop,
|
||
onScreenshot: _onScreenshot,
|
||
onViewMap: _onViewMap,
|
||
mapActive: _showMap,
|
||
),
|
||
),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
}
|
||
|
||
/// 顶部导航栏:左侧返回、中间标题/副标题、右侧设置与更多
|
||
class _PvTopNav extends StatelessWidget {
|
||
const _PvTopNav({
|
||
required this.deviceName,
|
||
required this.onBack,
|
||
required this.onSettings,
|
||
});
|
||
|
||
/// 当前选中的设备名(副标题位置展示)
|
||
final String deviceName;
|
||
final VoidCallback onBack;
|
||
final VoidCallback onSettings;
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
// 不再固定高度,随 _buildNormalLayout 中 navFlex 分配到的带状高度自动撑满,
|
||
// Row 默认垂直居中,内容在带内居中显示。
|
||
return Row(
|
||
children: [
|
||
IconButton(
|
||
onPressed: onBack,
|
||
visualDensity: VisualDensity.compact,
|
||
padding: EdgeInsets.zero,
|
||
constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
|
||
icon: const Icon(
|
||
Icons.chevron_left,
|
||
color: PvColors.textPrimary,
|
||
size: 26,
|
||
),
|
||
),
|
||
Expanded(
|
||
child: Column(
|
||
mainAxisAlignment: MainAxisAlignment.center,
|
||
children: [
|
||
Text(
|
||
AppLocalizations.of(
|
||
context,
|
||
).translate('pv_control.realtime_video'),
|
||
style: PvType.navTitle,
|
||
),
|
||
Text(
|
||
// 当前控制的是哪台设备(原先这里是写死的“光伏电站机器人远程遥控”)
|
||
deviceName,
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: PvType.navSubtitle,
|
||
),
|
||
],
|
||
),
|
||
),
|
||
IconButton(
|
||
onPressed: onSettings,
|
||
visualDensity: VisualDensity.compact,
|
||
padding: EdgeInsets.zero,
|
||
constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
|
||
icon: const Icon(
|
||
Icons.settings,
|
||
color: PvColors.textSecondary,
|
||
size: 20,
|
||
),
|
||
),
|
||
IconButton(
|
||
onPressed: () {},
|
||
visualDensity: VisualDensity.compact,
|
||
padding: EdgeInsets.zero,
|
||
constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
|
||
icon: const Icon(
|
||
Icons.more_horiz,
|
||
color: PvColors.textSecondary,
|
||
size: 20,
|
||
),
|
||
),
|
||
const SizedBox(width: 4),
|
||
],
|
||
);
|
||
}
|
||
}
|
||
|
||
/// 截图预览弹窗
|
||
class _ScreenshotPreviewDialog extends StatelessWidget {
|
||
const _ScreenshotPreviewDialog({required this.imageBytes, this.path});
|
||
final Uint8List imageBytes;
|
||
final String? path;
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
return Dialog(
|
||
backgroundColor: PvColors.card,
|
||
insetPadding: const EdgeInsets.all(40),
|
||
child: Padding(
|
||
padding: const EdgeInsets.all(16),
|
||
child: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
Expanded(
|
||
child: InteractiveViewer(
|
||
child: Image.memory(imageBytes, fit: BoxFit.contain),
|
||
),
|
||
),
|
||
if (path != null) ...[
|
||
const SizedBox(height: 10),
|
||
Text(
|
||
AppLocalizations.of(context)
|
||
.translate('pv_control.screenshot_saved_path')
|
||
.replaceAll('{path}', path!),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: PvType.label,
|
||
),
|
||
],
|
||
const SizedBox(height: 12),
|
||
Row(
|
||
mainAxisAlignment: MainAxisAlignment.end,
|
||
children: [
|
||
TextButton(
|
||
onPressed: () => Navigator.of(context).pop(),
|
||
child: Text(
|
||
AppLocalizations.of(context).translate('pv_control.close'),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
}
|