11 KiB
source_files, generated_at, model, schema_version, sha256
| source_files | generated_at | model | schema_version | sha256 | ||
|---|---|---|---|---|---|---|
|
2026-04-16T02:09:04.702798+00:00 | Qwen/Qwen3-Coder-Next-FP8 | 1 | 21dfcca726b35e5d |
Documentation: RESTConnection and EthernetConnection Classes
1. Purpose
This module provides two concrete implementations of the IConnection interface for network communication: RESTConnection, a stub implementation that simulates connection operations without actual network activity (intended for REST-based or mock scenarios), and EthernetConnection, a full-featured implementation using System.Net.Sockets.Socket for real-time Ethernet communication with hardware devices. RESTConnection exists to satisfy interface contracts in environments where actual socket communication is unnecessary or undesirable (e.g., testing, REST API interactions), while EthernetConnection handles real socket operations including connection establishment, data transfer, keep-alive configuration, and soft disconnect/reconnect workflows for embedded hardware.
2. Public Interface
RESTConnection (namespace DTS.DASLib.Connection)
-
bool IConnection.IsSoftDisconnected => false
Always returnsfalse; does not support soft disconnect semantics. -
SocketFlags IConnection.Flags { get; set; }
Gets/sets socket flags (unused; alwaysSocketFlags.None). -
string IConnection.ConnectString => _ConnectString
Returns the stored connection string (e.g.,"host:port"), set viaCreate. -
bool IConnection.Connected => _bConnected
Returns internal_bConnectedstate (set totrueonBeginConnect,falseonBeginDisconnect). -
event EventHandler OnDisconnected
Declared but never raised (no invocation in source). -
void IConnection.Create(string connectString)
StoresconnectStringin_ConnectString. -
void IConnection.Create(string connectString, string hostIPAddress)
StoresconnectStringandhostIPAddressin respective fields. -
IAsyncResult IConnection.BeginConnect(AsyncCallback callback, object callbackObject)
Sets_bConnected = trueand returns a synchronously completedIAsyncResultviaGetAlreadyCompleted. -
IAsyncResult IConnection.BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state)
Sets_bConnected = falseand returns a synchronously completedIAsyncResult. -
IAsyncResult IConnection.BeginSend(...)/BeginReceive(...)/BeginAccept(...)
All return synchronously completedIAsyncResultinstances; no actual I/O. -
void IConnection.EndConnect(...)/EndDisconnect(...)/EndSend(...)/EndReceive(...)/EndAccept(...)
No-op implementations.EndSend/EndReceivereturn0.EndAcceptreturnsthis. -
void IConnection.Bind(int port)
Stub; no-op. -
void IConnection.Listen(int backlog)
Stub; no-op. -
void IConnection.KeepAliveErrorReceived()
Stub; no-op. -
string IConnection.GetConnectionData()
Returns"{_ConnectString} - {_hostIPAddress}". -
Task<int> IConnection.SendAsync(...)
WrapsBeginSend/EndSendusingTask.Factory.FromAsync; returns a completed task with result0. -
void IConnection.SoftConnect()/SoftDisconnect()
Stubs; no-op. -
void Dispose()/~RESTConnection()
ImplementsIDisposable; marks_disposed = truebut performs no socket cleanup.
EthernetConnection (namespace DTS.Common)
-
bool IsSoftDisconnected { get; private set; }
Tracks soft-disconnect state;trueafter successfulSoftDisconnect(). -
bool Connected => Sock != null && Sock.Connected
Reflects underlying socket state. -
string ConnectString => Connect_String
Returns stored connection string. -
SocketFlags Flags { get; set; }
Gets/sets socket flags used inBeginSend/BeginReceive. -
Socket Sock
Public field holding the underlyingSocketinstance. -
event EventHandler OnDisconnected
Raised inKeepAliveErrorReceived(). -
void Create(string connectString, string hostIPAddress)
StoresconnectStringandhostIPAddress, then callsCreateSockto initializeSock. -
Socket CreateSock(string connectString, string hostIPAddress)
Creates and configures aSocketwith:NoDelay = true(Nagle disabled)KeepAlive = true- Buffer sizes from
DFConstantsAndEnums.SendBufferSizeBytes/ReceiveBufferSizeBytes - Custom keep-alive parameters from
DFConstantsAndEnums.LocalKeepAliveTimeOutMS/LocalKeepAliveRetryIntervalMS - Optional binding to
hostIPAddressif provided.
-
void SoftDisconnect()
IfHardwareConstants.AllowSoftDisconnectsistrueand socket is connected:- Disconnects and disposes
Sock - Sets
IsSoftDisconnected = true - Logs action.
- Disconnects and disposes
-
void SoftConnect()
IfAllowSoftDisconnectsistrueand socket is not connected:- Parses
Connect_Stringas"host:port". - If
RequiresKeepAliveResetistrue, connects to port8200, sends<60,5,4>, receives response, then disconnects. - Retries up to 3 times to connect to
host:port(1s delay between attempts). - Sets
IsSoftDisconnected = false, logs success.
- Parses
-
void KeepAliveErrorReceived()
Shuts down, closes, and disposesSock, setsSock = null, and raisesOnDisconnected. -
string GetConnectionData()
Returns"local: {LocalEndPoint}, Remote: {RemoteEndPoint}"or""on error. -
IAsyncResult BeginConnect(AsyncCallback, object)
ValidatesSock,Connect_String, and port format; delegates toSock.BeginConnect. -
void EndConnect(IAsyncResult)
CallsSock.EndConnect, logs connection details. -
IAsyncResult BeginDisconnect(bool, AsyncCallback, object)
ValidatesSock; throws if socket isnullor not connected (SocketException WSAEISCONN); delegates toSock.BeginDisconnect. -
void EndDisconnect(IAsyncResult)
CallsSock.EndDisconnect. -
IAsyncResult BeginAccept(AsyncCallback, object)
ValidatesSock; delegates toSock.BeginAccept. -
IConnection EndAccept(IAsyncResult)
CallsSock.EndAccept, wraps result in a newEthernetConnectioninstance. -
void Bind(int port)
ValidatesSock; binds to first DNS-resolved IP address onport. -
void Listen(int backlog)
ValidatesSock; callsSock.Listen. -
IAsyncResult BeginSend(byte[], int, int, AsyncCallback, object)
ValidatesSock, callback, and connection state; throws if not connected; delegates toSock.BeginSend. -
int EndSend(IAsyncResult)
CallsSock.EndSend; setsSock = nullon exception. -
Task<int> SendAsync(...)
WrapsBeginSend/EndSendviaTask.Factory.FromAsync. -
IAsyncResult BeginReceive(byte[], int, int, AsyncCallback, object)
ValidatesSockand callback; delegates toSock.BeginReceive. -
int EndReceive(IAsyncResult)
CallsSock.EndReceive. -
void Dispose()/~EthernetConnection()
ImplementsIDisposable; safely shuts down/disposesSockinDispose(bool).
3. Invariants
-
RESTConnection:_bConnectedis the sole source of truth for connection state; never updated by external I/O.- All
Begin*/End*operations are synchronous and return immediately; no async state is maintained. IsSoftDisconnectedis alwaysfalse; soft disconnect logic is absent.Connectedreflects_bConnected, which is manually toggled byBeginConnect/BeginDisconnect.
-
EthernetConnection:Connecteddepends onSock != null && Sock.Connected;Sockmay benullafter errors or disposal.SoftDisconnect()andSoftConnect()only execute ifHardwareConstants.AllowSoftDisconnectsistrue.SoftConnect()requiresConnect_Stringto be in"host:port"format; port must be parseable asint.BeginDisconnectthrowsSocketExceptionif socket is not connected (perWSAEISCONN).BeginSend/BeginReceivethrow if socket is not connected or callback isnull.KeepAliveErrorReceived()guaranteesSockisnullafter execution (disposal path).
4. Dependencies
RESTConnection:
- Imports:
DTS.Common.Interface.Connection(forIConnection)DTS.Common.Utilities.Logging(forAPILogger, but not used in this file)- Standard .NET libraries (
System.Net.Sockets,System.Threading, etc.)
- Depended on by: Any code requiring an
IConnectioninstance where network activity is unnecessary (e.g., unit tests, REST-based workflows).
EthernetConnection:
- Imports:
DTS.Common.Interface.Connection(IConnection)DTS.Common.DASResource(forStrings.EthernetConnection_*_Err*exception messages)DTS.Common.Enums.DASFactory(forHardwareConstants.AllowSoftDisconnects)DTS.Common.Utilities.Logging(forAPILogger)DFConstantsAndEnums(for buffer sizes, keep-alive timeouts,WSAEISCONN)
- Depended on by: Higher-level connection management logic (e.g., device initialization, data acquisition pipelines) requiring real Ethernet communication.
5. Gotchas
-
RESTConnection:IsSoftDisconnectedis hardcoded tofalse; callers expecting soft-disconnect behavior will be misled.OnDisconnectedis declared but never raised; event subscriptions have no effect.Begin*/End*methods are synchronous stubs; using them in async contexts may cause deadlocks or incorrect assumptions about I/O latency.EndSend/EndReceivealways return0—no actual bytes sent/received.SoftConnect/SoftDisconnectare no-ops despite being part ofIConnection.
-
EthernetConnection:SoftConnect()usesThread.Sleep(50ms/100ms/1000ms) for timing; this is blocking and may cause issues in high-throughput or UI contexts.SoftConnect()sends<60,5,4>to port8200for keep-alive setup; this is a hardcoded protocol-specific command (device-dependent).BeginDisconnectthrowsSocketExceptionif socket is not connected—not an error condition per se, but callers must handle this exception to avoid crashes.EndSendsetsSock = nullon exception; this may cause subsequent operations to fail unexpectedly.Binduses the first DNS-resolved IP address (AddressList[0]), which may be non-deterministic or IPv6 in some environments.CreateSockusesIOControlCode.KeepAliveValueswith hardcodedKeepAliveOn = 1; this may conflict with system-wide settings.IsSoftDisconnectedis not reset tofalseinSoftConnectifAllowSoftDisconnectsisfalse—only if soft disconnect logic runs.
-
Both:
- Neither class validates
connectStringformat inCreate(string)alone (only inCreate(string, string)orBeginConnect). RESTConnectionandEthernetConnectionshare the sameIConnectioninterface but have wildly different semantics; callers must know which implementation they hold.RESTConnection’sGetConnectionData()returns a string with_hostIPAddress, but_hostIPAddressis never used inRESTConnectionbeyond storage—no binding or resolution occurs.
- Neither class validates
None identified beyond those above.