接入声网四路视频

This commit is contained in:
2026-11-21 14:52:13 +08:00
parent 04fffd2267
commit 739d588a16
26 changed files with 1637 additions and 15 deletions

View File

@@ -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";

View File

@@ -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<void> init() async {
sl.registerLazySingleton(
() => ChangeDeviceControlModeUseCase(sl<DeviceControlModeRepository>()),
);
sl.registerLazySingleton(() => PvAgoraRemoteDataSource(sl<Dio>()));
sl.registerLazySingleton<PvAgoraRepository>(
() => PvAgoraRepositoryImpl(sl<PvAgoraRemoteDataSource>()),
);
sl.registerLazySingleton(
() => GetPvAgoraCredentialsUseCase(sl<PvAgoraRepository>()),
);
sl.registerLazySingleton(
() => StartPvAgoraVideoStreamUseCase(sl<PvAgoraRepository>()),
);
sl.registerLazySingleton(
() => RegionRemoteDatasource(sl<Dio>(), sl<ILoggerService>()),
);

View File

@@ -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<dynamic> 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);
}
}

View File

@@ -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<void> 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<PvAgoraCredentials> 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<Response<Object?>> _get(
String url,
String deviceSn,
String endpoint,
) async {
try {
final response = await dio.get<Object?>(
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<Object?>? response, {
DioExceptionType? errorType,
}) {
final body = response?.data;
final fields = <String, Object?>{
'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}>';
}
}

View File

@@ -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<Either<Failure, Unit>> 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<Either<Failure, PvAgoraCredentials>> 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)));
}
}
}

View File

@@ -0,0 +1,9 @@
import 'package:fpdart/fpdart.dart';
import '../../../../core/error/failure.dart';
import '../video/pv_agora_credentials.dart';
abstract class PvAgoraRepository {
Future<Either<Failure, Unit>> startVideoStream(String deviceSn);
Future<Either<Failure, PvAgoraCredentials>> getCredentials(String deviceSn);
}

View File

@@ -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<Either<Failure, PvAgoraCredentials>> call(String deviceSn) async {
final sn = deviceSn.trim();
if (sn.isEmpty) return Left(Failure('请先选择设备'));
return repository.getCredentials(sn);
}
}

View File

@@ -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<Either<Failure, Unit>> call(String deviceSn) async {
final sn = deviceSn.trim();
if (sn.isEmpty) return Left(Failure('请先选择设备'));
return repository.startVideoStream(sn);
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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<PvControlPage> {
/// 当前视频链路(多源可扩展):在设置面板「视频源」行切换,
/// 切换即重建对应链路 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<PvControlPage> {
// 控制会话由模式确认完成后的回调建立。
}
@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<PvControlPage> {
@override
void dispose() {
_agoraSession.dispose();
// 离开安全模式:启动 90 秒倒计时(与远程遥控页一致)。
sl<AuthCubit>().exitSafeMode();
// 取消「权限交接」弹窗监听,避免回调打到已销毁的 State。
@@ -568,7 +591,45 @@ class _PvControlPageState extends State<PvControlPage> {
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<GetPvAgoraCredentialsUseCase>().call,
startVideoStream: sl<StartPvAgoraVideoStreamUseCase>().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<PvControlPage> {
child: child,
);
case PvVideoSource.webrtc:
case PvVideoSource.agoraRtc:
return child;
}
}
@@ -680,7 +742,10 @@ class _PvControlPageState extends State<PvControlPage> {
cancelToPreview: true,
emergencyStopControl: const EmergencyStopButton(),
onReady: _startControl,
child: _buildPage(context),
child: PvAgoraScope(
session: _agoraSession,
child: _buildPage(context),
),
);
Widget _buildPage(BuildContext context) {

View File

@@ -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<PvAgoraScope>()!.session;
@override
bool updateShouldNotify(PvAgoraScope oldWidget) =>
session != oldWidget.session;
}

View File

@@ -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<void> _pending = Future.value();
Timer? _timeout;
int _generation = 0;
bool _disposed = false;
bool joined = false;
String? message;
String? tokenWarning;
PvAgoraConfig? config;
final Map<int, agora.RemoteVideoState> _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<void> 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<void> disconnect() {
++_generation;
_timeout?.cancel();
joined = false;
message = null;
_videoStates.clear();
_notify();
return _pending = _pending.then((_) => _release());
}
Future<void> _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();
}
}

View File

@@ -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<Either<Failure, PvAgoraCredentials>> Function(String deviceSn);
typedef PvAgoraStreamStarter =
Future<Either<Failure, Unit>> Function(String deviceSn);
Future<PvAgoraConfig?> showPvAgoraConfigDialog(
BuildContext context,
PvAgoraConfig config, {
required PvAgoraCredentialsLoader loadCredentials,
required PvAgoraStreamStarter startVideoStream,
}) => showDialog<PvAgoraConfig>(
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<void> _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<void> _confirmStartStream() async {
if (_startingStream || _loading) return;
final sn = widget.initial.channel;
final confirmed = await showDialog<bool>(
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 ? '正在获取配置…' : '获取配置并连接'),
),
],
);
}

View File

@@ -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<PvSwitchableCameraView> createState() => _PvSwitchableCameraViewState();
}
class _PvSwitchableCameraViewState extends State<PvSwitchableCameraView> {
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),
),
),
],
),
);
},
);
}
}

View File

@@ -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<PvManualControlView>
/// 障碍物预警横幅脉动动画。
late final AnimationController _pulse;
/// 绿色导向箭头的“递进流动”动画(单向循环)。
/// 绿色导向箭头的循环动画进度。
late final AnimationController _flow;
/// 停车时保留最近一次行驶方向,避免箭头在换向前抖动。
late bool _guideReversing;
/// 「未在控制」胶囊的呼吸动画(纯视觉,与远程遥控同款节奏;有权限时不参与渲染)。
late final AnimationController _breath;
@@ -144,6 +149,7 @@ class _PvManualControlViewState extends State<PvManualControlView>
/// 顶栏「视频」开关:显示左右视角浮窗(同时把两侧面板折叠)。
bool _showSidePips = false;
bool _rearMain = false;
/// 顶栏「地图」开关:左栏地图卡放大到屏幕正中央(同时把两侧面板折叠)。
bool _showBigMap = false;
@@ -196,6 +202,7 @@ class _PvManualControlViewState extends State<PvManualControlView>
@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<PvManualControlView>
@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<PvManualControlView>
/// 全屏底图:按「视频展示」档位做 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<PvManualControlView>
// ===== ② 假 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<PvManualControlView>
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<PvManualControlView>
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<PvManualControlView>
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<PvManualControlView>
),
_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<PvManualControlView>
/// 不会重复拉流 / 重复占用采集设备;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<PvManualControlView>
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<PvManualControlView>
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<double>(
valueListenable: _steerDeg,
builder: (context, deg, _) => ReverseGuideOverlay(
@@ -1650,6 +1703,9 @@ class _PvManualControlViewState extends State<PvManualControlView>
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;
}

View File

@@ -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,

View File

@@ -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'),
];
/// 视频展示选项:文案说清“取舍”以免用户选完还是困惑。

View File

@@ -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) {

View File

@@ -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) {