Complete API reference for the PortDIC .NET library — all public types organized by category.
IPortDic
The main entry point for all Port Dictionary operations. Obtain an instance via Port.GetDictionary(name).
Methods — Set
| Signature | Description |
|---|
bool Set(string category, string entireName, EntryValue value) | Sets a typed EntryValue for the given category/key pair. |
bool Set(string category, string entireName, double value) | Sets a double value for the given category/key pair. |
bool Set(string category, string entireName, string value) | Sets a string value for the given category/key pair. |
bool Set(string categoryMessage, string value, bool isAsync = false) | Sets a string using dot-notation ("category.key"). |
bool Set(string categoryMessage, double value) | Sets a double using dot-notation ("category.key"). |
bool Set(string categoryMessage, int value) | Sets an int using dot-notation ("category.key"). |
bool Set(SecsSystemBytes systemBytes, ISecsData value) | Sets SECS data correlated by system bytes. |
bool Set(string flowName, FlowAction action) | Controls a named flow (Start / Stop / Pause / Resume). |
Returns true on success, false if the port is not running or the operation fails.
Throws NotExistsKeyException when the key has not been registered.
port.Set("room1", "BulbOnOff", "On");
port.Set("Process.Temperature", 150.5);
port.Set("ProductionFlow", FlowAction.Start);
Methods — Get
| Signature | Description |
|---|
EntryValue Get(string categoryMessage) | Retrieves a value using dot-notation ("category.key"). |
EntryValue Get(string category, string entireName) | Retrieves a value by explicit category and key. |
Returns an EntryValue with .Text() / .Double() / .Int() accessors, or null if not found.
var temp = port.Get("Process.Temperature");
Console.WriteLine(temp.Double());
var status = port.Get("room1", "BulbOnOff");
Console.WriteLine(status.Text());
Methods — Registration
| Signature | Description |
|---|
void Add<T>(string key) | Registers a singleton of type T identified by key. |
void Add<T>(string key, string model) | Registers T and binds it to a flow model name. |
void Add<TController, TModel>(string key) | Registers a [Controller] + [Model] pair. |
void Add<T>(string key, params object[] models) | Registers T alongside one or more model instances ([CEID], [ALID], [SVID], …). |
void Add(ref IReference packages, ReferenceModel bindingMessage) | Scans assemblies for [Import] attributes and performs bulk injection. |
bool Add(FuncCode funCode, Options options) | Registers a protocol handler by function code + options. |
bool Add(FuncCode funCode, Type type) | Registers a protocol handler type by function code. |
bool New(string category, string entireName, DataType dataType, params IEntryAttribute[] attributes) | Dynamically defines a new entry in the dictionary. |
port.Add<LP1Controller>("LP1");
port.Add<VisionController, VisionModel>("Vision");
port.Add<GemHandler>("GEM", new CeidModel(), new AlidModel());
Methods — Lifecycle & Utility
| Signature | Description |
|---|
bool Run([CallerMemberName] string callerName = "") | Starts the Port server and all communication services. |
T BroadCast<T>() where T : IBroadcast | Returns or creates a broadcast protocol object (GEM / MQTT / RTSP / OPC UA). |
IFlowController GetController(string name) | Returns the flow controller for the named package. |
T GetObject<T>(string category) where T : class, IEntity | Returns the singleton entity registered under category. |
T GetObject<T>(string category, int subKey) where T : class, IEntity | Returns the per-slot entity at category:subKey. |
bool Push(string repoName, string category, Page list) | Pushes a Page to the specified repository/category. |
bool Push(string repoName, string category, Page list, string outputDir, string namespaceName = "portdic") | Pushes a Page and generates a C# const-key file. |
void Profile() | Activates performance profiling and diagnostic monitoring. |
Events
| Event | Handler Type | When Fired |
|---|
OnStatusChanged | StatusHandler | Port server status changes (Initializing → Running → Stopped / Failed). |
OnOccurred | PortEventHandler | Any system event (Info / Warning / Error / CatchException). |
OnRequest | RequestHandler | An external command or request arrives. |
OnFlowOccurred | FlowOccurredHandler | A flow transitions to the executing state. |
OnFlowFinished | FlowFinishedHandler | A flow completes all steps successfully. |
OnFlowIssue | FlowIssueHandler | A flow is interrupted (Stopped / Cancelled / Failed). |
port.OnStatusChanged += (s, e) => {
if (e.Status == PortStatus.Running)
Console.WriteLine("Ready");
};
port.OnFlowFinished += (s, e) => {
var elapsed = e.End - e.Since;
Console.WriteLine($"Flow '{e.Key}' done in {elapsed.TotalMilliseconds} ms");
};
IFlowController
Controls flow execution for a registered package. Retrieve via port.GetController(name).
Properties
| Property | Type | Description |
|---|
Status | ControlStatus | Current execution state (Idle or Executing). |
Methods
| Method | Returns | Description |
|---|
AbortAllFlow() | bool | Aborts all running flows immediately. |
Lock() | bool | Aborts running flows and blocks new ones until Release(). |
Release() | bool | Releases a Lock(), allowing flows to execute again. |
Shared(IShared handler) | void | Dispatches shared data to all [Shared]-decorated methods on the controller. |
var ctrl = port.GetController("LP1");
if (ctrl.Status == ControlStatus.Executing)
{
ctrl.Lock();
ctrl.Release();
}
ControlStatus Enum
| Value | Int | Description |
|---|
Unknown | -1 | Status cannot be determined. |
Idle | 0 | No flow is currently executing. |
Executing | 1 | One or more flows are running. |
PortLogConfiguration
Configuration object for file-based logging in TCP, Serial, and FileSender handlers.
Pass an instance to SetLogger(rootPath, conf).
Properties
| Property | Type | Default | Description |
|---|
RotationHours | int | 1 | Log file rotation interval in hours (1–24). |
RetentionDay | int | 0 | Days to keep log files. 0 = keep forever. |
LogFileExt | string | ".log" | File extension including the leading dot (e.g. ".txt"). |
LogNameFormat | string | "" | Filename prefix. Empty = protocol default ("tcp", "serial", "quic"). |
Generated filename pattern: {LogNameFormat}_{date}-{slot}{LogFileExt}
RotationHours | Current time | Generated name (LogNameFormat="tcp") |
|---|
| 1 | 14:35 | tcp_2025-01-01-14.log |
| 6 | 14:35 | tcp_2025-01-01-12.log |
| 24 | 14:35 | tcp_2025-01-01-00.log |
handler.SetLogger("./logs", new PortLogConfiguration
{
RotationHours = 6,
RetentionDay = 7,
LogNameFormat = "myapp",
LogFileExt = ".log"
});
ITCPHandler
TCP Client / Server communication. Injected automatically into [TCPHandler] properties of [TCP] classes.
Properties
| Property | Type | Description |
|---|
IsConnected | bool | true when the connection or server is active. |
Methods — Configuration
| Method | Description |
|---|
SetMode(TcpMode mode) | Sets Client or Server mode (must be called before Open()). |
SetHost(string host) | Sets the remote host address. Server: use "0.0.0.0" for all interfaces. |
SetPort(int port) | Sets the port number. |
SetTimeout(int timeoutMs) | Connection timeout in ms for client mode. Default: 5000. |
SetReconnection(uint intervalMs, uint maxRetries) | Enables auto-reconnect with exponential backoff. maxRetries = 0 = infinite. |
Methods — Connection
| Method | Returns | Description |
|---|
Open() | ERROR_CODE | Connects (client) or starts listening (server). |
Close() | ERROR_CODE | Disconnects or stops the server. |
TryReconnect() | void | Manually restarts the reconnect loop after GIVE_UP. |
Methods — Data
| Method | Returns | Description |
|---|
Send(byte[] data) | int | Sends raw bytes. Server: broadcasts to all clients. Returns bytes sent or -1. |
Send(string text) | int | Sends a UTF-8 string. Returns bytes sent or -1. |
StartReading() | void | Starts background reading. Fires OnDataReceived per packet. |
StopReading() | void | Stops background reading (client mode). |
Methods — Logging
| Method | Description |
|---|
SetLogger(string rootPath) | Enables hourly-rotated SEND/RECV logging in rootPath. |
SetLogger(string rootPath, PortLogConfiguration conf) | Logging with custom rotation/retention settings. |
WriteLog(string v) | Writes an arbitrary message to the configured log. |
Events
| Event | Delegate | When Fired |
|---|
OnDataReceived | TcpDataReceivedHandler(name, data, hex) | Data packet received. |
OnEvent | TcpEventHandler(name, eventType, description) | CONNECTED / DISCONNECTED / ERROR / LISTENING / CLIENT_CONNECTED / CLIENT_DISCONNECTED. |
OnConnected | ConnectedEventHandler(sender, args) | Connection established. args.ConnectionString = remote address. |
OnDisconnected | DisconnectedEventHandler(sender, args) | Connection lost. |
TCP ERROR_CODE Enum
| Value | Int | Description |
|---|
ERR_CODE_NO_ERROR | 1 | Success. |
ERR_CODE_OPEN | -1 | Connect/listen failed. |
ERR_CODE_DLL_NOT_LOADED | -2 | porttcp.dll not loaded. |
ERR_CODE_PORTNAME_EMPTY | -3 | Connection name not set. |
ERR_CODE_DLL_FUNC_NOT_CONFIRM | -4 | Required DLL export missing. |
ERR_CODE_CONNECT_FAILED | -5 | Connection attempt failed. |
TcpMode Enum
| Value | Description |
|---|
Client | Connects to a remote host. |
Server | Listens and accepts multiple clients. |
[TCP]
public class MyDevice
{
[TCPHandler]
public ITCPHandler handler { get; set; }
[Preset]
private void Init()
{
handler.SetMode(TcpMode.Client);
handler.SetHost("192.168.1.100");
handler.SetPort(5000);
handler.SetTimeout(5000);
handler.SetReconnection(1000, 0);
handler.OnDataReceived += (name, data, hex) =>
Console.WriteLine($"[{name}] {hex}");
handler.OnConnected += (s, e) =>
Console.WriteLine($"Connected: {e.ConnectionString}");
}
}
ISerialHandler
RS232 / RS485 serial port communication. Injected into [SerialHandler] properties of [Serial] classes.
Properties
| Property | Type | Description |
|---|
IsConnected | bool | true when the port is open and connected. |
Methods — Configuration
| Method | Description |
|---|
SetPortName(string portName) | Sets the COM port (e.g. "COM3"). |
SetBaudRate(int baudRate) | Sets baud rate (9600 / 19200 / 38400 / 57600 / 115200, …). |
SetDataBits(int dataBits) | Sets data bits (5, 6, 7, or 8). Default: 8. |
SetParity(SerialParity parity) | Sets parity (None / Odd / Even). Default: None. |
SetStopBits(SerialStopBits stopBits) | Sets stop bits (One / Two). Default: One. |
SetTimeout(int timeoutMs) | Read timeout in ms. Default: 1000. |
SetAutoConnection(bool enable, int intervalMs) | Enables auto-reconnect on disconnect. |
Methods — Connection
| Method | Returns | Description |
|---|
Open() | ERROR_CODE | Opens the serial port. |
Close() | ERROR_CODE | Closes the serial port. |
TryReconnect() | void | Manually restarts the reconnect loop. |
GetAvailablePorts() | string[] | Returns a list of available COM port names. |
Methods — Data
| Method | Returns | Description |
|---|
Send(byte[] data) | int | Sends raw bytes. Returns bytes sent or -1. |
Send(string text) | int | Sends a UTF-8 string. Returns bytes sent or -1. |
StartReading() | void | Starts background reading. Fires OnDataReceived per packet. |
StopReading() | void | Stops background reading. |
Methods — Logging
| Method | Description |
|---|
SetLogger(string rootPath) | Enables hourly-rotated SEND/RECV logging. |
SetLogger(string rootPath, PortLogConfiguration conf) | Logging with custom configuration. |
WriteLog(string v) | Writes a message to the configured log. |
Events
| Event | Delegate | When Fired |
|---|
OnDataReceived | SerialDataReceivedHandler(portName, data, hex) | Data received from port. |
OnEvent | SerialEventHandler(portName, eventType, description) | CONNECTED / DISCONNECTED / ERROR. |
OnConnected | ConnectedEventHandler(sender, args) | Port opened successfully. args.ConnectionString = e.g. "COM3:9600". |
OnDisconnected | DisconnectedEventHandler(sender, args) | Port connection lost. |
SerialParity Enum
| Value | Int | Description |
|---|
None | 0 | No parity. |
Odd | 1 | Total 1-bits kept odd. |
Even | 2 | Total 1-bits kept even. |
SerialStopBits Enum
| Value | Int | Description |
|---|
One | 0 | One stop bit. |
Two | 1 | Two stop bits. |
Serial ERROR_CODE Enum
| Value | Int | Description |
|---|
ERR_CODE_NO_ERROR | 1 | Success. |
ERR_CODE_OPEN | -1 | Port open failed. |
ERR_CODE_DLL_NOT_LOADED | -2 | portserial.dll not loaded. |
ERR_CODE_PORTNAME_EMPTY | -3 | No port name set. |
ERR_CODE_DLL_FUNC_NOT_CONFIRM | -4 | Required DLL export missing. |
ERR_CODE_CONNECT_FAILED | -5 | Connection could not be confirmed. |
[Serial]
public class MySerialDevice
{
[SerialHandler]
public ISerialHandler handler { get; set; }
[Preset]
private void Init()
{
handler.SetPortName("COM3");
handler.SetBaudRate(9600);
handler.SetDataBits(8);
handler.SetParity(SerialParity.None);
handler.SetStopBits(SerialStopBits.One);
handler.SetTimeout(1000);
handler.SetAutoConnection(true, 2000);
handler.OnDataReceived += (port, data, hex) =>
Console.WriteLine($"[{port}] {hex}");
}
}
Package Attributes
Attributes are the primary way to wire classes and properties into the PortDIC runtime.
Class-Level Attributes
| Attribute | Target | Description |
|---|
[Package] | class | Declares a class as a Port-managed package. Enables automatic instantiation, lifecycle management, and REST API generation. |
[Flow] | class | Marks a class as a sequential/parallel workflow. Steps are executed in [Step] index order. |
[Controller] | class | Marks a class as a flow controller (used together with [Model]). |
[TCP] | class | Declares TCP communication support. The runtime injects ITCPHandler and calls [Preset] before opening. |
[Serial] | class | Declares serial communication support. The runtime injects ISerialHandler and calls [Preset] before opening. |
[GEM] | class | Declares SECS/GEM handler support. |
Property / Field Injection Attributes
| Attribute | Injected Type | Description |
|---|
[TCPHandler] | ITCPHandler | Injects a TCP handler instance. Used inside a [TCP] class. |
[SerialHandler] | ISerialHandler | Injects a serial handler instance. Used inside a [Serial] class. |
[Logger] | ILogger | Injects the package logger for centralized log writing. |
[Property] | IProperty | Injects the entry property bag. Call Property.TryToGetValue(key, out val) to read config. |
[StepTimer] | IStepTimer | Injects a step timer for delayed / one-shot actions inside a [Flow]. |
[FlowControl] | IFlowControl | Injects a flow control object for JumpStep() navigation inside a [Flow]. |
[Import] | IFunction | Marks a dependency on a named function from another package. Resolved automatically at startup. |
[FileHandler("path")] | IFileHandler | Injects an XML file reader for the given config file path. |
Method Attributes
| Attribute | Target | Description |
|---|
[Preset] | method | Called by the runtime before the connection is opened. Use for handler configuration. |
[Step(index, ...)] | method | Marks a flow step. index controls execution order. Lower = earlier. |
[Valid("message")] | method | Validation gate called before the package starts. Return false to block startup. |
[Command("key")] | method | Exposes a method as a remote command endpoint. |
[Shared] | method | Called by IFlowController.Shared(handler) with the shared data object. |
[BeforeSync] | method | Called before memory sync operations. |
Property / Field Marker Attributes
| Attribute | Target | Description |
|---|
[API(EntryDataType, ...)] | property | Exposes the property as a REST API endpoint. Accepts data type, format, and property keys. |
[Comment("text")] | property | Adds documentation text visible in the API. |
[Mapping(typeof(T))] | property | Maps the property to a specific data type for automatic conversion. |
[ModelProperty("portKey")] | property / field | Marks a field as a model property bound to a port key. |
[EnumCode] | enum | Exposes enum values through the API so external systems can query them. |
[CEID] | class / field | Marks as a Collection Event ID model for GEM registration. |
[ALID] | class / field | Marks as an Alarm ID model for GEM registration. |
[SVID] | class / field | Marks as a Status Variable ID model for GEM registration. |
[DVID] | class / field | Marks as a Data Value ID model for GEM registration. |
[ECVID] | class / field | Marks as an Equipment Constant Variable ID model for GEM registration. |
IFlowControl
Provides step-level navigation inside a [Flow] class. Injected via [FlowControl].
| Method | Description |
|---|
JumpStep(int index) | Jumps execution to the step with the given [Step(index)]. |
IStepTimer
Timing and scheduling utilities inside a [Flow] class. Injected via [StepTimer].
Properties
| Property | Type | Description |
|---|
Since | DateTime | Timestamp when the current step started. |
TotalSeconds | double | Elapsed seconds since Since. |
Methods
| Method | Returns | Description |
|---|
Reserve(string id, int ms, Action func) | string | Schedules func to run after ms milliseconds. Returns the task ID. |
Once(string id, Action action) | string | Executes action exactly once per timer lifetime. Duplicate calls with same id are ignored. |
Reset() | void | Resets Since to now and cancels all pending reservations. |
IReference / IFunction
Used by the References & Import system for inter-package dependency injection.
IReference
| Member | Type | Description |
|---|
this[string key] | IFunction | Looks up a registered function by key. |
API | IEnumerable<IFunction> | Returns all registered functions. |
IFunction
| Member | Type | Description |
|---|
Key | string | Unique identifier of the function. |
Type | Type | CLR type of the function implementation. |
Binding(string entryKey) | IFunction | Binds the function to a specific entry key. |
Benchmark(string entryKey, params string[] args) | string | Runs a benchmark for the function. |
ILogger
Injected via [Logger]. Provides centralized log writing for packages.
| Method | Description |
|---|
Write(string message) | Writes a message to the package log. |
IProperty
Injected via [Property]. Provides access to the entry's declared property bag.
| Method | Returns | Description |
|---|
TryToGetValue(string key, out string value) | bool | Tries to retrieve a property by key. Returns false if not found. |
IFileHandler
Injected via [FileHandler("path")]. Reads values from an XML configuration file.
| Method | Returns | Description |
|---|
GetValue(string section, string key) | string | Returns the text content at <section><key>. Returns "" if not found. |
IBroadcast
Marker interface implemented by ITCPHandler, ISerialHandler, GEM, MQTT, RTSP, and OPC UA objects. No members — used as a type constraint for port.BroadCast<T>().
Quick Reference — Attribute Map
| What you want | Class attribute | Property/Field attribute |
|---|
| Managed package | [Package] | — |
| Sequential workflow | [Flow] | — |
| Flow controller | [Controller] | — |
| TCP communication | [TCP] | [TCPHandler] on ITCPHandler property |
| Serial communication | [Serial] | [SerialHandler] on ISerialHandler property |
| SECS/GEM handler | [GEM] | — |
| Logging | — | [Logger] on ILogger property |
| Config property access | — | [Property] on IProperty property |
| Flow step | — | [Step(n)] on method |
| Step timer | — | [StepTimer] on IStepTimer property |
| Flow navigation | — | [FlowControl] on IFlowControl property |
| REST API endpoint | — | [API(EntryDataType.X)] on property |
| Validation gate | — | [Valid("msg")] on bool method |
| Remote command | — | [Command("key")] on method |
| Pre-connect init | — | [Preset] on method |
| Package dependency | — | [Import("ref", "key")] on IFunction field |
| XML config access | — | [FileHandler("file.xml")] on IFileHandler property |