inmation Library Functions

asciitoutf8

inmation.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

inmation.asciitoutf8("Brühl")

attach

inmation.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.

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

  • inmation.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 inmation 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:

inmation.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:

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

buffer

inmation.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 inmation 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:

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

Depending on the provided arguments, it has several variations:

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

  2. inmation.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. inmation.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 inmation 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 inmation 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 ]]
    inmation.buffer(obj, "buff2", "buff", 60000, 6, func)
  4. inmation.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).

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

checkmodelaccess

inmation.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 = inmation.model.flags.ProfileModelAccess
local profile = inmation.getobject("/visitor")
return  inmation.checkmodelaccess(model_flags.PRF_MDL_ACC_IO | model_flags.PRF_MDL_ACC_ACC, profile)

checkpermission

inmation.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 pathspec for the union of permissions granted to the given profiles.

Component Execution

Core only

Parameters

Name Type Optional Description

pathspec

variant

no

Object’s path, or the inmation 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 = inmation.model.flags.SecurityAttributes
local profile = inmation.getobject("/ro")
local granted = inmation.checkpermission("/System/Core/Item", sec_flags.READ | sec_flags.WRITE, profile)

control.getself

inmation.control.getself()

Return Type

number

Description

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

control.dedicate

inmation.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

inmation.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.

  • 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.

control.terminate

inmation.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 inmation.control.terminate() is made on this instance, it will not terminate until the socket.sleep(60) command has finished. Any object associated with the instance will change its status to OpcUa_BadOutOfService and its value will be set to Terminated. 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.

createobject

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

Return Type

table

Description

Short name: inmation.new

Creates a new inmation 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 inmation 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 = inmation.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 = inmation.createobject("/System/localhost", "MODEL_CLASS_RULE", "OT_RULE")
obj.ObjectName = "rule"
obj:commit()

currenttime

inmation.currenttime([local])

Return Type

number

Description

Short name: inmation.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 = inmation.currenttime()
local no_of_ms_local = inmation.currenttime(true)

currenttimezone

inmation.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 = inmation.currenttimezone()

debase64

inmation.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 inmation.debase64("YWJjZAsdsdsasdasAw==")

defaults

inmation.defaults([default_params])

Return Type

table

Description

Short name: inmation.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

All the currently defined defaults deal with OPC write behavior:

Code Label Description

write_fetch

OPC Mode

Define how to read the value before writing.

write_delay

Pack Delay

Time to wait in order to collect multiple writes.

write_audit

Audit write

Create audit in system log for write operation.

write_async

Write async

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

write_group

Force OPC DA 2.05

Defines which OPC write method should be used.

write_timeo

Write timeout

Currently has no effect.

The possible values for the write_fetch parameter are:

  • "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

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

deleteobject

inmation.deleteobject(objspec)

Description

Short name: inmation.del

Deletes an inmation object.

Component Execution

Core only

Parameters

Name Type Optional Description

objspec

variant

no

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

Error Messages

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

Examples

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

deleterawhistory

inmation.deleterawhistory(pathspec, time_start, time_end)

Description

Deletes a time span of raw history for an inmation 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.

Component Execution

Core only

Parameters

Name Type Optional Description

pathspec

variant

no

Object’s path, or the inmation object itself, object or property ID for which raw history is to be deleted.

time_start

integer

no

The start of the time span where raw history is to be deleted.

time_end

integer

no

The end of the time span where raw history is to be deleted.

Error Messages

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

Examples

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

disableobject

inmation.disableobject(objspec)

Description

Short name: inmation.dis

Disables an inmation object.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

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

Error Messages

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

Examples

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

dumpimage

inmation.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 inmation support with steps to reproduce the problem.

Examples

inmation.dumpimage("D:\\backup\\core_snapshot")
inmation.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

inmation.enableobject(objspec)

Description

Short name: inmation.ena

Enables an inmation object.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

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

Error Messages

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

Examples

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

enbase64

inmation.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 inmation.enbase64("\97\98\99\100") -- result: "YWJjZA=="

excel2posix

inmation.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 = inmation.excel2posix(25569.52) -- 44928000
return inmation.gettime(psx_time) -- result: 1970-01-01T12:28:48.000Z

findobjects

inmation.findobjects(value, [model], [dynonly], [fullpath])

Return Type

table

Description

Searches a value in the entire tree structure and returns a table with all the inmation objects that contain this value in their paths.

Component Execution

All Components

Parameters

Name Type Optional Description

value

string

no

The string to be searched.

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 made only on dynamic objects. Default is false.

fullpath

boolean

yes

A boolean specifying if the value is searched in the entire path of the objects. Default is false.

Examples

local tab = inmation.findobjects("value") -- searches "value" in all models, all objects and doesn't take into account the whole path
local tab2 = inmation.findobjects("value", 1, true, true) -- searches "value" in the I/O Model, only dynamic objects and takes into account the whole path

foldcase

inmation.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 inmation.foldcase("DÜRST") -- returns "dürst"

getattributesex

inmation.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. inmation.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 = inmation.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 = inmation.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

inmation.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).

Component Execution

Master Core only

Parameters

Name Type Optional Description

objspec(s)

variant

yes

Object’s path, the inmation 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 beginning of the range of time to be queried.

time_end

integer

yes

The end 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.

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 Auidt 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 inmation.getaudittrail({'/System/Core'}, {limit = 100 , time_start = inmation.gettime("2020-03-30T11:41:55.940Z"),
time_end = inmation.gettime("2020-05-17T14:41:55.940Z")})

getconnectorpath

inmation.getconnectorpath(objspec)

Return Type

string

Description

Short name: inmation.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 connector to which the given object belongs or nil if no connector was found in the parent objects hierarchy.

Component Execution

Connector only

Parameters

Name Type Optional Description

objspec

variant

yes

Object’s path, the inmation 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 inmation.getconnectorpath("/System/Core/localhost/folder/object") -- returns "/System/Core/localhost"
return inmation.getconnectorpath("/System/Core/object") -- returns nil

getcorepath

inmation.getcorepath(objspec)

Return Type

string

Description

Short name: inmation.corep

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 core to which the given object belongs or nil if no core object was found in the parent objects hierarchy.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

yes

Object’s path, the inmation 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 core at the following path: "/System/Core"
return inmation.getcorepath("/System/Core/localhost/folder/object") -- returns "/System/Core"
return inmation.getconnectorpath("/System") -- returns nil

getdefaults

inmation.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 inmation.getdefaults().write_delay

geteventhistory

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

Return Type

string

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.

Component Execution

Core only

Parameters

Name Type Optional Description

paths

table

no

A table containing either the paths of the objects (objspec) or the inmation 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 inmation 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.

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)
    │   |   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 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)
                ...

Examples

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

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

inmation.geteventhistory({'/System/Core/ScriptEvent1', '/System/Core/Connector/ScriptEvent2'}, inmation.now() - 24 * 60  * 60000, inmation.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.

inmation.geteventhistory({'/System/Core/ScriptEvent1', '/System/Core/Connector/ScriptEvent2'}, inmation.now() - 24 * 60  * 60000, inmation.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.

inmation.geteventhistory({'/System/Core/ScriptEvent1', '/System/Core/Connector/ScriptEvent2'}, inmation.now() - 24 * 60  * 60000, inmation.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}'
})

gethistory

inmation.gethistory(paths, start, end, [intervals_no], [aggregates], [percentage_good], [percentage_bad], [treat_uncertain_as_bad], [slopped_extrapolation], [partial_interval_treatment])

Return Type

table

Description

Short name: inmation.hist

This function returns historical data.

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](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.

Component Execution

Core only

Parameters

Name Type Optional Description

paths

table

no

A table containing either the paths of the objects or the inmation 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.

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

By default false.

slopped_extrapolation

boolean

yes

By default false.

partial_interval_treatment

string

yes

By default "UASTANDARD".

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 = inmation.currenttime() - 60000 -- last minute
local end_time = inmation.currenttime()

local res = inmation.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 inmation.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 inmation.sethistory function:

local item_path = "/System/localhost/item"

local startt, endt = inmation.gethistoryframe(item_path)
local hist = inmation.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 = inmation.getpropertyid("/System/localhost/item2")
for i = 1, #data.V do
    inmation.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 inmation.currenttime function can be used as follows:

local t1 = inmation.now() -- insert inmation.history function call here
local total_time = inmation.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 inmation methods that access historical data (excluding inmation.gethistoryex as this method does not request data from the time-series repository)

gethistoryex

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

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

Indicating whether bounding values are required, false by default.

Examples

Each history is a table with fields V, Q, T, which are arrays of values, qualities and timestamps, respectively. The order of values in the V, Q, T tables is exactly as produced by the underlying HDA server which, for conformant serves, is governed by the start and end time arguments. Of these three arrays, only Q and T are true arrays, in the sense that thay can have their length reliable taken with #. The V array may have gaps due to empty or null data at certain points.

For an OPC HDA datasource:

local rt = inmation.gethistoryex(
    '/System/Core/localhost/inmation.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
    --inmation.now() - 24 * 3600000, inmation.now()
    30,
    true
)

local s = ""
for i = 1, #rt.Q do
    local ss = '{' .. tostring(rt.V[i]) .. ', ' .. rt.Q[i] .. ', ' .. inmation.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 = inmation.now()
local rt = inmation.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] .. '}'
     if #s > 0 then
       s = s .. ', ' .. ss
     else
       s = ss
     end
  end
end

return s

gethistoryframe

inmation.gethistoryframe(objspec)

Return Type

number

Description

Short name: inmation.histf

Returns the oldest and the newest timestamp in history for a given object or path. The function can return at most two elements. When there is only one historized value, it returns one, and when no data has ever been historized, it returns none.

Component Execution

Core only

Parameters

Name Type Optional Description

objspec

variant

no

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

Error Messages

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

Examples

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

getlogs

inmation.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.

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 inmation 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 = inmation.getlogs(inmation.now() - 20000 , inmation.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

inmation.getmicrosecondcounter()

Return Type

number

Description

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

Component Execution

All components

getmongoconnection

inmation.getmongoconnection([store], [testarchive], [storecode])

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 inmation.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.

storecode

number

yes

If the System object is passed as the store parameter, a valid inmation.model.codes.RepoStoreName shall be specified to select a particular data store in the object.

Examples

local mongo = require 'mongo'
local client = inmation.getmongoconnection()
-- Or alternatively,
-- local client = inmation.getmongoconnection(inmation.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 = inmation.getmongoconnection('/System/Core/CustomEventStore1')

getmongoconnectionstring

inmation.getmongoconnectionstring([store], [testarchive], [storecode])

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 inmation.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.

storecode

number

yes

If the System object is passed as the store parameter, a valid inmation.model.codes.RepoStoreName shall be specified to select a particular data store in the object.

Examples

local mongo = require 'mongo'
local client = mongo.Client( inmation.getmongoconnectionstring(inmation.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
inmation.getmongoconnectionstring('/System/Core/CustomEventStore1')

getobject

inmation.getobject(objspec)

Return Type

table

Description

Short name: inmation.obj

Gets an existing inmation 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 inmation 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: Lua local obj = inmation.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: Lua 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: Lua obj.Limits.OpcRangeLow = "abc" — this property accepts only numbers

Examples

local obj = inmation.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 inmation.createobject function case, changed properties are committed into the system only after the commit function is called on the object:

obj:commit()

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

local current = inmation.getobject(".")

getopcuaquality

inmation.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 = inmation.getopcuaquality(24) -- Converts the "Comm Failure" code to the UA "BadCommunicationError" code

getparentpath

inmation.getparentpath(objspec)

Return Type

string

Description

Short name: inmation.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 inmation 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 = inmation.getparentpath("/System/localhost/object") -- returns "/System/ localhost"

getpropertyid

inmation.getpropertyid(objspec, [property_name])

Return Type

number

Description

Short name: inmation.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 inmation 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 = inmation.getpropertyid("/System/Core/object")
local prop_id = inmation.getpropertyid("/System/Core/object", "ObjectName")

getpropertyname

inmation.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

inmation.getrawhistory(pathspec, bounds, time_start, time_end, max_limit)

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 the its ID or path.

Long Description

The number of data points return depends on the values of time_start, time_end and max_limit. Bounds is a boolean value that specify whether additional Bounding Values should also be returned. Bounding Values are data points that 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 that 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 return The behavior of this function is generally that specified by OPC UA part 11 Section 6.4.3.2 (with the exception of continuation points). Section 4.4 of the same document provides more information on Start and End periods.

Return Values

  • results - Lua Userdata containing a Lua Iterator that may be used to retrieve the values of the timestamp, data value and quality on a generic for loop.

  • 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

variant

no

Object’s path, the inmation object itself, the object ID 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.

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 inmation.getrawhistory function and iterate through the results.

local total = 0
local rs, more = inmation.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.

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

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

-- populating with inmation.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 = inmation.gettime('1970-01-01 00:00:00')
local prpid = inmation.getpropertyid(root .. '/' .. name)
for i = 1, #data do
  inmation.sethistory(prpid, data[i], 0, epoch + data[i])
end

-- 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 = inmation.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 inmation.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 = inmation.now() -- insert inmation.history function call here local total_time = inmation.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 inmation methods that access historical data (excluding `inmation.gethistoryex`as this method does not request data from the time-series repository) Although this function adheres to the OPC UA part 11 Section 6.4.3.2 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

inmation.getreferences([objspec])

Return Type

table

Description

Short name: inmation.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 inmation.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 inmation object itself or the object ID.

Error Messages

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

Examples

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

getsafconfirmedseqnr

inmation.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 inmation.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 inmation.model.codes.SafDataCategory.

Examples

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

getsafforwardedseqnr

inmation.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 inmation.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 inmation.model.codes.SafDataCategory.

Examples

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

getsafseqnr

inmation.getsafseqnr(category)

Return Type

variant

Description

Returns the current Store and Forward sequence number(s). If category is inmation.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 inmation.model.codes.SafDataCategory.

Examples

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

getscopeparameters

inmation.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 inmation.getscopeparameters()   -- returns a table of current scope-settings
                                       -- for eg. {comment = "Default Comment"}

getrelaypaths

inmation.getrelaypaths(objspec)

Return Type

table

Description

Short name: inmation.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 inmation 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 inmation.getrelaypaths("/System/Core/relay1/relay2/connector/object") -- returns [ "/System/Core/relay1", "/System/Core/relay1/relay2"]
return inmation.getrelaypaths("/System/Core/object") -- returns nil

getselectorentries

inmation.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 and optionally a tree field:

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

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, optional if options.tree = true)

  • class_code (number)

  • path (string, optional)

The value field is nil for items which represent hierachical nodes for InstanceSelector properties. Such items are not selectable and only used for hierarchically representing the items.

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.

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.

Additionally to the top-level items field, the tree field is returned for InstanceSelector type properties if options.tree is set to true. The field contains edge information for the returned items. Edges are encoded as an array of integral numbers in tree, where each pair of numbers (the first pair being the first and second number in the tree array) contains the index for the start and end node as they are stored in the items array. Note that every item whose index is not present in the tree array is a root node and there may be more than one root.

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 field tree is treated as a boolean field indicating if the result should contain additional structural information describing the hierarchy of the returned data (if applicable). 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 denoting a property of type InstanceSelector or TableRowSelector. In case of InstanceSelector properties, the parameter can be a property code like inmation.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, properties of type InstanceSelector require the caller to have LIST permissions on the default core object.

Examples

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

getself

inmation.getself()

Return Type

table

Description

Short name: inmation.slf

Returns the current object as an inmation object.

Component Execution

All Components

Examples

return inmation.getself():path()

getselfpath

inmation.getselfpath()

Return Type

string

Description

Short name: inmaton.selfp

Returns the path to the current object.

Component Execution

All Components

Examples

return inmation.getselfpath()

getsystemdb

inmation.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.

Long Description

The system database has 3 tables: 'properties', 'live_properties' and 'history' that can be used to query information. Their schemas are shown below:

The systemdb table schemas

The properties in the table are queried by the property code not the property name. The properties table contains only static properties. The table 'live_properties' can be used to query all properties of the objects but it is not as quick as the queries on properties table.

Examples

local sysDB = inmation.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 = inmation.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

However, he property codes can also be accessed by using the inmation.model.properties. notation.

--get the read-only handle
local sysDB = inmation.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 " .. inmation.model.properties.ObjectName .. " AND value IS 'gen_1';")

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

getsystempath

inmation.getsystempath(objspec)

Return Type

string

Description

Short name: inmation.systemp

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 system to which the given object belongs or nil if no system object was found in the parent objects hierarchy.

Component Execution

All Components

Parameters

Name Type Optional Description

objspec

variant

no

Object’s path, the inmation 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 inmation.getsystempath("/System/Core/localhost/folder/object") -- returns "/System"
return inmation.getsystempath("/") -- returns nil

gettime

inmation.gettime(time, [format])

Return Type

number

Description

Short name: inmation.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 = inmation.gettime("2014-12-02T07:41:03.871Z") -- returns 1417506063871
local no_of_ms = inmation.gettime("2014-12-02T07:41:03.871-02:00") -- returns 1417513263871
local no_of_ms = inmation.gettime("2014.12.02 07:41:03",  "%Y.%m.%d %H:%M:%S") -- returns 1417506063000
local no_of_ms = inmation.gettime("2014.12.02 07:41:03.871",  "%Y.%m.%d %H:%M:%s") -- returns 1417506063871
local timestamp = inmation.gettime(1417506063871) -- returns "2014-12-02T07:41:03.871Z"

gettimeparts

inmation.gettimeparts(datetime)

Return Type

number

Description

Short name: inmation.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 = inmation.gettimeparts(1461549032930)
-- or year, month, day, hour, min, sec, msec = inmation.gettimeparts("2016-04-25T01:50:32.930Z")
return {year, month, day, hour, min, sec, msec}

gettimepartstable

inmation.gettimepartstable(datetime)

Return Type

table

Description

Short name: inmation.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 inmation.gettimepartstable(1461549032930) -- OR
return inmation.gettimepartstable("2016-04-25T01:50:32.930Z") -- both cases return [2016, 4, 25, 1, 50, 32, 930]

getvalue

inmation.getvalue(pathspec)

Return Type

multiple return values

Description

Short name: inmation.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.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec

variant

no

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

Error Messages

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

Examples

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

In the following tree structure:

System

  • localhost

    • folder1

      + script

    - folder2 <blockquote>holder2</blockquote>
</blockquote>

+

For the script to access holder2 via a relative path:

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

Observations

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

hdagetitemattributes

inmation.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 = inmation.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

inmation.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 = inmation.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

inmation.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 = inmation.getvalue("/System/core/item")
return inmation.isbadstatus(q)

isgoodstatus

inmation.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

inmation.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

inmation.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 inmation 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:

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

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

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

listbuffer

inmation.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 inmation object itself or the object ID.

Error Messages

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

Examples

inmation.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".

linkprocessvalue

inmation.linkprocessvalue(objspec, ref)

Description

Short name: inmation.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 inmation 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

Examples

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

log

inmation.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 inmation.log() function:

Code Tag Severity/Type

1

ERR

Error

2

WRN

Warning

3

INF

Information

4

DBG

Debug

The inmation.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
inmation.log(1, "The script body returned a string; a table is expected")
-- Example of a debug log entry with detail
inmation.log(4, "The script body returned a string; a table is expected", "This can be fixed by returning a table. For more information ...")

luamemory

inmation.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 inmation 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

inmation.luamemory("/System/Core/script_item") -- returns an integer meaning the number of bytes being used by the object
inmation.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
inmation.luamemory() -- returns a table with the same format, but containing information about all script objects

mass

inmation.mass(entries, [batch_flags])

Return Type

table

Description

Does the equivalent of a Mass Configuation operation in DataStudio. A mass entry in the entries parameter contains the modifications that are applied to one single inmation 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: inmation.model.codes.MassOp.UPSERT

  • path - the path of the inmation 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: inmation.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 inmation object; numerical value; inmation.mass will be executed only if the inmation 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.

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: inmation.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
    inmation.mass({{path = base .. '/data/' .. i, class = inmation.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 = inmation.model.codes.MassOp.INSERT,
    class = inmation.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 = inmation.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 = inmation.model.classes.GenFolder,
    path = "/System/Core/Test Folder",
    ObjectName = 'Test Folder'
}

local res = inmation.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.

inmation.mass {{path = inmation.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

model.classes

inmation.model.classes.class_name

Description

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

Return Type

number

Component Execution

All Components

Examples

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

-- OR

local T = inmation.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

inmation.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 inmation.model.codes.SelectorGenItem.LUASCRIPT -- returns 5

-- OR

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

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

return inmation.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 = inmation.model.codes.SelectorGenItem return T[5] -- returns {"tag":"LUASCRIPT","meaning":"GenLuascript"}

model.counters

inmation.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 inmation.model.counters.CPU -- returns 72

-- OR

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

model.flags

inmation.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 inmation.model.flags.ItemValueStorageStrategy.STORE_RAW_HISTORY -- returns 1

-- OR

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

-- OR

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

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

return inmation.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 = inmation.model.flags.PlcType return T[0x8000] -- returns {"tag":"PLC_TYPE_REMOTE", "meaning":"Plc Type Remote"}

model.properties

inmation.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 inmation.model.properties.ObjectName -- returns 1

-- OR

local T = inmation.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

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

Description

Moves and/or renames an inmation 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 inmation object itself or the object ID.

parent

variant

no

Object’s path, or the inmation 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 = inmation.getobject('/A/B/C/D')
local pa1 = obj:parent()
local pa2 = inmation.getobject('/A/B/X')
inmation.moveobject(obj, pa2) -- if successful, obj becomes A/B/X/D
inmation.moveobject(obj, pa2, 'Y') -- if successful, obj becomes A/B/X/Y
inmation.moveobject(obj, pa1, 'Z') -- if successful, obj becomes A/B/C/Z

msgqueue

inmation.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 inmation.msg functions. Messages can be read from the queue either using inmation.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, but concurrent execution of these functions will raise a Lua error.

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 inmation 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 = inmation.msgqueue(inmation.getcorepath(), 1)

Iterating over all currently fetched (in memory) messages of a queue is done using pairs:

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

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

msgpush

inmation.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 inmaiton.msgqueue()

msg

string

no

The message to be pushed

Return Type

boolean, string

Examples

Push a single message:

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

msgpop

inmation.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 inmaiton.msgqueue()

msgid

integer

no

The message id to be removed from the queue

Examples

Pop all messages with id ⇐ 10:

inmation.msgpop(queue, 10)

msgnext

inmation.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 inmaiton.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 inmation.msgnext(queue) then
  print("queue is empty")
end

Get the first and second message:

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

msgclear

inmation.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 inmaiton.msgqueue()

msgstats

inmation.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 inmaiton.msgqueue()

Return Type

table

Examples

Print the statistics of queue as a JSON document:

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

with output (similar to):

{
  "oid": 1234567891234, // The inmation 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
}

peek

inmation.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 inmation object itself or the object ID.

name

string

no

The name of the buffer to be retrieved.

posix2excel

inmation.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 inmation.posix2excel(inmation.gettime("1970-01-01T12:28:48.000Z")) --result: 25569.52

queryenvironment

inmation.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_OPC_CLIENT_URI"

  • "APPLICATION_OPC_SERVER_URI"

  • "APPLICATION_OWNER_DOMAIN"

  • "APPLICATION_OWNER_NAME"

  • "APPLICATION_SECURITY"

  • "APPLICATION_SECURITY_MODE"

  • "APPLICATION_UA_CLIENT_URI"

  • "APPLICATION_UA_SERVER_URI"

  • "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_FRIENDLYNAME"

  • "MODULE_HOMEDRIVE"

  • "MODULE_HOST_LOG_FILE"

  • "MODULE_HOST_LOG_FOLDER"

  • "MODULE_LOG_FOLDER"

  • "MODULE_MANUFACTURER"

  • "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"

  • "PRODUCT_URI"

  • "SCRIPT_HOME"

  • "SERVICE_CERTIFICATE_FOLDER"

  • "SERVICE_DESCRIPTION"

  • "SERVICE_DROP_AE_FOLDER"

  • "SERVICE_DROP_DA_LOC_FOLDER"

  • "SERVICE_DROP_DA_UTC_FOLDER"

  • "SERVICE_DROP_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_SAF_IN_FOLDER"

  • "SERVICE_SAF_OUT_FOLDER"

  • "SERVICE_SERVER_PORT"

  • "SERVICE_SERVER_PREALLOC"

  • "SERVICE_SERVER_PROTOCOL"

  • "SERVICE_SHORT_NAME"

  • "SERVICE_STARTTIME"

  • "SERVICE_START_ACCOUNT"

  • "SERVICE_START_TYPE"

  • "SERVICE_TEMP_FOLDER"

  • "SERVICE_TYPE"

  • "SERVICE_WORK_FOLDER"

  • "WEBSITE"

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 inmation.queryenvironment("MODULE_ROOT_FOLDER") -- return the root folder, e.g., "D:\inmation.root"

regex

inmation.regex(string, expression)

Return Type

boolean

Description

Specifies whether a string matches a regular expression.

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.

Examples

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

scopedcall

inmation.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

inmation.scopedcall({comment = "This is a function specific comment"}, inmation.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"}
inmaiton.setscopeparameters(settings_a)
inmation.disableobject("/System/Core/object_1") -- settings_a will be applied

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

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

setdefaults

inmatiom.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

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

setevent

inmation.setevent(data)

Return Type

boolean

Description

Short name: inmation.setev

Sets a script event. Expects a JSON string or 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. By default, it is an empty string.

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

Component Execution

All Components

Parameters

Name Type Optional Description

data

string

no

The event data to be set; can be either a string in JSON format or a table containing key-value pairs.

Examples

local t = {}
t["Severity"] = 500
t["Message"] = "script event"
t["Timestamp"] = 1470663220365
t["key1"] = "str"
t["key2"] = 35
t["key3"] = {1, 2, 3}

return inmation.setevent(t)

sethistory

inmation.sethistory(ID, value, quality, timestamp)

Return Type

boolean

Description

Short name: inmation.sethist

Adds historical data to a given item and returns the result of executing this operation, where true means it was successful and false otherwise.

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 = inmation.sethistory(281476615897088, 10, 0, 1461051211899)
local success2 = inmation.sethistory(281476615700480, "abc", 0, 1461051211899)
local success3 = inmation.sethistory(inmation.getpropertyid("System/Core/Obj", "ItemValue"), 20, 0, 1461051211899)

sethistoryex

inmation.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

string

no

Path to, or object of an HDA Datasource (objspec).

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 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

inmation.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
)

setreferences

inmation.setreferences(objspec, refs)

Description

Creates or modifies the references of an inmation 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 inmation 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

inmation.setreferences(inmation.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:

inmation.setreferences(inmation.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:

inmation.setreferences("/System", {
    {
        path = "so",
        type = (inmation.model.codes.ReferenceType.SECURITY | inmation.model.flags.SecurityAttributes.INHERITABLE | inmation.model.flags.SecurityAttributes.READ)
    }
})

This sets a security reference to the "so" profile on the System object

setscopeparameters

inmation.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"}
inmation.setscopeparameters(settings)

inmation.disableobject("/System/Core/object_1")

The new scope-settings will be applied to all subsequent calls within the current Lua instance.

setvalue

inmation.setvalue(pathspec, value, [quality], [timestamp])

Return Type

none

Description

Short name: inmation.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 inmation.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.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec

variant

no

Object’s path, the inmation object itself, the object ID 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").

timestamp

userdata

yes

The timestamp 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

Examples

inmation.setvalue("Ref1", 10) -- sets the value of the referenced object
inmation.setvalue("/System/Core/Connector/Datasource/IoNode/Ioitem", 150) -- sets the value (the dynamic property) of the Ioitem
inmation.setvalue("RefItem.Location.Longitude", 6.9363280000) -- sets the value of the specified property
inmation.setvalue("Path/UnknownTagName.WrongPropertyName", true) -- shows error message

In the following tree structure : System

-localhost

-folder1

script

-folder2

holder2

For the script to access holder2 via a relative path:

inmation.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 inmation.

inmation.setvalue("Ref1", nil) -- sets the value of the referenced object to nil inmation.setvalue("RefItem.Location.Longitude", nil) -- sets the value of the specified property to nil

In system:inmation v1.20 and later, nullable values can also be written as arrays or as null value elements in an array.

inmation.setvalue("/System/Core/Data Holder 1", {nil}) -- Sets the value of the object as an array containing one element with a null value
inmation.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" ] }} ]]
inmation.setvalue("/System/Core/Table Holder.TableData", tab)

sleep

inmation.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()
inmation.sleep(42) -- sleep for 42 milliseconds
return now() - a

splitpath

inmation.splitpath(path)

Return Type

string

Description

Short name: inmation.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 this document.

Component Execution

All Components

Examples

local parent, child = inmation.splitpath("/a/b/c") -- parent = "/a/b", child = "c"
local parent, child = inmation.splitpath("^/a/b/c^/d^^e") -- parent = "/a/b", child = "c/d^e"

tear

inmation.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 inmation 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

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:

inmation.buffer(obj, "buff", ".ItemValue", 60000, 6)

Now assume inmation.tear is called after at least one minute:

local values, qualities, timestamps, count = inmation.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

inmation.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 = inmation.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

inmation.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 = inmation.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 = inmation.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

uaread

inmation.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 = inmation.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
  }
]

utf8toascii

inmation.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

inmation.utf8toascii("Brühl")

uuid

inmation.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 = inmation.uuid()

-- returns two version 1 UUIDs -- {"2f0bce8f-384d-11e9-85ad-448a5b5cb56b","2f0bce90-384d-11e9-85ad-448a5b5cb56b"}, 1, 1, 0
inmation.uuid(2)

-- returns two version 4 UUIDs -- {"11c6c9d8-1089-46a3-8933-f361f45d6289","711d7bfd-863d-4db1-a9fa-d39eb5074723"}, 4, 1, 0
inmation.uuid(2, 4)

-- returns a single version 4 UUID -- "11c6c9d8-1089-46a3-8933-f361f45d6289", 4, 1, 0
inmation.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
inmation.uuid(nil, { secure_mac = true })