USB 摄像头+远程遥控+中英的适配+topic的集成和状态的使用到相应页面

This commit is contained in:
2026-10-20 17:03:37 +08:00
parent 178cd2533c
commit 582242e9aa
144 changed files with 15759 additions and 406 deletions

View File

@@ -0,0 +1,35 @@
import 'package:shared_preferences/shared_preferences.dart';
/// 记录上一次使用的 USB 摄像头,插拔后优先重连。
class UsbCameraPrefs {
static const String _lastDeviceIdKey = 'usb_camera_last_device_id';
static const String _lastResolutionKey = 'usb_camera_last_resolution';
static Future<String?> getLastDeviceId() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_lastDeviceIdKey);
}
static Future<void> setLastDeviceId(String? id) async {
final prefs = await SharedPreferences.getInstance();
if (id == null) {
await prefs.remove(_lastDeviceIdKey);
return;
}
await prefs.setString(_lastDeviceIdKey, id);
}
static Future<String?> getLastResolution() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_lastResolutionKey);
}
static Future<void> setLastResolution(String? resolution) async {
final prefs = await SharedPreferences.getInstance();
if (resolution == null) {
await prefs.remove(_lastResolutionKey);
return;
}
await prefs.setString(_lastResolutionKey, resolution);
}
}

View File

@@ -0,0 +1,75 @@
import 'dart:async';
import 'package:usb_camera_android/usb_camera_android.dart' as plugin;
import '../domain/usb_camera_device.dart';
import 'usb_camera_prefs.dart';
/// UVC 摄像头原生能力封装。
class UvcCameraService {
bool _isOpen = false;
StreamSubscription? _eventSub;
/// 枚举当前已连接的 UVC 设备。
Future<List<UsbCameraDevice>> enumerateDevices() async {
final list = await plugin.UsbCameraAndroid.getDeviceList();
return list
.map(
(d) => UsbCameraDevice(
deviceId: d.deviceId,
vendorId: d.vendorId,
productId: d.productId,
productName: d.productName,
),
)
.toList();
}
/// 请求并打开指定设备。
Future<void> open(
UsbCameraDevice device, {
String? resolution,
}) async {
await UsbCameraPrefs.setLastDeviceId(device.deviceId);
if (resolution != null) {
await UsbCameraPrefs.setLastResolution(resolution);
}
await plugin.UsbCameraAndroid.open(
device.deviceId,
resolution: resolution,
);
_isOpen = true;
}
/// 关闭当前设备。
Future<void> close() async {
if (!_isOpen) return;
_isOpen = false;
await plugin.UsbCameraAndroid.close();
}
/// 切换分辨率。
Future<void> setResolution(String resolution) async {
await UsbCameraPrefs.setLastResolution(resolution);
await plugin.UsbCameraAndroid.setResolution(resolution);
}
/// 监听原生端插拔/权限等事件。
void startListeningEvents(
void Function(String type, String? deviceId) onEvent,
) {
_eventSub?.cancel();
_eventSub = plugin.UsbCameraAndroid.eventStream.listen((event) {
final type = event['type'] as String?;
final data = event['data'] as Map?;
final deviceId = data?['deviceId'] as String?;
onEvent(type ?? 'unknown', deviceId);
});
}
/// 释放事件监听。
Future<void> dispose() async {
await _eventSub?.cancel();
_eventSub = null;
}
}

View File

@@ -0,0 +1,36 @@
/// USB(UVC)摄像头设备实体。
class UsbCameraDevice {
const UsbCameraDevice({
required this.deviceId,
this.vendorId,
this.productId,
this.productName,
this.supportedResolutions = const [],
});
/// 系统分配的设备标识(重启可能变化,仅做本次会话使用)。
final String deviceId;
final int? vendorId;
final int? productId;
final String? productName;
/// 支持的分辨率字符串,例如 "1920x1080" / "1280x720"。
final List<String> supportedResolutions;
UsbCameraDevice copyWith({
String? deviceId,
int? vendorId,
int? productId,
String? productName,
List<String>? supportedResolutions,
}) {
return UsbCameraDevice(
deviceId: deviceId ?? this.deviceId,
vendorId: vendorId ?? this.vendorId,
productId: productId ?? this.productId,
productName: productName ?? this.productName,
supportedResolutions: supportedResolutions ?? this.supportedResolutions,
);
}
}

View File

@@ -0,0 +1,156 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:usb_camera_android/usb_camera_android.dart' as plugin;
import '../../data/uvc_camera_service.dart';
import '../../domain/usb_camera_device.dart';
import 'usb_camera_state.dart';
/// USB 摄像头页面 Cubit:枚举 → 授权 → 打开 → 预览。
class UsbCameraCubit extends Cubit<UsbCameraState> {
UsbCameraCubit(this._service) : super(const UsbCameraState()) {
_service.startListeningEvents(_onNativeEvent);
}
final UvcCameraService _service;
// ---------- 安全 emit:防止 close 后事件循环仍唤起导致 Bad state ----------
void _safeEmit(UsbCameraState newState) {
if (isClosed) return;
emit(newState);
}
// ---------- 原生事件回调(插拔等) ----------
void _onNativeEvent(String type, String? deviceId) {
// isClosed 守卫:Cubit 已销毁时忽略,避免 Bad state
if (isClosed) return;
if (type == 'detached') {
_onDeviceDetached();
}
}
// ---------- 页面初始化:枚举设备并尝试直接打开 ----------
Future<void> start() async {
_safeEmit(state.copyWith(phase: UsbCameraPhase.scanning));
try {
final devices = await _service.enumerateDevices();
if (devices.isEmpty) {
_safeEmit(state.copyWith(
phase: UsbCameraPhase.openFailed,
message: '未检测到 USB 摄像头\n请确认采集卡已插入',
));
return;
}
if (devices.length > 1) {
_safeEmit(state.copyWith(
phase: UsbCameraPhase.selecting,
devices: devices,
message: '发现 ${devices.length} 个 USB 摄像头,请选择一个',
));
return;
}
await _open(devices.first);
} catch (e) {
debugPrint('❌ [USB Camera] 枚举失败: $e');
_safeEmit(state.copyWith(
phase: UsbCameraPhase.openFailed,
message: '无法枚举 USB 设备\n$e',
));
}
}
/// 多设备列表中用户点击选择某台。
Future<void> selectAndOpen(UsbCameraDevice device) => _open(device);
/// 重新连接(重试按钮)。
Future<void> reconnect() => start();
// ---------- 核心:打开设备 ----------
Future<void> _open(UsbCameraDevice device) async {
_safeEmit(state.copyWith(
phase: UsbCameraPhase.connecting,
selected: device,
clearMessage: true,
));
try {
await _service.open(device, resolution: state.resolution);
double? aspectRatio;
try {
final size = await plugin.UsbCameraAndroid.getPreviewSize();
if (size != null && size.height > 0) {
aspectRatio = size.width / size.height;
}
} catch (_) {}
_safeEmit(state.copyWith(
phase: UsbCameraPhase.previewing,
selected: device,
previewAspectRatio: aspectRatio,
));
} on PlatformException catch (e) {
// CANCELLED:用户在权限对话框未响应就离开了页面,close() 链路主动取消了等待,
// 属于正常退出行为,不需要展示错误提示。
if (e.code == 'CANCELLED') {
debugPrint('[USB Camera] 打开被取消(用户离开页面),忽略');
return;
}
debugPrint('❌ [USB Camera] 打开失败: ${e.code} ${e.message}');
_safeEmit(state.copyWith(
phase: UsbCameraPhase.openFailed,
message: _friendlyOpenError(e),
));
} catch (e) {
debugPrint('❌ [USB Camera] 打开失败: $e');
_safeEmit(state.copyWith(
phase: UsbCameraPhase.openFailed,
message: '无法打开 USB 摄像头\n$e',
));
}
}
/// 将原生 PlatformException 转成用户友好的提示语。
String _friendlyOpenError(PlatformException e) {
final msg = e.message ?? '';
if (msg.contains('拒绝') || msg.toLowerCase().contains('permission')) {
return 'USB 权限被拒绝\n请点击「重试」,在弹窗中选择「允许」';
}
if (e.code == 'DEVICE_NOT_FOUND') {
return 'USB 设备已拔出\n请重新插入后点击「重试」';
}
return '无法打开 USB 摄像头\n$msg';
}
// ---------- 设备热拔插 ----------
void _onDeviceDetached() {
if (state.phase == UsbCameraPhase.previewing ||
state.phase == UsbCameraPhase.connecting) {
_safeEmit(state.copyWith(
phase: UsbCameraPhase.disconnected,
message: 'USB 摄像头已断开',
));
}
}
// ---------- 生命周期 ----------
@override
Future<void> close() async {
// 先取消事件订阅,避免原生回调唤醒已关闭的 Cubit
await _service.dispose();
// 再关硬件(原生层会取消等待中的 open MethodChannel,但我们已 catch CANCELLED)
await _service.close();
await super.close();
}
}

View File

@@ -0,0 +1,67 @@
import 'package:equatable/equatable.dart';
import '../../domain/usb_camera_device.dart';
enum UsbCameraPhase {
idle,
scanning, // 正在枚举 USB 设备
needPermission, // 等用户授权
selecting, // 找到多个,让用户选
connecting, // 已授权,正在打开
previewing, // 正在出画面
disconnected, // 设备被拔出
openFailed, // 打开失败
}
class UsbCameraState extends Equatable {
const UsbCameraState({
this.phase = UsbCameraPhase.idle,
this.devices = const [],
this.selected,
this.message,
this.resolution,
this.previewAspectRatio,
});
final UsbCameraPhase phase;
final List<UsbCameraDevice> devices;
final UsbCameraDevice? selected;
final String? message;
final String? resolution;
final double? previewAspectRatio;
bool get showPreview =>
phase == UsbCameraPhase.previewing ||
phase == UsbCameraPhase.disconnected;
UsbCameraState copyWith({
UsbCameraPhase? phase,
List<UsbCameraDevice>? devices,
UsbCameraDevice? selected,
bool clearSelected = false,
String? message,
bool clearMessage = false,
String? resolution,
bool clearResolution = false,
double? previewAspectRatio,
}) {
return UsbCameraState(
phase: phase ?? this.phase,
devices: devices ?? this.devices,
selected: clearSelected ? null : (selected ?? this.selected),
message: clearMessage ? null : (message ?? this.message),
resolution: clearResolution ? null : (resolution ?? this.resolution),
previewAspectRatio: previewAspectRatio ?? this.previewAspectRatio,
);
}
@override
List<Object?> get props => [
phase,
devices,
selected,
message,
resolution,
previewAspectRatio,
];
}

View File

@@ -0,0 +1,72 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/uvc_camera_service.dart';
import '../cubit/usb_camera_cubit.dart';
import '../cubit/usb_camera_state.dart';
import '../widgets/usb_camera_preview.dart';
import '../widgets/usb_camera_status_layer.dart';
/// USB 摄像头页:点击入口后直接尝试出画面,不展示额外步骤。
class UsbCameraPage extends StatelessWidget {
const UsbCameraPage({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => UsbCameraCubit(UvcCameraService())..start(),
child: const _UsbCameraView(),
);
}
}
class _UsbCameraView extends StatelessWidget {
const _UsbCameraView();
@override
Widget build(BuildContext context) {
final cubit = context.read<UsbCameraCubit>();
return BlocBuilder<UsbCameraCubit, UsbCameraState>(
builder: (context, state) {
return PopScope(
canPop: state.phase != UsbCameraPhase.connecting &&
state.phase != UsbCameraPhase.previewing,
onPopInvokedWithResult: (didPop, result) {
if (!didPop) cubit.close(); // 先释放再返回
},
child: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: const Color(0xFF165DFF),
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: () {
cubit.close();
Navigator.of(context).pop();
},
),
title: const Text(
'USB 摄像头',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
),
),
centerTitle: true,
),
body: state.showPreview && state.selected != null
? UsbCameraPreview(
device: state.selected!,
phase: state.phase,
onReconnect: cubit.reconnect,
aspectRatio: state.previewAspectRatio,
)
: UsbCameraStatusLayer(state: state, cubit: cubit),
),
);
},
);
}
}

View File

@@ -0,0 +1,87 @@
import 'package:flutter/material.dart';
import 'package:usb_camera_android/usb_camera_android.dart';
import '../../domain/usb_camera_device.dart';
import '../cubit/usb_camera_state.dart';
/// USB 摄像头预览区。
class UsbCameraPreview extends StatelessWidget {
const UsbCameraPreview({
super.key,
required this.device,
required this.phase,
required this.onReconnect,
this.aspectRatio,
});
final UsbCameraDevice device;
final UsbCameraPhase phase;
final VoidCallback onReconnect;
final double? aspectRatio;
@override
Widget build(BuildContext context) {
return Stack(
fit: StackFit.expand,
children: [
// 视频画面:保持宽高比居中,上下/左右填黑边
Container(
color: Colors.black,
child: Center(
child: aspectRatio != null
? AspectRatio(
aspectRatio: aspectRatio!,
child: const UsbCameraPreviewView(),
)
: const UsbCameraPreviewView(),
),
),
// 设备名浮层
Positioned(
left: 16,
top: 16,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(6),
),
child: Text(
device.productName ?? 'USB 摄像头',
style: const TextStyle(color: Colors.white70, fontSize: 13),
),
),
),
// 断开遮罩
if (phase == UsbCameraPhase.disconnected)
Container(
color: Colors.black.withValues(alpha: 0.65),
alignment: Alignment.center,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.usb_off, color: Colors.white54, size: 52),
const SizedBox(height: 18),
const Text(
'USB 摄像头已断开',
style: TextStyle(color: Colors.white, fontSize: 15),
),
const SizedBox(height: 22),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF165DFF),
foregroundColor: Colors.white,
),
onPressed: onReconnect,
icon: const Icon(Icons.refresh, size: 18),
label: const Text('重新连接'),
),
],
),
),
],
);
}
}

View File

@@ -0,0 +1,174 @@
import 'package:flutter/material.dart';
import '../../domain/usb_camera_device.dart';
import '../cubit/usb_camera_cubit.dart';
import '../cubit/usb_camera_state.dart';
/// 未出画面时的状态层:扫描中 / 无设备 / 多设备选择 / 失败。
class UsbCameraStatusLayer extends StatelessWidget {
const UsbCameraStatusLayer({
super.key,
required this.state,
required this.cubit,
});
final UsbCameraState state;
final UsbCameraCubit cubit;
@override
Widget build(BuildContext context) {
switch (state.phase) {
case UsbCameraPhase.scanning:
case UsbCameraPhase.connecting:
return _center(
icon: Icons.usb,
spinning: true,
message: state.phase == UsbCameraPhase.scanning
? '正在检测 USB 摄像头…'
: '正在打开 USB 摄像头…',
);
case UsbCameraPhase.selecting:
return _deviceList(state.devices);
case UsbCameraPhase.openFailed:
return _center(
icon: Icons.usb_off,
message: state.message ?? 'USB 摄像头打开失败',
actionLabel: '重试',
onAction: cubit.reconnect,
);
case UsbCameraPhase.needPermission:
case UsbCameraPhase.idle:
case UsbCameraPhase.previewing:
case UsbCameraPhase.disconnected:
return _center(icon: Icons.usb, message: state.message ?? '准备就绪');
}
}
Widget _center({
required IconData icon,
required String message,
bool spinning = false,
String? actionLabel,
VoidCallback? onAction,
}) {
return Container(
color: Colors.black,
alignment: Alignment.center,
// FittedBox:嵌进受限高度的小窗(如 pv 控制页视频区)时整组等比缩小,
// 避免「重试」按钮溢出;全屏独立页空间充足时保持原样。
child: FittedBox(
fit: BoxFit.scaleDown,
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (spinning)
const SizedBox(
width: 42,
height: 42,
child: CircularProgressIndicator(
color: Color(0xFF165DFF),
strokeWidth: 3,
),
)
else
Icon(icon, color: Colors.white54, size: 52),
const SizedBox(height: 18),
Text(
message,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white,
fontSize: 15,
height: 1.5,
),
),
if (actionLabel != null && onAction != null) ...[
const SizedBox(height: 22),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF165DFF),
foregroundColor: Colors.white,
),
onPressed: onAction,
icon: const Icon(Icons.refresh, size: 18),
label: Text(actionLabel),
),
],
],
),
),
),
);
}
Widget _deviceList(List<UsbCameraDevice> devices) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Text(
'发现多个 USB 摄像头,请点击选择',
style: TextStyle(color: Colors.white70, fontSize: 14),
),
),
Expanded(
child: ListView.separated(
padding: const EdgeInsets.symmetric(horizontal: 12),
itemCount: devices.length,
separatorBuilder: (context, index) => const SizedBox(height: 8),
itemBuilder: (context, i) {
final d = devices[i];
return Material(
color: const Color(0xFF1C1C1E),
borderRadius: BorderRadius.circular(12),
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () => cubit.selectAndOpen(d),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 14,
),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: const Color(
0xFF165DFF,
).withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(10),
),
child: const Icon(
Icons.usb,
color: Color(0xFF165DFF),
size: 22,
),
),
const SizedBox(width: 12),
Expanded(
child: Text(
d.productName ?? d.deviceId,
style: const TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
),
const Icon(Icons.chevron_right, color: Colors.white38),
],
),
),
),
);
},
),
),
],
);
}
}