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,193 @@
---
source_files:
- Common/DTS.Common.IConnection/EthernetConnection/RESTConnection.cs
- Common/DTS.Common.IConnection/EthernetConnection/EthernetConnection.cs
generated_at: "2026-04-16T11:48:39.886921+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "21dfcca726b35e5d"
---
# Documentation: IConnection Implementations
## 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, connection lifecycle, and keep-alive configuration for hardware devices. `RESTConnection` is a stub/skeleton implementation that immediately completes all operations without actual network I/O, designed to satisfy the `IConnection` interface contract for scenarios where REST-based communication replaces traditional socket connections.
---
## 2. Public Interface
### EthernetConnection (DTS.Common)
#### Properties
| Signature | Description |
|-----------|-------------|
| `bool IsSoftDisconnected { get; private set; }` | Returns `true` if the connection has been soft-disconnected. |
| `bool RequiresKeepAliveReset { get; set; }` | When `true`, `SoftConnect()` performs additional handshake on command port 8200 before connecting. |
| `Socket Sock` | The underlying `System.Net.Sockets.Socket` instance. Publicly accessible. |
| `bool Connected` | Returns `Sock != null && Sock.Connected`. |
| `string ConnectString` | Returns the connection string (format: `"host:port"`). |
| `SocketFlags Flags { get; set; }` | Socket flags used for send/receive operations. |
#### Events
| Signature | Description |
|-----------|-------------|
| `event EventHandler OnDisconnected` | Raised when `KeepAliveErrorReceived()` is invoked, indicating connection loss. |
#### Methods
| Signature | Description |
|-----------|-------------|
| `void Create(string connectString, string hostIPAddress)` | Creates and configures the underlying socket with keep-alive settings. Stores connection parameters. |
| `Socket CreateSock(string connectString, string hostIPAddress)` | Factory method that creates a configured `Socket` with TCP NoDelay, KeepAlive, and buffer sizes from `DFConstantsAndEnums`. Binds to `hostIPAddress` if provided. |
| `void SoftDisconnect()` | If `HardwareConstants.AllowSoftDisconnects` is true, disconnects and disposes the socket, sets `IsSoftDisconnected = true`. |
| `void SoftConnect()` | Reconnects a soft-disconnected socket. Optionally performs keep-alive reset via port 8200 if `RequiresKeepAliveReset` is true. Retries connection up to 3 times. |
| `void KeepAliveErrorReceived()` | Shuts down, closes, and disposes the socket; invokes `OnDisconnected` event. |
| `string GetConnectionData()` | Returns a string with local and remote endpoints, or empty string if unavailable. |
| `IAsyncResult BeginConnect(AsyncCallback cb, object state)` | Begins asynchronous connection. Throws if socket is null, `Connect_String` is empty/malformed, or port is invalid. |
| `void EndConnect(IAsyncResult ar)` | Completes the connection. Logs success with endpoints. |
| `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, object state)` | Begins asynchronous disconnect. Throws `SocketException(WSAEISCONN)` if socket is not connected. |
| `void EndDisconnect(IAsyncResult asyncResult)` | Completes the disconnect operation. |
| `IAsyncResult BeginAccept(AsyncCallback callback, object state)` | Begins asynchronous accept for incoming connections. |
| `IConnection EndAccept(IAsyncResult asyncResult)` | 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 send; returns bytes sent. Sets `Sock = null` on exception. |
| `Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)` | Task-based async wrapper over BeginSend/EndSend. |
| `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 receive; returns bytes received. |
| `void Bind(int port)` | Binds socket to local endpoint resolved via DNS. |
| `void Listen(int backlog)` | Starts listening for incoming connections. |
| `void Dispose()` | Disposes the socket and resources. |
---
### RESTConnection (DTS.DASLib.Connection)
#### Properties
| Signature | Description |
|-----------|-------------|
| `bool IConnection.IsSoftDisconnected` | Always returns `false`. |
| `SocketFlags IConnection.Flags { get; set; }` | Stored value, defaults to `SocketFlags.None`. |
| `string IConnection.ConnectString` | Returns the stored `_ConnectString`. |
| `bool IConnection.Connected` | Returns `_bConnected` (set by `BeginConnect`/`BeginDisconnect`). |
#### Events
| Signature | Description |
|-----------|-------------|
| `event EventHandler OnDisconnected` | Defined 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 private fields. |
| `IAsyncResult IConnection.BeginConnect(AsyncCallback callback, object callbackObject)` | Sets `_bConnected = true`; returns an already-completed `AsyncNoResult`. |
| `void IConnection.EndConnect(IAsyncResult ar)` | No-op. |
| `IAsyncResult IConnection.BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state)` | Sets `_bConnected = false`; returns an already-completed `AsyncNoResult`. |
| `void IConnection.EndDisconnect(IAsyncResult asyncResult)` | No-op. |
| `IAsyncResult IConnection.BeginAccept(AsyncCallback callback, object state)` | Returns an already-completed `AsyncNoResult`. |
| `IConnection IConnection.EndAccept(IAsyncResult asyncResult)` | Returns `this`. |
| `IAsyncResult IConnection.BeginSend(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend, AsyncCallback callback, object callbackObject)` | Returns an already-completed `AsyncNoResult`. |
| `int IConnection.EndSend(IAsyncResult ar)` | Returns `0`. |
| `IAsyncResult IConnection.BeginReceive(byte[] receiveBuffer, int bufferStartOffset, int maxSizeToReceive, AsyncCallback callback, object callbackObject)` | Returns an already-completed `AsyncNoResult`. |
| `int IConnection.EndReceive(IAsyncResult ar)` | Returns `0`. |
| `Task<int> IConnection.SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)` | Task wrapper over BeginSend/EndSend. |
| `void IConnection.Bind(int port)` | No-op (commented as "not really needed"). |
| `void IConnection.Listen(int backlog)` | No-op. |
| `void IConnection.KeepAliveErrorReceived()` | No-op. |
| `void IConnection.SoftConnect()` | No-op. |
| `void IConnection.SoftDisconnect()` | No-op. |
| `string IConnection.GetConnectionData()` | Returns `"$(_ConnectString) - $(_hostIPAddress)"`. |
| `void Dispose()` | Standard dispose pattern; no actual resource cleanup. |
#### Internal Class: AsyncNoResult
An `IAsyncResult` implementation used to represent immediately-completed operations.
| Member | Description |
|--------|-------------|
| `bool IsCompleted` | Returns `true` if `_executionState != PENDING`. |
| `WaitHandle AsyncWaitHandle` | Lazily-created `ManualResetEvent`. |
| `object AsyncState` | Returns the state object passed to constructor. |
| `bool CompletedSynchronously` | Returns `true` if `_executionState == COMPLETED_SYNC`. |
| `void SetCompleted(bool completedSync)` | Transitions from PENDING to COMPLETED_SYNC or COMPLETED_ASYNC; invokes callback. Throws `InvalidOperationException` if already completed. |
---
## 3. Invariants
### EthernetConnection
- **Connect string format**: Must be `"hostname:port"` where port is a valid integer. Validated in `BeginConnect`.
- **Socket creation prerequisite**: `Sock` must be created via `Create()` before calling `BeginConnect`, `BeginSend`, `BeginReceive`, `BeginAccept`, `BeginDisconnect`, `Bind`, or `Listen`. All these methods throw if `Sock` is null.
- **Connection state for send**: `BeginSend` throws if `Sock.Connected` is `false`.
- **Connection state for disconnect**: `BeginDisconnect` throws `SocketException(DFConstantsAndEnums.WSAEISCONN)` if `Sock.Connected` is `false`.
- **Callback requirement**: `BeginSend` and `BeginReceive` throw if callback is null.
- **Soft disconnect gate**: `SoftDisconnect()` and `SoftConnect()` do nothing if `HardwareConstants.AllowSoftDisconnects` is `false`.
- **Keep-alive configuration**: All sockets created via `CreateSock` have keep-alive enabled with values from `DFConstantsAndEnums.LocalKeepAliveTimeOutMS` and `DFConstantsAndEnums.LocalKeepAliveRetryIntervalMS`.
### RESTConnection
- **No actual I/O**: All Begin* methods return immediately with `CompletedSynchronously = true`.
- **Send/Receive return zero**: `EndSend` and `EndReceive` always return `0`.
- **IsSoftDisconnected**: Always `false`.
- **AsyncNoResult state machine**: `SetCompleted` can only be called once; subsequent calls throw `InvalidOperationException`.
---
## 4. Dependencies
### EthernetConnection depends on:
- `DTS.Common.Interface.Connection.IConnection` - Interface being implemented.
- `DTS.Common.Utilities.Logging.APILogger` - Used for logging throughout.
- `DTS.Common.DASResource.DFConstantsAndEnums` - Provides `SendBufferSizeBytes`, `ReceiveBufferSizeBytes`, `LocalKeepAliveTimeOutMS`, `LocalKeepAliveRetryIntervalMS`, `WSAEISCONN`.
- `DTS.Common.Enums.DASFactory` - Namespace imported but no direct usage visible in source.
- `DTS.Common.Enums.Hardware.HardwareConstants.AllowSoftDisconnects` - Controls soft disconnect behavior.
- `System.Net.Sockets.Socket` - Core socket functionality.
- `System.Net.Dns`, `System.Net.IPEndPoint`, `System.Net.IPAddress` - Network addressing.
### RESTConnection depends on:
- `DTS.Common.Interface.Connection.IConnection` - Interface being implemented.
- `DTS.Common.Utilities.Logging` - Namespace imported but no direct usage visible in source.
- `System.Net.Sockets.SocketFlags` - Used for the `Flags` property.
- `System.Threading` - `ManualResetEvent`, `Interlocked`, `Thread.VolatileRead`.
### What depends on these modules:
- Unclear from source alone. Both implement `IConnection`, suggesting consumers depend on that interface rather than concrete types directly.
---
## 5. Gotchas
### EthernetConnection
1. **Dead code in `Create(string connectString)`**: The single-parameter overload contains a commented-out recursive call with the comment `"this is recursive!"`. The method body is effectively empty and does nothing.
2. **Counterintuitive error code in `BeginDisconnect`**: When the socket is *not* connected, `BeginDisconnect` throws `SocketException(WSAEISCONN)`. The constant name suggests "is connected" which is the opposite of the actual condition being checked.
3. **SoftConnect has hardcoded command port logic**: When `RequiresKeepAliveReset` is true, `SoftConnect()` connects to port 8200 and sends `<60,5,4>` before connecting to the actual target port. This appears to be device-specific protocol behavior embedded in the connection class.
4. **Socket is public and mutable**: The `Sock` field is public, allowing external code to modify or replace it, potentially bypassing the class's invariants.
5. **EndSend nullifies socket on exception**: If `EndSend` throws, it sets `Sock = null` before re-throwing. This is not documented and could surprise callers.
6. **Thread.Sleep in SoftConnect/SoftDisconnect**: Both methods use `Thread.Sleep` (50ms and 100ms/1000ms respectively), which blocks the calling thread.
### RESTConnection
1. **No-op implementations**: Most methods do nothing or return immediately. This is by design but could cause confusion if developers expect actual network behavior.
2. **OnDisconnected never raised**: The event is declared but never invoked anywhere in the class.
3. **Namespace mismatch**: The file path suggests `DTS.Common.IConnection` but the namespace is `DTS.DASLib.Connection`. This may indicate a historical refactoring or organizational inconsistency.
4. **Unused imports**: `System.CodeDom`, `System.Collections.Specialized`, `System.Runtime.Remoting.Messaging` are imported but not used in the source.

View File

@@ -0,0 +1,40 @@
---
source_files:
- Common/DTS.Common.IConnection/EthernetConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:49:20.386594+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "21f98ce79850642b"
---
# Documentation: EthernetConnection Assembly Metadata
## 1. Purpose
This source file defines the assembly metadata for the `EthernetConnection` component, which appears to be part of the `DTS.Common.IConnection` subsystem. Its role is to establish the assembly's identity, version, and visibility configuration within the larger application. It provides the manifest information required by the .NET runtime to locate and bind this specific library.
## 2. Public Interface
This file does not contain executable logic or public classes. It strictly defines assembly-level attributes.
* **`AssemblyTitle`**: Set to `"EthernetConnection"`.
* **`AssemblyProduct`**: Set to `"EthernetConnection"`.
* **`AssemblyVersion`**: Set to `"1.06.0081"`.
* **`AssemblyFileVersion`**: Set to `"1.06.0081"`.
* **`ComVisible`**: Set to `false`. This prevents types within this assembly from being visible to COM components by default.
* **`Guid`**: Set to `"355ff6bb-d823-4853-93aa-4c12fd8c350e"`. This serves as the unique identifier for the assembly if exposed to COM.
## 3. Invariants
* **COM Visibility:** Types within this assembly are not COM-visible by default (`ComVisible(false)`). To expose a specific type to COM, that type must be explicitly marked with `ComVisible(true)`.
* **Version Consistency:** The `AssemblyVersion` and `AssemblyFileVersion` are currently synchronized at `"1.06.0081"`.
* **Identity:** The `Guid` attribute provides a unique, immutable identifier for the assembly's type library.
## 4. Dependencies
* **Framework Dependencies:**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
* **System Context:** Based on the file path (`Common/DTS.Common.IConnection/...`), this assembly likely implements an `IConnection` interface or related contracts defined elsewhere in the `DTS.Common` namespace, but the specific implementation details are not present in this file.
## 5. Gotchas
* **Hardcoded Versions:** The version numbers (`1.06.0081`) are hardcoded. While the comments suggest using `*` for auto-incrementing build/revision numbers, this feature is currently disabled.
* **Missing Metadata:** The `AssemblyDescription`, `AssemblyConfiguration`, `AssemblyCompany`, and `AssemblyTrademark` fields are initialized as empty strings. This may complicate automated documentation generation or assembly property inspection in production environments.
* **Legacy Timestamp:** The `AssemblyCopyright` attribute lists 2008, indicating this is a mature or legacy codebase.

View File

@@ -0,0 +1,48 @@
---
source_files:
- Common/DTS.Common.IConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:49:19.908878+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "344d5d1b6c8a507c"
---
# Documentation: DTS.Common.IConnection
## 1. Purpose
This file serves as the assembly manifest configuration for the `DTS.Common.IConnection` library. It provides versioning, metadata, and COM visibility settings for the compiled assembly. Based on the assembly name `IConnection`, this module is intended to define the contract or interface for connection-related logic within the larger DTS system, though the specific interface definitions are not contained within this configuration file.
## 2. Public Interface
This source file does not contain any public classes, methods, or interfaces. It strictly defines assembly-level attributes.
**Defined Attributes:**
* `AssemblyTitle`: Set to `"IConnection"`.
* `AssemblyDescription`: Empty string.
* `AssemblyConfiguration`: Empty string.
* `AssemblyCompany`: Empty string.
* `AssemblyProduct`: Set to `"IConnection"`.
* `AssemblyCopyright`: Set to `"Copyright © 2008"`.
* `AssemblyTrademark`: Empty string.
* `AssemblyCulture`: Empty string.
* `ComVisible`: Set to `false`.
* `Guid`: Set to `"c8394d57-92d3-4ee1-b2f3-f8fabce0d487"`.
* `AssemblyVersion`: Set to `"1.06.0081"`.
* `AssemblyFileVersion`: Set to `"1.06.0081"`.
## 3. Invariants
* **COM Visibility:** The assembly is explicitly configured with `ComVisible(false)`, ensuring types within this assembly are not exposed to COM components by default.
* **Versioning:** The assembly version (`1.06.0081`) is strictly defined and matches the file version.
## 4. Dependencies
**Internal Dependencies:**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
**External Dependencies:**
* None identified from this source file alone.
## 5. Gotchas
* **Missing Description:** The `AssemblyDescription` attribute is an empty string, which may hinder automatic documentation generation or assembly browsing tools.
* **Legacy Date:** The copyright string indicates a base year of 2008. Developers should verify if this metadata has been maintained or if it reflects the original creation date without updates.
* **Missing Logic:** This file contains only metadata; the actual `IConnection` interface and its members are defined in other files within this project not included in the provided source.

View File

@@ -0,0 +1,84 @@
---
source_files:
- Common/DTS.Common.IConnection/SerialConnection/SerialConnection.cs
generated_at: "2026-04-16T11:48:46.182914+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "4992256eaf51da73"
---
# Documentation: DTS.Common.SerialConnection.SerialConnection
## 1. Purpose
The `SerialConnection` class provides a wrapper around `System.IO.Ports.SerialPort` to implement the `IConnection` interface. Its primary role is to abstract serial port communication behind an asynchronous, socket-like API (APM pattern). This allows serial devices to be handled uniformly within a system designed around generic connection interfaces, mimicking the behavior of network sockets for operations like connecting, sending, and receiving data.
## 2. Public Interface
**Class:** `SerialConnection` (implements `IConnection`)
**Properties:**
* `bool Connected { get; }`: Returns the connection state. **Note:** Currently hardcoded to return `false`.
* `bool IsSoftDisconnected { get; }`: Returns `true` if the unit is soft disconnected.
* `string ConnectString { get; }`: Returns the stored port name (`_PortName`).
* `System.Net.Sockets.SocketFlags Flags { get; set; }`: Gets or sets socket flags.
**Events:**
* `EventHandler OnDisconnected`: Event raised upon disconnection.
**Methods:**
* `void Create(string PortName)`: Instantiates the internal `SerialPort` object.
* `void Create(string connectString, string hostIPAddress)`: Overload that currently performs no operation.
* `void SoftConnect()`: Intended to connect the unit; currently empty.
* `void SoftDisconnect()`: Intended to disconnect the unit; currently empty.
* `string GetConnectionData()`: Returns an empty string.
* `double GetCurrentDownloadRate()`: Returns `0.0`.
* `double GetCurrentUploadRate()`: Returns `0.0`.
**Connection Lifecycle (APM Pattern):**
* `IAsyncResult BeginConnect(AsyncCallback cb, object state)`: Opens the serial port. Throws `Exception` if `Port` is null or `_PortName` is empty. Returns `null`.
* `void EndConnect(IAsyncResult ar)`: Validates `Port` exists. Throws `Exception` if null.
**Data Transfer (APM Pattern):**
* `IAsyncResult BeginSend(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`: Begins an asynchronous write to the serial port. Throws `Exception` if `Port` or `cb` is null.
* `int EndSend(IAsyncResult ar)`: Completes the asynchronous write. Returns `Port.BytesToWrite`.
* `Task<int> SendAsync(byte[] sendBuffer, int bufferStartOffset, int bufferSizeToSend)`: Task-based async wrapper for `BeginSend`/`EndSend`.
* `IAsyncResult BeginReceive(byte[] buffer, int offset, int size, AsyncCallback cb, object state)`: Begins an asynchronous read from the serial port. Throws `Exception` if `Port` or `cb` is null.
* `int EndReceive(IAsyncResult ar)`: Completes the asynchronous read. Returns the number of bytes read.
**Server/Socket Mimicry Methods:**
* `IAsyncResult BeginAccept(AsyncCallback callback, Object state)`: Returns `null`. Throws if `Port` is null.
* `IConnection EndAccept(IAsyncResult asyncResult)`: Returns a new instance of `SerialConnection`. Throws if `Port` is null.
* `void Bind(int port)`: No-op. Throws if `Port` is null.
* `void Listen(int backlog)`: No-op. Throws if `Port` is null.
* `IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback cb, Object state)`: Returns `null`. Throws if `Port` is null.
* `void EndDisconnect(IAsyncResult asyncResult)`: No-op. Throws if `Port` is null.
**IDisposable:**
* `void Dispose()`: Disposes the `SerialPort` and suppresses finalization.
## 3. Invariants
* **Null Checks:** Nearly all public methods (except `Create` overloads and disposal methods) throw a `System.Exception` if the protected `Port` field is null.
* **Callback Validation:** `BeginSend` and `BeginReceive` throw a `System.Exception` if the provided `AsyncCallback` is null.
* **Connection String:** `BeginConnect` throws a `System.Exception` if `_PortName` is null or empty.
* **Disposal:** Once `Dispose(bool disposing)` runs, the `Port` is closed and set to null; subsequent calls return immediately.
## 4. Dependencies
* **Dependencies (Imports):**
* `DTS.Common.Interface.Connection`: Defines the `IConnection` interface this class implements.
* `System.IO.Ports`: Provides the underlying `SerialPort` functionality.
* `System`: Basic system types, exceptions, and async patterns.
* `System.Threading.Tasks`: Used for `Task`-based async operations (`SendAsync`).
* **Dependents:** Unknown from source alone (consumers of `IConnection`).
## 5. Gotchas
* **Critical Bug in `Create(string PortName)`:** The method assigns `_PortName` *after* attempting to initialize `Port`.
```csharp
Port = new SerialPort(_PortName); // _PortName is likely null or stale here
_PortName = PortName; // Assigned too late
```
This results in the `SerialPort` being instantiated with an incorrect or empty port name, likely causing connection failures.
* **Hardcoded `Connected` Property:** The `Connected` property is hardcoded to return `false` and is never updated by `BeginConnect` or `EndConnect`. Code relying on this property to verify connectivity will fail.
* **APM Return Values:** `BeginConnect`, `BeginDisconnect`, and `BeginAccept` return `null` instead of a valid `IAsyncResult`. This may break callers expecting a valid state object from standard APM implementations.
* **`EndSend` Return Value:** `EndSend` returns `Port.BytesToWrite` (the number of bytes waiting in the send buffer), not the number of bytes successfully written (which is the standard behavior for socket `EndSend`).
* **Soft Disconnect Implementation:** `SoftConnect` and `SoftDisconnect` are empty methods. The `IsSoftDisconnected` property is initialized to `false` but is never set by any method in the class.
* **No-op Methods:** `Bind`, `Listen`, and `KeepAliveErrorReceived` perform no actions but throw exceptions if `Port` is null, making them effectively validation checks with no side effects.

View File

@@ -0,0 +1,46 @@
---
source_files:
- Common/DTS.Common.IConnection/SerialConnection/Properties/AssemblyInfo.cs
generated_at: "2026-04-16T11:49:55.465329+00:00"
model: "zai-org/GLM-5-FP8"
schema_version: 1
sha256: "387f9fdb03f26ec5"
---
# Documentation: AssemblyInfo.cs (SerialConnection)
## 1. Purpose
This file provides assembly-level metadata and configuration attributes for the `DTS.Common.IConnection.SerialConnection` assembly. It defines the assembly's identity, version information, and COM visibility settings. As a standard `AssemblyInfo.cs` file, it does not contain executable logic but serves as a manifest for the compiled library, presumably handling serial port communication based on the naming conventions.
## 2. Public Interface
This file does not expose any public classes, methods, or functions. It strictly contains assembly-level attributes.
**Attributes Defined:**
* **`AssemblyTitle`**: Set to `"SerialConnection.cs"`.
* **`AssemblyDescription`**: Empty.
* **`AssemblyConfiguration`**: Empty.
* **`AssemblyCompany`**: Empty.
* **`AssemblyProduct`**: Set to `"SerialConnection.cs"`.
* **`AssemblyCopyright`**: Set to `"Copyright © 2009"`.
* **`AssemblyCulture`**: Empty (neutral culture).
* **`ComVisible`**: Set to `false`. Types in this assembly are not visible to COM components.
* **`Guid`**: Set to `"8d3a85de-321a-48fb-8f9e-f1d9594ee423"`.
* **`AssemblyVersion`**: Set to `"1.06.0081"`.
* **`AssemblyFileVersion`**: Set to `"1.06.0081"`.
## 3. Invariants
* **Version Consistency:** The `AssemblyVersion` and `AssemblyFileVersion` are synchronized at `"1.06.0081"`.
* **COM Visibility:** The assembly is explicitly marked as not visible to COM (`ComVisible(false)`); this behavior is constant unless overridden by specific types.
* **Identity:** The assembly is uniquely identified by the GUID `8d3a85de-321a-48fb-8f9e-f1d9594ee423` if exposed to COM in the future.
## 4. Dependencies
* **Internal Imports:**
* `System.Reflection`
* `System.Runtime.CompilerServices`
* `System.Runtime.InteropServices`
* **System Context:** This file is a component of the `DTS.Common.IConnection.SerialConnection` project. The specific runtime dependencies of the assembly logic are not visible in this file.
## 5. Gotchas
* **Misnamed Title/Product:** The `AssemblyTitle` and `AssemblyProduct` attributes are set to `"SerialConnection.cs"`. This appears to be a configuration error where a source filename was entered instead of a human-readable product name (e.g., `"SerialConnection"`).
* **Legacy Date:** The copyright string suggests the code originates from 2009. Developers should verify compatibility with modern .NET runtimes or operating systems, as serial communication APIs can change between framework versions.
* **Empty Description:** The `AssemblyDescription` attribute is empty, providing no inline documentation regarding the specific responsibilities of this assembly.

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.