543 lines
18 KiB
C#
543 lines
18 KiB
C#
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;
|
||
}
|
||
}
|