Files
2026-11-17 16:28:24 +08:00

513 lines
17 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using FlashCap;
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareControl.Core.UsbCamera;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace HardwareControl.Core.HardwareServiceImpl
{
public class UsbCameraService : IUsbCameraService
{
// 系统参数中保存相机硬件 ID 的配置名称
private const string CameraVidConfigName = "camera_vid";
private readonly UsbCameraOptions _options;
private readonly ILogger<UsbCameraService> _logger;
private readonly ISystemConfigService? _systemConfig;
// 串行化所有对 FlashCap 设备对象的访问
private readonly SemaphoreSlim _gate = new(1, 1);
private CaptureDevice? _device;
private CancellationTokenSource? _reconnectCts;
private volatile bool _connected;
private volatile CameraFrameFormat? _frameFormat;
private volatile string? _deviceName;
private long _lastFrameAtTicks;
private long _framesReceived;
private long _connectedAtTicks;
private volatile CameraFrameSnapshot? _latestFrame;
public bool IsConnected => _connected;
public string? DeviceName => _deviceName;
public CameraFrameFormat? FrameFormat => _frameFormat;
public DateTimeOffset? LastFrameAt
{
get
{
var ticks = Interlocked.Read(ref _lastFrameAtTicks);
return ticks == 0 ? null : new DateTimeOffset(ticks, TimeSpan.Zero);
}
}
public long FramesReceived => Interlocked.Read(ref _framesReceived);
public CameraFrameSnapshot? GetLatestFrame() => _latestFrame;
public event EventHandler<UsbCameraStatusChangedEventArgs>? StatusChanged;
public event EventHandler<FrameArrivedEventArgs>? FrameArrived;
public UsbCameraService(
IOptions<UsbCameraOptions> options,
ILogger<UsbCameraService> logger,
ISystemConfigService? systemConfig = null)
{
_options = options.Value;
_logger = logger;
_systemConfig = systemConfig;
RefreshCameraVid();
}
/// <summary>
/// 从系统参数读取 camera_vid 并写入 <see cref="UsbCameraOptions"/>。
/// 读取失败时保留原有配置,不影响相机连接流程。
/// </summary>
private void RefreshCameraVid()
{
if (_systemConfig is null)
{
return;
}
try
{
var config = _systemConfig
.GetAll()
.FirstOrDefault(c => string.Equals(
c.ConfigName, CameraVidConfigName, StringComparison.OrdinalIgnoreCase));
var value = config?.ConfigValue?.Trim();
if (string.IsNullOrWhiteSpace(value) ||
string.Equals(_options.CameraVid, value, StringComparison.Ordinal))
{
return;
}
_options.CameraVid = value;
_logger.LogInformation(
"相机选择使用系统参数 {ConfigName}={CameraVid}",
CameraVidConfigName,
value);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "读取系统参数 {ConfigName} 失败", CameraVidConfigName);
}
}
// ---------- 连接 ----------
public async Task ConnectAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct);
try
{
if (_connected) return;
await ConnectCoreAsync(ct);
}
finally
{
_gate.Release();
}
}
private async Task ConnectCoreAsync(CancellationToken ct)
{
try
{
// 每次连接前重新读取系统参数,管理界面修改 camera_vid 后重连即可生效
RefreshCameraVid();
_latestFrame = null;
var devices = new CaptureDevices();
var descriptors = devices.EnumerateDescriptors().ToList();
if (descriptors.Count == 0)
throw new HardwareException(
HardwareErrorKind.ConnectFailed, "没有枚举到任何相机设备");
var descriptor = SelectDescriptor(descriptors);
var characteristics = SelectCharacteristics(descriptor);
var format = CameraFrameFormat.From(characteristics);
_logger.LogInformation(
"尝试打开相机:{Device},格式:{Format}({Width}x{Height},{Fps:F1}fps,{Mime})",
descriptor, characteristics,
format.Width, format.Height, format.FramesPerSecond, format.MimeType);
Interlocked.Exchange(ref _framesReceived, 0);
Interlocked.Exchange(ref _lastFrameAtTicks, 0);
_frameFormat = format;
_deviceName = descriptor.Name;
// 注意:OpenAsync 的回调在 FlashCap 内部线程执行,
// 回调内不能阻塞太久,否则会丢帧。
_device = await descriptor.OpenAsync(
characteristics,
async bufferScope =>
{
try
{
if (!_connected)
{
// 已断开或正在重连,丢弃旧设备回调中的帧
return;
}
// ExtractImage() 可能返回 FlashCap 内部复用的缓冲区,
// 而帧会进入 Channel 异步发送,必须用 CopyImage() 取得独立副本。
byte[] image = bufferScope.Buffer.CopyImage();
long frameIndex = bufferScope.Buffer.FrameIndex;
var timestamp = bufferScope.Buffer.Timestamp;
var capturedAt = DateTimeOffset.Now;
Interlocked.Increment(ref _framesReceived);
Interlocked.Exchange(ref _lastFrameAtTicks, capturedAt.UtcTicks);
// 缓存独立副本,供后台按需抓帧(事件回调仍使用同一份数据)
_latestFrame = new CameraFrameSnapshot(
image,
format.Width,
format.Height,
format.MimeType,
capturedAt,
frameIndex);
FrameArrived?.Invoke(
this,
new FrameArrivedEventArgs(
image, frameIndex, timestamp, capturedAt, format));
}
catch (Exception ex)
{
_logger.LogWarning(ex, "抓帧回调中发生异常");
}
});
await _device.StartAsync();
Interlocked.Exchange(
ref _connectedAtTicks, DateTimeOffset.UtcNow.UtcTicks);
_connected = true;
_logger.LogInformation("相机已连接并开始采集");
StatusChanged?.Invoke(this, new(true, "相机已连接"));
// 启动后台监控(用于检测断线与画面超时)
EnsureReconnectWatcher();
}
catch (HardwareException)
{
_connected = false;
_frameFormat = null;
_deviceName = null;
_latestFrame = null;
_device?.Dispose();
_device = null;
throw;
}
catch (Exception ex)
{
_connected = false;
_frameFormat = null;
_deviceName = null;
_latestFrame = null;
_device?.Dispose();
_device = null;
_logger.LogError(ex, "连接相机失败");
throw new HardwareException(
HardwareErrorKind.ConnectFailed, "连接相机失败", ex);
}
}
private CaptureDeviceDescriptor SelectDescriptor(
List<CaptureDeviceDescriptor> descriptors)
{
// 优先按系统参数 camera_vid 匹配设备的 Identity。
// Identity 在不同设备/平台上大小写不一致,统一转大写后比较。
var cameraVid = _options.CameraVid?.Trim();
if (!string.IsNullOrWhiteSpace(cameraVid))
{
var target = cameraVid.ToUpperInvariant();
var matched = descriptors.FirstOrDefault(d =>
{
var identity = d.Identity?.ToString();
return identity is not null &&
identity.ToUpperInvariant().Contains(target);
});
if (matched != null) return matched;
_logger.LogWarning(
"未找到 Identity 包含 {CameraVid} 的相机,回退到名称关键词选择",
cameraVid);
}
if (!string.IsNullOrWhiteSpace(_options.DeviceNameKeyword))
{
var matched = descriptors.FirstOrDefault(
d => d.Name.Contains(
_options.DeviceNameKeyword, StringComparison.OrdinalIgnoreCase));
if (matched != null) return matched;
_logger.LogWarning(
"未找到名称包含 {Keyword} 的设备,回退到第一个设备",
_options.DeviceNameKeyword);
}
return descriptors[0];
}
private VideoCharacteristics SelectCharacteristics(
CaptureDeviceDescriptor descriptor)
{
var all = descriptor.Characteristics;
if (!string.IsNullOrWhiteSpace(_options.PreferredFormatKeyword))
{
var matched = all.FirstOrDefault(
c => c.ToString().Contains(
_options.PreferredFormatKeyword, StringComparison.OrdinalIgnoreCase));
if (matched != null) return matched;
_logger.LogWarning(
"未找到格式包含 {Keyword} 的配置,回退到第一个格式",
_options.PreferredFormatKeyword);
}
return all[0];
}
// ---------- 断开 ----------
public async Task DisconnectAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct);
try
{
await DisconnectCoreAsync();
}
finally
{
_gate.Release();
}
}
private async Task DisconnectCoreAsync()
{
CancelReconnectWatcher();
await StopDeviceAsync();
_latestFrame = null;
if (_connected)
{
_connected = false;
Interlocked.Exchange(ref _connectedAtTicks, 0);
StatusChanged?.Invoke(this, new(false, "相机已断开"));
}
}
// ---------- 重连监控 ----------
/// <summary>
/// 保证只有一个重连监控循环。重连成功时 ConnectCoreAsync 会调用它,
/// 若当前循环仍在运行则不会重复创建。
/// </summary>
private void EnsureReconnectWatcher()
{
var existing = _reconnectCts;
if (existing is { IsCancellationRequested: false })
{
return;
}
existing?.Dispose();
_reconnectCts = new CancellationTokenSource();
var token = _reconnectCts.Token;
_ = Task.Run(() => ReconnectLoopAsync(token));
}
private void CancelReconnectWatcher()
{
var cts = _reconnectCts;
_reconnectCts = null;
if (cts is null)
{
return;
}
try
{
cts.Cancel();
}
catch (ObjectDisposedException)
{
// 已释放,忽略
}
cts.Dispose();
}
private async Task ReconnectLoopAsync(CancellationToken ct)
{
var baseDelay = Math.Max(250, _options.ReconnectBaseDelayMs);
var maxDelay = Math.Max(baseDelay, _options.ReconnectMaxDelayMs);
var delay = baseDelay;
while (!ct.IsCancellationRequested)
{
try
{
await Task.Delay(delay, ct);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
if (ct.IsCancellationRequested)
{
break;
}
if (_connected)
{
if (!HasFrameTimedOut())
{
continue;
}
_logger.LogWarning(
"超过 {Timeout}ms 未收到相机帧,标记断线并重连",
_options.FrameTimeoutMs);
try
{
await MarkDisconnectedAsync("相机画面超时,正在重连...", ct);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
}
_logger.LogInformation("检测到断线,尝试重连...");
StatusChanged?.Invoke(this, new(false, "正在重连..."));
try
{
await _gate.WaitAsync(ct);
try
{
if (_connected)
{
continue;
}
await ConnectCoreAsync(ct);
delay = baseDelay;
}
finally
{
_gate.Release();
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "重连失败,{Delay}ms 后重试", delay);
delay = Math.Min(delay * 2, maxDelay);
}
}
}
/// <summary>检查当前连接是否长时间没有新帧。</summary>
private bool HasFrameTimedOut()
{
var timeoutMs = _options.FrameTimeoutMs;
if (timeoutMs <= 0)
{
return false;
}
var referenceTicks = Interlocked.Read(ref _lastFrameAtTicks);
if (referenceTicks == 0)
{
referenceTicks = Interlocked.Read(ref _connectedAtTicks);
}
if (referenceTicks == 0)
{
return false;
}
var reference = new DateTimeOffset(referenceTicks, TimeSpan.Zero);
return DateTimeOffset.UtcNow - reference >
TimeSpan.FromMilliseconds(timeoutMs);
}
/// <summary>画面超时时由监控循环调用:停止旧设备并通知前端。</summary>
private async Task MarkDisconnectedAsync(string message, CancellationToken ct)
{
await _gate.WaitAsync(ct);
try
{
if (!_connected)
{
return;
}
_connected = false;
Interlocked.Exchange(ref _connectedAtTicks, 0);
_latestFrame = null;
await StopDeviceAsync();
StatusChanged?.Invoke(this, new(false, message));
}
finally
{
_gate.Release();
}
}
private async Task StopDeviceAsync()
{
var device = _device;
_device = null;
if (device is null)
{
return;
}
try
{
await device.StopAsync();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "停止采集时发生异常");
}
device.Dispose();
}
// ---------- 释放 ----------
public async ValueTask DisposeAsync()
{
await DisconnectAsync();
_gate.Dispose();
}
}
}