466 lines
16 KiB
C#
466 lines
16 KiB
C#
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);
|
||
}
|
||
}
|