Skip to main content

Attributes and State Machines

Properties​

CategoryPropertyTypeAccessDescription
Staticis_service_ready()boolread-onlyWhether the local service is ready. On failure, write last_error; do not panic
last_error()StringRead-onlyThe string of the most recent failure at the process level (sticky; not cleared upon success)
last_error_code()PnSErrorCoderead-onlyThe fault code of the most recent process-level SDK call. Success if never failed
service_connected()boolread-onlyWhether the IO controller is performing cyclic exchange. If the service is not started, this returns false.
service_state()ServiceStateRead-onlyOperational ST. If the service is not RUN, the value is 'Unknown'.
service_wait_reason()StringRead-onlyReason for the wait. Service not up = 'Service not ready'
service_status_message()StringRead-onlyST message. If the service hasn't started = 'Service not ready'
Connections and Sessionsconnected()boolread-onlyWhether the IO controller has established cyclic data exchange. Only true means cyclic data is being exchanged.
attached()boolread-onlyWhether this SDK session is connected to the local service. true after new(), false after close(). stop does not change it
is_started() / is_running()boolread-onlyWhether the IO device is enabled (after start, before stop). Both return the same value
Operational STstate()ServiceStateread-onlyOperational ST. If the value cannot be read, it is considered 'Unknown'; do not treat it as 'STOP'
status()ServiceResult<ServiceState>read-onlyRetrieves the ST of status_ex. Returns Err if the service is unreachable
status_ex()ServiceResult<ServiceStatus>read-onlyRetrieves ST / connected / error_code / alarm count / ever_connected in a single call
wait_reason()StringRead-onlyReason for this session's wait. Empty when the IO controller is connected
status_message()StringRead-onlyST message for this session
ever_connected()boolread-onlyWhether a link has ever been established with the IO controller. true and connected is false = disconnected
fault Codeserror_code()PnSRuntimeErrorCoderead-onlyLast execution fault. Unrecognized value: Unknown. The original value is still passed through via error_code_raw
error_code_raw()i32read-onlyRaw fault code (0 = no fault). Unrecognized values are passed through by this function
error_message()StringRead-onlyRuntime fault message in Chinese. Unrecognized value with original value
last_service_error()StringRead-onlyThe most recent failure message for this session (sticky; not cleared upon success)
Alertsalarm_count()i32read-onlyTotal number of active alarms. Returns 0 if not available. Same as alarms()
critical_alarm_count()i32read-onlyNumber of critical alarms. If not retrievable, returns 0
alarms()ServiceResult<Vec<AlarmItem>>read-onlyActive alerts.
alarm_history()ServiceResult<Vec<AlarmItem>>read-onlyHistorical alerts (last 500 entries)
Diagnostic and Process Dataevents()&ServiceEventsread-onlyLocal runtime events.
diag_snapshot()ServiceResult<DiagSnapshot>Read-onlyRetrieves link, frame count, watchdog, and jitter in a single call. If the data cannot be read, ok is false.
io_status()IoStatusread-onlyIOPS / IOCS Snapshot.0x80 = GOOD,0x00 = BAD. If the link is lost, all values are BAD.
process_data()ProcessDataRead/WriteProcess data view; write to Q, read from I.
Local Sessionhost()&strread-onlyThe host of the service connected to in this session
port()u16read-onlyThe service port connected to in this session

No is_connected(). No PnSState / PnSStatus(The type name is ServiceState / ServiceStatus). A failure is returned ServiceError, not PnSError.

Free functions with the same name exist in darra_pns::statics::status(is_service_ready / service_connected / service_state / service_wait_reason / service_status_message / last_error / last_error_code); there is no need to construct instances.

let ready = PnSService::is_service_ready();
let ctrl = PnSService::service_connected();
let st = PnSService::service_state();
let wait = PnSService::service_wait_reason();
let err = PnSService::last_error();
let _ = (ready, ctrl, st, wait, err);
ServiceState

Operational ST Type: The ST of the link and data exchange between the device and the IO controller.

pub enum ServiceState {
Stopped, // Discontinued
Initialized, // The stack has been initialized and is waiting for a controller link.
Connecting, // Establishing a link with the controller
Parameterized, // Controller Parameterization Complete
Ready, // Ready for Use
DataExchange, // Periodic Data Exchange
Aborted, // link terminated
Resetting, // Device is resetting
ConfigError, // Configuration Error Downgrade ST (Process is alive, but process data exchange has not started)
Unknown, // Unknown / Not available
}
  • Mapped based on the server ST string; there is no fixed integer value, so use the enumeration name instead.
  • Only DataExchange indicates that periodic data is being exchanged.
  • Unknown Don't treat it as "uninitialized."
ServiceStatus
pub struct ServiceStatus {
pub state: ServiceState,
pub connected: bool,
pub error_code: i32,
pub alarm_count: i32,
pub critical_alarm_count: i32,
pub ever_connected: bool,
}

impl ServiceStatus {
pub fn error_code_enum(&self) -> PnSRuntimeErrorCode;
}
PnSRuntimeErrorCode

Runtime fault code types (server-side errorCode enumerations exposed by ST queries). These differ in PnSErrorCode semantics from call return codes and must not be used interchangeably.

pub enum 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 closed)
ErrDiag = -9, // Invalid diagnostic parameter
Win32Error = 1, // Win32 positive code (original value error_code_raw() passed through)
Unknown = -10000, // Unrecognized value
}

Unrecognized values are returned as-is Unknown, and the original values are passed through exactly (error_code_raw()).

runtime_error_message(raw) Translate the original values into Chinese; example: error_message() use the same table.

Start-Stop​

start Do this once; do not call it every cycle. The process writes data to Q (module output) and reads data from I (module input).

start()​

pub fn start(&self) -> ServiceResult<()>

Enable IO. If start has already been called and stop has not, returns idempotently with Ok(()). This does not mean the IO controller is exchanging data on a cycle basis; whether the controller is currently exchanging data is shown by connected().

Only one instance can exist at a time start. If the write fails last_error, the function returns ServiceError(indicating that another instance is in use = RealtimeGate / PnSErrorCode::Busy).

Example:

device.start()?;
if !device.connected() {
eprintln!("{}", device.wait_reason());
}

stop()​

pub fn stop(&self) -> ServiceResult<()>

Deactivated IO. The instance still exists and can be reactivated start. No close().

Example:

device.stop()?;

close()​

pub fn close(&mut self)

End this instance. Clear the Q data area; I is retained. Drop Will be called close. No stop.

Example:

device.close();

Operating State​

connected() / attached()​

pub fn connected(&self) -> bool
pub fn attached(&self) -> bool
  • connected: IO Has the controller established periodic data exchange? If not, the instance is = false.
  • attached: Is this instance connected to the local service? new() The value after is true, close and the value after is false. stop Do not change it.

Example:

if device.attached() && device.connected() {
println!("已连上服务且 IO 控制器在换周期数据");
}

state()​

pub fn state(&self) -> ServiceState

Runtime ST. The actual ST cannot be read as Unknown; do not treat it as Stopped. You can check it without creating an instance: static service_state().

Example:

if device.state() == darra_pns::ServiceState::DataExchange {
println!("周期数据交换正常");
}

status() / status_ex()​

pub fn status(&self) -> ServiceResult<ServiceState>
pub fn status_ex(&self) -> ServiceResult<ServiceStatus>

status_ex Retrieve a snapshot once. status Equals status_ex()?.state. Returns if the service is unreachable Err.

Only connected == true means periodic data exchange with the IO controller has been established. Even after a successful new() or start(), this value may still be false.

Example:

let snap = device.status_ex()?;
println!("{:?} {}", snap.state, snap.connected);

wait_reason()​

pub fn wait_reason(&self) -> String

Reason for this instance's wait. Empty when the IO controller is connected. In the if !device.connected() loop, read this function or last_service_error().

Example:

if !device.connected() {
eprintln!("{}", device.wait_reason());
}

ever_connected()​

pub fn ever_connected(&self) -> bool

Has a link ever been established with the IO controller? false = Never connected; true and connected() == false = Disconnected.

Example:

if !device.connected() && device.ever_connected() {
println!("掉线");
}

Error Code​

error_code() / error_code_raw() / error_message()​

pub fn error_code(&self) -> PnSRuntimeErrorCode
pub fn error_code_raw(&self) -> i32
pub fn error_message(&self) -> String

Runtime fault. This is not PnSErrorCode the same category as SDK call code ; do not use them interchangeably. Unreadable: error_code_raw() = 0, error_code() = Ok.

Example:

let err = device.error_code();
let text = device.error_message();
let raw = device.error_code_raw();
let _ = (err, text, raw);

last_error() / last_error_code() / last_service_error()​

pub fn last_error() -> String
pub fn last_error_code() -> PnSErrorCode
pub fn last_service_error(&self) -> String

"Static" refers to the process level; "Instance" refers to this instance. The static success path is not cleared. If this if !connected() property is empty during a loop, read it wait_reason().

PnSErrorCode

SDK Call fault code (success is Success). Negative value system: 0 = success, negative value = failure.

pub enum PnSErrorCode {
Success = 0, // Success
InvalidArgument = -1, // Invalid parameter
InvalidHandle = -2, // Invalid handle
NotConnected = -3, // Not connected
NativeError = -4, // Native / Server-side call failed
LengthMismatch = -5, // Data length mismatch
NotFound = -6, // Entry does not exist
Busy = -7, // Busy: The previous operation is not complete; or the real-time link port is occupied by another session.
NotSupported = -8, // Not supported
NativeDllNotFound = -100, // Library not found
PlatformNotSupported = -101, // Platform not supported
ServiceUnreachable = -102, // Service Unavailable
}

C language code ≠ this enumeration code(-4..-8 same value, different meaning), cross-language conversion is required PnSErrorCode::from_native_code(i32); direct conversion is prohibited.

Service path: ServiceResult<T> = Result<T, ServiceError>. Write to I, return OutputReadOnly (I is read-only; write to Q).

pub enum ServiceError {
NotConnected,
ConnectFailed(String, u16, String),
HttpStatus(u16, String),
BadResponse(String),
ServiceRejected(String),
ServiceRejectedCode(i32, String),
InvalidAddress(String),
InvalidParam(String),
OutputReadOnly, // Write I (I = read-only)
DbSlotNotSupported(u16),
OutOfRange(u16, usize, usize),
NotStarted, // Not started
InvalidString(String),
Io(String),
RealtimeGate(String), // Another instance has started
ServiceControl(String), // Failed to start or stop the local service (SCM /systemd)
SharedMemory(String), // Process data not ready / Read/write failure
CoreUnavailable(String), // Failed to load the native core library
}

Clock​

1ms high-precision clock is held by the service process; this crate provides no in-process toggle — toggle it through the service Web API POST /api/high-resolution-timer (body {"highResolutionTimer": true|false}). Not enabled by default in the installer.

note

After opening, wait for greater accuracy; the mouse may become sluggish. On non-Windows systems, this operation has no effect.

Complete Example​

use darra_pns::PnSService;

fn main() -> darra_pns::ServiceResult<()> {
let mut device = PnSService::new();
device.start()?;

while running {
if !device.connected() {
println!("{:?}", device.state());
println!("{}", device.wait_reason());
println!("{}", device.error_message());
continue;
}

device.write_bool("Q0.0", true)?;
let from_plc = device.read_bool("I0.0")?;
let _ = from_plc;
}

device.stop()?;
Ok(())
}