メインコンテンツまでスキップ

Library Reference

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

SignatureDescription
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

SignatureDescription
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()); // 150.5

var status = port.Get("room1", "BulbOnOff");
Console.WriteLine(status.Text()); // "On"

Methods — Registration

SignatureDescription
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

SignatureDescription
bool Run([CallerMemberName] string callerName = "")Starts the Port server and all communication services.
T BroadCast<T>() where T : IBroadcastReturns 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, IEntityReturns the singleton entity registered under category.
T GetObject<T>(string category, int subKey) where T : class, IEntityReturns 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

EventHandler TypeWhen Fired
OnStatusChangedStatusHandlerPort server status changes (Initializing → Running → Stopped / Failed).
OnOccurredPortEventHandlerAny system event (Info / Warning / Error / CatchException).
OnRequestRequestHandlerAn external command or request arrives.
OnFlowOccurredFlowOccurredHandlerA flow transitions to the executing state.
OnFlowFinishedFlowFinishedHandlerA flow completes all steps successfully.
OnFlowIssueFlowIssueHandlerA 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

PropertyTypeDescription
StatusControlStatusCurrent execution state (Idle or Executing).

Methods

MethodReturnsDescription
AbortAllFlow()boolAborts all running flows immediately.
Lock()boolAborts running flows and blocks new ones until Release().
Release()boolReleases a Lock(), allowing flows to execute again.
Shared(IShared handler)voidDispatches shared data to all [Shared]-decorated methods on the controller.
var ctrl = port.GetController("LP1");
if (ctrl.Status == ControlStatus.Executing)
{
ctrl.Lock();
// ... emergency work ...
ctrl.Release();
}

ControlStatus Enum

ValueIntDescription
Unknown-1Status cannot be determined.
Idle0No flow is currently executing.
Executing1One 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

PropertyTypeDefaultDescription
RotationHoursint1Log file rotation interval in hours (1–24).
RetentionDayint0Days to keep log files. 0 = keep forever.
LogFileExtstring".log"File extension including the leading dot (e.g. ".txt").
LogNameFormatstring""Filename prefix. Empty = protocol default ("tcp", "serial", "quic").

Generated filename pattern: {LogNameFormat}_{date}-{slot}{LogFileExt}

RotationHoursCurrent timeGenerated name (LogNameFormat="tcp")
114:35tcp_2025-01-01-14.log
614:35tcp_2025-01-01-12.log
2414:35tcp_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

PropertyTypeDescription
IsConnectedbooltrue when the connection or server is active.

Methods — Configuration

MethodDescription
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

MethodReturnsDescription
Open()ERROR_CODEConnects (client) or starts listening (server).
Close()ERROR_CODEDisconnects or stops the server.
TryReconnect()voidManually restarts the reconnect loop after GIVE_UP.

Methods — Data

MethodReturnsDescription
Send(byte[] data)intSends raw bytes. Server: broadcasts to all clients. Returns bytes sent or -1.
Send(string text)intSends a UTF-8 string. Returns bytes sent or -1.
StartReading()voidStarts background reading. Fires OnDataReceived per packet.
StopReading()voidStops background reading (client mode).

Methods — Logging

MethodDescription
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

EventDelegateWhen Fired
OnDataReceivedTcpDataReceivedHandler(name, data, hex)Data packet received.
OnEventTcpEventHandler(name, eventType, description)CONNECTED / DISCONNECTED / ERROR / LISTENING / CLIENT_CONNECTED / CLIENT_DISCONNECTED.
OnConnectedConnectedEventHandler(sender, args)Connection established. args.ConnectionString = remote address.
OnDisconnectedDisconnectedEventHandler(sender, args)Connection lost.

TCP ERROR_CODE Enum

ValueIntDescription
ERR_CODE_NO_ERROR1Success.
ERR_CODE_OPEN-1Connect/listen failed.
ERR_CODE_DLL_NOT_LOADED-2porttcp.dll not loaded.
ERR_CODE_PORTNAME_EMPTY-3Connection name not set.
ERR_CODE_DLL_FUNC_NOT_CONFIRM-4Required DLL export missing.
ERR_CODE_CONNECT_FAILED-5Connection attempt failed.

TcpMode Enum

ValueDescription
ClientConnects to a remote host.
ServerListens 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

PropertyTypeDescription
IsConnectedbooltrue when the port is open and connected.

Methods — Configuration

MethodDescription
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

MethodReturnsDescription
Open()ERROR_CODEOpens the serial port.
Close()ERROR_CODECloses the serial port.
TryReconnect()voidManually restarts the reconnect loop.
GetAvailablePorts()string[]Returns a list of available COM port names.

Methods — Data

MethodReturnsDescription
Send(byte[] data)intSends raw bytes. Returns bytes sent or -1.
Send(string text)intSends a UTF-8 string. Returns bytes sent or -1.
StartReading()voidStarts background reading. Fires OnDataReceived per packet.
StopReading()voidStops background reading.

Methods — Logging

MethodDescription
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

EventDelegateWhen Fired
OnDataReceivedSerialDataReceivedHandler(portName, data, hex)Data received from port.
OnEventSerialEventHandler(portName, eventType, description)CONNECTED / DISCONNECTED / ERROR.
OnConnectedConnectedEventHandler(sender, args)Port opened successfully. args.ConnectionString = e.g. "COM3:9600".
OnDisconnectedDisconnectedEventHandler(sender, args)Port connection lost.

SerialParity Enum

ValueIntDescription
None0No parity.
Odd1Total 1-bits kept odd.
Even2Total 1-bits kept even.

SerialStopBits Enum

ValueIntDescription
One0One stop bit.
Two1Two stop bits.

Serial ERROR_CODE Enum

ValueIntDescription
ERR_CODE_NO_ERROR1Success.
ERR_CODE_OPEN-1Port open failed.
ERR_CODE_DLL_NOT_LOADED-2portserial.dll not loaded.
ERR_CODE_PORTNAME_EMPTY-3No port name set.
ERR_CODE_DLL_FUNC_NOT_CONFIRM-4Required DLL export missing.
ERR_CODE_CONNECT_FAILED-5Connection 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

AttributeTargetDescription
[Package]classDeclares a class as a Port-managed package. Enables automatic instantiation, lifecycle management, and REST API generation.
[Flow]classMarks a class as a sequential/parallel workflow. Steps are executed in [Step] index order.
[Controller]classMarks a class as a flow controller (used together with [Model]).
[TCP]classDeclares TCP communication support. The runtime injects ITCPHandler and calls [Preset] before opening.
[Serial]classDeclares serial communication support. The runtime injects ISerialHandler and calls [Preset] before opening.
[GEM]classDeclares SECS/GEM handler support.

Property / Field Injection Attributes

AttributeInjected TypeDescription
[TCPHandler]ITCPHandlerInjects a TCP handler instance. Used inside a [TCP] class.
[SerialHandler]ISerialHandlerInjects a serial handler instance. Used inside a [Serial] class.
[Logger]ILoggerInjects the package logger for centralized log writing.
[Property]IPropertyInjects the entry property bag. Call Property.TryToGetValue(key, out val) to read config.
[StepTimer]IStepTimerInjects a step timer for delayed / one-shot actions inside a [Flow].
[FlowControl]IFlowControlInjects a flow control object for JumpStep() navigation inside a [Flow].
[Import]IFunctionMarks a dependency on a named function from another package. Resolved automatically at startup.
[FileHandler("path")]IFileHandlerInjects an XML file reader for the given config file path.

Method Attributes

AttributeTargetDescription
[Preset]methodCalled by the runtime before the connection is opened. Use for handler configuration.
[Step(index, ...)]methodMarks a flow step. index controls execution order. Lower = earlier.
[Valid("message")]methodValidation gate called before the package starts. Return false to block startup.
[Command("key")]methodExposes a method as a remote command endpoint.
[Shared]methodCalled by IFlowController.Shared(handler) with the shared data object.
[BeforeSync]methodCalled before memory sync operations.

Property / Field Marker Attributes

AttributeTargetDescription
[API(EntryDataType, ...)]propertyExposes the property as a REST API endpoint. Accepts data type, format, and property keys.
[Comment("text")]propertyAdds documentation text visible in the API.
[Mapping(typeof(T))]propertyMaps the property to a specific data type for automatic conversion.
[ModelProperty("portKey")]property / fieldMarks a field as a model property bound to a port key.
[EnumCode]enumExposes enum values through the API so external systems can query them.
[CEID]class / fieldMarks as a Collection Event ID model for GEM registration.
[ALID]class / fieldMarks as an Alarm ID model for GEM registration.
[SVID]class / fieldMarks as a Status Variable ID model for GEM registration.
[DVID]class / fieldMarks as a Data Value ID model for GEM registration.
[ECVID]class / fieldMarks as an Equipment Constant Variable ID model for GEM registration.

IFlowControl

Provides step-level navigation inside a [Flow] class. Injected via [FlowControl].

MethodDescription
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

PropertyTypeDescription
SinceDateTimeTimestamp when the current step started.
TotalSecondsdoubleElapsed seconds since Since.

Methods

MethodReturnsDescription
Reserve(string id, int ms, Action func)stringSchedules func to run after ms milliseconds. Returns the task ID.
Once(string id, Action action)stringExecutes action exactly once per timer lifetime. Duplicate calls with same id are ignored.
Reset()voidResets Since to now and cancels all pending reservations.

IReference / IFunction

Used by the References & Import system for inter-package dependency injection.

IReference

MemberTypeDescription
this[string key]IFunctionLooks up a registered function by key.
APIIEnumerable<IFunction>Returns all registered functions.

IFunction

MemberTypeDescription
KeystringUnique identifier of the function.
TypeTypeCLR type of the function implementation.
Binding(string entryKey)IFunctionBinds the function to a specific entry key.
Benchmark(string entryKey, params string[] args)stringRuns a benchmark for the function.

ILogger

Injected via [Logger]. Provides centralized log writing for packages.

MethodDescription
Write(string message)Writes a message to the package log.

IProperty

Injected via [Property]. Provides access to the entry's declared property bag.

MethodReturnsDescription
TryToGetValue(string key, out string value)boolTries to retrieve a property by key. Returns false if not found.

IFileHandler

Injected via [FileHandler("path")]. Reads values from an XML configuration file.

MethodReturnsDescription
GetValue(string section, string key)stringReturns 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 wantClass attributeProperty/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