Attributes and State Machines
Use namespace functions based on the ST; there is no need to construct it. The process is IO: construct → Start() → write Q / read I. For whether the IO controller has completed cyclic exchange, see Connected().
Start() Return on failure false; write LastError(); do not throw. Read and write—throw on failure IO PnSException.
Properties
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Static | IsServiceReady() | bool | read-only | Whether the local service is ready |
LastError() | const std::string& | read-only | The most recent fault message across the entire application (sticky; not cleared upon success) | |
LastErrorCode() | PnSErrorCode | read-only | The fault code from the most recent failed call across the entire application. 'Success' is returned if no failure has ever occurred | |
ServiceConnected() | bool | read-only | Whether the IO controller is performing cyclic exchange. If the service is not started, this returns false. | |
ServiceState() | PnSState | Read-only | Runtime ST. If the service is not RUN, the ST is 'Unknown' | |
ServiceWaitReason() | std::string | read-only | Reason for the wait. Service not RUN = 'Service not ready' | |
ServiceStatusMessage() | std::string | read-only | ST message. If the service hasn't started = 'Service not ready' | |
| Connections and Sessions | Connected() | bool | read-only | Whether the IO controller has established cyclic data exchange. Only true means cyclic data is being exchanged. |
Attached() | bool | read-only | Whether this SDK session is connected to the local service. Stop does not change this value | |
IsRunning() | bool | read-only | Whether the IO device is enabled (after Start, before Stop) | |
Host() | const std::string& | read-only | The host to which this session is connected | |
Port() | uint16_t | read-only | The service port connected to in this session | |
| Operational ST | Status() | PnSState | Read-only | Operational ST. Equals StatusEx().ST. If the actual ST cannot be read, it is set to 'Unknown' |
StatusEx() | PnSServiceStatus | Read-only | Retrieves ST / connected / error_code in a single call | |
WaitReason() | std::string | read-only | Reason for this session's wait. Empty when the IO controller is connected | |
EverConnected() | bool | read-only | Whether a link has ever been established with the IO controller. true and Connected is false = disconnected | |
| fault Codes | ErrorCode() | PnSRuntimeErrorCode | read-only | Last execution fault. Unrecognized value: Unknown |
ErrorCodeRaw() | int | read-only | Raw fault code (0 = no fault). Unrecognized values are passed through by this function | |
ErrorMessage() | std::string | read-only | Runtime fault message in Chinese | |
LastServiceError() | const std::string& | read-only | The most recent failure message for this session (sticky; not cleared upon success) | |
| Alerts | AlarmCount() | int | read-only | Total number of active alarms. Same GetAlarms as |
CriticalAlarmCount() | int | read-only | Number of critical alarms | |
GetAlarms() | std::vector<PnSServiceAlarmItem> | read-only | Active alerts. | |
GetAlarmHistory() | std::vector<PnSServiceAlarmItem> | read-only | Historical alerts. | |
| Diagnostic and Process Data | Events() | PnSEvents& | Read-only | Local runtime events. |
DiagSnapshot() | PnSServiceDiagSnapshot | read-only | Retrieves link, frame count, watchdog, and jitter in a single operation. Returns 'ok' as false if the data cannot be read | |
ProcessData() | PnSProcessData | Read-only | Process data subobject. |
Functions in the namespace of the same name are equivalent to static PnSService:: functions and do not need to be defined: IsServiceReady(), LastError(), LastErrorCode() , ServiceConnected() , ServiceState() , ServiceWaitReason(), ServiceStatusMessage(). If the service hasn't started yet, LastError() does not throw.
PnSState
link Between Equipment and IO Controllers / Data Exchange in Operational Mode.
enum class PnSState {
None = 0, // Not Initialized / Stack Not Initialized
Idle = 1, // Started, waiting for the IO controller (no AR)
Connecting = 2, // The controller has initiated a link (STARTUP)
Parameterized = 3, // Controller parameterization complete (PRMEND), waiting for the application to be ready
ApplicationReady = 4, // Application Ready (APPLRDY), parameter exchange complete
DataExchange = 5, // Cyclic data exchange is normal (DATA)
Aborted = 6, // link lost (ABORT)
Resetting = 7, // Device is resetting (reserved ST name; this ST is not generated when the server is reset in the current version)
ConfigError = 8, // Configuration Error Downgrade ST: ST can be queried, but process data exchange has not been started
Unknown = 9, // Unknown / Unable to read the actual ST
};
Only DataExchange indicates that periodic data is being exchanged. Unknown indicates that the actual ST cannot be read; do not treat it as None.
PnSRuntimeErrorCode
Server-side runtime fault codes (enumeration of errorCode fields exposed by ST queries).
enum class PnSRuntimeErrorCode {
Ok = 0, // No errors
ErrInit = -1, // Stack initialization failed
ErrCfg = -2, // Invalid configuration
ErrThread = -3, // Failed to create a periodic thread / set priority
ErrRunning = -4, // Invalid ST (repeated start/stop)
ErrPdi = -5, // Process Data Exchange Failed
ErrDap = -6, // Slot 0: Insertion Failed
ErrNull = -8, // The device has not started (empty session / not started or STOP)
ErrDiag = -9, // Invalid diagnostic parameter
Win32Error = 1, // System Win32 fault codes (such as 2048) passed through the downgraded ST; the original values are passed ErrorCodeRaw() through
Unknown = -10000, // Unrecognized value; the original value was passed ErrorCodeRaw() through
};
This differs in PnSErrorCode semantics from the return code of a function call; the two should not be used interchangeably. Unrecognized values are treated as null Unknown, while the original value is passed through ErrorCodeRaw() as-is.
Start-Stop
Start()
bool Start();
Enable the IO device. If it has already been Started and not yet Stopped, the function returns true idempotently. This does not mean the IO controller has completed cyclic exchange; whether the IO controller is exchanging data is shown by Connected().
Return value:
bool—trueSuccess; Return on failurefalse
Write to static if the operation fails LastError(); do not throw an exception.
Example:
if (!device.Start())
printf("%s\n", LastError().c_str());
Stop()
void Stop();
Deactivate the IO device. The instance still exists and can be started again with Start(). If Start was never called or Stop has already been called, it returns idempotently. Failures write LastError(); no exception is thrown.
Not Close(): Stop does not end the SDK session.
Example:
device.Stop();
Operating State
Status()
Operational ST. Start / Stop simply enable / disable the IO device; this function always reads the actual ST as it is on-site. If the actual ST cannot be read, the value is Unknown. When not connected to the service it throws PnSException; use ServiceState() when no construction is needed.
PnSState Status();
Example:
if (device.Status() == PnSState::DataExchange)
printf("周期数据交换正常\n");
StatusEx()
PnSServiceStatus StatusEx();
Retrieve state / connected / error_code, the wait message, and the alarm count in one call. When unable to connect to the service it throws PnSException. snap.connected == true means periodic data exchange has been established with the IO controller. Use the runtime fault enumeration device.ErrorCode().
struct PnSServiceStatus
{
PnSState state = PnSState::None;
bool connected = false;
int error_code = 0;
std::string wait_reason;
std::string status_message;
int alarm_count = 0;
int critical_alarm_count = 0;
bool ever_connected = false;
};
Example:
auto snap = device.StatusEx();
if (snap.connected)
printf("周期交换正常\n");
WaitReason()
std::string WaitReason();
Reason for this session's wait. Empty when the IO controller is connected. In the if (!device.Connected()) loop, read this function or LastServiceError().
Example:
if (!device.Connected())
printf("%s\n", device.WaitReason().c_str());
EverConnected()
bool EverConnected();
Has a link ever been established with the IO controller? false = Never connected; true and Connected() == false = Disconnected. This determination still holds even after the link is lost. Unable to connect to the service = false.
Example:
if (!device.Connected() && device.EverConnected())
printf("掉线\n");
Connected()
bool Connected();
IO Has the controller already established periodic data exchange? true Only then does periodic data exchange occur. When not connected to the service, switch to [...] ServiceConnected(); do not discard. Use [...], when construction is not required ServiceConnected().
Start() After that, this value may still be false.
Example:
if (device.Connected())
printf("IO 控制器在换周期数据\n");
Error Code
ErrorCode()
PnSRuntimeErrorCode ErrorCode();
Last runtime fault (enumeration). Unrecognized value Unknown. The original value is still passed ErrorCodeRaw() through. Use for Chinese messages ErrorMessage(). Unable to connect to the service = Ok.
Example:
PnSRuntimeErrorCode err = device.ErrorCode();
std::string text = device.ErrorMessage();
int raw = device.ErrorCodeRaw();
ErrorCodeRaw()
int ErrorCodeRaw();
Original value of the runtime fault (0 = no fault). Unrecognized values are passed through by this function. Service not connected = 0.
Example:
int raw = device.ErrorCodeRaw();
ErrorMessage()
std::string ErrorMessage();
Chinese fault messages. Return a description with the original value for unrecognized codes; do not discard the information.
Example:
printf("%s\n", device.ErrorMessage().c_str());
LastServiceError()
const std::string& LastServiceError() const;
The most recent failed script for this session (sticky). The success path is not cleared. if (!Connected()) If this value is empty during a loop, read WaitReason().
Example:
printf("%s\n", device.LastServiceError().c_str());
LastError() / LastErrorCode()
static const std::string& LastError();
static PnSErrorCode LastErrorCode();
Global; no need to construct. The success path does not clear the stack. Read/write IO failures throw an exception PnSException; code() is the SDK call fault code.
PnSErrorCode
SDK Return codes for calls (start/stop, read/write process data, diagnostics).
enum class PnSErrorCode {
Success = 0, // Success
InvalidArgument = -1, // Invalid parameter (invalid address / empty buffer / parameter out of bounds)
InvalidHandle = -2, // Handle is invalid / Not started or has been STOP
NotConnected = -3, // No application relationship / No data exchange has taken place
NativeError = -4, // Stack / Remote fault
LengthMismatch = -5, // Data length mismatch
NotFound = -6, // Address / Entry does not exist
Busy = -7, // Busy: The previous operation was not completed, or the real-time link port is occupied by another session.
NotSupported = -8, // Unsupported operations (such as writing to a read-only input address)
NativeDllNotFound = -100, // The built-in library was not loaded
PlatformNotSupported = -101, // Windows Only x64
ServiceUnreachable = -102, // Session Unreachable / Timeout
};
Negative value system: 0 = success; negative value = failure. Busy There are two possible causes: the previous operation was not completed, or the real-time link port is occupied by another session.
C language code ≠ this enumeration code(-4. . -8 Same value, different meaning), cross-language conversion must use PnSErrorCodeFromNative(int)(constexpr, which can be used for static_assert), and bare is prohibited static_cast.
Example:
try {
device.WriteBool("Q0.0", true);
} catch (const PnSException& ex) {
printf("%s code=%d\n", ex.what(), ex.code());
}
Diagnosis
DiagSnapshot()
PnSServiceDiagSnapshot DiagSnapshot();
Retrieve the link, frame count, watchdog, and jitter in a single operation. If a value cannot be read ok == false, read it again message; this is not considered an exception.
Example:
auto snap = device.DiagSnapshot();
if (!snap.ok)
printf("%s\n", snap.message.c_str());
Complete Example
#include "pns.hpp"
#include <cstdio>
using namespace darra::pns;
int main()
{
PnSService device;
if (!device.Start())
return 1;
while (running)
{
if (!device.Connected())
{
printf("%d\n", static_cast<int>(device.Status()));
printf("%s\n", device.WaitReason().c_str());
printf("%s\n", device.ErrorMessage().c_str());
continue;
}
device.WriteBool("Q0.0", true);
bool fromPlc = device.ReadBool("I0.0");
(void)fromPlc;
}
device.Stop();
return 0;
}