using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareWeb.Hubs;
using HardwareWeb.Models;
using Microsoft.AspNetCore.SignalR;
namespace HardwareWeb.Services
{
///
/// 统一管理位移台、对焦系统、光谱仪和相机的连接状态。
/// 软件启动时自动连接一次;任一设备失败会在首页提示,并支持重试。
///
public sealed class DeviceConnectionService
{
private const string StageKey = "stage";
private const string FocusKey = "focus";
private const string SpectrometerKey = "spectrometer";
private const string CameraKey = "camera";
private readonly IAxisStageService _stage;
private readonly IFocusSystemService _focus;
private readonly IArisSpectrometerService _spectrometer;
private readonly IUsbCameraService _camera;
private readonly IHubContext _hub;
private readonly ILogger _logger;
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly object _statusGate = new();
private readonly Dictionary _statuses;
public DeviceConnectionService(
IAxisStageService stage,
IFocusSystemService focus,
IArisSpectrometerService spectrometer,
IUsbCameraService camera,
IHubContext hub,
ILogger logger)
{
_stage = stage;
_focus = focus;
_spectrometer = spectrometer;
_camera = camera;
_hub = hub;
_logger = logger;
var now = DateTimeOffset.Now;
_statuses = new Dictionary(
StringComparer.OrdinalIgnoreCase)
{
[StageKey] = new(StageKey, "位移台", false, "unknown", "尚未连接", now),
[FocusKey] = new(FocusKey, "对焦系统", false, "unknown", "尚未连接", now),
[SpectrometerKey] = new(SpectrometerKey, "光谱仪", false, "unknown", "尚未连接", now),
[CameraKey] = new(CameraKey, "相机", false, "unknown", "尚未连接", now),
};
}
public DeviceStatusPayload GetSnapshot()
{
lock (_statusGate)
{
var devices = _statuses.Values
.OrderBy(item => item.Key switch
{
StageKey => 0,
FocusKey => 1,
SpectrometerKey => 2,
CameraKey => 3,
_ => 9,
})
.ToList();
return new DeviceStatusPayload(
devices.All(item => item.Connected),
devices,
DateTimeOffset.Now);
}
}
/// 连接所有尚未连接的设备。
public async Task ConnectAllAsync(
CancellationToken ct = default)
{
await _gate.WaitAsync(ct);
try
{
await ConnectOneAsync(
StageKey,
"位移台",
() => _stage.IsConnected,
() => _stage.ConnectAsync(ct),
ct);
await ConnectOneAsync(
FocusKey,
"对焦系统",
() => _focus.IsConnected,
() => _focus.ConnectAsync(ct),
ct);
await ConnectOneAsync(
SpectrometerKey,
"光谱仪",
() => _spectrometer.IsConnected,
() => _spectrometer.ConnectAsync(ct),
ct);
await ConnectOneAsync(
CameraKey,
"相机",
() => _camera.IsConnected,
() => _camera.ConnectAsync(ct),
ct);
}
finally
{
_gate.Release();
}
var snapshot = GetSnapshot();
await BroadcastAsync(snapshot);
return snapshot;
}
/// 重试连接失败或未连接的设备。
public Task RetryFailedAsync(
CancellationToken ct = default) => ConnectAllAsync(ct);
private async Task ConnectOneAsync(
string key,
string name,
Func isConnected,
Func connect,
CancellationToken ct)
{
if (isConnected())
{
SetStatus(key, name, true, "connected", null);
return;
}
SetStatus(key, name, false, "connecting", "正在连接...");
try
{
await connect();
if (isConnected())
{
SetStatus(key, name, true, "connected", null);
_logger.LogInformation("{Name}已连接", name);
}
else
{
SetStatus(key, name, false, "failed", "连接后设备状态仍为未连接");
_logger.LogWarning("{Name}连接后状态仍为未连接", name);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
SetStatus(key, name, false, "unknown", "连接已取消");
throw;
}
catch (Exception ex)
{
SetStatus(key, name, false, "failed", ex.Message);
_logger.LogWarning(ex, "连接{Name}失败", name);
}
}
private void SetStatus(
string key,
string name,
bool connected,
string status,
string? message)
{
lock (_statusGate)
{
_statuses[key] = new DeviceStatusItemPayload(
key,
name,
connected,
status,
message,
DateTimeOffset.Now);
}
}
private async Task BroadcastAsync(DeviceStatusPayload snapshot)
{
try
{
await _hub.Clients.All.SendAsync("DeviceStatus", snapshot);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "推送设备状态失败");
}
}
}
/// 软件启动后在后台连接所有硬件设备。
public sealed class DeviceStartupService : BackgroundService
{
private readonly DeviceConnectionService _devices;
private readonly ILogger _logger;
public DeviceStartupService(
DeviceConnectionService devices,
ILogger logger)
{
_devices = devices;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
// 等 Web 主机就绪后再连接,避免拖慢启动。
await Task.Delay(TimeSpan.FromMilliseconds(500), stoppingToken);
_logger.LogInformation("开始连接所有硬件设备");
await _devices.ConnectAllAsync(stoppingToken);
}
catch (OperationCanceledException)
{
// 正常停机
}
catch (Exception ex)
{
_logger.LogError(ex, "启动时连接硬件设备失败");
}
}
}
}