--- source_files: - Common/DTS.Common.IConnection/USBConnection/HIDUSBConnection/HIDUSBConnection.cs generated_at: "2026-04-16T11:51:28.238124+00:00" model: "zai-org/GLM-5-FP8" schema_version: 1 sha256: "4a9eeb7b8043999a" --- # Documentation: HIDUSBConnection ## 1. Purpose `HIDUSBConnection` implements the `IConnection` interface to provide asynchronous communication with USB Human Interface Device (HID) hardware. It serves as a bridge between the application layer and USB HID devices manufactured by DTS (Vendor ID `0x1CB9`, Product ID `0x0003`), encapsulating low-level Windows API calls for device discovery, connection management, and data transfer via input/output reports. --- ## 2. Public Interface ### Constants | Name | Value | Description | |------|-------|-------------| | `HIDSLICE_PID` | `0x0003` | Product ID for the target HID device | | `DTS_VID` | `0x1CB9` | Vendor ID for DTS devices | ### Properties | Signature | Description | |-----------|-------------| | `bool Connected { get; }` | Returns the current connection state (`_Connected`) | | `string ConnectString { get; }` | Returns the device name (`Device_Name`) | | `System.Net.Sockets.SocketFlags Flags { get; set; }` | Socket flags property (usage unclear from source) | | `double GetCurrentDownloadRate()` | Always returns `0D` | | `double GetCurrentUploadRate()` | Always returns `0D` | ### Events | Signature | Description | |-----------|-------------| | `event EventHandler OnDisconnected` | Event declared but **never raised** in the source | ### Methods | Signature | Description | |-----------|-------------| | `void Create(string ConnectString)` | Stores the device path in `Device_Name` | | `void Dispose()` | Public disposal method implementing IDisposable pattern | | `IAsyncResult BeginConnect(AsyncCallback cb, object state)` | Initiates an asynchronous connection attempt | | `void EndConnect(IAsyncResult ar)` | Completes the connection: opens handles, retrieves device capabilities, configures buffers | | `static string GetFirstConnectString()` | Scans for the first matching HID device (VID: `DTS_VID`, PID: `HIDSLICE_PID`) and returns its device path | | `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)` | Initiates an asynchronous disconnect | | `void EndDisconnect(IAsyncResult asyncResult)` | Closes all handles (`_HIDHandle`, `_ReadHandle`, `_WriteHandle`) and sets `_Connected = false` | | `IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` | Initiates an asynchronous send operation | | `int EndSend(IAsyncResult ar)` | Writes data to the device in chunks based on `OutputReportByteLength`; returns total bytes sent | | `IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` | Initiates an asynchronous receive operation | | `int EndReceive(IAsyncResult ar)` | Reads an input report and copies payload to the buffer; returns `size` on success, `0` on failure | | `string GetConnectionData()` | Returns an empty string | | `IAsyncResult BeginAccept(AsyncCallback callback, Object state)` | **Throws `NotSupportedException`** | | `IConnection EndAccept(IAsyncResult asyncResult)` | **Throws `NotSupportedException`** | | `void Bind(int port)` | **Throws `NotSupportedException`** | | `void Listen(int backlog)` | **Throws `NotSupportedException`** | ### Nested Classes | Name | Description | |------|-------------| | `HIDUSBRecAsyncResult` | Implements `IAsyncResult`; contains `buffer`, `offset`, `size` properties for async operations | | `AUSBRecFix` (private) | Helper class bundling `AsyncCallback` and `HIDUSBRecAsyncResult` for thread pool dispatch | --- ## 3. Invariants 1. **Device Identification**: `GetFirstConnectString()` only recognizes devices with Vendor ID `0x1CB9` and Product ID `0x0003`. 2. **Handle Validity**: `BeginSend` and `BeginReceive` throw if `_ReadHandle` or `_WriteHandle` equals `INVALID_HANDLE_VALUE`. 3. **Report Buffer Structure**: Output reports reserve byte 0 for the report ID (always set to `0`); actual data starts at byte 1. 4. **Input Report Buffer Size**: `InputReportBuffer` is sized to `_MyHID.Capabilities.InputReportByteLength`. 5. **Async Pattern**: All `Begin*` methods queue work via `ThreadPool.QueueUserWorkItem` and require corresponding `End*` calls. 6. **Dispose Guard**: The `disposed` flag prevents double-disposal. --- ## 4. Dependencies ### This Module Depends On | Namespace/Class | Usage | |-----------------|-------| | `DTS.DASLib.Connection.USBFramework.HIDevice` | HID device abstraction, capabilities, input/output reports | | `DTS.DASLib.Connection.USBFramework.DeviceManagement` | Device enumeration via GUID | | `DTS.DASLib.Connection.USBFramework.HIDDeclarations` | P/Invoke declarations for `HidD_GetHidGuid`, `HidD_GetAttributes` | | `DTS.DASLib.Connection.USBFramework.FileIODeclarations` | P/Invoke declarations for `CreateFile`, `CloseHandle`, `SECURITY_ATTRIBUTES` | | `DTS.DASLib.DASResource.Strings` | Localized error message strings | | `System.Runtime.InteropServices` | `Marshal.SizeOf` for structure sizing | ### What Depends On This Module **Unclear from source alone** — the `IConnection` interface suggests this is consumed by a connection abstraction layer, but callers are not visible in this file. --- ## 5. Gotchas 1. **`OnDisconnected` Event Never Raised**: The event is declared but no code path in this file invokes it. Callers should not rely on it for disconnection notification. 2. **`InputReportBuffer` is a Class-Level Field**: This buffer is shared across all receive operations. If multiple `BeginReceive`/`EndReceive` calls overlap, data corruption is possible. Thread safety is unclear. 3. **`EndReceive` Returns `size` on Success, Not Bytes Read**: The method returns `rar.size` (the requested size) rather than the actual number of bytes copied (`InputReportBuffer.Length - 1`). Callers may receive fewer bytes than indicated. 4. **`EndDisconnect` Ignores `CloseHandle` Results**: The `Result` variable from `CloseHandle` calls is captured but never checked. Failures are silently ignored. 5. **`GetCurrentDownloadRate`/`GetCurrentUploadRate` Are Stubbed**: Both always return `0D`. If rate monitoring is required, it is not implemented here. 6. **`GetFirstConnectString` Hardcodes Array Size**: The `DevicePathName` array is fixed at 128 elements. Systems with more than 128 HID devices could fail to find the target. 7. **`EndSend` Chunking Logic**: Data is chunked into `OutputReportByteLength - 1` sized pieces. Each chunk requires a separate write operation; there is no batching optimization. 8. **Exception Handling in `NetCallbackFix`**: Exceptions are shown via `MessageBox.Show`, which blocks the UI thread and is inappropriate for library code. 9. **`Flags` Property is Unused**: The `SocketFlags` property has no apparent purpose in this HID implementation. 10. **`BeginConnect` Does Not Perform Actual Connection**: The connection logic is in `EndConnect`. `BeginConnect` merely queues a callback that immediately invokes the user's `AsyncCallback`.