提交代码

This commit is contained in:
ldh
2026-11-19 16:42:26 +08:00
parent dd6edce089
commit 4929d5dcd5
209 changed files with 158631 additions and 1311 deletions
@@ -1,5 +1,3 @@
using Aris;
namespace HardwareControl.Core.Spectrometer
{
/// <summary>
@@ -30,41 +28,34 @@ namespace HardwareControl.Core.Spectrometer
public int DelayUs { get; set; }
/// <summary>
/// 单帧采集默认超时,单位毫秒;小于等于 0 时由 SDK 按
/// 单帧采集默认超时,单位毫秒;小于等于 0 时按
/// <c>max(3000, 曝光/1000 + 2000)</c> 计算。
/// </summary>
public int TimeoutMs { get; set; }
/// <summary>
/// 多台同步采集的默认曝光时间,单位微秒。
/// SDK 逐台武装设备,第三台通常比前两台晚约 0.6 秒启动;
/// 曝光窗口必须覆盖这段武装时间,否则前两台会在第三台触发激光前结束。
/// 默认 1 秒,可按现场时序下调,但建议不低于 0.7 秒。
/// 参数在连接时预配置,采集时三台设备只发启动命令(间隔约 1 ms),
/// 因此 100 ms 曝光即可覆盖全部设备,不再需要覆盖“逐台武装”的长曝光窗口。
/// </summary>
public int SynchronizedExposureUs { get; set; } = 1_000_000;
public int SynchronizedExposureUs { get; set; } = 100_000;
/// <summary>
/// 多台同步采集时,StartMeasurement 返回后等待所有设备回调的默认最长时间(毫秒)。
/// 多台同步采集时,启动后等待所有设备出帧的默认最长时间(毫秒)。
/// </summary>
public int SynchronizedWaitTimeoutMs { get; set; } = 8000;
/// <summary>
/// 连接成功后设置的触发模式;为 null 时保持设备当前配置。
/// 手册要求触发模式只在连接后设置一次。
/// 默认 <see cref="Aris.TriggerMode.Software"/>:纯自由运行。
/// 默认 <see cref="SpectrometerTriggerMode.Software"/>:自由运行。
/// 由第三台设备触发激光、其余设备自由收光的场景使用 Software;
/// 有外部 AD/TTL 触发源时改为 FreeRunEdge 或 External。
/// 有外部 AD/TTL 触发源时改为 External;FreeRunEdge 对应自由运行的开始触发脉冲。
/// </summary>
public TriggerMode? TriggerMode { get; set; } = Aris.TriggerMode.Software;
public SpectrometerTriggerMode? TriggerMode { get; set; } = SpectrometerTriggerMode.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>
/// Aris 光谱仪的触发模式。
/// 名称与 aris C API 保持一致,appsettings.json 仍可直接写 "Software" / "External" / "FreeRunEdge"。
/// </summary>
public enum SpectrometerTriggerMode
{
/// <summary>自由运行,内部定时启动曝光(对应设备 FreeRunningTriggerEnd)。</summary>
Software = 0,
/// <summary>硬件触发:等待 Trigger In 上升沿(对应设备 HardwareTrigger)。</summary>
External = 1,
/// <summary>自由运行,开始时输出触发脉冲(对应设备 FreeRunningTriggerStart)。</summary>
FreeRunEdge = 2,
}
}
@@ -9,8 +9,8 @@ namespace HardwareControl.Core.Spectrometer
/// <param name="Errors">测量过程中 SDK 上报的设备错误。</param>
/// <param name="ExpectedDeviceCount">本次期望采集的设备数。</param>
/// <param name="AcquiredAt">采集完成的主机本地时间。</param>
/// <param name="StartElapsed">StartMeasurement 武装设备所耗时间。</param>
/// <param name="WaitElapsed">等待设备回调所耗时间。</param>
/// <param name="StartElapsed">预配置参数并向所有设备发送启动命令所耗时间。</param>
/// <param name="WaitElapsed">等待所有设备出帧所耗时间。</param>
public sealed record SynchronizedSpectrumResult(
IReadOnlyList<SynchronizedSpectrumFrame> Frames,
MergedSpectrum Merged,
@@ -0,0 +1,465 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace HardwareControl.Core.Spectrometer.ZioLink
{
/// <summary>
/// Aris 光谱仪的 WinUSB 连接(与官方 Inspective 使用同一驱动与接口 GUID)。
/// 只负责 USB 管道读写,协议层见 <see cref="ZioLinkDevice"/>。
/// </summary>
internal sealed class WinUsbConnection : IDisposable
{
// GUID_DEVINTERFACE_USB_DEVICE,官方软件用它枚举全部 USB 设备后再按 VID/PID 过滤
private static readonly Guid UsbDeviceInterfaceGuid =
new Guid("a5dcbf10-6530-11d2-901f-00c04fb951ed");
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const uint FILE_SHARE_READ = 1;
private const uint FILE_SHARE_WRITE = 2;
private const uint OPEN_EXISTING = 3;
private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
private const uint FILE_FLAG_OVERLAPPED = 0x40000000;
private const int DIGCF_PRESENT = 0x02;
private const int DIGCF_DEVICEINTERFACE = 0x10;
private const uint POLICY_SHORT_PACKET_TERMINATE = 1;
private const uint POLICY_PIPE_TRANSFER_TIMEOUT = 3;
private readonly string _devicePath;
private SafeFileHandle? _deviceHandle;
private IntPtr _winUsbHandle;
private byte _inPipe;
private byte _outPipe;
public string DevicePath => _devicePath;
public string Manufacturer { get; private set; } = string.Empty;
public string Product { get; private set; } = string.Empty;
public string SerialNumber { get; private set; } = string.Empty;
public bool IsOpen => _winUsbHandle != IntPtr.Zero;
private WinUsbConnection(string devicePath)
{
_devicePath = devicePath;
}
/// <summary>枚举所有 Avenir 光谱仪的 WinUSB 接口路径。</summary>
public static string[] FindDevicePaths()
{
var results = new List<string>();
var guid = UsbDeviceInterfaceGuid;
var deviceInfoSet = SetupDiGetClassDevs(
ref guid, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (deviceInfoSet == IntPtr.Zero || deviceInfoSet == new IntPtr(-1))
{
return Array.Empty<string>();
}
try
{
var interfaceData = new SpDeviceInterfaceData
{
cbSize = Marshal.SizeOf<SpDeviceInterfaceData>(),
};
for (uint index = 0;
SetupDiEnumDeviceInterfaces(
deviceInfoSet, IntPtr.Zero, ref guid, index, ref interfaceData);
index++)
{
SetupDiGetDeviceInterfaceDetail(
deviceInfoSet, ref interfaceData, IntPtr.Zero, 0, out var requiredSize, IntPtr.Zero);
if (requiredSize <= 0)
{
continue;
}
var detail = Marshal.AllocHGlobal(requiredSize);
try
{
// x64: 8;x86: 4 + sizeof(WCHAR)
Marshal.WriteInt32(detail, IntPtr.Size == 8 ? 8 : 6);
if (!SetupDiGetDeviceInterfaceDetail(
deviceInfoSet, ref interfaceData, detail, requiredSize, out _, IntPtr.Zero))
{
continue;
}
var path = Marshal.PtrToStringUni(IntPtr.Add(detail, 4));
if (string.IsNullOrWhiteSpace(path))
{
continue;
}
// 官方软件同样按 vid_354f&pid_01 过滤,并排除 DFU 接口 pid_0103
if (path.Contains("vid_354f&pid_01", StringComparison.OrdinalIgnoreCase)
&& !path.Contains("pid_0103", StringComparison.OrdinalIgnoreCase))
{
results.Add(path);
}
}
finally
{
Marshal.FreeHGlobal(detail);
}
}
}
finally
{
SetupDiDestroyDeviceInfoList(deviceInfoSet);
}
results.Sort(StringComparer.OrdinalIgnoreCase);
return results.ToArray();
}
public static WinUsbConnection Open(
string devicePath,
uint readTimeoutMs = 2000,
uint writeTimeoutMs = 500)
{
var connection = new WinUsbConnection(devicePath);
try
{
connection.OpenCore(readTimeoutMs, writeTimeoutMs);
return connection;
}
catch
{
connection.Dispose();
throw;
}
}
private void OpenCore(uint readTimeoutMs, uint writeTimeoutMs)
{
_deviceHandle = CreateFile(
_devicePath,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
IntPtr.Zero,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
IntPtr.Zero);
if (_deviceHandle.IsInvalid)
{
var error = Marshal.GetLastWin32Error();
throw new ZioLinkException(
0,
$"无法打开光谱仪 {_devicePath}(Win32 错误 {error})。"
+ "设备可能正被 Inspective 或其他程序占用。");
}
if (!WinUsb_Initialize(_deviceHandle, out _winUsbHandle) || _winUsbHandle == IntPtr.Zero)
{
var error = Marshal.GetLastWin32Error();
throw new ZioLinkException(0, $"初始化 WinUSB 失败(Win32 错误 {error})");
}
UsbInterfaceDescriptor interfaceDescriptor = default;
if (!WinUsb_QueryInterfaceSettings(_winUsbHandle, 0, ref interfaceDescriptor))
{
throw new ZioLinkException(0, "读取 WinUSB 接口描述符失败");
}
for (var i = 0; i < interfaceDescriptor.bNumEndpoints; i++)
{
var pipe = default(WinUsbPipeInformation);
if (!WinUsb_QueryPipe(_winUsbHandle, 0, (byte)i, ref pipe))
{
throw new ZioLinkException(0, "查询 WinUSB 管道失败");
}
if ((pipe.PipeId & 0x80) != 0)
{
_inPipe = pipe.PipeId;
SetTimeout(pipe.PipeId, readTimeoutMs);
}
else
{
_outPipe = pipe.PipeId;
SetTimeout(pipe.PipeId, writeTimeoutMs);
var enable = 1u;
WinUsb_SetPipePolicy(
_winUsbHandle, pipe.PipeId, POLICY_SHORT_PACKET_TERMINATE, sizeof(uint), ref enable);
}
}
if (_inPipe == 0 || _outPipe == 0)
{
throw new ZioLinkException(0, "未找到光谱仪的 USB 批量端点");
}
// 用设备描述符里的 iManufacturer / iProduct / iSerialNumber 读取字符串
var languageId = ReadLanguageId();
var deviceDescriptor = ReadDeviceDescriptor();
Manufacturer = ReadStringDescriptor(deviceDescriptor.iManufacturer, languageId);
Product = ReadStringDescriptor(deviceDescriptor.iProduct, languageId);
SerialNumber = ReadStringDescriptor(deviceDescriptor.iSerialNumber, languageId);
if (string.IsNullOrWhiteSpace(SerialNumber))
{
SerialNumber = Path.GetFileNameWithoutExtension(_devicePath);
}
}
private void SetTimeout(byte pipeId, uint timeoutMs)
{
var value = timeoutMs;
WinUsb_SetPipePolicy(
_winUsbHandle, pipeId, POLICY_PIPE_TRANSFER_TIMEOUT, sizeof(uint), ref value);
}
public void Write(byte[] buffer, int count)
{
ThrowIfClosed();
if (!WinUsb_WritePipe(
_winUsbHandle, _outPipe, buffer, (uint)count, out _, IntPtr.Zero))
{
var error = Marshal.GetLastWin32Error();
throw new ZioLinkException(0, $"USB 写入失败(Win32 错误 {error})");
}
}
public int Read(byte[] buffer, int count)
{
ThrowIfClosed();
if (!WinUsb_ReadPipe(
_winUsbHandle, _inPipe, buffer, (uint)count, out var transferred, IntPtr.Zero))
{
var error = Marshal.GetLastWin32Error();
if (error == 121)
{
throw new ZioLinkException(0, "USB 读取超时,设备未响应");
}
throw new ZioLinkException(0, $"USB 读取失败(Win32 错误 {error})");
}
return (int)transferred;
}
private void ThrowIfClosed()
{
if (!IsOpen)
{
throw new ZioLinkException(0, "USB 连接已关闭");
}
}
private UsbDeviceDescriptor ReadDeviceDescriptor()
{
var buffer = new byte[Marshal.SizeOf<UsbDeviceDescriptor>()];
if (!WinUsb_GetDescriptor(
_winUsbHandle, 1, 0, 0, buffer, (uint)buffer.Length, out _))
{
throw new ZioLinkException(0, "读取 USB 设备描述符失败");
}
return MemoryMarshal.Read<UsbDeviceDescriptor>(buffer);
}
private ushort ReadLanguageId()
{
var buffer = new byte[256];
if (!WinUsb_GetDescriptor(
_winUsbHandle, 3, 0, 0, buffer, (uint)buffer.Length, out _))
{
return 0x0409;
}
var length = buffer[0] - 2;
if (length >= 2)
{
return BitConverter.ToUInt16(buffer, 2);
}
return 0x0409;
}
private string ReadStringDescriptor(byte index, ushort languageId)
{
if (index == 0)
{
return string.Empty;
}
var buffer = new byte[256];
if (!WinUsb_GetDescriptor(
_winUsbHandle, 3, index, languageId, buffer, (uint)buffer.Length, out _))
{
return string.Empty;
}
var length = buffer[0] - 2;
if (length <= 0)
{
return string.Empty;
}
return System.Text.Encoding.Unicode.GetString(buffer, 2, length).Trim();
}
public void Dispose()
{
if (_winUsbHandle != IntPtr.Zero)
{
WinUsb_Free(_winUsbHandle);
_winUsbHandle = IntPtr.Zero;
}
_deviceHandle?.Dispose();
_deviceHandle = null;
}
// ---------------- P/Invoke ----------------
[StructLayout(LayoutKind.Sequential)]
private struct SpDeviceInterfaceData
{
public int cbSize;
public Guid InterfaceClassGuid;
public int Flags;
public IntPtr Reserved;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct UsbDeviceDescriptor
{
public byte bLength;
public byte bDescriptorType;
public ushort bcdUSB;
public byte bDeviceClass;
public byte bDeviceSubClass;
public byte bDeviceProtocol;
public byte bMaxPacketSize0;
public ushort idVendor;
public ushort idProduct;
public ushort bcdDevice;
public byte iManufacturer;
public byte iProduct;
public byte iSerialNumber;
public byte bNumConfigurations;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct UsbInterfaceDescriptor
{
public byte bLength;
public byte bDescriptorType;
public byte bInterfaceNumber;
public byte bAlternateSetting;
public byte bNumEndpoints;
public byte bInterfaceClass;
public byte bInterfaceSubClass;
public byte bInterfaceProtocol;
public byte iInterface;
}
[StructLayout(LayoutKind.Sequential)]
private struct WinUsbPipeInformation
{
public int PipeType;
public byte PipeId;
public ushort MaximumPacketSize;
public byte Interval;
}
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(
ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, int flags);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInterfaces(
IntPtr deviceInfoSet,
IntPtr deviceInfoData,
ref Guid interfaceClassGuid,
uint memberIndex,
ref SpDeviceInterfaceData deviceInterfaceData);
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool SetupDiGetDeviceInterfaceDetail(
IntPtr deviceInfoSet,
ref SpDeviceInterfaceData deviceInterfaceData,
IntPtr deviceInterfaceDetailData,
int deviceInterfaceDetailDataSize,
out int requiredSize,
IntPtr deviceInfoData);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateFile(
string fileName,
uint desiredAccess,
uint shareMode,
IntPtr securityAttributes,
uint creationDisposition,
uint flagsAndAttributes,
IntPtr templateFile);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_Initialize(SafeFileHandle deviceHandle, out IntPtr interfaceHandle);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_Free(IntPtr interfaceHandle);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_QueryInterfaceSettings(
IntPtr interfaceHandle, byte alternateInterfaceNumber, ref UsbInterfaceDescriptor descriptor);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_QueryPipe(
IntPtr interfaceHandle,
byte alternateInterfaceNumber,
byte pipeIndex,
ref WinUsbPipeInformation pipeInformation);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_SetPipePolicy(
IntPtr interfaceHandle, byte pipeId, uint policyType, uint valueLength, ref uint value);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_WritePipe(
IntPtr interfaceHandle,
byte pipeId,
byte[] buffer,
uint bufferLength,
out uint lengthTransferred,
IntPtr overlapped);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_ReadPipe(
IntPtr interfaceHandle,
byte pipeId,
byte[] buffer,
uint bufferLength,
out uint lengthTransferred,
IntPtr overlapped);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_GetDescriptor(
IntPtr interfaceHandle,
byte descriptorType,
byte index,
ushort languageId,
byte[] buffer,
uint bufferLength,
out uint lengthTransferred);
}
}
@@ -0,0 +1,542 @@
using System;
using System.Text;
namespace HardwareControl.Core.Spectrometer.ZioLink
{
/// <summary>
/// Aris 光谱仪的 ZioLink 协议实现(与官方 Inspective 的 DeviceClasses.ZioLinkSpectrometer 一致)。
///
/// 与 aris.dll 的高层 StartMeasurement 不同,这里把“配置”和“启动”彻底分开:
/// * <see cref="ApplyParameters"/> 只在参数变化时下发一次(cmd 0x1100/0x1101/0x1105);
/// * <see cref="StartExposure"/> 只发 cmd 4(8 字节 USB 往返),设备收到后立即开始积分,
/// 主机不需要等待曝光结束;
/// * 多台设备依次调用 StartExposure 的间隔就是 USB 往返时间(约 1 ms/台),
/// 因此 100 ms 曝光可以覆盖全部设备。
/// </summary>
internal sealed class ZioLinkDevice : IDisposable
{
private const int MaxReplyLength = 16492;
private const int SpectrumHeaderOffset = 4;
private const int SpectrumValuesOffset = 68;
private const int CmdReset = 0;
private const int CmdStandBy = 1;
private const int CmdStartExposure = 4;
private const int CmdCancelExposure = 5;
private const int CmdGetExposureTime = 4096;
private const int CmdSetExposureTime = 4352;
private const int CmdGetAveraging = 4097;
private const int CmdSetAveraging = 4353;
private const int CmdGetSensorGain = 4109;
private const int CmdSetSensorGain = 4365;
private const int CmdGetMaxSensorGain = 4877;
private const int CmdGetMinExposureTime = 4608;
private const int CmdGetMaxExposureTime = 4864;
private const int CmdGetMaxAveraging = 4865;
private const int CmdGetTriggerInConfiguration = 4100;
private const int CmdSetTriggerInConfiguration = 4356;
private const int CmdGetTriggerInDelay = 4101;
private const int CmdSetTriggerInDelay = 4357;
private const int CmdGetStartPixel = 8201;
private const int CmdGetEndPixel = 8202;
private const int CmdGetSerialNumber = 8193;
private const int CmdGetManufacturer = 8194;
private const int CmdGetModelName = 8195;
private const int CmdGetSoftwareVersion = 8197;
private const int CmdGetPixelCount = 8199;
private const int CmdGetStatus = 12288;
private const int CmdGetSpectrum = 16384;
private const int CmdSetDateTime = 16645;
private const int CmdGetWavelengthCoefficient0 = 8220;
private static readonly Version MinFirmwareNewTriggering = new Version(4, 1, 7, 0);
private static readonly Version MinFirmwareDateTime = new Version(4, 0, 7, 1);
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);
private readonly WinUsbConnection _connection;
private readonly byte[] _reply = new byte[MaxReplyLength];
private bool _disposed;
public ZioLinkDevice(WinUsbConnection connection)
{
_connection = connection;
}
public string DevicePath => _connection.DevicePath;
public string SerialNumber { get; private set; } = string.Empty;
public string Manufacturer { get; private set; } = string.Empty;
public string ModelName { get; private set; } = string.Empty;
public Version FirmwareVersion { get; private set; } = new Version(0, 0);
public int PixelCount { get; private set; }
public float[] Wavelengths { get; private set; } = Array.Empty<float>();
public int StartPixel { get; private set; }
public int EndPixel { get; private set; }
public int MinExposureUs { get; private set; }
public int MaxExposureUs { get; private set; }
public int MaxAveraging { get; private set; }
public int MaxSensorGain { get; private set; }
public int SensorGain { get; private set; }
public int TriggerConfiguration { get; private set; }
/// <summary>最近一次成功下发的曝光时间(微秒)。</summary>
public int ExposureTimeUs { get; private set; }
/// <summary>最近一次成功下发的平均次数。</summary>
public int Averaging { get; private set; } = 1;
/// <summary>最近一次成功下发的触发延迟(微秒)。</summary>
public int DelayUs { get; private set; }
public void Open()
{
ThrowIfDisposed();
// 官方 Open 流程:先复位,再读取全部静态参数
WriteCommand(CmdReset);
FirmwareVersion = ReadVersion(CmdGetSoftwareVersion);
SerialNumber = ReadStringOrFallback(CmdGetSerialNumber, _connection.SerialNumber);
Manufacturer = ReadStringOrFallback(CmdGetManufacturer, _connection.Manufacturer);
ModelName = ReadStringOrFallback(CmdGetModelName, _connection.Product);
PixelCount = ReadInt(CmdGetPixelCount);
if (PixelCount <= 0)
{
throw new ZioLinkException(0, $"设备返回的像素数无效({PixelCount})");
}
var coefficients = new float[4];
for (var i = 0; i < coefficients.Length; i++)
{
coefficients[i] = ReadFloat(CmdGetWavelengthCoefficient0 + i);
}
Wavelengths = BuildWavelengths(coefficients, PixelCount);
MinExposureUs = ReadInt(CmdGetMinExposureTime);
MaxExposureUs = ReadInt(CmdGetMaxExposureTime);
MaxAveraging = ReadInt(CmdGetMaxAveraging);
ExposureTimeUs = ReadInt(CmdGetExposureTime);
Averaging = ReadInt(CmdGetAveraging);
MaxSensorGain = TryReadInt(CmdGetMaxSensorGain, 0);
SensorGain = TryReadInt(CmdGetSensorGain, 0);
TriggerConfiguration = ReadInt(CmdGetTriggerInConfiguration);
DelayUs = TryReadInt(CmdGetTriggerInDelay, 0);
StartPixel = TryReadInt(CmdGetStartPixel, 0);
EndPixel = TryReadInt(CmdGetEndPixel, 0);
}
/// <summary>
/// 把设备 RTC 同步到主机时间。三台设备应在同一时刻集中调用,
/// 否则帧头时间戳会出现固定偏移,影响启动偏差的诊断。
/// </summary>
public bool SynchronizeTime()
{
ThrowIfDisposed();
if (FirmwareVersion < MinFirmwareDateTime)
{
return true;
}
for (var attempt = 0; attempt < 3; attempt++)
{
try
{
UpdateDeviceTime();
return true;
}
catch (ZioLinkException)
{
Thread.Sleep(20);
}
}
return false;
}
/// <summary>
/// 预配置:只有参数变化时才发命令。官方软件在用户修改曝光/平均时才调用同样的命令,
/// 启动阶段不会重复下发。
/// </summary>
public void ApplyParameters(int exposureUs, int averaging, int delayUs)
{
ThrowIfDisposed();
if (delayUs != DelayUs)
{
WriteInt(CmdSetTriggerInDelay, delayUs);
DelayUs = delayUs;
}
if (averaging != Averaging)
{
WriteInt(CmdSetAveraging, averaging);
Averaging = averaging;
}
if (exposureUs != ExposureTimeUs)
{
WriteInt(CmdSetExposureTime, exposureUs);
ExposureTimeUs = exposureUs;
}
}
public void SetTriggerMode(SpectrometerTriggerMode mode)
{
ThrowIfDisposed();
int modeValue;
if (FirmwareVersion >= MinFirmwareNewTriggering)
{
modeValue = mode switch
{
SpectrometerTriggerMode.Software => 0,
SpectrometerTriggerMode.FreeRunEdge => 1,
SpectrometerTriggerMode.External => 2,
_ => throw new ZioLinkException(0, $"不支持的触发模式:{mode}"),
};
}
else
{
// 旧固件只区分“自由运行”和“硬件触发”
modeValue = mode == SpectrometerTriggerMode.External ? 6 : 0;
}
var value = (TriggerConfiguration & ~0xFF) | modeValue;
WriteInt(CmdSetTriggerInConfiguration, value);
TriggerConfiguration = value;
}
public void SetGain(int gain)
{
ThrowIfDisposed();
WriteInt(CmdSetSensorGain, gain);
SensorGain = gain;
}
/// <summary>只发启动命令;设备收到后立即在固件内开始积分。</summary>
public void StartExposure(int numSpectra)
{
ThrowIfDisposed();
WriteInt(CmdStartExposure, numSpectra);
}
public void CancelExposure()
{
ThrowIfDisposed();
WriteCommand(CmdCancelExposure);
}
public ZioLinkDeviceStatus GetStatus(out int availableSpectra)
{
ThrowIfDisposed();
var value = ReadInt(CmdGetStatus);
availableSpectra = (value >> 8) & 0xFFFF;
var state = value & 0xFF;
return state switch
{
0 => ZioLinkDeviceStatus.Idle,
1 => ZioLinkDeviceStatus.WaitingForTrigger,
2 => ZioLinkDeviceStatus.TakingSpectrum,
3 => ZioLinkDeviceStatus.WaitingForTemperature,
8 => ZioLinkDeviceStatus.PoweredOff,
9 => ZioLinkDeviceStatus.SleepMode,
10 => ZioLinkDeviceStatus.NotConnected,
_ => ZioLinkDeviceStatus.Unknown,
};
}
/// <summary>丢弃设备里残留的旧帧(例如上一次采集超时后留下的数据)。</summary>
public int DrainPendingSpectra(int maxFrames = 8)
{
var drained = 0;
while (drained < maxFrames)
{
GetStatus(out var available);
if (available <= 0)
{
break;
}
ReadSpectrum();
drained++;
}
return drained;
}
public ZioLinkSpectrum ReadSpectrum()
{
ThrowIfDisposed();
var length = ReadBulk(CmdGetSpectrum);
if (length < SpectrumValuesOffset)
{
throw new ZioLinkException(0, $"收到的光谱只有 {length} 字节");
}
var header = SpectrumHeaderOffset;
var pixelCount = BitConverter.ToUInt16(_reply, header + 24);
if (pixelCount != PixelCount)
{
throw new ZioLinkException(0, $"收到的光谱像素数 {pixelCount} 与设备像素数 {PixelCount} 不一致");
}
var dataFormat = _reply[header + 26];
if (dataFormat != 0)
{
throw new ZioLinkException(0, $"不支持的光谱数据格式 {dataFormat}");
}
var expected = SpectrumValuesOffset + pixelCount * sizeof(float);
if (length != expected)
{
throw new ZioLinkException(0, $"光谱长度 {length} 与期望值 {expected} 不一致");
}
var values = new float[pixelCount];
Buffer.BlockCopy(_reply, SpectrumValuesOffset, values, 0, pixelCount * sizeof(float));
var exposureSettings = BitConverter.ToUInt16(_reply, header + 28);
var appliedProcessing = BitConverter.ToUInt16(_reply, header + 30);
return new ZioLinkSpectrum(
BitConverter.ToUInt32(_reply, header + 0),
BitConverter.ToUInt32(_reply, header + 4),
BitConverter.ToUInt32(_reply, header + 8),
BitConverter.ToUInt32(_reply, header + 12),
BitConverter.ToSingle(_reply, header + 16),
BitConverter.ToSingle(_reply, header + 20),
pixelCount,
dataFormat,
exposureSettings,
appliedProcessing,
BitConverter.ToSingle(_reply, header + 56),
BitConverter.ToSingle(_reply, header + 60),
values);
}
private void UpdateDeviceTime()
{
if (FirmwareVersion < MinFirmwareDateTime)
{
return;
}
var now = DateTime.Now;
var time = (int)(now.TimeOfDay.TotalMilliseconds * 10.0);
var days = (int)(now.Date - UnixEpoch).TotalDays;
WriteTwoInts(CmdSetDateTime, time, days);
}
private static float[] BuildWavelengths(float[] coefficients, int pixelCount)
{
var wavelengths = new float[pixelCount];
for (var i = 0; i < pixelCount; i++)
{
wavelengths[i] = coefficients[0]
+ (coefficients[1] + (coefficients[2] + coefficients[3] * i) * i) * i;
}
return wavelengths;
}
private void WriteCommand(int cmd)
{
var message = new byte[4];
CopyInt(message, cmd, 0);
SendReceive(message);
}
private void WriteInt(int cmd, int value)
{
var message = new byte[8];
CopyInt(message, cmd, 0);
CopyInt(message, value, 4);
SendReceive(message);
}
private void WriteTwoInts(int cmd, int value1, int value2)
{
var message = new byte[12];
CopyInt(message, cmd, 0);
CopyInt(message, value1, 4);
CopyInt(message, value2, 8);
SendReceive(message);
}
private int ReadInt(int cmd)
{
WriteCommand(cmd);
return BitConverter.ToInt32(_reply, 4);
}
private int TryReadInt(int cmd, int fallback)
{
try
{
return ReadInt(cmd);
}
catch (ZioLinkException)
{
return fallback;
}
}
private float ReadFloat(int cmd)
{
WriteCommand(cmd);
return BitConverter.ToSingle(_reply, 4);
}
private Version ReadVersion(int cmd)
{
WriteCommand(cmd);
return new Version(_reply[7], _reply[6], _reply[5], _reply[4]);
}
private string ReadStringOrFallback(int cmd, string fallback)
{
try
{
WriteCommand(cmd);
var end = Array.IndexOf(_reply, (byte)0, 4);
if (end < 0)
{
end = _reply.Length;
}
var value = Encoding.ASCII.GetString(_reply, 4, end - 4).Trim();
return string.IsNullOrWhiteSpace(value) ? fallback : value;
}
catch (ZioLinkException)
{
return fallback;
}
}
private int ReadBulk(int cmd)
{
WriteCommand(cmd);
return _replyLength;
}
private int _replyLength;
private int SendReceive(byte[] message)
{
_connection.Write(message, message.Length);
var length = _connection.Read(_reply, _reply.Length);
if (length < 4)
{
throw new ZioLinkException(0, $"设备回复长度不足({length} 字节)");
}
var status = BitConverter.ToInt32(_reply, 0);
var errorCode = status >> 8;
if (errorCode != 0)
{
throw new ZioLinkException(
errorCode,
BuildErrorMessage(errorCode, BitConverter.ToInt32(message, 0), status));
}
_replyLength = length;
return length;
}
private static string BuildErrorMessage(int errorCode, int command, int status)
{
var description = errorCode switch
{
1 => "设备不支持该命令",
2 => "设备参数无效",
4 => "设备当前状态不允许该操作(可能仍在测量中)",
5 => "设备不支持该操作",
6 => "操作密码错误",
7 => "通信错误",
8 => "设备内部错误",
10 => "无法读取设备存储(校验和错误或内容为空)",
11 => "光谱处理错误",
_ => "设备返回错误",
};
return $"{description}(cmd=0x{command:X4}, err=0x{status:X4})";
}
private static void CopyInt(byte[] buffer, int value, int offset)
{
buffer[offset] = (byte)value;
buffer[offset + 1] = (byte)(value >> 8);
buffer[offset + 2] = (byte)(value >> 16);
buffer[offset + 3] = (byte)(value >> 24);
}
private void ThrowIfDisposed()
{
ObjectDisposedException.ThrowIf(_disposed, this);
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_connection.Dispose();
}
}
internal enum ZioLinkDeviceStatus
{
Idle = 0,
WaitingForTrigger = 1,
TakingSpectrum = 2,
WaitingForTemperature = 3,
PoweredOff = 8,
SleepMode = 9,
NotConnected = 10,
Unknown = 255,
}
internal sealed record ZioLinkSpectrum(
uint ExposureTimeUs,
uint Averaging,
uint DeviceTime10Us,
uint DeviceDateDays,
float LoadLevel,
float SensorTemperature,
int PixelCount,
int DataFormat,
ushort ExposureSettings,
ushort AppliedProcessing,
float DarkAvg,
float ReadoutNoise,
float[] Values)
{
public int ErrorFlags => ExposureSettings >> 12;
public int IntensityUnit => AppliedProcessing & 0x0F;
public bool DarkSubtracted => (AppliedProcessing & 0x10) != 0;
}
}
@@ -0,0 +1,17 @@
using System;
namespace HardwareControl.Core.Spectrometer.ZioLink
{
/// <summary>ZioLink 协议或 USB 通信错误。</summary>
internal sealed class ZioLinkException : Exception
{
public ZioLinkException(int code, string message, Exception? innerException = null)
: base(message, innerException)
{
Code = code;
}
/// <summary>设备返回的错误码(报文头 status &gt;&gt; 8);0 表示 USB 层错误。</summary>
public int Code { get; }
}
}