Files
SpectraElement/HardwareControl.Core/HardwareServiceImpl/FocusSystemService.cs
T

638 lines
22 KiB
C#
Raw 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 HardwareControl.Core.FocusSystem;
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace HardwareControl.Core.HardwareServiceImpl
{
/// <summary>
/// 定焦系统服务实现:FocusSystem2.dll 负责串口与协议,
/// 本类负责串口参数解析、调用串行化、错误映射与日志。
/// </summary>
public sealed class FocusSystemService : IFocusSystemService
{
// 系统参数中保存对焦硬件串口的配置名称
private const string ComPortConfigName = "focus_com";
private readonly FocusSystemOptions _options;
private readonly ILogger<FocusSystemService> _logger;
private readonly ISystemConfigService? _systemConfig;
// 串行化所有原生调用,DLL 句柄不支持并发访问
private readonly SemaphoreSlim _gate = new(1, 1);
private IntPtr _handle = IntPtr.Zero;
private volatile bool _connected;
private volatile string? _portName;
private bool _disposed;
public FocusSystemService(
IOptions<FocusSystemOptions> options,
ILogger<FocusSystemService> logger,
ISystemConfigService? systemConfig = null)
{
_options = options.Value;
_logger = logger;
_systemConfig = systemConfig;
}
public bool IsConnected => _connected;
public string? PortName => _portName;
public event EventHandler<FocusSystemStatusChangedEventArgs>? StatusChanged;
// ---------- 连接 ----------
public async Task ConnectAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
if (_connected)
{
return;
}
await Task.Run(ConnectCore, CancellationToken.None).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
private void ConnectCore()
{
var port = ResolvePort();
try
{
_logger.LogInformation("正在打开对焦系统串口 {Port}", port);
var handle = FocusSystemNative.focus_init(port);
if (handle == IntPtr.Zero)
{
throw new HardwareException(
HardwareErrorKind.ConnectFailed,
$"打开对焦系统串口 {port} 失败:串口不存在或被占用");
}
_handle = handle;
_connected = true;
_portName = port;
_logger.LogInformation("对焦系统串口已打开:{Port}", port);
StatusChanged?.Invoke(
this,
new FocusSystemStatusChangedEventArgs(true, $"对焦系统已连接:{port}"));
}
catch (HardwareException)
{
ResetConnectionState();
throw;
}
catch (Exception ex) when (ex is DllNotFoundException
or BadImageFormatException
or EntryPointNotFoundException)
{
ResetConnectionState();
_logger.LogError(ex, "加载 FocusSystem2.dll 失败");
throw new HardwareException(
HardwareErrorKind.ConnectFailed,
BuildNativeLoadFailureMessage(ex),
ex);
}
catch (Exception ex)
{
ResetConnectionState();
_logger.LogError(ex, "打开对焦系统串口时发生未预期异常");
throw new HardwareException(
HardwareErrorKind.ConnectFailed,
"连接对焦系统失败",
ex);
}
}
/// <summary>
/// 串口优先取系统参数 focus_com;为空时回退到 appsettings 的 FocusSystem:ComPort。
/// </summary>
private string ResolvePort()
{
string? configured = null;
try
{
configured = _systemConfig?
.GetAll()
.FirstOrDefault(config => string.Equals(
config.ConfigName,
ComPortConfigName,
StringComparison.OrdinalIgnoreCase))?
.ConfigValue?
.Trim();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "读取系统参数 {ConfigName} 失败", ComPortConfigName);
}
var port = !string.IsNullOrWhiteSpace(configured)
? configured
: _options.ComPort?.Trim();
if (string.IsNullOrWhiteSpace(port))
{
throw new HardwareException(
HardwareErrorKind.InvalidArgument,
$"未配置对焦系统串口:请先在系统参数中添加 {ComPortConfigName}(例如 COM6)");
}
return SerialPortNames.Normalize(port);
}
// ---------- 断开 ----------
public async Task DisconnectAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_disposed)
{
return;
}
var wasConnected = _connected;
CloseHandle();
if (wasConnected)
{
_logger.LogInformation("对焦系统串口已关闭");
StatusChanged?.Invoke(
this,
new FocusSystemStatusChangedEventArgs(false, "对焦系统已断开"));
}
}
finally
{
_gate.Release();
}
}
private void CloseHandle()
{
var handle = _handle;
ResetConnectionState();
if (handle == IntPtr.Zero)
{
return;
}
try
{
FocusSystemNative.focus_close(handle);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "关闭对焦系统串口时发生异常");
}
}
private void ResetConnectionState()
{
_handle = IntPtr.Zero;
_connected = false;
_portName = null;
}
// ---------- 命令 ----------
public Task StartSingleFocusAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_single_focus, "单次对焦", ct);
public Task StartContinuousFocusAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_continuous_focus, "连续对焦", ct);
public Task EnterCalibrationModeAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_calib_mode, "进入校准模式", ct);
public Task MoveCalibrationAsync(
int distanceMm,
int? speed = null,
CancellationToken ct = default)
{
var distance = ToInt8(distanceMm, "校准位移");
var speedValue = speed ?? _options.DefaultCalibrationSpeed;
if (speedValue is <= 0 or > ushort.MaxValue)
{
return Task.FromException(new HardwareException(
HardwareErrorKind.InvalidArgument,
$"校准速度 {speedValue} 超出范围(1~{ushort.MaxValue})"));
}
return ExecuteAsync(
handle => FocusSystemNative.focus_calib_move(
handle,
distance,
(ushort)speedValue),
$"校准位移 {distance}mm",
ct);
}
public Task SaveCalibrationAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_calib_save, "保存校准参数", ct);
public Task TurnLaserOnAsync(byte frequency, CancellationToken ct = default) =>
ExecuteAsync(
handle => FocusSystemNative.focus_laser_on(handle, frequency),
$"激光器出光(频率 {frequency}Hz)",
ct);
public Task TurnLaserOffAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_laser_off, "激光器关光", ct);
public Task SetLaserPowerAsync(byte power, CancellationToken ct = default) =>
ExecuteAsync(
handle => FocusSystemNative.focus_laser_power(handle, power),
$"设置激光能量 {power}",
ct);
public Task StartSingleRangeAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_single_range, "单次测距", ct);
public Task StartContinuousRangeAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_continuous_range, "连续测距", ct);
public Task ControlLiftAsync(int position, CancellationToken ct = default)
{
var target = ToInt8(position, "升降位置");
return ExecuteAsync(
handle => FocusSystemNative.focus_lift_control(handle, target),
$"升降机构移动到 {target}",
ct);
}
public Task SetExternalTriggerAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_ext_trigger_set, "外部触发设置", ct);
public Task FireExternalTriggerAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_ext_trigger_fire, "外部触发出光", ct);
public Task StartAutoDescendAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_auto_descend, "自动下降检测", ct);
public Task StartFixedCycleAsync(
ushort intervalMs,
ushort count,
CancellationToken ct = default) =>
ExecuteAsync(
handle => FocusSystemNative.focus_fixed_cycle(handle, intervalMs, count),
$"固定周期出光(周期 {intervalMs}ms,{count} 次)",
ct);
public Task SetSyncTimeAsync(
FocusSyncTime parameters,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(parameters);
var native = new Focus2SyncTimeParams
{
DelayUs = parameters.DelayUs,
OffsetUs = parameters.OffsetUs,
HoldUs = parameters.HoldUs,
HoldOffsetUs = parameters.HoldOffsetUs,
};
return ExecuteAsync(
handle => FocusSystemNative.focus_sync_time_set(handle, ref native),
"设置光谱仪同步延时",
ct);
}
public Task RequestSyncTimeAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_sync_time_get, "获取光谱仪同步延时", ct);
public Task PowerOffAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_power_off, "总电源关机", ct);
private async Task ExecuteAsync(
Func<IntPtr, int> command,
string operation,
CancellationToken ct)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
ct.ThrowIfCancellationRequested();
// 命令内部会等待设备应答,放到线程池避免占用请求线程
var result = await Task.Run(
() => command(handle),
CancellationToken.None)
.ConfigureAwait(false);
EnsureSuccess(handle, result, operation);
_logger.LogInformation("对焦系统:{Operation}完成", operation);
}
finally
{
_gate.Release();
}
}
// ---------- 查询 ----------
public async Task<FocusSystemStatus> ReadSystemInfoAsync(
int? timeoutMs = null,
CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
var timeout = NormalizeTimeout(timeoutMs);
return await Task.Run(
() => ReadSystemInfoCore(handle, timeout, ct),
CancellationToken.None)
.ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
private FocusSystemStatus ReadSystemInfoCore(
IntPtr handle,
int timeoutMs,
CancellationToken ct)
{
var deadline = Environment.TickCount64 + timeoutMs;
var retryInterval = ResolveRetryInterval();
while (true)
{
ct.ThrowIfCancellationRequested();
var result = FocusSystemNative.focus_read_sys_info(handle, out var info);
if (result == FocusSystemNative.Ok)
{
var status = MapStatus(info);
_logger.LogDebug(
"对焦系统信息:位置={Position},错误={Error},激光在线={LaserOnline},电压={Voltage:F1}V",
status.FocusPosition,
status.Error,
status.LaserOnline,
status.VoltageVolts);
return status;
}
// 未收到应答/解析失败时在超时时间内重试,其余错误立即抛出
if (result is not (FocusSystemNative.ErrTimeout
or FocusSystemNative.ErrParseFailed))
{
throw MapNativeError(handle, result, "读取对焦系统信息");
}
if (Environment.TickCount64 >= deadline)
{
var detail = result == FocusSystemNative.ErrTimeout
? "未收到应答"
: "CRC 校验失败或载荷不足";
throw new HardwareException(
HardwareErrorKind.Timeout,
$"读取对焦系统信息超时({timeoutMs}ms):{detail}");
}
Thread.Sleep(retryInterval);
}
}
public async Task<FocusRealTimeResult> ReadResultAsync(
int? timeoutMs = null,
CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
var timeout = NormalizeTimeout(timeoutMs);
return await Task.Run(
() => ReadResultCore(handle, timeout, ct),
CancellationToken.None)
.ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
private FocusRealTimeResult ReadResultCore(
IntPtr handle,
int timeoutMs,
CancellationToken ct)
{
var deadline = Environment.TickCount64 + timeoutMs;
var retryInterval = ResolveRetryInterval();
while (true)
{
ct.ThrowIfCancellationRequested();
var result = FocusSystemNative.focus_query_result(handle, out var response);
if (result == FocusSystemNative.Ok)
{
return MapResult(response);
}
// 非阻塞查询,未找到结果帧时继续轮询
if (result != FocusSystemNative.ErrTimeout)
{
throw MapNativeError(handle, result, "查询对焦系统结果");
}
if (Environment.TickCount64 >= deadline)
{
throw new HardwareException(
HardwareErrorKind.Timeout,
$"查询对焦系统结果超时({timeoutMs}ms):未找到结果帧");
}
Thread.Sleep(retryInterval);
}
}
private static FocusSystemStatus MapStatus(Focus2SysInfo info) =>
new(
info.FocusPos,
info.Error,
FocusSystemStatus.DescribeError(info.Error),
info.Location,
info.LaserSta != 0,
info.Voltage / 10.0,
info.ExtVoltage / 10.0,
info.HwVersion,
info.SwVersion,
info.StartTime,
info.SyncTime,
info.SysSta != 0,
DateTimeOffset.Now);
private static FocusRealTimeResult MapResult(Focus2RealTimeResp response)
{
var type = response.Type switch
{
0x01 => FocusRealTimeResultType.MessageAck,
0x02 => FocusRealTimeResultType.RunningResult,
0x03 => FocusRealTimeResultType.QueryResult,
_ => FocusRealTimeResultType.Unknown,
};
return new FocusRealTimeResult(
type,
response.Sta == 0x01,
response.Error,
type == FocusRealTimeResultType.QueryResult ? response.Data : null,
DateTimeOffset.Now);
}
// ---------- 参数校验与错误映射 ----------
private int NormalizeTimeout(int? timeoutMs)
{
var timeout = timeoutMs ?? _options.ReadTimeoutMs;
return timeout > 0 ? timeout : 1000;
}
private int ResolveRetryInterval() =>
Math.Clamp(_options.ReadRetryIntervalMs, 10, 1000);
private static sbyte ToInt8(int value, string name)
{
if (value is < sbyte.MinValue or > sbyte.MaxValue)
{
throw new HardwareException(
HardwareErrorKind.InvalidArgument,
$"{name} {value} 超出范围({sbyte.MinValue}~{sbyte.MaxValue})");
}
return (sbyte)value;
}
/// <summary>命令返回 FOCUS2_OK(0) 表示成功,非 0 时按错误映射。</summary>
private static void EnsureSuccess(IntPtr handle, int result, string operation)
{
if (result >= 0)
{
return;
}
throw MapNativeError(handle, result, operation);
}
private static HardwareException MapNativeError(
IntPtr handle,
int code,
string operation)
{
var kind = code switch
{
FocusSystemNative.ErrNullPtr => HardwareErrorKind.InvalidArgument,
FocusSystemNative.ErrBufTooSmall => HardwareErrorKind.InvalidArgument,
FocusSystemNative.ErrFrameTooShort => HardwareErrorKind.CommunicationFailed,
FocusSystemNative.ErrComOpenFailed => HardwareErrorKind.ConnectFailed,
FocusSystemNative.ErrComNotOpen => HardwareErrorKind.NotConnected,
FocusSystemNative.ErrComSendFailed => HardwareErrorKind.CommunicationFailed,
FocusSystemNative.ErrParseFailed => HardwareErrorKind.CommunicationFailed,
FocusSystemNative.ErrTimeout => HardwareErrorKind.Timeout,
_ => HardwareErrorKind.Unknown,
};
var hint = code switch
{
FocusSystemNative.ErrComOpenFailed => "(串口不存在或被占用)",
FocusSystemNative.ErrComNotOpen => "(串口尚未打开)",
FocusSystemNative.ErrComSendFailed => "(设备返回失败应答或串口发送失败)",
FocusSystemNative.ErrParseFailed => "(CRC 校验失败或载荷不足)",
FocusSystemNative.ErrTimeout => "(未收到应答)",
_ => string.Empty,
};
var detail = FocusSystemNative.GetError(handle);
var message = string.IsNullOrWhiteSpace(detail)
? $"{operation}失败{hint}(错误码 {code})"
: $"{operation}失败{hint}(错误码 {code}):{detail}";
return new HardwareException(kind, message);
}
private static string BuildNativeLoadFailureMessage(Exception ex) => ex switch
{
DllNotFoundException =>
"加载 FocusSystem2.dll 失败:请确认该 DLL 已复制到程序输出目录"
+ $"(当前目录:{AppContext.BaseDirectory})",
BadImageFormatException =>
"加载 FocusSystem2.dll 失败:DLL 位数与进程不匹配,请使用 x64 进程运行",
EntryPointNotFoundException =>
"加载 FocusSystem2.dll 失败:DLL 版本与接口声明不匹配",
_ => "加载 FocusSystem2.dll 失败",
};
// ---------- 释放 ----------
private IntPtr RequireHandle()
{
var handle = _handle;
if (!_connected || handle == IntPtr.Zero)
{
throw new HardwareException(
HardwareErrorKind.NotConnected,
"对焦系统尚未连接,请先调用连接接口");
}
return handle;
}
private void ThrowIfDisposed()
{
ObjectDisposedException.ThrowIf(_disposed, this);
}
public async ValueTask DisposeAsync()
{
await _gate.WaitAsync().ConfigureAwait(false);
try
{
if (_disposed)
{
return;
}
_disposed = true;
CloseHandle();
}
finally
{
_gate.Release();
_gate.Dispose();
}
GC.SuppressFinalize(this);
}
}
}