添加项目文件。
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FlashCap" Version="1.12.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.14" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.14" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="ArisSharp">
|
||||
<HintPath>dll\aris\ArisSharp.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
aris.dll / libusb-1.0.dll 是 ArisSharp.dll 的原生依赖,必须和可执行文件放在同一目录。
|
||||
作为项目内容复制,引用本项目的 HardwareWeb / HardwareProbe 输出目录也会带上它们。
|
||||
-->
|
||||
<ItemGroup>
|
||||
<None Update="dll\aris\aris.dll">
|
||||
<Link>aris.dll</Link>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
</None>
|
||||
<None Update="dll\aris\libusb-1.0.dll">
|
||||
<Link>libusb-1.0.dll</Link>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HardwareControl.Core
|
||||
{
|
||||
public enum HardwareErrorKind
|
||||
{
|
||||
NotConnected,
|
||||
ConnectFailed,
|
||||
CommunicationFailed,
|
||||
Timeout,
|
||||
Unknown,
|
||||
InvalidArgument,
|
||||
InvalidState,
|
||||
NotSupported
|
||||
}
|
||||
|
||||
public class HardwareException : Exception
|
||||
{
|
||||
public HardwareErrorKind Kind { get; }
|
||||
|
||||
public HardwareException(HardwareErrorKind kind, string message, Exception? inner = null) : base(message, inner)
|
||||
{
|
||||
Kind = kind;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using HardwareControl.Core.Spectrometer;
|
||||
|
||||
namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
|
||||
{
|
||||
/// <summary>
|
||||
/// aris 光谱仪服务。
|
||||
/// 单台使用 AcquireFrame 同步单帧;多台使用 StartMeasurement 一次性武装,
|
||||
/// 收齐回调后按波长拼接。所有操作在内部串行化,单帧/多台采集互斥。
|
||||
/// </summary>
|
||||
public interface IArisSpectrometerService : IAsyncDisposable
|
||||
{
|
||||
/// <summary>是否已经成功连接(不保证设备此刻仍在线)。</summary>
|
||||
bool IsConnected { get; }
|
||||
|
||||
/// <summary>连接时发现并初始化的设备数量。</summary>
|
||||
int DeviceCount { get; }
|
||||
|
||||
/// <summary>当前选中的设备;未连接时为 null。</summary>
|
||||
SpectrometerDeviceInfo? SelectedDevice { get; }
|
||||
|
||||
/// <summary>选中设备的像素数;未连接时为 null。</summary>
|
||||
int? PixelCount { get; }
|
||||
|
||||
/// <summary>连接时缓存的设备列表;未连接时为空。</summary>
|
||||
IReadOnlyList<SpectrometerDeviceInfo> Devices { get; }
|
||||
|
||||
/// <summary>本次连接累计成功采集的帧数。</summary>
|
||||
long FramesAcquired { get; }
|
||||
|
||||
/// <summary>最近一次成功采集的完成时间;尚未采集时为 null。</summary>
|
||||
DateTimeOffset? LastAcquireAt { get; }
|
||||
|
||||
Task ConnectAsync(CancellationToken ct = default);
|
||||
|
||||
Task DisconnectAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// 同步采一帧。内部串行化所有原生调用,因此并发调用会排队,
|
||||
/// <paramref name="ct"/> 只影响排队阶段,已开始的曝光无法取消。
|
||||
/// </summary>
|
||||
Task<SpectrumFrame> AcquireFrameAsync(
|
||||
SpectrumAcquisitionRequest? request = null,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// 多台光谱仪同步采集一帧:StartMeasurement 一次武装所有设备,
|
||||
/// 收齐每台设备的回调后按波长自动拼接(重合区间各去一半)。
|
||||
/// 由第三台设备触发激光的场景使用 Software 触发模式;
|
||||
/// 有外部 AD/TTL 触发源时使用 FreeRunEdge/External。
|
||||
/// 部分设备超时会返回已收到的帧,并通过 MissingSerials 标记缺失设备。
|
||||
/// </summary>
|
||||
Task<SynchronizedSpectrumResult> AcquireSynchronizedAsync(
|
||||
SynchronizedSpectrumRequest? request = null,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>查询设备运行时状态(一次 USB 往返)。</summary>
|
||||
Task<SpectrometerDeviceStatus> GetDeviceStatusAsync(
|
||||
int? deviceIndex = null,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>读取波长数组(用于单独绘制坐标轴)。</summary>
|
||||
Task<float[]> GetWavelengthsAsync(
|
||||
int? deviceIndex = null,
|
||||
CancellationToken ct = default);
|
||||
|
||||
event EventHandler<SpectrometerStatusChangedEventArgs>? StatusChanged;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using HardwareControl.Core.UsbCamera;
|
||||
|
||||
namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
|
||||
{
|
||||
public interface IUsbCameraService : IAsyncDisposable
|
||||
{
|
||||
bool IsConnected { get; }
|
||||
|
||||
/// <summary>最近一次成功打开的设备名称。</summary>
|
||||
string? DeviceName { get; }
|
||||
|
||||
/// <summary>当前(或最近一次)采集格式;未打开过设备时为 null。</summary>
|
||||
CameraFrameFormat? FrameFormat { get; }
|
||||
|
||||
/// <summary>最近一帧的到达时间(UTC);尚未收到帧时为 null。</summary>
|
||||
DateTimeOffset? LastFrameAt { get; }
|
||||
|
||||
/// <summary>本次连接累计收到的帧数。</summary>
|
||||
long FramesReceived { get; }
|
||||
|
||||
Task ConnectAsync(CancellationToken ct = default);
|
||||
Task DisconnectAsync(CancellationToken ct = default);
|
||||
|
||||
event EventHandler<UsbCameraStatusChangedEventArgs>? StatusChanged;
|
||||
event EventHandler<FrameArrivedEventArgs>? FrameArrived;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,921 @@
|
||||
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
|
||||
{
|
||||
/// <summary>
|
||||
/// aris 光谱仪服务实现。
|
||||
///
|
||||
/// 线程模型:
|
||||
/// * 所有原生调用(连接、单帧采集、多台同步采集、状态、波长)都由 <see cref="_gate"/> 串行化,
|
||||
/// 因为 <see cref="ArisSpectrometer"/> / aris.dll 内部虽然也加锁,但采集是长事务,
|
||||
/// 在业务层排队更容易控制超时与日志;
|
||||
/// * 原生调用是同步阻塞的,因此放到线程池执行,避免占用 ASP.NET Core 请求线程;
|
||||
/// * 单台使用同步 <c>AcquireFrame</c>;多台使用 <c>StartMeasurement</c> 一次武装,
|
||||
/// 回调只做拷贝/入队,收齐后调用 <c>StopMeasurement</c> 并拼接。
|
||||
/// 单帧与多台测量在 SDK 层互斥(测量中调用单帧会返回 InvalidState)。
|
||||
/// </summary>
|
||||
public sealed class ArisSpectrometerService : IArisSpectrometerService
|
||||
{
|
||||
private readonly ArisSpectrometerOptions _options;
|
||||
private readonly ILogger<ArisSpectrometerService> _logger;
|
||||
|
||||
// 串行化全部原生调用
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
|
||||
private ArisSpectrometer? _spectrometer;
|
||||
private volatile SpectrometerDeviceInfo[] _devices = 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 => _devices.Length;
|
||||
|
||||
public SpectrometerDeviceInfo? SelectedDevice => _selectedDevice;
|
||||
|
||||
public int? PixelCount => _selectedDevice?.PixelCount;
|
||||
|
||||
public IReadOnlyList<SpectrometerDeviceInfo> 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<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()
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>停止测量、断开并销毁上下文;异常只记日志,保证状态一定归零。</summary>
|
||||
private void DisposeSpectrometerCore()
|
||||
{
|
||||
var spectrometer = _spectrometer;
|
||||
_spectrometer = null;
|
||||
_connected = false;
|
||||
_devices = Array.Empty<SpectrometerDeviceInfo>();
|
||||
_selectedDevice = null;
|
||||
|
||||
if (spectrometer is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// ArisSpectrometer.Dispose 内部会先 stop 再 disconnect,然后销毁上下文。
|
||||
spectrometer.Dispose();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "释放 aris 光谱仪上下文时发生异常");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 单帧采集 ----------
|
||||
|
||||
public async Task<SpectrumFrame> 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<SynchronizedSpectrumResult> 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<string, SpectrometerDeviceInfo>(
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var device in devices)
|
||||
{
|
||||
if (!bySerial.TryAdd(device.SerialNumber, device))
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"重复的光谱仪序列号 {SerialNumber},只保留第一台",
|
||||
device.SerialNumber);
|
||||
}
|
||||
}
|
||||
|
||||
var frames = new ConcurrentDictionary<string, CapturedSpectrum>(
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
var errors = new ConcurrentDictionary<string, string>(
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
var accounted = new ConcurrentDictionary<string, byte>(
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
var completion = new TaskCompletionSource<bool>(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
EventHandler<SpectrumReceivedEventArgs> 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<SpectrometerErrorEventArgs> 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<SynchronizedSpectrumFrame>(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<string>(
|
||||
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<SpectrometerDeviceStatus> 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<float[]> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
using FlashCap;
|
||||
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
||||
using HardwareControl.Core.UsbCamera;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace HardwareControl.Core.HardwareServiceImpl
|
||||
{
|
||||
public class UsbCameraService : IUsbCameraService
|
||||
{
|
||||
private readonly UsbCameraOptions _options;
|
||||
private readonly ILogger<UsbCameraService> _logger;
|
||||
|
||||
// 串行化所有对 FlashCap 设备对象的访问
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
|
||||
private CaptureDevice? _device;
|
||||
private CancellationTokenSource? _reconnectCts;
|
||||
private volatile bool _connected;
|
||||
|
||||
private volatile CameraFrameFormat? _frameFormat;
|
||||
private volatile string? _deviceName;
|
||||
private long _lastFrameAtTicks;
|
||||
private long _framesReceived;
|
||||
private long _connectedAtTicks;
|
||||
|
||||
public bool IsConnected => _connected;
|
||||
|
||||
public string? DeviceName => _deviceName;
|
||||
|
||||
public CameraFrameFormat? FrameFormat => _frameFormat;
|
||||
|
||||
public DateTimeOffset? LastFrameAt
|
||||
{
|
||||
get
|
||||
{
|
||||
var ticks = Interlocked.Read(ref _lastFrameAtTicks);
|
||||
return ticks == 0 ? null : new DateTimeOffset(ticks, TimeSpan.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
public long FramesReceived => Interlocked.Read(ref _framesReceived);
|
||||
|
||||
public event EventHandler<UsbCameraStatusChangedEventArgs>? StatusChanged;
|
||||
public event EventHandler<FrameArrivedEventArgs>? FrameArrived;
|
||||
|
||||
public UsbCameraService(
|
||||
IOptions<UsbCameraOptions> options,
|
||||
ILogger<UsbCameraService> logger)
|
||||
{
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// ---------- 连接 ----------
|
||||
|
||||
public async Task ConnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (_connected) return;
|
||||
await ConnectCoreAsync(ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ConnectCoreAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var devices = new CaptureDevices();
|
||||
var descriptors = devices.EnumerateDescriptors().ToList();
|
||||
|
||||
if (descriptors.Count == 0)
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.ConnectFailed, "没有枚举到任何相机设备");
|
||||
|
||||
var descriptor = SelectDescriptor(descriptors);
|
||||
var characteristics = SelectCharacteristics(descriptor);
|
||||
var format = CameraFrameFormat.From(characteristics);
|
||||
|
||||
_logger.LogInformation(
|
||||
"尝试打开相机:{Device},格式:{Format}({Width}x{Height},{Fps:F1}fps,{Mime})",
|
||||
descriptor, characteristics,
|
||||
format.Width, format.Height, format.FramesPerSecond, format.MimeType);
|
||||
|
||||
Interlocked.Exchange(ref _framesReceived, 0);
|
||||
Interlocked.Exchange(ref _lastFrameAtTicks, 0);
|
||||
_frameFormat = format;
|
||||
_deviceName = descriptor.Name;
|
||||
|
||||
// 注意:OpenAsync 的回调在 FlashCap 内部线程执行,
|
||||
// 回调内不能阻塞太久,否则会丢帧。
|
||||
_device = await descriptor.OpenAsync(
|
||||
characteristics,
|
||||
async bufferScope =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_connected)
|
||||
{
|
||||
// 已断开或正在重连,丢弃旧设备回调中的帧
|
||||
return;
|
||||
}
|
||||
|
||||
// ExtractImage() 可能返回 FlashCap 内部复用的缓冲区,
|
||||
// 而帧会进入 Channel 异步发送,必须用 CopyImage() 取得独立副本。
|
||||
byte[] image = bufferScope.Buffer.CopyImage();
|
||||
long frameIndex = bufferScope.Buffer.FrameIndex;
|
||||
var timestamp = bufferScope.Buffer.Timestamp;
|
||||
var capturedAt = DateTimeOffset.Now;
|
||||
|
||||
Interlocked.Increment(ref _framesReceived);
|
||||
Interlocked.Exchange(ref _lastFrameAtTicks, capturedAt.UtcTicks);
|
||||
|
||||
FrameArrived?.Invoke(
|
||||
this,
|
||||
new FrameArrivedEventArgs(
|
||||
image, frameIndex, timestamp, capturedAt, format));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "抓帧回调中发生异常");
|
||||
}
|
||||
});
|
||||
|
||||
await _device.StartAsync();
|
||||
|
||||
Interlocked.Exchange(
|
||||
ref _connectedAtTicks, DateTimeOffset.UtcNow.UtcTicks);
|
||||
_connected = true;
|
||||
_logger.LogInformation("相机已连接并开始采集");
|
||||
StatusChanged?.Invoke(this, new(true, "相机已连接"));
|
||||
|
||||
// 启动后台监控(用于检测断线与画面超时)
|
||||
EnsureReconnectWatcher();
|
||||
}
|
||||
catch (HardwareException)
|
||||
{
|
||||
_connected = false;
|
||||
_frameFormat = null;
|
||||
_deviceName = null;
|
||||
_device?.Dispose();
|
||||
_device = null;
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_connected = false;
|
||||
_frameFormat = null;
|
||||
_deviceName = null;
|
||||
_device?.Dispose();
|
||||
_device = null;
|
||||
|
||||
_logger.LogError(ex, "连接相机失败");
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.ConnectFailed, "连接相机失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private CaptureDeviceDescriptor SelectDescriptor(
|
||||
List<CaptureDeviceDescriptor> descriptors)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_options.DeviceNameKeyword))
|
||||
{
|
||||
var matched = descriptors.FirstOrDefault(
|
||||
d => d.Name.Contains(
|
||||
_options.DeviceNameKeyword, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (matched != null) return matched;
|
||||
|
||||
_logger.LogWarning(
|
||||
"未找到名称包含 {Keyword} 的设备,回退到第一个设备",
|
||||
_options.DeviceNameKeyword);
|
||||
}
|
||||
|
||||
return descriptors[0];
|
||||
}
|
||||
|
||||
private VideoCharacteristics SelectCharacteristics(
|
||||
CaptureDeviceDescriptor descriptor)
|
||||
{
|
||||
var all = descriptor.Characteristics;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(_options.PreferredFormatKeyword))
|
||||
{
|
||||
var matched = all.FirstOrDefault(
|
||||
c => c.ToString().Contains(
|
||||
_options.PreferredFormatKeyword, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (matched != null) return matched;
|
||||
|
||||
_logger.LogWarning(
|
||||
"未找到格式包含 {Keyword} 的配置,回退到第一个格式",
|
||||
_options.PreferredFormatKeyword);
|
||||
}
|
||||
|
||||
return all[0];
|
||||
}
|
||||
|
||||
// ---------- 断开 ----------
|
||||
|
||||
public async Task DisconnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await DisconnectCoreAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DisconnectCoreAsync()
|
||||
{
|
||||
CancelReconnectWatcher();
|
||||
await StopDeviceAsync();
|
||||
|
||||
if (_connected)
|
||||
{
|
||||
_connected = false;
|
||||
Interlocked.Exchange(ref _connectedAtTicks, 0);
|
||||
StatusChanged?.Invoke(this, new(false, "相机已断开"));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 重连监控 ----------
|
||||
|
||||
/// <summary>
|
||||
/// 保证只有一个重连监控循环。重连成功时 ConnectCoreAsync 会调用它,
|
||||
/// 若当前循环仍在运行则不会重复创建。
|
||||
/// </summary>
|
||||
private void EnsureReconnectWatcher()
|
||||
{
|
||||
var existing = _reconnectCts;
|
||||
if (existing is { IsCancellationRequested: false })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
existing?.Dispose();
|
||||
_reconnectCts = new CancellationTokenSource();
|
||||
var token = _reconnectCts.Token;
|
||||
_ = Task.Run(() => ReconnectLoopAsync(token));
|
||||
}
|
||||
|
||||
private void CancelReconnectWatcher()
|
||||
{
|
||||
var cts = _reconnectCts;
|
||||
_reconnectCts = null;
|
||||
if (cts is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
cts.Cancel();
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// 已释放,忽略
|
||||
}
|
||||
|
||||
cts.Dispose();
|
||||
}
|
||||
|
||||
private async Task ReconnectLoopAsync(CancellationToken ct)
|
||||
{
|
||||
var baseDelay = Math.Max(250, _options.ReconnectBaseDelayMs);
|
||||
var maxDelay = Math.Max(baseDelay, _options.ReconnectMaxDelayMs);
|
||||
var delay = baseDelay;
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(delay, ct);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (ct.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (_connected)
|
||||
{
|
||||
if (!HasFrameTimedOut())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_logger.LogWarning(
|
||||
"超过 {Timeout}ms 未收到相机帧,标记断线并重连",
|
||||
_options.FrameTimeoutMs);
|
||||
|
||||
try
|
||||
{
|
||||
await MarkDisconnectedAsync("相机画面超时,正在重连...", ct);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("检测到断线,尝试重连...");
|
||||
StatusChanged?.Invoke(this, new(false, "正在重连..."));
|
||||
|
||||
try
|
||||
{
|
||||
await _gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (_connected)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await ConnectCoreAsync(ct);
|
||||
delay = baseDelay;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "重连失败,{Delay}ms 后重试", delay);
|
||||
delay = Math.Min(delay * 2, maxDelay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>检查当前连接是否长时间没有新帧。</summary>
|
||||
private bool HasFrameTimedOut()
|
||||
{
|
||||
var timeoutMs = _options.FrameTimeoutMs;
|
||||
if (timeoutMs <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var referenceTicks = Interlocked.Read(ref _lastFrameAtTicks);
|
||||
if (referenceTicks == 0)
|
||||
{
|
||||
referenceTicks = Interlocked.Read(ref _connectedAtTicks);
|
||||
}
|
||||
|
||||
if (referenceTicks == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var reference = new DateTimeOffset(referenceTicks, TimeSpan.Zero);
|
||||
return DateTimeOffset.UtcNow - reference >
|
||||
TimeSpan.FromMilliseconds(timeoutMs);
|
||||
}
|
||||
|
||||
/// <summary>画面超时时由监控循环调用:停止旧设备并通知前端。</summary>
|
||||
private async Task MarkDisconnectedAsync(string message, CancellationToken ct)
|
||||
{
|
||||
await _gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
if (!_connected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_connected = false;
|
||||
Interlocked.Exchange(ref _connectedAtTicks, 0);
|
||||
await StopDeviceAsync();
|
||||
StatusChanged?.Invoke(this, new(false, message));
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StopDeviceAsync()
|
||||
{
|
||||
var device = _device;
|
||||
_device = null;
|
||||
if (device is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await device.StopAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "停止采集时发生异常");
|
||||
}
|
||||
|
||||
device.Dispose();
|
||||
}
|
||||
|
||||
// ---------- 释放 ----------
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await DisconnectAsync();
|
||||
_gate.Dispose();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using Aris;
|
||||
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// aris 光谱仪配置,对应 appsettings.json 的 "ArisSpectrometer" 节。
|
||||
/// 所有属性都有默认值,配置文件可只写需要覆盖的项。
|
||||
/// </summary>
|
||||
public sealed class ArisSpectrometerOptions
|
||||
{
|
||||
public const string SectionName = "ArisSpectrometer";
|
||||
|
||||
/// <summary>
|
||||
/// 默认使用的设备索引(0 起)。多台设备时由 <see cref="PreferredSerialNumber"/> 优先。
|
||||
/// </summary>
|
||||
public int DeviceIndex { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 优先匹配的序列号;非空且能匹配到设备时覆盖 <see cref="DeviceIndex"/>。
|
||||
/// </summary>
|
||||
public string? PreferredSerialNumber { get; set; }
|
||||
|
||||
/// <summary>单帧采集默认曝光时间,单位微秒,必须大于 0。</summary>
|
||||
public int ExposureUs { get; set; } = 1000;
|
||||
|
||||
/// <summary>单帧采集默认平均次数,必须大于等于 1。</summary>
|
||||
public int Averaging { get; set; } = 1;
|
||||
|
||||
/// <summary>单帧采集默认触发延迟,单位微秒,必须大于等于 0。</summary>
|
||||
public int DelayUs { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 单帧采集默认超时,单位毫秒;小于等于 0 时由 SDK 按
|
||||
/// <c>max(3000, 曝光/1000 + 2000)</c> 计算。
|
||||
/// </summary>
|
||||
public int TimeoutMs { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 多台同步采集的默认曝光时间,单位微秒。
|
||||
/// SDK 逐台武装设备,第三台通常比前两台晚约 0.6 秒启动;
|
||||
/// 曝光窗口必须覆盖这段武装时间,否则前两台会在第三台触发激光前结束。
|
||||
/// 默认 1 秒,可按现场时序下调,但建议不低于 0.7 秒。
|
||||
/// </summary>
|
||||
public int SynchronizedExposureUs { get; set; } = 1_000_000;
|
||||
|
||||
/// <summary>
|
||||
/// 多台同步采集时,StartMeasurement 返回后等待所有设备回调的默认最长时间(毫秒)。
|
||||
/// </summary>
|
||||
public int SynchronizedWaitTimeoutMs { get; set; } = 8000;
|
||||
|
||||
/// <summary>
|
||||
/// 连接成功后设置的触发模式;为 null 时保持设备当前配置。
|
||||
/// 手册要求触发模式只在连接后设置一次。
|
||||
/// 默认 <see cref="Aris.TriggerMode.Software"/>:纯自由运行。
|
||||
/// 由第三台设备触发激光、其余设备自由收光的场景使用 Software;
|
||||
/// 有外部 AD/TTL 触发源时改为 FreeRunEdge 或 External。
|
||||
/// </summary>
|
||||
public TriggerMode? TriggerMode { get; set; } = Aris.TriggerMode.Software;
|
||||
|
||||
/// <summary>
|
||||
/// 连接成功后设置的增益(0=低增益,1=高增益);为 null 时保持设备当前配置。
|
||||
/// </summary>
|
||||
public int? Gain { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否打开 aris.dll 内部的诊断日志(默认关闭,避免刷屏)。
|
||||
/// </summary>
|
||||
public bool SdkLogEnabled { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 多台光谱仪按波长拼接后的结果。
|
||||
/// 拼接直接使用各设备原始采样点,不做插值;重合波长区间的处理规则见
|
||||
/// <see cref="SpectrumMerger"/>。
|
||||
/// </summary>
|
||||
/// <param name="Wavelengths">拼接后的波长数组,按升序排列。</param>
|
||||
/// <param name="Spectrum">拼接后的强度数组,与波长等长。</param>
|
||||
/// <param name="Segments">每一段数据的来源设备,用于分段绘图。</param>
|
||||
public sealed record MergedSpectrum(
|
||||
float[] Wavelengths,
|
||||
float[] Spectrum,
|
||||
IReadOnlyList<MergedSpectrumSegment> Segments)
|
||||
{
|
||||
public int PixelCount => Wavelengths.Length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 拼接后光谱中的一段,表示这一段采样点来自哪台设备。
|
||||
/// 前端应按 Segments 分段绘制;相邻段波长不连续时应断开连线,避免把光谱间隙画成直线。
|
||||
/// </summary>
|
||||
/// <param name="DeviceIndex">来源设备索引。</param>
|
||||
/// <param name="SerialNumber">来源设备序列号。</param>
|
||||
/// <param name="WavelengthStart">该段第一个点的波长。</param>
|
||||
/// <param name="WavelengthEnd">该段最后一个点的波长。</param>
|
||||
/// <param name="PointCount">该段的采样点数。</param>
|
||||
public sealed record MergedSpectrumSegment(
|
||||
int DeviceIndex,
|
||||
string SerialNumber,
|
||||
float WavelengthStart,
|
||||
float WavelengthEnd,
|
||||
int PointCount);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 光谱仪静态信息(连接时读取一次)。
|
||||
/// </summary>
|
||||
/// <param name="Index">设备索引(0 起),调用单帧采集时使用。</param>
|
||||
/// <param name="SerialNumber">设备序列号。</param>
|
||||
/// <param name="PixelCount">光谱像素数,即波长与强度数组的长度。</param>
|
||||
/// <param name="StartPixel">
|
||||
/// 协议 0x2009 的原始值(手册语义为 FirstOffsetPixel),
|
||||
/// 不是光谱起始像素,请勿用于切片。
|
||||
/// </param>
|
||||
/// <param name="EndPixel">
|
||||
/// 协议 0x200A 的原始值(手册语义为 NumOffsetPixels),
|
||||
/// 不是光谱结束像素,请勿用于切片。
|
||||
/// </param>
|
||||
/// <param name="FirmwareVersion">固件版本,形如 4.1.7.0。</param>
|
||||
public sealed record SpectrometerDeviceInfo(
|
||||
int Index,
|
||||
string SerialNumber,
|
||||
int PixelCount,
|
||||
int StartPixel,
|
||||
int EndPixel,
|
||||
string FirmwareVersion);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 光谱仪运行时状态(每次查询都会走一次 USB 往返)。
|
||||
/// </summary>
|
||||
/// <param name="DeviceIndex">设备索引。</param>
|
||||
/// <param name="State">设备状态名,如 Idle、TakingSpectrum。</param>
|
||||
/// <param name="AvailableSpectra">设备缓冲中可读的帧数。</param>
|
||||
public sealed record SpectrometerDeviceStatus(
|
||||
int DeviceIndex,
|
||||
string State,
|
||||
int AvailableSpectra);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 光谱仪连接状态变化事件参数。
|
||||
/// </summary>
|
||||
public class SpectrometerStatusChangedEventArgs : EventArgs
|
||||
{
|
||||
public bool IsConnected { get; }
|
||||
|
||||
public string Message { get; }
|
||||
|
||||
public SpectrometerStatusChangedEventArgs(bool isConnected, string message)
|
||||
{
|
||||
IsConnected = isConnected;
|
||||
Message = message;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 单帧同步采集参数。为 null 的字段使用
|
||||
/// <see cref="ArisSpectrometerOptions"/> 中的默认值。
|
||||
/// </summary>
|
||||
public sealed record SpectrumAcquisitionRequest
|
||||
{
|
||||
/// <summary>设备索引;为 null 时使用连接时选中的设备。</summary>
|
||||
public int? DeviceIndex { get; init; }
|
||||
|
||||
/// <summary>曝光时间,单位微秒,必须大于 0。</summary>
|
||||
public int? ExposureUs { get; init; }
|
||||
|
||||
/// <summary>平均次数,必须大于等于 1。</summary>
|
||||
public int? Averaging { get; init; }
|
||||
|
||||
/// <summary>触发延迟,单位微秒,必须大于等于 0。</summary>
|
||||
public int? DelayUs { get; init; }
|
||||
|
||||
/// <summary>超时,单位毫秒;小于等于 0 时由 SDK 计算。</summary>
|
||||
public int? TimeoutMs { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>测量过程中 SDK 上报的单台设备错误。</summary>
|
||||
public sealed record SpectrumDeviceError(string SerialNumber, string Message);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 一帧同步采集的光谱。数组已从原生内存复制到托管内存,调用方可以安全留存。
|
||||
/// </summary>
|
||||
/// <param name="DeviceIndex">实际采集的设备索引。</param>
|
||||
/// <param name="SerialNumber">设备序列号。</param>
|
||||
/// <param name="Wavelengths">波长数组,长度等于 <paramref name="Spectrum"/> 的长度。</param>
|
||||
/// <param name="Spectrum">强度数组。</param>
|
||||
/// <param name="Info">报文头元数据。</param>
|
||||
/// <param name="AcquiredAt">采集完成的主机本地时间。</param>
|
||||
/// <param name="Elapsed">从调用原生采集到返回所耗时间。</param>
|
||||
public sealed record SpectrumFrame(
|
||||
int DeviceIndex,
|
||||
string SerialNumber,
|
||||
float[] Wavelengths,
|
||||
float[] Spectrum,
|
||||
SpectrumFrameInfo Info,
|
||||
DateTimeOffset AcquiredAt,
|
||||
TimeSpan Elapsed);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 光谱帧头元数据(来自设备返回的 64 字节报文头)。
|
||||
/// </summary>
|
||||
/// <param name="ExposureTimeUs">实际曝光时间,单位微秒。</param>
|
||||
/// <param name="Averaging">实际平均次数。</param>
|
||||
/// <param name="DeviceTime10Us">设备时间戳:当日 0 点起的 0.1ms 计数。</param>
|
||||
/// <param name="DeviceDateDays">设备日期戳:1970-01-01 起的天数。</param>
|
||||
/// <param name="PixelCount">本帧像素数。</param>
|
||||
/// <param name="DataFormat">设备数据格式;当前 SDK 只支持 0。</param>
|
||||
/// <param name="LoadLevel">负载率,接近 1.0 表示接近饱和。</param>
|
||||
/// <param name="SensorTemperature">传感器温度,单位摄氏度。</param>
|
||||
/// <param name="DarkAvg">暗电平平均值。</param>
|
||||
/// <param name="ReadoutNoise">读出噪声。</param>
|
||||
/// <param name="AppliedProcessing">已应用的处理标志(原始 16 位)。</param>
|
||||
/// <param name="ErrorFlags">非 0 表示该帧处理出错(报文头高 4 位)。</param>
|
||||
/// <param name="IntensityUnit">强度单位(低 4 位)。</param>
|
||||
/// <param name="DarkSubtracted">是否已扣除暗背景。</param>
|
||||
public sealed record SpectrumFrameInfo(
|
||||
int ExposureTimeUs,
|
||||
int Averaging,
|
||||
uint DeviceTime10Us,
|
||||
uint DeviceDateDays,
|
||||
int PixelCount,
|
||||
int DataFormat,
|
||||
float LoadLevel,
|
||||
float SensorTemperature,
|
||||
float DarkAvg,
|
||||
float ReadoutNoise,
|
||||
ushort AppliedProcessing,
|
||||
ushort ErrorFlags,
|
||||
ushort IntensityUnit,
|
||||
bool DarkSubtracted);
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 多台光谱仪的波长拼接。
|
||||
///
|
||||
/// 规则:
|
||||
/// * 任意两台设备的波长区间重合时,以重合区间的中点切分:
|
||||
/// 低波长设备保留重合区间的下半段,高波长设备保留上半段,
|
||||
/// 即“重合部分各去一半”;
|
||||
/// * 三台及以上同时重合时,按两两中点划分区间,再按两两胜出次数决定该区间归属;
|
||||
/// * 单台设备被其他设备覆盖时,允许该设备贡献多段不连续区间;
|
||||
/// * 直接使用各设备原始采样点,不做插值;输出按波长升序排列。
|
||||
/// </summary>
|
||||
public static class SpectrumMerger
|
||||
{
|
||||
private const double Epsilon = 1e-6;
|
||||
|
||||
public static MergedSpectrum Merge(IReadOnlyList<SynchronizedSpectrumFrame> frames)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
|
||||
if (frames.Count == 0)
|
||||
{
|
||||
return Empty();
|
||||
}
|
||||
|
||||
var normalized = frames
|
||||
.Select(Normalize)
|
||||
.Where(frame => frame is not null)
|
||||
.Cast<NormalizedFrame>()
|
||||
.OrderBy(frame => frame.Start)
|
||||
.ThenBy(frame => frame.DeviceIndex)
|
||||
.ToList();
|
||||
|
||||
if (normalized.Count == 0)
|
||||
{
|
||||
return Empty();
|
||||
}
|
||||
|
||||
// 所有设备起止点 + 每两台设备重合区间的中点,把波长轴切成若干基本区间。
|
||||
var boundaries = new List<double>(normalized.Count * 4);
|
||||
foreach (var frame in normalized)
|
||||
{
|
||||
boundaries.Add(frame.Start);
|
||||
boundaries.Add(frame.End);
|
||||
}
|
||||
|
||||
var pairMidpoints = new Dictionary<(int Lower, int Higher), double>();
|
||||
for (var i = 0; i < normalized.Count; i++)
|
||||
{
|
||||
for (var j = i + 1; j < normalized.Count; j++)
|
||||
{
|
||||
var overlapStart = Math.Max(normalized[i].Start, normalized[j].Start);
|
||||
var overlapEnd = Math.Min(normalized[i].End, normalized[j].End);
|
||||
|
||||
if (overlapEnd - overlapStart <= Epsilon)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var midpoint = (overlapStart + overlapEnd) / 2.0;
|
||||
pairMidpoints[(i, j)] = midpoint;
|
||||
boundaries.Add(midpoint);
|
||||
}
|
||||
}
|
||||
|
||||
boundaries.Sort();
|
||||
var uniqueBoundaries = new List<double>(boundaries.Count);
|
||||
foreach (var boundary in boundaries)
|
||||
{
|
||||
if (uniqueBoundaries.Count == 0
|
||||
|| boundary - uniqueBoundaries[^1] > Epsilon)
|
||||
{
|
||||
uniqueBoundaries.Add(boundary);
|
||||
}
|
||||
}
|
||||
|
||||
if (uniqueBoundaries.Count < 2)
|
||||
{
|
||||
return MergeSinglePoint(normalized);
|
||||
}
|
||||
|
||||
var mergedWavelengths = new List<float>(normalized.Sum(frame => frame.Wavelengths.Length));
|
||||
var mergedSpectrum = new List<float>(mergedWavelengths.Capacity);
|
||||
var owners = new List<int>(mergedWavelengths.Capacity);
|
||||
|
||||
for (var index = 0; index < uniqueBoundaries.Count - 1; index++)
|
||||
{
|
||||
var intervalStart = uniqueBoundaries[index];
|
||||
var intervalEnd = uniqueBoundaries[index + 1];
|
||||
if (intervalEnd - intervalStart <= Epsilon)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var probe = (intervalStart + intervalEnd) / 2.0;
|
||||
var covering = new List<int>(normalized.Count);
|
||||
for (var i = 0; i < normalized.Count; i++)
|
||||
{
|
||||
var frame = normalized[i];
|
||||
if (frame.Start <= probe + Epsilon && frame.End >= probe - Epsilon)
|
||||
{
|
||||
covering.Add(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (covering.Count == 0)
|
||||
{
|
||||
// 设备之间的波长空隙:保留空隙,由前端按 Segments 断开绘制。
|
||||
continue;
|
||||
}
|
||||
|
||||
var winner = ChooseWinner(covering, normalized, pairMidpoints, probe);
|
||||
var source = normalized[winner];
|
||||
var first = LowerBound(source.Wavelengths, intervalStart - Epsilon);
|
||||
var last = UpperBound(source.Wavelengths, intervalEnd + Epsilon);
|
||||
|
||||
for (var point = first; point < last; point++)
|
||||
{
|
||||
var wavelength = source.Wavelengths[point];
|
||||
if (!float.IsFinite(wavelength))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// 基本区间在边界处会重叠取点,这里按波长去重。
|
||||
if (mergedWavelengths.Count > 0
|
||||
&& wavelength <= mergedWavelengths[^1] + Epsilon)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
mergedWavelengths.Add(wavelength);
|
||||
mergedSpectrum.Add(source.Spectrum[point]);
|
||||
owners.Add(winner);
|
||||
}
|
||||
}
|
||||
|
||||
if (mergedWavelengths.Count == 0)
|
||||
{
|
||||
return Empty();
|
||||
}
|
||||
|
||||
return new MergedSpectrum(
|
||||
mergedWavelengths.ToArray(),
|
||||
mergedSpectrum.ToArray(),
|
||||
BuildSegments(owners, mergedWavelengths, normalized));
|
||||
}
|
||||
|
||||
private static int ChooseWinner(
|
||||
List<int> covering,
|
||||
List<NormalizedFrame> frames,
|
||||
Dictionary<(int Lower, int Higher), double> pairMidpoints,
|
||||
double probe)
|
||||
{
|
||||
if (covering.Count == 1)
|
||||
{
|
||||
return covering[0];
|
||||
}
|
||||
|
||||
if (covering.Count == 2)
|
||||
{
|
||||
return ChoosePairWinner(
|
||||
covering[0], covering[1], frames, pairMidpoints, probe);
|
||||
}
|
||||
|
||||
// 三台以上同时覆盖:每对设备按其中点规则投一票,票多者获得该区间。
|
||||
var wins = covering.ToDictionary(index => index, _ => 0);
|
||||
for (var x = 0; x < covering.Count; x++)
|
||||
{
|
||||
for (var y = x + 1; y < covering.Count; y++)
|
||||
{
|
||||
var i = covering[x];
|
||||
var j = covering[y];
|
||||
var key = i < j ? (i, j) : (j, i);
|
||||
|
||||
if (!pairMidpoints.TryGetValue(key, out var midpoint))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var winner = ChoosePairWinner(i, j, frames, pairMidpoints, probe);
|
||||
wins[winner]++;
|
||||
}
|
||||
}
|
||||
|
||||
// 平票时优先保留起始波长更高(更靠长波侧)的设备,再按设备索引稳定排序。
|
||||
return covering
|
||||
.OrderByDescending(index => wins[index])
|
||||
.ThenByDescending(index => frames[index].Start)
|
||||
.ThenBy(index => frames[index].DeviceIndex)
|
||||
.First();
|
||||
}
|
||||
|
||||
private static int ChoosePairWinner(
|
||||
int i,
|
||||
int j,
|
||||
List<NormalizedFrame> frames,
|
||||
Dictionary<(int Lower, int Higher), double> pairMidpoints,
|
||||
double probe)
|
||||
{
|
||||
var first = frames[i];
|
||||
var second = frames[j];
|
||||
|
||||
// 起始波长更小的设备是“低波长设备”;完全相同时按设备索引决定。
|
||||
var iIsLower = first.Start < second.Start
|
||||
|| (Math.Abs(first.Start - second.Start) <= Epsilon
|
||||
&& first.DeviceIndex < second.DeviceIndex);
|
||||
|
||||
var lower = iIsLower ? i : j;
|
||||
var higher = iIsLower ? j : i;
|
||||
|
||||
var key = i < j ? (i, j) : (j, i);
|
||||
if (!pairMidpoints.TryGetValue(key, out var midpoint))
|
||||
{
|
||||
return lower;
|
||||
}
|
||||
|
||||
return probe < midpoint ? lower : higher;
|
||||
}
|
||||
|
||||
private static IReadOnlyList<MergedSpectrumSegment> BuildSegments(
|
||||
List<int> owners,
|
||||
List<float> wavelengths,
|
||||
List<NormalizedFrame> frames)
|
||||
{
|
||||
var segments = new List<MergedSpectrumSegment>();
|
||||
var segmentStart = 0;
|
||||
|
||||
for (var i = 1; i <= owners.Count; i++)
|
||||
{
|
||||
if (i < owners.Count && owners[i] == owners[segmentStart])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var source = frames[owners[segmentStart]];
|
||||
segments.Add(new MergedSpectrumSegment(
|
||||
source.DeviceIndex,
|
||||
source.SerialNumber,
|
||||
wavelengths[segmentStart],
|
||||
wavelengths[i - 1],
|
||||
i - segmentStart));
|
||||
|
||||
segmentStart = i;
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
private static MergedSpectrum MergeSinglePoint(List<NormalizedFrame> frames)
|
||||
{
|
||||
var source = frames[0];
|
||||
return new MergedSpectrum(
|
||||
source.Wavelengths,
|
||||
source.Spectrum,
|
||||
new[]
|
||||
{
|
||||
new MergedSpectrumSegment(
|
||||
source.DeviceIndex,
|
||||
source.SerialNumber,
|
||||
source.Wavelengths[0],
|
||||
source.Wavelengths[^1],
|
||||
source.Wavelengths.Length),
|
||||
});
|
||||
}
|
||||
|
||||
private static NormalizedFrame? Normalize(SynchronizedSpectrumFrame frame)
|
||||
{
|
||||
var count = frame.Wavelengths.Length;
|
||||
if (count == 0 || frame.Spectrum.Length != count)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var points = new List<(float Wavelength, float Intensity)>(count);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var wavelength = frame.Wavelengths[i];
|
||||
if (float.IsFinite(wavelength))
|
||||
{
|
||||
points.Add((wavelength, frame.Spectrum[i]));
|
||||
}
|
||||
}
|
||||
|
||||
if (points.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// 正常情况下 SDK 返回的波长已升序;这里排序同时兼容降序/乱序数据。
|
||||
points.Sort((left, right) => left.Wavelength.CompareTo(right.Wavelength));
|
||||
|
||||
var wavelengths = new float[points.Count];
|
||||
var spectrum = new float[points.Count];
|
||||
for (var i = 0; i < points.Count; i++)
|
||||
{
|
||||
wavelengths[i] = points[i].Wavelength;
|
||||
spectrum[i] = points[i].Intensity;
|
||||
}
|
||||
|
||||
return new NormalizedFrame(
|
||||
frame.DeviceIndex,
|
||||
frame.SerialNumber,
|
||||
wavelengths,
|
||||
spectrum,
|
||||
wavelengths[0],
|
||||
wavelengths[^1]);
|
||||
}
|
||||
|
||||
private static int LowerBound(float[] values, double target)
|
||||
{
|
||||
var low = 0;
|
||||
var high = values.Length;
|
||||
while (low < high)
|
||||
{
|
||||
var middle = low + ((high - low) / 2);
|
||||
if (values[middle] < target)
|
||||
{
|
||||
low = middle + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
private static int UpperBound(float[] values, double target)
|
||||
{
|
||||
var low = 0;
|
||||
var high = values.Length;
|
||||
while (low < high)
|
||||
{
|
||||
var middle = low + ((high - low) / 2);
|
||||
if (values[middle] <= target)
|
||||
{
|
||||
low = middle + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
private static MergedSpectrum Empty() => new(
|
||||
Array.Empty<float>(),
|
||||
Array.Empty<float>(),
|
||||
Array.Empty<MergedSpectrumSegment>());
|
||||
|
||||
private sealed record NormalizedFrame(
|
||||
int DeviceIndex,
|
||||
string SerialNumber,
|
||||
float[] Wavelengths,
|
||||
float[] Spectrum,
|
||||
double Start,
|
||||
double End);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 多台同步采集时,某一台设备返回的一帧光谱。
|
||||
/// 流式回调不携带报文头,因此这里没有温度/负载率等元数据;
|
||||
/// 需要这些字段请使用单帧 <c>AcquireFrame</c> 接口。
|
||||
/// </summary>
|
||||
/// <param name="DeviceIndex">设备索引(0 起)。</param>
|
||||
/// <param name="SerialNumber">设备序列号。</param>
|
||||
/// <param name="Wavelengths">波长数组。</param>
|
||||
/// <param name="Spectrum">强度数组,与波长等长。</param>
|
||||
/// <param name="ReceivedAt">回调在本机收到该帧的时间。</param>
|
||||
public sealed record SynchronizedSpectrumFrame(
|
||||
int DeviceIndex,
|
||||
string SerialNumber,
|
||||
float[] Wavelengths,
|
||||
float[] Spectrum,
|
||||
DateTimeOffset ReceivedAt)
|
||||
{
|
||||
public int PixelCount => Wavelengths.Length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 多台光谱仪同步采集参数。一次调用会采集所有已连接设备各一帧。
|
||||
/// 为 null 的字段使用 <see cref="ArisSpectrometerOptions"/> 中的默认值。
|
||||
/// </summary>
|
||||
public sealed record SynchronizedSpectrumRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 曝光时间,单位微秒,必须大于 0。
|
||||
/// 为 null 时使用配置中的 <see cref="ArisSpectrometerOptions.SynchronizedExposureUs"/>。
|
||||
/// </summary>
|
||||
public int? ExposureUs { get; init; }
|
||||
|
||||
/// <summary>平均次数,必须大于等于 1。</summary>
|
||||
public int? Averaging { get; init; }
|
||||
|
||||
/// <summary>触发延迟,单位微秒,必须大于等于 0。</summary>
|
||||
public int? DelayUs { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// StartMeasurement 返回后,等待所有设备回调的最长时间(毫秒)。
|
||||
/// 小于等于 0 时使用配置中的 <see cref="ArisSpectrometerOptions.SynchronizedWaitTimeoutMs"/>。
|
||||
/// </summary>
|
||||
public int? WaitTimeoutMs { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace HardwareControl.Core.Spectrometer
|
||||
{
|
||||
/// <summary>
|
||||
/// 多台光谱仪同步采集的结果:每台设备一帧原始光谱,外加按波长拼接后的完整光谱。
|
||||
/// </summary>
|
||||
/// <param name="Frames">实际收到的设备帧,按序列号排序。</param>
|
||||
/// <param name="Merged">拼接后的光谱。</param>
|
||||
/// <param name="MissingSerials">超时未收到帧的序列号。</param>
|
||||
/// <param name="Errors">测量过程中 SDK 上报的设备错误。</param>
|
||||
/// <param name="ExpectedDeviceCount">本次期望采集的设备数。</param>
|
||||
/// <param name="AcquiredAt">采集完成的主机本地时间。</param>
|
||||
/// <param name="StartElapsed">StartMeasurement 武装设备所耗时间。</param>
|
||||
/// <param name="WaitElapsed">等待设备回调所耗时间。</param>
|
||||
public sealed record SynchronizedSpectrumResult(
|
||||
IReadOnlyList<SynchronizedSpectrumFrame> Frames,
|
||||
MergedSpectrum Merged,
|
||||
IReadOnlyList<string> MissingSerials,
|
||||
IReadOnlyList<SpectrumDeviceError> Errors,
|
||||
int ExpectedDeviceCount,
|
||||
DateTimeOffset AcquiredAt,
|
||||
TimeSpan StartElapsed,
|
||||
TimeSpan WaitElapsed)
|
||||
{
|
||||
/// <summary>所有设备都返回了帧(允许存在已收到帧的设备的告警)。</summary>
|
||||
public bool IsComplete => MissingSerials.Count == 0;
|
||||
|
||||
public int ReceivedDeviceCount => Frames.Count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using FlashCap;
|
||||
|
||||
namespace HardwareControl.Core.UsbCamera
|
||||
{
|
||||
/// <summary>
|
||||
/// 当前采集格式。前端用它选择正确的 data URL MIME,
|
||||
/// MJPG/PNG 帧可直接显示,YUV 等格式由 FlashCap 转码为 BMP。
|
||||
/// </summary>
|
||||
public sealed record CameraFrameFormat(
|
||||
int Width,
|
||||
int Height,
|
||||
string PixelFormat,
|
||||
double FramesPerSecond,
|
||||
string MimeType)
|
||||
{
|
||||
public bool IsCompressed => MimeType is "image/jpeg" or "image/png";
|
||||
|
||||
public static string ResolveMimeType(PixelFormats pixelFormat) =>
|
||||
pixelFormat switch
|
||||
{
|
||||
PixelFormats.JPEG => "image/jpeg",
|
||||
PixelFormats.PNG => "image/png",
|
||||
_ => "image/bmp",
|
||||
};
|
||||
|
||||
public static CameraFrameFormat From(VideoCharacteristics characteristics) =>
|
||||
new(
|
||||
characteristics.Width,
|
||||
characteristics.Height,
|
||||
characteristics.PixelFormat.ToString(),
|
||||
(double)characteristics.FramesPerSecond,
|
||||
ResolveMimeType(characteristics.PixelFormat));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
namespace HardwareControl.Core.UsbCamera
|
||||
{
|
||||
/// <summary>
|
||||
/// 一帧图像。ImageData 由 <c>CopyImage()</c> 生成,
|
||||
/// 调用方可以安全地在回调返回后继续持有、排队或异步发送。
|
||||
/// </summary>
|
||||
public class FrameArrivedEventArgs : EventArgs
|
||||
{
|
||||
public byte[] ImageData { get; }
|
||||
public long FrameIndex { get; }
|
||||
public TimeSpan Timestamp { get; }
|
||||
public DateTimeOffset CapturedAt { get; }
|
||||
|
||||
/// <summary>采集格式与 MIME 类型,随帧一起传递。</summary>
|
||||
public CameraFrameFormat Format { get; }
|
||||
|
||||
public string MimeType => Format.MimeType;
|
||||
public int Width => Format.Width;
|
||||
public int Height => Format.Height;
|
||||
|
||||
public FrameArrivedEventArgs(
|
||||
byte[] imageData,
|
||||
long frameIndex,
|
||||
TimeSpan timestamp,
|
||||
DateTimeOffset capturedAt,
|
||||
CameraFrameFormat format)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(imageData);
|
||||
ArgumentNullException.ThrowIfNull(format);
|
||||
|
||||
ImageData = imageData;
|
||||
FrameIndex = frameIndex;
|
||||
Timestamp = timestamp;
|
||||
CapturedAt = capturedAt;
|
||||
Format = format;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace HardwareControl.Core.UsbCamera
|
||||
{
|
||||
/// <summary>
|
||||
/// Usb相机操作类
|
||||
/// </summary>
|
||||
public class UsbCameraOptions
|
||||
{
|
||||
// 设备名称关键词,null 表示取第一个设备
|
||||
public string? DeviceNameKeyword { get; set; }
|
||||
|
||||
// 优先使用的格式关键词,例如 "MJPG" 或 "640x480"
|
||||
// 为 null 时取该设备的第一个格式
|
||||
public string? PreferredFormatKeyword { get; set; }
|
||||
|
||||
// 重连基础间隔,单位毫秒
|
||||
public int ReconnectBaseDelayMs { get; set; } = 1000;
|
||||
|
||||
// 重连最大间隔,单位毫秒
|
||||
public int ReconnectMaxDelayMs { get; set; } = 10_000;
|
||||
|
||||
// 抓帧超时,单位毫秒
|
||||
public int FrameTimeoutMs { get; set; } = 5000;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace HardwareControl.Core.UsbCamera
|
||||
{
|
||||
public class UsbCameraStatusChangedEventArgs : EventArgs
|
||||
{
|
||||
public bool IsConnected { get; }
|
||||
public string Message { get; }
|
||||
|
||||
public UsbCameraStatusChangedEventArgs(bool isConnected, string message)
|
||||
{
|
||||
IsConnected = isConnected;
|
||||
Message = message;
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user