From 739d588a164923cb4213525389ca381e769f0b81 Mon Sep 17 00:00:00 2001 From: Songzex <2402265378@qq.com> Date: Sat, 21 Nov 2026 14:52:13 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=A5=E5=85=A5=E5=A3=B0=E7=BD=91=E5=9B=9B?= =?UTF-8?q?=E8=B7=AF=E8=A7=86=E9=A2=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets/languages/en-US.json | 1 + assets/languages/zh-CN.json | 1 + docs/pv_agora_video_demo.md | 26 + lib/core/consts/http_api_consts.dart | 5 + lib/core/di/injection.dart | 15 + lib/core/network/dio_client.dart | 37 +- .../pv_agora_remote_datasource.dart | 135 ++++++ .../pv_agora_repository_impl.dart | 40 ++ .../repositories/pv_agora_repository.dart | 9 + .../get_pv_agora_credentials_usecase.dart | 17 + .../start_pv_agora_video_stream_usecase.dart | 16 + .../domain/video/pv_agora_config.dart | 49 ++ .../domain/video/pv_agora_credentials.dart | 11 + .../domain/video/pv_camera_direction.dart | 10 + .../presentation/models/pv_video_source.dart | 8 +- .../presentation/pages/pv_control_page.dart | 69 ++- .../presentation/video/pv_agora_scope.dart | 17 + .../presentation/video/pv_agora_session.dart | 193 ++++++++ .../widgets/pv_agora_config_dialog.dart | 269 +++++++++++ .../presentation/widgets/pv_camera_view.dart | 172 +++++++ .../widgets/pv_manual_control_view.dart | 84 +++- .../widgets/pv_rear_view_card.dart | 8 +- .../widgets/pv_settings_sheet.dart | 1 + .../presentation/widgets/pv_video_area.dart | 4 + .../widgets/pv_video_fit_box.dart | 4 +- test/pv_agora_video_test.dart | 451 ++++++++++++++++++ 26 files changed, 1637 insertions(+), 15 deletions(-) create mode 100644 docs/pv_agora_video_demo.md create mode 100644 lib/features/pv_control/data/datasources/pv_agora_remote_datasource.dart create mode 100644 lib/features/pv_control/data/repositories/pv_agora_repository_impl.dart create mode 100644 lib/features/pv_control/domain/repositories/pv_agora_repository.dart create mode 100644 lib/features/pv_control/domain/usecases/get_pv_agora_credentials_usecase.dart create mode 100644 lib/features/pv_control/domain/usecases/start_pv_agora_video_stream_usecase.dart create mode 100644 lib/features/pv_control/domain/video/pv_agora_config.dart create mode 100644 lib/features/pv_control/domain/video/pv_agora_credentials.dart create mode 100644 lib/features/pv_control/domain/video/pv_camera_direction.dart create mode 100644 lib/features/pv_control/presentation/video/pv_agora_scope.dart create mode 100644 lib/features/pv_control/presentation/video/pv_agora_session.dart create mode 100644 lib/features/pv_control/presentation/widgets/pv_agora_config_dialog.dart create mode 100644 lib/features/pv_control/presentation/widgets/pv_camera_view.dart create mode 100644 test/pv_agora_video_test.dart diff --git a/assets/languages/en-US.json b/assets/languages/en-US.json index f054bb1a..4c469f51 100644 --- a/assets/languages/en-US.json +++ b/assets/languages/en-US.json @@ -567,6 +567,7 @@ "set_source_rtsp": "Ethernet RTSP", "set_source_hdmi": "HDMI", "set_source_webrtc": "WebRTC", + "set_source_agora": "Agora RTC", "set_video_fit": "Display", "set_fit_contain": "Fit", "set_fit_cover": "Fill", diff --git a/assets/languages/zh-CN.json b/assets/languages/zh-CN.json index 7a302484..f0c7a407 100644 --- a/assets/languages/zh-CN.json +++ b/assets/languages/zh-CN.json @@ -570,6 +570,7 @@ "set_source_rtsp": "以太网 RTSP 源", "set_source_hdmi": "HDMI", "set_source_webrtc": "WebRTC", + "set_source_agora": "声网 RTC", "set_video_fit": "视频展示", "set_fit_contain": "完整显示", "set_fit_cover": "铺满屏幕", diff --git a/docs/pv_agora_video_demo.md b/docs/pv_agora_video_demo.md new file mode 100644 index 00000000..d576d5b6 --- /dev/null +++ b/docs/pv_agora_video_demo.md @@ -0,0 +1,26 @@ +# 远程遥控:声网 RTC(Demo) + +## 实测 + +1. 进入远程遥控,打开设置,点击「声网 RTC(Demo)」。 +2. 配置弹窗默认填入提供的 App ID、cam2-17 频道、临时 Token;前/左/后/右 UID 分别为 101/102/103/104。可分别修改。观看端 UID 默认 0;如果 Token 绑定了观看端 UID,填写该 UID,不能使用摄像头的 UID。 +3. 点击「保存并连接」。取消则保留原视频源。再次点击此选项可修改配置或重连;临时 Token 失效时在这里替换。 +4. 主画面默认前视,双击视频空白区域切换后视,再双击切回。手动遥控左侧小卡显示另一视角,全屏按钮也可切换。 +5. 手动遥控点击原有「视频」键打开左右悬浮窗,分别应为 UID 102 和 104,可拖动;再次点击收起。 +6. 某路摄像头关闭时,仅该路显示等待信息;其它视角应继续播放。切换到其它视频源或退出遥控会释放 RTC 连接。 + +本次配置只保留在当前遥控页面。Demo 频道不会按车辆 SN 自动匹配;实测需核对频道中的画面是否属于目标车辆。临时 Token 的有效期取决于签发端,不代表配置有误。 + +## 扩展位置 + +- `domain/video/pv_camera_direction.dart`:与传输方式无关的前、左、后、右摄像头标识。 +- `domain/video/pv_agora_config.dart`:声网连接参数、UID 映射及校验,Demo 默认值独立集中管理。 +- `presentation/video/pv_agora_session.dart`:页面共享的单引擎/单频道会话,作为观众订阅视频,不发布摄像头和麦克风。异步重连、退出和释放按队列串行执行,旧连接回调不能更新新会话。 +- `presentation/widgets/pv_camera_view.dart`:视频源与摄像头方向的渲染入口。新的多路视频源可复用同一方向模型,通过 `PvVideoSource.hasDirectionalViews` 声明能力,再注册对应的会话及渲染分支。 +- `presentation/widgets/pv_agora_config_dialog.dart`:配置表单,不拥有连接;保存后交给页面会话连接,取消无副作用。 + +前后切换、左右浮窗不会创建新的 RTC 连接。其它视频源保留原来的播放与裁切逻辑,现有概览 Demo 不作修改。 + +## 本地验证 + +`test/pv_agora_video_test.dart` 使用模拟 RTC 引擎,覆盖共享观众会话与四路状态、快速重连的释放顺序与旧回调隔离、前后双击、配置校验/保存/取消,不连接真实频道。真实视频与浮窗合成效果仍需手机实测。 diff --git a/lib/core/consts/http_api_consts.dart b/lib/core/consts/http_api_consts.dart index d4adad72..76fa28f0 100644 --- a/lib/core/consts/http_api_consts.dart +++ b/lib/core/consts/http_api_consts.dart @@ -60,6 +60,11 @@ class HttpApiConsts { // 一键寻车(GET,query 参数 deviceId = 设备编码 MC700-…,不是数字主键) static String get hostSearchDevice => "$baseUrl/iot/host/searchDevice"; + static const hostAgoraTokenPath = '/iot/host/getAgoraToken'; + static String get hostAgoraToken => '$baseUrl$hostAgoraTokenPath'; + static const hostStartVideoStreamPath = '/iot/host/startVideoStream'; + static String get hostStartVideoStream => '$baseUrl$hostStartVideoStreamPath'; + // GET,2=自主任务,3=远程遥控;路径 modeChage 沿用后端协议拼写。 static String get hostModeChange => "$baseUrl/iot/host/modeChage"; diff --git a/lib/core/di/injection.dart b/lib/core/di/injection.dart index d678fd34..a3b341ac 100644 --- a/lib/core/di/injection.dart +++ b/lib/core/di/injection.dart @@ -30,6 +30,11 @@ import '../../features/device_control_mode/data/datasources/control_mode_remote_ import '../../features/device_control_mode/data/repositories/device_control_mode_repository_impl.dart'; import '../../features/device_control_mode/domain/repositories/device_control_mode_repository.dart'; import '../../features/device_control_mode/domain/usecases/device_control_mode_usecases.dart'; +import '../../features/pv_control/data/datasources/pv_agora_remote_datasource.dart'; +import '../../features/pv_control/data/repositories/pv_agora_repository_impl.dart'; +import '../../features/pv_control/domain/repositories/pv_agora_repository.dart'; +import '../../features/pv_control/domain/usecases/get_pv_agora_credentials_usecase.dart'; +import '../../features/pv_control/domain/usecases/start_pv_agora_video_stream_usecase.dart'; import 'package:flutter/widgets.dart'; import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; @@ -782,6 +787,16 @@ Future init() async { sl.registerLazySingleton( () => ChangeDeviceControlModeUseCase(sl()), ); + sl.registerLazySingleton(() => PvAgoraRemoteDataSource(sl())); + sl.registerLazySingleton( + () => PvAgoraRepositoryImpl(sl()), + ); + sl.registerLazySingleton( + () => GetPvAgoraCredentialsUseCase(sl()), + ); + sl.registerLazySingleton( + () => StartPvAgoraVideoStreamUseCase(sl()), + ); sl.registerLazySingleton( () => RegionRemoteDatasource(sl(), sl()), ); diff --git a/lib/core/network/dio_client.dart b/lib/core/network/dio_client.dart index fa70c852..03b293dd 100644 --- a/lib/core/network/dio_client.dart +++ b/lib/core/network/dio_client.dart @@ -30,7 +30,7 @@ class DioClient { ); dio.interceptors.add( - LogInterceptor( + _ApiLogInterceptor( requestBody: true, responseBody: true, requestHeader: true, @@ -96,3 +96,38 @@ class DioClient { return dio; } } + +class _ApiLogInterceptor extends LogInterceptor { + _ApiLogInterceptor({ + super.requestBody, + super.responseBody, + super.requestHeader, + }); + + bool _hasAgoraResponseLog(RequestOptions options) { + final path = options.uri.path; + return path.endsWith(HttpApiConsts.hostAgoraTokenPath) || + path.endsWith(HttpApiConsts.hostStartVideoStreamPath); + } + + @override + void onResponse( + Response response, + ResponseInterceptorHandler handler, + ) { + if (_hasAgoraResponseLog(response.requestOptions)) { + handler.next(response); + return; + } + super.onResponse(response, handler); + } + + @override + void onError(DioException error, ErrorInterceptorHandler handler) { + if (_hasAgoraResponseLog(error.requestOptions)) { + handler.next(error); + return; + } + super.onError(error, handler); + } +} diff --git a/lib/features/pv_control/data/datasources/pv_agora_remote_datasource.dart b/lib/features/pv_control/data/datasources/pv_agora_remote_datasource.dart new file mode 100644 index 00000000..7ed1e0c1 --- /dev/null +++ b/lib/features/pv_control/data/datasources/pv_agora_remote_datasource.dart @@ -0,0 +1,135 @@ +import 'dart:convert'; + +import 'package:dio/dio.dart'; +import 'package:flutter/foundation.dart'; + +import '../../../../core/consts/http_api_consts.dart'; +import '../../domain/video/pv_agora_credentials.dart'; + +class PvAgoraRemoteDataSource { + const PvAgoraRemoteDataSource(this.dio); + + final Dio dio; + + Future startVideoStream(String deviceSn) async { + final response = await _get( + HttpApiConsts.hostStartVideoStream, + deviceSn, + 'startVideoStream', + ); + final body = response.data; + if (response.statusCode != 200 || + body is! Map || + '${body['code']}' != '200' || + body['data'] == false) { + final message = body is Map ? body['msg'] : null; + throw FormatException( + message is String && message.trim().isNotEmpty + ? message.trim() + : '服务端未确认推流已开启', + ); + } + } + + Future getCredentials(String deviceSn) async { + final response = await _get( + HttpApiConsts.hostAgoraToken, + deviceSn, + 'getAgoraToken', + ); + final body = response.data; + if (body is! Map) throw const FormatException('声网配置响应格式错误'); + if (body.containsKey('code') && '${body['code']}' != '200') { + throw const FormatException('服务端未能签发声网配置,请稍后重试'); + } + final data = body.containsKey('data') ? body['data'] : body; + if (data is! Map) throw const FormatException('声网配置响应格式错误'); + + final appId = data['appId']; + final token = data['token']; + final uid = int.tryParse('${data['uid']}'.trim()); + if (appId is! String || token is! String || uid == null) { + throw const FormatException('声网配置缺少有效的 App ID、Token 或 UID'); + } + // 加入频道只需要已签发的 Token,App Certificate 由服务端使用。 + return PvAgoraCredentials( + appId: appId.trim(), + token: token.trim(), + viewerUid: uid, + ); + } + + Future> _get( + String url, + String deviceSn, + String endpoint, + ) async { + try { + final response = await dio.get( + url, + queryParameters: {'deviceId': deviceSn}, + ); + _logResponse(endpoint, deviceSn, response); + return response; + } on DioException catch (error) { + _logResponse(endpoint, deviceSn, error.response, errorType: error.type); + rethrow; + } + } + + void _logResponse( + String endpoint, + String deviceSn, + Response? response, { + DioExceptionType? errorType, + }) { + final body = response?.data; + final fields = { + 'deviceId': deviceSn, + 'httpStatus': response?.statusCode, + 'bodyType': body.runtimeType.toString(), + if (errorType != null) 'errorType': errorType.name, + 'body': _redact(_decodeForLog(body)), + }; + debugPrint('[声网配置][$endpoint] ${jsonEncode(fields)}'); + } + + Object? _decodeForLog(Object? body) { + if (body is! String) return body; + try { + final decoded = jsonDecode(body); + if (decoded is Map || decoded is List) return decoded; + } on FormatException { + // 纯文本可能包含凭据,只记录长度。 + } + return '<文本长度 ${body.length}>'; + } + + Object? _redact(Object? value) { + if (value is Map) { + return value.map((key, field) { + final name = key.toString(); + final normalized = name.toLowerCase(); + if (normalized.contains('token') || + normalized.contains('certificate') || + normalized == 'authorization') { + final masked = field is String && field.isNotEmpty + ? '<已脱敏,长度 ${field.length}>' + : field == null || field == '' + ? field + : '<已脱敏>'; + return MapEntry(name, masked); + } + return MapEntry(name, _redact(field)); + }); + } + if (value is List) return value.map(_redact).toList(); + if (value == null || + value is String || + value is bool || + (value is num && value.isFinite)) { + return value; + } + return '<${value.runtimeType}>'; + } +} diff --git a/lib/features/pv_control/data/repositories/pv_agora_repository_impl.dart b/lib/features/pv_control/data/repositories/pv_agora_repository_impl.dart new file mode 100644 index 00000000..d7c7eb15 --- /dev/null +++ b/lib/features/pv_control/data/repositories/pv_agora_repository_impl.dart @@ -0,0 +1,40 @@ +import 'package:dio/dio.dart'; +import 'package:fpdart/fpdart.dart'; + +import '../../../../core/error/failure.dart'; +import '../../../../core/network/error_handler.dart'; +import '../../domain/repositories/pv_agora_repository.dart'; +import '../../domain/video/pv_agora_credentials.dart'; +import '../datasources/pv_agora_remote_datasource.dart'; + +class PvAgoraRepositoryImpl implements PvAgoraRepository { + const PvAgoraRepositoryImpl(this.remote); + + final PvAgoraRemoteDataSource remote; + + @override + Future> startVideoStream(String deviceSn) async { + try { + await remote.startVideoStream(deviceSn); + return const Right(unit); + } on FormatException catch (error) { + return Left(ServerFailure('开启推流失败(${error.message})')); + } on DioException catch (error) { + final reason = ErrorHandler.getErrorMessage(error); + return Left(NetworkFailure('开启推流失败($reason)')); + } + } + + @override + Future> getCredentials( + String deviceSn, + ) async { + try { + return Right(await remote.getCredentials(deviceSn)); + } on FormatException catch (error) { + return Left(ServerFailure(error.message)); + } on DioException catch (error) { + return Left(NetworkFailure(ErrorHandler.getErrorMessage(error))); + } + } +} diff --git a/lib/features/pv_control/domain/repositories/pv_agora_repository.dart b/lib/features/pv_control/domain/repositories/pv_agora_repository.dart new file mode 100644 index 00000000..58a33d83 --- /dev/null +++ b/lib/features/pv_control/domain/repositories/pv_agora_repository.dart @@ -0,0 +1,9 @@ +import 'package:fpdart/fpdart.dart'; + +import '../../../../core/error/failure.dart'; +import '../video/pv_agora_credentials.dart'; + +abstract class PvAgoraRepository { + Future> startVideoStream(String deviceSn); + Future> getCredentials(String deviceSn); +} diff --git a/lib/features/pv_control/domain/usecases/get_pv_agora_credentials_usecase.dart b/lib/features/pv_control/domain/usecases/get_pv_agora_credentials_usecase.dart new file mode 100644 index 00000000..e9e81308 --- /dev/null +++ b/lib/features/pv_control/domain/usecases/get_pv_agora_credentials_usecase.dart @@ -0,0 +1,17 @@ +import 'package:fpdart/fpdart.dart'; + +import '../../../../core/error/failure.dart'; +import '../repositories/pv_agora_repository.dart'; +import '../video/pv_agora_credentials.dart'; + +class GetPvAgoraCredentialsUseCase { + const GetPvAgoraCredentialsUseCase(this.repository); + + final PvAgoraRepository repository; + + Future> call(String deviceSn) async { + final sn = deviceSn.trim(); + if (sn.isEmpty) return Left(Failure('请先选择设备')); + return repository.getCredentials(sn); + } +} diff --git a/lib/features/pv_control/domain/usecases/start_pv_agora_video_stream_usecase.dart b/lib/features/pv_control/domain/usecases/start_pv_agora_video_stream_usecase.dart new file mode 100644 index 00000000..32332c85 --- /dev/null +++ b/lib/features/pv_control/domain/usecases/start_pv_agora_video_stream_usecase.dart @@ -0,0 +1,16 @@ +import 'package:fpdart/fpdart.dart'; + +import '../../../../core/error/failure.dart'; +import '../repositories/pv_agora_repository.dart'; + +class StartPvAgoraVideoStreamUseCase { + const StartPvAgoraVideoStreamUseCase(this.repository); + + final PvAgoraRepository repository; + + Future> call(String deviceSn) async { + final sn = deviceSn.trim(); + if (sn.isEmpty) return Left(Failure('请先选择设备')); + return repository.startVideoStream(sn); + } +} diff --git a/lib/features/pv_control/domain/video/pv_agora_config.dart b/lib/features/pv_control/domain/video/pv_agora_config.dart new file mode 100644 index 00000000..936597d9 --- /dev/null +++ b/lib/features/pv_control/domain/video/pv_agora_config.dart @@ -0,0 +1,49 @@ +import 'pv_camera_direction.dart'; + +/// A single RTC channel with independently configurable camera publishers. +class PvAgoraConfig { + const PvAgoraConfig({ + required this.appId, + required this.channel, + required this.token, + this.viewerUid = 0, + this.frontUid = 101, + this.leftUid = 102, + this.rearUid = 103, + this.rightUid = 104, + }); + + final String appId; + final String channel; + final String token; + + /// 0 lets Agora assign the viewer UID. A UID-bound token needs its exact UID. + final int viewerUid; + final int frontUid; + final int leftUid; + final int rearUid; + final int rightUid; + + int uidFor(PvCameraDirection direction) => switch (direction) { + PvCameraDirection.front => frontUid, + PvCameraDirection.left => leftUid, + PvCameraDirection.rear => rearUid, + PvCameraDirection.right => rightUid, + }; + + String? validate() { + if (!RegExp(r'^[a-fA-F0-9]{32}$').hasMatch(appId)) { + return 'App ID 应为 32 位十六进制字符'; + } + if (channel.trim().isEmpty) return '请先选择设备'; + if (token.trim().isEmpty) return '请填写临时 Token'; + final uids = PvCameraDirection.values.map(uidFor).toList(); + if (uids.any((uid) => uid <= 0 || uid > 0xffffffff)) { + return '视频 UID 应为 1~4294967295 的整数'; + } + if (uids.toSet().length != uids.length) return '四路视频 UID 不能重复'; + if (viewerUid < 0 || viewerUid > 0xffffffff) return '观看端 UID 无效'; + if (uids.contains(viewerUid)) return '观看端 UID 不能与视频 UID 相同'; + return null; + } +} diff --git a/lib/features/pv_control/domain/video/pv_agora_credentials.dart b/lib/features/pv_control/domain/video/pv_agora_credentials.dart new file mode 100644 index 00000000..dc66933a --- /dev/null +++ b/lib/features/pv_control/domain/video/pv_agora_credentials.dart @@ -0,0 +1,11 @@ +class PvAgoraCredentials { + const PvAgoraCredentials({ + required this.appId, + required this.token, + required this.viewerUid, + }); + + final String appId; + final String token; + final int viewerUid; +} diff --git a/lib/features/pv_control/domain/video/pv_camera_direction.dart b/lib/features/pv_control/domain/video/pv_camera_direction.dart new file mode 100644 index 00000000..f1d9b2a5 --- /dev/null +++ b/lib/features/pv_control/domain/video/pv_camera_direction.dart @@ -0,0 +1,10 @@ +/// Camera identity is independent of transport, channel and publisher UID. +enum PvCameraDirection { + front('前视'), + left('左视'), + rear('后视'), + right('右视'); + + const PvCameraDirection(this.label); + final String label; +} diff --git a/lib/features/pv_control/presentation/models/pv_video_source.dart b/lib/features/pv_control/presentation/models/pv_video_source.dart index b840b83e..9bb16c1d 100644 --- a/lib/features/pv_control/presentation/models/pv_video_source.dart +++ b/lib/features/pv_control/presentation/models/pv_video_source.dart @@ -5,7 +5,7 @@ /// ② 在 pv_control_page 的 `_wrapVideoProvider` 注册对应 cubit(若需要); /// ③ 在 PvVideoArea / PvManualControlView 的视频层加一个渲染分支。 /// -/// 切换 UI 暂不做,由页面字段 `_videoSource` 指定当前链路。 +/// 设置面板负责选择链路;各路摄像头由 PvCameraView 统一分发。 enum PvVideoSource { /// 云端 WebRTC 流(原始方案,走 webrtc:// 地址)。 webrtc, @@ -15,4 +15,10 @@ enum PvVideoSource { /// USB 摄像头(UVC 采集卡,PlatformView 低延迟直显)。 usbCamera, + + /// 声网 RTC:同一频道按 UID 区分前、左、后、右四路。 + agoraRtc; + + /// 独立摄像头能力。未来其它链路接入多路时,在这里声明即可复用 HUD。 + bool get hasDirectionalViews => this == agoraRtc; } diff --git a/lib/features/pv_control/presentation/pages/pv_control_page.dart b/lib/features/pv_control/presentation/pages/pv_control_page.dart index 65d16b2a..41fa4a77 100644 --- a/lib/features/pv_control/presentation/pages/pv_control_page.dart +++ b/lib/features/pv_control/presentation/pages/pv_control_page.dart @@ -33,6 +33,12 @@ 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 '../../domain/usecases/get_pv_agora_credentials_usecase.dart'; +import '../../domain/usecases/start_pv_agora_video_stream_usecase.dart'; +import '../../domain/video/pv_agora_config.dart'; +import '../video/pv_agora_session.dart'; +import '../video/pv_agora_scope.dart'; +import '../widgets/pv_agora_config_dialog.dart'; import '../theme/pv_colors.dart'; import '../widgets/pv_control_bar.dart'; import '../widgets/pv_info_column.dart'; @@ -119,6 +125,11 @@ class _PvControlPageState extends State { /// 当前视频链路(多源可扩展):在设置面板「视频源」行切换, /// 切换即重建对应链路 cubit(_wrapVideoProvider 挂了 ValueKey)。 PvVideoSource _videoSource = PvVideoSource.usbCamera; + String get _deviceSn => widget.deviceId.trim(); + PvAgoraConfig? _agoraConfig; + final PvAgoraSession _agoraSession = PvAgoraSession(); + + bool _editingVideoConfig = false; /// 视频展示方式(设置面板「视频展示」行切换): /// contain 完整显示(可能留黑边)/ cover 等比铺满(裁掉边缘)。 @@ -170,6 +181,17 @@ class _PvControlPageState extends State { // 控制会话由模式确认完成后的回调建立。 } + @override + void didUpdateWidget(covariant PvControlPage oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.deviceId.trim() == _deviceSn) return; + _agoraConfig = null; + if (_videoSource == PvVideoSource.agoraRtc) { + _videoSource = PvVideoSource.usbCamera; + unawaited(_agoraSession.disconnect()); + } + } + /// 本页的视频、地图、遥测都是围绕 `deviceId` 这一台设备,所以进页时确保 /// MQTT 实时定位/路线订阅就指向它(全局单例 bloc,数据源内部同 SN 去重、 /// 自动退旧订新,重复调用无副作用)。退出页面不切回去:语义与设备列表 @@ -211,6 +233,7 @@ class _PvControlPageState extends State { @override void dispose() { + _agoraSession.dispose(); // 离开安全模式:启动 90 秒倒计时(与远程遥控页一致)。 sl().exitSafeMode(); // 取消「权限交接」弹窗监听,避免回调打到已销毁的 State。 @@ -568,7 +591,45 @@ class _PvControlPageState extends State { simObstacle: _simObstacle, simReverse: _simReverse, showJoysticks: _showJoysticks, - onVideoSourceChanged: (v) => update(() => _videoSource = v), + onVideoSourceChanged: (v) async { + if (_editingVideoConfig) return; + if (v == PvVideoSource.agoraRtc) { + final sn = _deviceSn; + if (sn.isEmpty) { + CapsuleToast.show('请先选择设备'); + return; + } + _editingVideoConfig = true; + PvAgoraConfig? config; + try { + config = await showPvAgoraConfigDialog( + sheetCtx, + _agoraConfig ?? + PvAgoraConfig(appId: '', channel: sn, token: ''), + loadCredentials: sl().call, + startVideoStream: sl().call, + ); + } finally { + _editingVideoConfig = false; + } + if (!mounted || + !sheetCtx.mounted || + config == null || + sn != _deviceSn) { + return; + } + final confirmed = config; + update(() { + _agoraConfig = confirmed; + _videoSource = v; + }); + unawaited(_agoraSession.connect(confirmed)); + } else { + if (v == _videoSource) return; + unawaited(_agoraSession.disconnect()); + update(() => _videoSource = v); + } + }, onVideoFitChanged: (v) => update(() => _videoFit = v), onSimObstacleChanged: (v) => update(() => _simObstacle = v), // 倒车影像:不靠面板回传的 value 取反(面板是独立 Route, @@ -667,6 +728,7 @@ class _PvControlPageState extends State { child: child, ); case PvVideoSource.webrtc: + case PvVideoSource.agoraRtc: return child; } } @@ -680,7 +742,10 @@ class _PvControlPageState extends State { cancelToPreview: true, emergencyStopControl: const EmergencyStopButton(), onReady: _startControl, - child: _buildPage(context), + child: PvAgoraScope( + session: _agoraSession, + child: _buildPage(context), + ), ); Widget _buildPage(BuildContext context) { diff --git a/lib/features/pv_control/presentation/video/pv_agora_scope.dart b/lib/features/pv_control/presentation/video/pv_agora_scope.dart new file mode 100644 index 00000000..88ee082b --- /dev/null +++ b/lib/features/pv_control/presentation/video/pv_agora_scope.dart @@ -0,0 +1,17 @@ +import 'package:flutter/widgets.dart'; + +import 'pv_agora_session.dart'; + +/// Page owns the session lifecycle; camera widgets listen independently so a +/// video event never rebuilds the vehicle controls or the whole HUD. +class PvAgoraScope extends InheritedWidget { + const PvAgoraScope({super.key, required this.session, required super.child}); + final PvAgoraSession session; + + static PvAgoraSession of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()!.session; + + @override + bool updateShouldNotify(PvAgoraScope oldWidget) => + session != oldWidget.session; +} diff --git a/lib/features/pv_control/presentation/video/pv_agora_session.dart b/lib/features/pv_control/presentation/video/pv_agora_session.dart new file mode 100644 index 00000000..cabf8ab6 --- /dev/null +++ b/lib/features/pv_control/presentation/video/pv_agora_session.dart @@ -0,0 +1,193 @@ +import 'dart:async'; + +import 'package:agora_rtc_engine/agora_rtc_engine.dart' as agora; +import 'package:flutter/foundation.dart'; + +import '../../domain/video/pv_agora_config.dart'; + +/// One engine / one channel per remote-control page. All camera views share it. +/// Lifecycle operations are serialized so rapid source/config changes cannot +/// initialize another engine before the previous one has finished releasing. +class PvAgoraSession extends ChangeNotifier { + PvAgoraSession({agora.RtcEngine Function()? createEngine}) + : _createEngine = createEngine ?? agora.createAgoraRtcEngine; + + final agora.RtcEngine Function() _createEngine; + agora.RtcEngine? _engine; + agora.RtcEngineEventHandler? _handler; + Future _pending = Future.value(); + Timer? _timeout; + int _generation = 0; + bool _disposed = false; + bool joined = false; + String? message; + String? tokenWarning; + PvAgoraConfig? config; + final Map _videoStates = {}; + + agora.RtcEngine? get engine => _engine; + int get generation => _generation; + bool hasVideo(int uid) => + joined && + _videoStates[uid] == agora.RemoteVideoState.remoteVideoStateDecoding; + + void _notify() { + if (!_disposed) notifyListeners(); + } + + Future connect(PvAgoraConfig next) { + final validation = next.validate(); + if (validation != null) return Future.error(ArgumentError(validation)); + final generation = ++_generation; + config = next; + joined = false; + message = '正在连接声网频道…'; + tokenWarning = null; + _videoStates.clear(); + _timeout?.cancel(); + _notify(); + return _pending = _pending.then((_) async { + await _release(); + if (_disposed || generation != _generation) return; + bool current() => !_disposed && generation == _generation; + try { + final engine = _createEngine(); + _engine = engine; + await engine.initialize( + agora.RtcEngineContext( + appId: next.appId, + channelProfile: + agora.ChannelProfileType.channelProfileLiveBroadcasting, + ), + ); + if (!current()) return; + await engine.enableVideo(); + await engine.enableLocalVideo(false); + await engine.enableLocalAudio(false); + if (!current()) return; + final handler = agora.RtcEngineEventHandler( + onJoinChannelSuccess: (_, _) { + if (!current()) return; + joined = true; + message = null; + _timeout?.cancel(); + _notify(); + }, + onUserOffline: (_, uid, reason) { + if (!current()) return; + _videoStates.remove(uid); + _notify(); + }, + onRemoteVideoStateChanged: (_, uid, state, reason, elapsed) { + if (!current()) return; + _videoStates[uid] = state; + _notify(); + }, + onConnectionStateChanged: (_, state, reason) { + if (!current()) return; + if (state == agora.ConnectionStateType.connectionStateConnected) { + joined = true; + message = null; + _timeout?.cancel(); + } else { + joined = false; + _videoStates.clear(); + message = state == agora.ConnectionStateType.connectionStateFailed + ? '声网连接失败,请核对配置和 Token' + : '声网连接中断,正在重新连接…'; + } + _notify(); + }, + onTokenPrivilegeWillExpire: (_, token) { + if (!current()) return; + tokenWarning = 'Token 即将过期,请在视频源设置中更新'; + _notify(); + }, + onRequestToken: (_) { + if (!current()) return; + joined = false; + _videoStates.clear(); + message = 'Token 已过期,请在视频源设置中更新'; + _notify(); + }, + onError: (error, detail) { + if (!current()) return; + joined = false; + _videoStates.clear(); + // SDK details can contain credentials; never display/log them. + message = '声网连接异常(${error.value()}),请核对配置和 Token'; + _timeout?.cancel(); + _notify(); + }, + ); + _handler = handler; + engine.registerEventHandler(handler); + _timeout = Timer(const Duration(seconds: 15), () { + if (!current() || joined) return; + message = '连接超时,请检查网络或在视频源设置中更新 Token 后重试'; + _notify(); + }); + await engine.joinChannel( + token: next.token, + channelId: next.channel, + uid: next.viewerUid, + options: const agora.ChannelMediaOptions( + clientRoleType: agora.ClientRoleType.clientRoleAudience, + autoSubscribeVideo: true, + autoSubscribeAudio: false, + publishCameraTrack: false, + publishMicrophoneTrack: false, + ), + ); + } catch (_) { + if (current()) { + _timeout?.cancel(); + joined = false; + message = '声网连接失败,请检查配置、网络及 Token 有效期'; + _notify(); + } + await _release(); + } + }); + } + + Future disconnect() { + ++_generation; + _timeout?.cancel(); + joined = false; + message = null; + _videoStates.clear(); + _notify(); + return _pending = _pending.then((_) => _release()); + } + + Future _release() async { + final engine = _engine; + final handler = _handler; + _engine = null; + _handler = null; + if (engine == null) return; + try { + if (handler != null) engine.unregisterEventHandler(handler); + } catch (_) { + /* Still release if unregistering fails. */ + } + try { + await engine.leaveChannel(); + } catch (_) { + /* An engine that never joined still needs releasing. */ + } + try { + await engine.release(); + } catch (_) { + /* No UI callbacks during teardown. */ + } + } + + @override + void dispose() { + _disposed = true; + unawaited(disconnect()); + super.dispose(); + } +} diff --git a/lib/features/pv_control/presentation/widgets/pv_agora_config_dialog.dart b/lib/features/pv_control/presentation/widgets/pv_agora_config_dialog.dart new file mode 100644 index 00000000..6d40db7f --- /dev/null +++ b/lib/features/pv_control/presentation/widgets/pv_agora_config_dialog.dart @@ -0,0 +1,269 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fpdart/fpdart.dart' show Either, Unit; + +import '../../../../core/error/failure.dart'; +import '../../domain/video/pv_agora_config.dart'; +import '../../domain/video/pv_agora_credentials.dart'; +import '../../domain/video/pv_camera_direction.dart'; + +typedef PvAgoraCredentialsLoader = + Future> Function(String deviceSn); +typedef PvAgoraStreamStarter = + Future> Function(String deviceSn); + +Future showPvAgoraConfigDialog( + BuildContext context, + PvAgoraConfig config, { + required PvAgoraCredentialsLoader loadCredentials, + required PvAgoraStreamStarter startVideoStream, +}) => showDialog( + context: context, + builder: (_) => _AgoraConfigDialog( + initial: config, + loadCredentials: loadCredentials, + startVideoStream: startVideoStream, + ), +); + +class _AgoraConfigDialog extends StatefulWidget { + const _AgoraConfigDialog({ + required this.initial, + required this.loadCredentials, + required this.startVideoStream, + }); + + final PvAgoraConfig initial; + final PvAgoraCredentialsLoader loadCredentials; + final PvAgoraStreamStarter startVideoStream; + + @override + State<_AgoraConfigDialog> createState() => _AgoraConfigDialogState(); +} + +class _AgoraConfigDialogState extends State<_AgoraConfigDialog> { + late final _appId = TextEditingController(text: widget.initial.appId); + late final _channel = TextEditingController(text: widget.initial.channel); + late final _token = TextEditingController(text: widget.initial.token); + late final _viewer = TextEditingController( + text: '${widget.initial.viewerUid}', + ); + late final _uids = { + for (final direction in PvCameraDirection.values) + direction: TextEditingController( + text: '${widget.initial.uidFor(direction)}', + ), + }; + String? _error; + String? _streamMessage; + bool _showToken = false; + bool _loading = false; + bool _startingStream = false; + + @override + void dispose() { + for (final controller in [ + _appId, + _channel, + _token, + _viewer, + ..._uids.values, + ]) { + controller.dispose(); + } + super.dispose(); + } + + PvAgoraConfig _buildConfig([PvAgoraCredentials? credentials]) { + int uid(PvCameraDirection d) => int.tryParse(_uids[d]!.text.trim()) ?? -1; + return PvAgoraConfig( + appId: credentials?.appId ?? _appId.text.trim(), + channel: widget.initial.channel, + token: credentials?.token ?? _token.text.trim(), + viewerUid: + credentials?.viewerUid ?? (int.tryParse(_viewer.text.trim()) ?? -1), + frontUid: uid(PvCameraDirection.front), + leftUid: uid(PvCameraDirection.left), + rearUid: uid(PvCameraDirection.rear), + rightUid: uid(PvCameraDirection.right), + ); + } + + bool _validate(PvAgoraConfig config) { + final error = config.validate(); + if (error == null) return true; + setState(() => _error = error); + return false; + } + + void _connectManually() { + if (_loading) return; + final config = _buildConfig(); + if (_validate(config)) Navigator.of(context).pop(config); + } + + Future _fetchAndConnect() async { + if (_loading) return; + setState(() { + _loading = true; + _error = null; + }); + final result = await widget.loadCredentials(widget.initial.channel); + if (!mounted) return; + setState(() => _loading = false); + if (ModalRoute.of(context)?.isCurrent != true) return; + result.match((failure) => setState(() => _error = failure.message), ( + credentials, + ) { + final config = _buildConfig(credentials); + if (_validate(config)) Navigator.of(context).pop(config); + }); + } + + Future _confirmStartStream() async { + if (_startingStream || _loading) return; + final sn = widget.initial.channel; + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: const Text('开启设备推流'), + content: Text('为设备 $sn 开启推流?'), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: const Text('取消'), + ), + FilledButton( + onPressed: () => Navigator.of(dialogContext).pop(true), + child: const Text('开启推流'), + ), + ], + ), + ); + if (!mounted || confirmed != true) return; + setState(() { + _startingStream = true; + _streamMessage = null; + }); + final result = await widget.startVideoStream(sn); + if (!mounted) return; + setState(() { + _startingStream = false; + _streamMessage = result.match( + (failure) => failure.message, + (_) => '已开启设备推流', + ); + }); + } + + Widget _field( + String label, + TextEditingController controller, { + bool numeric = false, + bool readOnly = false, + }) { + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: TextField( + controller: controller, + readOnly: readOnly, + autocorrect: false, + enableSuggestions: false, + keyboardType: numeric ? TextInputType.number : TextInputType.text, + inputFormatters: numeric + ? [FilteringTextInputFormatter.digitsOnly] + : null, + decoration: InputDecoration( + labelText: label, + border: const OutlineInputBorder(), + ), + ), + ); + } + + @override + Widget build(BuildContext context) => AlertDialog( + title: const Text('声网 RTC 配置'), + content: SizedBox( + width: 520, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Flexible( + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text('同一频道,按 UID 区分四路视频。前后双击切换,左右通过「视频」键打开悬浮窗。'), + const SizedBox(height: 14), + _field('App ID', _appId), + _field('频道(设备 SN)', _channel, readOnly: true), + Padding( + padding: const EdgeInsets.only(bottom: 14), + child: TextField( + controller: _token, + obscureText: !_showToken, + autocorrect: false, + enableSuggestions: false, + decoration: InputDecoration( + labelText: '临时 Token', + helperText: 'Token 过期后可重新获取配置或手动填写', + border: const OutlineInputBorder(), + suffixIcon: IconButton( + tooltip: _showToken ? '隐藏 Token' : '显示 Token', + onPressed: () => + setState(() => _showToken = !_showToken), + icon: Icon( + _showToken + ? Icons.visibility_off + : Icons.visibility, + ), + ), + ), + ), + ), + _field( + '观看端 UID(0 为自动;Token 绑定 UID 时请填写对应值)', + _viewer, + numeric: true, + ), + for (final direction in PvCameraDirection.values) + _field( + '${direction.label} UID', + _uids[direction]!, + numeric: true, + ), + ], + ), + ), + ), + if (_streamMessage != null) Text(_streamMessage!), + if (_error != null) + Text( + _error!, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('取消'), + ), + TextButton( + onPressed: _startingStream || _loading ? null : _confirmStartStream, + child: Text(_startingStream ? '正在开启推流…' : '开启推流'), + ), + OutlinedButton( + onPressed: _loading ? null : _connectManually, + child: const Text('保存并连接'), + ), + FilledButton( + onPressed: _loading ? null : _fetchAndConnect, + child: Text(_loading ? '正在获取配置…' : '获取配置并连接'), + ), + ], + ); +} diff --git a/lib/features/pv_control/presentation/widgets/pv_camera_view.dart b/lib/features/pv_control/presentation/widgets/pv_camera_view.dart new file mode 100644 index 00000000..c9dcd515 --- /dev/null +++ b/lib/features/pv_control/presentation/widgets/pv_camera_view.dart @@ -0,0 +1,172 @@ +import 'package:agora_rtc_engine/agora_rtc_engine.dart' as agora; +import 'package:flutter/material.dart'; +import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/webrtc/webrtc_local_player.dart'; + +import '../../domain/video/pv_camera_direction.dart'; +import '../models/pv_video_fit.dart'; +import '../models/pv_video_source.dart'; +import '../video/pv_agora_scope.dart'; +import 'pv_local_rtsp_video.dart'; +import 'pv_usb_camera_video.dart'; + +/// Front/rear interaction for the overview video area; the manual HUD owns its +/// own direction selection so its small preview can display the opposite view. +class PvSwitchableCameraView extends StatefulWidget { + const PvSwitchableCameraView({ + super.key, + required this.source, + required this.fit, + }); + final PvVideoSource source; + final PvVideoFit fit; + + @override + State createState() => _PvSwitchableCameraViewState(); +} + +class _PvSwitchableCameraViewState extends State { + bool _rear = false; + + @override + Widget build(BuildContext context) => GestureDetector( + behavior: HitTestBehavior.opaque, + onDoubleTap: () => setState(() => _rear = !_rear), + child: Stack( + fit: StackFit.expand, + children: [ + PvCameraView( + source: widget.source, + fit: widget.fit, + direction: _rear ? PvCameraDirection.rear : PvCameraDirection.front, + ), + Positioned( + bottom: 8, + right: 8, + child: IgnorePointer( + child: Text( + '${_rear ? "后视" : "前视"} · 双击切换前后', + style: const TextStyle( + color: Colors.white, + backgroundColor: Colors.black54, + fontSize: 12, + ), + ), + ), + ), + ], + ), + ); +} + +/// Central transport dispatcher. Camera identity stays separate from video +/// source selection, so another transport can implement the same four views. +class PvCameraView extends StatelessWidget { + const PvCameraView({ + super.key, + required this.source, + this.direction = PvCameraDirection.front, + this.streamUrl = '', + this.fit = PvVideoFit.contain, + }); + final PvVideoSource source; + final PvCameraDirection direction; + final String streamUrl; + final PvVideoFit fit; + + @override + Widget build(BuildContext context) => switch (source) { + PvVideoSource.agoraRtc => _AgoraCameraView(direction: direction, fit: fit), + PvVideoSource.usbCamera => const PvUsbCameraVideo(), + PvVideoSource.localRtsp => const PvLocalRtspVideo(), + PvVideoSource.webrtc => + streamUrl.isNotEmpty + ? WebRTCLocalPlayer( + streamUrl: streamUrl, + showLeftPip: false, + showRightPip: false, + mainViewAlignment: Alignment.center, + ) + : const ColoredBox( + color: Colors.black87, + child: Center( + child: Icon( + Icons.videocam_off, + size: 48, + color: Colors.white38, + ), + ), + ), + }; +} + +class _AgoraCameraView extends StatelessWidget { + const _AgoraCameraView({required this.direction, required this.fit}); + final PvCameraDirection direction; + final PvVideoFit fit; + + @override + Widget build(BuildContext context) { + final session = PvAgoraScope.of(context); + return AnimatedBuilder( + animation: session, + builder: (context, _) { + final config = session.config; + final engine = session.engine; + final uid = config?.uidFor(direction); + final canRender = engine != null && session.joined && uid != null; + final playing = uid != null && session.hasVideo(uid); + return ColoredBox( + color: Colors.black, + child: Stack( + fit: StackFit.expand, + children: [ + if (canRender) + IgnorePointer( + child: agora.AgoraVideoView( + key: ValueKey('agora/${session.generation}/$uid'), + controller: agora.VideoViewController.remote( + rtcEngine: engine, + canvas: agora.VideoCanvas( + uid: uid, + setupMode: agora.VideoViewSetupMode.videoViewSetupAdd, + renderMode: fit == PvVideoFit.cover + ? agora.RenderModeType.renderModeHidden + : agora.RenderModeType.renderModeFit, + ), + connection: agora.RtcConnection( + channelId: config!.channel, + ), + useAndroidSurfaceView: false, + ), + ), + ), + if (!playing) + Center( + child: Padding( + padding: const EdgeInsets.all(12), + child: Text( + session.message ?? + '${direction.label} · UID $uid\n等待该路视频上线', + textAlign: TextAlign.center, + style: const TextStyle( + color: Colors.white70, + fontSize: 12, + ), + ), + ), + ), + if (playing && session.tokenWarning != null) + Align( + alignment: Alignment.bottomCenter, + child: Text( + session.tokenWarning!, + style: const TextStyle(color: Colors.amber, fontSize: 11), + ), + ), + ], + ), + ); + }, + ); + } +} diff --git a/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart b/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart index 86854ded..c1a8e44d 100644 --- a/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart +++ b/lib/features/pv_control/presentation/widgets/pv_manual_control_view.dart @@ -32,6 +32,8 @@ import '../../../remote_control/presentation/widgets/remote_control_link_feedbac import '../../../remote_control/presentation/widgets/permission_request_feedback.dart'; import 'pv_control_bar.dart'; import 'pv_rear_view_card.dart'; +import '../../domain/video/pv_camera_direction.dart'; +import 'pv_camera_view.dart'; import 'pv_local_rtsp_video.dart'; // 顶栏「任务」入口暂时隐藏,该弹窗导入一并注释(恢复时取消注释) // import 'pv_task_dialog.dart'; @@ -127,9 +129,12 @@ class _PvManualControlViewState extends State /// 障碍物预警横幅脉动动画。 late final AnimationController _pulse; - /// 绿色导向箭头的“递进流动”动画(单向循环)。 + /// 绿色导向箭头的循环动画进度。 late final AnimationController _flow; + /// 停车时保留最近一次行驶方向,避免箭头在换向前抖动。 + late bool _guideReversing; + /// 「未在控制」胶囊的呼吸动画(纯视觉,与远程遥控同款节奏;有权限时不参与渲染)。 late final AnimationController _breath; @@ -144,6 +149,7 @@ class _PvManualControlViewState extends State /// 顶栏「视频」开关:显示左右视角浮窗(同时把两侧面板折叠)。 bool _showSidePips = false; + bool _rearMain = false; /// 顶栏「地图」开关:左栏地图卡放大到屏幕正中央(同时把两侧面板折叠)。 bool _showBigMap = false; @@ -196,6 +202,7 @@ class _PvManualControlViewState extends State @override void initState() { super.initState(); + _guideReversing = (widget.telemetry.speed ?? 0) < 0; _pulse = AnimationController( vsync: this, duration: const Duration(milliseconds: 750), @@ -226,6 +233,10 @@ class _PvManualControlViewState extends State @override void didUpdateWidget(covariant PvManualControlView oldWidget) { super.didUpdateWidget(oldWidget); + final speed = widget.telemetry.speed; + if (speed != null && speed != 0) { + _guideReversing = speed < 0; + } if (oldWidget.showJoysticks && !widget.showJoysticks) { // 归零后清掉去重基准:否则下次推到同一个值会被当成“没变化”吞掉。 _lastDriveY = 0; @@ -317,6 +328,24 @@ class _PvManualControlViewState extends State /// 全屏底图:按「视频展示」档位做 contain / cover 适配。 Widget _buildVideo() { + if (widget.videoSource.hasDirectionalViews) { + return GestureDetector( + behavior: HitTestBehavior.opaque, + onDoubleTap: () => setState(() => _rearMain = !_rearMain), + child: Stack(fit: StackFit.expand, children: [ + PvCameraView( + key: ValueKey('main/$_rearMain'), + source: widget.videoSource, + direction: _rearMain ? PvCameraDirection.rear : PvCameraDirection.front, + fit: widget.videoFit, + ), + Positioned(top: d(58), right: d(80), child: IgnorePointer(child: Text( + '${_rearMain ? "后视" : "前视"} · 双击切换前后', + style: const TextStyle(color: Colors.white, backgroundColor: Colors.black54, fontSize: 12), + ))), + ]), + ); + } return PvVideoFitBox( fit: widget.videoFit, source: widget.videoSource, @@ -350,6 +379,7 @@ class _PvManualControlViewState extends State // ===== ② 假 AR 覆盖层 ===== Widget _buildArOverlay(double w, double h) { + final rearView = widget.videoSource.hasDirectionalViews && _rearMain; return Positioned.fill( child: IgnorePointer( child: Stack( @@ -364,7 +394,11 @@ class _PvManualControlViewState extends State builder: (context, deg, _) => AnimatedBuilder( animation: _flow, builder: (context, _) => CustomPaint( - painter: _PvArPainter(progress: _flow.value, steering: deg), + painter: _PvArPainter( + progress: _flow.value, + steering: deg, + towardCamera: _guideReversing != rearView, + ), ), ), ), @@ -995,7 +1029,9 @@ class _PvManualControlViewState extends State final tr = AppLocalizations.of(context); // 窗体宽高比 = 源画面宽高比 ÷ 2(“左右半幅”的比例),再把画面按宽度放大 2 倍裁切: // 二者抵消后等比不拉伸、不留黑边、也不丢掉任何画面内容。 - final cropRatio = pvFrameRatioOf(context, widget.videoSource) / 2; + final cropRatio = widget.videoSource.hasDirectionalViews + ? 16 / 9 + : pvFrameRatioOf(context, widget.videoSource) / 2; var pipW = (w * 0.24).clamp(d(150), d(300)); var pipH = pipW / cropRatio; final maxH = h * 0.62; // 不让浮窗吃掉摇杆区域 @@ -1011,6 +1047,7 @@ class _PvManualControlViewState extends State children: [ _sidePip( label: tr.translate('pv_control.view_left_pip'), + direction: PvCameraDirection.left, crop: Alignment.centerLeft, pos: _leftPipPos!, size: Size(pipW, pipH), @@ -1019,6 +1056,7 @@ class _PvManualControlViewState extends State ), _sidePip( label: tr.translate('pv_control.view_right_pip'), + direction: PvCameraDirection.right, crop: Alignment.centerRight, pos: _rightPipPos!, size: Size(pipW, pipH), @@ -1039,6 +1077,7 @@ class _PvManualControlViewState extends State /// 不会重复拉流 / 重复占用采集设备;WebRTC 链路每实例自建连接,浮窗会另开拉流。 Widget _sidePip({ required String label, + required PvCameraDirection direction, required Alignment crop, required Offset pos, required Size size, @@ -1078,7 +1117,9 @@ class _PvManualControlViewState extends State children: [ ClipRRect( borderRadius: BorderRadius.circular(d(9)), - child: LayoutBuilder( + child: widget.videoSource.hasDirectionalViews + ? PvCameraView(source: widget.videoSource, direction: direction) + : LayoutBuilder( builder: (context, c) => OverflowBox( // 只把可用宽翻倍,高度保持窗体高:与 cropRatio = 源比例 / 2 配套 maxWidth: c.maxWidth * 2, @@ -1164,10 +1205,22 @@ class _PvManualControlViewState extends State final tr = AppLocalizations.of(context); return PvRearViewCard( scale: _sc, + video: widget.videoSource.hasDirectionalViews + ? PvCameraView( + key: ValueKey('preview/$_rearMain'), + source: widget.videoSource, + direction: _rearMain ? PvCameraDirection.front : PvCameraDirection.rear, + ) + : null, + onExpand: widget.videoSource.hasDirectionalViews + ? () => setState(() => _rearMain = !_rearMain) + : null, // 后视引导线弯曲实时跟右摇杆转向。 // 未来接入下位机后,ReverseCameraData 的 gear/steeringAngle/ // rearDistanceCm 全部改成读回传数据即可,本组件不改。 - title: tr.translate('pv_control.reverse_camera'), + title: widget.videoSource.hasDirectionalViews && _rearMain + ? '前视图' + : tr.translate('pv_control.reverse_camera'), overlay: ValueListenableBuilder( valueListenable: _steerDeg, builder: (context, deg, _) => ReverseGuideOverlay( @@ -1650,6 +1703,9 @@ class _PvManualControlViewState extends State final int y = v.y.toInt(); if (y == _lastDriveY) return; _lastDriveY = y; + if (widget.telemetry.speed == null && y != 0) { + _guideReversing = y < 0; + } widget.channel?.sendDriveY(y); }, onPanEnd: () async { @@ -2196,7 +2252,11 @@ class _PvRedGlowPainter extends CustomPainter { /// 脊柱以画面底部正中为固定顶点,随 [steering](-45~45)做等曲率圆弧弯曲, /// 车道线沿法线守恒宽度地跟随,箭头沿弧线切线放置;steering=0 即回到原直线形态。 class _PvArPainter extends CustomPainter { - _PvArPainter({this.progress = 0, this.steering = 0}); + _PvArPainter({ + required this.progress, + required this.steering, + required this.towardCamera, + }); /// 0..1 循环进度,驱动绿色箭头的流动。 final double progress; @@ -2204,6 +2264,9 @@ class _PvArPainter extends CustomPainter { /// 转向角(度,右正左负,-45~45):驱动辅助线左右弯曲,当前由右摇杆喂入。 final double steering; + /// 车辆朝向当前摄像头画面的近端移动。 + final bool towardCamera; + /// 近端(底部顶点)纵向比例 static const double _bottomT = 0.98; @@ -2291,8 +2354,9 @@ class _PvArPainter extends CustomPainter { // 中央绿色导向箭头:沿弯曲脊柱放置并随切线旋转,虚实渐隐 const n = 4; + final flow = towardCamera ? -progress : progress; for (var i = 0; i < n; i++) { - final phase = (progress + i / n) % 1.0; // 0=近/底 → 1=远/顶 + final phase = (flow + i / n) % 1.0; // 0=近/底 → 1=远/顶 final ay = h * (0.90 - phase * 0.34); final f = ((bottomY - ay) / (bottomY - topY)).clamp(0.0, 1.0).toDouble(); final half = w * (0.105 - phase * 0.05); @@ -2309,7 +2373,7 @@ class _PvArPainter extends CustomPainter { final c = spineAt(f); canvas.save(); canvas.translate(c.dx, c.dy); - canvas.rotate(headAt(f)); + canvas.rotate(headAt(f) + (towardCamera ? math.pi : 0)); final path = Path() ..moveTo(-half, drop) ..lineTo(0, 0) @@ -2321,5 +2385,7 @@ class _PvArPainter extends CustomPainter { @override bool shouldRepaint(covariant _PvArPainter oldDelegate) => - oldDelegate.progress != progress || oldDelegate.steering != steering; + oldDelegate.progress != progress || + oldDelegate.steering != steering || + oldDelegate.towardCamera != towardCamera; } diff --git a/lib/features/pv_control/presentation/widgets/pv_rear_view_card.dart b/lib/features/pv_control/presentation/widgets/pv_rear_view_card.dart index 043c6235..e3619f7a 100644 --- a/lib/features/pv_control/presentation/widgets/pv_rear_view_card.dart +++ b/lib/features/pv_control/presentation/widgets/pv_rear_view_card.dart @@ -25,6 +25,7 @@ class PvRearViewCard extends StatelessWidget { this.scale = 1, this.overlay, this.onExpand, + this.video, }); /// 卡片标题;为空时根据当前语言回退为「后视图」。 @@ -33,6 +34,9 @@ class PvRearViewCard extends StatelessWidget { /// 视频流地址;为空时显示无信号占位。 final String streamUrl; + /// Transport-independent camera slot, taking precedence over streamUrl. + final Widget? video; + /// 缩放系数(HUD 传入 _sc;独立使用时保持默认 1 即为设计像素)。 final double scale; @@ -66,7 +70,9 @@ class PvRearViewCard extends StatelessWidget { fit: StackFit.expand, children: [ // 画面:有流播流,无流占位 - if (streamUrl.isNotEmpty) + if (video != null) + video! + else if (streamUrl.isNotEmpty) WebRTCLocalPlayer( streamUrl: streamUrl, showLeftPip: false, diff --git a/lib/features/pv_control/presentation/widgets/pv_settings_sheet.dart b/lib/features/pv_control/presentation/widgets/pv_settings_sheet.dart index 6c050614..83690b35 100644 --- a/lib/features/pv_control/presentation/widgets/pv_settings_sheet.dart +++ b/lib/features/pv_control/presentation/widgets/pv_settings_sheet.dart @@ -57,6 +57,7 @@ class PvSettingsSheet extends StatelessWidget { (PvVideoSource.localRtsp, 'pv_control.set_source_rtsp'), (PvVideoSource.usbCamera, 'pv_control.set_source_hdmi'), (PvVideoSource.webrtc, 'pv_control.set_source_webrtc'), + (PvVideoSource.agoraRtc, 'pv_control.set_source_agora'), ]; /// 视频展示选项:文案说清“取舍”以免用户选完还是困惑。 diff --git a/lib/features/pv_control/presentation/widgets/pv_video_area.dart b/lib/features/pv_control/presentation/widgets/pv_video_area.dart index 3bb3f64e..ade16f53 100644 --- a/lib/features/pv_control/presentation/widgets/pv_video_area.dart +++ b/lib/features/pv_control/presentation/widgets/pv_video_area.dart @@ -11,6 +11,7 @@ import '../theme/pv_colors.dart'; import 'pv_local_rtsp_video.dart'; import 'pv_usb_camera_video.dart'; import 'pv_video_fit_box.dart'; +import 'pv_camera_view.dart'; /// 实时视频区:底层播放 WebRTC 流,上层叠加设计稿中的信息浮层。 /// @@ -100,6 +101,9 @@ class PvVideoArea extends StatelessWidget { /// 各链路的原始视频层(组件内部自己等比居中)。 Widget _buildLayer() { + if (videoSource.hasDirectionalViews) { + return PvSwitchableCameraView(source: videoSource, fit: videoFit); + } if (videoSource == PvVideoSource.usbCamera) return const PvUsbCameraVideo(); if (videoSource == PvVideoSource.localRtsp) return const PvLocalRtspVideo(); if (streamUrl.isNotEmpty) { diff --git a/lib/features/pv_control/presentation/widgets/pv_video_fit_box.dart b/lib/features/pv_control/presentation/widgets/pv_video_fit_box.dart index e80ee5e1..9149b1c5 100644 --- a/lib/features/pv_control/presentation/widgets/pv_video_fit_box.dart +++ b/lib/features/pv_control/presentation/widgets/pv_video_fit_box.dart @@ -32,6 +32,7 @@ double pvFrameRatioOf(BuildContext context, PvVideoSource source) { (c != null && c.value.isInitialized) ? c.value.aspectRatio : 0.0; return r > 0 ? r : 16 / 9; case PvVideoSource.webrtc: + case PvVideoSource.agoraRtc: // WebRTC 侧未对外暴露 renderer 尺寸,沿用播放器内部的 16:9 主视口。 return 16 / 9; } @@ -62,7 +63,8 @@ class PvVideoFitBox extends StatelessWidget { @override Widget build(BuildContext context) { - if (fit == PvVideoFit.contain) return child; + // RTC renderMode handles the actual per-camera aspect ratio natively. + if (fit == PvVideoFit.contain || source == PvVideoSource.agoraRtc) return child; final ratio = pvFrameRatioOf(context, source); return LayoutBuilder( builder: (context, c) { diff --git a/test/pv_agora_video_test.dart b/test/pv_agora_video_test.dart new file mode 100644 index 00000000..eb8fb43d --- /dev/null +++ b/test/pv_agora_video_test.dart @@ -0,0 +1,451 @@ +import 'dart:async'; + +import 'package:agora_rtc_engine/agora_rtc_engine.dart' as agora; +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:maibu_satabot_v2/features/pv_control/data/datasources/pv_agora_remote_datasource.dart'; +import 'package:maibu_satabot_v2/features/pv_control/data/repositories/pv_agora_repository_impl.dart'; +import 'package:maibu_satabot_v2/features/pv_control/domain/usecases/get_pv_agora_credentials_usecase.dart'; +import 'package:maibu_satabot_v2/features/pv_control/domain/usecases/start_pv_agora_video_stream_usecase.dart'; +import 'package:maibu_satabot_v2/features/pv_control/domain/video/pv_agora_config.dart'; +import 'package:maibu_satabot_v2/features/pv_control/domain/video/pv_camera_direction.dart'; +import 'package:maibu_satabot_v2/features/pv_control/presentation/models/pv_video_fit.dart'; +import 'package:maibu_satabot_v2/features/pv_control/presentation/models/pv_video_source.dart'; +import 'package:maibu_satabot_v2/features/pv_control/presentation/video/pv_agora_session.dart'; +import 'package:maibu_satabot_v2/features/pv_control/presentation/video/pv_agora_scope.dart'; +import 'package:maibu_satabot_v2/features/pv_control/presentation/widgets/pv_agora_config_dialog.dart'; +import 'package:maibu_satabot_v2/features/pv_control/presentation/widgets/pv_camera_view.dart'; + +const _config = PvAgoraConfig( + appId: '00000000000000000000000000000000', + channel: 'test-channel', + token: 'test-token', +); + +class _Engine extends Fake implements agora.RtcEngine { + agora.RtcEngineEventHandler? handler; + agora.ChannelMediaOptions? options; + String? channel; + String? token; + int? viewerUid; + final releaseStarted = Completer(); + Completer? releaseGate; + bool cameraEnabled = true; + bool micEnabled = true; + int joins = 0; + + @override + Future initialize(agora.RtcEngineContext context) async {} + @override + Future enableVideo() async {} + @override + Future enableLocalVideo(bool enabled) async { + cameraEnabled = enabled; + } + + @override + Future enableLocalAudio(bool enabled) async { + micEnabled = enabled; + } + + @override + void registerEventHandler(agora.RtcEngineEventHandler eventHandler) { + handler = eventHandler; + } + + @override + void unregisterEventHandler(agora.RtcEngineEventHandler eventHandler) {} + @override + Future joinChannel({ + required String token, + required String channelId, + required int uid, + agora.ChannelMediaOptions? options, + }) async { + channel = channelId; + this.token = token; + viewerUid = uid; + this.options = options; + joins++; + } + + @override + Future leaveChannel({agora.LeaveChannelOptions? options}) async {} + @override + Future release({bool sync = false}) async { + releaseStarted.complete(); + await releaseGate?.future; + } +} + +void main() { + test( + 'four publishers share one audience channel and offline/token events clear video', + () async { + final engine = _Engine(); + var creations = 0; + final session = PvAgoraSession( + createEngine: () { + creations++; + return engine; + }, + ); + await session.connect(_config); + expect(creations, 1); + expect(engine.joins, 1); + expect(engine.channel, 'test-channel'); + expect(engine.cameraEnabled, isFalse); + expect(engine.micEnabled, isFalse); + expect( + engine.options!.clientRoleType, + agora.ClientRoleType.clientRoleAudience, + ); + expect(engine.options!.publishCameraTrack, isFalse); + expect(engine.options!.publishMicrophoneTrack, isFalse); + const connection = agora.RtcConnection(channelId: 'test-channel'); + engine.handler!.onJoinChannelSuccess!(connection, 0); + for (final direction in PvCameraDirection.values) { + final uid = _config.uidFor(direction); + engine.handler!.onRemoteVideoStateChanged!( + connection, + uid, + agora.RemoteVideoState.remoteVideoStateDecoding, + agora.RemoteVideoStateReason.remoteVideoStateReasonRemoteUnmuted, + 0, + ); + expect(session.hasVideo(uid), isTrue); + } + expect(PvCameraDirection.values.map(_config.uidFor), [ + 101, + 102, + 103, + 104, + ]); + engine.handler!.onUserOffline!( + connection, + 102, + agora.UserOfflineReasonType.userOfflineQuit, + ); + expect(session.hasVideo(102), isFalse); + expect(session.hasVideo(101), isTrue); + engine.handler!.onRequestToken!(connection); + expect(session.joined, isFalse); + expect(session.hasVideo(101), isFalse); + expect(session.message, contains('Token')); + await session.disconnect(); + session.dispose(); + }, + ); + + test( + 'rapid reconfiguration waits for release and ignores obsolete callbacks', + () async { + final first = _Engine()..releaseGate = Completer(); + final second = _Engine(); + var creations = 0; + final session = PvAgoraSession( + createEngine: () => creations++ == 0 ? first : second, + ); + await session.connect(_config); + final oldHandler = first.handler!; + final reconnect = session.connect(_config); + await first.releaseStarted.future; + expect(creations, 1); + oldHandler.onJoinChannelSuccess!( + const agora.RtcConnection(channelId: 'old'), + 0, + ); + expect(session.joined, isFalse); + first.releaseGate!.complete(); + await reconnect; + expect(creations, 2); + await session.disconnect(); + session.dispose(); + }, + ); + + testWidgets('double tap selects rear/front without creating an engine', ( + tester, + ) async { + final session = PvAgoraSession( + createEngine: () => throw StateError('must not connect'), + ); + await tester.pumpWidget( + MaterialApp( + home: PvAgoraScope( + session: session, + child: const PvSwitchableCameraView( + source: PvVideoSource.agoraRtc, + fit: PvVideoFit.contain, + ), + ), + ), + ); + expect( + tester.widget(find.byType(PvCameraView)).direction, + PvCameraDirection.front, + ); + final target = find.byType(PvSwitchableCameraView); + await tester.tap(target); + await tester.pump(const Duration(milliseconds: 80)); + await tester.tap(target); + await tester.pumpAndSettle(); + expect( + tester.widget(find.byType(PvCameraView)).direction, + PvCameraDirection.rear, + ); + await tester.pumpWidget(const SizedBox()); + session.dispose(); + }); + + testWidgets( + 'start confirmation is optional and credentials can load during or after a failed start', + (tester) async { + const sn = 'ROBOT-SN-02'; + final requests = []; + final logs = []; + final startResponse = Completer(); + var tokenRequests = 0; + final dio = Dio(); + addTearDown(dio.close); + dio.interceptors.add( + InterceptorsWrapper( + onRequest: (options, handler) async { + requests.add(options); + if (options.uri.path.endsWith('/startVideoStream')) { + await startResponse.future; + handler.resolve( + Response( + requestOptions: options, + statusCode: 200, + data: {'code': 200, 'data': false, 'msg': '设备尚未开启推流'}, + ), + ); + return; + } + tokenRequests++; + if (tokenRequests == 1) { + handler.reject( + DioException.badResponse( + statusCode: 500, + requestOptions: options, + response: Response( + requestOptions: options, + statusCode: 500, + data: {'msg': '设备服务异常', 'token': 'error-token'}, + ), + ), + ); + return; + } + handler.resolve( + Response( + requestOptions: options, + statusCode: 200, + data: tokenRequests == 2 + ? {'code': 500, 'msg': '设备尚未配置'} + : { + 'code': '200', + 'data': { + 'uid': '42', + 'token': 'device-token', + 'appId': _config.appId, + 'appCertificate': 'unused-server-certificate', + }, + }, + ), + ); + }, + ), + ); + final repository = PvAgoraRepositoryImpl(PvAgoraRemoteDataSource(dio)); + final getCredentials = GetPvAgoraCredentialsUseCase(repository); + final startVideoStream = StartPvAgoraVideoStreamUseCase(repository); + final engine = _Engine(); + final session = PvAgoraSession(createEngine: () => engine); + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => TextButton( + onPressed: () async { + final config = await showPvAgoraConfigDialog( + context, + const PvAgoraConfig( + appId: '', + channel: sn, + token: '', + leftUid: 202, + ), + loadCredentials: getCredentials.call, + startVideoStream: startVideoStream.call, + ); + if (config != null) await session.connect(config); + }, + child: const Text('configure'), + ), + ), + ), + ); + + await tester.tap(find.text('configure')); + await tester.pumpAndSettle(); + final fetch = find.text('获取配置并连接'); + final start = find.widgetWithText(TextButton, '开启推流'); + final confirmation = find.widgetWithText(AlertDialog, '开启设备推流'); + await tester.tap(start); + await tester.pumpAndSettle(); + expect(tester.widget(confirmation).actions, hasLength(2)); + await tester.tap( + find.descendant(of: confirmation, matching: find.text('取消')), + ); + await tester.pumpAndSettle(); + expect(requests, isEmpty); + + final previousDebugPrint = debugPrint; + debugPrint = (message, {wrapWidth}) { + if (message != null && message.startsWith('[声网配置][getAgoraToken]')) { + logs.add(message); + } + }; + try { + await tester.tap(fetch); + await tester.pumpAndSettle(); + expect(requests, hasLength(1)); + expect(tokenRequests, 1); + expect(find.text('服务器异常,请稍后重试'), findsOneWidget); + expect(engine.joins, 0); + + await tester.tap(start); + await tester.pumpAndSettle(); + expect(requests, hasLength(1)); + await tester.tap( + find.descendant(of: confirmation, matching: find.text('开启推流')), + ); + await tester.pumpAndSettle(); + expect(requests, hasLength(2)); + expect(find.text('正在开启推流…'), findsOneWidget); + + await tester.tap(fetch); + await tester.pumpAndSettle(); + expect(tokenRequests, 2); + expect(find.text('服务端未能签发声网配置,请稍后重试'), findsOneWidget); + expect(find.text('正在开启推流…'), findsOneWidget); + expect(engine.joins, 0); + + startResponse.complete(); + await tester.pumpAndSettle(); + expect(find.text('开启推流失败(设备尚未开启推流)'), findsOneWidget); + expect(find.text('保存并连接'), findsOneWidget); + + await tester.tap(fetch); + await tester.pumpAndSettle(); + } finally { + debugPrint = previousDebugPrint; + } + expect(requests.map((request) => request.uri.path), [ + endsWith('/iot/host/getAgoraToken'), + endsWith('/iot/host/startVideoStream'), + endsWith('/iot/host/getAgoraToken'), + endsWith('/iot/host/getAgoraToken'), + ]); + expect(logs, hasLength(3)); + expect(logs[0], contains('"httpStatus":500')); + expect(logs[0], contains('"errorType":"badResponse"')); + expect(logs[0], contains('设备服务异常')); + expect(logs[0], isNot(contains('error-token'))); + expect(logs[1], contains('"code":500')); + expect(logs[1], contains('设备尚未配置')); + expect(logs[2], contains('"deviceId":"$sn"')); + expect(logs[2], contains('"uid":"42"')); + expect(logs[2], contains('"appId":"${_config.appId}"')); + expect(logs[2], contains('"token":"<已脱敏,长度 12>"')); + expect(logs[2], contains('"appCertificate":"<已脱敏,长度 25>"')); + expect(logs[2], isNot(contains('device-token'))); + expect(logs[2], isNot(contains('unused-server-certificate'))); + for (final request in requests) { + expect(request.method, 'GET'); + expect(request.queryParameters, {'deviceId': sn}); + } + expect(engine.joins, 1); + expect(engine.channel, sn); + expect(engine.token, 'device-token'); + expect(engine.viewerUid, 42); + expect(session.config?.leftUid, 202); + await session.disconnect(); + session.dispose(); + }, + ); + + testWidgets( + 'manual form validates and connects without sending either request', + (tester) async { + PvAgoraConfig? result; + final requests = []; + final dio = Dio(); + addTearDown(dio.close); + dio.interceptors.add( + InterceptorsWrapper( + onRequest: (options, handler) { + requests.add(options); + handler.resolve( + Response( + requestOptions: options, + statusCode: 200, + data: {'code': 500}, + ), + ); + }, + ), + ); + final repository = PvAgoraRepositoryImpl(PvAgoraRemoteDataSource(dio)); + final getCredentials = GetPvAgoraCredentialsUseCase(repository); + final startVideoStream = StartPvAgoraVideoStreamUseCase(repository); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () async { + result = await showPvAgoraConfigDialog( + context, + _config, + loadCredentials: getCredentials.call, + startVideoStream: startVideoStream.call, + ); + }, + child: const Text('configure'), + ), + ), + ), + ), + ); + await tester.tap(find.text('configure')); + await tester.pumpAndSettle(); + Finder field(String label) => find.byWidgetPredicate( + (widget) => + widget is TextField && widget.decoration?.labelText == label, + ); + final channel = tester.widget(field('频道(设备 SN)')); + expect(channel.readOnly, isTrue); + expect(channel.controller!.text, 'test-channel'); + await tester.ensureVisible(field('左视 UID')); + await tester.enterText(field('左视 UID'), '101'); + await tester.tap(find.text('保存并连接')); + await tester.pumpAndSettle(); + expect(find.text('四路视频 UID 不能重复'), findsOneWidget); + expect(requests, isEmpty); + await tester.enterText(field('左视 UID'), '202'); + await tester.tap(find.text('保存并连接')); + await tester.pumpAndSettle(); + expect(result!.uidFor(PvCameraDirection.left), 202); + expect(result!.token, 'test-token'); + await tester.tap(find.text('configure')); + await tester.pumpAndSettle(); + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(result, isNull); + expect(requests, isEmpty); + }, + ); +}