/* ================================================================== * HidDevice.cs -- 纯 Win32 API 实现的 USB-HID 设备访问类 * 不依赖任何第三方 NuGet 包,仅用系统 hid.dll / kernel32.dll * 使用 Overlapped 异步读,保证 UI 轮询不阻塞 还需改动 :上位机配合的两处算法(务必对齐) ① 0x02 包的第 62 字节 = Crc8(前 62 字节),CRC8 参数:多项式 0x07、初值 0x00、输入输出不反转、结果不异或。 ② 0x03 包的第 2 字节 = 把所有规则共 12×N 字节按顺序逐字节相加,只取低 8 位(unsigned char 溢出自然回绕)。 注意顺序:上位机必须按 MCU 接收的顺序(包序号递增、包内规则顺序)累加,否则和 MCU 的 CkSum 对不上。 MCU 侧是从 RecvCnt 开始顺序递增的,所以上位机按"第 0 包第 0 条 → 第 0 包第 1 条 → … → 第 1 包第 0 条 → …"的顺序累加即可。 唯一需要上位机注意的:上位机自己的"重发"逻辑应以 MCU 应答里的 [1](RecvCnt)为准来算下一包序号,而不是自己计数,这样最稳。 请确认上位机是否按"应答[1] ÷ 5"来决定重发哪个包?如果是,逻辑完全自洽; * ================================================================== */ using System; using System.Runtime.InteropServices; namespace Ai8051U_PLC { public class HidDevice { [StructLayout(LayoutKind.Sequential)] private struct SP_DEVICE_INTERFACE_DATA { public int cbSize; public Guid InterfaceClassGuid; public int Flags; public IntPtr Reserved; } [StructLayout(LayoutKind.Sequential)] private struct HIDD_ATTRIBUTES { public int Size; public ushort VendorID; public ushort ProductID; public ushort VersionNumber; } [StructLayout(LayoutKind.Sequential)] private struct HIDP_CAPS { public ushort Usage; public ushort UsagePage; public ushort InputReportByteLength; public ushort OutputReportByteLength; public ushort FeatureReportByteLength; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)] public ushort[] Reserved; public ushort NumberLinkCollectionNodes; public ushort NumberInputButtonCaps; public ushort NumberInputValueCaps; public ushort NumberInputDataIndices; public ushort NumberOutputButtonCaps; public ushort NumberOutputValueCaps; public ushort NumberOutputDataIndices; public ushort NumberFeatureButtonCaps; public ushort NumberFeatureValueCaps; public ushort NumberFeatureDataIndices; } private const int DIGCF_PRESENT = 0x02; private const int DIGCF_DEVICEINTERFACE = 0x10; private const uint GENERIC_READ = 0x80000000; private const uint GENERIC_WRITE = 0x40000000; private const uint FILE_SHARE_READ = 0x01; private const uint FILE_SHARE_WRITE = 0x02; private const uint OPEN_EXISTING = 3; private const uint FILE_FLAG_OVERLAPPED = 0x40000000; private const int HIDP_STATUS_SUCCESS = 0x00110000; private const int WAIT_TIMEOUT = 0x102; [DllImport("hid.dll")] private static extern void HidD_GetHidGuid(out Guid guid); [DllImport("hid.dll")] private static extern bool HidD_GetAttributes(IntPtr h, ref HIDD_ATTRIBUTES attr); [DllImport("hid.dll")] private static extern bool HidD_GetPreparsedData(IntPtr h, out IntPtr pp); [DllImport("hid.dll")] private static extern bool HidD_FreePreparsedData(IntPtr pp); [DllImport("hid.dll")] private static extern int HidP_GetCaps(IntPtr pp, ref HIDP_CAPS caps); [DllImport("setupapi.dll", CharSet = CharSet.Auto)] private static extern IntPtr SetupDiGetClassDevs( ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, int flags); [DllImport("setupapi.dll", CharSet = CharSet.Auto)] private static extern bool SetupDiEnumDeviceInterfaces( IntPtr hDevInfo, IntPtr devInfo, ref Guid interfaceClassGuid, int memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData); [DllImport("setupapi.dll", CharSet = CharSet.Auto)] private static extern bool SetupDiGetDeviceInterfaceDetail( IntPtr hDevInfo, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, IntPtr deviceInterfaceDetailData, int detailSize, ref int requiredSize, IntPtr deviceInfoData); [DllImport("setupapi.dll")] private static extern bool SetupDiDestroyDeviceInfoList(IntPtr hDevInfo); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr CreateFile( string fileName, uint desiredAccess, uint shareMode, IntPtr securityAttributes, uint creationDisposition, uint flagsAndAttributes, IntPtr templateFile); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool WriteFile( IntPtr hFile, byte[] buffer, int numberOfBytesToWrite, out int numberOfBytesWritten, IntPtr overlapped); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool ReadFile( IntPtr hFile, byte[] buffer, int numberOfBytesToRead, out int numberOfBytesRead, IntPtr overlapped); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetOverlappedResult( IntPtr hFile, IntPtr overlapped, out int numberOfBytesTransferred, bool wait); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr CreateEvent(IntPtr attr, bool manualReset, bool initialState, string name); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool WaitForSingleObject(IntPtr hHandle, int milliseconds); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool CloseHandle(IntPtr hObject); private ushort m_vid; private ushort m_pid; private IntPtr m_handle = new IntPtr(-1); private int m_outLen = 65; private int m_inLen = 65; public bool IsOpen { get { return m_handle != new IntPtr(-1); } } public HidDevice(ushort vid, ushort pid) { m_vid = vid; m_pid = pid; } /* 查找并打开指定 VID/PID 的 HID 设备 */ public bool Open() { Guid hidGuid; IntPtr hDevInfo; SP_DEVICE_INTERFACE_DATA did; IntPtr pDetail; int required; string path; HIDD_ATTRIBUTES attr; IntPtr h; IntPtr preparsed; HIDP_CAPS caps; int i; HidD_GetHidGuid(out hidGuid); hDevInfo = SetupDiGetClassDevs(ref hidGuid, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (hDevInfo == new IntPtr(-1)) return false; did = new SP_DEVICE_INTERFACE_DATA(); did.cbSize = Marshal.SizeOf(did); i = 0; while (SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref hidGuid, i, ref did)) { required = 0; SetupDiGetDeviceInterfaceDetail(hDevInfo, ref did, IntPtr.Zero, 0, ref required, IntPtr.Zero); if (required > 0) { pDetail = Marshal.AllocHGlobal(required); Marshal.WriteInt32(pDetail, IntPtr.Size == 8 ? 8 : 5); if (SetupDiGetDeviceInterfaceDetail(hDevInfo, ref did, pDetail, required, ref required, IntPtr.Zero)) { path = Marshal.PtrToStringAuto(new IntPtr(pDetail.ToInt64() + 4)); h = CreateFile(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero); if (h != new IntPtr(-1)) { attr = new HIDD_ATTRIBUTES(); attr.Size = Marshal.SizeOf(attr); if (HidD_GetAttributes(h, ref attr) && attr.VendorID == m_vid && attr.ProductID == m_pid) { m_handle = h; if (HidD_GetPreparsedData(h, out preparsed)) { caps = new HIDP_CAPS(); if (HidP_GetCaps(preparsed, ref caps) == HIDP_STATUS_SUCCESS) { m_outLen = caps.OutputReportByteLength; m_inLen = caps.InputReportByteLength; } HidD_FreePreparsedData(preparsed); } Marshal.FreeHGlobal(pDetail); SetupDiDestroyDeviceInfoList(hDevInfo); return true; } CloseHandle(h); } } Marshal.FreeHGlobal(pDetail); } i++; } SetupDiDestroyDeviceInfoList(hDevInfo); return false; } public void Close() { if (m_handle != new IntPtr(-1)) { CloseHandle(m_handle); m_handle = new IntPtr(-1); } } /* 发送一包:pkt 为 64 字节业务数据,内部自动加 1 字节报告 ID(0) */ public bool Write(byte[] pkt) { byte[] buf; int written; if (!IsOpen) return false; if (pkt.Length > 64) return false; buf = new byte[m_outLen]; buf[0] = 0x00; Array.Copy(pkt, 0, buf, 1, pkt.Length); return WriteFile(m_handle, buf, buf.Length, out written, IntPtr.Zero); } /* 非阻塞读:timeoutMs 内无数据返回 null */ public byte[] Read(int timeoutMs) { byte[] buf; byte[] ret; int read; IntPtr ov; IntPtr evt; int x; if (!IsOpen) return null; ov = Marshal.AllocHGlobal(32); for (x = 0; x < 32; x++) Marshal.WriteByte(ov, x, 0); evt = CreateEvent(IntPtr.Zero, true, false, null); Marshal.WriteIntPtr(ov, IntPtr.Size == 8 ? 24 : 16, evt); buf = new byte[m_inLen]; if (!ReadFile(m_handle, buf, buf.Length, out read, ov)) { if (WaitForSingleObject(evt, timeoutMs) != 0) { CloseHandle(evt); Marshal.FreeHGlobal(ov); return null; } if (!GetOverlappedResult(m_handle, ov, out read, false)) { CloseHandle(evt); Marshal.FreeHGlobal(ov); return null; } } CloseHandle(evt); Marshal.FreeHGlobal(ov); ret = new byte[64]; if (read > 1) Array.Copy(buf, 1, ret, 0, Math.Min(read - 1, 64)); return ret; } } }