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(pathspec, 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(pathspec, name) - Removes a repeater from the buffer with the specified name at the specified object or path.

  • inmation.attach(pathspec, 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

pathspec

variant

no

Object’s path, or the inmation object itself, object or property 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(pathspec, 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

pathspec

variant

no

Object’s path, or the inmation object itself, object or property 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(pathspec, name) - Removes the buffer with the specified name from the specified object.

  2. inmation.buffer(pathspec, 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(pathspec, 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)
  1. inmation.buffer(pathspec, 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 pathspec or table of pathspec 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 pathspec or table of pathspec 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.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.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.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

string

no

Can be either a string, representing the parent’s path, or an inmation object representing the parent object itself.

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

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_delay 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(pathspec)

Description

Short name: inmation.del

Deletes an inmation object.

Component Execution

Core only

Parameters

Name Type Optional Description

pathspec

variant

no

Object’s path, or the inmation object itself, object or property 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(pathspec)

Description

Short name: inmation.dis

Disables an inmation object.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec

variant

no

Object’s path, or the inmation object itself, object or property 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(pathspec)

Description

Short name: inmation.ena

Enables an inmation object.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec

variant

no

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

Error Messages

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

Examples

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

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"

getconnectorpath

inmation.getconnectorpath(pathspec)

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

pathspec

variant

yes

Object’s path, or the inmation object itself, object or property 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(pathspec)

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

pathspec

variant

yes

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

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

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 Datasurce object.

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(pathspec)

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

pathspec

variant

no

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

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.

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([storecode], [testarchive])

Return Type

userdata

Description

Takes the numerical code for a MongoDB data store and returns a lua-mongo 'client' which represents a connection to the data store. As of now, the function only works for the Custom Data Store and if no argument is passed, the custom data store is assumed.

Component Execution

All 64-bit components

Parameters

Name Type Optional Description

storecode

number

yes

A numerical code which represents a MongoDB data store, defaults to the code for Custom Data Store.

testarchive

boolean

yes

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

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

getmongoconnectionstring

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

Return Type

string

Description

Takes 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 custom data store is assumed.

Component Execution

All 64-bit components

Parameters

Name Type Optional Description

storecode

number

yes

A numerical code which represents a MongoDB data store, defaults to the code for Custom Data Store

testarchive

boolean

yes

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

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 }

getobject

inmation.getobject(pathspec)

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

pathspec

variant

no

Object’s path, or the inmation object itself, object or property 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(pathspec)

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

pathspec

variant

no

Object’s path, or the inmation object itself, object or property 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(pathspec, [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

pathspec

variant

no

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

bounds

boolean

no

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

time_start

number

no

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

time_end

number

no

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

max_limit

number

yes

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

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([pathspec])

Return Type

table

Description

Short name: inmation.refs

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

pathspec

variant

yes

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

getrelaypaths

inmation.getrelaypaths(pathspec)

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

pathspec

variant

no

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

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(pathspec)

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

pathspec

variant

no

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

userdata

Description

Short name: inmation.get

This function gets the value, quality and timestamp of an item or of a referenced item. If a property path is included, the function returns the value of the property only.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec

variant

no

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

Error Messages

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

Examples

local x0 = 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.

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(pathspec, 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 (pathspec).

Parameters

Name Type Optional Description

pathspec

variant

no

Object’s path, or the inmation object itself, object or property 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([pathspec])

Return Type

table

Description

Lists the buffers set up for the object specified by pathspec, 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

pathspec

variant

yes

Object’s path, or the inmation object itself, object or property 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(pathspec, ref)

Description

Short name: inmation.linkpv

Sets the ProcessValueLink property of a KPI object (for example, a GenKPI) 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 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

pathspec

variant

no

Object’s path, or the inmation object itself, object or property 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([pathspec], [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

pathspec

variant

yes

Object’s path, or the inmation object itself, object or property 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) the configuration version of the inmation object; numerical value; default value: 0

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

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.

moveobject

inmation.moveobject(pathspec, 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

pathspec

variant

no

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

peek

inmation.peek(pathspec, name)

Return Type

variant

Description

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

Parameters

Name Type Optional Description

pathspec

variant

no

The path to or the inmation object itself having a buffer attached to it.

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

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.

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(pathspec, 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

pathspec

variant

no

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

setvalue

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

Return Type

userdata

Description

Short name: inmation.set

This method sets the value of a property of a specified Item or referenced Item. When using inmation.setvalue() to write to IO-Items of an OPC Datasource, the OPC write parameters are defined according to the following table.

Component Execution

All Components

Parameters

Name Type Optional Description

pathspec

variant

no

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

value

userdata

no

The new value to be set.

quality

userdata

yes

The quality of the value. By default, it is 0 (equivalent to "good").

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)

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(pathspec, 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

pathspec

variant

no

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

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