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 { private readonly UsbCameraOptions _options; private readonly ILogger _logger; // 串行化所有对 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; 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 event EventHandler? StatusChanged; public event EventHandler? FrameArrived; public UsbCameraService( IOptions options, ILogger logger) { _options = options.Value; _logger = logger; } // ---------- 连接 ---------- 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 { 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); 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; _device?.Dispose(); _device = null; throw; } catch (Exception ex) { _connected = false; _frameFormat = null; _deviceName = null; _device?.Dispose(); _device = null; _logger.LogError(ex, "连接相机失败"); throw new HardwareException( HardwareErrorKind.ConnectFailed, "连接相机失败", ex); } } private CaptureDeviceDescriptor SelectDescriptor( List descriptors) { 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(); if (_connected) { _connected = false; Interlocked.Exchange(ref _connectedAtTicks, 0); StatusChanged?.Invoke(this, new(false, "相机已断开")); } } // ---------- 重连监控 ---------- /// /// 保证只有一个重连监控循环。重连成功时 ConnectCoreAsync 会调用它, /// 若当前循环仍在运行则不会重复创建。 /// 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); } } } /// 检查当前连接是否长时间没有新帧。 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); } /// 画面超时时由监控循环调用:停止旧设备并通知前端。 private async Task MarkDisconnectedAsync(string message, CancellationToken ct) { await _gate.WaitAsync(ct); try { if (!_connected) { return; } _connected = false; Interlocked.Exchange(ref _connectedAtTicks, 0); 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(); } } }