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,76 @@
---
source_files:
- Common/DTS.Common.IConnection/EthernetConnection/RESTConnection.cs
- Common/DTS.Common.IConnection/EthernetConnection/EthernetConnection.cs
generated_at: "2026-04-17T15:41:01.253739+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "b30ad0e6e8a9dd7c"
---
# Documentation: EthernetConnection and RESTConnection
## 1. Purpose
This module provides two implementations of the `IConnection` interface for network communication within the DTS system. `EthernetConnection` is a full TCP socket wrapper that manages asynchronous socket operations including connect, disconnect, send, receive, and accept, with support for soft disconnect/reconnect functionality and TCP keepalive configuration. `RESTConnection` is a stub implementation that simulates synchronous completion of all operations without actual network I/O, designed to satisfy the `IConnection` interface for REST-based endpoints where traditional socket semantics do not apply.
---
## 2. Public Interface
### EthernetConnection (DTS.Common)
#### Properties
| Signature | Description |
|-----------|-------------|
| `bool IsSoftDisconnected { get; }` | Returns `true` if the connection has been soft-disconnected. |
| `bool RequiresKeepAliveReset { get; set; }` | When `true`, `SoftConnect()` performs a keepalive reset via a secondary command port before reconnecting. |
| `Socket Sock` | Public field exposing the underlying `System.Net.Sockets.Socket`. |
| `string ConnectString { get; }` | Returns the connection string (format: `"host:port"`). |
| `bool Connected { get; }` | Returns `true` if `Sock` is non-null and `Sock.Connected` is `true`. |
| `SocketFlags Flags { get; set; }` | Socket flags used for send/receive operations. |
| `event EventHandler OnDisconnected` | Fired when `KeepAliveErrorReceived()` is called. |
#### Methods
| Signature | Description |
|-----------|-------------|
| `void SoftDisconnect()` | Disconnects and disposes the socket if connected and soft disconnects are allowed via `HardwareConstants.AllowSoftDisconnects`. Sets `IsSoftDisconnected = true`. |
| `void SoftConnect()` | Reconnects a soft-disconnected socket. Optionally sends a keepalive reset message to port 8200 if `RequiresKeepAliveReset` is `true`. Retries connection up to 3 times on failure. |
| `void KeepAliveErrorReceived()` | Shuts down, closes, and disposes the socket; fires `OnDisconnected` event. |
| `string GetConnectionData()` | Returns a string with local and remote `EndPoint` information, or empty string on error. |
| `Socket CreateSock(string connectString, string hostIPAddress)` | Factory method creating a TCP socket with `NoDelay`, `KeepAlive`, and custom keepalive timing configured. Optionally binds to `hostIPAddress`. |
| `void Create(string connectString)` | **Note:** Contains a bug (commented-out recursive call). Does nothing. |
| `void Create(string connectString, string hostIPAddress)` | Creates and configures the internal socket; stores connection parameters. |
| `void Bind(int port)` | Binds the socket to a local endpoint on the specified port using the first IP address from `Dns.GetHostEntry`. |
| `void Listen(int backlog)` | Places the socket in listening state. |
| `IAsyncResult BeginConnect(AsyncCallback cb, object state)` | Begins an asynchronous connection. Validates socket exists and `Connect_String` format (`host:port`). |
| `void EndConnect(IAsyncResult ar)` | Completes the asynchronous connect operation. |
| `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, object state)` | Begins asynchronous disconnect. Throws `SocketException(WSAEISCONN)` if socket is already disconnected. |
| `void EndDisconnect(IAsyncResult asyncResult)` | Completes the asynchronous disconnect operation. |
| `IAsyncResult BeginAccept(AsyncCallback callback, object state)` | Begins an asynchronous accept operation. |
| `IConnection EndAccept(IAsyncResult asyncResult)` | Completes accept and returns a new `EthernetConnection` wrapping the accepted socket. |
| `IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` | Begins asynchronous send. Throws if socket is null, callback is null, or socket is not connected. |
| `int EndSend(IAsyncResult ar)` | Completes the asynchronous send; returns bytes sent. Sets `Sock = null` on exception. |
| `Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)` | Task-based async send wrapper using `FromAsync`. |
| `IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` | Begins asynchronous receive. Throws if socket is null or callback is null. |
| `int EndReceive(IAsyncResult ar)` | Completes the asynchronous receive; returns bytes received. |
| `void Dispose()` | Disposes the socket and suppresses finalization. |
---
### RESTConnection (DTS.DASLib.Connection)
#### Properties
| Signature | Description |
|-----------|-------------|
| `bool IConnection.IsSoftDisconnected` | Always returns `false`. |
| `SocketFlags IConnection.Flags { get; set; }` | Defaults to `SocketFlags.None`. |
| `string IConnection.ConnectString` | Returns the stored connection string. |
| `bool IConnection.Connected` | Returns the internal `_bConnected` flag. |
| `event EventHandler OnDisconnected` | Event declared but never invoked in the source. |
#### Methods
| Signature | Description |
|-----------|-------------|
| `void IConnection.Create(string connectString)` | Stores `connectString` in `_ConnectString`. |
| `void IConnection.Create(string connectString, string hostIPAddress)` | Stores both parameters in

View File

@@ -0,0 +1,48 @@
---
source_files:
- Common/DTS.Common.IConnection/EthernetConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-17T16:08:48.739930+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "bbe00a85a5e9455d"
---
# Properties
### Purpose
This module contains assembly metadata for the `DASResource` assembly. It is a standard .NET AssemblyInfo file that defines version information, copyright, and COM visibility settings. The actual implementation code for DASResource is not present in this file—only assembly-level attributes.
### Public Interface
No public types, functions, or methods are defined in this file. The following assembly-level attributes are declared:
- `AssemblyTitle("DASResource")` - Sets the assembly title
- `AssemblyDescription("")` - Empty description
- `AssemblyConfiguration("")` - Empty configuration
- `AssemblyCompany("")` - Empty company name
- `AssemblyProduct("DASResource")` - Product name
- `AssemblyCopyright("Copyright © 2008 - 2009")` - Copyright notice
- `AssemblyTrademark("")` - Empty trademark
- `AssemblyCulture("")` - Neutral culture (not a satellite assembly)
- `ComVisible(false)` - Types not visible to COM by default
- `Guid("E20CF41A-9884-40f4-AD18-4F06A42FE36D")` - COM typelib GUID
- `AssemblyVersion("1.06.0081")` - Assembly version
- `AssemblyFileVersion("1.06.0081")` - File version
### Invariants
- AssemblyVersion and AssemblyFileVersion are synchronized at "1.06.0081"
- ComVisible is set to false, meaning no types are exposed to COM by default
- AssemblyCulture is empty, indicating this is not a satellite assembly
### Dependencies
**Imports:**
- `System.Reflection`
- `System.Runtime.InteropServices`
**What depends on this:** Cannot be determined from source alone. The actual DASResource implementation files would reference this assembly, but they are not provided.
### Gotchas
- The actual DASResource types and functionality are not visible in this file; only assembly metadata is present.
- The copyright date range (2008 - 2009) suggests this assembly was actively developed during that period.
- The description, company, and trademark fields are empty—typical of internal/proprietary projects.
---

View File

@@ -0,0 +1,42 @@
---
source_files:
- Common/DTS.Common.IConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-17T16:08:48.738829+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "fdac77f93f143db6"
---
# Properties
### Purpose
This module contains assembly metadata for the `IConnection` assembly. Based on the assembly name, this appears to define an interface abstraction for connections. The actual interface and implementation code is not present in this file—only assembly-level attributes.
### Public Interface
No public types, functions, or methods are defined in this file. The following assembly-level attributes are declared:
- `AssemblyTitle("IConnection")` - Sets the assembly title
- `AssemblyDescription("")` - Empty description
- `AssemblyConfiguration("")` - Empty configuration
- `AssemblyCompany("")` - Empty company name
- `AssemblyProduct("IConnection")` - Product name
- `AssemblyCopyright("Copyright © 2008")` - Copyright notice
- `AssemblyTrademark("")` - Empty trademark
- `AssemblyCulture("")` - Neutral culture
- `ComVisible(false)` - Types not visible to COM by default
- `Guid("c8394d57-92d3-4ee1-b2f3-f8fabce0d487")` - COM typelib GUID
- `AssemblyVersion("1.06.0081")` - Assembly version
- `AssemblyFileVersion("1.06.0081")` - File version
### Invariants
- AssemblyVersion and AssemblyFileVersion are synchronized at "1.06.0081"
- ComVisible is set to false
- AssemblyCulture is empty, indicating this is not a satellite assembly
### Dependencies
**Imports:**
- `System.Reflection`
- `System.Runtime.CompilerServices`
- `System.Runtime.InteropServices`
**What depends on this:** Cannot be determined from source alone

View File

@@ -0,0 +1,43 @@
---
source_files:
- Common/DTS.Common.IConnection/SerialConnection/SerialConnection.cs
generated_at: "2026-04-17T15:43:20.559385+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "b99650f076547574"
---
# Documentation: SerialConnection
## 1. Purpose
`SerialConnection` is an implementation of the `IConnection` interface that wraps `System.IO.Ports.SerialPort` to provide serial port communication capabilities. It exists to allow serial-based devices to be used within a connection abstraction layer that appears designed primarily around socket-based communication patterns (evidenced by the APM-style `Begin*`/`End*` methods and `SocketFlags` property). This class enables the system to treat serial connections uniformly alongside other connection types.
## 2. Public Interface
### Properties
| Signature | Description |
|-----------|-------------|
| `bool IsSoftDisconnected { get; }` | Returns `true` if the unit is soft disconnected. Initialized to `false`. |
| `bool Connected { get; }` | Always returns `false`. Read-only property. |
| `string ConnectString => _PortName` | Returns the port name. |
| `System.Net.Sockets.SocketFlags Flags { get; set; }` | Socket flags property (inherited from interface, not used for serial). |
| `event EventHandler OnDisconnected` | Event for disconnection notification. |
### Methods
| Signature | Description |
|-----------|-------------|
| `void SoftConnect()` | Empty implementation. Comment indicates soft disconnect is not implemented for serial. |
| `void SoftDisconnect()` | Empty implementation. Comment indicates soft disconnect is not implemented for serial. |
| `void Create(string connectString, string hostIPAddress)` | Does nothing. Parameters are ignored. |
| `void Create(string PortName)` | Creates a new `SerialPort` instance with the provided port name and stores the name in `_PortName`. |
| `string GetConnectionData()` | Returns empty string. |
| `double GetCurrentDownloadRate()` | Returns `0D`. |
| `double GetCurrentUploadRate()` | Returns `0D`. |
| `void Dispose()` | Implements `IDisposable`. Calls `Dispose(true)` and suppresses finalization. |
| `IAsyncResult BeginConnect(AsyncCallback cb, object state)` | Opens the serial port. Returns `null`. Throws if `Port` is null or `_PortName` is empty. |
| `void EndConnect(IAsyncResult ar)` | Throws if `Port` is null. No other action. |
| `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)` | Returns `null`. Throws if `Port` is null. |
| `void EndDisconnect

View File

@@ -0,0 +1,48 @@
---
source_files:
- Common/DTS.Common.IConnection/SerialConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-17T16:08:48.740620+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "e0115c791f240810"
---
# Properties
### Purpose
This module contains assembly metadata for the `DASResource` assembly. It is a standard .NET AssemblyInfo file that defines version information, copyright, and COM visibility settings. The actual implementation code for DASResource is not present in this file—only assembly-level attributes.
### Public Interface
No public types, functions, or methods are defined in this file. The following assembly-level attributes are declared:
- `AssemblyTitle("DASResource")` - Sets the assembly title
- `AssemblyDescription("")` - Empty description
- `AssemblyConfiguration("")` - Empty configuration
- `AssemblyCompany("")` - Empty company name
- `AssemblyProduct("DASResource")` - Product name
- `AssemblyCopyright("Copyright © 2008 - 2009")` - Copyright notice
- `AssemblyTrademark("")` - Empty trademark
- `AssemblyCulture("")` - Neutral culture (not a satellite assembly)
- `ComVisible(false)` - Types not visible to COM by default
- `Guid("E20CF41A-9884-40f4-AD18-4F06A42FE36D")` - COM typelib GUID
- `AssemblyVersion("1.06.0081")` - Assembly version
- `AssemblyFileVersion("1.06.0081")` - File version
### Invariants
- AssemblyVersion and AssemblyFileVersion are synchronized at "1.06.0081"
- ComVisible is set to false, meaning no types are exposed to COM by default
- AssemblyCulture is empty, indicating this is not a satellite assembly
### Dependencies
**Imports:**
- `System.Reflection`
- `System.Runtime.InteropServices`
**What depends on this:** Cannot be determined from source alone. The actual DASResource implementation files would reference this assembly, but they are not provided.
### Gotchas
- The actual DASResource types and functionality are not visible in this file; only assembly metadata is present.
- The copyright date range (2008 - 2009) suggests this assembly was actively developed during that period.
- The description, company, and trademark fields are empty—typical of internal/proprietary projects.
---

View File

@@ -0,0 +1,61 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/HIDUSBConnection/HIDUSBConnection.cs
generated_at: "2026-04-17T15:42:39.330640+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "7d6d1a6f53e67671"
---
# HIDUSBConnection Documentation
## 1. Purpose
`HIDUSBConnection` implements the `IConnection` interface to provide asynchronous communication with USB Human Interface Device (HID) hardware. It targets specific DTS devices identified by Vendor ID `0x1CB9` and Product ID `0x0003`. The class wraps Windows HID API calls for device discovery, connection management, and bidirectional data transfer using input/output reports.
---
## 2. Public Interface
### Constants
| Name | Value | Description |
|------|-------|-------------|
| `HIDSLICE_PID` | `0x0003` | Product ID for target HID device |
| `DTS_VID` | `0x1CB9` | Vendor ID for DTS devices |
### Properties
| Signature | Description |
|-----------|-------------|
| `bool Connected { get; }` | Returns current connection state |
| `string ConnectString { get; }` | Returns the device path name set via `Create()` |
| `System.Net.Sockets.SocketFlags Flags { get; set; }` | Socket flags property (purpose unclear in HID context) |
### Events
| Signature | Description |
|-----------|-------------|
| `event EventHandler OnDisconnected` | Event raised when device disconnects (defined but never invoked in source) |
### Methods
| Signature | Description |
|-----------|-------------|
| `void Create(string ConnectString)` | Stores device path in `Device_Name` |
| `void Dispose()` | Public disposal method implementing IDisposable pattern |
| `IAsyncResult BeginConnect(AsyncCallback cb, object state)` | Queues async connect operation via ThreadPool |
| `void EndConnect(IAsyncResult ar)` | Opens handles to device, retrieves capabilities, initializes buffers |
| `static string GetFirstConnectString()` | Enumerates HID devices to find first matching VID/PID; returns device path or empty string |
| `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)` | Queues async disconnect operation |
| `void EndDisconnect(IAsyncResult asyncResult)` | Closes `_HIDHandle`, `_ReadHandle`, `_WriteHandle`; sets `_Connected = false` |
| `IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` | Queues async send operation; validates handles first |
| `int EndSend(IAsyncResult ar)` | Writes data to device via HID output reports; returns total bytes sent |
| `IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` | Queues async receive operation; validates handles first |
| `int EndReceive(IAsyncResult ar)` | Reads HID input report; copies to buffer (skipping first byte); returns bytes read or 0 on failure |
| `double GetCurrentDownloadRate()` | Returns `0D` (stub) |
| `double GetCurrentUploadRate()` | Returns `0D` (stub) |
| `string GetConnectionData()` | Returns empty string (stub) |
| `void Bind(int port)` | Throws `NotSupportedException` |
| `void Listen(int backlog)` | Throws `NotSupportedException` |
| `IAsyncResult BeginAccept(AsyncCallback callback, Object state)`

View File

@@ -0,0 +1,43 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/HIDUSBConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-17T16:07:59.588341+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "2a1f4602e744c5de"
---
# Properties
### Purpose
This module contains assembly metadata for the `WINUSBConnection` assembly. It is a standard .NET Framework assembly information file that defines versioning, copyright, and COM visibility settings for the WINUSB connection library, which appears to be part of a USB device communication subsystem.
### Public Interface
No public types or functions are defined in this module. It contains only assembly-level attributes:
- `AssemblyTitle`: "WINUSBConnection"
- `AssemblyDescription`: Empty
- `AssemblyCompany`: Empty
- `AssemblyProduct`: "WINUSBConnection"
- `AssemblyCopyright`: "Copyright © 2008"
- `ComVisible`: `false` - Types in this assembly are not visible to COM components
- `Guid`: "F3C369E6-BFFB-41bc-B8E8-A31094CED447" - Type library ID if exposed to COM
- `AssemblyVersion`: "1.06.0081"
- `AssemblyFileVersion`: "1.06.0081"
### Invariants
- The assembly version and file version are kept synchronized (both "1.06.0081").
- COM visibility is explicitly disabled at the assembly level.
### Dependencies
**Imports:**
- `System.Reflection`
- `System.Runtime.CompilerServices`
- `System.Runtime.InteropServices`
**Dependents:** Cannot be determined from this file alone. This assembly appears to be part of a larger USB connection framework.
### Gotchas
- The copyright year is 2008, indicating this is legacy code that may not have been updated recently.
- The version format "1.06.0081" uses a non-standard four-part scheme where the third component appears to be a build number (81) rather than following semantic versioning conventions.
---

View File

@@ -0,0 +1,196 @@
---
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

View File

@@ -0,0 +1,43 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/USBFramework/Properties/AssemblyInfo.cs
generated_at: "2026-04-17T16:07:59.587456+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "39b5c5af10b56ba5"
---
# Properties
### Purpose
This module contains assembly metadata for the `HIDFramework` assembly (note: the module directory is named "USBFramework" but the assembly title is "HIDFramework"). It provides versioning and COM interop configuration for what appears to be a Human Interface Device (HID) framework library within the USB connection subsystem.
### Public Interface
No public types or functions are defined in this module. It contains only assembly-level attributes:
- `AssemblyTitle`: "HIDFramework"
- `AssemblyDescription`: Empty
- `AssemblyCompany`: Empty
- `AssemblyProduct`: "HIDFramework"
- `AssemblyCopyright`: "Copyright © 2008"
- `ComVisible`: `false` - Types in this assembly are not visible to COM components
- `Guid`: "c655f31f-ca6c-4e9b-9480-934762d20a8c" - Type library ID if exposed to COM
- `AssemblyVersion`: "1.06.0081"
- `AssemblyFileVersion`: "1.06.0081"
### Invariants
- The assembly version and file version are kept synchronized (both "1.06.0081").
- COM visibility is explicitly disabled at the assembly level.
### Dependencies
**Imports:**
- `System.Reflection`
- `System.Runtime.CompilerServices`
- `System.Runtime.InteropServices`
**Dependents:** Cannot be determined from this file alone.
### Gotchas
- **Naming inconsistency:** The directory is named "USBFramework" but the `AssemblyTitle` and `AssemblyProduct` are set to "HIDFramework". This discrepancy could cause confusion when referencing the assembly or searching logs. It is unclear whether this is intentional or a historical oversight.
- The copyright year is 2008, indicating legacy code.
---

View File

@@ -0,0 +1,158 @@
---
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-17T15:37:40.541814+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "ead3f24c8ac15de2"
---
# USB Connection Module Documentation
## 1. Purpose
This module provides USB connectivity for DTS hardware devices through two distinct implementations: `CDCUSBConnection` for CDC (Communications Device Class) USB devices that present as virtual serial ports, and `WINUSBConnection` for devices using the WinUSB driver for direct bulk/interrupt transfers. Both classes implement the `IConnection` interface, providing a unified async communication pattern (Begin/End and Task-based async) for sending and receiving data. The module also includes `WinUsbDevice` (partial class in `WINUSBDeviceApi.cs`) which provides low-level P/Invoke bindings to the Windows WinUSB API.
---
## 2. Public Interface
### CDCUSBConnection (CDCUSBConnection.cs)
A connection class for CDC USB devices that uses `System.IO.Ports.SerialPort` for communication.
**Properties:**
- `bool IsSoftDisconnected { get; }` - Returns whether the device is soft-disconnected (always `false` for this implementation).
- `bool Connected { get; }` - Returns the current connection state.
- `string ConnectString { get; }` - Returns the device pathname.
- `string PortName { get; set; }` - The serial port name (e.g., "COM3").
- `System.Net.Sockets.SocketFlags Flags { get; set; }` - Socket flags (purpose unclear from source).
- `static IList<string> RegKeys { get; }` - Registry keys for device discovery.
**Constants:**
- `const int DTS_VENDOR_ID = 0x1CB9`
- `const string DTS_VENDOR_ID_STR = "VID_1CB9"`
- `const string DTS_TSR2_CDCUSB_PRODUCT_ID_STR = "PID_001A"`
**Methods:**
- `void Create(string connectString, string hostIPAddress)` - Parses the connect string to extract the port name from registry.
- `IAsyncResult BeginConnect(AsyncCallback cb, object state)` - Begins an async connection attempt.
- `void EndConnect(IAsyncResult ar)` - Completes the connection; configures and opens the serial port with default settings (9600 baud, 8 data bits, no parity, one stop bit).
- `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)` - Begins an async disconnect.
- `void EndDisconnect(IAsyncResult ar)` - Closes and disposes the serial port.
- `IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` - Begins an async send operation.
- `int EndSend(IAsyncResult ar)` - Completes the send; writes data to the serial port.
- `Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)` - Task-based async send wrapper.
- `IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` - Begins an async receive operation.
- `int EndReceive(IAsyncResult ar)` - Completes the receive; blocks until data is available.
- `void Dispose()` - Disposes the connection.
- `void SoftConnect()` - No-op (empty body).
- `void SoftDisconnect()` - No-op (empty body).
- `double GetCurrentUploadRate()` - Returns `0D`.
- `double GetCurrentDownloadRate()` - Returns `0D`.
- `string GetConnectionData()` - Returns empty string.
**Events:**
- `event EventHandler OnDisconnected` - Event for disconnection notification (never raised in source).
**Not Supported:**
- `BeginAccept`, `EndAccept`, `Listen`, `Bind` - Throw `NotSupportedException`.
---
### WINUSBConnection (WINUSBConnection.cs)
A connection class for WinUSB devices using direct USB transfers via the WinUSB API.
**Properties:**
- `bool IsSoftDisconnected { get; }` - Returns whether the device is soft-disconnected (always `false` for this implementation).
- `bool Connected { get; }` - Returns the current connection state.
- `string ConnectString { get; }` - Returns the device connection string.
- `System.Net.Sockets.SocketFlags Flags { get; set; }` - Socket flags (purpose unclear from source).
**Methods:**
- `void Create(string connectString, string hostIPAddress)` - Stores the connect string.
- `IAsyncResult BeginConnect(AsyncCallback cb, object state)` - Begins an async connection; validates not already connected.
- `void EndConnect(IAsyncResult ar)` - Completes the connection; creates `WinUsbDevice` instance, gets device handle, and initializes device.
- `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)` - Begins an async disconnect.
- `void EndDisconnect(IAsyncResult ar)` - Disposes the `WinUsbDevice` via `DisposeSliceDev()`.
- `IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` - Begins an async send; validates connection and parameters.
- `int EndSend(IAsyncResult ar)` - Completes the send; uses `SendViaInterruptTransfer` or `SendViaBulkTransfer` based on `MyDevInfo.UseHybridBulkIntMode`.
- `Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)` - Task-based async send wrapper.
- `IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)` - Begins an async receive.
- `int EndReceive(IAsyncResult ar)` - Completes the receive; uses `ReadViaBulkTransfer` with a polling loop.
- `void Dispose()` - Disposes the connection and device management resources.
- `void SoftConnect()` - No-op (empty body).
- `void SoftDisconnect()` - No-op (empty body).
- `double GetCurrentUploadRate()` - Returns `0D`.
- `double GetCurrentDownloadRate()` - Returns `0D`.
- `string GetConnectionData()` - Returns empty string.
**Events:**
- `event EventHandler OnDisconnected` - Event for disconnection notification (never raised in source).
**Not Supported:**
- `BeginAccept`, `EndAccept`, `Listen`, `Bind` - Throw `NotSupportedException`.
**Nested Classes:**
- `WinUSBRecAsyncResult` - Implements `IAsyncResult` with additional `Buffer`, `Offset`, `Size` properties.
---
### WinUsbDevice (WINUSBDeviceApi.cs) - Internal Partial Class
Low-level P/Invoke bindings to `winusb.dll`.
**Constants:**
- `const uint DEVICE_SPEED = 1`
- `const byte USB_ENDPOINT_DIRECTION_MASK = 0x80`
**Enums:**
- `PolicyType` - Pipe policy types: `ShortPacketTerminate`, `AutoClearStall`, `PipeTransferTimeout`, `IgnoreShortPackets`, `AllowPartialReads`, `AutoFlush`, `RawIO`.
- `USBDPipeTypes` - Pipe types: `UsbdPipeTypeControl`, `UsbdPipeTypeIsochronous`, `UsbdPipeTypeBulk`, `UsbdPipeTypeInterrupt`.
- `USBDeviceSpeeds` - Device speeds: `UsbLowSpeed = 1`, `UsbFullSpeed`, `UsbHighSpeed`.
**Structs:**
- `USBConfigurationDescriptor` - USB configuration descriptor with fields: `bLength`, `bDescriptorType`, `wTotalLength`, `bNumInterfaces`, `bConfigurationValue`, `iConfiguration`, `bmAttributes`, `MaxPower`.
- `USBInterfaceDescriptor` - USB interface descriptor with fields: `bLength`, `bDescriptorType`, `bInterfaceNumber`, `bAlternateSetting`, `bNumEndpoints`, `bInterfaceClass`, `bInterfaceSubClass`, `bInterfaceProtocol`, `iInterface`.
- `WinUSBPipeInformation` - Pipe information with fields: `PipeTypes`, `PipeId`, `MaximumPacketSize`, `Interval`.
- `WinUSBSetupPacket` - Setup packet for control transfers with fields: `RequestType`, `Request`, `Value`, `Index`, `Length`.
**P/Invoke Functions (all from `winusb.dll`):**
- `WinUsb_ControlTransfer(IntPtr interfaceHandle, WinUSBSetupPacket setupPacket, byte[] buffer, uint bufferLength, ref uint lengthTransferred, IntPtr overlapped)`
- `WinUsb_Free(IntPtr interfaceHandle)`
- `WinUsb_Initialize(SafeFileHandle deviceHandle, ref IntPtr interfaceHandle)`
- `WinUsb_QueryDeviceInformation(IntPtr interfaceHandle, uint informationType, ref uint bufferLength, ref byte buffer)`
- `WinUsb_QueryInterfaceSettings(IntPtr interfaceHandle, byte alternateInterfaceNumber, ref USBInterfaceDescriptor usbAltInterfaceDescriptor)`
- `WinUsb_QueryPipe(IntPtr interfaceHandle, byte alternateInterfaceNumber, byte pipeIndex, ref WinUSBPipeInformation pipeInformation)`
- `WinUsb_ReadPipe(IntPtr interfaceHandle, byte pipeId, byte[] buffer, uint bufferLength, ref uint lengthTransferred, IntPtr overlapped)`
- `WinUsb_SetPipePolicy(IntPtr interfaceHandle, byte pipeId, uint policyType, uint valueLength, ref byte Value)` - For byte policy values.
- `WinUsb_SetPipePolicy1(IntPtr interfaceHandle, byte pipeId, uint policyType, uint valueLength, ref uint Value)` - For `uint` policy values (alias for `WinUsb_SetPipePolicy`).
- `WinUsb_WritePipe(IntPtr interfaceHandle, Byte pipeId, byte[] buffer, uint bufferLength, ref uint lengthTransferred, IntPtr overlapped)`
---
### UsbRecAsyncResult (CDCUSBConnection.cs)
Helper class implementing `IAsyncResult` for async operations.
**Properties:**
- `object AsyncState { get; set; }`
- `WaitHandle AsyncWaitHandle { get; set; }`
- `bool CompletedSynchronously { get; set; }`
- `bool IsCompleted { get; set; }`
- `byte[] buffer { get; set; }`
- `int Offset { get; set; }`
- `int Size { get; set; }`
---
## 3. Invariants
1. **Connection State Consistency**: `_Connected`/`Connected` must be `false` when `_sliceDev`/`_comPort` is `null` or disposed.
2. **Single Connection**: `WINUSBConnection.BeginConnect` throws `NotConnectedException` if already connected (`_sliceDev != null || Connected`).
3. **Thread Safety**: `WINUSBConnection` uses a `Mutex` named `"USBConnection"` to protect device initialization and disposal operations.
4. **Dispose Guard**: Both connection classes use `Disposed` and `Disposing` flags to prevent double-disposal.
5. **Parameter Validation**: `BeginSend` and `BeginReceive` validate that `buffer` is not null/empty

View File

@@ -0,0 +1,43 @@
---
source_files:
- Common/DTS.Common.IConnection/USBConnection/WINUSBConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-17T16:07:59.584637+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "bc07a36281104a6a"
---
# Properties
### Purpose
This module contains assembly metadata for the `WINUSBConnection` assembly. It is a standard .NET Framework assembly information file that defines versioning, copyright, and COM visibility settings for the WINUSB connection library, which appears to be part of a USB device communication subsystem.
### Public Interface
No public types or functions are defined in this module. It contains only assembly-level attributes:
- `AssemblyTitle`: "WINUSBConnection"
- `AssemblyDescription`: Empty
- `AssemblyCompany`: Empty
- `AssemblyProduct`: "WINUSBConnection"
- `AssemblyCopyright`: "Copyright © 2008"
- `ComVisible`: `false` - Types in this assembly are not visible to COM components
- `Guid`: "F3C369E6-BFFB-41bc-B8E8-A31094CED447" - Type library ID if exposed to COM
- `AssemblyVersion`: "1.06.0081"
- `AssemblyFileVersion`: "1.06.0081"
### Invariants
- The assembly version and file version are kept synchronized (both "1.06.0081").
- COM visibility is explicitly disabled at the assembly level.
### Dependencies
**Imports:**
- `System.Reflection`
- `System.Runtime.CompilerServices`
- `System.Runtime.InteropServices`
**Dependents:** Cannot be determined from this file alone. This assembly appears to be part of a larger USB connection framework.
### Gotchas
- The copyright year is 2008, indicating this is legacy code that may not have been updated recently.
- The version format "1.06.0081" uses a non-standard four-part scheme where the third component appears to be a build number (81) rather than following semantic versioning conventions.
---