syslib Library Functions

asciitoutf8

syslib.asciitoutf8(string, [code_page])

Description

Converts an ASCII string into an UTF8 string and returns it.

Return Type

string

Component Execution

All Components

Parameters

Name Type Optional Description

string

string

no

The string to be converted.

code_page

string

yes

The country encoding; by default it’s zero, meaning current code page.

Error Messages

  • String conversion error - when string length is over 4096 bytes

Examples

syslib.asciitoutf8("Brühl")

attach

syslib.attach(objspec, name, [repeater])

Description

This method is related to buffering historical data (see buffer function) and, depending on the specified arguments, it has two variations.

  • syslib.attach(objspec, name) - Removes a repeater from the buffer with the specified name at the specified object or path.

  • syslib.attach(objspec, name, repeater) - Attaches the specified repeater object to the buffer with the specified name at the specified object or path.

The repeater shall be an object or a path to an object that has a dynamic property. The buffer with the specified name must exist. If a repeater at the specified buffer already exists, it is replaced. The dynamic property of the repeater object receives each value stored into the buffer.

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

First, assume there is an object obj which has a dynamic property that generates numerical values every second. Also, assume it historizes these values in raw format (without any aggregation). We set a buffer on this object, which will contain the generated values within the last minute:

syslib.buffer(obj, "buff", ".ItemValue", 60000, 60)

Now, assume there is another object obj2 that has a dynamic property. This property can take the values received by the buffer buff in the following way:

syslib.attach(obj, "buff", obj2)

buffer

syslib.buffer(objspec, name, [input], [duration], [size])

Description

This function is related to historization (see gethistory function) and its main purpose is buffering historical data. See the In-Memory Aggregation Jump Start for more information and working examples of the buffer function.

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

Assume obj is an object having a dynamic property which generates numerical values every second. Also, assume it historizes these values in raw format (without any aggregation). We could set a buffer which will contain the generated values within the last minute in the following way:

syslib.buffer(obj, "buff", ".ItemValue", 60000, 60)

Depending on the provided arguments, it has several variations:

  1. syslib.buffer(objspec, name) - Removes the buffer with the specified name from the specified object.

  2. syslib.buffer(objspec, name, [input], [duration], [size]) - Creates a buffer with the specified name at the specified object, on the specified input, with the specified duration and size. If a buffer with the specified name already exists at the specified object, the buffer is replaced. The input argument shall be a string. It is either a relative path to a property within the specified object (so it shall start with a dot in this case), or it is the name of a buffer previously created at the specified object. The duration and size shall be positive integers, specifying, respectively, the maximum difference in milliseconds between the last and first elements in the buffer, and the maximum number of elements the buffer can have. New elements will be placed at the end of the buffer, and whenever that causes the conditions imposed by the specified duration and size to be violated, elements are removed at the opposite end of the buffer until the conditions are satisfied.

  3. syslib.buffer(objspec, name, input, duration, size, function) Creates a buffer with the specified name at the specified object, on the specified input, with the specified duration and size, with the specified transformation function. The arguments except function are identical with those specified in (2). The input argument shall be the name of a buffer, not a of property. The buffer should exist before calling the function. The function shall be a string, which must be a well-formed Lua chunk. The function is executed whenever the specified input buffer receives a new value; it is executed before older values are purged from the input buffer. If the function returns a non-nil value, the value is placed into the buffer with the specified name. The function executes in a restricted environment that does not have the object, nor user-defined libraries. Therefore, it cannot access other objects, and cannot even (using the inmation object) access its input buffer. The function has three arguments: input, peek and tear. The input is a reference to the input buffer. The peek and tear are functions that can be used to access the input buffer. Their semantics is largely identical with the peek and tear functions from the syslib library. Using the supplied arguments, the function can analyze the input buffer and decide whether it needs to produce a value that will be placed into the buffer with the specified name. It can use the standard Lua libraries (such as math and table) for this purpose. Note the function executes within the thread that modifies the underlying property and the thread is blocked, and the property`s object write-locked, while the function executes. It is therefore recommended that only very simple logic should be implemented in the function. More complicated logic can be run in dedicated scripts (action or generic items).

    Assuming we have already run the code example in (2), we can create at obj another buffer which stores the values returned by the transformation function. The following code will put in buff2 the average value for each 10 seconds interval for the last minute.

    local func = [[ return function(input, peek, tear)
        local values = peek(input)
        if #values >= 10 then
            local sum = 0
            for i=1,10 do sum = sum + values[i] end
            tear(input)
            return sum / 10
        end
    end ]]
    syslib.buffer(obj, "buff2", "buff", 60000, 6, func)
  4. syslib.buffer(objspec, name, input, duration, size, aggregation_period, aggregation_type) Creates a buffer with the specified name at the specified object, on the specified input, with the specified duration and size, with the specified aggregation period and type. The first two arguments identical with those specified in (2). The input argument shall be the name of a buffer, not of a property. The buffer should exist before calling the function. The aggregation period shall be a non-negative integer. If it is zero, the aggregation of the specified type is run each time the specified input buffer receives a new value, and the result of the aggregation is placed into the buffer with the specified name. The aggregation uses the full input buffer. If the aggregation period is above zero, it is treated as the interval, in milliseconds, for the aggregation of the specified type; the start time of the aggregation is chosen at a "natural" time for the specified interval, i.e., it is the time that is a whole number of the specified intervals since the beginning of the current day (UTC). The aggregation runs only when there is at least one full interval of data in the input that had not been previously aggregated. The aggregation only works on full intervals, and a single value placed into the input buffer may generated multiple full intervals of data. The result of the aggregation for each full interval is placed into the buffer with the specified name. The aggregation type shall be a string with a valid Aggregates code group value. Note that the aggregation with zero and non-zero periods executes largely in the same environment as that described in (3), and it may be desirable to offload aggregation to dedicated items.

    Assuming we have already run the code example in (2), the following will have the same effect like the example in (3) (with the exception that the resulting values will be stored in another buffer - buff3).

    syslib.buffer(obj, "buff3", "buff", 60000, 6, 10000, "AGG_TYPE_AVERAGE")

checkmodelaccess

syslib.checkmodelaccess(model_flags, [profiles])

Return Type

boolean

Description

Checks if the profile of the user or the optional list of profiles have access to the models given. The function returns a boolean value indicating if all the profiles together have access to all the models given.

Component Execution

Core only

Parameters

Name Type Optional Description

model_flags

number

no

A bitwise OR combination of ProfileModelAccess flags.

profiles

string

yes

An optional single objspec or table of objspec entries pointing to profile objects. If no profiles are specified, the permissions are checked against the profile of the user executing this function.

Error Messages

  • The function is not supported in this component - the function is being called from a component which does not support that function to be called

  • Unknown flag or coding value - one of the given ProfileModelAccess flags are not known

  • argument could not be resolved to a profile - one of the given profiles could not be resolved to a profile object

Examples

This example checks if the profile "visitor" has access to IO and Access models.

local model_flags = syslib.model.flags.ProfileModelAccess
local profile = syslib.getobject("/visitor")
return  syslib.checkmodelaccess(model_flags.PRF_MDL_ACC_IO | model_flags.PRF_MDL_ACC_ACC, profile)

checkpermission

syslib.checkpermission(pathspec, sec_attr, [profiles])

Return Type

boolean

Description

Checks the access permissions (security attributes) for a given object in the context of an optional list of profiles. The function returns a boolean value indicating if all attributes apply to the specified pathspec for the union of permissions granted to the given profiles.

Component Execution

Core only

Parameters

Name Type Optional Description

pathspec

variant

no

Path to object or property, the object itself, object or property ID.

sec_attr

number

no

A bitwise OR combination of SecurityAttributes flags.

profiles

string

yes

An optional single objspec or table of objspec entries pointing to profile objects. If no profiles are specified, the permissions are checked against the profile of the user executing this function.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

  • The function is not supported in this component - the function is being called from a component which does not support that function to be called

  • Unknown flag or coding value - one of the given security attribute flags are not known

  • argument could not be resolved to a profile - one of the given profiles could not be resolved to a profile object

Examples

This example checks if the object with the path "/System/Core/Item" can be read and written to using the read-only profile "/ro".

local sec_flags = syslib.model.flags.SecurityAttributes
local profile = syslib.getobject("/ro")
local granted = syslib.checkpermission("/System/Core/Item", sec_flags.READ | sec_flags.WRITE, profile)

control.getself

syslib.control.getself()

Return Type

number

Description

Returns the id of the Lua instance that called syslib.control.getself.

control.dedicate

syslib.control.dedicate(id)

Return Type

boolean

Description

You need to be system administrator to run this function. Promotes a non-dedicated instance to a dedicated instance, if the instance is not yet dedicated. If the instance is already dedicated then this function will do nothing. Returns false followed by an error message if it failed to make the request to the Lua instance to be made dedicated. Returns true otherwise.

Parameters

Name Type Optional Description

id

number

no

Specifies the id of the Lua instance which will be made dedicated.

control.list

syslib.control.list()

Return Type

table

Description

Lists all running Lua instances. Returns a table of tables, where each inner table represents a Lua instance. The Lua instance tables have the following properties:

  • id – the id of the Lua instance.

  • state – the state of the Lua instance. This can be one of the following values: "idle", "running", "terminated", or "disabled".

  • mem_usage – the number of bytes of memory this Lua instance is using.

  • cpu_usage - the percent of a single CPU thread this Lua instance is using. The usage is not normalized to conisder all CPU hardware threads.

  • source_type – this describes what kind of Lua instance the instance is. This can be one of the following string values: "default", "thread", "lua_obj", "lua_channel", or "channel".

  • source_sub_type – this currently returns the sub-type of the source type of the Lua instance. It is currently used for channels to specify the channel type.

  • source_id – this is used to specify the channel ID.

  • source_is_non_persisting_channel – this field is set to true when the channel is a non-persisting Lua channel, or nil if it is anything else. Non-persisting Lua channels are created by the console when you run the script by pushing the play button / the F5 key. Alternatively, persisting Lua channels are created when you open the console, choose the Advanced menu, and then choose Execute (ctrl+shift+E) or Reset and Execute (ctrl-shift-X).

  • totalruntime – the total amount of time that the Lua instance has been running, in nanoseconds

  • elapsed – if the Lua instance is currently running then this will specify the amount of time that has elapsed since it was most recently invoked, in nanoseconds. Otherwise this will be set to nil.

  • dedicated – this is true for Lua instances which are running on their own dedicated threads.

  • self – this is the object associated with the instance.

Parameters

Name Type Optional Description

options

table

yes

If the table contains a field named "self", it is treated as an objspec.

control.terminate

syslib.control.terminate(id)

Description

You need to be system administrator to run this function. Terminates the Lua virtual machine running an instance. If the Lua virtual machine is executing native code then the instance will not terminate until it has finished running the native code.

For example, if a Lua instance is running socket.sleep(60) and a call to syslib.control.terminate() is made on this instance, it will not terminate until the socket.sleep(60) command has finished. An attempt to terminate an instance associated with an object, such as a Generic Item that is not running in a dedicated thread, from another object that is also not running in a dedicated thread, may not work as expected if the target instance is currently running and does not return control to the system (because it is running an infinite loop or experiences a similar condition). This is because the running instance will monopolize the thread used by all such objects.

Any object associated with the instance will change its status to OpcUa_BadOutOfService and its value will be set to Terminated. The bad status and the "Terminated" message will be set only when the instance is terminated when it was running, or at the next attempt to run the instance. If the instance is terminated while it is idle, and the next attempt to run the instance is not forthcoming (soon or ever), the previous status and value are preserved.

Returns false followed by an error message if it failed to make the request to the Lua instance to be terminated. Returns true otherwise.

Parameters

Name Type Optional Description

id

number

no

Specifies the id of the Lua instance which will be terminated.

createevent

syslib.createevent(standard_attrs, [custom_attrs])

Return Type

userdata

Description

Creates and returns a userdata representing an event that can be fed to syslib.setevent() upon which it is invalidated and cannot be used again.

Component Execution

Core and Connector Components

Parameters

Name Type Optional Description

standard_attrs

table

no

A table containing key-value pairs of built-in attributes (listed under syslib.setevent()). Non-standard attributes are ignored.

custom_attrs

table

yes

A table of tables containing key-value pairs of vendor-specific attributes where each sub-table consists of two elements: a key and a value. The order of the attributes is respected. Unlike syslib.setevent(), keys are not converted into lowercase.

Examples

local standard_attrs = {
    Severity = 500,
    Message = "script event",
    Timestamp = syslib.now()
}

local custom_attrs = {
    { "key1", "str" },
    { "key2", 35 },
    { "key3", {1, 2, 3} }
}

return syslib.setevent(syslib.createevent(standard_attrs, custom_attrs))

createjwt

syslib.createjwt(header, payload, algo_params)

Return Type

string

Description

Create a Base64 encoded JWT token.

Component Execution

All Components

Parameters

Name Type Optional Description

header

string

no

It contains the header claims. It is a JSON-encoded string expected to conform to RFC 8259.

payload

string

no

It contains the payload claims. It is JSON-encoded string expected to conform to RFC 8259.

algo_params

table

yes

It contains the parameters for the algorithm used to sign the token.

Note that the function doesn’t verify RFC 8259 compliance for the header and payload. For the header, an alg field is required that contains one of the algorithms listed below.

The implemented algorithms are: none, HS256, HS384, HS512, RS256, ES256, PS256, Ed25519, RS384, ES384, PS384, Ed448, RS512, ES512, PS512, ES256K. For the none algorithm no field in the algo_params table is evaluated. The table is optional in this case. For the algorithms HSxxx, the field secret in the algo_params table is evaluated. For the other algorithms, the field private_key in the algo_params is evaluated. This field needs to be in PEM format RFC 7468.

Examples

The secret can be stored in a Stored Credential object

local credentialsPath = "/System/Core/Stored Credentials Group/Stored Credential"
local my_secret = syslib.getvalue(credentialsPath .. ".SharedKeyCredentials.SharedKey")
return syslib.createjwt('{"alg":"HS256", "typ":"JWT" }','{"loggedInAs":"admin",
  "iat":1422779638}',{secret=my_secret})

The private key can be stored by importing the PEM file in a Stored Credential object.

return syslib.createjwt('{"alg":"RS256", "typ":"JWT" }','{"loggedInAs":"admin",
  "iat":1422779638}',{
private_key=syslib.getvalue('/System/Core/Stored Credentials Group/Stored Credential.CertificateCredentials.CertificateKey')
})

createobject

syslib.createobject(parent, class, [type])

Return Type

table

Description

Short name: syslib.new

Creates a new object and returns it. The possible values for the type parameter are:

  • "OT_TEMPLATE" - a template object holds configuration data which can be applied to other objects

  • "OT_RULE" - a rule object can be invoked on certain system state changes (e.g. on newly discovered entities)

  • "OT_OBJECT" - a regular object holds configuration data and supports system functionality

  • "OT_PROTO" - a prototype object holds data until it is either finally rejected or constructed by rule processing

Component Execution

All Components

Parameters

Name Type Optional Description

parent

variant

no

Parent object’s path, the parent object itself or the object ID of the parent.

class

string

no

A symbolic name of an object, e.g. "MODEL_CLASS_HOLDERITEM" for the HolderItem class.

type

string

yes

Specifies the object’s type as a string code. Default value is "OT_OBJECT".

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

  • Unknown class name - the string code provided for the object class could not be found

  • Object could not be created - an error occurred while creating the object internally

  • property value exceeds limits - the numeric value is not in a valid range

  • Property not found - attempt to modify a non-existent property for the given object class

  • Invalid object id - the object’s table gets corrupted internally

  • Compound properties cannot be set directly - all the compound properties have to be specified

  • Property could not be set - attempt to set a property with an incompatible type

  • Object class must be top-level - attempt to create an object that is not top level

  • Object type is not supported by the given object class. Hint: check parameter 3 - mismatch between the object class and its type

Examples

local obj = syslib.createobject("/System/localhost", "MODEL_CLASS_HOLDERITEM")

The example above will create a Data Holder Item under /System/localhost. Now properties can be set on this object. The object is not physically created until the "commit" function is called on it. This solution was approached in order to commit all the changes in a single transaction.

The example above can be elaborated as follows:

obj.ObjectName = "newObject"
obj.ObjectDescription = "newDescription"
obj.Limits.OpcRangeLow = 50
obj:commit() -- pay attention to the colon!

When the third parameter is not specified, it is assumed that the object’s type is regular object ("OT_OBJECT"). Below, there is an example of creating another type of object – a rule:

obj = syslib.createobject("/System/localhost", "MODEL_CLASS_RULE", "OT_RULE")
obj.ObjectName = "rule"
obj:commit()

currenttime

syslib.currenttime([local])

Return Type

number

Description

Short name: syslib.now

Returns the number of milliseconds since Epoch in UTC time. If it is called with a parameter which is true, it will return the local time.

Component Execution

All Components

Parameters

Name Type Optional Description

local

boolean

no

Specifies whether the returned time should be local or UTC.

Examples

local no_of_ms_utc = syslib.currenttime()
local no_of_ms_local = syslib.currenttime(true)

currenttimezone

syslib.currenttimezone()

Return Type

variant

Description

This function returns 3 values regarding current time zone information. The first value is the offset from UTC time in milliseconds (including possible daylight bias); the second one is the name of the time zone; the third one is a boolean specifying whether daylight saving time is active or not.

Component Execution

All Components

Examples

local offset, name, dst = syslib.currenttimezone()

debase64

syslib.debase64(str)

Return Type

string

Description

Returns binary data, as Lua-string, converted from Base64-encoded ASCII input.

Component execution

All components

Parameters

Name Type Optional Description

str

string

no

Base64 encoded binary data

Examples

return syslib.debase64("YWJjZAsdsdsasdasAw==")

defaults

syslib.defaults([default_params])

Return Type

table

Description

Short name: syslib.def

When called without a table parameter, it resets the current defaults to the default defaults. When called with a table parameter, it copies valid defaults from the supplied table into the current defaults. The effects of this function apply only to the executing script and are preserved during the lifetime of a script environment.

Component Execution

All Components

Long Description

Code Label type default value Description

write_fetch

OPC Mode

number

1 (OPC_READ_CACHE_BEFORE_WRITE)

Define how to read the value before writing.

write_delay

Pack Delay

number

0

Time to wait in order to collect multiple writes.

write_audit

Audit write

boolean

false

Create audit in system log for write operation.

write_async

Write async

boolean

false

This currently has no user-visible effect, but setting this to true causes the system to do something that gets ultimately ignored, and should be avoided.

write_group

Force OPC DA 2.05

boolean

false

Defines which OPC write method should be used.

write_timeo

Write timeout

number

0

Currently has no effect.

hierarchical_event_data

Hierarchical event data

boolean

false

Get event data as a hierarchical table instead of a translated flat table when using syslib.getvalue()

event_history_table

Event history table

boolean

false

Make syslib.geteventhistory() return a table instead of a JSON string

log_opccom_calls

Log OPC COM calls

boolean

false

Setting this to true creates a log in system log for successful COM method calls on OPC classic server.

log_opccom_errors

Log OPC COM errors

boolean

false

Setting this to true creates a log in system log for failed COM method calls on OPC classic server.

The possible values for the write_fetch parameter are in the coding group OpcWriteMode:

  • "OPC_READ_CACHE_BEFORE_WRITE" (default)

  • "OPC_READ_DEVICE_BEFORE_WRITE"

  • "OPC_READ_OBJECT_BEFORE_WRITE"

  • "OPC_NO_READ_BEFORE_WRITE"

The possible values for the write_group parameter are:

  • False (default) - OPC write uses the DA 3.0 write method (IOPCSyncIO2::WriteVQT). This allows to write value, quality and timestamp.

  • True - OPC writes uses the DA 2.05 write method (IOPCSyncIO::Write). This allows to write value only. Some OPC Server do not support the DA 3.0 write method.

Parameters

Name Type Optional Description

default_params

table

no

A table containing the default parameters to be set.

Examples

syslib.defaults({write_group = true}) -- sets only the write_group default, keeping all the others intact
syslib.defaults({write_group = true, write_delay = 100}) -- sets write_group and write_delay, keeping all the others intact
local tab = syslib.defaults({}) -- sets nothing, gets the current defaults

deletefile

syslib.deletefile(pathspec [, name])

Return Type

table

Description

Some object properties can be used to store files in the system. The files themselves are stored in a MongoDB GridFS bucket. The files can be deleted using this function with the file name as the key.

On success, this function returns the metadata table of the deleted file, which can be an empty table if the file didn’t exist. Otherwise, it raises a Lua error if argument validation failed or returns nil and an error message in case of a runtime error.

This function works only on a property of type File or FileList.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec

variant

no

pathspec to a property from which the file should be deleted.

filter

string

maybe

The name of the file to be deleted. Optional if pathspec referes to a property of type File.

Examples

Delete a file which was stored as example.pdf in the Attachments property of an object.

local name = "example.pdf"
syslib.deletefile('/System/Core/Connector.Attachments', name)

deleteobject

syslib.deleteobject(objspec)

Description

Short name: syslib.del

Deletes an object.

Component Execution

Core only

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

syslib.deleteobject("/System/localhost/object")

deleterawhistory

syslib.deleterawhistory(pathspec, time_start, time_end [,datastore])

Description

Deletes a time span of raw history for an object.

All the parameters are mandatory. The time parameters are the numbers of milliseconds since the POSIX epoch. A time value that is not an integer number of hours is adjusted to a system-defined time boundary in an unspecified way. After the adjustment, if any, all the values stored for the specified object that are at or after the adjusted start time, and before the adjusted end time, are deleted.

If wrapped inside syslib.pcall(), the table returned in case of error may contain the field transient. This means that the error is temporary, therefore a new attempt may be successful.

Component Execution

Core only

Parameters

Name Type Optional Description

pathspec

pathspec

no

Path to object or property, the object itself, object or property ID, for which raw history is to be deleted.

time_start

integer

no

The timestamp (number of milliseconds since Epoch) of the start of the time span where raw history is to be deleted.

time_end

integer

no

The timestamp (number of milliseconds since Epoch) of the end of the time span where raw history is to be deleted.

datastore

storespec

yes

The strorespec to a data store from which the timeseries data should be deleted.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

syslib.deleterawhistory("/System/localhost/object", syslib.now() - 7 * 24 * 3600000, syslib.now())

digest

syslib.digest(text)

Return Type

string

Description

Returns the SHA256 digest of the string passed as argument. Instead of a string, the value returned from digestupdate can be passed to retrieve the computed digest.

Component Execution

All Components

Parameters

Name Type Optional Description

text

string

no

A generic string.

Error Messages

  • zero parameters were given, expected one. - the function has been called without arguments

  • more than one parameter was given, expected one. - the function has been called with more than one argument

  • bad argument #1 to 'digest' (either a string or userdata expected) - the argument was not a string or userdata

Examples

local content = syslib.getvalue("/System.ScriptLibrary.AdvancedLuaScript")[1] --get the content of the first custom library
local sha256 = syslib.digest(content)

digestupdate

syslib.digestupdate(digest, text)

Return Type

userdata

Description

Updates the digest with the text passed as the second argument. Using nil as the digest will create a new digest userdata and update it with the passed text. The newly created or passed digest is returned.

To retrieve the final digest value, the digest userdata needs to be passed to syslib.digest, which will reset the digest userdata such that it can be used again in syslib.digestupdate for new computations.

Component Execution

All Components

Parameters

Name Type Optional Description

digest

nil or userdata

no

nil or a digest userdata

text

string

no

A generic string.

Error Messages

  • expected two argument - the function has been called with the wrong number of arguments

  • digest update failed - updating the digest failed

Examples

local io = require 'io'

local filepath = "C:\\temp\\doc.pdf"
local file = assert(io.open(filepath, "rb"))

local sha256
while true do
    local block = file:read(1024)
    if not block or block:len() == 0 then break end
    sha256 = syslib.digestupdate(sha256, block)
end
return syslib.digest(sha256)

digestlib

syslib.digestlib(lib_name)

Description

Returns the SHA256 digest of the library libname that is embedded in the executable. The main use of this function is to obtain the digest of a built-in library and compare it with the digest of the overloaded library (a Lua library stored in an AdvancedLuaScript property that has the same name as the one shipped with the executable). The latter can be obtained with syslib.digest(text).

Component Execution

All Components

Parameters

Name Type Optional Description

lib_name

string

no

The name of a built-in library.

Error Messages

  • zero parameters were given, expected one. - the function has been called without arguments

  • more than one parameter was given, expected one. - the function has been called with more than one argument

  • bad argument #1 to 'digestlib' (string expected, got …​) - the argument was not a string

  • no built-in library name can be deduced from …​ (compatibility mode: …​). - the process has not been able to find a built-in library from the specified name

Examples

local table = syslib.getvalue("/System.ScriptLibrary.LuaModuleName")

local i = 1
for _,value in ipairs(table) do
    if(syslib.digest(syslib.getvalue("/System.ScriptLibrary.AdvancedLuaScript")[i]) == syslib.digestlib(value)) then
        print(value)
    end
    i=i+1
end

disableobject

syslib.disableobject(objspec)

Description

Short name: syslib.dis

Disables an object.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

syslib.disableobject("/System/localhost/object")

dumpimage

syslib.dumpimage(path)

Return Type

string

Description

Dumps the objects under the immation component to an image file. The function also creates a copy of the fingerprint file and a db file which contain some details necessary for the component to function. This function can be used to back up the current state of the objects under the component. The function deletes any existing image, fingerprint and db files with the same path as the argument before starting the dump.

Component Execution

All Components

Parameters

Name Type Optional Description

path

string

no

A valid path in the filesystem including the filename.

Error Messages

  • another image dump is already in progress - Only one image dump operation can be uder progress at any point in time. Please try again after the current operation is finished.

  • dump path invalid - The path argument is invalid

  • path '…​' does not exist - The path mentioned in the message does not exist. Please provide a path that exists.

  • dump path provided is an existing directory - The path is an existing folder. Please provide a path including the file name.

  • a file system error occurred: …​ - An error occurred while interacting with the file system. Please refer to the rest of the message for more details.

  • an exception was caught: …​ - An exception was caught during the operation. Please refer to the rest of the message for more details.

  • an unexpected error occurred - An unexpected error occurred. If the error persists, please contact support with steps to reproduce the problem.

Examples

syslib.dumpimage("D:\\backup\\core_snapshot")
syslib.dumpimage("D:/backup/core_snapshot")

The two examples above are equivalent and create three files called "core_snapshot.inimgdump", "core_snapshot.infpdump" and "core_snapshot.dbdump" at "D:/backup". These files contain the state of the component at the time the function was called and can be used to restore the component to that state at a later point in time.

enableobject

syslib.enableobject(objspec)

Description

Short name: syslib.ena

Enables an object.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

syslib.enableobject("/System/localhost/object")

enbase64

syslib.enbase64(bytes)

Return Type

string

Description

Returns ASCII representation of binary data using Base64 binary-to-text encoding schema.

Component execution

All components

Parameters

Name Type Optional Description

bytes

string

no

Lua string to be interpreted as raw binary data

Examples

return syslib.enbase64("\97\98\99\100") -- result: "YWJjZA=="

excel2posix

syslib.excel2posix(exl_time)

Return Type

number

Description

Converts Excel time to POSIX time.

Component execution

All components

Parameters

Name Type Optional Description

exl_time

number

no

Excel time as a double number.

Examples

local psx_time = syslib.excel2posix(25569.52) -- 44928000
return syslib.gettime(psx_time) -- result: 1970-01-01T12:28:48.000Z

execute

syslib.execute(objspec, chunk, timeout)

Return Type

nil

Description

Executes a Lua chunk, potentially in a remote component.

The executing component is either the Core component which invokes the syslib.execute() call, or the Connector component closest to the object specified by objspec. Remote execution in other components is not supported. The chunk executes in a dedicated thread, which terminates as soon as the chunk returns.

If the timeout is nil or a non-zero number, the chunk executes synchronously, i.e., the call to syslib.execute() blocks till the remote chunk terminates or times out. In this case, the return values of the remote chunk are returned by syslib.execute(). If the remote chunk raises a compilation or execution error, the error is returned.

If the timeout is zero, the chunk executes asynchronously, i.e., syslib.execute() returns as soon as the chunk is scheduled for the transmission to the remote component. Neither normal nor return values are transferred. This is a low level mode, and the user will typically want to use, for example, messaging API to communicate and synchronize execution.

The default timeout is 30000 milliseconds. A non-zero value is adjusted to at least 30000 milliseconds.

When syslib.execute synchronously executes a Lua chunk in a remote Connector component, the call can time out for several reasons. Because such calls involve network communication, they are inherently different from calls which don’t. In general, syslib.execute should not be called repeatedly in a rapid fashion from the same Lua script.

Component Execution

Core Components

Parameters

Name Type Optional Description

objspec

variant

no

The object in the context of which the chunk will execute.

chunk

string

no

A string that is the Lua chunk (i.e., Lua code) to execute.

timeout

number

yes

The execution timeout, in millisceonds.

The objspec parameter specifies the current object during execution. This means that a call to getself returns objspec and not necessarily the component that the Lua code is running on. If objspec is referring to an object under a connector (or the connector itself) then the Lua chunk is executed remotely on this connector.

Examples

syslib.execute('/System/core/connector', 'return "Hello from connector" ')

findobjects

syslib.findobjects(str, [model], [dynonly], [fullpath])

Return Type

table

Description

Returns an array of all inmation objects which contain the string str in their names or paths (see fullpath parameter below) and satisfy the criteria of the optional arguments. Searches in the entire tree structure.

Component Execution

All Components

Parameters

Name Type Optional Description

str

string

no

The string to be searched (case-insensitive).

model

number

yes

A number representing the model code where the search is performed. Default is 0 - all class models.

dynonly

boolean

yes

A boolean specifying if the search is performed only on dynamic objects. Default is false.

fullpath

boolean

yes

A boolean specifying whether the search is performed on the entire paths of objects or just their names. Default is false.

Examples

Search for "target" in the names of all objects of all models:

local tab = syslib.findobjects("target")

Search for "target" in the paths of dynamic objects of the I/O Model:

local tab = syslib.findobjects("target", 1, true, true)

Given the following tree:

--   System
--       |__ Core
--             |__ A
--             |   |__ B
--             |__ A/B
--             |__ G/H

Object A^/B can be found by searching for: * A or B in objects names or paths. * A^/B (not A/B due to path ambiguity with object B) in objects names or path.

Object G^/H can be found by searching for: * G or H in objects names or paths. * G^/H (or G/H as there is no path ambiguity) in objects names or path.

foldcase

syslib.foldcase(string)

Return Type

string

Description

Converts a string into lowercase and returns it. It also takes into account non-ASCII characters.

Component Execution

All Components

Parameters

Name Type Optional Description

string

string

no

The string to be converted.

Examples

return syslib.foldcase("Förderband Eingänge 3") -- returns förderband eingänge 3

getattributesex

syslib.getattributesex(datasource, item_ids, [attribute_ids], [skip_values])

Return Type

table

Description

Returns attribute information of itmes from an OPC-compliant data source.

Component Execution

Connector only

Parameters

Name Type Optional Description

datasource

variant

no

Path to or a Datasource object.

item_ids

variant

no

An item-id (string) or a table of items-ids, for which the attributes will be returned.

attribute_ids

table

yes

By default all relevant attributes of the specified item-ids will be returned. attribute_ids can be specified if only a subset of available attributes are required. Formats and details of this argument is given below.

skip_values

boolean

yes

If set to TRUE, the values of the individual attributes will not be returned. FALSE by default.

attribute_ids

The attribute_ids argument is expected to be a table of valid attribute ids, corresponding to the type of the data source.

  • OPC-HDA compliant datasources:

    The attribute ids must be valid integer values as supported by the server. hdagetitemattributes function can be used to obtain the list of attribute-ids(tags) supported by the server.

  • OPC-UA compliant datasources:

    The attribute ids can be:

    • Integer : Representing the standard UA Attributes of a node.

    • String : Browse name of references for an item with reference type "HasProperty" ("ns=0;i=46").

Only OPC-HDA and OPC-UA compliant datasources are supported. If a datasource supports both DA and HDA specifications, only HDA specific attributes will be returned by this function.

Return Value Description

The function returns a Lua table-of-tables, where every subtable contains the information of the specified attributes per item-id. Every subtable contains the following entries per attribute, if available from the server:

Key DataType Description

tag

integer

Attribute id.

name

string

Name of the attribute.

description

string

Description of the attribute. Only returned for OPC-HDA sources.

type

integer

Data type of the attribute (integer representation of the variant type). Only returned for OPC-HDA sources.

value

table

Value of the attribute. Table with fields V, Q, T, which are arrays of values, qualities and timestamps, respectively.

err

integer

0 = Success and 1 = error in retrieving the value of the attribute.

Examples

OPC-HDA compliant source

local values = syslib.getattributesex("/System/Core/localhost/Matrikon.OPC.Simulation.1",
                {"Random.Int4"} , -- items to be read
                {1,2,13}          -- attributes of the items to be returned
                )
return require('rapidjson').encode(values)

Returned values:

[
  [
    {
      "name": "DATA_TYPE",
      "type": 2,
      "value": {
        "Q": {},
        "T": 1564147349469,
        "V": 3
      },
      "err": 0,
      "tag": 1,
      "description": "Data type"
    },
    {
      "name": "DESCRIPTION",
      "type": 8,
      "value": {
        "Q": {},
        "T": 1564147349469,
        "V": "Random value."
      },
      "err": 0,
      "tag": 2,
      "description": "Item Description"
    },
    {
      "name": "ITEMID",
      "type": 8,
      "value": {
        "Q": {},
        "T": 1564147349469,
        "V": "Random.Int4"
      },
      "err": 0,
      "tag": 13,
      "description": "Item ID"
    }
  ]
]

OPC-UA compliant source

local values = syslib.getattributesex("/System/Core/localhost/UACPP",
                {"ns=2;s=Demo.Static.Scalar.Int64"} , -- items to be read
                {1,2,13}                           -- attributes of the items to be returned
                )
return require('rapidjson').encode(values)

Returned values:

[
  [
    {
      "tag": 1,
      "name": "NodeId",
      "err": 0,
      "value": {
        "T": -11644473600000,
        "Q": 0,
        "V": "ns=2;s=Demo.Static.Scalar.Int64"
      }
    },
    {
      "tag": 2,
      "name": "NodeClass",
      "err": 0,
      "value": {
        "T": -11644473600000,
        "Q": 0,
        "V": 2
      }
    },
    {
      "tag": 13,
      "name": "Value",
      "err": 0,
      "value": {
        "T": 1563970440656,
        "Q": 0,
        "V": 0
      }
    }
  ]
]

getaudittrail

syslib.getaudittrail(objspec(s), options)

Return Type

table

Description

This function retrieves Audit Trail entries from the repository.

To use this function, the profile of the user should have either System-wide Reviewer or Limited Reviewer Audit Trail Roles assigned (see Enabling Audit Trail Hands on for more details).

The schema of documents returned by this function is described here.

If wrapped inside syslib.pcall(), the table returned in case of error may contain the field transient. This means that the error is temporary, therefore a new attempt may be successful.

Component Execution

Master Core only

Parameters

Name Type Optional Description

objspec(s)

variant

yes

Object’s path, the object itself or the object ID. Or a table of objspecs. When no object is specified, Audit Trail entries for all objects are returned.

options

table

yes

Options that may be used while querying the repository.

Below is a list of supported options.

Name Type Optional Description

time_start

integer

yes

The timestamp (number of milliseconds since Epoch) of the beginning of the range of time to be queried.

time_end

integer

yes

The timestamp (number of milliseconds since Epoch) of the of the range of time to be queried.

skip

integer

yes

Number of documents to skip. Defaults to 0.

limit

integer

yes

The maximum number of documents to return. If unspecified, then defaults to no limit. A limit of 0 is equivalent to setting no limit.

type

integer

yes

A bitwise OR combination of AuditTrailTypes flags. Defaults to all types.

projection

table

yes

A table of strings representing document fields to be returned. Defaults to all fields.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

  • The user doesn’t have permission to view Audit Trail for all the objects specified - the user doesn’t have the necessary permission to view Audit Trail for the objects. See Enabling Audit Trail Hands on for more details.

  • The user doesn’t have permission to view Audit Trail. - The user doesn’t have any Audit Trail Reviewer roles assigned. See Enabling Audit Trail Hands on for more details.

Examples

return syslib.getaudittrail({'/System/Core'}, {limit = 100, time_start = syslib.gettime("2020-03-30T11:41:55.940Z"),
    time_end = syslib.gettime("2020-05-17T14:41:55.940Z"), projection = {"ts", "obj.objid"},
    type = syslib.model.flags.AuditTrailTypes.CONFIG_CHANGE | syslib.model.flags.AuditTrailTypes.EXT_WRITE})

getbackreferences

syslib.getbackreferences(objspec)

Return Type

table

Description

Short name: syslib.brefs

The function returns an array, whose elements are a table with three fields: name (of the reference), path (to the referencing object), and type (of the reference). The type can be either a string or an integer, with the following possible string values:

  • "SECURITY" - security reference

  • "OBJECT_LINK" - triggering reference

  • "PROPERTY_LINK" - process value link

  • "OBJECT_LINK_PASSIVE" - non-triggering reference

These are listed in the ReferenceType coding group. The numeric type typically encodes a security reference with access right permissions.

The returned table meets the expectations of syslib.setreferences.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

Error Messages

  • invalid number of arguments - the number of arguments is not as expected

  • Object could not be resolved - the object path or id could not be resolved

Examples

return syslib.getbackreferences(syslib.getcorepath() .. '/DataHolder_01') -- the detailed list of back-references on object DataHolder_01

getconnectorpath

syslib.getconnectorpath(objspec)

Return Type

string

Description

Short name: syslib.connp

Takes as parameter an object path or nil (in the latter case, the path defaults to the current object). It returns the path of the first connector object found when traversing the model hierarchy upwards, starting at the object specified with the objspec parameter, or nil if no connector object was found in the parent objects hierarchy.

Component Execution

Connector only

Parameters

Name Type Optional Description

objspec

variant

yes

Object’s path, the object itself or the object ID. By default it is the path to the current object containing the script.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

-- Assume there is a connector at the following path: "/System/Core/localhost"
return syslib.getconnectorpath("/System/Core/localhost/folder/object") -- returns "/System/Core/localhost"
return syslib.getconnectorpath("/System/Core/object") -- returns nil

getcorepath

syslib.getcorepath(objspec)

Return Type

string

Description

Short name: syslib.corep

If the argument is an object not in the IO-model, the function returns nil.

If the argument is an object in the IO-model, the function traverses the model hierarchy upwards, starting at the object specified with the objspec argument, and returns the path to the first core object found.

If the argument is an object in the IO-model which does not have a parent core or if no argument is passed or if the argument is nil, then it works as if the objspec of the component in which the function is being executed is passed as the argument to this function.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

yes

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

-- Assume that there is a core at the following path: "/System/Core", a LocalCore at "/System/Core/LocalCore" and a Connector at "/System/Core/Connector"
return syslib.getcorepath("/System/Core/Connector/folder/object") -- returns "/System/Core"
return syslib.getcorepath("/System/Core/LocalCore/folder/object") -- returns "/System/Core/LocalCore"
return syslib.getcorepath("/System") -- returns "/System/Core/LocalCore" when called from "/System/Core/LocalCore/ActionItem"
return syslib.getcorepath() -- returns "/System/Core" when called from "/System/Core/ActionItem"
return syslib.getcorepath() -- returns "/System/Core/LocalCore" when called from "/System/Core/LocalCore/ActionItem"
return syslib.getcorepath() -- returns "/System/Core" when called from "/System/Core/Connector"
return syslib.getcorepath() -- returns "/System/Core" when called from "/Enterprise/Site/Asset/ActionItem" if the Site's "Code Execution" property is set to Core.
return syslib.getcorepath() -- returns "/System/Core/LocalCore" when called from "/Enterprise/Site/Asset/ActionItem" if the Site's "Code Execution" property is set to LocalCore

getdefaults

syslib.getdefaults()

Return Type

table

Description

Returns the current default values for read/write SCI. See defaults function for a list of all the possible default values.

Component Execution

All Components

Examples

return syslib.getdefaults().write_delay

getdefaultstore

syslib.getdefaultstore(pathspec, [allow_remote])

Return Type

number

Description

This function returns the object id of a Time Series Store that is currently configured as an archive target for the property given by the pathspec argument. If the archive target is a data store set, then a local data store is prefered. If allow_remote is true and there is no local data store, then a remote data store is returned.

A system store is specified by the ArchiveTarget coding group. So if an item is historizing to the system production store then syslib.getdefaultstore returns the value 2. This is in accordance with what gethistory expects from its datastore parameter, so the result of syslib.getdefaultstore can be used here directly.

On a local core, the function needs to query the master core if allow_remote is true and there is no local default store.

Component Execution

Core only

Parameters

Name Type Optional Description

pathspec

pathspec

no

Property (or object with a default property) that can be historized.

allow_remote

boolean

yes

If not specified or if set to false only local data stores are considered.

Error Messages

  • property not found - the given pathspec cannot be resolved to a property.

  • error resolving remote default store - there is an issue on a local core when communicating with the master core to resolve a remote default store

  • permission denied - the caller does not have READ permission for the given pathspec

Examples

The following example shows how to retrieve the history of an item that is historizing to a remote data store.

local start_time = syslib.currenttime() - 60000 -- last minute
local end_time = syslib.currenttime()
local item_path = "/System/mastercore/localcore/item"
local aggs = {"AGG_TYPE_INTERPOLATIVE"}
local data_store = syslib.getdefaultstore(item_path, true)
local history = syslib.gethistory({item_path}, start_time, end_time, 100, aggs, nil, nil, nil, nil, nil, data_store)

geteventhistory

syslib.geteventhistory(paths, start, end, [options])

Return Type

string/table - a serialized JSON which needs to be decoded into a Lua table to make it accessible

Description

This function returns historical events for the given objects within the interval provided. A set of options to filter and process the event data can also be passed to the function.

If wrapped inside syslib.pcall(), the table returned in case of error may contain the field transient. This means that the error is temporary, therefore a new attempt may be successful.

Component Execution

Core only

Parameters

Name Type Optional Description

paths

table

no

A table containing either the paths of the objects (objspec) or the objects to be queried for historical events.

start

number

no

A number representing the start time in milliseconds (UTC time).

end

number

no

A number representing the end time in milliseconds (UTC time).

options

table

yes

Options to filter and process event data.

Below is a list of supported options.

Name Type Optional Description

data_store

objspec

yes

Specifies a data store for the query operation. If not specified, this defaults to the System Event Data Store for Master Cores. For Local Cores, this option is required. The value should be an objspec, identifying the System object or a Custom Event Store object.

filter

string

yes

A MongoDB document as a JSON string to filter the event data. Knowledge of MongoDB and the schema of event documents is required to create the document.

sort

string

yes

A MongoDB document as a JSON string to sort the event data. Knowledge of MongoDB and the schema of event documents is required to create the document.

projection

string

yes

A MongoDB document as a JSON string to be used for projection. Knowledge of MongoDB and the schema of event documents is required to create the document.

limit

number

yes

Maximum number of event documents to be returned.

skip

number

yes

Number of matching event documents to skip before returning up to limit results.

transformation

string

yes

A string to indicate the format of the returned document. The accepted strings are "none", "readable", "readable_lc", "kv" and "kv_lc". "none" is used by default. This field can’t be used when "projection" is also specified.

Event Document Schema

Below is a representation of the schema of event documents.

\
│   _id (MongoDB ID)
│   i   (magic number)
│
└───e_  (Event Data)
    └───s_ (System)
    │   │   a   (System Flags)
    │   │   b   (Source Flags)
    |   │   c   (State Flags)
    │   |   i   (Core Event ID)
    │   │   n   (Connector Event ID)
    |   │   o   (Event Stream Object ID)
    |   │   g   (Origin Event Stream Object ID)
    │   |   p   (Data Source Object ID)
    │   │   q   (Core Target Object)
    |   │   r   (Server Routes)
    │   |   t   (Timestamp)
    │   │   u   (Core Reception)
    │   │   x   (Stream Counter)
    │   │   y   (Replicas)
    │   │   z   (SafKey)
    │   │
    │   └───a_  (Stage)
    │       │   a   (State Flags)
    │       │   c   (Commands)
    │       │   e   (Stage Errors)
    │
    └───c_ (Common)
    │   │   m   (Message)
    │   │   t   (Timestamp)
    │
    └───o_ (OPC Classic Event)
    |   │   f   (Flags)
    |   └───h_  (Header)
    |   |   └───c_  (Category)
    |   |   |   |   c   (Code)
    |   |   |   |   t   (Text)
    |   |   |   |
    |   |   |   f   (Flags)
    |   |   |
    |   |   └───m_  (Condition)
    |   |   |   |   c   (Code)
    |   |   |   |   t   (Text)
    |   |   |
    |   |   |   n   (New State)
    |   |   |   o   (State Change)
    |   |   |   q   (Quality)
    |   |   |
    |   |   └───r_  (Severity)
    |   |   |   |   c   (Code)
    |   |   |   |   t   (Text)
    |   |   |
    |   |   └───s_  (SubCondition)
    |   |   |   |   c   (Code)
    |   |   |   |   t   (Text)
    |   |   |
    |   |   |   t   (Timestamp)
    |   |   |   u   (Time Active)
    |   |   |
    |   |   └───x_  (Source)
    |   |   |   |   i   (Item ID)
    |   |   |   |   o_  (Objects)
    |   |   |
    |   |   |   y   (Number of Attributes)
    |   |
    |   └───a_  (Attributes)
    |       |   f   (Flags)
    |       |   i   (Number Indicated)
    |       |   n   (Number Good)
    |       |
    |       └───a_  (Array of Custom Attributes)
    |           └───0    (First Custom Attribute)
    |           |   |   c   (Code)
    |           |   └───d_
    |           |   |   |   d   (data type)
    |           |   |   |   v   (Value)
    |           |   |   |   q   (Quality)
    |           |   |   |   t   (Timestamp)
    |           |   |   |   n   (Update Count)
    |           |   |
    |           |   |   f   (Flags)
    |           |   |   l   (Label)
    |           |   |   v   (Value Type Indicated)
    |           |
    |           └───1    (Second Custom Attribute)
    |           |            ...
    |           └───2    (Third Custom Attribute)
    |           ...
    |
    └───u_ (OPC UA Event)
        └─── "2041" (BaseEventType)
              |
              └─── "2042" (EventId)
              |     └───d_ (data)
              |
              └─── "2043" (EventType)
              |      └───d_ (data)
              ...
If the Origin Event Stream Object ID field is absent or zero, it can be treated as if it has the same values as the Event Stream Object ID field. It is different from Event Stream Object ID if the event was historized by a Redundant Event Stream and in this case identifies the original Event Stream which captured this event.
OPC UA events are represented with the same hierarchy that the UA Event Types are present in the server’s address space. The standard well-known nodes are represented using their numeric node-ids. Any vendor specific types are stored in the document with their browse names.
Please refer to event_history_table in syslib.defaults() to make this function return a table instead of a JSON string.

Examples

  • Get all events for two given objects in the last hour.

syslib.geteventhistory({'/System/Core/ScriptEvent1', '/System/Core/Connector/ScriptEvent2'}, syslib.now() - 24 * 60  * 60000, syslib.now())
  • Get all events for two given objects in the last hour from a custom event data store.

syslib.geteventhistory({'/System/Core/ScriptEvent1', '/System/Core/Connector/ScriptEvent2'}, syslib.now() - 24 * 60  * 60000, syslib.now(),
{
  data_store = "/System/Core/CustomEventStore1"
})
  • Get 20 events for the given objects in the last hour where a custom attribute’s value is greater than 10.

syslib.geteventhistory({'/System/Core/ScriptEvent1', '/System/Core/Connector/ScriptEvent2'}, syslib.now() - 24 * 60  * 60000, syslib.now(),
{
    filter = '{"e_.o_.a_.a_": {"$elemMatch": {"l":"custom-attribute-1", "d_.v":{"$gt" :"10"}}}}',
    limit = 20
})
  • Get timestamp and object id of events for the given objects in the last hour where a custom attribute’s value is greater than 10, sorted by the timestamp of the event.

syslib.geteventhistory({'/System/Core/ScriptEvent1', '/System/Core/Connector/ScriptEvent2'}, syslib.now() - 24 * 60  * 60000, syslib.now(),
{
    filter = '{"e_.o_.a_.a_": {"$elemMatch": {"l":"custom-attribute-1", "d_.v":{"$gt" :"10"}}}}',
    projection = '{"e_.c_.t" : 1, "e_.s_.o":1, "_id":0}',
    sort = '{"e_.c_.t" : -1}'
})
  • If node-ids of the OPC UA Event Types to be filtered by are known, one can use the numeric codes directly as shown below. Here we are looking for all events where the SourceName (node-id ns=0;i=2045) of an event is equal to SampleEventNotifier. SourceName is the child of the node BaseEventType (node-id ns=0;i=2041) in standard OPC UA address space. We also project the Severity (node-id ns=0;i=2051) of the filtered events.

local str = syslib.geteventhistory({'^/System/Core/Local/opc.tcp:^/^/localhost:48020/es'}, 0, syslib.now(),
  {
    filter = '{"e_.u_.2041.2045.d_":{"$eq": "SampleEventNotifier"}}',
    projection = '{"e_.u_.2041.2051.d_": 1, "_id":0}'
  }
)
  • If the OPC UA node-ids are not known, the coding group syslib.model.codes.UaEventType can be used to map human readable strings to numeric codes. The query above can also be written in the following way.

local query_format_string ='{"e_.u_.%s.%s.d_":{"$eq": "SampleEventNotifier"}}'
local query = string.format(query_format_string, syslib.model.codes.UaEventType.BASEEVENTTYPE, syslib.model.codes.UaEventType.BASEEVENTTYPE_SOURCENAME)
local projection_format_string = '{"e_.u_.%s.%s.d_": 1, "_id":0}'
local projection = string.format(projection_format_string, syslib.model.codes.UaEventType.BASEEVENTTYPE, syslib.model.codes.UaEventType.BASEEVENTTYPE_SEVERITY)
local str = syslib.geteventhistory({'^/System/Core/Local/opc.tcp:^/^/localhost:48020/es'}, 0, syslib.now(),
  {
    filter = query,
    projection = projection
  }
)

The coding group syslib.model.codes.UaEventType can also be used to map the numeric codes from the returned documents to human readable strings.

getfile

syslib.getfile(pathspec [, filter])

Return Type

string, table

Description

Some object properties can be used to store files in the system. The files themselves are stored in a MongoDB GridFS bucket. The files can be retrieved using the file name as the key. The content of the file is returned as a string.

If pathspec specifies a File property, the name parameter can be omitted. Otherwise, it is mandatory.

On success, the function returns the file contents and its metadata table. Otherwise, it raises a Lua error if argument validation failed or returns nil and an error message in case of a runtime error.

If wrapped inside syslib.pcall(), the table returned in case of error may contain the field transient. This means that the error is temporary, therefore a new attempt may be successful. NOTE: This function works only on a property of type File or FileList.

Since files are stored in MongoDB and they may be huge, it may potentially take a long time for this function to return. Hence, it is recommended to call this function from a dedicated thread.

Component Execution

Master Core only

Parameters

Name Type Optional Description

pathspec

variant

no

pathspec to a property from which the file should be returned.

filter

variant

yes

A filter specification used when looking up files. See the getfilemetadata function for details.

Examples

Retrieve a file which was stored in the Attachments property of an object as example.pdf and write it to the disk.

local io = require "io"
local name = "example.pdf"
local data = syslib.getfile('/System/Core/Connector.Attachments', name)
local outfile = assert(io.open("C:\\tmp\\example_retrieved.pdf", "wb"))
outfile:write(data)

getfilemetadata

syslib.getfilemetadata(pathspec [, filter])

Return Type

table [, string]

Description

Some object properties can be used to store files in the system. The files themselves are stored in a MongoDB GridFS bucket. The metadata of existing files can be retrieved using this function.

On success, the function returns the metadata table. Otherwise, it raises a Lua error if argument validation failed or returns nil and an error message in case of a runtime error.

This function works only on a property of type File or FileList.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec

variant

no

pathspec to a property from which the file metadata should be returned.

filter

variant

yes

A filter specification used when looking up metadata.

The filter parameter consists of zero or more arguments used to match a particular file entry. It’s grammar is:

filter    = [ prev ] , ( string | pairs | ( condition , [ mode ] ) | function )
prev      = nil | integer | table
pairs     = pair , [ "," , pairs ]
pair      = string , "," , value
condition = "{" , fields , [ ", custom = " , condition ] , "}"
fields    = string , "=" , value , [ "," , fields ]
value     = ? any Lua value ?

A filter can have an optional start value prev which is typically the metatable obtained from a previous call to continue iterating over all matching entries. It may also be an integral row index (negative values are relative to the last row, i.e. specifying -2 returns the last table row if it matches).

The next symbols define the filter criteria.

The simplest form is a single string value matching the name metadata field.

To match multiple fields simultaneously use pairs, which is a list of key - value pairs which all have to match a metadata entry.

condition is similar to pairs, but the key - value pairs are encoded as a regular Lua table.

To match custom metadata fields, the key needs to be prefixed with "custom." for the pairs filter, or nested inside a "custom" table in a condition filter. If a condition filter is used, an optional mode string can be specified to control how string values are matched. The mode can be "e" (case-sensitive equality, the default) or "p" (string values in the condition are used as a Lua pattern to match against the metadata field).

Finally, a filter can be a function which is called for each metadata entry until it returns true or all entries have been visited.

The filter values are matched against metadata values case-sensitively. For full control, use a function filter.

Examples:

filter Behavior

nil

matches the first file entry

report.pdf

matches the metadata with a name field equal to "report.pdf"

"extension", "pdf"

matches the first metadata entry with a "pdf" file extension field

3, "extension", "pdf", "custom.approved", false

starts at the fourth entry and matches the first entry with a "pdf" extension field and a custom field "approved" set to false

3, { extension = "pdf", custom = { approved = false } }

same as the previous filter

function(meta) return meta.size < 1024 end

matches the first metadata entry with file size < 1 KB

Examples

Retrieve metadata of a file example.pdf in the Attachments property of an object.

local name = "example.pdf"
local proppath = "/System/Core/Connector.Attachments"
local metadata = syslib.getfilemetadata(proppath, name)

Retrieve all PDF documents

local proppath = "/System/Core/Connector.Attachments"
local pdffiles = {}
local meta
repeat
  meta = syslib.getfilemetadata(proppath, meta, "extension", "pdf")
  table.insert(pdffiles, meta)
until not meta
return pdffiles, meta

gethistory

syslib.gethistory(paths, start, end, [intervals_no], [aggregates], [percentage_good], [percentage_bad], [treat_uncertain_as_bad], [sloped_extrapolation], [partial_interval_treatment], [datastore])

Return Type

table

Description

Short name: syslib.hist

This function returns historical data according to the specified aggregate(s), which conform to the OPC UA standard.

Each given path is mapped to the aggregate which corresponds to its index, i.e. the item at paths[i] will be mapped to the aggregate at aggregates[i]. If there are more objects than aggregates, the extra objects will be mapped to the last aggregate in the aggregates table. If multiple aggregates are desired for the same object, then the object’s path has to be repeated in the paths table. The resulting table structure is:

1 = {
    1 = { V = v1, S = s1, T = t1 },
        ...,
        intervals_no =  { V = vn, S = sn, T = tn }
    },
    ...,
    paths_no =  {
        1 = { V = v1, S = s1, T = t1 },
        ...,
        intervals_no =  { V = vn, S = sn, T = tn }
    }
}

A table is represented like: {key_1 = value_1, …​, key_n = value_n} The keys V, S, T represent value, status, timestamp respectively. If the requested aggregate is AGG_TYPE_RAW, then to each V, S, T corresponds a table containing all the raw values available in the given interval of time. Otherwise, the V, S, T keys map single values, which are the result of aggregating the existing raw values. The status is made of two parts: aggregation flag + quality code.

A code snippet as below can be used to mask out the aggregation flags and retrieve a 32-bit UA quality code:

local status_code = 8589934592
local ua_quality = status_code & 0xFFFFFFFF

Aggregation flags are as follows:

Name Code Description

AGG_STATUS_UNDEFINED

0x000000000

Undefined

AGG_STATUS_PARTIAL

0x100000000

Partial interval

AGG_STATUS_CALCULATED

0x200000000

Calculated value

AGG_STATUS_INTERPOLATED

0x400000000

Inter (Extra-) polated value

AGG_STATUS_RAW

0x800000000

Raw value

AGG_STATUS_MULTI_VALUE

0x1000000000

Multi-value

They are compliant to the OPC UA specification. For example 0x200000000 means AGG_STATUS_CALCULATED + GOOD QUALITY.

If wrapped inside syslib.pcall(), the table returned in case of error may contain the field transient. This means that the error is temporary, therefore a new attempt may be successful.

Component Execution

Core only

Parameters

Name Type Optional Description

paths

table

no

A table containing either the paths of the objects or the objects to be queried for historical information.

start

number

no

A number representing the start time in milliseconds (UTC time).

end

number

no

A number representing the end time in milliseconds (UTC time).

intervals_no

number

yes

The number of intervals in the [start, end] timespan; by default 100. Note: The end time value itself is not included in the timespan.

aggregates

table

yes

A table containing the aggregate types as string code; by default \{"AGG_TYPE_INTERPOLATIVE"}.

percentage_good

number

yes

A number representing the percentage of values to be returned that have quality "good"; by default 100.

percentage_bad

number

yes

A number representing the percentage of values to be returned that have quality "bad"; by default 100.

treat_uncertain_as_bad

boolean

yes

Indicates how the server treats data returned with a StatusCode severity 'Uncertain', with respect to Aggregate calculation; optional parameter. By default false.

sloped_extrapolation

boolean

yes

Indicates how the server interpolates data when no boundary value exists (i.e. extrapolating into the future from the last known value); optional parameter. By default false.

partial_interval_treatment

string

yes

By default "UASTANDARD".

datastore

storespec

yes

The storespec to a data store from which the timeseries data should be retrieved. If an object is only historizing to stores that are not local to this component, this option must be specified. Use getdefaultstore to get a default remote store.

Examples

The following example shows how to collect the values from the resulting tables with respect to the requested aggregate.

local paths = {"/System/Core/hist", "/System/Core/hist2"}
local aggregates = {"AGG_TYPE_RAW", "AGG_TYPE_AVERAGE"}
local intervals = 10
local start_time = syslib.currenttime() - 60000 -- last minute
local end_time = syslib.currenttime()

local res = syslib.gethistory(paths, start_time, end_time, intervals, aggregates)

local values_raw = {}
for i = 1, intervals do
    raw_interval = res[1][i].V
    for j = 1, #raw_interval do
        table.insert(values_raw, raw_interval[j])
    end
end

local values_avg = {}
for i = 1, intervals do
    table.insert(values_avg, res[2][i].V)
end

return table.concat(values_raw, " | ") .. " && " .. table.concat(values_avg, " | ")

When the time period of the historization is not precisely known, the syslib.gethistoryframe function can be used in order to get the time interval start and end point of the entire historized data for a specific item. The example below shows how historic raw data can be collected and written to another item using the syslib.sethistory function:

local item_path = "/System/localhost/item"

local startt, endt = syslib.gethistoryframe(item_path)
local hist = syslib.gethistory({item_path}, startt, endt, 1, {"AGG_TYPE_RAW"})

-- we have 1 item and 1 interval so in order to access the raw data
-- we use hist[1][1]
local data = hist[1][1]

local ID = syslib.getpropertyid("/System/localhost/item2")
for i = 1, #data.V do
    syslib.sethistory(ID, data.V[i], data.Q[i], data.T[i])
end

Observations

Because of their nondeterministic time of execution, scripts having history calls should be run on a separate thread. To do this, go to the Object Properties view of the item that contains the script and then, under Common menu, tick Dedicated Thread Execution. In order to obtain the duration of a history call, the syslib.currenttime function can be used as follows:

local t1 = syslib.now() -- insert syslib.history function call here
local total_time = syslib.currenttime() - t1
return total_time -- the duration of the call in milliseconds
Objects located beneath the Connector are unable to access the time-series repository. Therefore, executing scripts that request historical data from any location other than below the Core object will return the error: "Attempt to access historical data from a component that does not have the time-series repository". This applies to all functions that access historical data (excluding syslib.gethistoryex as this function does not request data from the time-series repository)

gethistoryex

syslib.gethistoryex(datasource, ids, [start], [end], [max_values], [bound_required], [modified_info])

Return Type

table

Description

Returns historical data from an external HDA/UA server.

Component Execution

Connector only

Parameters

Name Type Optional Description

datasource

string

no

Path to or a Datasource object (objspec).

ids

string

no

Tag (Item ID) or an array of them.

start

number

yes

Start time, can be integer number of milliseconds since POSIX epoch, nil or string per OPC HDA 1.2, section 5.3.4.

end

number

yes

End time, can be integer number of milliseconds since POSIX epoch, nil or string per OPC HDA 1.2, section 5.3.4.

max_values

number

yes

Max number of values, 0 if unrestricted (as default).

bound_required

boolean

yes

Indicates whether bounding values are required, false by default.

modification_info

boolean

yes

Indicates whether information about modifications to historical data is to be retrieved, false by default. This argumment is applicable only for OPC UA datasources.

Examples

For OPC HDA datasources, each history is a table with fields V, Q, T, which are arrays of values, qualities and timestamps, respectively. On OPC UA datasources, arrays S(Server Timestamps) and optionally M(Modification Information) are returned in addition to V, Q and T. The order of values in the arrays is exactly as produced by the underlying OPC HDA/UA server which, for conformant servers, is governed by the start and end time arguments. The V array may have gaps due to empty or null data at certain points which means that operator does not return its real length. Q, T, S and M are real arrays in the sense that operator returns their true length.

The M array is returned only for OPC UA datasources when modification_info argument is set to true. Each element in the array is a table with two keys, MT which indicates Modification Time and UT which indicates Update Type. To know more about Modification Information, please refer to OPC UA Specification Part 11 Section 6.4.3.3.

For an OPC HDA datasource:

local rt = syslib.gethistoryex(
    '/System/Core/localhost/syslib.OpcServer.1',
    '/System/Core/localhost/gen',
    nil, 'now', -- -- this is per OPC HDA 1.2, section 5.3.4
    --'now-1D', nil,-- this is per OPC HDA 1.2, section 5.3.4
    --syslib.now() - 24 * 3600000, syslib.now()
    30,
    true
)

local s = ""
for i = 1, #rt.Q do
    local ss = '{' .. tostring(rt.V[i]) .. ', ' .. rt.Q[i] .. ', ' .. syslib.time(rt.T[i]) .. '}'
    if #s > 0 then
        s = s .. ', ' .. ss
    else
        s = ss
    end
end

return s

For an OPC UA datasource:

local now = syslib.now()
local rt = syslib.gethistoryex(
  '^/System/Core/localhost/opc.tcp:^/^/localhost:4880',
  {'ns=2;s=/System/Core/item1', 'ns=2;s=/System/Core/item2'},
  now - 24* 60 *60000, now,  -- last day's data
  50, -- 50 values per item
  false
)
local s = ""
for j = 1, #rt do
  for i = 1, #rt[j].Q do
     local ss = '{' .. tostring(rt[j].V[i]) .. ', '  .. rt[j].Q[i] .. ', ' .. rt[j].T[i] .. ', ' .. rt[j].S[i] '}'
     if #s > 0 then
       s = s .. ', ' .. ss
     else
       s = ss
     end
  end
end

return s

gethistoryframe

syslib.gethistoryframe(pathspec [,datastore])

Return Type

[number][,number]

Description

Short name: syslib.histf

Returns the oldest and the newest timestamp in history for a given object or path. The function can return at most two elements. If there is only one historized value, it returns one, and if no data has ever been historized, it returns none. When being applied to properties with the Data Historization capability, this function takes into account the current Archive Mode configuration for this capability. E.g., if the Archive Mode is set to 'No Value', nothing will be returned, no matter if earlier changes of this property have been historized or not.

If wrapped inside syslib.pcall(), the table returned in case of error may contain the field transient. This means that the error is temporary, therefore a new attempt may be successful.

Component Execution

Core only

Parameters

Name Type Optional Description

pathspec

pathspec

no

Object’s path, the object itself or the object ID.

datastore

storespec

yes

The strorespec to a data store from which the timeseries data should be retrieved.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

local object = syslib.getobject("/System/localhost/object")
local startt, endt = syslib.gethistoryframe(object) -- OR
local startt2, endt2 = syslib.gethistoryframe("/System/localhost/object")

getlogs

syslib.getlogs(start_time, end_time, [objects], [maxlogs])

Return Type

table

Description

Returns the logs which were created between the start and end times for the objects specified. If no objects are specified, the logs for all objects in the system are returned. The function returns a table which contains the log messages and their details. The structure of the table data is the same as what you see on Log Display in DataStudio.

If wrapped inside syslib.pcall(), the table returned in case of error may contain the field transient. This means that the error is temporary, therefore a new attempt may be successful.

Component Execution

Master Core only

Parameters

Name Type Optional Description

start_time

number

no

Start time in milliseconds.

end_time

number

no

End time in milliseconds.

objects

table

yes

The objects can be represented using their id, path or the object itself. If no objects are given, the function returns logs for all objects in the system.

maxlogs

number

yes

The maximum number of logs that should be returned. Defaults to 100. If it’s set to 0, all the logs which match the criterion will be returned.

Error Messages

  • The function is not supported in this component - the function is being called from a component which does not support that function to be called

  • Path could not be resolved - an object in the list of objects could not be resolved

  • Invalid value provided for argument maxlogs - maxlogs was a negative value

  • Property could not be set - there was an error retrieving the logs

Examples

-- Get the last 20 logs that were created in the last 20 seconds by Item1 and Item2
-- Count the number of errors based on severity
local logtable = syslib.getlogs(syslib.now() - 20000 , syslib.now(), {'/System/Core/Item1', '/System/Core/Item2'}, 20)
local errors = 0
for i = 1, #logtable do
    if logtable[i].severity == "Error" then
        errors = errors + 1
    end
end
return errors

getmicrosecondcounter

syslib.getmicrosecondcounter()

Return Type

number

Description

Returns a micro-second based time count using a steady clock.

Component Execution

All components

getmongoconnection

syslib.getmongoconnection([store], [testarchive])

Return Type

userdata

Description

Takes the objspec or the numerical code for a MongoDB data store and returns a lua-mongo 'client' which represents a connection to the data store. If no argument is passed, the System Custom Data Store is assumed on the Master Core. On Local Cores, the store parameter is required and should represent a custom datastore object.

Component Execution

All 64-bit components

Parameters

Name Type Optional Description

store

objspec

yes

An objspec of a MongoDB data store object. To select a system data store, a valid numeric code of the group syslib.model.codes.RepoStoreName shall be passed. The parameter defaults to System Custom Data Store on the Master Core. On Local Cores, the store parameter is required and should represent a custom datastore object.

testarchive

boolean

yes

Indicates whether the test archive is being specified. It is false by default and is relevant only for System object’s Time Series Data Store.

Examples

local mongo = require 'mongo'
local client = syslib.getmongoconnection()
-- Or alternatively,
-- local client = syslib.getmongoconnection(syslib.model.codes.RepoStoreName.STORE_CUSTOM)

local collection = client:getCollection('custom-mongo-test', 'test')

collection:drop() -- Clear collection

-- Common variables
local id = mongo.ObjectID()
local query1 = mongo.BSON '{ "height" : { "$gt" : 175 } }'

-- Store document
collection:insert { _id = id, name = 'Jane Smith', height = 185 }

-- Fetch document
local document = collection:findOne(query1):value()
print(document.name)

-- Iterate in a for-loop
for document in collection:find(query1):iterator() do
    print(document.name)
end
-- get a connection to a custom event datastore
local client = syslib.getmongoconnection('/System/Core/CustomEventStore1')

getmongoconnectionstring

syslib.getmongoconnectionstring([store], [testarchive])

Return Type

string

Description

Takes the objspec or the numerical code for a MongoDB data store and returns a MongoDB connection string which can be used with lua-mongo library to create a connection to the data store. If no argument is passed, the System Custom Data Store is assumed on the Master Core. On Local Cores, the store parameter is required and should represent a custom datastore object.

Component Execution

All 64-bit components

Parameters

Name Type Optional Description

store

objspec

yes

An objspec of a MongoDB data store object. To select a system data store, a valid numeric code of the group syslib.model.codes.RepoStoreName shall be passed. The parameter defaults to System Custom Data Store on the Master Core. On Local Cores, the store parameter is required and should represent a custom datastore object.

testarchive

boolean

yes

Indicates whether the test archive is being specified. It is false by default and is relevant only for System object’s Time Series Data Store.

Examples

local mongo = require 'mongo'
local client = mongo.Client( syslib.getmongoconnectionstring(syslib.model.codes.RepoStoreName.STORE_CUSTOM))
local collection = client:getCollection('custom-mongo-test', 'test')
collection:drop() -- Clear collection

-- Store document
collection:insert { _id = id, name = 'Jane Smith', height = 175 }
-- get a connection string for a custom event datastore
syslib.getmongoconnectionstring('/System/Core/CustomEventStore1')

getobject

syslib.getobject(objspec)

Return Type

table

Description

Short name: syslib.obj

Returns an existing object. If the object doesn’t exist, it returns nil.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

Error Messages

  • Property not found - there is made an attempt to modify a non-existent property for the given object class.

    Example of code that would raise this error:

    local obj = syslib.getobject("/System/Core/Folder") -- object of type Generic Folder
    obj.Limits.OpcRangeLow = 50 -- this property does not exist for a generic folder
  • Invalid object id - the object’s table gets corrupted internally Compound properties cannot be set directly.

    Example of code that would raise this error:

    obj.Limits = 50 -- the exact limit has to be specified, e.g. Limits.OpcRangeLow
  • Property could not be set - there is made an attempt to set a property with an incompatible type.

    Example of code that would raise this error:

    obj.Limits.OpcRangeLow = "abc" -- this property accepts only numbers

Examples

local obj = syslib.getobject("/System/localhost/object")
If the path "/System/localhost/object" doesn’t exist, then obj will be nil.

Now the object’s properties can be read or written to:

local name = obj.ObjectName
obj.ObjectName = "newObjectName"

Like in the syslib.createobject function case, changed properties are committed into the system only after the commit function is called on the object:

obj:commit()
The changes for set-once properties are ignored because they can be set only when the object is newly created. The changes for other properties are committed irrespective of the ignored changes.

Additionally, the current object can be obtained using a relative path to the current folder:

local current = syslib.getobject(".")

getopcuaquality

syslib.getopcuaquality(opcclassicquality)

Return Type

number

Description

Takes an integer argument and interprets the low 16 bits as an OPC Classic quality code and returns a corresponding OPC UA quality code.

Component Execution

All Components

Parameters

Name Type Optional Description

opcclassicquality

number

no

An integer number (only the low 16 bits are considered).

Examples

local opcclassic = syslib.getopcuaquality(24) -- Converts the "Comm Failure" code to the UA "BadCommunicationError" code

getparentpath

syslib.getparentpath(objspec)

Return Type

string

Description

Short name: syslib.parent

Takes the path of an object as argument and returns the path of the parent.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

local parent_path = syslib.getparentpath("/System/Core/Object name") -- returns "/System/Core"

getproductkey

syslib.getproductkey()

Return Type

string

Description

Returns the product key with which the product is registered. If the product key is not present, an empty string will be returned.

Component Execution

Core only.

Parameters

No parameters required.

Error Messages

  • the function is not supported in this component - the function has been called on a component different from the Core component.

  • permission denied - the user does not have an Administrator role.

Examples

local productkey = syslib.getproductkey()

getpropertyid

syslib.getpropertyid(objspec, [property_name])

Return Type

number

Description

Short name: syslib.propid

Takes as parameters an object or a path and, optionally, a property name. When the second parameter is omitted, it returns the id of the dynamic property which belongs to the given object. If a property name is passed and such property can be found in the object’s configuration, then its corresponding id is returned. If no property is found, the function returns nil.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

property_name

string

yes

The name of the property whose id we want to obtain; optional, defaults to the dynamic property of the given object.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

local dyn_prop_id = syslib.getpropertyid("/System/Core/object")
local prop_id = syslib.getpropertyid("/System/Core/object", "ObjectName")

getpropertyname

syslib.getpropertyname(propid)

Return Type

string

Description

Returns the name of a property given its id.

Component Execution

All Components

Parameters

Name Type Optional Description

propid

number

no

An integer value representing a property id.

Error Messages

  • property not found - the given property id could not be found

getrawhistory

syslib.getrawhistory(pathspec, bounds, time_start, time_end, [max_limit], [datastore], [modified_data_mode])

Return Type

userdata

Description

This function returns raw historic data, i.e. the actual stored data points, from the given property or object, either specified by its ID or path. The function may also return modified historical data (as defined in OPC UA) if they are supported by the underlying data store. If wrapped inside syslib.pcall(), the table returned in case of error may contain the field transient. This means that the error is temporary, therefore a new attempt may be successful.
Remote data stores can not be accessed.

Long Description

The number of data points returned depends on the values of time_start, time_end and max_limit.
Bounds is a boolean value that specifies whether additional Bounding Values should also be returned. This must be false when modified_data_mode is true. Bounding Values are data points which are not necessarily part of the original data set, but may be used to interpolate the actual data for calculations.
time_start and time_end specify the time window which should be retrieved. Both values should be specified in milliseconds from the current epoch (inmation’s POSIX time standard). Values are retrieved sequentially, from time_start to time_end, unless time_start is greater than time_end, in which case the values are retrieved on a backwards order. Either time_start or time_end may be nil (but not both). If time_end equals nil the values will be read towards the latest available time, or if time_start is nil the values will be read backwards to the earliest available time.
max_limit specifies the maximum number of values that may be retrieved. If fewer values are available, they are all returned. If more values are available for the specified period, only the first max_limit points are returned and the "more" flag is raised. If max_limit is set to 0 then all the available data points are returned.
The behavior of this function is generally that, which is specified by OPC UA part 11 Section 6.4.3.2 (with the exception of continuation points and possibly modified data; see below on the latter) or Section 6.4.3.3 (depending on the value of modified_data_mode). Section 4.4 of the same document provides more information on Start and End periods, and Section 3.1 on modified data.

By default, i.e., when modified_data_mode is nil or absent, the function returns only the most recent version of the raw data, completely ignoring any modified data that may be present in the queried time domain. Note that, when modified data are present, this behavior is not fully OPC UA compliant. It is retained for backward compatibility.

If the value of modified_data_mode is false, the function will use the status (quality) to indicate whether modified data are present for a given raw value. In this mode, the function still returns only the most recent version of raw data. The presence of the modified data is signaled by the bits 10 (InfoType) and 3 (Extra Data): see the definition of StatusCode in OPC UA Part 4 Section 7.34.1 and the behavior prescribed in Part 11 Section 6.4.3.2. If the underlying data store does not support modified data, the parameter has no effect (i.e., the behavior as if it were nil). In this mode, the function is fully compliant with respect to modified data. For convenience, syslib.uaextradata() can be used to check for the presence of modified data.

If the value of modified_data_mode is true, the functions returns only the modified data, mostly as described in OPC UA Part 11 Section 6.4.3.3. In this mode, the returned data are all the versions of the modified raw data present in the specified time domain. If a raw value has no previous version, nothing is returned for that raw value. The multiple versions of a raw value are returned with the same source timestamp, sequentially together in the reverse order with respect to the general order of retrieval: if 'time_start' is less than or equal to 'time_end', the most recent version is returned first; otherwise, the least recent version is returned first. If the underlying data store does not support modified data, the behavior is as if no modified data were present, i.e., an empty result set is returned. By derogation from OPC UA Part 11 Section 6.4.3.3, as already remarked, the latest version is also returned. Every version is returned with a server timestamp, which can be used to construct the "modification timestamp" (per Section 6.4.3.3) a.k.a. modificationTime (per Section 6.5.3) by taking the server timestamp of the next more recent value.

Return Values

  • results - Lua Userdata containing a Lua Iterator that may be used to retrieve the values of the (source) timestamp, data value, quality and server timestamp in a generic 'for' loop. The server timestamp is only present when modified_data_mode is true.

  • more - A boolean value indicating whether the max_limit input parameter disallowed for more results to be returned. This behavior applies only when all three of time_start, time_end and max_limit are specified and greater than zero

Component Execution

Core only

Parameters

Name Type Optional Description

pathspec

pathspec

no

Path to object or property, the object itself, object or property ID.

bounds

boolean

no

A boolean value specifying whether or not to include bounding values on the results.

time_start

number

no

The start time of the desired period in milliseconds (or nil).

time_end

number

no

The end time of the desired period in milliseconds (or nil).

max_limit

number

yes

The maximum number of values that should be returned by the function. If set to 0 all values should be returned; default is 0.

datastore

storespec

yes

The strorespec to a data store from which the timeseries data should be retrieved.

modified_data_mode

boolean

yes

The behavior with respect to modified historical data.

Examples

Although time_start and time_end may be set to nil, they are not optional and both may not be set to nil at the same time.

The following code shows how to call the syslib.getrawhistory function and iterate through the results.

local total = 0
local rs, more = syslib.getrawhistory(path, bounds, time_start, time_end, max_limit)

for T, v, q in rs() do -- note the order: timestamp, value and quality
    total = total + v
end

The following example creates an object, populates it with history data and then query its history, using the previous code.

-- syslib.getrawhistory() usage example
local root = syslib.getcorepath()
local folder = 'test_raw'
local name = 'history object'
root = root .. '/' .. folder

-- creating objects
syslib.mass {
    {
        path = root,
        ObjectName = folder,
        class = syslib.model.classes.GenFolder,
        ["AuxStateManagement.AuxStateChangeStrategy"] = syslib.model.codes.AuxStateChangeStrategy.VOLATILE
    },
    {
        path = root .. '/' .. name,
        ObjectName = name,
        class = syslib.model.classes.Variable,
        ["ArchiveOptions.StorageStrategy"] = 1,
        ["ArchiveOptions.ArchiveSelector"] = syslib.model.codes.ArchiveTarget.ARC_PRODUCTION -- required, because the test archive will purge old data
    }
}

-- populating with syslib.sethistory
-- the data and test matrix are taken form OPC UA part 11, v. 1.03, Section 4.4 & Table 1.
local data = {0, 2, 3, 5, 6}
local epoch = syslib.gettime('1970-01-01 00:00:00')
local prpid = syslib.getpropertyid(root .. '/' .. name)
for i = 1, #data do
  syslib.sethistory(prpid, data[i], 0, epoch + data[i])
end

syslib.sleep(1000) -- wait some time for the data to be written before trying to retrieve it

-- retrieving data
local t = {time_start = 0, time_end = 5, max_limit = 0, bounds = true, result = {0, 2, 3, 5}}
local expected = 0

for v in pairs(t.result) do
   expected = expected + v
end

local start = t.time_start and epoch + t.time_start
local tend = t.time_end and epoch + t.time_end
local path = root .. '/' .. name
local total = 0

local rs, more = syslib.getrawhistory(path, t.bounds, start, tend, t.max_limit)
for T, v, q in rs() do -- note the order: timestamp, value and quality
   total = total + v
end

return 'expected = '..expected.. ' total = ' .. total

Using the following value for t instead would force syslib.getrawhistory to return a "more" flag.

local t = {time_start = 0, time_end = 5, max_limit = 3, bounds = true, result = {0, 2, 3}, more = true}
local t1 = syslib.now() -- insert syslib.history function call here local total_time = syslib.currenttime() - t1
return total_time -- the duration of the call in milliseconds

The following example retrieves raw data and looks for the "Extra Data" bit for modified values:

local rs, more = syslib.getrawhistory(path, false, start, tend, nil, nil, false)
local ExtraData = (1 << 10) | (1 << 3) -- bit 10 InfoType and bit 3 Extra Data
for T, v, q in rs() do -- note the order: timestamp, value and quality
   if (q & ExtraData) == ExtraData then
      total = total + v
   end
end

The following example retrieves modified data:

local rs, more = syslib.getrawhistory(path, false, start, tend, nil, nil, true)
for T, v, q, S in rs() do -- note the order: (source) timestamp, value, quality and server timestamp
end

Objects located beneath the Connector are unable to access the time-series repository. Therefore, executing scripts that request historical data from any location other than below the Core object will return the error: "Attempt to access historical data from a component that does not have the time-series repository". This applies to all syslib functions that access historical data (excluding `syslib.gethistoryex`as this function does not request data from the time-series repository) Although this function adheres to the OPC UA part 11 Section 6.4.3.2 (or. 3) standard, it doesn’t implement Continuation Points, therefore all calls to this function return the max_limit number of data points or all (if max_limit equals 0). Please keep in mind that further calls to this function do not handle data that wasn’t returned on a previous call due to a max_limit specification. A subsequent call to treat those data points must specifically identify them. Lua Iterators are presented on the book "Programming in Lua", in chapter 7, as well as their usage with Generic fors.

getreferences

syslib.getreferences([objspec])

Return Type

table

Description

Short name: syslib.refs

If objspec parameter is supplied, the function returns an array, whose elements are a table with three fields: name (of the reference), path (to the referenced object), and type (of the reference). The type can be either a string or an integer, with the following possible string values:

  • "SECURITY" - security reference

  • "OBJECT_LINK" - triggering reference

  • "PROPERTY_LINK" - process value link

  • "OBJECT_LINK_PASSIVE" - non-triggering reference

These are listed in the ReferenceType coding group. The numeric type typically encodes a security reference with access right permissions. The returned table meets the expectations of syslib.setreferences. If parameter objspec is not supplied, the function returns an array containing the names of the references belonging to the current (self) object. The array does not contain empty names.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

yes

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

return syslib.getreferences(syslib.getself()) -- the detailed list of references on self
return syslib.getreferences() -- the names of references on self

getsafconfirmedseqnr

syslib.getsafconfirmedseqnr(category)

Return Type

variant

Description

Returns the Store and Forward sequence number(s) for data forwarded to the target system which has been confirmed (stored successfully). If category is syslib.model.codes.SafDataCategory.NONE then a table with sequence numbers of all available categories, keyed by the numeric category code, is returned. Otherwise, a single integer number is returned.

Component Execution

Core and Connector

Parameters

Name Type Optional Description

category

number

no

A numerical code from syslib.model.codes.SafDataCategory.

Examples

local vqt_cur = syslib.getsafseqnr(syslib.model.codes.SafDataCategory.VQT)
local vqt_conf = syslib.getsafconfirmedseqnr(syslib.model.codes.SafDataCategory.VQT)
if vqt_cur > vqt_conf then
    print("SaF contains non-confirmed VQT data")
end

getsafforwardedseqnr

syslib.getsafforwardedqnr(category)

Return Type

variant

Description

Returns the Store and Forward sequence number(s) for which data has been forwarded to the target system. If category is syslib.model.codes.SafDataCategory.NONE then a table with sequence numbers of all available categories, keyed by the numeric category code, is returned. Otherwise, a single integer number is returned.

Component Execution

Core and Connector

Parameters

Name Type Optional Description

category

number

no

A numerical code from syslib.model.codes.SafDataCategory.

Examples

local vqt_forwarded = syslib.getsafforwardedseqnr(syslib.model.codes.SafDataCategory.VQT)

getsafseqnr

syslib.getsafseqnr(category)

Return Type

variant

Description

Returns the current Store and Forward sequence number(s). If category is syslib.model.codes.SafDataCategory.NONE then a table with sequence numbers of all available categories, keyed by the numeric category code, is returned. Otherwise, a single integer number is returned. Separate SaF sequence numbers for each data category are used to uniquely enumerate each stored datum. Sequence numbers are strictly monotonically increasing when new data is stored. The current sequence number is always greater or equal to the forwarded sequence number, which is always greater or equal to the confirmed sequence number. Calculating differences between those three numbers allows to deduce state changes of the SaF system from one point in time to another.

Component Execution

Core and Connector

Parameters

Name Type Optional Description

category

number

no

A numerical code from syslib.model.codes.SafDataCategory.

Examples

local seq_nrs = syslib.getsafseqnr(syslib.model.codes.SafDataCategory.NONE)
for category, seqnr in pairs(seq_nrs) do
  print("Current sequence number for", syslib.model.codes.SafDataCategory[category].tag, seqnr)
end

getscopeparameters

syslib.getscopeparameters()

Return Type

table

Description

Utility function to retrieve the scope-setttings of the current Lua Instance.

Component Execution

All Components

Parameters

None

Examples

return syslib.getscopeparameters()   -- returns a table of current scope-settings
                                       -- for eg. {comment = "Default Comment"}

getrelaypaths

syslib.getrelaypaths(objspec)

Return Type

table

Description

Short name: syslib.relayp

Takes as parameter an object path or nil (in the latter case, the path defaults to the current object). It returns a table containing the paths of the relays to which the given object belongs or nil if no relay was found in the parents hierarchy.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

-- assume there are two relays at the following paths: "/System/Core/relay1", "/System/Core/relay1/relay2"
return syslib.getrelaypaths("/System/Core/relay1/relay2/connector/object") -- returns [ "/System/Core/relay1", "/System/Core/relay1/relay2"]
return syslib.getrelaypaths("/System/Core/object") -- returns nil

getselectorentries

syslib.getselectorentries(pathspec_or_propcode [, options])

Return Type

table

Description

Returns the currently available entries for a selector property, given its pathspec or property code.

Long Description

The returned table may be empty or contain a items field:

{
  items = { {}, ... }
}

The items field is an array (table with consecutive numerical indices) of tables. Each array element has the following member fields, depending on the property type.

For InstanceSelector type properties:

  • label (string)

  • description (string)

  • value (number)

  • class_code (number)

  • path (string, optional)

If label and description are both nil, the label and description information should be retrieved using the localized text associated with the code in class_code. This function only returns instances for which the caller has the LIST permission.

For TableRowSelector type properties:

  • label (string, optional)

  • description (string, optional)

  • value (number)

  • coding_group (number, optional)

If a coding_group field is present, the label and description fields are nil. The label and description information should be retrieved using the localized text associated with the coding value from value for the codding group identified by the coding_group field.

In general, every item field can be nil if some internal data mismatch is encountered.

The options parameter no longer supports setting the tree option. An error will we raised if this option is still enabled.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec_or_propcode

number or pathspec

no

A pathspec for a property or a property code

options

table

yes

A options table, where the field resolve_path is treated as a boolean field indicating if the returned data should contain full paths for entries representing inmation objects. The parent field can be set to a objspec identifying the parent object. If parent is used, the pathspec_or_propcode parameter is required to contain a valid object ID.

The pathspec_or_propcode parameter supports a pathspec (or property code) denoting a property of type InstanceSelector or TableRowSelector. In case of InstanceSelector properties, the parameter can be a property code like syslib.model.properties.DataStoreSelector.

Error Messages

  • invalid property type - the property is not of the correct type

  • permission denied - properties of type TableRowSelector require the callers to have READ permissions on the object which holds the referenced table data.

  • tree option not supported - the options parameter contains the no longer supported tree option.

Examples

return syslib.getselectorentries("/System/Core/Tag.ArchiveOptions.ArchiveSelector")

getself

syslib.getself()

Return Type

table

Description

Short name: syslib.slf

Returns the current object as an inmation object.

Component Execution

All Components

Examples

return syslib.getself():path()

getselfpath

syslib.getselfpath()

Return Type

string

Description

Short name: syslib.selfp

Returns the path to the current object.

Component Execution

All Components

Examples

return syslib.getselfpath()

getstoreid

syslib.getstoreid(store)

Return Type

integer

Description

This function returns a numerical id identifying a "store object". These objects are generic buffer objects like Generic Time Series Buffer and Generic Event Buffer objects, custom MongoDB data store objects, or one of the system stores. For system stores, the store parameter must be value from the RepoStoreName coding group. For all other store types, the store parameter is a regular objspec.

Component Execution

All components

Parameters

Name Type Optional Description

store

objspec or RepoStoreName coding value

no

An objspec for non-system stores, or a syslib.model.codes.RepoStoreName value.

getsystemdb

syslib.getsystemdb()

Return Type

userdata

Description

Returns a read-only handle to the system database. This handle can be used to query information about the system data using SQL.

Long Description

The values of all static properties in the system is stored in a table called properties. It can be used to find objects and properties matching various criterion using SQL.

The schema of the properties table is given below

Column Name Type Optional Description

objid

integer

no

Object ID of the owner object of the property

path

string

no

The relative path of the property with respect to the object. In Datastudio, path of a paroperty can be copied by right clicking on the property in Object Properties panel.

code

integer

no

The code of a static property. Property codes may also be accessed by using the syslib.model.properties.property_name notation.

value

variant

no

The current value of the property.

position

integer

no

The position of the value in an array property. Is 0 for non-array properties.

modelcode

integer

no

The code of the model that the owning object of the property belongs to. Please refer to this page for codes of various models.

The properties table contains only static properties.
An object may contain multiple properties with the same code.
The properties table is read-only. It is updated when the value of a property changes but the user cannot update it directly.

Examples

Properties may be accessed using their code. 1 is the code for the property ObjectName.

local sysDB = syslib.getsystemdb() -- get the read-only handle
local cur,errMsg = sysDB:query("SELECT objid FROM properties WHERE code IS 1 AND value IS 'gen_1';") -- returns a cursor and if there’s any error, an error message
row = cur:fetch ({}, "a") -- the rows will be indexed by field name
while row do
  local obj = syslib.getobject(row.objid) -- load the object from the numid
  obj.ObjectName = "New Name"
  obj:commit()
  row = cur:fetch(row, "a") -- get the next row
end

Property codes may also be accessed by using the syslib.model.properties.property_name notation.

--get the read-only handle
local sysDB = syslib.getsystemdb()

-- returns a cursor and if there’s any error, an error message
local cur, errMsg = sysDB:query("SELECT objid FROM properties WHERE code IS " .. syslib.model.properties.ObjectName .. " AND value IS 'gen_1';")

row = cur:fetch({}, "a") -- the rows will be indexed by field name

Properties may also be accessed using the path of the property.

--get the read-only handle
local sysDB = syslib.getsystemdb()

-- returns a cursor and if there’s any error, an error message
local cur, errMsg = sysDB:query("SELECT objid FROM properties WHERE path IS '.ObjectName' AND value IS 'gen_1';")

row = cur:fetch({}, "a") -- the rows will be indexed by field name

Putting it all together we can search for propery codes for specific Object Types, in this case Connector.

local sysDB = syslib.getsystemdb() -- get the read-only handle

local classType = syslib.model.classes.Connector -- ClassType for the objects to search

local propertyCode = syslib.model.properties.ObjType -- propertycode for ObjectType

-- build the query with the given property and type
local sqlcmd = "SELECT DISTINCT objid FROM properties WHERE code = %s and value is %s"
local cur,errMsg = sysDB:query(sqlcmd:format(propertyCode, classType))
local count = 0
local row = cur:fetch ({}, "a") -- the rows will be indexed by field name
while row do
count = count + 1
row = cur:fetch(row, "a") -- get the next row
end
return count

We support JSON1 extension of SQLite3 using which we can query any JSON strings stored in our properties. The following code fetches all objects where the first row of the firstname column of the property CustomOptions.CustomTables.TableData is John.

local cur,errMsg = sysDB:query("SELECT objid FROM properties WHERE code IS " .. syslib.model.properties.TableData .. " AND json_extract(value, '$.data.firstname[0]')  = 'John'")

if not cur then
    return errMsg
end

row = cur:fetch ({}, "a") -- the rows will be indexed by field name
local objects = {}
while row do
  table.insert(objects, row.objid)
  row = cur:fetch(row, "a") -- get the next row
end

return objects

JSON1 extension is documented here.

getsystempath

syslib.getsystempath(objspec)

Return Type

string

Description

Short name: syslib.systemp

If the argument is an object not in the IO-model, the function returns nil. Otherwise, it returns the path to the System object.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

yes

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

-- Assume there is a system at the following path: "/System"
return syslib.getsystempath("/System/Core/localhost/folder/object") -- returns "/System"

gettcpconnections

syslib.gettcpconnections(version)

Return Type

table

Description

This function will return a table that contains the information about TCP/IP connections for the component where this function is executed. It contains information on both TCP/IP v4 and v6.

This functionality is available only for the 64-bit inmation executable.

Parameters

Name Type Optional Description

version

number

yes

A number specifying the tcp version for which to retrieve the connections.

version values:

  • 4: retrieve connections for tcp v4 only

  • 6: retrieve connections for tcp v6 only

When no parameters are passed, the function will retrieve connections for both tcp v4 and v6.

Returned value description

The returned table is of the form:

returned_table = {tcp_connection, tcp_connection, ...}

where tcp_connection is

tcp_connection = {raddr= "...", proto = 8, laddr = "...", state = 2, v = 4, rport = 123, lport = 123}

The order of the attributes may vary.

  • proto is a number, and represents the protocol. It is always equal to 6 which is the corresponding number for TCP. Further information here.

  • v is a number, and specifies the Internet Protocol version.

  • state is a number, and specifies the status of the connection. More details in the table below.

  • laddr is a string, and represents the local address. It may be either IPv4 or IPv6 in accordance to v.

  • raddr is a string, and represents the remote address. It may be either IPv4 or IPv6 in accordance to v.

  • lport is a number, and represents the local port.

  • rport is a number, and represents the remote port.

State description

Code Meaning Description

1

CLOSED

The TCP connection is closed.

2

LISTENING

The TCP connection is in the listen state.

3

SYN_SENT

A SYN packet has been sent.

4

SYN_RCVD

A SYN packet has been received.

5

ESTABLISHED

The TCP connection has been established.

6

FIN_WAIT1

The TCP connection is waiting for a FIN packet.

7

FIN_WAIT2

The TCP connection is waiting for a FIN packet.

8

CLOSE_WAIT

The TCP connection is in the close wait state.

9

CLOSING

The TCP connection is closing.

10

LAST_ACK

The TCP connection is in the last ACK state.

11

TIME_WAIT

The TCP connection is in the time wait state.

12

DELETE_TCB

The TCP connection is in the delete TCB state.

Note that when the state member is 2, the TCP connection state is in the listen state, so the remote address and the remote port has no meaning.
When the local address is 0.0.0.0 or :: it means that the listener can accept connections on any interface.

Component Execution

All Components

Error Messages

  • unable to get connection stats for tcp v(4|6) - the component was not able to retrieve such information from the host machine.

  • the function is not supported in this component - the executable where this function was run is 32-bit, therefore this functionality is not available.

Examples

return syslib.gettcpconnections()

gettime

syslib.gettime(time, [format])

Return Type

number

Description

Short name: syslib.time

This function returns the number of milliseconds since Epoch, corresponding to the parameter given as a timestamp. If the format is omitted,then the timestamp is considered to have the default format "%Y-%m-%d %H:%M:%S%f%ZP" (which is also compatible with the ISO 8601 format). If the format and / or the timestamp are wrong, it returns a negative number. For more about the possible formats, click here. Alternatively, it can also take the number of milliseconds since Epoch and return a timestamp having the ISO 8601 format.

Component Execution

All Components

Parameters

Name Type Optional Description

time

string

no

A string representing the timestamp to be converted in milliseconds. By default, it has the following format: "%Y-%m-%d %H:%M:%S%f%ZP". It can also be a number representing the number of milliseconds since Epoch.

format

string

yes

Represents the format of the first parameter time; it is an optional parameter and it can be useful only when the first parameter is a timestamp string.

Examples

local no_of_ms = syslib.gettime("2014-12-02T07:41:03.871Z") -- returns 1417506063871
local no_of_ms = syslib.gettime("2014-12-02T07:41:03.871-02:00") -- returns 1417513263871
local no_of_ms = syslib.gettime("2014.12.02 07:41:03",  "%Y.%m.%d %H:%M:%S") -- returns 1417506063000
local no_of_ms = syslib.gettime("2014.12.02 07:41:03.871",  "%Y.%m.%d %H:%M:%s") -- returns 1417506063871
local no_of_ms = syslib.gettime("02/12/2014 07:41:03 AM", "%d/%m/%Y %I:%M:%S %p") -- returns 1417506063000
local no_of_ms = syslib.gettime("02/12/2014 07:41:03 PM", "%d/%m/%Y %I:%M:%S %p") -- returns 1417549263000
local timestamp = syslib.gettime(1417506063871) -- returns "2014-12-02T07:41:03.871Z"

gettimeparts

syslib.gettimeparts(datetime)

Return Type

number

Description

Short name: syslib.tparts

Takes as parameter a string datetime (having ISO 8601 format) or a number representing the POSIX time as milliseconds. It returns the corresponding time parts as year, month, day, hour, minutes, seconds, milliseconds. If a string datetime is passed and it doesn’t have the ISO 8601 format, incorrect values may be returned.

Component Execution

All Components

Parameters

Name Type Optional Description

datetime

number

no

Either a number representing the POSIX time as milliseconds or a string datetime (ISO 8601). If the string is provided in another format, incorrect values may be returned.

Examples

local year, month, day, hour, min, sec, msec = syslib.gettimeparts(1461549032930)
-- or year, month, day, hour, min, sec, msec = syslib.gettimeparts("2016-04-25T01:50:32.930Z")
return {year, month, day, hour, min, sec, msec}

gettimepartstable

syslib.gettimepartstable(datetime)

Return Type

table

Description

Short name: syslib.tpartst

Takes as parameter a string datetime (having ISO 8601 format) or a number representing POSIX time as milliseconds. It returns a table containing the corresponding time parts as year, month, day, hour, minutes, seconds, milliseconds. If a string datetime is passed and it doesn’t have the ISO 8601 format, incorrect values may be returned.

Component Execution

All Components

Parameters

Name Type Optional Description

datetime

number

no

This parameter can be a number representing the POSIX time as milliseconds or a string datetime (having ISO 8601 format). If the string is provided in another format, incorrect values may be returned.

Examples

return syslib.gettimepartstable(1461549032930) -- OR
return syslib.gettimepartstable("2016-04-25T01:50:32.930Z") -- both cases return [2016, 4, 25, 1, 50, 32, 930]

getvalue

syslib.getvalue(pathspec)

Return Type

multiple return values

Description

Short name: syslib.get

This function gets the value, quality and timestamp of a property specified by the pathspec. If the pathspec includes a property specification, this property will be resolved, if present. If the pathspec has no property specification at all (i.e., it refers to an object), a default property will be selected, if availble at the specified object. Please refer to the documentation on paths for more information.

Please note that, depending on the property, any or all of the returned values may be nil. Please refer to the documentation on Property Values for more information. For more information on quality codes and expected return values for quality, please see the Quality Codes section of the documentation.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec

variant

no

Path to object or property, the object itself, object or property ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

local x0 = syslib.getvalue("Ref1") -- returns the value, quality and timestamp of the referenced object
local x1 = syslib.getvalue("/System/Core/Connector/Datasource/IoNode/Ioitem") -- returns the VQT (the dynamic property) of the Ioitem
local x2 = syslib.getvalue("RefItem.Location.Longitude") -- returns the value of the specified property
local x3 = syslib.getvalue("Path/UnknownTagName.WrongPropertyName") -- shows error message
local v, q, t = syslib.getvalue("Ref1") --returns value, quality and timestamp as separate values v, q and t

In the following tree structure:

+-- System
|   +-- Core
|   |   +-- Folder1
|   |   |   +-- Script
|   |   +-- Folder2
|   |   |   +-- Dataholder2

For the script to access Dataholder2 via a relative path:

syslib.getvalue("../../folder2/holder2.ArchiveOptions.StorageStrategy") -- gets parameter value from holder2

Observations

If the item contains binary data, i.e. an image, the syslib.getvalue() returns the data in Base64 encoding scheme.

hdagetitemattributes

syslib.hdagetitemattributes(datasource)

Return Type

table, integer

Description

Returns the item attributes supported by the server. The function mimics the IOPCHDA_Server::GetItemAttributes interface as specified in OPC HDA 1.20 Specification.

Component Execution

Connector only

Parameters

Name Type Optional Description

datasource

variant

no

Datasource object’s path, the Datasource object itself or the object ID.

Return Value Description

The function will always return two values: ATTRIBUTE_DESCRIPTION_TABLE, RETURN_CODE

  • ATTRIBUTE_DESCRIPTION_TABLE :

    Its a Lua table-of-tables holding different properties of the available attributes as described below:

    Key DataType Description

    tags

    table (integer)

    IDs of all available attributes.

    names

    table (string)

    Names of all available attributes.

    descriptions

    table (string)

    Descriptions of all available attributes.

    types

    table (integer)

    Integer representations of VARIANT data-types of all attributes.

  • RETURN_CODE :

    Integer Representation of HRESULT value, as returned by the underlying HDA Server, as a result of IID_IOPCHDA_Server::GetItemAttributes function call.

Examples

local attributes, ret = syslib.hdagetitemattributes("/System/Core/localhost/Matrikon.OPC.Simulation.1")

local str = ""
if ret == 0 then
    return require("rapidjson").encode(attributes)
else
    return "Failed to access the item attributes"
end

The code above will return 4 Lua-tables containing tags, names, descriptions and data-type information of all available attributes as shown below:

{
  "tags" : [1, 2, 11, 12, 13, 4294967291, 4294967292, 4294967293, 4294967294, 4294967295],
  "names" : ["DATA_TYPE", "DESCRIPTION", "NORMAL_MAXIMUM", "NORMAL_MINIMUM", "ITEMID", "TRIANGLE", "SQUARE", "SAWTOOTH", "RANDOM", "BUCKET"],
  "descriptions" : ["Data type", "Item Description", "High EU", "Low EU", "Item ID", "Triangle Wave", "Square Wave", "Saw-toothed Wave", "Random", "Bucket Brigade"],
  "types" : [2, 8, 5, 5, 8, 12, 12, 12, 12, 12]
}

hdareadattributes

syslib.hdareadattributes(datasource, item_tag, attribute_tags, [start_time], [end_time])

Return Type

table

Description

Returns values of attributes for a specified item. The function mimics the IOPCHDA_SyncRead::ReadAttribute as specified in OPC HDA 1.20 Specification.

Component Execution

Connector only

Parameters

Name Type Optional Description

datasource

variant

no

Datasource object’s path, the Datasource object itself or the object ID.

item_tag

string

no

HDA Item tag.

attribute_tags

table

no

Table of OPC-HDA attribute IDs (Integer) to be read.

start_time

variant

yes

Start time, can be integer number of milliseconds since POSIX epoch, nil or string per OPC HDA 1.20, section 5.3.4. Default = "NOW".

end_time

variant

yes

Start time, can be integer number of milliseconds since POSIX epoch, nil or string per OPC HDA 1.20, section 5.3.4. Default = "".

Return Value Description

The function always returns a lua table-of-tables, where each sub-table represents an attribute value. Each sub-table contains the following entries:

Key DataType Description

value

table

Table with fields V, Q, T, which are arrays of values, qualities and timestamps, respectively.

err

Integer

Integer representation of the return code (HResult), as returned by the server, for the corresponding IOPCHDA_SyncRead::ReadAttribute function call.

The returned attributes values are in the same order as the attribute-tags, specified in the function call.

Examples

local values = syslib.hdareadattributes("/System/Core/localhost/Matrikon.OPC.Simulation.1",
                            "Random.Int4",{1,2,1099})
return require("rapidjson").encode(values)

The return value of the code-snippet above will be:

[
     {"value":{"V":[3],"Q":{},"T":[1563812766490]},"err":0},
     {"value":{"V":["Random value."],"Q":{},"T":[1563812766490]},"err":0},
     {"value":{"V":{},"Q":{},"T":{}},"err":-1073475572}
]

isbadstatus

syslib.isbadstatus(quality)

Return Type

boolean

Description

Checks if a quality code is bad.

Component Execution

All Components

Parameters

Name Type Optional Description

quality

number

no

The quality numerical code (in OPC UA or classic).

Examples

local _, q = syslib.getvalue("/System/core/item")
return syslib.isbadstatus(q)

isgoodstatus

syslib.isgoodstatus(quality)

Return Type

boolean

Description

Checks if a quality code is good. For more details, see the isbadstatus function.

Component Execution

All Components

isuncertainstatus

syslib.isuncertainstatus(quality)

Return Type

boolean

Description

Checks if a quality code is uncertain. For more details, see the isbadstatus function.

Component Execution

All Components

last

syslib.last(objspec, name)

Return Type

variant

Description

This function is related to buffering historical data (see buffer function). It retrieves the last value in the buffer with the specified name (name) at the specified object or path (objspec).

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

First assume there is a numerical generator obj which historizes its data. We first set a buffer on it:

syslib.buffer(obj, "buff", ".ItemValue", 60000, 60)

The last value that is stored in the buffer buff can be obtained as follows:

local last_val = syslib.last(obj, "buff")

listbuffer

syslib.listbuffer([objspec])

Return Type

table

Description

Lists the buffers set up for the object specified by objspec, if present, or all the buffers in the component service otherwise.

The returned table has the following keys:

Key Meaning

object

The numeric ID of the object where a buffer is defined

name

The name of the buffer (see buffer function)

lower

The name of the input buffer (or property) for the buffer (see buffer function)

length

The maximum size of the buffer, in elements (see buffer function)

duration

The maximum duration of the buffer, in milliseconmds (see buffer function)

counter

The buffer’s counter (see tear function)

size

The current size of the buffer, in elements.

capacity

The current capacity reserved for the buffer, in elements

peeks

The total number of peek operations performed on the buffer

peeked

The total number of elements peeked from the buffer

The value for each key in the returned table is an array (i.e., a table with keys from 1 to N). All the arrays have the same length, and each buffer is described by elements with an identical index. See the Examples section.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

yes

Object’s path, the object itself or the object ID.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

syslib.listbuffer('/System/localhost/object')

Sample return value:

{
    -- index =               [1]              [2]
    object   = { 281475110535168, 281475110535168 },
    name     = {          "buf2",          "buf1" },
    lower    = {    ".ItemValue",    ".ItemValue" },
    length   = {             600,              60 },
    duration = {           60000,           60000 },
    counter  = {            2633,             276 },
    size     = {             600,              60 },
    capacity = {             711,              63 },
    peeks    = {               0,               0 },
    peeked   = {               0,               0 },
}

All the elements with index 1 correspond to buffer "buf2", and all those with index 2 to buffer "buf1".

listproperties

syslib.listproperties(objspec, [resultspec], [args…​])

Return Type

table, size

Description

A function providing a way to obtain detailed information about object properties, including their values.

The function returns a list of live object properties, which can differ depending on an object configuration; in comparison with getvalue it does not require knowing the property paths in advance; it has a performance advantage over multiple calls of getvalue; and it has limited convenience filtering.

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

resultspec

string

yes

A string pattern specifying what data a caller is interested in and in what order. The format of this argument is explained below in more details.

args…​

variant

yes

Additional positioned arguments, corresponding to the resultspec.

Result specifiers

The string defining result consists of two parts devided by the pipe (|) symbol, <fields>|<options>. The fields part preceding the pipe symbol, defines which values should appear in the result and in which order. If the part fields is absent then its value is "FV". The options part after the pipe symbol defines formatting and filtering options as well as in which order their values appear as additional arguments.

For example, let’s consider the result format "FVC|ad". This means that every three values in the resulting array table correspond to a single property and they are presented in the following order: full property path, property value and property code. The result also includes properties with default values, which are absent by default. If a property value is encrypted then its value in the result is decrypted, which is also turned off by default.

Field specifiers

Field Type Description

F

string

Fully qualified property name (FQPN), e.g., "ArchiveOptions.ArchiveSelector"

N

string

Property tag name (the last part of FQPN)

C

number

Property code; see System Model > Properties and model.properties

G

string

Property disambiguator. If a property is present multiple times in the object, the string result encodes an ambiguous path to the property. It’s a string in UTF-8 format, where every path element consists of a type letter and a code. The type letter 'c' is used to denote a class and 'p' for property. A code is encoded as a single code point.

I

number

Property ID

D

Boolean

true if property value is a default value

E

Boolean

true if property value is null, meaning that it is absent, otherwise false, even if the value is represented as nil in lua.

V

variant

Property value

Y

number

Type code syslib.model.codes.VariantTypes optionally ORed with syslib.model.flags.VariantTypeFlags.VT_ARRAY.

Q

number

Quality

T

number

Timestamp

Option specifiers

Option Requires value Description

a

-

Result includes properties with default values, by default they are not listed.

d

-

Encrypted property values are decrypted in the result, by default encrypted property value stays encrypted in the result.

w

number

Result only includes properties which have at least one attribute specified as an additional flags argument; by default all properties are listed.

b

number

Result does not contain properties which have at least one attribute specified as an additional flags argument; by default no properties are excluded.

Required option values should appear in the same order as their options are specified in the result format string. Filtering conditions are combined with logical AND.

Returns

The function returns two values: a lua array table containing a flattened list of requested data; and a number of elements in that table - in order to properly handle nil values.

Examples

Get properties for mass.

local objspec = syslib.getcorepath()
local prop_attrs = syslib.model.flags.SysPropAttributes
-- select only CONFIGURABLE properties and exclude VOLATILE and DYNAMIC
local props, props_len = syslib.listproperties(objspec, "|wb", prop_attrs.PROP_CONFIGURABLE, prop_attrs.PROP_VOLATILE & prop_attrs.PROP_DYNAMIC)

local mass_entry = {}
for i = 1, props_len, 2 do -- 2 because default result format is FV
    local prop_path, prop_value = props[i], props[i + 1]
        mass_entry[prop_path] = prop_value
end
return mass_entry

linkprocessvalue

syslib.linkprocessvalue(objspec, ref)

Description

Short name: syslib.linkpv

Sets the ProcessValueLink property of a KPI or ISA-95 Equipment model object (for example: GenKPI or Analog Measurement object) to a data item in the I/O model (for example: an I/O item). The first parameter is the path of the object or the object itself which receives the reference (the KPI or ISA-95 model object) and the second one is the path to the object to be linked (the I/O model object).

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

ref

string

no

Represents the path to the object to be linked.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

  • permission denied: Can’t read the linked item. - the user does not have permission to READ the reference object

  • permission denied: Can’t modify the object. - the user does not have permission to MODIFY the target object

Examples

syslib.linkprocessvalue("/Enterprise/genKPI", "/System/localhost/object")

log

syslib.log(log_code, log_message, [log_details])

Description

Creates a log entry in the system log using the supplied arguments as content. The log_code argument determines the severity or type of the log message.

Log Severity Codes for the syslib.log() function:

Code Tag Severity/Type

1

ERR

Error

2

WRN

Warning

3

INF

Information

4

DBG

Debug

The syslib.log() function will only create log messages for the object that is executing the Lua script. Log messages cannot be attched to other objects. To view the log messages generated by the object, open the Log Display or right click on the object and select Admin > Open Log.

Component Execution

All Components

Parameters

Name Type Optional Description

log_code

number

no

The severity of the log entry (see table above). Expects a number code.

log_message

string

no

The content of message displayed in the log entry.

log_details

string

yes

The content of any further details to be included with the log entry.

Examples

-- Example of an error log entry
syslib.log(1, "The script body returned a string; a table is expected")
-- Example of a debug log entry with detail
syslib.log(4, "The script body returned a string; a table is expected", "This can be fixed by returning a table. For more information ...")

luamemory

syslib.luamemory([objspec], [limit])

Return Type

variant

Description

Returns the memory usage for one or more objects. It can be called either with a single argument (object id or path) and it returns the memory usage for this object, or with a limit as a second argument (the first being nil), which returns a table containing up to limit entries such as { oid1 = size1, oid2 = size2, oid3 = size3, …​ }. It can also be called with no arguments, in which case memory usage information is returned for all objects containing scripts.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

yes

Object’s path, the object itself or the object ID. When the second argument is provided, it shall be nil.

limit

number

yes

The number of objects to request memory information for.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

syslib.luamemory("/System/Core/script_item") -- returns an integer meaning the number of bytes being used by the object
syslib.luamemory(nil, 3) -- returns a table containing the first three objects that consume most memory; the keys are the objects' ids and the values are the corresponding number of bytes being used
syslib.luamemory() -- returns a table with the same format, but containing information about all script objects

luacpuusage

syslib.luacpuusage([objspec], [limit])

Return Type

variant

Description

This function returns two values. The first is the CPU usage for one or more objects and the second is the normalization factor. If the total CPU usage with respect to all hardware threads is required, then the CPU usage should be divided by the normalization factor. If the function is called with a single argument (objspec), it returns the cpu usage for that object. If it is called with a limit as a second argument (the first being nil), it returns CPU usage as a table containing up to limit entries of highest CPU consuming Lua scripts as { oid1 = size1, oid2 = size2, oid3 = size3, …​ }. It can also be called with no arguments, in which case cpu usage information is returned for all objects containing scripts.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

yes

Object’s path, the object itself or the object ID. When the second argument is provided, it shall be nil.

limit

number

yes

The number of objects to request cpu usage information for.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

cpu_usage, normalization_factor = syslib.luacpuusage("/System/Core/script_item") -- returns a number meaning the percent cpu used used by the object and the normalization factor
cpu_usage, normalization_factor = syslib.luacpuusage(nil, 3) -- returns a table containing the first three objects that consume most CPU and the normalization factor; the keys for CPU usage are the objects' ids and the values are the corresponding percent usage.
cpu_usage, normalization_factor = syslib.luacpuusage() -- returns a table and normalization factor with the same format, but containing information about all script objects

mass

syslib.mass(entries, [batch_flags])

Return Type

table

Description

Does the equivalent of a Mass Configuration operation in DataStudio. A mass entry in the entries parameter contains the modifications that are applied to one single object and it’s represented as key-value pairs. The keys can be settings or names of respective object’s properties. The entry’s settings are reserved case-sensitive words:

  • operation - the mass operation to be applied; optional setting (numerical value); default value: syslib.model.codes.MassOp.UPSERT

  • path - the path of an object; mandatory setting

  • class - the object type; it is only required if the object does not exist prior to the mass operation and it only accepts numerical values, see here for all available classes

  • type - (advanced) the system object type; optional setting; numerical value; default value: syslib.model.codes.SysObjectType.OT_OBJECT

  • flags - (advanced) flags for individual operations in a mass request; optional setting; numerical value; default value: 0, see here for a listing of all possible flags

  • cfgversion - (advanced) a configuration version of an object; numerical value; syslib.mass will be executed only if the object that should be modified has the configuration version that matches the specified one

The type, flags and cfgversion in the entries parameter are advanced settings, which are already set by default, and should be only used by advanced users.

The property names for compound properties can be specified in two ways:

  • In a flat manner: entry = { Latitude = 10 }

  • With dotted path:

entry = {}
entry["Location.Latitude"] = 10

In the above two cases we did exactly the same operation, we have set the Latitude property to be equal to 10. The only difference is the syntax, in the second case a full property path has to be specified to the root property compound. See here in order to get all the available options for the batch_flags parameter.

The changes for set-once properties are ignored because they can be set only when the object is newly created. The other properties are updated irrespective of the ignored changes.

Component Execution

All components

Parameters

Name Type Optional Description

entries

table

no

A table of tables where each inner table represents a mass entry.

batch_flags

number

yes

Affects the entire mass operation by controlling its execution type; default value: syslib.model.flags.MassBatchFlags.SUPPRESS_RESULTS

Returns

The function returns two values when the SUPPRESS_RESULTS flag is not set, otherwise it returns no values:

  • A table containing the ordered numerical codes of the mass operation results for each entry, see here for a listing of all possible codes.

  • A table containing the explanation for a possible error code for each entry, again preserving the order of the entries. When the code of a mass entry result is less than 200, no corresponding entry will be present in this table, which means that it only contains errors.

Examples

Simple example:

local base = '/System/Core'
for i=1, 100 do
    syslib.mass({{path = base .. '/data/' .. i, class = syslib.model.classes.HolderItem, objectname = i}})
end

The above example will create 100 HolderItems under the ../data folder if they do not exist.

More advanced examples:

local e1 = {
    operation = syslib.model.codes.MassOp.INSERT,
    class = syslib.model.classes.GenItem,
    path = "/System/Core/Test Generic Item",
    ObjectName = 'Test Generic Item',
    ObjectDescription = "Describe the object",
    GenerationType = 1,
    Latitude = 10
}
e1["GenNumeric.GenerationMin"] = 8

local e2 = {
    class = syslib.model.classes.ActionItem,
    path = "/System/Core/Test Action Item",
    ObjectName = 'Test Action Item',
    OpcEngUnit = "m/s",
    AdvancedLuaScript = "return 5"
}
e2["Limits.OpcRangeLow"] = 9

local e3 = {
    class = syslib.model.classes.GenFolder,
    path = "/System/Core/Test Folder",
    ObjectName = 'Test Folder'
}

local res = syslib.mass({e1, e2, e3}, 0) -- no batch flags set (any errors will be skipped and the function will return results)
if type(res) == 'table' then
    return table.concat(res, ', ')
end
return 'no results'

The above example will create three objects, namely, Generic Item, Action Item and Folder, with a few predefined properties.

syslib.mass {{path = syslib.getcorepath(), ObjectName ='newName'..now(), cfgversion = 1}}

The above example will update the current core object’s name if the object’s config version is 1. If it is not the case, the operation will not be executed.

Error Messages

  • config version not matched at mass entry index <index> - the specified config version does not match the actual object’s config version.

  • information supplied was malformed at mass entry index <index> - a mass entry passed to the function is not formatted correctly, this error can occur when an unexisting property is specified or wrong data for a property is given

  • parent-child class mismatch at mass entry index <index> (object path: <path>) - for every class it is predefined parents of which class are allowed for it, the given error occurs if such relation is violated

  • wrong class code was specified at mass entry index <index> - the error occurs when a passed value purporting to be a class code does not match any predefined class code

  • the specified path is orphaned at mass entry index <index> (object path: <path>) - a non-existing path was specified for an entry

  • object not found for update at mass entry index 1 - can be generated in multiple cases where an invalid field entry is provided - for example a specific cfgversion

model.classes

syslib.model.classes.class_name

Description

Returns the numerical code for an object, all available objects are listed here.

Return Type

number

Component Execution

All Components

Examples

return syslib.model.classes.Core --returns 3

-- OR

local T = syslib.model.classes return T.Core --returns 3
The values are loaded on demand so the classes will not be statically present in the table T if it is iterated.

model.codes

syslib.model.codes.coding_group_name.[coding_name]

Description

Returns the available codings for a coding group or the numerical code for a specific coding, all available coding groups are listed here. See the examples below for more details.

Return Type

variant

Component Execution

All Components

Examples

return syslib.model.codes.SelectorGenItem.LUASCRIPT -- returns 5

-- OR

local T = syslib.model.codes.SelectorGenItem return T.LUASCRIPT --returns 5

Code groups can also be referenced by their numerical code, see the example below.

return syslib.model.codes.SelectorGenItem[5] -- returns {"tag":"LUASCRIPT","meaning":"GenLuascript"}

-- OR

-- the table T already has the values loaded and can be iterated to find all existing coding groups
local T = syslib.model.codes.SelectorGenItem return T[5] -- returns {"tag":"LUASCRIPT","meaning":"GenLuascript"}

model.counters

syslib.model.counters.counter_name

Description

Returns the numerical code for a performance counter. All available counters of an object can be seen on its dev page, e.g. here is the dev page of the Connector object.

Return Type

number

Component Execution

All Components

Examples

return syslib.model.counters.CPU -- returns 72

-- OR

return syslib.model.counters.DiskUsage -- returns 144

model.flags

syslib.model.flags.flag_group_name.[flag_name]

Description

Returns the available flags for a flag group or the numerical code for a specific flag, all available flag groups are listed here. See the examples below for more details.

Return Type

variant

Component Execution

All Components

Examples

return syslib.model.flags.ItemValueStorageStrategy.STORE_RAW_HISTORY -- returns 1

-- OR

local T = syslib.model.flags.ItemValueStorageStrategy return T.STORE_RAW_HISTORY --returns 1

-- OR

syslib.model.flags.ModUserState.STATE_GOOD -- returns 1024

Code groups can also be referenced by their numerical code, see the example below.

return syslib.model.flags.PlcType[0x8000] -- returns {"tag":"PLC_TYPE_REMOTE", "meaning":"Plc Type Remote"}

-- OR

-- the table T already has the values loaded and can be iterated to find all existing flag groups
local T = syslib.model.flags.PlcType return T[0x8000] -- returns {"tag":"PLC_TYPE_REMOTE", "meaning":"Plc Type Remote"}

model.properties

syslib.model.properties.property_name

Description

Returns the numerical code for an object property, all available properties are listed here.

Return Type

number

Component Execution

All Components

Examples

return syslib.model.properties.ObjectName -- returns 1

-- OR

local T = syslib.model.properties return T.ObjectName -- returns 1
The values are loaded on demand so the properties will not be statically present in the table T if it is iterated.

moveobject

syslib.moveobject(objspec, parent, [rename])

Description

Moves and/or renames an object. The operation will succeed only when object and parent are within the same component service, and when object and parent are different and parent is not currently a direct or indirect child of object, and when object’s name (optionally renamed) is not currently used by other children of parent, and when parent’s type accepts children of object’s type.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

parent

variant

no

Object’s path, or the object itself, object or property ID.

rename

string

yes

If supplied, this is a string that the object will have after the operation.

Error Messages

  • object could not be resolved - the object path or id could not be resolved

  • permission denied - the user is not permitted to change one of the objects involved

  • object deleted - the object has been deleted

  • parent deleted - the parent has been deleted

  • relationship cycle - the intended move would create a cycle

  • path conflict - the intended move would create a conflicting path

  • unacceptable type - the object’s type is not acceptable at the intended destination

  • unsupported move - the intended move is not supported

Examples

local obj = syslib.getobject('/A/B/C/D')
local pa1 = obj:parent()
local pa2 = syslib.getobject('/A/B/X')
syslib.moveobject(obj, pa2) -- if successful, obj becomes A/B/X/D
syslib.moveobject(obj, pa2, 'Y') -- if successful, obj becomes A/B/X/Y
syslib.moveobject(obj, pa1, 'Z') -- if successful, obj becomes A/B/C/Z

msgqueue

syslib.msgqueue(objspec, slot)

Description

Get the message queue associated with objspec and the numeric slot number slot. The returned message queue is an opaque object, to be passed as an argument to the other syslib.msg functions. Messages can be read from the queue either using syslib.msgnext(queue [, msgid]) or pairs(queue). Messages themselves are strings, which are opaque to the messaging system.

There is currently a hard limit of 63 message queues per object, with the slot number in the range of [1, 63].

Messages can be pushed to the same queue from different Lua scripts (which can run concurrently in dedicated threads). However, messages can only be read, popped and cleared sequentially. It is allowed to read, pop and clear messages from different Lua instances. However, popping and clearing messages concurrently is discouraged.

Component Execution

All Components.

Currently, a message queue cannot be shared between components and messages cannot be pushed to or read from different components.

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

slot

integer

no

A slot number identifying the queue in the given objspec

Return Type

userdata

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

  • slot number not in the range [1, 63] - the slot argument is out-of-range

Examples

Get the message queue of the Core object with slot number 1:

local q = syslib.msgqueue(syslib.getcorepath(), 1)

Iterating over all currently fetched (in memory) messages of a queue is done using pairs or the call operator on the queue:

for msgid, msg in pairs(q) do
  print(msgid, msg)
end

The call operator allows to specify a maximum waiting time for messages to be available in the queue before the iteration starts:

-- Wait at most 5000 ms until at least one message is available
for msgid, msg in q({ wait_for = 5000 }) do
  print(msgid, msg)
end

Removing elements using syslib.msgpop while iterating over a queue is allowed. Another way of reading messages is analoguous to Lua’s next function for tables, see syslib.msgnext.

msgpush

syslib.msgpush(queue, msg)

Description

Push a new message to queue. The message is persistently stored and can be read (multiple times) until it is popped from the queue (or a later message is popped).

On success, the function returns true. Otherwise, it returns false and an error string.

Component Execution

All Components.

Parameters

Name Type Optional Description

queue

userdata

no

A message queue retrieved via syslib.msgqueue()

msg

string

no

The message to be pushed

Return Type

boolean, string

Examples

Push a single message:

local ok, errmsg = syslib.msgpush(queue, "My first message")

msgpop

syslib.msgpop(queue, msgid)

Description

Pop (delete) messages from queue. Messages are identified with a strict monotonically increasing msgid. All messages with id <= msgid are deleted from the queue.

This function returns nothing.

Component Execution

All Components.

Parameters

Name Type Optional Description

queue

userdata

no

A message queue retrieved via syslib.msgqueue()

msgid

integer

no

The message id to be removed from the queue

Examples

Pop all messages with id <= 10:

syslib.msgpop(queue, 10)

msgnext

syslib.msgnext(queue [, msgid])

Description

Return the next message and its id pending in queue after msgid. If msgid is nil, the function returns the first message in the queue. If there is no message after msgid, nothing is returned (nil).

This function can be used to test if queue is empty.

Component Execution

All Components.

Parameters

Name Type Optional Description

queue

userdata

no

A message queue retrieved via syslib.msgqueue()

msgid

integer

yes

The message id of the previous message

Return Type

integer, string

Examples

Test if a message queue is empty:

if not syslib.msgnext(queue) then
  print("queue is empty")
end

Get the first and second message:

local msgid, msg = syslib.msgnext(queue)
if msgid then
  print("First message:", msg)
  msgid, msg = syslib.msgnext(queue, msgid)
  print("Second message:", msg)
end

msgclear

syslib.msgclear(queue)

Description

Remove all messages from queue. This completely removes all persisted messages.

This function returns nothing.

Component Execution

All Components.

Parameters

Name Type Optional Description

queue

userdata

no

A message queue retrieved via syslib.msgqueue()

msgstats

syslib.msgstats([queue])

Description

This function returns statistics about the specified queue or about all queues currently being used.

If no queue is specified, a table of tables is returned. Otherwise, a single table is returned.

Component Execution

All Components.

Parameters

Name Type Optional Description

queue

userdata

yes

A message queue retrieved via syslib.msgqueue()

Return Type

table

Examples

Print the statistics of queue as a JSON document:

local rj = require 'rapidjson'
print(rj.encode(syslib.msgstats(queue)))

with output (similar to):

{
  "oid": 1234567891234, // The object id the queue is associated with
  "slot": 1, // The queue's slot number
  "msgs_inmem": 34, // The currently fetched messages available in memory
  "inserts": 164, // The total number of inserted messages since component start-up
  "reads": 34, // The total number of messages read since component start-up
}

opcdabrowse

syslib.opcdabrowse()

Description

Establish connection with a specified OPC DA Server (also known as a Classic or COM Server). If connection is successful, then a session object is returned, otherwise nil. In the latter case, the second and third return values are, respectively, the error message and error number.

The session object has these methods:

  1. QueryOrganisation(). Finds whether the datasource associated with the session has a flat or hierarchical structure. If hierarchical, the first return value is OPC_NS_HIERARCHICAL, if flat, OPC_NS_FLAT (these are the values of the coding group syslib.model.codes.OpcNamespaceType) and, if there is an error condition, nil. In the latter case, the second and third return values are, respectively, the error message and error number.

  2. ChangeBrowsePosition(). Provides a way to move ‘up’ or ‘down’ or 'to' in a hierarchical space. If successful, true is returned. Otherwise, the second and third return values are, respectively, the error message and error number.

  3. BrowseOPCItemIDs(). Returns an iterator to ItemIDs as determined by the passed parameters. The position from the which the browse is done can be set via ChangeBrowsePosition(). If successful, an iterator in the form of user data is returned. Otherwise, the first returned value is nil and the second and third returned values are, respectively, the error message and error number; these values are also returned if the iterator is empty. The iterator takes an optional parameter which, if non-nil, causes errors to be ignored.

  4. GetItemID(). Provides a way to assemble a fully qualified ITEM ID in a hierarchical space. If successful, the fully qualified ID is returned. Otherwise, the first returned value is nil and the second and third returned values are, respectively, the error message and error number.

  5. BrowseAccessPaths(). Provides a way to browse the available AccessPaths for an ITEM ID. If successful, returns an iterator the access paths. Otherwise, the first returned value is nil and the second and third returned values are, respectively, the error number and error message; these values are also returned if the iterator is empty. The iterator takes an optional parameter which, if non-nil, causes errors to be ignored.

  6. QueryAvailableProperties(). Provides a way to retrieve available properties for an ITEM ID. If successful, returns an array with three elements, each of which is another array of size count, where count is the number of available properties. The first array contains property IDs, the second one property descriptions, and the third one property data types (these are the values of the coding group syslib.model.codes.VariantTypes). If unsuccessful, the first returned value is nil and the second and third returned values are, respectively, the error message and error number.

  7. GetItemProperties(). Provides a way to retrieve values of properties for an ITEM ID and property IDs. If successful, returns an array with two elements, each of which is another array of size count, where count is the number of requested property values. The first array contains current property values, and the second one error numbers. If unsuccessful, the first returned value is nil and the second and third returned values are, respectively, the error message and error number.

  8. LookupItemIDs(). Provides a way to retrieve ITEM IDs (if available) for each of the passed property IDs, indicating ITEM IDs which could be added to an OPCGroup and used for more efficient access to the data corresponding to the properties. If successful, returns an array with two elements, each of which is another array of size count, where count is the number of requested properties. The first array contains said ITEM IDs, and the second one error numbers. If unsuccessful, the first returned value is nil and the second and third returned values are, respectively, the error message and error number.

  9. Disconnect(). Disconnect from the server.

Return types

Function or Method Return Types

syslib.opcdabrowse

userdata, [, string, integer]

session:BrowseAccessPaths

userdata [, string, integer]

session:BrowseOPCItemIDs

userdata [, string, integer]

session:ChangeBrowsePosition

bool [, string, integer]

session:Disconnect

-

session:GetItemID

string [, string, integer]

session:GetItemProperties

table [, string, integer]

session:LookupItemIDs

table [, string, integer]

session:QueryAvailableProperties

table [, string, integer]

session:QueryOrganisation

integer [, string, integer]

Component Execution

Connector only

Parameters

Function or Method Parameter Name Type Optional Description

syslib.opcdabrowse

datasource

string

no

path to datasource

session:BrowseAccessPaths

ItemID

string

no

Fully qualified Item ID

session:BrowseOPCItemIDs

browsetype

integer

no

a type from syslib.model.codes.OpcBrowseType.

session:BrowseOPCItemIDs

filtercriteria

string

yes

a server-specific filter string

session:BrowseOPCItemIDs

datatypefilter

integer

yes

a variant from syslib.model.codes.VariantTypes

session:BrowseOPCItemIDs

accessrightsfilter

integer

yes

an access rights filter from syslib.model.flags.OpcAccessRights

session:ChangeBrowsePosition

direction

integer

no

a direction from syslib.model.codes.OpcBrowseDirection.

session:ChangeBrowsePosition

position

string

no

for 'down', the name of the branch to move into, for' up' should be a null string and for 'to' a fully qualified name (or the null string to move to the root).

session:Disconnect

-

session:GetItemID

Item

string

no

The name of an item at the current level, as returned by BrowseOPCItemIDs().

session:GetItemProperties

ItemID

string

no

Item ID for which the properties are read

session:GetItemProperties

propertyIDs

table

no

IDs of the queried properties, as returned by QueryAvailableProperties().

session:LookupItemIDs

ItemID

string

no

Item ID for which the properties are looked up

session:LookupItemIDs

propertyIDs

table

no

IDs of the requested properties, as returned by QueryAvailableProperties().

session:QueryAvailableProperties

ItemID

string

no

Item ID for which the available properties are returned

session:QueryOrganisation

-

Error Messages

  • the IO sub-system is not available - the IO sub-system is not available (perhaps execution is not under a connector)

  • the object for OPC DA browsing must be a data source - the parameter is not a data source

Examples

local session = assert(syslib.opcdabrowse("/System/Core/Connector/Softing.OPCToolboxDemo_ServerDA.1"))
local org = assert(session:QueryOrganisation())
if (org == syslib.model.codes.OpcNamespaceType.OPC_NS_FLAT) then
    return "Unexpected OpcNamespaceType"
end
assert(session:ChangeBrowsePosition(syslib.model.codes.OpcBrowseDirection.OPC_BROWSE_DOWN, "maths"))

local items = assert(session:BrowseOPCItemIDs(syslib.model.codes.OpcBrowseType.OPC_LEAF, "",
                                              syslib.model.codes.VariantTypes.VT_R8, 0))

local tbl = {}
for item in items() do  -- or 'for itemid in items(true) do' to ignore errors
    local qid = assert(session:GetItemID(item))
    table.insert(tbl, qid)
end
session:Disconnect()
return tbl
local session = assert(syslib.opcdabrowse("/System/Core/Connector/Softing.OPCToolboxDemo_ServerDA.1"))

local items = assert(session:BrowseAccessPaths("maths.cos"))

local tbl = {}
for itemid in items() do
    table.insert(tbl, itemid)
end
return tbl
local session = assert(syslib.opcdabrowse("/System/Core/Connector/Softing.OPCToolboxDemo_ServerDA.1"))
local itemid = "maths.cos"

local properties = session:QueryAvailableProperties(itemid)
local values = session:GetItemProperties(itemid, properties[1])
local itemids = session:LookupItemIDs(itemid, properties[1])

return properties, values, itemids

pcall

syslib.pcall(func, …​)

Parameters

Name Type Optional Description

func

function

no

The function that will be executed in protected mode.

param

variant

yes

The argument (zero or more) of func.

Error Messages

  • bad argument #1 to 'pcall' (value expected) - the function (syslib.pcall) has been called with no parameters.

Return Type

a boolean value followed by zero or more variant values

Description

This function will execute func(…​) in a protected mode, i.e. no errors will be raised ever. The beavior is the same as Lua pcall, except for the additional table, as a third return value, in case of an error. If the function passed raises no errors, the returned values will be

  • true

  • returned val_1 of func (if any)

  • returned val_2 of func (if any)

  • …​

Otherwise, then the returned values will be of the form:

  • false

  • err_msg

  • err_table

where err_msg is an object which contains the error message, while err_table is a table with entries providing more detailed error information. At the moment transient is the only possible entry in the table.

Example

-- no errors
local ok, err_msg_or_result, err_table = syslib.pcall(syslib.gethistory, {"/System/Core/hist", "/System/Core/hist2"}, syslib.currenttime() - 60000, syslib.currenttime())}
-- ok = true, err_msg_or_result = {...}, err_table = nil
-- errors
local ok, err_msg_or_result, err_table = syslib.pcall(syslib.gethistory, nil, syslib.currenttime() - 60000, syslib.currenttime())}
-- ok = false, err_msg_or_result = "bad argument #1 to '?' (table expected, got nil)", err_table = {}

peek

syslib.peek(objspec, name)

Return Type

variant

Description

See tear function, the behavior is identical except it does not clear the buffer.

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

name

string

no

The name of the buffer to be retrieved.

posix2excel

syslib.posix2excel(psx_time)

Return Type

number

Description

Converts POSIX time to Excel time.

Component Execution

All components

Parameters

Name Type Optional Description

psx_time

number

no

POSIX time (also known as Unix time or epoch time).

Examples

return syslib.posix2excel(syslib.gettime("1970-01-01T12:28:48.000Z")) --result: 25569.52

queryenvironment

syslib.queryenvironment(key)

Return Type

string

Description

Takes as parameter a string representing a key in the environment variables map and returns its value.

Long Description

Below, there is a list of all the currently available variables:

  • "APPLICATION"

  • "APPLICATION_INIT_CONNECTION"

  • "APPLICATION_NAME"

  • "APPLICATION_OWNER_DOMAIN"

  • "APPLICATION_OWNER_NAME"

  • "APPLICATION_SECURITY"

  • "APPLICATION_SECURITY_MODE"

  • "APPLICATION_USER_DOMAIN"

  • "APPLICATION_USER_NAME"

  • "CORE_HOST"

  • "CORE_INIT_DB"

  • "CORE_INIT_ROLE"

  • "CORE_PORT"

  • "HOST_DETECTED_DOMAIN"

  • "HOST_DETECTED_DOMAIN_SUFFIX"

  • "HOST_DETECTED_NAME"

  • "HOST_FULLNAME"

  • "INSTALL_BROKER_PORT"

  • "INSTALL_CACHE_PORT"

  • "INSTALL_CONNECTOR_PORT"

  • "INSTALL_CORE_HOST"

  • "INSTALL_CORE_PORT"

  • "INSTALL_PARM_DB"

  • "INSTALL_RELAY_PORT"

  • "INSTALL_SERVER_PORT"

  • "LEGAL_COPYRIGHT"

  • "MANUFACTURER"

  • "MODULE_FOLDER"

  • "MODULE_HOMEDRIVE"

  • "MODULE_HOST_LOG_FILE"

  • "MODULE_HOST_LOG_FOLDER"

  • "MODULE_LOG_FOLDER"

  • "MODULE_NAME"

  • "MODULE_PATH"

  • "MODULE_ROOT_FOLDER"

  • "MODULE_STEM"

  • "MODULE_VERSION"

  • "OS_FIREWALL"

  • "OS_FIREWALL_CTL_ALLOWED"

  • "OS_NAME"

  • "PROCESS_ELEVATED"

  • "PROCESS_ID"

  • "PROCESS_INSTANCES"

  • "PROCESS_PARENT_ID"

  • "PROCESS_PARENT_NAME"

  • "PROCESS_USER_DOMAIN"

  • "PROCESS_USER_NAME"

  • "PRODUCT_KEY_COM_PER"

  • "PRODUCT_KEY_COM_SUB"

  • "PRODUCT_KEY_CORE_COUNT"

  • "PRODUCT_KEY_ENT_PER"

  • "PRODUCT_KEY_ENT_SUB"

  • "PRODUCT_KEY_EVAL"

  • "PRODUCT_KEY_EXP_DAY"

  • "PRODUCT_KEY_EXP_MONTH"

  • "PRODUCT_KEY_EXP_YEAR"

  • "PRODUCT_KEY_FEATURES"

  • "PRODUCT_KEY_NCO_PER"

  • "PRODUCT_KEY_NCO_SUB"

  • "PRODUCT_KEY_USAGE_COMMERCIAL"

  • "PRODUCT_KEY_USAGE_RESTRICTED"

  • "PRODUCT_KEY_USAGE_TIMELIMIT"

  • "PRODUCT_KEY_VALID"

  • "SCRIPT_HOME"

  • "SERVICE_CERTIFICATE_FOLDER"

  • "SERVICE_DESCRIPTION"

  • "SERVICE_DROP_AE_FOLDER"

  • "SERVICE_DROP_DA_LOC_FOLDER"

  • "SERVICE_DROP_DA_UTC_FOLDER"

  • "SERVICE_DROP_HDA_FOLDER"

  • "SERVICE_DROP_LOG_FOLDER"

  • "SERVICE_ERROR_CONTROL"

  • "SERVICE_FP_DB_LOG"

  • "SERVICE_FP_DB_SYSTEM"

  • "SERVICE_FP_INSTALL_ID"

  • "SERVICE_FP_IRREGULAR"

  • "SERVICE_FP_NEXT_LOG_ID"

  • "SERVICE_FP_RECENT_STOP"

  • "SERVICE_FP_RUNTIME_ID"

  • "SERVICE_FP_SERVER_PORT"

  • "SERVICE_FP_SERVICE_ID"

  • "SERVICE_FP_SYSTEM_ID"

  • "SERVICE_FP_VERSION"

  • "SERVICE_FULL_NAME"

  • "SERVICE_IMAGE_FOLDER"

  • "SERVICE_LOG_NAME"

  • "SERVICE_NAME"

  • "SERVICE_SAF_FOLDER"

  • "SERVICE_SERVER_PORT"

  • "SERVICE_SERVER_PREALLOC"

  • "SERVICE_SHORT_NAME"

  • "SERVICE_STARTTIME"

  • "SERVICE_START_ACCOUNT"

  • "SERVICE_START_TYPE"

  • "SERVICE_TEMP_FOLDER"

  • "SERVICE_TYPE"

  • "SERVICE_WORK_FOLDER"

Component Execution

All Components

Parameters

Name Type Optional Description

key

string

no

The string key to be queried in the environment variables map.

Examples

return syslib.queryenvironment("MODULE_ROOT_FOLDER") -- return the root folder, e.g., "D:\syslib.root"

queryservertimestamp

syslib.queryservertimestamp(pathspec, time[, datastore])

Return Type

table

Description

Queries the server timestamp in the data archived for the given pathspec, where the server timestamp is either absent or less recent than the specified time.

The datastore parameter chooses the time series data store to query; if it is not specified, a data store default for the given pathspec is selected.

The function returns a table of source (key) - server (value) timestamp pairs that correspond to the archived data matching the arguments of the query. For some source timestamps, server timestamps may be absent, in which case the value is false. Otherwise, all the timestamps are integer Posix time values, in milliseconds.

Note that server timestamps are associated with blocks of source values, rather than individual source values.

Component Execution

Core Components

Parameters

Name Type Optional Description

pathspec

pathspec

no

The pathspec.

time

integer

no

Posix time, in milliseconds.

datastore

storespec

yes

The strorespec to a data store from which the timeseries data should be retrieved.

Examples

local chart = syslib.queryservertimestamp(property, time)
for source, server in pairs(chart) do
end

regex

syslib.regex(string, expression)

Return Type

boolean

Description

Specifies whether a string matches a regular expression. This function uses ECMAScript variant.

Component Execution

All Components

Parameters

Name Type Optional Description

string

string

no

A string against which the regex expression is matched.

expression

string

no

A regular expression (pattern) to match. Reminder, backslahes in the regex expression should be escaped using another backslash e.g. "\d+-"

Examples

return syslib.regex("subject", "(sub)(.*)") -- returns true

scopedcall

syslib.scopedcall(settings, callback_func, args, …​)

Return Type

variant

Description

Utility function to execute a Lua function with the specified scope-parameters. Please note that the scope-parameters outside the function call remains unchanged.

Component Execution

All Components

Parameters

Name Type Optional Description

settings

table

yes

Lua-Table with predefined fields for scoped parameters. Only specified parameters are reset within the current scope. For eg. an empty table has no effect on the current scope-setup.

callback_func

Lua function

yes

The Lua function to be executed within the scope

args, …​

variant

yes

Arguments for the callback_func

Supported scope parameters

The following keys can be used, as part of settings, to modify the corresponding scope parameters: - comment : specify the audit-comment.

Examples

syslib.scopedcall({comment = "This is a function specific comment"}, syslib.enableobject, "/System/Core/object_1")

When we modify a function specific scope-setting, the previous scope settings are copied as it is and newly specified settings are reset. The new scope settings are applicable within the scope of the callback function. After this call is completed, previous scope settings will be applied as usual in the outer scope. For example:

local settings_a = {comment = "This is the default comment"}
syslib.setscopeparameters(settings_a)
syslib.disableobject("/System/Core/object_1") -- settings_a will be applied

local settings_b = {comment = "This is a function specific comment"}
syslib.scopedcall(settings_b, syslib.enableobject, "/System/Core/object_1") -- settings_b will be applied

syslib.disableobject("/System/Core/object_1") -- settings_a from the default scope will be applied

setdefaults

syslib.setdefaults([default_params])

Return Type

table

Description

Sets the default values for read/write SCI. When called without a table parameter, it resets the current defaults to the default defaults. When called with a table parameter, it copies valid defaults from the supplied table into the current defaults. The effects of this function apply only to the executing script and are preserved during the lifetime of a script environment. See defaults function for a list of all the possible default values.

Component Execution

All Components

Parameters

Name Type Optional Description

default_params

table

no

A table containing the default parameters to be set; optional.

Examples

syslib.setdefaults({write_group = true}) -- sets only the write_group default, keeping all the others intact
syslib.setdefaults({write_group = true, write_delay = 100}) -- sets write_group and write_delay, keeping all the others intact
syslib.setdefaults() -- resets all the defaults

setevent

syslib.setevent(data)

Return Type

boolean

Description

Short name: syslib.setev

Sets a script event. Expects a table. Returns a boolean value stating the success of the operation. The table should contain key-value pairs, representing attributes of the event. Below, there is a list of built-in attributes that can be set (otherwise, they are automatically initialized with default values):

  • Severity - Can be a number or a string. As a number, it can take values between 1 and 1000 (highest). As a string, it can have the following values: HIGH, MEDIUM HIGH, MEDIUM, MEDIUM LOW, LOW. By default, it is 1 ("LOW").

  • Message - String value (or a value convertible to a string). By default, it is an empty string.

  • Timestamp - Time of the event in milliseconds (POSIX). By default, it is the current time.

  • Type - A string or number containing the numeric value of an entry from the syslib.model.codes.EventType coding group. By default, this is syslib.model.codes.EventType.OPC_SIMPLE_EVENT. If the field is not absent and cannot be converted to one of the supported event types, the event will be marked with a special "type missing" flag.

  • Newstate - A string or number containing one or more flags from the syslib.model.flags.EventNewStatee flag group. This is used only for conditional events.

  • Source - A string (or a value convertible to a string) identifying the source of the event. Defaults to the empty string.

Many of the built-in attributes are evaluated when filtering events, e.g. when storing them in a Custom Event Data Store. Setting them to invalid or empty values may affect how they are processed by the filtering logic.
The function converts all keys into lowercase and assumes their uniqueness. To avoid this behavior for vendor-specific attributes as well as maintain their order, use syslib.createevent() in combination with this function.
The event userdata (returned by syslib.createevent()) is invalidated after it is passed to this function and cannot be used again.

Component Execution

All Components

Parameters

Name Type Optional Description

data

table or userdata

no

The event data to be set either as a Lua table or an event userdata returned by syslib.createevent()

Examples

local t = {}
t["Severity"] = 500
t["Message"] = "script event"
t["Timestamp"] = 1470663220365
t["Type"] = syslib.model.codes.EventType.OPC_SIMPLE_EVENT -- the default
t["key1"] = "str"
t["key2"] = 35
t["key3"] = {1, 2, 3}

return syslib.setevent(t)

setfile

syslib.setfile(pathspec, data [, name | metadata [, mode]])

Return Type

table [, string]

Description

Some object properties can be used to store files in the system. The files themselves are stored in a MongoDB GridFS bucket. The files can be stored or updated using this function with name or metadata.name as the key plus additional metadata. The metadata specification (a table schema) is documented together with the property in question.

If a file already exists in the property with the given file name, it is replaced with the new one and the metadata is replaced or merged depending on mode. The file name can be omitted (or set to nil) for properties of type File.

If a file with the given name does not already exist, it is added as a new file if the property can hold multiple files (i.e., the property is of type FileList) or completely replaced otherwise (independent of the mode parameter).

Depending on the actual property the file is attached to, some meta-data is added automatically.

On success, the function returns the new file’s meta-data. Otherwise, it raises a Lua error if argument validation failed or returns nil and an error message in case of a runtime error.

This function works only on a property of type File or FileList.
Since the files are stored in MongoDB and the files may be huge, it may potentially take a long time for this function to return. Hence, it is recommended to call this function from a dedicated thread.

If wrapped inside syslib.pcall(), the table returned in case of error may contain the field transient. This means that the error is temporary, therefore a new attempt may be successful.

Component Execution

Master Core only

Parameters

Name Type Optional Description

pathspec

variant

no

pathspec to a property where the file is to be stored. It should be of the datatype File or FileList.

data

string

no

The content of the file.

name or metadata

variant

maybe

The name (a string) of the file or a metadata table with a name field. Optional for File properties.

mode

string

yes

If nil or set to "replace" (the default), metadata completely replaces existing metadata. If set to "merge", the new metadata is merged with the existing data, overwriting existing fields or adding new ones.

If mode is set to "replace", system-defined metadata like the size or upload date are not removed, even if the metadata table parameter does not contain such fields (they are updated). If a metadata table is not provided, then all custom meta-data is removed in replace mode.

Examples

Read a file and store it as example.pdf in the Attachments property of an object.

local io = require "io"
local name = "example.pdf"
local path = "C:\\tmp\\" .. name
local file = io.open(path, "rb")
local data = file:read("a")
local meta = { name = name, path = path }
meta = syslib.setfile('/System/Core/Connector.Attachments', data, meta)

setfilemetadata

syslib.setfilemetadata(pathspec, name or metadata [, metadata] [, mode])

Return Type

table [, string]

Description

Some object properties can be used to store files in the system. The files themselves are stored in a MongoDB GridFS bucket. The metadata of existing files can be set and modified using this function. The metadata specification (a table schema) is documented together with the property whose metadata is modified.

On success, the function returns the updated metadata table. Otherwise, it raises a Lua error if argument validation failed or returns nil and an error message in case of a runtime error.

This function works only on a property of type is File or FileList.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec

variant

no

pathspec to a property where the metadata is to be stored.

name

string

maybe

The file name. Can be omitted if metadata.name is set or the property is of type File

metadata

table

yes

New or additional metadata for the file, see mode.

mode

string

yes

If nil or set to "replace", metadata completely replaces existing metadata. If set to "merge" (the default), the new metadata is merged with the existing data, overwriting existing fields or adding new ones.

If mode is set to "replace", system-defined metadata like the size or upload date are not removed, even if the metadata table parameter does not contain such fields. If metadata is nil or an empty table, then all custom meta-data is removed in replace mode.

Examples

Modify metadata of a file example.pdf in the Attachments property of an object.

local name = "example.pdf"
local pathspec = "/System/Core/Connector.Attachments"

-- Set new metadata on a FileList property, which contains a file called example.pdf
local customdata = { tags = { "training", "manual"} }
local meta, errmsg = syslib.setfilemetadata(pathspec, { name = name, custom = customdata }, "replace")

-- Update a single custom metadata field on a File property
meta = syslib.setfilemetadata(pathspec, { name = name, custom = { note = "Important!" } })
meta = syslib.setfilemetadata(pathspec, { name = name, custom = { note = "Very Important!" } })

-- Rename the "example.pdf" file in the FileList property to "test.pdf"
meta = syslib.setfilemetadata(pathspec, name, { name = "test.pdf" })

sethistory

syslib.sethistory(ID, value, quality, timestamp)

Return Type

boolean

Description

Short name: syslib.sethist

Adds historical data to a given item directly, without affecting its current value. The function can be used to add large amounts of historical data and stores batches of data in the SaF system. A return value of true signals successful addition of the data point to an in-memory queue, false otherwise. The data is persisted asynchronously, typically in less than 100ms after the function returns.

Component Execution

All Components

Parameters

Name Type Optional Description

ID

number

no

The numerical ID of the dynamic property of the item, to which the historical data is added.

value

variant

no

The value V from the VQT historical data to be added; it can be boolean, number, string or nil.

quality

number

no

The quality Q from the VQT historical data to be added; usually, it is 0, meaning quality good.

timetstamp

number

no

The timestamp T from the VQT historical data to be added; it is represented as number of milliseconds since Epoch.

Examples

local success = syslib.sethistory(281476615897088, 10, 0, 1461051211899)
local success2 = syslib.sethistory(281476615700480, "abc", 0, 1461051211899)
local success3 = syslib.sethistory(syslib.getpropertyid("/System/Core/Obj", "ItemValue"), 20, 0, 1461051211899)

sethistoryex

syslib.sethistoryex(datasource, tags, values, qualities, timestamps, [mode])

Return Type

table

Description

Update the historical data on external historians using OPC HDA Classic.

if all the values should have good quality, pass an empty table here. When used, these must be UA quality codes, they will be converted to OPC classic qualities

Component Execution

Connector only

Parameters

Name Type Optional Description

datasource

objspec

no

Path to, object, or object ID of a non-read-only HDA Datasource.

tags

table

no

A table with tag names. When multiple values (at different times) are needed for one tag, repeat the tag name.

values

table

no

A table with values corresponding to the tag names.

qualities

table

no

A table of qualities corresponding to the tag names. Extra values are ignored, missing values substituted with good quality.

timestamps

table

no

A table of timestamps (number of milliseconds since Epoch) corresponding to the tag names. Extra values are ignored, missing values substituted with 'now'.

mode

string

yes

The mode of operation. The available options are 'upsert', 'insert', or 'update'. It defaults to 'upsert'.

Examples

syslib.sethistoryex(
    -- path to or object of an HDA datasource
    '/S/C/localhost/Matrikon.OPC.Simulation.1',

    -- A table with tag names
    -- When multiple values (at different times) are needed for one tag, repeat the tag name
    -- It is OK to repeat tag names
    {
        'Bucket Brigade.Real4', 'Bucket Brigade.Real8',
        'Bucket Brigade.Real4', 'Bucket Brigade.Real8',
    },

    -- A table with values corresponding to the tag names
    -- Extra values are ignored, missing values substituted with empty values
    {
        111,   112,
        's23', 's24'
    },

    -- A table of qualities corresponding to the tag names
    -- Extra values are ignored, missing values substituted with good quality
    -- Tip: if all the values should have good quality, pass an empty table here
    -- When used, these must be UA quality codes, they will be converted to OPC  classic qualities
    {
        0x80320000, 0x808D0000, -- two bad qualities
        0x40000000, 0           -- one uncertain, one good
    },
    -- A table of timestamps corresponding to the tag names
    -- Extra values are ignored, missing values substituted with 'now'
    {
        now,               now + 1000,
        now + 2000,        now + 4000
    },

    --An optional argument, defaulting to 'upsert'
    'upsert' -- or 'insert', or 'update
)

setproductkey

syslib.setproductkey(product_key)

Return Type

none

Description

Register a product key with the current Core component.

Component Execution

Core only.

Parameters

Name Type Optional Description

product_key

string

no

The product key to be set into the software.

Error Messages

  • the function is not supported in this component - the function has been called on a component different from the Core component.

  • permission denied - the user does not have an Administrator role.

  • The product key is invalid. - The product key is invalid

  • bad argument #1 to 'setproductkey' (string expected, got …​). - The argument was either missing or not a string

Examples

local product_key = 'ABCDE-12345-...'
syslib.setproductkey(product_key)

setreferences

syslib.setreferences(objspec, refs)

Description

Creates or modifies the references of an object. Receives a table as parameter (refs) where each entry is itself a table, corresponding to one reference. Each reference has three fields: name, path, and type. Only the path field is mandatory. The type, when not specified, defaults to "OBJECT_LINK" (triggering). The existing types are:

  • "SECURITY" (0x000000000) - security reference

  • "OBJECT_LINK" (0x100000000) - triggering reference

  • "PROPERTY_LINK" (0x200000000) - process value link

  • "OBJECT_LINK_PASSIVE" (0x300000000) - non-triggering reference (NOTE in v.1.8 type is "ACTION_OUT_ONLY")

These are listed in the ReferenceType Coding Group.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

refs

table

no

A table containing as elements other tables that represent objects to be set as references; each reference has three fields: name, path, and type; only the path field is mandatory; the type, when not specified, defaults to triggering.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

Examples

syslib.setreferences(syslib.getself(), {
    {name="A", path="/System/localhost/ref1"},
    {name="B", path="/System/localhost/ref2", type="OBJECT_LINK_PASSIVE"}
}) -- sets two references to the current object, first one is triggering, the second one is non-triggering

To delete the references from an object use the following:

syslib.setreferences(syslib.getself(), {}) -- deletes all references of the current object

To set a security reference, the refs table should also contain the security flags (see the SecurityAttributes flag group for available flags). To set the security reference with flags, use the 64bit mask where the upper 32bit contains the ReferenceType and the lower 32bit contains the SecurityAttribute flags:

syslib.setreferences("/System", {
    {
        path = "so",
        type = (syslib.model.codes.ReferenceType.SECURITY | syslib.model.flags.SecurityAttributes.INHERITABLE | syslib.model.flags.SecurityAttributes.READ)
    }
})

This sets a security reference to the "so" profile on the System object

setscopeparameters

syslib.setscopeparameters()

Return Type

None

Description

Utility function to modify the scope-settings of the current Lua Instance.

Component Execution

All Components

Parameters

Name Type Optional Description

settings

table

yes

Lua-Table with predefined fields for scoped parameters. Only specified parameters are reset within the current scope. For eg. an empty table has no effect on the current scope-setup.

Supported scope parameters

The following keys can be used, as part of settings, to modify the corresponding scope parameters: - comment : specify the audit-comment.

Examples

local settings = {comment = "This is the default comment"}
syslib.setscopeparameters(settings)

syslib.disableobject("/System/Core/object_1")

The new scope-settings will be applied to all subsequent calls within the current Lua instance.

setvalue

syslib.setvalue(pathspec, value, [quality], [timestamp])

Return Type

none

Description

Short name: syslib.set

This function sets the value, quality and timestamp of a property specified by the pathspec. If the pathspec includes a property specification, this property will be resolved, if present. If the pathspec has no property specification at all (i.e., it refers to an object), a default property will be selected, if availble at the specified object. Please refer to the documentation on paths for more information.

When using syslib.setvalue() to set the value property of an IO Item, the function converts this to an OPC Write to the associated Data Source, rather than setting the property directly. The value property will then be updated from the resultant value change as indicated by the Data Source, if any. For more information on writing quality for values, please see the Quality Codes section of the documentation.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec

variant

no

Path to object or property, the object itself, object or property ID.

value

userdata

no

The new value to be set.

quality

userdata

yes

The quality of the value. By default, it is 0 (equivalent to "good"). See Quality Codes for more information.

timestamp

userdata

yes

The timestamp (number of milliseconds since Epoch) of the value. By default, it is the current time.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

  • Cannot set the value of a set-once property - The value of a set-once property cannot be changed because it can be set only when the object is newly created.

Examples

syslib.setvalue("Ref1", 10) -- sets the value of the referenced object
syslib.setvalue("/System/Core/Connector/Datasource/IoNode/Ioitem", 150) -- sets the value (the dynamic property) of the Ioitem
syslib.setvalue("RefItem.Location.Longitude", 6.9363280000) -- sets the value of the specified property
syslib.setvalue("Path/UnknownTagName.WrongPropertyName", true) -- shows error message

In the following tree structure :

+-- System
|   +-- Core
|   |   +-- Folder1
|   |   |   +-- Script
|   |   +-- Folder2
|   |   |   +-- Dataholder2

For the script to access Dataholder2 via a relative path:

syslib.setvalue("../../folder2/holder2.ArchiveOptions.StorageStrategy", "STORE_RAW_HISTORY") -- sets StorageStrategy parameter of holder2 to "STORE_RAW_HISTORY"

Writing null values (or nil values in the Lua syntax) to objects or object properties in system syslib.

syslib.setvalue("Ref1", nil) -- sets the value of the referenced object to nil syslib.setvalue("RefItem.Location.Longitude", nil) -- sets the value of the specified property to nil

Nullable values can also be written as arrays or as null value elements in an array.

syslib.setvalue("/System/Core/Data Holder 1", {nil}) -- Sets the value of the object as an array containing one element with a null value
syslib.setvalue("/System/Core/Data Holder 1", {nil, 1}) -- Sets the value of the object as an array containing two elements, one element being null

Using setvalue with tabledata properties

To successfully set tabledata properties the user must know whether the tabledata property is Schema-defined or Schema-less. Schema-defined tabledata properties have a set schema so this schema needs to be known and matched in order to successfully set the property. Schema-less tabledata properties (for example the Table Holder object’s Table Data property) can be set using the { "data": {}} JSON structure as the property value. It is recommend to define JSON strings using double square brackets.

For a table with 2 columns containing 2 rows of values on a Table Holder object:

local tab = [[ { "data": { "Column1": [ "val1", "val2" ], "Column2": [ "val1", "val2" ] }} ]]
syslib.setvalue("/System/Core/Table Holder.TableData", tab)

sleep

syslib.sleep(milliseconds)

Description

This function causes its calling thread to sleep for the specified number of milliseconds. Note that function is not guaranteed to sleep exactly the specified duration, the actual duration is the best effort by the operating system.

Component Execution

All Components

Examples

local a = now()
syslib.sleep(42) -- sleep for 42 milliseconds
return now() - a

splitpath

syslib.splitpath(path)

Return Type

string

Description

Short name: syslib.splitp

This function splits a given object path and returns the path of the parent and the object’s name. If the path contains escape characters, the result of the function will follow the rules detailed in the Disambiguation of Item Paths section of the documentation. If the diambgiuation rules are violated then the function will fail. The returned object name will have all of its escape characters removed, should it have some. If the parent path does not contain escaped characters it will have no preceding escape caret.

Component Execution

All Components

Examples

local parent, child = syslib.splitpath("/a/b/c") -- parent = "/a/b", child = "c"
local parent, child = syslib.splitpath("^/a/b/c^/d^^e") -- parent = "/a/b", child = "c/d^e"
local parent, child = syslib.splitpath("^/a/b^//c") -- parent = "^/a/b^/", child = "c"

tear

syslib.tear(objspec, name)

Return Type

variant

Description

This function is related to buffering historical data (see buffer function). See the In-Memory Aggregation Jump Start for more information and working examples of the buffer function. It retrieves and clears, atomically, the buffer with the specified name at the specified object or path. The buffer must exist. It returns four values, the array of buffered data values, the array of buffered time stamps, the array of buffered qualities, and the buffer’s counter. The buffer’s counter increases monotonically each time a value is placed into the buffer, and is meant as an aid in detecting buffer overflows.

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the object itself or the object ID.

name

string

no

The name of the buffer to be retrieved and cleared.

Error Messages

  • Object could not be resolved - the object path or id could not be resolved

  • Permission denied - the user does not have sufficient permissions set in Object Level Security

Examples

Assume there is an object obj that generates a numerical value every 10 seconds and historizes its data. We set a buffer on it that stores the values from the last minute:

syslib.buffer(obj, "buff", ".ItemValue", 60000, 6)

Now assume syslib.tear is called after at least one minute:

local values, qualities, timestamps, count = syslib.tear(obj, "buff")

Possible output can be:

  • values: [10, 20, 30, 40, 50, 60]

  • qualities: [0, 0, 0, 0, 0, 0]

  • timestamps: [1476802638691, 1476802648691, 1476802658691, 1476802668691, 1476802678691, 1476802688691]

  • count: 6

uabrowse

syslib.uabrowse(datasource, nodes_to_browse, [defaults] )

Return Type

table

Description

Returns the References of the specified nodes. The function mimics Browse Service call from View Service Set as specified in Section 5.8.2 of OPC-UA Specification Release 1.04.

Component Execution

Connector only

Parameters

Name Type Optional Description

datasource

variant

no

Path to, or a Datasource object (objspec).

nodes_to_browse

variant

no

The nodes to be browsed and corresponding browse properties. The format of this argument is explained below in more details.

defaults

table

no

The default browse properties. The supported browse properties are explained below in more details.

Browse Properties (defaults)

UA Browse service call supports different browse properties which can be used to control the type and information of references being browsed for. The following key-value entries can be used to specify these browse properties:

Key Type Optional Description

browseDirection

integer

yes

Specifies the direction of references to follow. 0 = Forward (Default), 1 = Inverse, 2 = Both.

referenceTypeId

string

yes

Specifies the UA NodeId of the ReferenceType to be browsed. If not specified then all References are returned and includeSubtypes is ignored.

includeSubtypes

boolean

yes

If TRUE (Default) subtypes of the ReferenceType will be browsed, otherwise not

nodeClassMask

integer

yes

The target nodes for which "class" = target_mask, will be returned. The specified value should be an Unsigned 32bit Integer Value representing the Bits being set according to: 0 = Object, 1 = Variable, 2 = Method, 3 = ObjectType, 4 = VariableType, 5 = ReferenceType, 6 = DataType, 7 = View. Default = 0.

resultMask

integer

yes

Species the fields in the ReferenceDescription structure that will be returned. The specified value should be an Unsigned 32bit Integer Value representing the Bits being set according to: 0 = ReferenceType, 1 = IsForward, 2 = NodeClass, 3 = BrowseName, 4 = DisplayName, 5 = TypeDefinition. Default = 63, indicating all fields will be included.

requestedMax

integer

yes

Specifies maximum number of references to be browsed for each Item. Value 0 (Default) indicates no limitation.

Browse Descriptions (nodes_to_browse)

The browse description for the nodes can be specified in one of the three formats given below:

  1. Single String (UA NodeId format) for 1 UA-Node.

  2. Table of Strings (UA NodeId format) for multiple UA-Nodes

  3. Table of detailed browse descriptions, each holding a set of key-value pairs to specify the browse properties.

    • Every browse descriptions must include the "nodeId" field, which is the UA NodeId of the item to be browsed.

    • Additionally, the following entries from the default browse properties can be overridden for each item:

      • browseDirection

      • referenceTypeId

      • includeSubtypes

      • nodeClassMask

      • resultMask

A table with mixed argument formats : (2) and (3) is also supported.

The browse properties specified as part of nodes_to_browse argument overrides the values specified in defaults. If a browse property is not specified anywhere then its default values will be is used.

Return Value Description

The function will always return a Lua table-of-tables, where every sub-table represents the references information of each UA-node specified in the input. Each sub-table contains the following fields:

Key DataType Description

nrefs

integer

Number of references for the item.

continuationPoint

string

Continuation point for the Item which can be used for a UA BrowseNext call.

references

table

"References Table" for the item, explained below.

statusCode

integer

Status code as returned by the server for the corresponding Item.

  • The "References Table" returned for each item, contains the following fields:

    Key DataType Description

    referenceTypeId

    string

    Node Id of the reference type.

    isForward

    boolean

    Indicating browse direction by the server : TRUE = Forward, FALSE = Inverse.

    nodeId

    table

    "NodeId Table" , explained below, contains the expanded node-id information for the reference.

    browseName

    string

    "Browse Name Table" , explained below, contains the qualified browse name of the reference.

    displayName

    table

    "Display Name Table" , explained below, contains the locale and name of the reference.

    nodeClass

    integer

    Node class of the target node.

    typeDefinition

    table

    "TypeDefinition Table" providing the type definition NodeId of the target node. (only available for the Object and Variable node classes)

Based on the resultMask argument, only relevant fields from "References Table" will contain server results. Rest of the entries in the table will simply contain the default values: Boolean fields = FALSE, String fields = "".
  • The NodeId Table returned for each reference, contains the following fields:

    Key DataType Description

    NodeId

    string

    NodeId of the TargetNode

    NamespaceUri

    string

    URI of the name-space

    ServerIndex

    string

    Index of the server that contains the target node

  • The Browse Name Table returned for each reference, contains the following fields:

    Key DataType Description

    name

    string

    Text portion of the name

    namsespaceIndex

    integer

    Namespace index of the Browse name

  • The Display Name Table returned for each reference, contains the following fields:

    Key DataType Description

    locale

    string

    Code representing the location

    name

    string

    Local display name

  • The TypeDefinition Table returned for each reference, contains the following fields:

    Key DataType Description

    NodeId

    string

    NodeId of the type definition

    NamespaceUri

    string

    URI of the name-space

    ServerIndex

    string

    Index of the server that contains the type definition

Examples

A example browse call from UA AnsiC server is shown below:

local value = syslib.uabrowse("/System/Core/localhost/UA",
        -- nodeToBrowse
        { {nodeId="ns=4;s=Demo.BoilerDemo.Boiler1.TemperatureSensor.Temperature", referenceTypeId="ns=0;i=46"}  },
        -- Default browse properties
        {   browseDirection= 0,
            nodeClassMask= 0,
            requestedMax = 2  }
        )
return require("rapidjson").encode(value)

The above code returns two "HasProperty" type references for the corresponding UA node, as shown below:

[
  {
    "nrefs": 2,
    "continuationPoint": "",
    "statusCode": 0,
    "references": [

      {
        "typeDefinition": {
          "serverIndex": 0,
          "namespaceUri": "",
          "nodeId": "ns=0;i=68"
        },
        "browseName": "EngineeringUnits",
        "nodeId": {
          "serverIndex": 0,
          "namespaceUri": "",
          "nodeId": "ns=4;s=Demo.BoilerDemo.Boiler1.TemperatureSensor.Temperature.EngineeringUnits"
        },
        "referenceTypeId": "ns=0;i=46",
        "isForward": true,
        "displayName": {
          "name": "EngineeringUnits",
          "locale": "en-US"
        },
        "nodeClass": 2
      },

      {
        "typeDefinition": {
          "serverIndex": 0,
          "namespaceUri": "",
          "nodeId": "ns=0;i=68"
        },
        "browseName": "EURange",
        "nodeId": {
          "serverIndex": 0,
          "namespaceUri": "",
          "nodeId": "ns=4;s=Demo.BoilerDemo.Boiler1.TemperatureSensor.Temperature.EURange"
        },
        "referenceTypeId": "ns=0;i=46",
        "isForward": true,
        "displayName": {
          "name": "EURange",
          "locale": "en-US"
        },
        "nodeClass": 2
      }
    ]
  }
]

uabrowsenext

syslib.browsenext(datasource,checkpoints)

Return Type

table

Description

Returns the next set of browsed References from the specified continuation points. The function mimics BrowseNext Service call from View Service Set as specified in Section 5.8.3 of OPC-UA Specification Release 1.04.

Component Execution

Connector only

Parameters

Name Type Optional Description

datasource

variant

no

Path to, or a Datasource object (objspec).

checkpoints

table

no

Lua table of continuation points, each being a Lua-String representations of OpcUa_ByteString

Return Value Description

The return value format of uabrowsenext is identical to uabrowse, except that the returned references are per continuation-point basis instead of per UA node basis.

Examples

local append_references = function(dst, src)
    for _,ref in pairs(src) do
        table.insert(dst,ref)
    end
end

local o_datasource = "/System/Core/localhost/UAR"
local result = syslib.uabrowse(o_datasource, "ns=4;s=Admin.StateCurrentTime")

local cp = result[1]["continuationPoint"]
result[1]["continuationPoint"]  = ""    -- get rid of the old CP from the result

while (cp ~= "" ) do
    new_refs = syslib.uabrowsenext(o_datasource, {cp})
    append_references(result[1]["references"], new_refs[1]["references"])
    result[1]["nrefs"] = result[1]["nrefs"] + new_refs[1]["nrefs"]
    result[1]["statusCode"] = new_refs[1]["statusCode"]
    cp = new_refs[1]["continuationPoint"]
end

return result

uaextradata

syslib.uaextradata(quality, ignore_info_type)

Return Type

boolean

Description

Checks whether an OPC UA quality code indicates the presence of Extra Data. This check is only performed if the InfoType bits represent an association with a DataValue or if ignore_info_type is true. Otherwise, false is returned.

For more information, refer to Part 4 Section 7.39.1 of OPC UA Specification Release 1.05.

Component Execution

All Components

Parameters

Name Type Optional Description

quality

number

no

The OPC UA quality numerical code.

ignore_info_type

boolean

yes

When true, the check of InfoType bits is skipped.

Examples

local _, q = syslib.getvalue("/System/Core/Item")
return syslib.uaextradata(q)

uamethodcall

syslib.uamethodcall(datasource, methods_to_call)

Return Type

table

Description

Calls one or more OPC UA Methods and returns their results. The function mimics Call Service call from Method Service Set as specified in Section 5.11.2 of OPC-UA Specification Release 1.04.

Component Execution

Connector only

Parameters

Name Type Optional Description

datasource

variant

no

Path to, or a Datasource object (objspec).

methods_to_call

table

no

Table of methods to call, explained below.

methods_to_call

methods_to_call is a table-of-tables where each sub-table represents a UA Method to be called. It may have the following entries.

Key Type Optional Description

objectId

string

no

UA NodeId of the Object or ObjectType on which the Method is invoked.

methodId

string

no

UA NodeId of the Method to invoke.

inputArguments

table

yes

Table of input argument values. The size and order of this list matches the size and order of the input arguments defined by the InputArguments property of the Method.

datatypes

table

yes

Table of datatypes of each argument in inputArguments table. If a datatype is not specified for an argument, then the function deduces it based on an unspecified logic.

Return Value Description

The function returns a table-of-tables, where each sub-table at represents the return value of a method in the methods_to_call table. The size and order of this table matches the size and order of the methods_to_call table.

Each sub-table has the following entries.

Key Type Optional Description

statusCode

integer

no

Status Code of the Method executed in the Server. It is set to Bad_InvalidArgument if at least one input argument broke a constraint (e.g. wrong data type, value out of range). It is set to a bad Status Code if the Method execution failed in the Server, e.g. based on an exception. Common OPC UA status codes are defined in Section 7.34 of OPC-UA Specification Release 1.04.

inputArgumentResults

table

no

Table of StatusCodes corresponding to the inputArguments. If this table is populated, it has the same length as the inputArguments table.

outputArguments

table

no

Table of returned values from the Method. An empty table indicates that there are no returned values. The size and order of this table matches the size and order of the output arguments defined by the OutputArguments property of the Method.

Examples

Call 3 methods on the Unified Automation AnsiC server. Pass a double to the first two methods and pass an unsigned 32-bit integer to the third one.

return syslib.uamethodcall('^/System/Core/Connector/UAAnsiC_Datasource',
{
{'ns=4;s=Demo.BoilerDemo.Boiler1', 'ns=4;s=Demo.BoilerDemo.Boiler1.Fill', {50.0}},
{'ns=4;s=Demo.BoilerDemo.Boiler1', 'ns=4;s=Demo.BoilerDemo.Boiler1.Heat', {20.0}},
{'ns=0;i=2253', 'ns=0;i=11492', {1}, {syslib.model.codes.OPCUADataTypes.UINT32}}
})

The function above returns the following table. It can be seen that, the first two methods don’t return anything. The third method returns 2 tables. The server also returns a custom code in the inputArgumentResults table.

{
    {
        "outputArguments": {},
        "statusCode": 0,
        "inputArgumentResults": {}
    },
    {
        "outputArguments": {},
        "statusCode": 0,
        "inputArgumentResults": {}
    },
    {
        "outputArguments": {
            {1,2,3,4,5},
            {1,2,3,4,6}
        },
        "statusCode": 0,
        "inputArgumentResults": {
            3354931
        }
    }
}

uaread

syslib.uaread(datasource, nodes_to_read, [max_age], [return_ts])

Return Type

table

Description

Returns the value of the specified attributes of UA nodes. The function mimics Read Service call from Attribute Service Set as specified in Section 5.10.2 of OPC-UA Specification Release 1.04.

Component Execution

Connector only

Parameters

Name Type Optional Description

datasource

variant

no

Path to, or a Datasource object (objspec).

nodes_to_read

table

no

Table of nodes, their attribute to read and read properties, explained below.

max_age

integer

yes

Maximum age of the value to be read in milliseconds. 0 = Server shall attempt to read a new value from the data source, max Int32 value or greater, the Server shall attempt to get a cached value. Default = 0.

return_ts

integer

yes

0 = Source timestamp , 1 = Server timestamp, 2 = BOTH (Default), 3 = neither

nodes_to_read

nodes_to_read is a Lua table-of-tables where every sub-table represents a node description containing the following entries:

Key Type Optional Description

nodeId

string

no

UA NodeId

attributeId

integer

no

Id of the attribute

indexRange

string

yes

Represents the Numeric Range, as described in Section 7.22 of OPC-UA Specification Release 1.04, Default = ""

dataEncoding

string

yes

This parameter specifies the BrowseName of the DataTypeEncoding that the Server should use when returning the Value Attribute of a Variable. Default = "".

Return Value Description

The function always returns a Lua table-of-tables, where every sub-table represents the attribute value per entry in the nodes_to_read argument. Each attribute-value table contains the following entries:

Key DataType Description

value

table

Table with fields V, Q, T, which are arrays of values, qualities and timestamps, respectively. In this table, timestamp (T) is always the Source-timestamp returned by the server. The validity of the timestamp will depend on the argument return_ts

serverPicoseconds

integer

Specifies the number of 10 picoseconds (1,0 e-11 seconds) intervals which shall be added to the server timestamp.

serverTimestamp

integer

UTC server timestamp of the value.

sourcePicoseconds

integer

Specifies the number of 10 picoseconds (1,0 e-11 seconds) intervals which shall be added to the source timestamp.

sourceTimestamp

integer

UTC source timestamp of the value.

Examples

local values = syslib.uaread("/System/Core/localhost/UACPP",
        {
            {nodeId="ns=2;s=Demo.Static.Scalar.Int64",attributeId="3"},     -- browse-name
            {nodeId="ns=2;s=Demo.Static.Scalar.Int64",attributeId="13"}     -- value
        })

return require('rapidjson').encode(values)

Returned value :

[
  {
    "value": {
      "T": -11644473600000,
      "Q": 0,
      "V": "2:Int64"
    },
    "serverPicoseconds": 0,
    "sourceTimestamp": -11644473600000,
    "serverTimestamp": 1564140933262,
    "sourcePicoseconds": 0,
    "statusCode": 0
  },
  {
    "value": {
      "T": 1563970440656,
      "Q": 0,
      "V": 0
    },
    "serverPicoseconds": 0,
    "sourceTimestamp": 1563970440656,
    "serverTimestamp": 1564140933262,
    "sourcePicoseconds": 0,
    "statusCode": 0
  }
]

utf16to8

syslib.utf16to8(string, [Big_Endian])

Return Type

string

Description

Interprets the input string as a sequence of bytes in the UTF-16 encoding and returns its UTF-8 equivalent. If the length of the input string is odd, it is padded with a zero byte before conversion. Malformed codepoints are replaced with U+FFFD.

The Byte Order Mark (BOM) codepoint U+FEFF, as well as its "Inverse-Endian" U+FFFE, are treated as regular codepoints and have no effect on the conversion as a whole.

Component Execution

All Components

Parameters

Name Type Optional Description

string

string

no

The string to be converted.

Big_Endian

Boolean

yes

Whether the input is Big-Endian. It is not by default.

Error Messages

None

Examples

local string_in_UTF8 = syslib.utf16to8(string_in_UTF16)

utf8to16

syslib.utf8to16(string, [Big_Endian])

Return Type

string

Description

Interprets the input string as a sequence of bytes in the UTF-8 encoding and returns its equivalent string of bytes in the UTF-16 encoding. Malformed codepoints are replaced with U+FFFD.

The Byte Order Mark (BOM) codepoint U+FEFF, as well as its "Inverse-Endian" U+FFFE, are treated as regular codepoints and have no effect on the conversion as a whole.

Component Execution

All Components

Parameters

Name Type Optional Description

string

string

no

The string to be converted.

Big_Endian

Boolean

yes

Whether the return string is Big-Endian. It is not by default.

Error Messages

None

Examples

local string_in_UTF16 = syslib.utf8to16(string_in_UTF8)

utf8toascii

syslib.utf8toascii(string, [code_page])

Return Type

string

Description

Converts an UTF8 string into an ASCII string and returns it.

Component Execution

All Components

Parameters

Name Type Optional Description

string

string

no

The string to be converted.

code_page

number

yes

The country encoding. By default it’s zero, meaning current code page.

Error Messages

  • String conversion error - when string length is over 4096 bytes

Examples

syslib.utf8toascii("Brühl")

uuid

syslib.uuid([count], [options])

Return Type

variant

Description

Returns four values: a single UUID or a table of UUIDs, the UUID version, the UUID variant, and a UUID version specific status code (a integral number). The UUID version defaults to 1 (date-time and MAC address). If no count argument is specified (or nil is used), a single UUID is generated and returned, otherwise count UUIDs are generated and returned as a table. The second argument is either an integer number specifying the UUID version or a table containing options specifying the output format and version-specific UUID generation parameters.

Returned status codes

The status code may be non-zero for version 1 UUIDs only and may be platform-specific.

  • 0 - Good.

  • 1 - The UUID is guaranteed to be unique to this computer only.

Component Execution

All Components

Parameters

Name Type Optional Description

count

number

yes

The number of UUIDs to generate. If count is nil, a single UUID is returned. Otherwise, a table of UUIDs is returned.

options

number

yes

A number specifying the UUID version to generate, or a table containing more options.

Version values (if options is a number):

  • 0 (nil-UUID), the version number returned by this function will be -1 (unknown)

  • 1 (date-time and MAC address), the default

  • 2 (date-time and MAC address, DEC security version), not supported

  • 3 (namepace name-based using MD5), not supported

  • 4 (random)

  • 5 (namepace name-based using SHA-1), not supported

Options table fields:

  • version: A integral number, specifying the UUID version number

  • format: Accepts strings or numeric values, "text" (2) (the default) or "binary" (1). Note that "binary" is not suitable for printing

  • secure_mac: Only applies to version 1 and 2 UUIDs. If the value converts to true, a platform-specific UUID generator is used to avoid leaking network-card addresses.

Error Messages

  • Version <version> uuid generation is not supported yet - the specified UUID version cannot be generated.

  • Cannot get Ethernet or token-ring hardware address for this computer - retrieving the hardware address for UUID version 1 or 2 failed.

Examples

-- returns a single version 1 UUID -- "00112233-4455-1677-2899-aabbccddeeff", 1, 1, 0
local uuid, ver, var, status = syslib.uuid()

-- returns two version 1 UUIDs -- {"2f0bce8f-384d-11e9-85ad-448a5b5cb56b","2f0bce90-384d-11e9-85ad-448a5b5cb56b"}, 1, 1, 0
syslib.uuid(2)

-- returns two version 4 UUIDs -- {"11c6c9d8-1089-46a3-8933-f361f45d6289","711d7bfd-863d-4db1-a9fa-d39eb5074723"}, 4, 1, 0
syslib.uuid(2, 4)

-- returns a single version 4 UUID -- "11c6c9d8-1089-46a3-8933-f361f45d6289", 4, 1, 0
syslib.uuid(nil, 4)

-- returns a single version 4 UUID which cannot be traced to the computer on which it was generated -- "e1708052-1127-4d00-a174-f72025df0ce0", 4, 1, 0
syslib.uuid(nil, { secure_mac = true })