Files
DP44/enriched-qwen3-coder-next/DataPRO/ICommand.md
2026-04-17 14:55:32 -04:00

212 lines
11 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
source_files:
- DataPRO/ICommand/CommandReport.cs
- DataPRO/ICommand/ICommand.cs
- DataPRO/ICommand/CommandLogEntryBase.cs
- DataPRO/ICommand/SliceCommandBase.cs
- DataPRO/ICommand/CommandPacketBase.cs
- DataPRO/ICommand/SliceCommandPacketBase.cs
generated_at: "2026-04-16T03:45:59.897128+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "d99db64c66704ca9"
---
# Command Infrastructure Module Documentation
## 1. Purpose
This module defines the core infrastructure for command execution, status reporting, and packet handling within the DAS (Data Acquisition System) library. It provides abstractions for command packets (with protocol-specific variants for SLICE and RIBYE systems), command execution semantics (synchronous and asynchronous via callbacks), and structured status reporting. The module enables consistent command lifecycle management—including serialization, CRC computation, sequence numbering, and logging—while supporting device-specific addressing (e.g., `DeviceID`, `DeviceGroup`) and rate-limiting mechanisms for SLICE communication. It serves as the foundational layer for all command-based interactions with hardware devices.
## 2. Public Interface
### Enums
- **`CommandStatus`**
Represents high-level command execution outcome: `Success`, `Failure`, or `Canceled`.
- **`CommandErrorReason`**
Provides granular failure reasons for `CommandException`: `SendFailed`, `ReceiveFailed`, `InvalidMode`, `Canceled`.
- **`CommandReceiveAction`**
Return value for `CommandCallback`: `StopReceiving` or `ContinueReceiving`.
### Classes
- **`CommandException`**
Exception type for command-related errors.
- **Properties**:
- `Error`: `CommandErrorReason` indicating the cause.
- **Constructors**:
- `CommandException(CommandErrorReason _err)`
- `CommandException(CommandErrorReason _err, string msg)`
- **`CommandReport`**
Encapsulates the result of a command execution. Implements `ICommandReport`.
- **Properties**:
- `CallbackObject`: `object` passed during execution, returned unchanged.
- `Status`: `CommandStatus` indicating success/failure/cancellation.
- **Constructor**:
- `CommandReport(CommandStatus _Status, object _CallbackObject)`
- **`CommandPacketBase`**
Abstract base class for all command/response packets. Defines common packet structure and behavior.
- **Nested Types**:
- `PacketState`: `OK`, `TooShort`, `Unknown` — result of packet validation.
- **Fields**:
- `Status`: `DFConstantsAndEnums.CommandStatus` — low-level status code from device.
- `ShouldLog`: `bool` — whether to include in logs.
- `AlreadyRun`: `bool` — whether the command has been executed.
- `OriginalBytes`: `byte[]` — raw bytes used to construct the packet (if applicable).
- `Type`: `object` — holds the concrete `CommandType` enum value (defined in derived classes).
- `SequenceNumber`: `UInt16` — packet sequence identifier.
- **Properties**:
- None (all fields are public).
- **Methods**:
- `SetCommand(byte command, string commandDescription)`
- `GetCommand()`, `GetCommandDescription()`
- `abstract byte[] ToBytes()`
- `abstract object ConvertByteToCommandType(byte b)`
- `abstract PacketState VerifyPacket(byte[] Bytes)`
- `abstract void GetNextSequenceNumber()`
- `abstract void ComputeCRCs()`
- `GetPacketLogHeader(ref List<List<string>> lines)`
- `GetPacketLogHeader(CommandPacketBase commandPacket, ref List<List<string>> lines, DateTime executeTime)`
- `StatusLabels`: `string[]` — static array mapping status codes (0x000xFF) to human-readable strings (e.g., `Strings.CmdStatusNoErr`, `Strings.CmdStatusInvalidCRC`).
- **`SliceCommandPacketBase`**
Abstract base class for SLICE-specific command packets. Extends `CommandPacketBase`.
- **Constants**:
- `MAGIC_BYTE = 0xFA`
- `HEADER_SIZE_BYTES = 12`
- `DATA_CRC_SIZE_BYTES = 2`
- **Fields** (all public):
- `ParameterLength`, `DeviceGroup`, `DeviceID`, `HeaderCRC`, `Parameter`, `ParameterCRC`
- **Constructors**:
- `SliceCommandPacketBase()` — initializes empty packet, sets `ShouldLog = true`, calls `GetNextSequenceNumber()`.
- `SliceCommandPacketBase(byte[] Bytes)` — parses raw packet bytes.
- **Methods**:
- `override PacketState VerifyPacket(byte[] Bytes)` — validates packet structure (magic byte, length, size). *Note: CRC verification is commented out.*
- `override void ComputeCRCs()` — computes header and parameter CRCs using `Utils.Math_DoCRCCCITTStep`.
- `override byte[] ToBytes()` — serializes packet to wire format.
- `GetParameter<T>(int Offset, out T Value)` — generic parameter extraction for `double`, `UInt64`, `Int64`, `Int32`, `UInt32`, `Int16`, `UInt16`, `byte`, `bool`, `float`, `string`.
- `SetParameter<T>(int Offset, T Value)` — generic parameter setting for same types.
- **`SliceCommandBase`**
Abstract base class for SLICE commands. Extends `AbstractCommandBase` (not shown in source).
- **Properties**:
- `DeviceID`: `byte` — gets/sets device ID.
- `DeviceGroup`: `byte` — gets/sets device group.
- **Constructors**:
- `SliceCommandBase(ICommunication sock)`
- `SliceCommandBase(ICommunication sock, int TimeoutMillisec)`
- **Methods**:
- `override void CommandToString(ref List<List<string>> list)` — appends serial number and connection data to log header.
- `override void ResponseToString(ref List<List<string>> lines)` — appends serial number to response log header.
- `override void SyncExecute()` — currently no-op wrapper around `base.SyncExecute()`. *Semaphore logic is commented out.*
- `static void Initialize(int spots, int delayMs)` — configures static semaphore (`_slicePool`) and delay (`_slicePoolDelayMs`).
- **`CommandLogEntryBase`**
Abstract base class for log entry formatting. Used by `SliceCommandLogEntry` and `CommonLogEntry`.
- **Fields**:
- `sb`: `StringBuilder` — log content accumulator.
- `command`: `CommandPacketBase` — associated command packet.
- **Constructor**:
- `CommandLogEntryBase(CommandPacketBase _command)` — initializes `sb` and writes sequence number header.
- **Methods**:
- `TagCommonCommandData(string CommandName)` — logs command type.
- `TagCommonResponseData(string CommandName)` — logs status and timestamp.
- `override string ToString()` — returns full log entry string.
### Interfaces
- **`ICommandReport`**
Contract for command execution reports.
- `object CallbackObject { get; set; }`
- `CommandStatus Status { get; set; }`
- **`ICommand`**
Contract for executable commands.
- `void Execute(CommandCallback Callback, object CallbackObject)`
- `void SyncExecute()`
### Delegates
- **`CommandCallback`**
`delegate CommandReceiveAction CommandCallback(ICommandReport report)`
Called after command execution to determine whether to continue receiving responses.
## 3. Invariants
- **Packet Structure**:
- `SliceCommandPacketBase` packets must begin with `MAGIC_BYTE` (`0xFA`).
- Header size is fixed at 12 bytes.
- Parameter CRC is appended *after* parameter data (if any).
- CRCs are computed using `Utils.Math_DoCRCCCITTStep` (CRC-16 CCITT).
- **Sequence Numbers**:
- Each packet type (SLICE, SLICE-DB, RIBYE) maintains independent sequence counters (per `GetNextSequenceNumber()` implementation).
- **Status Codes**:
- `CommandPacketBase.Status` holds a `DFConstantsAndEnums.CommandStatus` value.
- `CommandReport.Status` holds a `CommandStatus` enum (`Success`, `Failure`, `Canceled`).
- **Logging**:
- `ShouldLog` controls inclusion in logs (default `true`).
- `AlreadyRun` tracks execution state.
- **SLICE Threading**:
- `SliceCommandBase.Initialize()` must be called *before* communication starts if semaphore settings are to be customized.
- Semaphore-based rate limiting is *currently disabled* (code commented out in `SyncExecute()` and `Initialize()`).
## 4. Dependencies
### Internal Dependencies (Inferred from Source)
- **`DTS.Common.ICommunication`**
- Used by `SliceCommandBase` (`ICommunication` interface for device transport).
- **`DTS.Common.DASResource`**
- Used by `CommandPacketBase` (`DFConstantsAndEnums.CommandStatus`).
- **`DTS.Common.Enums.DASFactory`**
- Used by `SliceCommandPacketBase` (`CommandStatus`).
- **`DTS.Common.Utilities.Logging`**
- Used by `SliceCommandPacketBase` (`APILogger`).
- **`DTS.Common.Utils`**
- Used by `SliceCommandPacketBase` (`Utils.Math_DoCRCCCITTStep`, `ByteConvertor`).
### External Dependencies
- **`System`**
- Core types (`System.Text`, `System.Collections.Generic`, `System.Threading`, `System.Diagnostics`).
- **`System.Threading`**
- `SemaphoreSlim` used in `SliceCommandBase` (though disabled).
### Inferred Usage
- `SliceCommandBase` and `SliceCommandPacketBase` are used for SLICE-specific commands.
- `CommandPacketBase` is the base for all command packets (including RIBYE variants, though not shown).
- `CommandLogEntryBase` is extended by `SliceCommandLogEntry` and `CommonLogEntry` (not provided).
- `ICommand` implementations (e.g., `SliceCommandBase` subclasses) are executed via `Execute()` or `SyncExecute()`.
## 5. Gotchas
- **CRC Verification Disabled**:
`SliceCommandPacketBase.VerifyPacket()` does *not* validate header or parameter CRCs despite computing them in `ComputeCRCs()`. The CRC checks are commented out in both `VerifyPacket()` and `ComputeCRCs()`.
- **Semaphore Rate Limiting Disabled**:
`SliceCommandBase.SyncExecute()` and `Initialize()` contain commented-out semaphore logic. The `_slicePool` and delay mechanism are *not active*, despite being documented as added for SLICE 6 multiple IP performance.
- **`CommandPacketBase.Status` vs `CommandReport.Status`**:
`CommandPacketBase.Status` is a low-level `DFConstantsAndEnums.CommandStatus` (e.g., `StatusNoError`, `StatusInvalidCRC`). `CommandReport.Status` is a high-level `CommandStatus` (`Success`, `Failure`, `Canceled`). Conversion between them is not defined in this module.
- **`Type` Field Ambiguity**:
`CommandPacketBase.Type` is `object` because the concrete `CommandType` enum is defined in derived classes. This requires downcasting to use.
- **String Parameter Handling**:
`SetParameter(int, string)` appends a null terminator, but `GetParameter(int, string)` stops at *any* null byte (not just the terminator). This may cause truncation if the string contains embedded nulls.
- **`AlreadyRun` Not Enforced**:
`AlreadyRun` is a property but there is no enforcement in `Execute()`/`SyncExecute()` to prevent re-execution of the same command instance.
- **`CommandException` Inheritance**:
Inherits from `ApplicationException` (deprecated in modern .NET); no custom serialization or additional context beyond `Error`.
- **Missing `AbstractCommandBase`**:
`SliceCommandBase` extends `AbstractCommandBase`, but its definition is not provided. Its behavior (e.g., `SyncExecute()`) is unknown.