using System.Collections.Concurrent; using System.Diagnostics; using Aris; using HardwareControl.Core.HardwareServiceImpl.HardwareService; using HardwareControl.Core.Spectrometer; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using ArisSpectrumFrame = Aris.SpectrumFrame; using SpectrumFrame = HardwareControl.Core.Spectrometer.SpectrumFrame; namespace HardwareControl.Core.HardwareServiceImpl { /// /// aris 光谱仪服务实现。 /// /// 线程模型: /// * 所有原生调用(连接、单帧采集、多台同步采集、状态、波长)都由 串行化, /// 因为 / aris.dll 内部虽然也加锁,但采集是长事务, /// 在业务层排队更容易控制超时与日志; /// * 原生调用是同步阻塞的,因此放到线程池执行,避免占用 ASP.NET Core 请求线程; /// * 单台使用同步 AcquireFrame;多台使用 StartMeasurement 一次武装, /// 回调只做拷贝/入队,收齐后调用 StopMeasurement 并拼接。 /// 单帧与多台测量在 SDK 层互斥(测量中调用单帧会返回 InvalidState)。 /// public sealed class ArisSpectrometerService : IArisSpectrometerService { private readonly ArisSpectrometerOptions _options; private readonly ILogger _logger; // 串行化全部原生调用 private readonly SemaphoreSlim _gate = new(1, 1); private ArisSpectrometer? _spectrometer; private volatile SpectrometerDeviceInfo[] _devices = Array.Empty(); private volatile SpectrometerDeviceInfo? _selectedDevice; private volatile bool _connected; private bool _disposed; private long _framesAcquired; private long _lastAcquireAtTicks; public ArisSpectrometerService( IOptions options, ILogger logger) { _options = options.Value; _logger = logger; } public bool IsConnected => _connected; public int DeviceCount => _devices.Length; public SpectrometerDeviceInfo? SelectedDevice => _selectedDevice; public int? PixelCount => _selectedDevice?.PixelCount; public IReadOnlyList Devices => _devices; 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? 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() { EnsureProcessIs64Bit(); try { EnsureSpectrometer(); var spectrometer = _spectrometer!; _logger.LogInformation("正在连接 aris 光谱仪..."); spectrometer.Connect(); var count = spectrometer.DeviceCount; if (count <= 0) { throw new HardwareException( HardwareErrorKind.ConnectFailed, "aris 光谱仪连接成功但设备数量为 0"); } var devices = new SpectrometerDeviceInfo[count]; for (var i = 0; i < count; i++) { devices[i] = MapDevice(i, spectrometer.GetDeviceInfo(i)); } var selected = SelectDevice(devices); // 触发模式只应在连接后设置一次;设备要求全部 Idle。 if (_options.TriggerMode is { } triggerMode) { spectrometer.SetTriggerMode(triggerMode); } if (_options.Gain is { } gain) { spectrometer.SetGain(selected.Index, gain); } _devices = devices; _selectedDevice = selected; _connected = true; // 帧数按“本次连接”统计,与相机服务保持一致。 Interlocked.Exchange(ref _framesAcquired, 0); Interlocked.Exchange(ref _lastAcquireAtTicks, 0); var message = count == 1 ? $"光谱仪已连接:{selected.SerialNumber}({selected.PixelCount} 像素)" : $"光谱仪已连接:共 {count} 台,当前使用 {selected.SerialNumber}({selected.PixelCount} 像素)"; _logger.LogInformation( "aris 光谱仪已连接:{DeviceCount} 台,选中索引 {Index},序列号 {SerialNumber},像素数 {PixelCount},固件 {Firmware}", count, selected.Index, selected.SerialNumber, selected.PixelCount, selected.FirmwareVersion); StatusChanged?.Invoke(this, new SpectrometerStatusChangedEventArgs(true, message)); } catch (ArisException ex) { // 连接流程可能已经打开了 USB 设备(例如设置触发模式时才失败), // 立即销毁上下文,避免留下半连接状态导致下一次连接报 not idle。 DisposeSpectrometerCore(); _logger.LogError( ex, "连接 aris 光谱仪失败,状态码 {Status}", ex.Status); throw MapArisException(ex, "连接光谱仪", connecting: true); } catch (HardwareException) { DisposeSpectrometerCore(); throw; } catch (Exception ex) when (ex is DllNotFoundException or BadImageFormatException or EntryPointNotFoundException) { DisposeSpectrometerCore(); _logger.LogError(ex, "加载 aris 原生库失败"); throw new HardwareException( HardwareErrorKind.ConnectFailed, BuildNativeLoadFailureMessage(ex), ex); } catch (Exception ex) { DisposeSpectrometerCore(); _logger.LogError(ex, "连接 aris 光谱仪时发生未预期异常"); throw new HardwareException( HardwareErrorKind.ConnectFailed, "连接光谱仪失败", ex); } } private static void EnsureProcessIs64Bit() { if (!Environment.Is64BitProcess) { throw new HardwareException( HardwareErrorKind.ConnectFailed, "aris.dll 仅提供 x64 版本,请使用 64 位进程运行" + "(PlatformTarget=x64 或 64 位宿主)"); } } private void EnsureSpectrometer() { if (_spectrometer is not null) { return; } // SetLogEnabled 也会加载 aris.dll,因此必须放在异常映射覆盖的范围内。 ArisSpectrometer.SetLogEnabled(_options.SdkLogEnabled); _spectrometer = new ArisSpectrometer(); } 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(DisposeSpectrometerCore, CancellationToken.None) .ConfigureAwait(false); if (wasConnected) { _logger.LogInformation("aris 光谱仪已断开"); StatusChanged?.Invoke( this, new SpectrometerStatusChangedEventArgs(false, "光谱仪已断开")); } } finally { _gate.Release(); } } /// 停止测量、断开并销毁上下文;异常只记日志,保证状态一定归零。 private void DisposeSpectrometerCore() { var spectrometer = _spectrometer; _spectrometer = null; _connected = false; _devices = Array.Empty(); _selectedDevice = null; if (spectrometer is null) { return; } try { // ArisSpectrometer.Dispose 内部会先 stop 再 disconnect,然后销毁上下文。 spectrometer.Dispose(); } catch (Exception ex) { _logger.LogWarning(ex, "释放 aris 光谱仪上下文时发生异常"); } } // ---------- 单帧采集 ---------- public async Task AcquireFrameAsync( SpectrumAcquisitionRequest? request = null, CancellationToken ct = default) { await _gate.WaitAsync(ct).ConfigureAwait(false); try { ThrowIfDisposed(); var spectrometer = _spectrometer; if (!_connected || spectrometer is null) { throw new HardwareException( HardwareErrorKind.NotConnected, "光谱仪尚未连接,请先调用连接接口"); } var parameters = Normalize(request); ct.ThrowIfCancellationRequested(); _logger.LogDebug( "开始单帧采集:设备 {DeviceIndex},曝光 {ExposureUs}us,平均 {Averaging},延迟 {DelayUs}us,超时 {TimeoutMs}ms", parameters.DeviceIndex, parameters.ExposureUs, parameters.Averaging, parameters.DelayUs, parameters.TimeoutMs); var startedAt = Stopwatch.GetTimestamp(); ArisSpectrumFrame native; try { native = await Task.Run( () => spectrometer.AcquireFrame( parameters.DeviceIndex, parameters.ExposureUs, parameters.Averaging, parameters.DelayUs, parameters.TimeoutMs), CancellationToken.None) .ConfigureAwait(false); } catch (ArisException ex) { _logger.LogWarning( ex, "单帧采集失败,状态码 {Status}", ex.Status); throw MapArisException(ex, "采集光谱"); } var acquiredAt = DateTimeOffset.Now; var elapsed = Stopwatch.GetElapsedTime(startedAt); var frame = MapFrame(native, parameters.DeviceIndex, acquiredAt, elapsed); Interlocked.Increment(ref _framesAcquired); Interlocked.Exchange(ref _lastAcquireAtTicks, acquiredAt.UtcTicks); _logger.LogDebug( "单帧采集完成:设备 {DeviceIndex},{PixelCount} 像素,耗时 {ElapsedMs:F0}ms,温度 {Temperature:F2}℃", frame.DeviceIndex, frame.Info.PixelCount, elapsed.TotalMilliseconds, frame.Info.SensorTemperature); return frame; } finally { _gate.Release(); } } // ---------- 多台同步采集 ---------- public async Task AcquireSynchronizedAsync( SynchronizedSpectrumRequest? request = null, CancellationToken ct = default) { await _gate.WaitAsync(ct).ConfigureAwait(false); try { ThrowIfDisposed(); var spectrometer = RequireConnected(); var parameters = NormalizeSynchronized(request); ct.ThrowIfCancellationRequested(); return await Task.Run( () => AcquireSynchronizedCore(spectrometer, parameters), CancellationToken.None) .ConfigureAwait(false); } finally { _gate.Release(); } } private SynchronizedSpectrumResult AcquireSynchronizedCore( ArisSpectrometer spectrometer, (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 bySerial = new Dictionary( StringComparer.OrdinalIgnoreCase); foreach (var device in devices) { if (!bySerial.TryAdd(device.SerialNumber, device)) { _logger.LogWarning( "重复的光谱仪序列号 {SerialNumber},只保留第一台", device.SerialNumber); } } var frames = new ConcurrentDictionary( StringComparer.OrdinalIgnoreCase); var errors = new ConcurrentDictionary( StringComparer.OrdinalIgnoreCase); var accounted = new ConcurrentDictionary( StringComparer.OrdinalIgnoreCase); var completion = new TaskCompletionSource( TaskCreationOptions.RunContinuationsAsynchronously); EventHandler onSpectrum = (_, e) => { // 回调在 aris 测量线程上:只做拷贝/入队,不调用任何阻塞接口。 var serial = e.SerialNumber.Trim(); if (!bySerial.ContainsKey(serial)) { return; } frames.TryAdd( serial, new CapturedSpectrum(e.Wavelengths, e.Spectrum, DateTimeOffset.Now)); accounted.TryAdd(serial, 0); if (accounted.Count >= expected) { completion.TrySetResult(true); } }; EventHandler onError = (_, e) => { var serial = e.SerialNumber.Trim(); if (!bySerial.ContainsKey(serial)) { return; } errors[serial] = e.Message; accounted.TryAdd(serial, 0); if (accounted.Count >= expected) { completion.TrySetResult(true); } }; var startedAt = Stopwatch.GetTimestamp(); var startElapsed = TimeSpan.Zero; var waitElapsed = TimeSpan.Zero; spectrometer.SpectrumReceived += onSpectrum; spectrometer.ErrorOccurred += onError; try { _logger.LogInformation( "开始多台光谱仪同步采集:{DeviceCount} 台,曝光 {ExposureUs}us,平均 {Averaging},延迟 {DelayUs}us", expected, parameters.ExposureUs, parameters.Averaging, parameters.DelayUs); // 一次武装所有空闲设备;measureCount=1 表示每台只采一帧。 spectrometer.StartMeasurement( parameters.ExposureUs, parameters.Averaging, parameters.DelayUs, measureCount: 1); startElapsed = Stopwatch.GetElapsedTime(startedAt); var waitStarted = Stopwatch.GetTimestamp(); completion.Task.Wait(parameters.WaitTimeoutMs); waitElapsed = Stopwatch.GetElapsedTime(waitStarted); } catch (ArisException ex) { _logger.LogError( ex, "多台光谱仪同步采集失败,状态码 {Status}", ex.Status); throw MapArisException(ex, "同步采集多台光谱仪"); } finally { // StopMeasurement 会置停止标志并 join 全部测量线程,必须在回调线程之外调用。 try { spectrometer.StopMeasurement(); } catch (Exception ex) { _logger.LogWarning(ex, "停止多台光谱仪测量时发生异常"); } spectrometer.SpectrumReceived -= onSpectrum; spectrometer.ErrorOccurred -= onError; } var acquiredAt = DateTimeOffset.Now; var received = new List(frames.Count); foreach (var pair in frames.OrderBy( pair => pair.Key, StringComparer.OrdinalIgnoreCase)) { if (!bySerial.TryGetValue(pair.Key, out var device)) { continue; } var captured = pair.Value; if (captured.Wavelengths.Length == 0 || captured.Wavelengths.Length != captured.Spectrum.Length) { errors[pair.Key] = "波长与光谱长度不一致或为空"; continue; } received.Add(new SynchronizedSpectrumFrame( device.Index, device.SerialNumber, captured.Wavelengths, captured.Spectrum, captured.ReceivedAt)); } var receivedSerials = new HashSet( received.Select(frame => frame.SerialNumber), StringComparer.OrdinalIgnoreCase); var missing = devices .Where(device => !receivedSerials.Contains(device.SerialNumber)) .Select(device => device.SerialNumber) .ToArray(); var errorList = errors .OrderBy(pair => pair.Key, StringComparer.OrdinalIgnoreCase) .Select(pair => new SpectrumDeviceError(pair.Key, pair.Value)) .ToArray(); if (received.Count == 0) { var detail = errorList.Length == 0 ? "等待超时,未收到任何设备的光谱帧" : "未收到任何设备的光谱帧:" + string.Join( ";", errorList.Select(error => $"{error.SerialNumber}: {error.Message}")); throw new HardwareException(HardwareErrorKind.Timeout, detail); } MergedSpectrum merged; try { merged = SpectrumMerger.Merge(received); } 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, received.Count); Interlocked.Exchange(ref _lastAcquireAtTicks, acquiredAt.UtcTicks); _logger.LogInformation( "多台光谱仪同步采集完成:收到 {ReceivedCount}/{ExpectedCount} 台,拼接后 {PixelCount} 点,等待 {WaitMs:F0}ms", received.Count, expected, merged.PixelCount, waitElapsed.TotalMilliseconds); return new SynchronizedSpectrumResult( received, merged, missing, errorList, expected, acquiredAt, startElapsed, waitElapsed); } 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 GetDeviceStatusAsync( int? deviceIndex = null, CancellationToken ct = default) { await _gate.WaitAsync(ct).ConfigureAwait(false); try { ThrowIfDisposed(); var spectrometer = RequireConnected(); var index = ResolveDeviceIndex(deviceIndex); try { var status = await Task.Run( () => spectrometer.GetDeviceStatus(index), CancellationToken.None) .ConfigureAwait(false); return new SpectrometerDeviceStatus( index, status.State.ToString(), status.AvailableSpectra); } catch (ArisException ex) { throw MapArisException(ex, "查询设备状态"); } } finally { _gate.Release(); } } public async Task GetWavelengthsAsync( int? deviceIndex = null, CancellationToken ct = default) { await _gate.WaitAsync(ct).ConfigureAwait(false); try { ThrowIfDisposed(); var spectrometer = RequireConnected(); var index = ResolveDeviceIndex(deviceIndex); try { return await Task.Run( () => spectrometer.GetWavelengths(index), CancellationToken.None) .ConfigureAwait(false); } catch (ArisException ex) { throw MapArisException(ex, "读取波长"); } } finally { _gate.Release(); } } private ArisSpectrometer RequireConnected() { var spectrometer = _spectrometer; if (!_connected || spectrometer is null) { throw new HardwareException( HardwareErrorKind.NotConnected, "光谱仪尚未连接,请先调用连接接口"); } return spectrometer; } // ---------- 映射 ---------- private static SpectrometerDeviceInfo MapDevice(int index, DeviceInfo info) => new( index, info.SerialNumber, info.PixelCount, info.StartPixel, info.EndPixel, info.FirmwareVersion.ToString()); private static SpectrumFrame MapFrame( ArisSpectrumFrame native, int deviceIndex, DateTimeOffset acquiredAt, TimeSpan elapsed) { var info = native.Info; return new SpectrumFrame( deviceIndex, native.SerialNumber, native.Wavelengths, native.Spectrum, new SpectrumFrameInfo( info.ExposureTimeUs, info.Averaging, info.DeviceTime10Us, info.DeviceDateDays, info.PixelCount, info.DataFormat, info.LoadLevel, info.SensorTemperature, info.DarkAvg, info.ReadoutNoise, info.AppliedProcessing, info.ErrorFlags, info.IntensityUnit, info.DarkSubtracted), acquiredAt, elapsed); } private sealed record CapturedSpectrum( float[] Wavelengths, float[] Spectrum, DateTimeOffset ReceivedAt); private static HardwareException MapArisException( ArisException ex, string operation, bool connecting = false) { var kind = ex.Status switch { ArisStatus.NoDevice => connecting ? HardwareErrorKind.ConnectFailed : HardwareErrorKind.NotConnected, ArisStatus.NotConnected => HardwareErrorKind.NotConnected, ArisStatus.Timeout => HardwareErrorKind.Timeout, ArisStatus.InvalidArgument => HardwareErrorKind.InvalidArgument, ArisStatus.InvalidState => HardwareErrorKind.InvalidState, ArisStatus.NotSupported => HardwareErrorKind.NotSupported, ArisStatus.DeviceError or ArisStatus.Communication => HardwareErrorKind.CommunicationFailed, ArisStatus.BufferTooSmall or ArisStatus.Internal => HardwareErrorKind.Unknown, _ => HardwareErrorKind.Unknown, }; var hint = ex.Status switch { ArisStatus.NoDevice => "。请检查光谱仪 USB 连接以及 354F:0101 的 WinUSB/libusb 驱动", ArisStatus.Timeout => "。请检查触发模式与曝光时间,或确认设备是否响应", ArisStatus.InvalidState => "。设备可能仍在上一轮测量中,请稍后重试或重新连接", ArisStatus.Communication or ArisStatus.DeviceError => "。请检查 USB 供电与线缆", ArisStatus.NotSupported => "。设备/固件不支持该配置(例如数据格式不是 0)", _ => string.Empty, }; return new HardwareException(kind, $"{operation}失败:{ex.Message}{hint}", ex); } private static string BuildNativeLoadFailureMessage(Exception ex) => ex switch { DllNotFoundException => "加载 aris.dll 失败:请确认 aris.dll 与 libusb-1.0.dll 已复制到程序输出目录" + $"(当前目录:{AppContext.BaseDirectory})", BadImageFormatException => "加载 aris.dll 失败:DLL 位数与进程不匹配,请使用 x64 进程运行", EntryPointNotFoundException => "加载 aris.dll 失败:DLL 版本与 ArisSharp.dll 不匹配,请使用配套版本", _ => "加载 aris 原生库失败", }; // ---------- 释放 ---------- private void ThrowIfDisposed() { ObjectDisposedException.ThrowIf(_disposed, this); } public async ValueTask DisposeAsync() { await _gate.WaitAsync().ConfigureAwait(false); try { if (_disposed) { return; } _disposed = true; DisposeSpectrometerCore(); } finally { _gate.Release(); _gate.Dispose(); } GC.SuppressFinalize(this); } } }