using HardwareControl.Core.HardwareServiceImpl.HardwareService; using HardwareWeb.Models; using HardwareWeb.Services; using Microsoft.AspNetCore.SignalR; namespace HardwareWeb.Hubs { /// /// 相机实时通道: /// - 连接后自动加入画面组,并立即收到一次 CameraStatus; /// - 前端可调用 SubscribeFrames / UnsubscribeFrames 暂停或恢复画面; /// - GetStatus 用于页面刷新或断线重连后的状态对齐。 /// public class CameraHub : Hub { public const string FrameGroup = "camera-frames"; private readonly IUsbCameraService _cameraService; private readonly CameraViewerRegistry _viewers; private readonly ILogger _logger; public CameraHub( IUsbCameraService cameraService, CameraViewerRegistry viewers, ILogger logger) { _cameraService = cameraService; _viewers = viewers; _logger = logger; } public override async Task OnConnectedAsync() { await base.OnConnectedAsync(); await JoinFrameGroupAsync(Context.ConnectionId, Context.ConnectionAborted); await SendStatusAsync(Clients.Caller, Context.ConnectionAborted); _logger.LogInformation( "SignalR 客户端已连接:{ConnectionId},当前画面观看者 {Count}", Context.ConnectionId, _viewers.Count); } public override async Task OnDisconnectedAsync(Exception? exception) { _viewers.Remove(Context.ConnectionId); await base.OnDisconnectedAsync(exception); _logger.LogInformation( "SignalR 客户端已断开:{ConnectionId},当前画面观看者 {Count}", Context.ConnectionId, _viewers.Count); } /// 读取当前相机状态,不改变订阅。 public CameraStatusPayload GetStatus() => CameraStatusPayload.From(_cameraService); /// 恢复画面推送。连接时默认已订阅,可重复调用。 public async Task SubscribeFrames() { await JoinFrameGroupAsync(Context.ConnectionId, Context.ConnectionAborted); return CameraStatusPayload.From(_cameraService); } /// 停止接收画面,但仍可接收 CameraStatus。 public async Task UnsubscribeFrames() { await Groups.RemoveFromGroupAsync( Context.ConnectionId, FrameGroup, Context.ConnectionAborted); _viewers.Remove(Context.ConnectionId); _logger.LogInformation( "客户端暂停画面:{ConnectionId},当前画面观看者 {Count}", Context.ConnectionId, _viewers.Count); } private async Task JoinFrameGroupAsync( string connectionId, CancellationToken ct) { try { await Groups.AddToGroupAsync(connectionId, FrameGroup, ct); _viewers.Add(connectionId); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogWarning( ex, "加入相机画面组失败:{ConnectionId}", connectionId); } } private async Task SendStatusAsync(IClientProxy client, CancellationToken ct) { try { await client.SendAsync( "CameraStatus", CameraStatusPayload.From(_cameraService), ct); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogWarning( ex, "发送相机初始状态失败:{ConnectionId}", Context.ConnectionId); } } } }