982 lines
36 KiB
C#
982 lines
36 KiB
C#
using System.Diagnostics;
|
||
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
||
using HardwareControl.Core.Spectrometer;
|
||
using HardwareControl.Core.Spectrometer.ZioLink;
|
||
using Microsoft.Extensions.Logging;
|
||
using Microsoft.Extensions.Options;
|
||
|
||
namespace HardwareControl.Core.HardwareServiceImpl
|
||
{
|
||
/// <summary>
|
||
/// aris 光谱仪服务实现(ZioLink 协议,与官方 Inspective 的 Combined Spectrometer 行为一致)。
|
||
///
|
||
/// 线程模型:
|
||
/// * 所有 USB 调用由 <see cref="_gate"/> 串行化,采集期间不存在并发的设备访问;
|
||
/// * 采集拆成“预配置 + 启动 + 轮询 + 读取”四步:
|
||
/// - 预配置只在参数变化时下发(曝光/平均/延时),连接后已经预置默认值;
|
||
/// - 启动对每台设备只发一条 cmd 4(8 字节 USB 往返),三台设备的启动间隔是毫秒级;
|
||
/// - 启动后按 2 ms 周期轮询 GetStatus,收到可用帧后再 bulk 读取光谱;
|
||
/// * 因此 100 ms 曝光即可覆盖全部设备,不再需要 1 s 的曝光窗口。
|
||
/// </summary>
|
||
public sealed class ArisSpectrometerService : IArisSpectrometerService
|
||
{
|
||
private readonly ArisSpectrometerOptions _options;
|
||
private readonly ILogger<ArisSpectrometerService> _logger;
|
||
|
||
// 串行化全部 USB 调用
|
||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||
|
||
private ZioLinkDevice[] _devices = Array.Empty<ZioLinkDevice>();
|
||
private SpectrometerDeviceInfo[] _deviceInfos = Array.Empty<SpectrometerDeviceInfo>();
|
||
private volatile SpectrometerDeviceInfo? _selectedDevice;
|
||
private volatile bool _connected;
|
||
private bool _disposed;
|
||
|
||
private long _framesAcquired;
|
||
private long _lastAcquireAtTicks;
|
||
|
||
public ArisSpectrometerService(
|
||
IOptions<ArisSpectrometerOptions> options,
|
||
ILogger<ArisSpectrometerService> logger)
|
||
{
|
||
_options = options.Value;
|
||
_logger = logger;
|
||
}
|
||
|
||
public bool IsConnected => _connected;
|
||
|
||
public int DeviceCount => _deviceInfos.Length;
|
||
|
||
public SpectrometerDeviceInfo? SelectedDevice => _selectedDevice;
|
||
|
||
public int? PixelCount => _selectedDevice?.PixelCount;
|
||
|
||
public IReadOnlyList<SpectrometerDeviceInfo> Devices => _deviceInfos;
|
||
|
||
public long FramesAcquired => Interlocked.Read(ref _framesAcquired);
|
||
|
||
public DateTimeOffset? LastAcquireAt
|
||
{
|
||
get
|
||
{
|
||
var ticks = Interlocked.Read(ref _lastAcquireAtTicks);
|
||
return ticks == 0 ? null : new DateTimeOffset(ticks, TimeSpan.Zero);
|
||
}
|
||
}
|
||
|
||
public event EventHandler<SpectrometerStatusChangedEventArgs>? 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 paths = WinUsbConnection.FindDevicePaths();
|
||
if (paths.Length == 0)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.ConnectFailed,
|
||
"未发现 aris 光谱仪。请检查 USB 连接以及 354F:0101 的 WinUSB 驱动");
|
||
}
|
||
|
||
var devices = new List<ZioLinkDevice>(paths.Length);
|
||
try
|
||
{
|
||
_logger.LogInformation("正在连接 aris 光谱仪,共发现 {Count} 个 WinUSB 接口", paths.Length);
|
||
|
||
foreach (var path in paths)
|
||
{
|
||
var connection = WinUsbConnection.Open(path);
|
||
var device = new ZioLinkDevice(connection);
|
||
try
|
||
{
|
||
device.Open();
|
||
}
|
||
catch
|
||
{
|
||
device.Dispose();
|
||
throw;
|
||
}
|
||
|
||
devices.Add(device);
|
||
|
||
_logger.LogInformation(
|
||
"已打开光谱仪 {SerialNumber}({Model},{PixelCount} 像素,固件 {Firmware})",
|
||
device.SerialNumber,
|
||
device.ModelName,
|
||
device.PixelCount,
|
||
device.FirmwareVersion);
|
||
}
|
||
|
||
var infos = new SpectrometerDeviceInfo[devices.Count];
|
||
for (var i = 0; i < devices.Count; i++)
|
||
{
|
||
var device = devices[i];
|
||
infos[i] = new SpectrometerDeviceInfo(
|
||
i,
|
||
device.SerialNumber,
|
||
device.PixelCount,
|
||
device.StartPixel,
|
||
device.EndPixel,
|
||
device.FirmwareVersion.ToString());
|
||
}
|
||
|
||
// 三台设备集中同步 RTC,避免帧头时间戳出现固定偏移
|
||
foreach (var device in devices)
|
||
{
|
||
if (!device.SynchronizeTime())
|
||
{
|
||
_logger.LogWarning(
|
||
"同步光谱仪 {SerialNumber} 的 RTC 失败,帧时间戳将只用于相对比较",
|
||
device.SerialNumber);
|
||
}
|
||
}
|
||
|
||
var selected = SelectDevice(infos);
|
||
|
||
// 触发模式只在连接后设置一次;Combined 模式下所有设备使用同一模式
|
||
if (_options.TriggerMode is { } triggerMode)
|
||
{
|
||
foreach (var device in devices)
|
||
{
|
||
device.SetTriggerMode(triggerMode);
|
||
}
|
||
}
|
||
|
||
if (_options.Gain is { } gain)
|
||
{
|
||
devices[selected.Index].SetGain(gain);
|
||
}
|
||
|
||
// 预配置默认曝光参数:采集时只发启动命令,三台设备的启动偏差降到 USB 往返级
|
||
var preExposureUs = _options.SynchronizedExposureUs > 0
|
||
? _options.SynchronizedExposureUs
|
||
: _options.ExposureUs;
|
||
|
||
foreach (var device in devices)
|
||
{
|
||
device.ApplyParameters(preExposureUs, _options.Averaging, _options.DelayUs);
|
||
}
|
||
|
||
_devices = devices.ToArray();
|
||
_deviceInfos = infos;
|
||
_selectedDevice = selected;
|
||
_connected = true;
|
||
|
||
Interlocked.Exchange(ref _framesAcquired, 0);
|
||
Interlocked.Exchange(ref _lastAcquireAtTicks, 0);
|
||
|
||
var message = infos.Length == 1
|
||
? $"光谱仪已连接:{selected.SerialNumber}({selected.PixelCount} 像素)"
|
||
: $"光谱仪已连接:共 {infos.Length} 台,当前使用 {selected.SerialNumber}({selected.PixelCount} 像素)";
|
||
|
||
_logger.LogInformation(
|
||
"aris 光谱仪已连接:{DeviceCount} 台,选中索引 {Index},序列号 {SerialNumber},"
|
||
+ "像素数 {PixelCount},触发模式 {TriggerMode}",
|
||
infos.Length,
|
||
selected.Index,
|
||
selected.SerialNumber,
|
||
selected.PixelCount,
|
||
_options.TriggerMode?.ToString() ?? "(设备当前配置)");
|
||
|
||
StatusChanged?.Invoke(this, new SpectrometerStatusChangedEventArgs(true, message));
|
||
}
|
||
catch (ZioLinkException ex)
|
||
{
|
||
DisposeDevices(devices);
|
||
_logger.LogError(ex, "连接 aris 光谱仪失败,错误码 {Code}", ex.Code);
|
||
throw MapZioLinkException(ex, "连接光谱仪", connecting: true);
|
||
}
|
||
catch (HardwareException)
|
||
{
|
||
DisposeDevices(devices);
|
||
throw;
|
||
}
|
||
catch (Exception ex) when (ex is DllNotFoundException or BadImageFormatException
|
||
or EntryPointNotFoundException)
|
||
{
|
||
DisposeDevices(devices);
|
||
_logger.LogError(ex, "加载 WinUSB 失败");
|
||
throw new HardwareException(
|
||
HardwareErrorKind.ConnectFailed,
|
||
"加载 WinUSB 失败,请确认系统为 Windows 8 及以上且 winusb.dll 可用",
|
||
ex);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
DisposeDevices(devices);
|
||
_logger.LogError(ex, "连接 aris 光谱仪时发生未预期异常");
|
||
throw new HardwareException(HardwareErrorKind.ConnectFailed, "连接光谱仪失败", ex);
|
||
}
|
||
}
|
||
|
||
private SpectrometerDeviceInfo SelectDevice(SpectrometerDeviceInfo[] devices)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(_options.PreferredSerialNumber))
|
||
{
|
||
var matched = devices.FirstOrDefault(device => string.Equals(
|
||
device.SerialNumber,
|
||
_options.PreferredSerialNumber,
|
||
StringComparison.OrdinalIgnoreCase));
|
||
|
||
if (matched is not null)
|
||
{
|
||
return matched;
|
||
}
|
||
|
||
_logger.LogWarning(
|
||
"未找到序列号为 {SerialNumber} 的光谱仪,回退到配置的设备索引 {DeviceIndex}",
|
||
_options.PreferredSerialNumber,
|
||
_options.DeviceIndex);
|
||
}
|
||
|
||
if (_options.DeviceIndex < 0 || _options.DeviceIndex >= devices.Length)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidArgument,
|
||
$"配置的 DeviceIndex={_options.DeviceIndex} 超出已连接设备数量 {devices.Length}");
|
||
}
|
||
|
||
return devices[_options.DeviceIndex];
|
||
}
|
||
|
||
// ---------- 断开 ----------
|
||
|
||
public async Task DisconnectAsync(CancellationToken ct = default)
|
||
{
|
||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||
try
|
||
{
|
||
if (_disposed)
|
||
{
|
||
return;
|
||
}
|
||
|
||
var wasConnected = _connected;
|
||
await Task.Run(() => DisposeDevices(null), CancellationToken.None)
|
||
.ConfigureAwait(false);
|
||
|
||
if (wasConnected)
|
||
{
|
||
_logger.LogInformation("aris 光谱仪已断开");
|
||
StatusChanged?.Invoke(
|
||
this,
|
||
new SpectrometerStatusChangedEventArgs(false, "光谱仪已断开"));
|
||
}
|
||
}
|
||
finally
|
||
{
|
||
_gate.Release();
|
||
}
|
||
}
|
||
|
||
private void DisposeDevices(List<ZioLinkDevice>? pending)
|
||
{
|
||
var devices = pending?.ToArray() ?? _devices;
|
||
|
||
_devices = Array.Empty<ZioLinkDevice>();
|
||
_deviceInfos = Array.Empty<SpectrometerDeviceInfo>();
|
||
_selectedDevice = null;
|
||
_connected = false;
|
||
|
||
foreach (var device in devices)
|
||
{
|
||
try
|
||
{
|
||
device.CancelExposure();
|
||
}
|
||
catch (Exception ex) when (ex is ZioLinkException or ObjectDisposedException)
|
||
{
|
||
// 设备可能已经停止或断开,忽略
|
||
}
|
||
|
||
try
|
||
{
|
||
device.Dispose();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogWarning(ex, "关闭光谱仪 {SerialNumber} 时发生异常", device.SerialNumber);
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---------- 单帧采集 ----------
|
||
|
||
public async Task<SpectrumFrame> AcquireFrameAsync(
|
||
SpectrumAcquisitionRequest? request = null,
|
||
CancellationToken ct = default)
|
||
{
|
||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||
try
|
||
{
|
||
ThrowIfDisposed();
|
||
RequireConnected();
|
||
var parameters = Normalize(request);
|
||
ct.ThrowIfCancellationRequested();
|
||
|
||
return await Task.Run(
|
||
() => AcquireFrameCore(parameters),
|
||
CancellationToken.None)
|
||
.ConfigureAwait(false);
|
||
}
|
||
finally
|
||
{
|
||
_gate.Release();
|
||
}
|
||
}
|
||
|
||
private SpectrumFrame AcquireFrameCore(
|
||
(int DeviceIndex, int ExposureUs, int Averaging, int DelayUs, int TimeoutMs) parameters)
|
||
{
|
||
var device = _devices[parameters.DeviceIndex];
|
||
var startedAt = Stopwatch.GetTimestamp();
|
||
|
||
_logger.LogDebug(
|
||
"开始单帧采集:设备 {DeviceIndex}({SerialNumber}),曝光 {ExposureUs}us,平均 {Averaging}",
|
||
parameters.DeviceIndex,
|
||
device.SerialNumber,
|
||
parameters.ExposureUs,
|
||
parameters.Averaging);
|
||
|
||
try
|
||
{
|
||
var drained = device.DrainPendingSpectra();
|
||
if (drained > 0)
|
||
{
|
||
_logger.LogWarning(
|
||
"丢弃光谱仪 {SerialNumber} 残留的 {Count} 帧旧数据",
|
||
device.SerialNumber,
|
||
drained);
|
||
}
|
||
|
||
device.ApplyParameters(
|
||
parameters.ExposureUs, parameters.Averaging, parameters.DelayUs);
|
||
device.StartExposure(1);
|
||
|
||
var timeoutMs = parameters.TimeoutMs > 0
|
||
? parameters.TimeoutMs
|
||
: Math.Max(3000, (parameters.ExposureUs / 1000) + 2000);
|
||
|
||
if (!WaitForSpectrum(device, timeoutMs))
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.Timeout,
|
||
$"等待光谱仪 {device.SerialNumber} 出帧超时({timeoutMs} ms)。"
|
||
+ "请检查触发模式与曝光时间");
|
||
}
|
||
|
||
var spectrum = device.ReadSpectrum();
|
||
var acquiredAt = DateTimeOffset.Now;
|
||
var elapsed = Stopwatch.GetElapsedTime(startedAt);
|
||
|
||
var info = new SpectrumFrameInfo(
|
||
(int)spectrum.ExposureTimeUs,
|
||
(int)spectrum.Averaging,
|
||
spectrum.DeviceTime10Us,
|
||
spectrum.DeviceDateDays,
|
||
spectrum.PixelCount,
|
||
spectrum.DataFormat,
|
||
spectrum.LoadLevel,
|
||
spectrum.SensorTemperature,
|
||
spectrum.DarkAvg,
|
||
spectrum.ReadoutNoise,
|
||
spectrum.AppliedProcessing,
|
||
(ushort)spectrum.ErrorFlags,
|
||
(ushort)spectrum.IntensityUnit,
|
||
spectrum.DarkSubtracted);
|
||
|
||
var frame = new SpectrumFrame(
|
||
parameters.DeviceIndex,
|
||
device.SerialNumber,
|
||
device.Wavelengths,
|
||
spectrum.Values,
|
||
info,
|
||
acquiredAt,
|
||
elapsed);
|
||
|
||
Interlocked.Increment(ref _framesAcquired);
|
||
Interlocked.Exchange(ref _lastAcquireAtTicks, acquiredAt.UtcTicks);
|
||
|
||
_logger.LogDebug(
|
||
"单帧采集完成:设备 {DeviceIndex},{PixelCount} 像素,耗时 {ElapsedMs:F0}ms,温度 {Temperature:F2}℃",
|
||
parameters.DeviceIndex,
|
||
frame.Info.PixelCount,
|
||
elapsed.TotalMilliseconds,
|
||
frame.Info.SensorTemperature);
|
||
|
||
return frame;
|
||
}
|
||
catch (ZioLinkException ex)
|
||
{
|
||
_logger.LogWarning(
|
||
ex, "单帧采集失败,设备 {SerialNumber},错误码 {Code}", device.SerialNumber, ex.Code);
|
||
throw MapZioLinkException(ex, "采集光谱");
|
||
}
|
||
}
|
||
|
||
// ---------- 多台同步采集 ----------
|
||
|
||
public async Task<SynchronizedSpectrumResult> AcquireSynchronizedAsync(
|
||
SynchronizedSpectrumRequest? request = null,
|
||
CancellationToken ct = default)
|
||
{
|
||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||
try
|
||
{
|
||
ThrowIfDisposed();
|
||
RequireConnected();
|
||
var parameters = NormalizeSynchronized(request);
|
||
ct.ThrowIfCancellationRequested();
|
||
|
||
return await Task.Run(
|
||
() => AcquireSynchronizedCore(parameters),
|
||
CancellationToken.None)
|
||
.ConfigureAwait(false);
|
||
}
|
||
finally
|
||
{
|
||
_gate.Release();
|
||
}
|
||
}
|
||
|
||
private SynchronizedSpectrumResult AcquireSynchronizedCore(
|
||
(int ExposureUs, int Averaging, int DelayUs, int WaitTimeoutMs) parameters)
|
||
{
|
||
var devices = _devices;
|
||
var expected = devices.Length;
|
||
if (expected == 0)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.NotConnected,
|
||
"没有可采集的光谱仪,请先调用连接接口");
|
||
}
|
||
|
||
var errors = new List<SpectrumDeviceError>();
|
||
var prepared = new bool[expected];
|
||
var started = new bool[expected];
|
||
var ready = new bool[expected];
|
||
|
||
var prepareStartedAt = Stopwatch.GetTimestamp();
|
||
|
||
// 1. 预配置:只有参数变化时才发命令(连接后默认参数已下发的场合为 0 条命令)
|
||
for (var i = 0; i < expected; i++)
|
||
{
|
||
try
|
||
{
|
||
var drained = devices[i].DrainPendingSpectra();
|
||
if (drained > 0)
|
||
{
|
||
_logger.LogWarning(
|
||
"丢弃光谱仪 {SerialNumber} 残留的 {Count} 帧旧数据",
|
||
devices[i].SerialNumber,
|
||
drained);
|
||
}
|
||
|
||
devices[i].ApplyParameters(
|
||
parameters.ExposureUs, parameters.Averaging, parameters.DelayUs);
|
||
prepared[i] = true;
|
||
}
|
||
catch (ZioLinkException ex)
|
||
{
|
||
errors.Add(new SpectrumDeviceError(devices[i].SerialNumber, ex.Message));
|
||
_logger.LogWarning(
|
||
ex, "预配置光谱仪 {SerialNumber} 失败", devices[i].SerialNumber);
|
||
}
|
||
}
|
||
|
||
// 2. 启动:每台只发一条 cmd 4,三台间隔为 USB 往返时间
|
||
var startCommandsAt = Stopwatch.GetTimestamp();
|
||
for (var i = 0; i < expected; i++)
|
||
{
|
||
if (!prepared[i])
|
||
{
|
||
continue;
|
||
}
|
||
|
||
try
|
||
{
|
||
devices[i].StartExposure(1);
|
||
started[i] = true;
|
||
}
|
||
catch (ZioLinkException ex)
|
||
{
|
||
errors.Add(new SpectrumDeviceError(devices[i].SerialNumber, ex.Message));
|
||
_logger.LogError(
|
||
ex, "启动光谱仪 {SerialNumber} 失败", devices[i].SerialNumber);
|
||
}
|
||
}
|
||
|
||
var startElapsed = Stopwatch.GetElapsedTime(prepareStartedAt);
|
||
var startCommandElapsed = Stopwatch.GetElapsedTime(startCommandsAt);
|
||
|
||
_logger.LogInformation(
|
||
"启动命令发送完成:{Count} 台,命令间隔 {StartCommandMs:F2}ms,预配置+启动合计 {StartMs:F2}ms",
|
||
started.Count(value => value),
|
||
startCommandElapsed.TotalMilliseconds,
|
||
startElapsed.TotalMilliseconds);
|
||
|
||
// 3. 轮询:2 ms 一轮,收齐所有设备的可用帧
|
||
var waitStartedAt = Stopwatch.GetTimestamp();
|
||
var timeout = TimeSpan.FromMilliseconds(parameters.WaitTimeoutMs);
|
||
var pending = Enumerable.Range(0, expected).Where(i => started[i]).ToList();
|
||
|
||
while (pending.Count > 0 && Stopwatch.GetElapsedTime(waitStartedAt) < timeout)
|
||
{
|
||
var progressed = false;
|
||
|
||
for (var index = pending.Count - 1; index >= 0; index--)
|
||
{
|
||
var deviceIndex = pending[index];
|
||
try
|
||
{
|
||
var status = devices[deviceIndex].GetStatus(out var available);
|
||
if (available > 0)
|
||
{
|
||
ready[deviceIndex] = true;
|
||
pending.RemoveAt(index);
|
||
progressed = true;
|
||
}
|
||
else if (status == ZioLinkDeviceStatus.NotConnected)
|
||
{
|
||
pending.RemoveAt(index);
|
||
progressed = true;
|
||
errors.Add(new SpectrumDeviceError(
|
||
devices[deviceIndex].SerialNumber, "设备已断开"));
|
||
}
|
||
}
|
||
catch (ZioLinkException ex)
|
||
{
|
||
pending.RemoveAt(index);
|
||
progressed = true;
|
||
errors.Add(new SpectrumDeviceError(
|
||
devices[deviceIndex].SerialNumber, ex.Message));
|
||
_logger.LogWarning(
|
||
ex, "查询光谱仪 {SerialNumber} 状态失败", devices[deviceIndex].SerialNumber);
|
||
}
|
||
}
|
||
|
||
if (!progressed)
|
||
{
|
||
Thread.Sleep(2);
|
||
}
|
||
}
|
||
|
||
foreach (var deviceIndex in pending)
|
||
{
|
||
errors.Add(new SpectrumDeviceError(
|
||
devices[deviceIndex].SerialNumber, "等待超时,未收到可用帧"));
|
||
}
|
||
|
||
var waitElapsed = Stopwatch.GetElapsedTime(waitStartedAt);
|
||
|
||
// 4. 读取:状态确认有帧后再 bulk 读,避免在 USB 读上等待曝光时间
|
||
var frames = new List<SynchronizedSpectrumFrame>(expected);
|
||
var deviceTimestamps = new List<(string SerialNumber, ulong TenthMilliseconds)>(expected);
|
||
|
||
for (var i = 0; i < expected; i++)
|
||
{
|
||
if (!ready[i])
|
||
{
|
||
continue;
|
||
}
|
||
|
||
try
|
||
{
|
||
var spectrum = devices[i].ReadSpectrum();
|
||
frames.Add(new SynchronizedSpectrumFrame(
|
||
i,
|
||
devices[i].SerialNumber,
|
||
devices[i].Wavelengths,
|
||
spectrum.Values,
|
||
DateTimeOffset.Now));
|
||
|
||
deviceTimestamps.Add((
|
||
devices[i].SerialNumber,
|
||
spectrum.DeviceDateDays * 86_400_000UL + spectrum.DeviceTime10Us));
|
||
|
||
_logger.LogInformation(
|
||
"光谱仪 {SerialNumber} 出帧:曝光 {ExposureUs}us,平均 {Averaging},"
|
||
+ "设备时间戳 {DateDays}+{Time10Us},像素 {PixelCount}",
|
||
devices[i].SerialNumber,
|
||
spectrum.ExposureTimeUs,
|
||
spectrum.Averaging,
|
||
spectrum.DeviceDateDays,
|
||
spectrum.DeviceTime10Us,
|
||
spectrum.PixelCount);
|
||
}
|
||
catch (ZioLinkException ex)
|
||
{
|
||
errors.Add(new SpectrumDeviceError(devices[i].SerialNumber, ex.Message));
|
||
_logger.LogError(
|
||
ex, "读取光谱仪 {SerialNumber} 光谱失败", devices[i].SerialNumber);
|
||
}
|
||
}
|
||
|
||
LogStartSkew(deviceTimestamps);
|
||
|
||
var acquiredAt = DateTimeOffset.Now;
|
||
|
||
if (frames.Count == 0)
|
||
{
|
||
var detail = errors.Count == 0
|
||
? "等待超时,未收到任何设备的光谱帧"
|
||
: "未收到任何设备的光谱帧:" + string.Join(
|
||
";",
|
||
errors.Select(error => $"{error.SerialNumber}: {error.Message}"));
|
||
|
||
throw new HardwareException(HardwareErrorKind.Timeout, detail);
|
||
}
|
||
|
||
var receivedSerials = new HashSet<string>(
|
||
frames.Select(frame => frame.SerialNumber),
|
||
StringComparer.OrdinalIgnoreCase);
|
||
|
||
var missing = devices
|
||
.Where(device => !receivedSerials.Contains(device.SerialNumber))
|
||
.Select(device => device.SerialNumber)
|
||
.ToArray();
|
||
|
||
var orderedFrames = frames
|
||
.OrderBy(frame => frame.SerialNumber, StringComparer.OrdinalIgnoreCase)
|
||
.ToArray();
|
||
var errorList = errors
|
||
.OrderBy(error => error.SerialNumber, StringComparer.OrdinalIgnoreCase)
|
||
.ToArray();
|
||
|
||
MergedSpectrum merged;
|
||
try
|
||
{
|
||
merged = SpectrumMerger.Merge(orderedFrames);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError(ex, "拼接多台光谱仪数据失败");
|
||
throw new HardwareException(
|
||
HardwareErrorKind.CommunicationFailed,
|
||
"拼接光谱数据失败",
|
||
ex);
|
||
}
|
||
|
||
if (merged.PixelCount == 0)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.CommunicationFailed,
|
||
"拼接光谱为空,请检查设备返回的波长数据");
|
||
}
|
||
|
||
Interlocked.Add(ref _framesAcquired, orderedFrames.Length);
|
||
Interlocked.Exchange(ref _lastAcquireAtTicks, acquiredAt.UtcTicks);
|
||
|
||
_logger.LogInformation(
|
||
"多台光谱仪同步采集完成:收到 {ReceivedCount}/{ExpectedCount} 台,"
|
||
+ "预配置+启动 {StartMs:F1}ms,等待 {WaitMs:F0}ms,拼接后 {PixelCount} 点",
|
||
orderedFrames.Length,
|
||
expected,
|
||
startElapsed.TotalMilliseconds,
|
||
waitElapsed.TotalMilliseconds,
|
||
merged.PixelCount);
|
||
|
||
return new SynchronizedSpectrumResult(
|
||
orderedFrames,
|
||
merged,
|
||
missing,
|
||
errorList,
|
||
expected,
|
||
acquiredAt,
|
||
startElapsed,
|
||
waitElapsed);
|
||
}
|
||
|
||
private void LogStartSkew(List<(string SerialNumber, ulong TenthMilliseconds)> timestamps)
|
||
{
|
||
if (timestamps.Count < 2)
|
||
{
|
||
return;
|
||
}
|
||
|
||
var min = timestamps.Min(item => item.TenthMilliseconds);
|
||
var max = timestamps.Max(item => item.TenthMilliseconds);
|
||
// 设备时间戳单位是 0.1 ms
|
||
var skewMs = (max - min) / 10.0;
|
||
|
||
_logger.LogInformation(
|
||
"设备 RTC 帧时间戳偏差 {SkewMs:F2}ms(诊断用,{Details})",
|
||
skewMs,
|
||
string.Join(
|
||
",",
|
||
timestamps.Select(item => $"{item.SerialNumber}:{item.TenthMilliseconds}")));
|
||
}
|
||
|
||
private static bool WaitForSpectrum(ZioLinkDevice device, int timeoutMs)
|
||
{
|
||
var startedAt = Stopwatch.GetTimestamp();
|
||
var timeout = TimeSpan.FromMilliseconds(timeoutMs);
|
||
|
||
while (Stopwatch.GetElapsedTime(startedAt) < timeout)
|
||
{
|
||
var status = device.GetStatus(out var available);
|
||
if (available > 0)
|
||
{
|
||
return true;
|
||
}
|
||
|
||
if (status == ZioLinkDeviceStatus.NotConnected)
|
||
{
|
||
return false;
|
||
}
|
||
|
||
Thread.Sleep(1);
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
private (int ExposureUs, int Averaging, int DelayUs, int WaitTimeoutMs)
|
||
NormalizeSynchronized(SynchronizedSpectrumRequest? request)
|
||
{
|
||
var defaultExposureUs = _options.SynchronizedExposureUs > 0
|
||
? _options.SynchronizedExposureUs
|
||
: _options.ExposureUs;
|
||
|
||
var exposureUs = request?.ExposureUs ?? defaultExposureUs;
|
||
if (exposureUs <= 0)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidArgument,
|
||
"曝光时间 ExposureUs 必须大于 0 微秒");
|
||
}
|
||
|
||
var averaging = request?.Averaging ?? _options.Averaging;
|
||
if (averaging < 1)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidArgument,
|
||
"平均次数 Averaging 必须大于等于 1");
|
||
}
|
||
|
||
var delayUs = request?.DelayUs ?? _options.DelayUs;
|
||
if (delayUs < 0)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidArgument,
|
||
"触发延迟 DelayUs 不能小于 0");
|
||
}
|
||
|
||
var waitTimeoutMs = request?.WaitTimeoutMs
|
||
?? _options.SynchronizedWaitTimeoutMs;
|
||
if (waitTimeoutMs <= 0)
|
||
{
|
||
waitTimeoutMs = _options.SynchronizedWaitTimeoutMs > 0
|
||
? _options.SynchronizedWaitTimeoutMs
|
||
: 8000;
|
||
}
|
||
|
||
return (exposureUs, averaging, delayUs, waitTimeoutMs);
|
||
}
|
||
|
||
private (int DeviceIndex, int ExposureUs, int Averaging, int DelayUs, int TimeoutMs)
|
||
Normalize(SpectrumAcquisitionRequest? request)
|
||
{
|
||
var exposureUs = request?.ExposureUs ?? _options.ExposureUs;
|
||
if (exposureUs <= 0)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidArgument,
|
||
"曝光时间 ExposureUs 必须大于 0 微秒");
|
||
}
|
||
|
||
var averaging = request?.Averaging ?? _options.Averaging;
|
||
if (averaging < 1)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidArgument,
|
||
"平均次数 Averaging 必须大于等于 1");
|
||
}
|
||
|
||
var delayUs = request?.DelayUs ?? _options.DelayUs;
|
||
if (delayUs < 0)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidArgument,
|
||
"触发延迟 DelayUs 不能小于 0");
|
||
}
|
||
|
||
var timeoutMs = request?.TimeoutMs ?? _options.TimeoutMs;
|
||
if (timeoutMs < 0)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidArgument,
|
||
"超时 TimeoutMs 不能小于 0");
|
||
}
|
||
|
||
var deviceIndex = ResolveDeviceIndex(request?.DeviceIndex);
|
||
|
||
return (deviceIndex, exposureUs, averaging, delayUs, timeoutMs);
|
||
}
|
||
|
||
private int ResolveDeviceIndex(int? deviceIndex)
|
||
{
|
||
var index = deviceIndex ?? _selectedDevice?.Index ?? _options.DeviceIndex;
|
||
if (index < 0 || index >= _devices.Length)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidArgument,
|
||
$"设备索引 {index} 超出范围,已连接设备数量 {_devices.Length}");
|
||
}
|
||
|
||
return index;
|
||
}
|
||
|
||
// ---------- 查询 ----------
|
||
|
||
public async Task<SpectrometerDeviceStatus> GetDeviceStatusAsync(
|
||
int? deviceIndex = null,
|
||
CancellationToken ct = default)
|
||
{
|
||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||
try
|
||
{
|
||
ThrowIfDisposed();
|
||
RequireConnected();
|
||
|
||
var index = ResolveDeviceIndex(deviceIndex);
|
||
try
|
||
{
|
||
var status = await Task.Run(
|
||
() =>
|
||
{
|
||
var state = _devices[index].GetStatus(out var available);
|
||
return new SpectrometerDeviceStatus(
|
||
index, state.ToString(), available);
|
||
},
|
||
CancellationToken.None)
|
||
.ConfigureAwait(false);
|
||
|
||
return status;
|
||
}
|
||
catch (ZioLinkException ex)
|
||
{
|
||
throw MapZioLinkException(ex, "查询设备状态");
|
||
}
|
||
}
|
||
finally
|
||
{
|
||
_gate.Release();
|
||
}
|
||
}
|
||
|
||
public async Task<float[]> GetWavelengthsAsync(
|
||
int? deviceIndex = null,
|
||
CancellationToken ct = default)
|
||
{
|
||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||
try
|
||
{
|
||
ThrowIfDisposed();
|
||
RequireConnected();
|
||
|
||
var index = ResolveDeviceIndex(deviceIndex);
|
||
return (float[])_devices[index].Wavelengths.Clone();
|
||
}
|
||
finally
|
||
{
|
||
_gate.Release();
|
||
}
|
||
}
|
||
|
||
private void RequireConnected()
|
||
{
|
||
if (!_connected || _devices.Length == 0)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.NotConnected,
|
||
"光谱仪尚未连接,请先调用连接接口");
|
||
}
|
||
}
|
||
|
||
// ---------- 异常映射 ----------
|
||
|
||
private static HardwareException MapZioLinkException(
|
||
ZioLinkException ex,
|
||
string operation,
|
||
bool connecting = false)
|
||
{
|
||
var kind = ex.Code switch
|
||
{
|
||
0 => connecting
|
||
? HardwareErrorKind.ConnectFailed
|
||
: HardwareErrorKind.CommunicationFailed,
|
||
2 => HardwareErrorKind.InvalidArgument,
|
||
4 => HardwareErrorKind.InvalidState,
|
||
5 => HardwareErrorKind.NotSupported,
|
||
6 => HardwareErrorKind.InvalidArgument,
|
||
7 or 8 or 10 or 11 => HardwareErrorKind.CommunicationFailed,
|
||
_ => HardwareErrorKind.Unknown,
|
||
};
|
||
|
||
var hint = kind switch
|
||
{
|
||
HardwareErrorKind.ConnectFailed =>
|
||
"。请检查光谱仪 USB 连接以及 354F:0101 的 WinUSB 驱动",
|
||
HardwareErrorKind.InvalidState =>
|
||
"。设备可能仍在上一轮测量中,请稍后重试或重新连接",
|
||
HardwareErrorKind.CommunicationFailed =>
|
||
"。请检查 USB 供电与线缆,并确认没有其他程序(如 Inspective)正在占用设备",
|
||
HardwareErrorKind.NotSupported =>
|
||
"。设备/固件不支持该配置(例如数据格式不是 0)",
|
||
_ => string.Empty,
|
||
};
|
||
|
||
return new HardwareException(kind, $"{operation}失败:{ex.Message}{hint}", ex);
|
||
}
|
||
|
||
// ---------- 释放 ----------
|
||
|
||
private void ThrowIfDisposed()
|
||
{
|
||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||
}
|
||
|
||
public async ValueTask DisposeAsync()
|
||
{
|
||
await _gate.WaitAsync().ConfigureAwait(false);
|
||
try
|
||
{
|
||
if (_disposed)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_disposed = true;
|
||
DisposeDevices(null);
|
||
}
|
||
finally
|
||
{
|
||
_gate.Release();
|
||
_gate.Dispose();
|
||
}
|
||
|
||
GC.SuppressFinalize(this);
|
||
}
|
||
}
|
||
}
|