This commit is contained in:
2026-04-17 14:55:32 -04:00
commit bc3ac1d4c9
18017 changed files with 4371742 additions and 0 deletions

View File

@@ -0,0 +1,123 @@
---
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`.

View File

@@ -0,0 +1,42 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/HIDUSBConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:52:31.104928+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "1fcf58774b015c19"
---
# Documentation: HIDUSBConnection Assembly Configuration
## 1. Purpose
This source file defines the assembly metadata for the `USBConnection` component, specifically within the `DTS.Common.IConnection` namespace structure. It exists to configure the manifest of the compiled .NET assembly, setting the version information, title, and COM visibility settings. Its role is strictly limited to build-time configuration; it contains no executable logic.
## 2. Public Interface
This file does not contain any public classes, methods, or functions. It consists entirely of assembly-level attributes used by the compiler.
**Attributes Defined:**
* `AssemblyTitle`: Set to `"USBConnection"`.
* `AssemblyProduct`: Set to `"USBConnection"`.
* `AssemblyCopyright`: Set to `"Copyright © 2008"`.
* `ComVisible`: Set to `false`.
* `Guid`: Set to `"9127ae79-928b-4187-a425-97f49034c5ad"`.
* `AssemblyVersion`: Set to `"1.06.0081"`.
* `AssemblyFileVersion`: Set to `"1.06.0081"`.
## 3. Invariants
* **COM Visibility:** The attribute `[assembly: ComVisible(false)]` dictates that no types within this assembly are visible to COM components by default. This must be explicitly overridden on specific types if COM interop is required.
* **Version Synchronization:** The `AssemblyVersion` and `AssemblyFileVersion` are currently synchronized at `"1.06.0081"`.
* **Identity:** The assembly is identified by the GUID `9127ae79-928b-4187-a425-97f49034c5ad` if exposed to COM.
## 4. Dependencies
* **Internal Dependencies:**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
* **External Dependencies:** None identified from this file alone. The file is a properties file for the `HIDUSBConnection` project.
## 5. Gotchas
* **Legacy Project Format:** This file uses the explicit `AssemblyInfo` style typical of older .NET Framework projects (pre-SDK style). If this project is migrated to a modern SDK-style `.csproj` format, these attributes may conflict with auto-generated values unless `<GenerateAssemblyInfo>false</GenerateAssemblyInfo>` is set in the project file.
* **Hardcoded Versions:** The version string `"1.06.0081"` is hardcoded. Continuous Integration (CI) pipelines looking to inject version numbers dynamically would need to modify this file pre-build or use a different versioning strategy.
* **Empty Metadata:** `AssemblyDescription`, `AssemblyConfiguration`, `AssemblyCompany`, and `AssemblyTrademark` are initialized as empty strings, which may result in missing metadata in the compiled DLL properties.

View File

@@ -0,0 +1,217 @@
---
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-16T11:51:16.904126+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "8939bee008e13a9a"
---
# USB Framework Module Documentation
## 1. Purpose
This module provides a .NET wrapper around Windows Win32 APIs for USB device communication and management. It enables applications to discover, monitor, and interact with HID-class USB devices through P/Invoke declarations for `kernel32.dll`, `hid.dll`, `setupapi.dll`, `user32.dll`, and `advapi32.dll`. The module handles device enumeration by GUID, device arrival/removal notifications, and low-level file I/O operations required for USB device communication.
---
## 2. Public Interface
### FileIODeclarations Class
**Namespace:** `DTS.Common.USBFramework`
A container for Win32 file I/O P/Invoke declarations.
**Constants:**
- `GENERIC_READ` (uint): `0x80000000`
- `GENERIC_WRITE` (uint): `0x40000000`
- `FILE_SHARE_READ` (uint): `0x00000001`
- `FILE_SHARE_WRITE` (uint): `0x00000002`
- `FILE_FLAG_OVERLAPPED` (uint): `0x40000000`
- `INVALID_HANDLE_VALUE` (int): `-1`
- `OPEN_EXISTING` (short): `3`
- `WAIT_TIMEOUT` (int): `0x102`
- `WAIT_OBJECT_0` (uint): `0`
- `WAIT_FAILED` (uint): `0xFFFFFFFF`
- `WAIT_ABANDONED` (uint): `0x00000080`
- `FSCTL_SET_COMPRESSION` (int): `0x9C040`
**Structures:**
- `OVERLAPPED` - Sequential layout structure with fields: `Internal`, `InternalHigh`, `Offset`, `OffsetHigh`, `hEvent` (all int)
- `SECURITY_ATTRIBUTES` - Sequential layout structure with fields: `nLength`, `lpSecurityDescriptor`, `bInheritHandle` (all int)
**Static Methods (DllImport kernel32.dll):**
- `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 Class
**Namespace:** `DTS.Common.USBFramework`
Alternative file I/O declarations using `SafeFileHandle`.
**Constants:**
- `FILE_ATTRIBUTE_NORMAL` (short): `0x80`
- `FILE_FLAG_OVERLAPPED` (int): `0x40000000`
- `FILE_SHARE_READ` (short): `0x1`
- `FILE_SHARE_WRITE` (short): `0x2`
- `GENERIC_READ` (uint): `0x80000000`
- `GENERIC_WRITE` (uint): `0x40000000`
- `INVALID_HANDLE_VALUE` (int): `-1`
- `OPEN_EXISTING` (short): `3`
**Structure:**
- `SECURITY_ATTRIBUTES` - Sequential layout with `nLength` (int), `lpSecurityDescriptor` (IntPtr), `bInheritHandle` (int)
**Static Methods (DllImport kernel32.dll):**
- `bool CloseHandle(SafeFileHandle hObject)`
- `SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, ref SECURITY_ATTRIBUTES lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile)`
---
### HIDDeclarations Class
**Namespace:** `DTS.DASLib.Connection.USBFramework` (Note: different namespace)
A container for HID device P/Invoke declarations.
**Constants:**
- `HidP_Input` (short): `0`
- `HidP_Output` (short): `1`
- `HidP_Feature` (short): `2`
**Structures:**
- `HIDD_ATTRIBUTES` - Fields: `Size` (int), `VendorID` (short), `ProductID` (short), `VersionNumber` (short)
- `HIDP_CAPS` - Fields: `Usage`, `UsagePage`, `InputReportByteLength`, `OutputReportByteLength`, `FeatureReportByteLength`, `Reserved[17]`, `NumberLinkCollectionNodes`, `NumberInputButtonCaps`, `NumberInputValueCaps`, `NumberInputDataIndices`, `NumberOutputButtonCaps`, `NumberOutputValueCaps`, `NumberOutputDataIndices`, `NumberFeatureButtonCaps`, `NumberFeatureValueCaps`, `NumberFeatureDataIndices`
- `HidP_Value_Caps` - Extensive structure with fields for usage page, report ID, bit field, link collection, logical/physical min/max, usage min/max, string min/max, designator min/max, data index min/max, and multiple reserved fields
**Static Methods (DllImport hid.dll):**
- `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 Class
**Namespace:** `DTS.Common.USBFramework`
A container for device management P/Invoke declarations.
**Constants:**
- Device event constants: `DBT_DEVICEARRIVAL` (`0x8000`), `DBT_DEVICEREMOVECOMPLETE` (`0x8004`), `DBT_DEVTYP_DEVICEINTERFACE` (`5`), `DBT_DEVTYP_HANDLE` (`6`)
- Notification constants: `DEVICE_NOTIFY_ALL_INTERFACE_CLASSES` (`4`), `DEVICE_NOTIFY_SERVICE_HANDLE` (`1`), `DEVICE_NOTIFY_WINDOW_HANDLE` (`0`), `WM_DEVICECHANGE` (`0x219`)
- Error constants: `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` - Fields: `dbcc_size`, `dbcc_devicetype`, `dbcc_reserved`, `dbcc_classguid` (Guid), `dbcc_name` (string, SizeConst=400)
- `DEV_BROADCAST_DEVICEINTERFACE_1` - Class variant with `dbcc_classguid` as byte[16] and `dbcc_name` as char[255]
- `DEV_BROADCAST_HANDLE` - Fields: `dbch_size`, `dbch_devicetype`, `dbch_reserved`, `dbch_handle`, `dbch_hdevnotify`
- `DEV_BROADCAST_HDR` - Fields: `dbch_size`, `dbch_devicetype`, `dbch_reserved`
- `SP_DEVICE_INTERFACE_DATA` - Fields: `cbSize`, `InterfaceClassGuid` (Guid), `Flags`, `Reserved` (IntPtr)
- `SP_DEVICE_INTERFACE_DETAIL_DATA` - Fields: `cbSize`, `DevicePath` (string)
- `SP_DEVINFO_DATA` - Fields: `cbSize`, `ClassGuid` (Guid), `DevInst`, `Reserved`
**Enum:**
- `RegSAM` - Flags enum with values: `QueryValue`, `SetValue`, `CreateSubKey`, `EnumerateSubKeys`, `Notify`, `CreateLink`, `WOW64_32Key`, `WOW64_64Key`, `WOW64_Res`, `Read`, `Write`, `Execute`, `AllAccess`
**Static Methods:**
- `IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, int Flags)` - user32.dll
- `int SetupDiCreateDeviceInfoList(ref System.Guid ClassGuid, int hwndParent)` - setupapi.dll
- `int SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet)` - setupapi.dll
- `int SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref System.Guid InterfaceClassGuid, int MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData)` - setupapi.dll
- `IntPtr SetupDiGetClassDevs(ref System.Guid ClassGuid, string Enumerator, int hwndParent, uint Flags)` - setupapi.dll
- `bool SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, int DeviceInterfaceDetailDataSize, ref int RequiredSize, IntPtr DeviceInfoData)` - setupapi.dll
- `bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, uint MemberIndex, out SP_DEVINFO_DATA DeviceInfoData)` - setupapi.dll
- `IntPtr SetupDiGetClassDevsA(ref Guid ClassGuid, uint Enumerator, IntPtr hwndParent, uint Flags)` - setupapi.dll
- `bool SetupDiGetDeviceRegistryPropertyA(IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, uint Property, uint PropertyRegDataType, StringBuilder PropertyBuffer, uint PropertyBufferSize, IntPtr RequiredSize)` - setupapi.dll
- `int SetupDiOpenDevRegKey(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, uint Scope, uint HwProfile, uint KeyType, RegSAM samDesired)` - setupapi.dll
- `uint RegQueryValueEx(int hKey, string lpValueName, uint lpReserved, out uint lpType, ref byte[] lpData, ref uint lpcbData)` - Advapi32.dll
- `bool UnregisterDeviceNotification(IntPtr Handle)` - user32.dll
- `int GetLastError()` - kernel32.dll
---
### DeviceManagement Class
**Namespace:** `DTS.Common.USBFramework`
Implements `IDisposable`. Provides high-level device management operations.
**Public Methods:**
- `void Dispose()` - Empty implementation; does not release resources.
- `bool DeviceNameMatch(Message m, string mydevicePathName)` - Compares the device path name from a `WM_DEVICECHANGE` message against a specified device path name. Returns `true` if names match (case-insensitive), `false` otherwise. Only processes messages where `dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE`.
- `bool FindDeviceFromGuid(System.Guid myGuid, ref string[] devicePathName)` - Enumerates all present devices matching the specified interface class GUID. Populates `devicePathName` array with device path names. Returns `true` if at least one device is found. Caller must pre-allocate the `devicePathName` array with sufficient size.
- `bool RegisterForDeviceNotifications(IntPtr formHandle, Guid classGuid, ref IntPtr deviceNotificationHandle)` - Registers a window to receive device arrival/removal notifications for a specific device interface class. Returns `true` on success. The `deviceNotificationHandle` is set to the registration handle on success.
- `void StopReceivingDeviceNotifications(IntPtr deviceNotificationHandle)` - Unregisters device notifications. Failures are silently ignored.
- `bool GetDeviceRegistryProperty(Guid myGuid)` - Enumerates devices and logs driver names via `APILogger.Log()`. Returns `true` on success, `false` on error or if no matching device found.
**Static Fields:**
- `IS64_BIT_PROCESS` (bool, readonly) - Computed as `(IntPtr.Size == 8)`
---
## 3. Invariants
- **Handle Validity:** All Win32 handles (`int` or `IntPtr` types) must be valid when passed to API functions. `INVALID_HANDLE_VALUE` (-1) indicates failure from `CreateFile` operations.
- **Structure Size Initialization:** Structures with `cbSize` fields (`SP_DEVICE_INTERFACE_DATA`, `SP_DEVICE_INTERFACE_DETAIL_DATA`, `SP_DEVINFO_DATA`) must have `cbSize` set to `Marshal.SizeOf()` before passing to API functions.
- **Memory Management:** Memory allocated via `Marshal.AllocHGlobal()` must be freed via `Marshal.FreeHGlobal()`. The `FindDeviceFromGuid` method allocates and frees `detailDataBuffer` within its scope.
- **Device Path Array Pre-allocation:** `FindDeviceFromGuid` requires the caller to pre-allocate the `devicePathName` string array; the method does not resize it.
- **32/64-bit Compatibility:** The code conditionally handles pointer arithmetic based on `IS64_BIT_PROCESS` for correct memory offset calculations.
- **Namespace Inconsistency:** `HIDDeclarations` resides in `DTS.DASLib.Connection.USBFramework` while all other classes are in `DTS.Common.USBFramework`.
---
## 4. Dependencies
**External Dependencies (DLL Imports):**
- `kernel32.dll` - File I/O, handles, synchronization
- `hid.dll` - HID device communication
- `setupapi.dll` - Device enumeration and management
- `user32.dll` - Device notification registration
- `Advapi32.dll` - Registry operations
**Internal Dependencies:**
- `Microsoft.Win32.SafeHandles` - Used by `FileIO` class for `SafeFileHandle`
- `System.Runtime.InteropServices` - P/Invoke and marshaling
- `System.Windows.Forms` - `Message` struct used in `DeviceNameMatch`
- `DTS.Common.Utilities.Logging` - `APILogger` used in `DeviceManagement.GetDeviceRegistryProperty`
**Consumers:**
- Not determinable from source alone; this module appears to be a low-level infrastructure layer for USB communication.
---
## 5. Gotchas
1. **Empty Dispose Implementation:** `DeviceManagement.Dispose()` is empty and does not release the `deviceNotificationHandle` or clean up any resources. Callers must explicitly call `StopReceivingDeviceNotifications()` before disposal.
2. **Namespace Mismatch:** `HIDDeclarations` is in `DTS.DASLib.Connection.USBFramework` namespace, while all other classes are in `DTS.Common.USBFramework`. This may cause compilation issues or require multiple using directives.
3. **Duplicate Constants:** `FileIODeclarations` and `FileIO` both define identical constants (`GENERIC_READ`, `GENERIC_WRITE`, `FILE_SHARE_READ`, `FILE_SHARE_WRITE`, `FILE_FLAG_OVERLAPPED`, `INVALID_HANDLE_VALUE`, `OPEN_EXISTING`) with slightly different

View File

@@ -0,0 +1,42 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/USBFramework/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:52:05.531680+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "f8e1fde835545ec4"
---
# Documentation: USBFramework Assembly Configuration
## 1. Purpose
This source file (`AssemblyInfo.cs`) provides standard .NET assembly metadata for the `HIDFramework` component, which appears to be part of the larger `DTS.Common.IConnection` USB connectivity subsystem. Its primary role is to define the assembly's identity, version, and COM visibility settings during the build process. It serves as the manifest root for this specific library.
## 2. Public Interface
As an assembly information file, this module does not expose traditional methods or classes. Instead, it defines the following assembly-level attributes:
* **`AssemblyTitle`**: Set to `"HIDFramework"`. Defines the friendly name for the assembly.
* **`AssemblyProduct`**: Set to `"HIDFramework"`. Specifies product information for the assembly output.
* **`AssemblyVersion`**: Set to `"1.06.0081"`. Specifies the version number used by the common language runtime.
* **`AssemblyFileVersion`**: Set to `"1.06.0081"`. Specifies the file version number displayed on the file properties dialog.
* **`ComVisible`**: Set to `false`. Ensures types within this assembly are not visible to COM components by default.
* **`Guid`**: Set to `"c655f31f-ca6c-4e9b-9480-934762d20a8c"`. Provides a unique identifier for the assembly if exposed to COM.
* **`AssemblyCopyright`**: Set to `"Copyright © 2008"`.
* **`AssemblyDescription`**, **`AssemblyConfiguration`**, **`AssemblyCompany`**, **`AssemblyTrademark`**, **`AssemblyCulture`**: Defined but set to empty strings.
## 3. Invariants
* **COM Visibility:** The attribute `[assembly: ComVisible(false)]` guarantees that no types within this assembly are exposed to COM unless a specific type overrides this with `[ComVisible(true)]`.
* **Version Synchronization:** The `AssemblyVersion` and `AssemblyFileVersion` are explicitly synchronized to the string `"1.06.0081"`. They do not use auto-increment wildcards.
* **Identity:** The internal identity of the assembly is strictly defined as `HIDFramework` via both `AssemblyTitle` and `AssemblyProduct`.
## 4. Dependencies
* **Internal Dependencies:**
* `System.Reflection`: Required for the assembly attributes.
* `System.Runtime.CompilerServices`: Required for compiler interaction.
* `System.Runtime.InteropServices`: Required for the `ComVisible` and `Guid` attributes.
* **External Dependencies:** None inferred from this file alone. As an AssemblyInfo file, it is a leaf node in the dependency graph, consumed by the compiler during the build of the `HIDFramework` DLL.
## 5. Gotchas
* **Naming Discrepancy:** The file path indicates this project resides in a directory named `USBFramework` (`.../USBConnection/USBFramework/...`), but the `AssemblyTitle` and `AssemblyProduct` attributes explicitly name the output `"HIDFramework"`. This inconsistency between the folder structure and the binary name could cause confusion when referencing the DLL.
* **Empty Metadata:** Several standard metadata fields (`AssemblyDescription`, `AssemblyCompany`) are empty. This may result in missing metadata in the compiled DLL properties, which can be problematic for automated tooling or license management.
* **Legacy Date:** The copyright year is 2008, suggesting this is a legacy codebase. Modern .NET projects often embed this information in the `.csproj` file rather than a separate `AssemblyInfo.cs`.

View File

@@ -0,0 +1,111 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/WINUSBConnection/WINUSBDeviceApi.cs
- Common/DTS.Common.IConnection/USBConnection/WINUSBConnection/CDCUSBConnection.cs
- Common/DTS.Common.IConnection/USBConnection/WINUSBConnection/WINUSBConnection.cs
generated_at: "2026-04-16T11:50:38.580755+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "2043cd8e3c0f04ef"
---
# Documentation: DTS.Common.WINUSBConnection
## 1. Purpose
This module provides USB connectivity abstractions within the `DTS.Common.WINUSBConnection` namespace. It contains two concrete implementations of the `IConnection` interface: `CDCUSBConnection`, which wraps a standard `System.IO.Ports.SerialPort` for CDC (Communications Device Class) USB devices, and `WINUSBConnection`, which provides low-level communication via the native `winusb.dll` API for custom WinUSB devices. Additionally, it defines the internal P/Invoke signatures and data structures required to interact with the Windows WinUSB driver stack.
## 2. Public Interface
### Class: `CDCUSBConnection`
Implements `IConnection`. Represents a USB device connection via a virtual COM port (CDC).
* **`void Create(string connectString, string hostIPAddress)`**
* Parses the `connectString` to match against registry keys in `RegKeys`. If a match is found, it retrieves the `PortName` from the registry (`Device Parameters` subkey) and configures the internal `SerialPort` instance.
* **`IAsyncResult BeginConnect(AsyncCallback cb, object state)`**
* Initiates an asynchronous connection. Queues the connection logic to the thread pool.
* **`void EndConnect(IAsyncResult ar)`**
* Completes the asynchronous connection. Configures the serial port (BaudRate, DataBits, etc.) and calls `_comPort.Open()`. Sets `Connected` to `true`.
* **`IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`**
* Initiates an asynchronous send operation.
* **`int EndSend(IAsyncResult ar)`**
* Completes the send operation. Writes data to the internal `_comPort` using `_comPort.Write`.
* **`Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)`**
* Task-based asynchronous wrapper for `BeginSend`/`EndSend`.
* **`IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`**
* Initiates an asynchronous receive operation.
* **`int EndReceive(IAsyncResult ar)`**
* Completes the receive operation. Reads data from `_comPort`. **Note:** This method blocks in a loop (`Thread.Sleep(1)`) until at least one byte is read.
* **`IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)`**
* Initiates an asynchronous disconnect.
* **`void EndDisconnect(IAsyncResult ar)`**
* Completes the disconnect. Closes and disposes the internal `_comPort`.
* **Properties**
* `bool Connected`: Gets the current connection state.
* `string ConnectString`: Returns the device pathname.
* `IList<string> RegKeys`: Static property that lazily loads registry keys for the device from `SYSTEM\CurrentControlSet\Enum\USB\`.
### Class: `WINUSBConnection`
Implements `IConnection`. Represents a USB device connection using the native WinUSB driver.
* **`void Create(string connectString, string hostIPAddress)`**
* Stores the `connectString` in the `ConnectString` property.
* **`IAsyncResult BeginConnect(AsyncCallback cb, object state)`**
* Initiates an asynchronous connection. Throws `NotConnectedException` if already connected.
* **`void EndConnect(IAsyncResult ar)`**
* Completes the connection. Instantiates a new `WinUsbDevice`, retrieves a device handle via `GetDeviceHandle`, and initializes the device via `InitializeDevice`. Uses a mutex (`_usbConnectionMutex`) to synchronize access.
* **`IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`**
* Initiates an asynchronous send. Validates buffer parameters.
* **`int EndSend(IAsyncResult ar)`**
* Completes the send. Checks `MyDevInfo.UseHybridBulkIntMode`. If true, calls `SendViaInterruptTransfer`; otherwise, calls `SendViaBulkTransfer`.
* **`Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)`**
* Task-based asynchronous wrapper for `BeginSend`/`EndSend`.
* **`IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`**
* Initiates an asynchronous receive.
* **`int EndReceive(IAsyncResult ar)`**
* Completes the receive. Reads data via `ReadViaBulkTransfer`. Blocks in a loop (`Thread.Sleep(1)`) until bytes are read. Returns 0 if the connection fails or closes.
* **`IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)`**
* Initiates an asynchronous disconnect.
* **`void EndDisconnect(IAsyncResult ar)`**
* Completes the disconnect. Calls `DisposeSliceDev` to release the WinUSB handle.
* **Properties**
* `bool Connected`: Gets the current connection state.
* `string ConnectString`: Gets the device pathname.
### Internal Class: `WinUsbDevice` (Partial)
Defines P/Invoke signatures and structures for `winusb.dll`.
* **Structs**: `USBConfigurationDescriptor`, `USBInterfaceDescriptor`, `WinUSBPipeInformation`, `WinUSBSetupPacket`.
* **Enums**: `PolicyType`, `USBDPipeTypes`, `USBDeviceSpeeds`.
* **Methods**: `WinUsb_Initialize`, `WinUsb_Free`, `WinUsb_ControlTransfer`, `WinUsb_ReadPipe`, `WinUsb_WritePipe`, `WinUsb_QueryPipe`, `WinUsb_SetPipePolicy`, etc.
## 3. Invariants
* **Registry Dependency (CDCUSBConnection)**: The `CDCUSBConnection` requires the device to be registered under `SYSTEM\CurrentControlSet\Enum\USB\` with a Vendor ID of `VID_1CB9` and Product ID of `PID_001A`. The `Create` method cannot resolve the port name if these registry keys are missing.
* **Thread Safety (WINUSBConnection)**: The `WINUSBConnection.EndConnect` and `DisposeSliceDev` methods rely on a named Mutex (`"USBConnection"`) to prevent race conditions during device initialization and disposal.
* **Disposal State**: Both connection classes track `Disposed` and `Disposing` flags. Methods generally do not proceed if `Disposed` is true.
* **APM Pattern**: Both classes implement the Asynchronous Programming Model (APM) using internal `IAsyncResult` implementations (`UsbRecAsyncResult` and `WinUSBRecAsyncResult`). Callbacks are invoked via `ThreadPool.QueueUserWorkItem`.
## 4. Dependencies
### Internal Dependencies
* `DTS.Common.Interface.Connection`: Implements `IConnection`.
* `DTS.Common.DASResource`: Uses localized strings for exception messages (e.g., `Strings.CDCUSBConnection_BeginConnect_Err1`).
* `DTS.Common.Utilities.Logging`: Uses `APILogger` for logging exceptions and status messages.
* `DTS.Common.USBFramework`: Uses `DeviceManagement` class (in `WINUSBConnection`).
* `DTS.Common.Classes.Connection`: Uses `NotConnectedException`.
### External Dependencies
* `System.IO.Ports`: Used by `CDCUSBConnection` for `SerialPort`.
* `System.Runtime.InteropServices`: Used for P/Invoke attributes.
* `Microsoft.Win32`: Used for registry access (`RegistryKey`, `SafeFileHandle`).
* `winusb.dll`: Native Windows DLL imported by `WinUsbDevice`.
## 5. Gotchas
* **Blocking Async Reads**: The `EndReceive` methods in both `CDCUSBConnection` and `WINUSBConnection` contain `while` loops that sleep (`Thread.Sleep(1)`) if zero bytes are read. This effectively makes the "asynchronous" operation blocking and consumes a thread pool thread while waiting for data.
* **Recursive Comment**: The `Create(string connectString)` method in both connection classes contains a commented-out line `//Create(connectString);` with a note "this is recursive!". This suggests a historical bug or confusion regarding method overloads.
* **Empty Soft Disconnect**: `SoftConnect` and `SoftDisconnect` methods are implemented but empty. The comments explicitly state they do nothing because there is no soft disconnect option implemented.
* **Hardcoded Device IDs**: `CDCUSBConnection` hardcodes `DTS_VENDOR_ID` (0x1CB9) and `DTS_TSR2_CDCUSB_PRODUCT_ID_STR` ("PID_001A"). It will not work with other USB devices.
* **Partial Class Source**: `WinUsbDevice` is defined as `internal sealed partial class`. The logic for `GetDeviceHandle`, `InitializeDevice`, `SendViaBulkTransfer`, etc., is referenced in `WINUSBConnection` but is **not present in the provided source files** (likely in another file part of the partial class definition).
* **Hybrid Mode Logic**: `WINUSBConnection.EndSend` switches between interrupt and bulk transfers based on a boolean `UseHybridBulkIntMode` located on a `MyDevInfo` object. The definition of `MyDevInfo` is not visible in the provided source.

View File

@@ -0,0 +1,48 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/WINUSBConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:51:53.479173+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "8875c5ea92f3aea7"
---
# Documentation: WINUSBConnection Assembly Info
## 1. Purpose
This file configures assembly-level metadata for the `WINUSBConnection` component within the `DTS.Common.IConnection` namespace. It establishes the assembly's identity, version, and COM visibility settings, serving as the manifest definition for the compiled output. This module exists to provide versioning and attribution information for the WinUSB connection library.
## 2. Public Interface
This file contains no executable public classes, methods, or functions. It strictly defines assembly-level attributes using C# attribute syntax.
**Defined Attributes:**
* **`AssemblyTitle`**: Set to `"WINUSBConnection"`.
* **`AssemblyDescription`**: Set to an empty string.
* **`AssemblyConfiguration`**: Set to an empty string.
* **`AssemblyCompany`**: Set to an empty string.
* **`AssemblyProduct`**: Set to `"WINUSBConnection"`.
* **`AssemblyCopyright`**: Set to `"Copyright © 2008"`.
* **`AssemblyTrademark`**: Set to an empty string.
* **`AssemblyCulture`**: Set to an empty string.
* **`ComVisible`**: Set to `false`. Prevents types in this assembly from being visible to COM components.
* **`Guid`**: Set to `"F3C369E6-BFFB-41bc-B8E8-A31094CED447"`. Identifies the Type Library ID if the project is exposed to COM.
* **`AssemblyVersion`**: Set to `"1.06.0081"`.
* **`AssemblyFileVersion`**: Set to `"1.06.0081"`.
## 3. Invariants
* **Version Consistency:** The `AssemblyVersion` and `AssemblyFileVersion` are explicitly synchronized at `"1.06.0081"`.
* **COM Visibility:** The assembly is explicitly marked as not visible to COM (`ComVisible(false)`). This must be overridden at the type level if specific types need COM exposure.
* **Identity:** The `Guid` attribute provides a unique identifier for this specific assembly's type library.
## 4. Dependencies
* **Imports:**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
* **Consumers:** Any project or reference that depends on the `WINUSBConnection` assembly relies on this file for correct versioning and assembly identity resolution.
## 5. Gotchas
* **Missing Metadata:** The `AssemblyDescription`, `AssemblyCompany`, and `AssemblyConfiguration` attributes are empty. This may result in missing information in assembly property dialogs or automated documentation generation.
* **Legacy Date:** The `AssemblyCopyright` attribute lists the year 2008. It is unclear if this is historical or if the metadata has not been updated to reflect current ownership/year.
* **Hardcoded Version:** The version `1.06.0081` is hardcoded. Unlike the commented-out suggestion in the source (`"*"` for auto-generation), the build and revision numbers are fixed, requiring manual updates for new releases.