--- source_files: - Common/DTS.Common.IConnection/USBConnection/USBFramework/FileIODeclarations.cs - Common/DTS.Common.IConnection/USBConnection/USBFramework/HIDDeclarations.cs - Common/DTS.Common.IConnection/USBConnection/USBFramework/DeviceManagementDeclarations.cs - Common/DTS.Common.IConnection/USBConnection/USBFramework/DeviceManagement.cs generated_at: "2026-04-17T15:36:27.113042+00:00" model: "zai-org/GLM-5-FP8" schema_version: 1 sha256: "9419e177c65ead81" --- # USBFramework Module Documentation ## 1. Purpose The USBFramework module provides low-level Windows API interoperability for USB device communication in the DTS system. It encapsulates P/Invoke declarations and helper logic for three distinct areas: file I/O operations (kernel32.dll), HID-class device communication (hid.dll), and device management/enumeration (setupapi.dll, user32.dll). The module enables the application to discover, connect to, and communicate with USB devices through their device paths and interface class GUIDs, while also supporting device arrival/removal notifications. --- ## 2. Public Interface ### FileIODeclarations (DTS.Common.USBFramework) A static container class for Windows kernel32.dll file I/O P/Invoke declarations. **Constants:** - `GENERIC_READ` (0x80000000), `GENERIC_WRITE` (0x40000000) - `FILE_SHARE_READ` (0x00000001), `FILE_SHARE_WRITE` (0x00000002) - `FILE_FLAG_OVERLAPPED` (0x40000000) - `INVALID_HANDLE_VALUE` (-1) - `OPEN_EXISTING` (3) - `WAIT_TIMEOUT` (0x102), `WAIT_OBJECT_0` (0), `WAIT_FAILED` (0xFFFFFFFF), `WAIT_ABANDONED` (0x00000080) - `FSCTL_SET_COMPRESSION` (0x9C040) **Structures:** - `OVERLAPPED` - Sequential layout structure with `Internal`, `InternalHigh`, `Offset`, `OffsetHigh`, `hEvent` fields - `SECURITY_ATTRIBUTES` - Sequential layout structure with `nLength`, `lpSecurityDescriptor`, `bInheritHandle` fields (all `int`) **P/Invoke Functions:** - `int CancelIo(int hFile)` - `int CloseHandle(int hObject)` - `int CreateEvent(ref SECURITY_ATTRIBUTES SecurityAttributes, int bManualReset, int bInitialState, string lpName)` - `int CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, ref SECURITY_ATTRIBUTES lpSecurityAttributes, int dwCreationDisposition, uint dwFlagsAndAttributes, int hTemplateFile)` - `int GetLastError()` - `int ReadFile(int hFile, ref byte lpBuffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, int lpOverlapped)` - `uint WaitForSingleObject(int hHandle, int dwMilliseconds)` - `int WriteFile(int hFile, ref byte lpBuffer, int nNumberOfBytesToWrite, ref int lpNumberOfBytesWritten, int lpOverlapped)` - `int DeviceIoControl(IntPtr hDevice, int dwIoControlCode, ref short lpInBuffer, int nInBufferSize, IntPtr lpOutBuffer, int nOutBufferSize, ref int lpBytesReturned, IntPtr lpOverlapped)` --- ### FileIO (DTS.Common.USBFramework) A secondary file I/O declaration class with safer handle types. **Constants:** - `FILE_ATTRIBUTE_NORMAL` (0x80), `FILE_FLAG_OVERLAPPED` (0x40000000) - `FILE_SHARE_READ` (0x1), `FILE_SHARE_WRITE` (0x2) - `GENERIC_READ` (0x80000000), `GENERIC_WRITE` (0x40000000) - `INVALID_HANDLE_VALUE` (-1), `OPEN_EXISTING` (3) **Structure:** - `SECURITY_ATTRIBUTES` - Sequential layout with `nLength` (int), `lpSecurityDescriptor` (IntPtr), `bInheritHandle` (int) **P/Invoke Functions:** - `bool CloseHandle(SafeFileHandle hObject)` - `SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, ref SECURITY_ATTRIBUTES lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile)` --- ### HIDDeclarations (DTS.DASLib.Connection.USBFramework) A sealed class containing P/Invoke declarations for HID-class device communication via hid.dll. **Constants:** - `HidP_Input` (0), `HidP_Output` (1), `HidP_Feature` (2) **Structures:** - `HIDD_ATTRIBUTES` - Contains `Size` (int), `VendorID` (short), `ProductID` (short), `VersionNumber` (short) - `HIDP_CAPS` - Device capabilities including report byte lengths, usage info, and 17-element `Reserved` array - `HidP_Value_Caps` - Value capabilities structure with extensive fields for usage ranges, logical/physical min/max, bit sizes, etc. **P/Invoke Functions:** - `bool HidD_FlushQueue(int HidDeviceObject)` - `bool HidD_FreePreparsedData(ref IntPtr PreparsedData)` - `int HidD_GetAttributes(int HidDeviceObject, ref HIDD_ATTRIBUTES Attributes)` - `bool HidD_GetFeature(int HidDeviceObject, ref byte lpReportBuffer, int ReportBufferLength)` - `bool HidD_GetInputReport(int HidDeviceObject, ref byte lpReportBuffer, int ReportBufferLength)` - `void HidD_GetHidGuid(ref System.Guid HidGuid)` - `bool HidD_GetNumInputBuffers(int HidDeviceObject, ref int NumberBuffers)` - `bool HidD_GetPreparsedData(int HidDeviceObject, ref IntPtr PreparsedData)` - `bool HidD_SetFeature(int HidDeviceObject, ref byte lpReportBuffer, int ReportBufferLength)` - `bool HidD_SetNumInputBuffers(int HidDeviceObject, int NumberBuffers)` - `bool HidD_SetOutputReport(int HidDeviceObject, ref byte lpReportBuffer, int ReportBufferLength)` - `int HidP_GetCaps(IntPtr PreparsedData, ref HIDP_CAPS Capabilities)` - `int HidP_GetValueCaps(short ReportType, ref byte ValueCaps, ref short ValueCapsLength, IntPtr PreparsedData)` --- ### DeviceManagementDeclarations (DTS.Common.USBFramework) A class containing P/Invoke declarations for device management via setupapi.dll, user32.dll, and advapi32.dll. **Constants:** - Device event types: `DBT_DEVICEARRIVAL` (0x8000), `DBT_DEVICEREMOVECOMPLETE` (0x8004) - Device types: `DBT_DEVTYP_DEVICEINTERFACE` (5), `DBT_DEVTYP_HANDLE` (6) - Notification flags: `DEVICE_NOTIFY_ALL_INTERFACE_CLASSES` (4), `DEVICE_NOTIFY_SERVICE_HANDLE` (1), `DEVICE_NOTIFY_WINDOW_HANDLE` (0) - `WM_DEVICECHANGE` (0x219) - Error codes: `ERROR_INSUFFICIENT_BUFFER` (122), `NO_ERROR` (0), `ERROR_NO_MORE_ITEMS` (259) - SetupAPI flags: `DIGCF_PRESENT` (0x00000002), `DIGCF_DEVICEINTERFACE` (0x00000010), `DIGCF_ALLCLASSES` (0x00000004) - Registry property constants: `SPDRP_FRIENDLYNAME`, `SPDRP_DEVICEDESC`, `SPDRP_DRIVER` **Structures:** - `DEV_BROADCAST_DEVICEINTERFACE` - For registering device notifications - `DEV_BROADCAST_DEVICEINTERFACE_1` - For reading device name and class GUID - `DEV_BROADCAST_HANDLE`, `DEV_BROADCAST_HDR` - `SP_DEVICE_INTERFACE_DATA`, `SP_DEVICE_INTERFACE_DETAIL_DATA`, `SP_DEVINFO_DATA` **Enum:** - `RegSAM` - Registry access mask flags **P/Invoke Functions:** - `IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, int Flags)` - `int SetupDiCreateDeviceInfoList(ref System.Guid ClassGuid, int hwndParent)` - `int SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet)` - `int SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref System.Guid InterfaceClassGuid, int MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData)` - `IntPtr SetupDiGetClassDevs(ref System.Guid ClassGuid, string Enumerator, int hwndParent, uint Flags)` - `bool SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, int DeviceInterfaceDetailDataSize, ref int RequiredSize, IntPtr DeviceInfoData)` - `bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, uint MemberIndex, out SP_DEVINFO_DATA DeviceInfoData)` - `IntPtr SetupDiGetClassDevsA(ref Guid ClassGuid, uint Enumerator, IntPtr hwndParent, uint Flags)` - `bool SetupDiGetDeviceRegistryPropertyA(IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, uint Property, uint PropertyRegDataType, StringBuilder PropertyBuffer, uint PropertyBufferSize, IntPtr RequiredSize)` - `int SetupDiOpenDevRegKey(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, uint Scope, uint HwProfile, uint KeyType, RegSAM samDesired)` - `uint RegQueryValueEx(int hKey, string lpValueName, uint lpReserved, out uint lpType, ref byte[] lpData, ref uint lpcbData)` - `bool UnregisterDeviceNotification(IntPtr Handle)` - `int GetLastError()` --- ### DeviceManagement (DTS.Common.USBFramework) A concrete class implementing `IDisposable` that provides high-level device management operations. **Methods:** - `void Dispose()` - Empty implementation; no resources released. - `bool DeviceNameMatch(Message m, string mydevicePathName)` - Compares the device path name from a `WM_DEVICECHANGE` message against a known device path. Returns `true` if names match (case-insensitive), `false` otherwise. Only processes messages where `dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE`. - `bool FindDeviceFromGuid(Guid myGuid, ref string[] devicePathName)` - Enumerates all present devices matching the specified interface class GUID. Populates `devicePathName` array with device paths. Returns `true` if at least one device found. Caller must pre-allocate the string array. - `bool RegisterForDeviceNotifications(IntPtr formHandle, Guid classGuid, ref IntPtr deviceNotificationHandle)` - Registers a window to receive device arrival/removal notifications for a specific interface class. Returns `true` on success. - `void StopReceivingDeviceNotifications(IntPtr deviceNotificationHandle)` - Unregisters device notifications. Failures are silently ignored. - `bool GetDeviceRegistryProperty(Guid myGuid)` - Enumerates devices and logs their driver registry property (`SPDRP_DRIVER`) via `APILogger.Log()`. Returns `true` on success. **Static Fields:** - `IS64_BIT_PROCESS` - Readonly boolean, computed as `(IntPtr.Size == 8)` --- ## 3. Invariants - **Handle Validity**: All handle parameters passed to P/Invoke functions must be valid; the module does not validate handles before use. - **Array Pre-allocation**: `FindDeviceFromGuid` requires the caller to pre-allocate the `devicePathName` string array with sufficient size; the method does not resize the array. - **Structure Size**: `SP_DEVICE_INTERFACE_DATA.cbSize` and `SP_DEVICE_INTERFACE_DETAIL_DATA.cbSize` must be set before passing to API functions; `DeviceManagement` handles this internally. - **Memory Management**: `FindDeviceFromGuid` allocates unmanaged memory via `Marshal.AllocHGlobal` and must free it via `Marshal.FreeHGlobal`; the `finally` block ensures cleanup even on exceptions. - **32/64-bit Compatibility**: The code explicitly handles pointer size differences via `IS64_BIT_PROCESS` for structure marshaling in `FindDeviceFromGuid` and `RegisterForDeviceNotifications`. - **Device Path String Size**: In `DeviceNameMatch`, the device name string size is calculated as `(dbch_size - 28) / 2`, assuming 28 bytes for the header structure. --- ## 4. Dependencies **This module depends on:** - `System` (core types) - `System.Runtime.InteropServices` (P/Invoke, Marshal) - `System.Text` (StringBuilder) - `System.Diagnostics` (Debug - commented out but imported) - `System.Windows.Forms` (Message type) - `Microsoft.Win32.SafeHandles` (SafeFileHandle) - `DTS.Common.Utilities.Logging` (APILogger - used in `DeviceManagement.GetDeviceRegistryProperty`) **What depends on this module:** - Not determinable from the provided source files alone. --- ## 5. Gotchas 1. **Namespace Inconsistency**: `HIDDeclarations` resides in namespace `DTS.DASLib.Connection.USBFramework`, while all other classes are in `DTS.Common.USBFramework`. This may cause confusion or require multiple using directives. 2. **Duplicate Constants**: `FileIODeclarations` and `FileIO` both define the same constants (e.g., `GENERIC_READ`, `GENERIC_WRITE`, `FILE_FLAG_OVERLAPPED`, `INVALID_HANDLE_VALUE`, `OPEN_EXISTING`) with identical or similar values. The purpose of this duplication is unclear from source. 3. **Duplicate SECURITY_ATTRIBUTES**: Two different `SECURITY_ATTRIBUTES` structures exist—one in `FileIODeclarations` (with `int