99 lines
3.3 KiB
C#
99 lines
3.3 KiB
C#
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
|
using HardwareControl.Core.Scanning;
|
|
using HardwareWeb.Models;
|
|
using HardwareWeb.Services;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
|
|
namespace HardwareWeb.Hubs
|
|
{
|
|
/// <summary>
|
|
/// 扫描实时通道:
|
|
/// * 连接后立即推送设备状态、扫描进度和位移台当前位置;
|
|
/// * 服务端事件:StagePosition / ScanProgress / ScanSpectrum / ScanFinished / DeviceStatus。
|
|
/// </summary>
|
|
public class StageHub : Hub
|
|
{
|
|
private readonly IScanWorkflowService _workflow;
|
|
private readonly IAxisStageService _stage;
|
|
private readonly DeviceConnectionService _devices;
|
|
private readonly ILogger<StageHub> _logger;
|
|
|
|
public StageHub(
|
|
IScanWorkflowService workflow,
|
|
IAxisStageService stage,
|
|
DeviceConnectionService devices,
|
|
ILogger<StageHub> logger)
|
|
{
|
|
_workflow = workflow;
|
|
_stage = stage;
|
|
_devices = devices;
|
|
_logger = logger;
|
|
}
|
|
|
|
public override async Task OnConnectedAsync()
|
|
{
|
|
await base.OnConnectedAsync();
|
|
|
|
await SendSafeAsync("DeviceStatus", _devices.GetSnapshot());
|
|
await SendSafeAsync("ScanProgress", ScanProgressPayload.From(_workflow.Current));
|
|
|
|
var position = await ReadStagePositionAsync();
|
|
if (position is not null)
|
|
{
|
|
await SendSafeAsync("StagePosition", position);
|
|
}
|
|
|
|
_logger.LogInformation("扫描实时通道已连接:{ConnectionId}", Context.ConnectionId);
|
|
}
|
|
|
|
public override Task OnDisconnectedAsync(Exception? exception)
|
|
{
|
|
_logger.LogInformation("扫描实时通道已断开:{ConnectionId}", Context.ConnectionId);
|
|
return base.OnDisconnectedAsync(exception);
|
|
}
|
|
|
|
public DeviceStatusPayload GetDeviceStatus() => _devices.GetSnapshot();
|
|
|
|
public ScanProgressPayload GetScanProgress() =>
|
|
ScanProgressPayload.From(_workflow.Current);
|
|
|
|
public Task<StagePositionPayload?> GetStagePosition() => ReadStagePositionAsync();
|
|
|
|
private async Task<StagePositionPayload?> ReadStagePositionAsync()
|
|
{
|
|
if (!_stage.IsConnected)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
try
|
|
{
|
|
var status = await _stage.ReadStatusAsync(300, Context.ConnectionAborted);
|
|
return new StagePositionPayload(
|
|
status.XPosition,
|
|
status.YPosition,
|
|
status.ZPosition,
|
|
status.AnyMoving,
|
|
DateTimeOffset.Now);
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
_logger.LogDebug(ex, "读取位移台位置失败");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private async Task SendSafeAsync(string method, object payload)
|
|
{
|
|
try
|
|
{
|
|
await Clients.Caller.SendAsync(method, payload, Context.ConnectionAborted);
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
_logger.LogDebug(ex, "发送初始状态失败:{Method}", method);
|
|
}
|
|
}
|
|
}
|
|
}
|