topcua
Not logged in

opcua command

Name

opcua - Tcl binding to the OPC/UA implementation of http://www.open62541.org

Synopsis

package require topcua
opcua cmd ?arg?

Description

This command provides several operations to manage and communicate using the OPC/UA implementation of http://www.open62541.org. It is available on common POSIX and Windows platforms. cmd indicates which operation to carry out. Any unique abbreviation for cmd is acceptable. The valid commands are:

opcua acl handle ?user pass ...?

Modifies the user/password based access control list of the server object handle. This command must be called after the server object has been created (see opcua new server) and before it is put into operation (see opcua start). To allow anonymous logins, specify an empty username in the arguments, whose password will be ignored.

opcua add handle DataType nodeid parent reftype brname ?attrs?

Adds an new node of node class DataType in the object handle and returns the node identifer. The parameter nodeid is the requested new node identifier of the node to be created. parent is the parent node identifier and reftype the reference type or node identifier of the reference between the parent and the new node. brname is the browse name (see section Qualified Names) of the new node. The optional attrs parameter specifies attributes for the new node in form of a dictionary (see opcua attr default). If it is omitted, default values are used. The DisplayName attribute if left empty is preset to the name part of the browse name parameter.

opcua add handle Method|SimpleMethod nodeid parent reftype outargs brname inargs cmd ?attrs?

Adds an new node of node class Method in the object handle and returns the node identifer. In the SimpleMethod command form the parameter outargs describes the output arguments of the method as a list of zero or more pairs of data type and argument names. To force an argument to be a scalar, the argument name must be prefixed with an exclamation mark. To force an argument to be an array, the argument name must be prefixed with an asterisk. Likewise, inargs describes the input arguments of the method with identical prefix rules. In the Method command form, both outargs and inargs must be provided as lists of dicts with the template obtained from opcua types empty Argument. The parameter cmd is the Tcl callback to handle the method invocation, see section Method Callbacks for more information. For the other parameters, refer to opcua add DataType.

opcua add handle Namespace name

Adds the new namespace name to the server object handle and returns a numeric identifier for this namespace.

opcua add handle Object nodeid parent reftype brname ?typeid attrs?

Adds an new node of node class Object in the object handle and returns the node identifer. The optional parameter typeid must be a known data type name (see opcua types) or a node identifier of a data type. For the other parameters, refer to opcua add DataType.

opcua add handle ObjectType nodeid parent reftype brname ?attrs?

Adds an new node of node class ObjectType in the object handle and returns the node identifer. For the other parameters, refer to opcua add DataType.

opcua add handle Reference srcid reftype target ?forward?

Adds a reference of type reftype (see opcua reftype) between the node identifiers srcid and <target on the object handle. The optional parameter forward must be a boolean indicating the direction of the reference (true, the default, is forward, false is inverse).

opcua add handle ReferenceType nodeid parent reftype brname ?attrs?

Adds an new node of node class ReferenceType in the object handle and returns the node identifer. For the other parameters, refer to opcua add DataType.

opcua add handle Variable nodeid parent reftype brname ?typeid attrs cmd?

Adds an new node of node class Variable in the object handle and returns the node identifer. The optional parameter typeid must be a known data type name (see opcua types) or a node identifier of a data type or an empty string for a default value. Parameter cmd is an optional data source callback which produces (read operation) or consumes (write operation) the variable's value. See section Data Source Callbacks for more information. For the other parameters, refer to opcua add DataType.

opcua add handle VariableType nodeid parent reftype brname ?typeid attrs?

Adds an new node of node class VariableType in the object handle and returns the node identifer. The optional parameter typeid must be a known data type name (see opcua types) or a node identifier of a data type or an empty string for a default value. For the other parameters, refer to opcua add DataType.

opcua add handle View nodeid parent reftype brname ?attrs?

Adds an new node of node class View in the object handle and returns the node identifer. For the other parameters, refer to opcua add DataType.

opcua appdesc handle ?description?

Queries or sets the application description of the object handle. For a query, the current application description is returned as a a dictionary. This dictionary can be used as basis for modification and further to set a new application description. The set operation can be performed only on stopped server objects and unconnected client objects. Note, that the ApplicationUri component of the application description must match the corresponding information in certificates.

opcua attrs ?list|default|numeric? ?name?

Without further parameters returns a list of attribute names the opcua read and opcua write commands support, e.g. Value, NodeClass, etc. With the list keyword a list of the data types used as attributes for creation of nodes with the opcua add command is returned. With the default keyword combined with the name of the data type a dictionary describing the default attributes of this type is returned, e.g opcua attrs default DataTypeAttributes yields a default dictionary for creation of a DataType node. With the numeric keyword combined with the name of the data type, the numeric value of the attribute is returned.

opcua attr_init name body ...

Helper function to create and return a dictionary for the attribute type name which is initially filled with defaults from opcua attrs default... and finally modified by the Tcl code in body with the same rules as in the dict with command. The parameters following body are assigned to the list args as in a proc. In contrast to dict with, body is executed in a call frame of its own.

opcua browse handle nodeid ?dir reftype mask ...?

Performs a browse operation on the client or server object handle starting at the node nodeid. The browse direction can be specified with the dir parameter as Forward, Inverse, or Both. Forward is the default direction. The optional reftype parameter selects the types of references to be considered. References can be preceeded with an exclamation mark in order to reverse their direction. A reference may be abbreviated as slash for HierarchicalReferences or as dot for Aggregates. If reftype is not specified, all nodes referenced to/from nodeid are reported. The optional mask and following parameters select specific node classes Object, Variable, Method, ObjectType, VariableType, ReferenceType, DataType, and View. The result of the browse operation is a list where each item is made up of the six elements node identifier, browse name (qualified name), display name (locale and text), node class, reference node identifier, and type node identifier.

opcua call handle nodeid methodid ?type value ...? ?-async cmd?

Calls the method with node identifier methodid on the object with node identifier nodeid on the client or server object handle with parameters described by pairs of type (data type, e.g. Int32 or String) and value (the parameter's value). The method's result is returned. The method is carried out on the server, i.e. when directly used with a server handle there's no network traffic since the method is run locally. The type parameters should be prefixed with an asterisk or an exclamation mark in order to achieve the same semantic as in a method definition with opcua add SimpleMethod. Otherwise, array vs. scalar interpretion is automatically performed, i.e. when the corresponding value is a list, it is used as an array. For client objects, asynchronous operation is carried out when the last two parameters are -async and a (possibly empty) callback command cmd. In case of a non-empty callback the command returns an integer request identifier, which can be used to cancel the asynchronous operation. Otherwise the call is performed but the result is ignored. See section Asynchronous Operations for more information.

opcua cancel handle reqid ...

Cancels one or more asynchronous requests on the client object handle. The requests to be cancelled are identified by their integer identifiers reqid. The associated callbacks are evaluated with a timeout status code.

opcua cert handle cert pkey ?trust ...?

Loads the certificate cert and private key pkey into the client or server object handle. Both must be byte arrays. The optional parameters trust are zero or more byte arrays with certificates which are added to the object's trust list. If the underlying open62541 library does not support encryption, this command fails with an appropriate error message. If it succeeds, it forces a server object to only allow encrypted sessions. Similarly, a client object tries to use a sign-and-encrypt endpoint of a server. However, an exception is an empty certificate as part of the trust list (an empty byte array). This allows for unencrypted sessions.

opcua children handle nodeid

Returns the child node identifiers of the given node identifier nodeid on the client or server object handle.

opcua connect handle url ?user password?

Connects the client object handle to the URL url using the optional credentials user and password.

opcua connect handle url -async

Connects the client object handle to the URL url. The operation is asynchronous, i.e. the connection establishment takes place in background. It can be observed with the optional onclientstate callback of the client object.

opcua const ?name ...?

Without optional parameters returns a list of names for which mappings to numerical values are known. If name is provided, the numerical value for the name is returned. When more than one name is given, a bitwise OR of the values for the names is returned. name can be optionally prefixed with UA_, i.e. ACCESSLEVELMASK_READ and UA_ACCESSLEVELMASK_READ are mapped to the same numerical value.

opcua createcert fmt subjects subjectaltnames ?bits?

Creates a self signed certificate and private key given format fmt (der or pem), a list of subjects, a list of subjectaltnames, and optional bits. If bits is omitted a reasonable default is selected. The result is a two element list made up of a byte array with the certificate and a byte array with the private key.

opcua datasources handle ?nodeid? ?cmd?

Returns or modifies information on data sources (Variable nodes with callbacks) for the server object handle. Without optional parameters for each known data source two list elements with node identifier and callback command are added to the result. With nodeid information for the specified node is returned. With cmd the Tcl callback is changed. If cmd is given as an empty list, that callback is deleted and the variable node will return to normal (non-datasource driven) behaviour.

opcua datetime ?seconds|...|utc ?value??

Returns either POSIX or OPC/UA timestamps as Tcl_WideInt values. If called without further parameters the current OPC/UA local DateTime is returned. If called with the single keyword utc the current OPC/UA UtcTime is returned. Otherwise, value is required and converted from POSIX to OPC/UA UtcTime for the keywords seconds, milliseconds, and microseconds, and from OPC/UA UtcTime to POSIX for the keywords unixseconds, unixmillis, and unixmicros, respectively. For the keyword string the value given is returned as an ISO 8601 formatted string with local time offset, for utcstring as an ISO 8601 formatted string in UTC. For the keyword scan the value given is parsed as an ISO 8601 or RFC 3339 time string and converted to an OPC/UA timestamp as Tcl_WideInt value.

opcua decode ?handle? type bytes

Performs deserialization of the byte array bytes as data type type, which can be a type name or node identifier. Optionally, handle is used for type lookup. By default, if the type is ExtensionObject, an additional decoding step is performed to deserialize the content of that object. This can be turned off if the type is prefixed with a caret.

opcua deftypes handle nsuri defs

Defines custom datatypes (structures with and without optional fields, unions, and simple enumerations) in the server object handle and namespace URI nsuri. The namespace is created with the opcua add Namespace command and must exist before the opcua deftypes command is called. The parameter defs describes the structures and enumerations to be created. The command does all necessary steps to create the required nodes in the server object's address space and to store an XML bytestring describing the (de)serialization for the structures as extension objects. That XML is later to be reparsed with the opcua gentypes command. For details refer to section Defining Custom Data Structures below.

opcua delete handle Node nodeid ?withrefs?

Deletes the node with identifier nodeid on the server object handle. If withrefs is true, the references of the node are deleted, too.

opcua delete handle Reference srcid reftypeid targetid ?forward? ?bidir?

Deletes the reference described by srcid, reftypeid, and targetid on the server object handle. The boolean flag forward selects forward or inverse direction of the reference to be deleted. The boolean flag bidir requests a bidirectional reference to be deleted. The default is to delete in forward direction only.

opcua destroy handle

Destroys the client or server object handle and releases its resources, e.g. closes network connections, tears down the handle specific namespace, etc.

opcua dict_init name body ...

Helper function to create and return a dictionary for the data type name which first is primed with opcua types empty... and finally modified by the Tcl code in body with the same rules as in the dict with command. The parameters following body are assigned to the list args as in a proc. In contrast to dict with, body is executed in a call frame of its own.

opcua disconnect handle ?-async?

Disconnects the client object handle. If the optional parameter -async is specified, the operation is carried out in asynchronous mode.

opcua encode ?handle? type data

Performs serialization of data as data type type, which can be a type name or node identifier. Optionally, handle is used for type lookup. By default, the resulting byte array is wrapped in an ExtensionObject.This can be turned off if the type is prefixed with a caret.

opcua endpoints ?url?

Queries the local OPC/UA server opc.tcp://localhost:4840 or the server specified by the url parameter for endpoints and returns a list of URLs describing the endpoints found.

opcua event handle create nodeid

Creates an event node on the server object handle. The node identifer nodeid must be an event object type. The node identifier of the newly created event is returned. This can be used in opcua property commands to add information to the event, and in further opcua event commands to trigger it, i.e. send it out.

opcua event handle oneshot eventid originid

Sends the event node eventid on the server object handle with its origin set to node identifier originid. The event node is automatically deleted after this operation.

opcua event handle trigger eventid originid

Similar to opcua event oneshot but the event node is kept and can be sent again later.

opcua fromjson ?handle? type json

This is an optional command which is available when the open62541 library is compiled with JSON support. The JSON string json is converted to an equivalent Tcl serialization (dictionaries, lists) according to the datatype type. The type is looked up globally and optionally in the type information available for the client or server object handle. The serialized value is returned as result of the command.

opcua genstubs handle ?strip stubsts ...?

Generates stubs for methods in the handle specific address space derived from the client or server object handle. The address space is traversed and browse paths and node class paths are accumulated. The resulting browse paths optionally get the prefix strip stripped off from the beginning and optionally filtered using the glob patterns following the strip parameter. If substs is not empty it specifies pairwise regexps and substitutions which are applied on the browse paths for the final procedure names. For all nodes matching the node class path pattern Object/Method the optional InputArguments and OutputArguments child nodes are retrieved and stub procedures are written using the browse path and argument information.

opcua gentypes handle ?uri xml ...?

Generates custom data type mappings using information obtained from analyzing the address space derived from the client or server object handle. This feature is highly experimental and requires the tDOM package for parsing XML. It can create encoders/decoders for simple structure data types defined in the address space which perform a mapping from/to Tcl dictionaries. If the type information is to be provided directly, the optional parameters uri and xml are pairs of URI identifying a namespace and XML formatted type descriptions. The URIs are matched against the namespace array obtained from the address space of handle. For further information, see the server_types.tcl and client_types.tcl scripts in the examples directory. If this command is used, it should be invoked prior to creating method stubs, since methods may require custom data types in their arguments.

opcua guidgen ?nsindex|seed number?

Generates a random GUID. If nsindex is specified, a node identifier in namespace nsindex with a random GUID is produced. If the keyword seed is used, the random generator is primed with current time or the optionally specified number.

opcua history handle delete nodeid start end

Deletes historic data given client handle, node identifier nodeid, and time range start and end, which must be given as OPC/UA UtcTime timestamps.

opcua history handle insert|replace|update nodeid value

Inserts, replaces, or updates a OPC/UA DataValue value given client handle and node identifier nodeid. The timestamps of the DataValue are used to select the place for the insert operation or the value to be changed, respectively.

opcua history handle read nodeid start end ?numvals timestamps bounds range?

Reads historic data given client handle and node identifier nodeid. The parameters start and end give the time range of interest as OPC/UA UtcTime timestamps. The numvals parameter limits the number of items returned. With timestamps the timestamps to be returned in the result are specified. With the boolean bounds the treatment of the upper and lower boundary of the selected set can be included or excluded. The range parameter must be an empty string or a valid OPC/UA index range further filtering the result set. The result is a list made up of the Tcl representation of OPC/UA DataValues.

opcua info ?handle?

Returns the object type of handle, either client or server. If handle is omitted, a list of all known client and server object handles is returned.

opcua limits handle ?name?

Returns operation limits like MaxNodesPerRead or MaxNodesPerBrowse for the client or server handle. If name is specified that limit is returned. For both a client and server handle this involves a read operation of a variable's Value attribute below Root/Objects/Server/ServerCapabilities/OperationLimits when the limit isn't known yet. The value read is then cached for later re-use. If name is omitted a list with all limits suitable for array set is returned. In a client, limits whose values are still unknown are reported as zero. In a server the cache is filled immediately.

opcua loader handle xml ?evar rvar tvar?

Imports a node set from an XML string xml into the server handle. The amount of imported information highly depends on the build options of the underlying open62541 library. Node descriptions which can't be supported are ignored and internally accumulated. For analysis, that information is made available by the evar, rvar, and tvar result variables, which receive a list in array set form with each key being the node identifier and each value a dictionary with node information (for evar) including an error description, and reference information (for rvar), and typedef information (for tvar). A result is returned which is a list in array set form with each key being the method's implementation proc name and each value a list of node identifiers which will invoke the respective implementation.

opcua log ?command?

Retrieves or sets the callback command for open62541 log messages. When a log message is issued, command is invoked with three parameters appended: the log level, e.g. info, warning, the category, e.g. network, client, and the text of the log message.

opcua mapstruct handle ?nodeid destid members ...?

Adds variable nodes with an internal data source mapping to the members of the structure identified by nodeid in the server handle. It allows clients to read the structure element wise even when there's no client support for deserialization of the whole structure. Alternatively, if pairs of destid and members are provided, no additional variable nodes are created but the mapping is established between the variable identified by destid and the structure field members of structure nodeid. If nodeid and following parameters are left out, the current mappings are returned as a list where each three elements are made up of destination node identifier, structure node identifier, and structure member name. Warning: no logic is built in to prevent from creating multiple mappings, when variable nodes are to be added. Thus, the user should ensure in this case to call the mapstruct subcommand only once per nodeid. Since a node only supports a single data source, an error is raised when a node already has a callback installed from the add or datasources subcommand.

opcua mbrowse handle {nodeid ?dir reftype mask?} ...

Performs a multi browse operation on the client or server object handle similar to opcua browse, think of a parallel version useful to reduce network latency. The nodes, browse directions and further constraints are specified in separate lists. The result is a list for each input list of arguments made up of the six elements described in opcua browse.

opcua methods handle ?nodeid outtype cmd

Returns information on methods for the server object handle. Without optional parameters, for each known method three list elements with node identifier, result type information, and callback command are added to the result. With nodeid information for the specified node is returned. With outtype which must be a list of dicts of serialized Argument structs the method's mapping of result values is modified. With cmd, the Tcl callback is changed. If cmd is given as an empty list, that callback is deleted and the method node will report an error upon call from the OPC/UA side.

opcua methods handle -async|-sync nodeid

Sets the execution mode for the method identified by nodeid in the server object handle to asynchronous or synchronous. In both cases, an event loop must operate. For asynchronous execution the OPC/UA server thread does not block for the method execution but maintains an internal work queue coordinating the information flow. This queue is checked 10 times per second for completed operations, i.e. the minimum durations of a complete asynchronous method is thus about 100 milliseconds. The default execution mode is synchronous. For further information refer to the description of opcua postpone and opcua result.

opcua methods handle -isasync nodeid

Returns the current execution mode of the method identified by nodeid in the server object handle. The result is non-zero when the method will be executed asynchronously.

opcua monitor handle configure 0 monid ?cmd?

Configures the monitor monid on the server object handle with the provided parameters, see opcua monitor new for further information.

opcua monitor handle configure subid monid ?cmd mode interval?

Configures the monitor monid in subscription subid on the client object handle with the provided parameters, see opcua monitor new for further information.

opcua monitor handle destroy subid monid

Destroys the monitor monid in subscription subid on the object handle and releases all its resources. If handle is a server object, subid must be specified as zero.

opcua monitor handle info subid ?monid?

Returns information on monitor monid in subscription subid on the handle. If handle is a server object, subid must be specified as zero. The result is a list of monitor type (data or event) when handle refers to a client object (otherwise the list element is left out), the node identifier, the callback command, the attribute, the monitor's mode (only for client handles), and the interval. If monid is omitted, a list of all monitor identifers registered in the subscription or in the server object is returned.

opcua monitor handle new 0 cmd nodeid ?attr interval?

Creates a monitored item of the data value for the node identifier nodeid on the server object handle. The optional parameter attr selects the attribute of the node to be monitored (Value is the default). The monitoring interval interval must be given as number of milliseconds. The callback command parameter cmd is discussed in section Monitor Callbacks below. The command returns a numeric identifier of the newly created monitor.

opcua monitor handle new subid type cmd nodeid ?filter attr mode interval?

Creates a monitored item of type (data or event) for the node identifier nodeid in the subscription subid on the client object handle. The parameter filter must be specified for event monitors as a list made up of type identifiers, qualified names, and attributes, e.g. {BaseEventType Message Value ...}, where BaseEventType must be given as node identifier by look up per opcua translate. For data monitors, filter must be a list of data change trigger type, deadband type, and deadband value. If left empty, reasonable defaults are selected. The optional parameter attr selects the attribute of the node to be monitored (Value is the default for data monitors, EventNotifier for event monitors). The monitor mode mode must be one of Disabled, Sampling, and Reporting. The monitoring interval interval must be given as number of milliseconds, if omitted its value is derived from the subscription. The callback command parameter cmd is discussed in section Monitor Callbacks below. The command returns a numeric identifier of the newly created monitor.

opcua monitor handle triggering subid monid addids rmids

Sets triggering information for the subscription subid on the client object handle. The other parameters provide the monitor monid which additionally shall trigger the monitor identifiers in the list addids and shall not trigger the monitor identifiers in the list rmids anymore. All given monitor identifiers must have been created in the subscription subid. This allows for depending monitored items in addids to have Sampling mode instead of Reporting mode in order to be sent to the client whenever a change was detected and monid was triggered.

opcua mread handle cmd nodeid ...

Similar to opcua read this command carries out a multi read operation of value attributes on nodeid and following node identifiers. If cmd is given as empty string, the operation is synchronous and a list of value attributes is returned. For asynchronous operation see opcua call and section Aynchronous Operations.

opcua mreadx handle cmd nodeid attr index ...

Similar to opcua mread this command carries out a multi read operation of attribute attr with index on nodeid and following parameters. Each single read is described by note identifier, attribute, and index. The index parameter must be an empty string or a valid OPC/UA index range. If cmd is given as empty string, the operation is synchronous and status codes and values for all attributes are returned as a list. For asynchronous operation see opcua call and section Aynchronous Operations.

opcua mtranslate handle {nodeid reftype target ..} ...

Performs a multi translate operation on the client or server object handle similar to opcua translate, think of a parallel version useful to reduce network latency. The nodes, reference types and targets are specified in separate lists. The result is a list for each input list of arguments made up of the three elements described in opcua translate.

opcua mwrite handle cmd nodeid type value ...

Similar to opcua write this command carries out a multi write operation of value attributes on nodeid and following node identifiers. Each single write is described by node identifier, data type, and value. If cmd is given as empty string, the operation is synchronous. For asynchronous operation see opcua call and section Asynchronous Operations. In contrast to the opcua write command this operation transfers all values with their source timestamp set to the current time.

opcua mwritex handle cmd nodeid attr index type value ...

Similar to opcua mwrite this command carries out a multi write operation of attribute attr with index on nodeid given type and value. Each single write is described by note identifier, attribute, index, data type and value. The index parameter must be an empty string or a valid OPC/UA index range. If cmd is given as empty string, the operation is synchronous. The result is a list of status codes for each attribute given. For asynchronous operation see opcua call and section Aynchronous Operations. In contrast to the opcua write command this operation transfers all values with their source timestamp set to the current time.

opcua namespace handle ?uri?

Returns the namespace index for the namespace uri of the client or server object handle (or throws an error e.g. when the namespace doesn't exist). If uri is omitted, a list of all known namespace indices and corresponding URIs is returned.

opcua new ?client? ?name?
opcua new server port name

Creates a new client or server object and returns its handle. The port parameter must be present for server objects and specifies the server's TCP port. The optional name is the object name (the handle). If no parameters are given to opcua new a client object with an automatic name is created. During that process the Tcl namespace ::opcua::name is created which later is used to hold method stub procedures and other information. That namespace is tied to the life time of the client or server object. The initial access control list of a server object is empty.

opcua onclientstate handle ?cmd?

Returns or sets the callback for client connection state changes for the client object handle. The parameter cmd is the Tcl callback to receive connection state information; it is invoked with three added parameters: 1. the connection state as numeric OPC/UA status code, 2. the secure channel state as a string, and 3. the session state as a string. Possible secure channel states are closed, hel_sent, hel_received, ack_sent, ack_received, opn_sent, open, and closing. Possible session states are closed, create_requested, created, activate_requested, activated, and closing.

opcua onfinalize handle ?typeid? ?cmd?

Returns or sets the callback for node finalization events on the server object handle. The parameter cmd is the Tcl callback to handle the finalization event; it is invoked when a node in the server's address space is deleted with one additional parameter which is the node identifier of the node being deleted. cmd must have proper list format. If specified as an empty list, no callback on node finalization is carried out. If typeid is specified it must be the node identifier of an ObjectType or a VariableType. In this case, the callback is invoked when an Object or Variable node of this type is to be deleted. The callback gets two additional parameters which are the node identifiers of the deleted node and its respective type. If both, typeid and cmd parameters are omitted, a list of all finalizer callbacks is returned with the odd elements being the type node identifiers (empty element for global finalizer) and the even elements the respective callback commands.

opcua oninitialize handle ?cmd?

Returns or sets the callback for node initialization events on the server object handle. The parameter cmd is the Tcl callback to handle the initialization event; it is invoked when a new node is added in the server's address space with two additional parameter which are the node identifier of the new node and its node class. Cmd must have proper list format. If specified as an empty list, no callback on node initialization is carried out. If typeid is specified it must be the node identifier of an ObjectType or a VariableType. In this case, the callback is invoked when an Object or Variable node of this type is created. The callback gets two additional parameters which are the node identifiers of the new node and its respective type. If both, typeid and cmd parameters are omitted, a list of all initializer callbacks is returned with the odd elements being the type node identifiers (empty element for global initializer) and the even elements the respective callback commands.

opcua parent handle nodeid

Returns the parent node identifier of the given node identifier nodeid on the client or server object handle.

opcua permissions handle user namespaceindex ?permission ...?

Queries or modifies the user/namespace specific permissions for the server object handle. user specifies the user name from the access control list (see opcua acl) or an empty string for anonymous logins. namespaceindex is the namespace of interest in the range 0 to 31 or for changing permissions all to deal with all 32 namespaces at once. Namespace numbers out of range are treated like namespace zero. If no further arguments are provided, the list of permissions for that user and namespaceindex is returned. Each granted permission is indicated with a leading plus character, each revoked permission with a leading minus character, e.g. +ACCESSLEVELMASK_READ and -ACCESSLEVELMASK_WRITE. If at least one permission argument is specified, the same logic as for a query is used, i.e. a leading plus (minus) character grants (revokes) the respective following permission. Valid permissions are ACCESSLEVELMASK_READ, ACCESSLEVELMASK_WRITE, ACCESSLEVELMASK_HISTORYREAD, ACCESSLEVELMASK_HISTORYWRITE, ACCESSLEVELMASK_SEMANTICCHANGE, ACCESSLEVELMASK_STATUSWRITE, ACCESSLEVELMASK_TIMESTAMPWRITE, EXECUTABLE, EXECUTABLE_ON_OBJECT, WRITEMASK_ACCESSLEVEL, WRITEMASK_ARRAYDIMENSIONS, WRITEMASK_BROWSENAME, WRITEMASK_CONTAINSNOLOOPS, WRITEMASK_DATATYPE, WRITEMASK_DESCRIPTION, WRITEMASK_DISPLAYNAME, WRITEMASK_EVENTNOTIFIER, WRITEMASK_EXECUTABLE, WRITEMASK_HISTORIZING, WRITEMASK_INVERSENAME, WRITEMASK_ISABSTRACT, WRITEMASK_MINIMUMSAMPLINGINTERVAL, WRITEMASK_NODECLASS, WRITEMASK_NODEID, WRITEMASK_SYMMETRIC, WRITEMASK_USERACCESSLEVEL, WRITEMASK_USEREXECUTABLE, WRITEMASK_USERWRITEMASK, WRITEMASK_VALUERANK, WRITEMASK_WRITEMASK, WRITEMASK_VALUEFORVARIABLETYPE, WRITEMASK_USERACCESSLEVEL, ADD_NODE, ADD_REFERENCE, DELETE_NODE, DELETE_REFERENCE, BROWSE_NODE, HISTORY_UPDATE_DATA, HISTORY_DELETE_RAW_DATA. The permission string may be optionally prefixed with UA_ in order to provide names as in the open62541.h header file. The special permission names ACCESSLEVELMASK_ALL and WRITEMASK_ALL are not reported in a query but can be used as a shortcut to turn all respective permissions on or off.

opcua postpone

When invoked in a method context (method callback) and that method is marked as asynchronous (see opcua methods -async) arranges for the callback's result to be delivered at a later point in time. In this case the command returns a handle which is used later in opcua result to send the response to the caller. In all other cases this command returns an empty string.

opcua pread ...

See section Prepared Read And Write Operations.

opcua property handle read nodeid name

Reads the property name from node identifier nodeid on the server object handle.

opcua property handle write nodeid name type value

Writes value of data type type to the property name of the node identifier nodeid on the server object handle.

opcua ptree handle ?nodeid? ?mask?

Returns information similar to opcua tree using the client or server object handle. The address space is traversed starting at the node identifier nodeid (the root node if omitted). The result list is made up of browse path name, node identifier, node class path, reference node identier, type node identifier, and parent node identifier. With mask the node kinds to be considered can be specified, if omitted all nodes are reported. The browse path name is a path name like notation made up of the browse names pointing to the final node as seen from the starting node. Browse names are written as qualified names, i.e. including the numeric namespace index if not in root namespace. Similarly, the node class path is a path name like notation made up of the node classes of all nodes along the path. The opcua ptree command is used internally by the opcua genstubs command in order to filter out objects and methods when creating stub Tcl commands to invoke methods on objects.

opcua pubsub handle AddConnection config

Adds a new PubSubConnection with the parameters from config, which must be a dictionary of type PubSubConnectionDataType. The operation is carried out on the server given the client or server object handle. The node identifier of the new PubSubConnection is returned.

opcua pubsub handle AddDataSetFolder name

Adds a new DataSetFolder object with name name in the server given the client or server object handle. The operation is carried out on the server given the client or server object handle. The node identifier of the new DataSetFolder is returned.

opcua pubsub handle AddDataSetReader groupId readerData

Adds a new DataSetReader object with information from readerData which must be a dictionary of type DataSetReaderDataType on the ReaderGroup with node identifier groupId. The operation is carried out on the server given the client or server object handle. The node identifier of the new DataSetReader is returned.

opcua pubsub handle AddDataSetWriter groupId writerData

Adds a new DataSetWriter object with information from writerData which must be a dictionary of type DataSetWriterDataType on the WriterGroup with node identifier groupId. The operation is carried out on the server given the client or server object handle. The node identifier of the new DataSetWriter is returned.

opcua pubsub handle AddPublishedDataItems name aliases flags vars

Adds a new PublishedDataSet with name name and the information contained in the three parameters aliases (list of String type), flags (list of UInt16 type), and vars (list of PublishedVariableDataType). The three lists must have the same number of elements. The operation is carried out on the server given the client or server object handle. The node identifier of the new PublishedDataSet is returned.

opcua pubsub handle AddReaderGroup connId readerGroupData

Adds a new ReaderGroup object with information from readerGroupData which must be a dictionary of type ReaderGroupDataType on the PubSubConnection with node identifier connId. The operation is carried out on the server given the client or server object handle. The node identifier of the new ReaderGroup is returned.

opcua pubsub handle AddWriterGroup connId writerGroupData

Adds a new WriterGroup object with information from writerGroupData which must be a dictionary of type WriterGroupDataType on the PubSubConnection with node identifier connId. The operation is carried out on the server given the client or server object handle. The node identifier of the new WriterGroup is returned.

opcua pubsub handle DeletePubSubConfiguration

Removes all currently configured PubSub components (PubSubConnections, ReaderGroups, WriterGroups, PublishedDataSets, DataSetReaders, and DataSetWriters) in the server given the client or server object handle.

opcua pubsub handle LoadPubSubConfigurationFile bytes

This subcommand is identical to opcua pubsubcfg load but can be invoked from a client object handle, too.

opcua pubsub handle RemoveConnection connId

Removes the PubSubConnection with node identifier connId. The operation is carried out on the server given the client or server object handle.

opcua pubsub handle RemoveDataSetFolder folderId

Removes the DataSetFolder object with node identifier folderId and all contained PublishedDataSets. The operation is carried out on the server given the client or server object handle.

opcua pubsub handle RemoveDataSetReader groupId readerId

Removes the DataSetReader with node identifier readerId on the ReaderGroup with node identifier groupId. The operation is carried out on the server given the client or server object handle.

opcua pubsub handle RemoveDataSetWriter groupId writerId

Removes the DataSetWriter with node identifier writerId on the WriterGroup with node identifier groupId. The operation is carried out on the server given the client or server object handle.

opcua pubsub handle RemoveGroup connId groupId

Removes the ReaderGroup or WriterGroup with node identifier groupId on the PubSubConnection with node identifier connId. The operation is carried out on the server given the client or server object handle.

opcua pubsub handle RemovePublishedDataSet pdsId

Removes the PublishedDataSet object with node identifier pdsId. The operation is carried out on the server given the client or server object handle.

opcua pubsubcfg handle load|save ?bytes?

Performs a serialization (save) or deserialization (load) of the PubSub configuration of the server object handle. For the load operation, bytes must contain a byte array of the serialization, for save a serialization is returned as result. The deserialization operation reconstructs the PubSub components in the server described by bytes.

opcua pwrite ...

See section Prepared Read And Write Operations.

opcua read handle nodeid ?attr cmd?

Performs a read operation on the client or server object handle and returns the value of attribute attr of the node identifier nodeid. If attr is omitted, it defaults to the Value attribute. The optional parameter cmd can be specified on client objects in order to carry out the read operation in asynchronous mode. See opcua call and section Asynchronous Operations for more information. If cmd is an empty list, on both client and server, the return value of the read operation is not the deserialized value, but a DataValue dictionary with additional information. The dictionary has the keys value for the value itself, valueRank with optional arrayDimensions, dataType with the node identifier of the type of the value, and optional timestamps. This mode of operation can be useful to find out if a Variable is a scalar or an array, or to learn the real type of a value when the related Variable is of an abstract type.

opcua readjson handle nodeid ?attr?

This is an optional command which is available when the open62541 library is compiled with JSON support. Similar to opcua read a read operation on the client or server object handle is performed and the value of attribute attr of the node identifier nodeid is returned as a JSON string. If attr is omitted, it defaults to the Value attribute. This operation is always synchronous.

opcua reconnect handle ?user password?

Reconnects the client object handle with the same parameters which were used upon the most recent opcua connect call. Prior settings of user/password are overwritten with the arguments user and password, if provided.

opcua reftype ?name?

Returns the node identifier for the reference type name. When name is omitted, a list of all reference type names is returned.

opcua register handle nodelist

Registers the node identifiers from nodelist in the server to which handle is connected. If the operation succeeds, another list of node identifiers is returned which provides aliases to the node identifiers passed to the command during the life time of the session. Using the aliases instead of the original node identifiers can improve performance of subsequent read and write operations.

opcua request handle ?reqid?

Returns information on pending asynchronous operations of the client object handle. If a numeric request identifier reqid is given, a two element list for this request is returned made up of the operation type (call, read, or write) and the callback command which receives the response. If reqid is omitted, a list of all known pending request identifiers is returned.

opcua result phandle result ?statuscode?

Uses the handle phandle which was returned by opcua postpone to send result as the result for an asynchronous method. Optionally, statuscode may be specified to report a status code for the operation different from zero. If opcua result is invoked too late, that is phandle timed out, result and statuscode are silently discarded.

opcua root

Returns the node identifier of the root node.

opcua run handle ?ms?

Runs asynchronous operations (subscriptions, monitored items) on the client object handle for ms milliseconds. If ms is omitted, that duration defaults to zero. Normally, this operation is carried out by the Tcl event loop. Still, this command can be used to test if the client object is in the connected state.

opcua sc2str ?-short? code

Translates the numeric status code code to an error message string. A single word error string such as BadTimeout is produced when the -short option is specified.

opcua servers ?url?

Queries the local OPC/UA server opc.tcp://localhost:4840 or the server specified by the url parameter for server information and returns a list made up of deserialized dictionaries based on the UA_ServerOnNetwork structure. Consult the open62541 documention for more information.

opcua session handle admin|current|isadmin|list

Queries session information from handle which must be a server handle. With parameter current the current session identifier during a method or data source callback or during a constructor or destructor is returned. In all other contexts, the result is an empty string. Similarly, the isadmin parameter reports 1 if the current session is the adminstrative (server internal) session, or 0 in all other cases. With parameter list a list of all known session identifiers is returned. With parameter admin the identifier of the adminstrative (server interal) session is returned.

opcua start handle

Starts the server object handle. See section Server Object And Event Loop below for further information.

opcua state handle

Reports the current state of handle. If handle refers to a client, the result is a three element list with the identical information as passed in the additional parameters to the onclientstate callback. Otherwise, the result is a two element list. The first element is either stopped or running indicating the server state. The second element is a dictionary with statistic counters for connections, secure channels, and sessions.

opcua stop handle

Stops the server object handle.

opcua subscription handle configure id ?interval lifetime keepalive max prio?

Configures the subscription id on the client object handle. See opcua subscription new for the optional parameters.

opcua subscription handle destroy id

Destroys the subscription id on the client object handle.

opcua subscription handle info ?id?

Returns information about subscription id on the client object handle as a list of enable flag, interval, lifetime, keepalive, and maximum counters, and the priority value. If id is omitted, a list of all subscription identifiers of the client object is returned.

opcua subscription handle new ?flag interval lifetime keepalive max prio?

Creates a new subscription (a container for monitored items, see opcua monitor) on the client object handle and returns a numeric identifier of it. The following optional parameters control properties of the subscription: flag is the initial enable state (on by default), interval, lifetime, keepalive, and max the timing and queuing parameters, and prio the subscription's priority.

opcua subscription handle off id

Disables the subscription id on the client object handle.

opcua subscription handle on id

Enables the subscription id on the client object handle.

opcua tojson ?handle? type data

This is an optional command which is available when the open62541 library is compiled with JSON support. The serialized (dictionaries, lists) Tcl value data is converted to an equivalent JSON string according to the datatype type. The type is looked up globally and optionally in the type information available for the client or server object handle. The JSON string is returned as result of the command.

opcua translate handle nodeid reftype target ...

Performs a translate operation on the client or server object handle. The operation starts at node identifier nodeid and traverses the object tree along the references reftype and browse name target. A list made up of the node identifier, namespace URI, and server index of the final target is returned as the result. References can be preceeded with an exclamation mark in order to reverse their direction. A reference may be abbreviated as slash for HierarchicalReferences or as dot for Aggregates.

opcua tree handle ?nodeid? ?mask?

Returns information similar to opcua browse using the client or server object handle. The address space is traversed starting at the node identifier nodeid (the root node if omitted). The kind of nodes to be included can be specified with mask. If mask is empty or omitted, all matching nodes are reported. The result list is made up of tree level (0-based), node identifier, browse name (qualified name), display name (locale and text), node class, reference node identifier, type node identifier, and parent node identifier.

opcua trust handle trustlist issuerlist revocationlist

Reloads the trust, issuer, and revocation lists of the server object handle. trustlist and issuerlist must be lists of byte arrays of certificates in pem or der format. revocationlist must be a list of byte arrays of certificates in der format. All lists may be empty (but this effectively locks down the server). It is not necessary to stop the server.

opcua type handle nodeid ?attr?

Performs a read operation on the client or server object handle like opcua read but instead of the attribute's value returns the type name of attribute attr of the node identifier nodeid. If attr is omitted, it defaults to the Value attribute.

opcua types basic|builtin|empty|info|list|map|name|nodeid ?handle name?

Returns a list of OPC/UA type names for the basic and list subcommands. Basic types are primitives (e.g. integer numbers) for which a mapping to Tcl objects is provided. The map subcommand returns a list of alternating node identifiers and type names suitable for array set. The empty subcommand requires name to be a known OPC/UA type name and produces and returns an empty value of this type, e.g. 0.0 for a floating point type. The nodeid subcommand returns the node identifier for the type name. The name subcommand is the reverse operation of the nodeid subcommand and reports the type name for node identifier in nodeid. The info subcommand returns detailed type information for the requested name or nodeid. For the command forms where a handle can be specified, this allows to deal with additional custom data types (see e.g. opcua deftypes) which where loaded into the client or server object handle. The builtin subcommand returns the numeric value of the data type name for primitive types of namespace zero.

opcua unregister handle nodelist

Unregisters the node identifiers from nodelist in the server to which handle is connected. This is the reverse of the register subcommand which removes the aliases to the node identifiers in nodelist.

opcua users handle

Returns the usernames of the currently set user/password based access control list of the server object handle. If anonymous logins are allowed, this is indicated by a username which is an empty string.

opcua version

Returns the major and minor version numbers of the integrated open62541 library, e.g. "1.0".

opcua write handle nodeid ?attr? type value ?cmd?

Performs a write operation on the client or server object handle writing value with type type into the attribute attr of the node identifier nodeid. If attr is omitted, it defaults to Value. The operation is performed without setting an explicit source timestamp. The optional parameter cmd can be specified on client objects in order to carry out the write operation in asynchronous mode. See opcua call and section Asynchronous Operations for more information. When the type argument is prefixed with an asterisk, the ValueRank of the write operation is performed as a write to an array of one or more dimensions, i.e. the value is interpreted as a list of values to be written. Likewise, when the type argument is prefixed with an exclamation mark, the value argument is treated as a scalar. For dealing with multidimensional variables (the attribute ValueRank indicating arrays of one or more dimensions, and the ArrayDimensions even explicitely stating the bounds) the special prefix for the type must be the array dimensions separated by commas and overall enclosed in parenthesis, e.g. "(3,3)i=6" or "(3,3)Int32" for an Int32 3x3 matrix. Warning: this command performs additional queries of the address space in synchronous mode (cmd argument omitted), if no prefix to the type indicating its interpretation is provided. This can cost up to two additional round-trips to the server in client mode.

opcua writejson handle nodeid ?attr? type value

This is an optional command which is available when the open62541 library is compiled with JSON support. Similar to opcua write a write operation on the client or server object handle is performed and the attribute attr of the node identifier nodeid is written by serializing the JSON string value according to the data type type. If attr is omitted, it defaults to Value. This operation is always synchronous.

opcua xcall handle nodeid methodid ?type value ...?

This is the coroutine aware version of opcua call. If called with a client handle in a coroutine context it uses an asynchronous call operation with yield as callback, i.e. automatically suspends the coroutine and resumes it again when the result becomes available.

opcua xgenstubs handle ?strip substs ...?

This is the coroutine aware version of opcua genstubs. Instead of procedure bodies using opcua call it writes coroutine aware procedure bodies using opcua xcall.

opcua xmldump handle

Returns an XML string of the address space of the client or server object handle. This includes only namespaces with numeric index 2 and higher. If there are only namespace indices 0 and 1, i.e. in a fresh server without additional node sets loaded, an error is reported.

opcua xmread handle nodeid ...

This is the coroutine aware version of opcua mread. If called with a client handle in a coroutine context it uses an asynchronous read operation with yield as callback, i.e. automatically suspends the coroutine and resumes it again when the result becomes available.

opcua xmreadx handle nodeid attr index ...

This is the coroutine aware version of opcua mreadx. If called with a client handle in a coroutine context it uses an asynchronous read operation with yield as callback, i.e. automatically suspends the coroutine and resumes it again when the result becomes available.

opcua xmwrite handle nodeid type value ...

This is the coroutine aware version of opcua mwrite. If called with a client handle in a coroutine context it uses an asynchronous write operation with yield as callback, i.e. automatically suspends the coroutine and resumes it again when the result becomes available.

opcua xmwritex handle nodeid attr index type value ...

This is the coroutine aware version of opcua mwritex. If called with a client handle in a coroutine context it uses an asynchronous write operation with yield as callback, i.e. automatically suspends the coroutine and resumes it again when the result becomes available.

opcua xread handle nodeid ?attr?

This is the coroutine aware version of opcua read. If called with a client handle in a coroutine context it uses an asynchronous read operation with yield as callback, i.e. automatically suspends the coroutine and resumes it again when the result becomes available.

opcua xsleep ms

This is a coroutine aware convenience function which delays execution for ms milliseconds by using the after command with a callback in order to service events, if invoked in a coroutine context.

opcua xwrite handle nodeid ?attr? type value

This is the coroutine aware version of opcua write. If called with a client handle in a coroutine context it uses an asynchronous write operation with yield as callback, i.e. automatically suspends the coroutine and resumes it again when the result becomes available.

OPC/UA Ensemble

The current implementation uses an ensemble and namespace opcua, i.e. the command opcua info can be alternatively written as opcua::info. Some more complex subcommands of the opcua namespace are implemented in Tcl, namely the opcua tree and opcua genstubs procedures.

Node Identifiers

Numeric node identifiers can be written as ns=N;i=I where N is the numeric namespace, and I the numeric identifier. Likewise, string node identifiers are written as ns=N;s=S with S being the string identifier. GUID node identifiers are written as ns=N;g=G where the GUID is G with the usual format as sequence of hexadecimal numbers and dashes. The namespace part can be left out when namespace zero is addressed. Currently, byte string node identifiers are not supported. If the format cannot be determined (e.g. since the equal sign is missing) the fallback chosen is string node identifier in namespace zero. String named namespaces are not supported.

Qualified Names

Qualified names are used for example in the opcua browse and opcua translate operations as so called browse names. These are made up of an optional numeric namespace prefix (a number followed by a colon) and a name, e.g. 2:MyObject. The namespace prefix is left out if the name refers to namespace zero.

Localized Text

The data type LocalizedText is represented as a dict with the keys locale and text. When converting a Tcl value to a LocalizedText item, these keys are tried to be associated. If this operation fails, the Tcl value is used as the text part of the LocalizedText item and the locale part is left empty.

Supported Data Types

Currently, most of the data types of namespace zero are supported and can be mapped to/from Tcl, i.e. integral and floating point numbers, strings, GUIDs, and interal extension objects (similar to structures). For the latter, dictionaries are used in both directions, i.e. for encoding, a dictionary is searched for the respective member names, for decoding, a dictionary is created from the internal representation using the member names of the data type, see opcua attrs default for example. Support for custom data types is highly experimental and underdocumented (see opcua gentypes).

Monitor Callbacks

Monitor callbacks are invoked when a monitored item (data or event) is received. The callback parameter given in opcua monitor new must have proper list format and gets a single value (data) or a list of values (event) appended prior to invocation.

Data Source Callbacks

Data source callbacks are invoked when a DataValue is read or written to. The callback parameter given in the node creation (opcua add Variable) must have proper list format and gets the following parameters appended prior to invocation: the node identifier of the DataValue, the operation (either read or write), and the value attribute for write operations. If the read or write operation specifies a numeric range, the range description is added as the last parameter. It is expressed as a Tcl list with even number of integer elements. Each pair describes the start and end elements of a dimension. For read operations the callback must return a two element list of the data type (e.g. String or Int32) and the value itself. If the callback returns the TCL_BREAK return code, the value is assumed to be an array and splitted into list elements which then are converted to OPC/UA data in an OPC/UA array.

Method Callbacks

Method callbacks are invoked when a Method node is called. The callback parameter given in the node creation (opcua add Method) must have proper list format and gets the following parameters appended prior to invocation: the object node identifier, the method node identifier, and a list of type names derived from the method's output arguments. This list may be used in the method's implementation to form the result. The callback must return a single value which must be a list with the same number of items of the output argument's type list. Each item gets converted to the respective OPC/UA data value according to the output argument information of the Method node. I.e. for simple types, a list item may be a single integer e.g. for a single UInt16, a list of integers for an array of UInt16's, a single dict for a structure type, or a list of dicts for an array of structured types. If the method invocation has to report back an error as non-zero OPC/UA status code, the method must use return -code break, which triggers collection of the status code from the global errorCode Tcl list.

Client Object And Event Loop

A client object obtained with opcua new client requires a running event loop only when subscriptions/monitored items are involved. Most other operations are performed synchronously (and thus blocking).

Asynchronous Operations

Asynchronous mode of operation is supported for client objects and their opcua call, opcua read, and opcua write subcommands. The callback parameter must have proper list format and gets a single value appended prior to invocation which carries the deserialized response message corresponding to the operation. It is made up as a nested dict which contains a ResponseHeader with the status code of the operation and depending on the operation the method call result(s) or the value of the attribute read plus additional diagnostic information. That dict gets an extra key named RequestId appended which is the integer request identifier of the operation which was returned by the command initiating the request. If the callback parameter is specified as empty list, the response is discarded, i.e. no Tcl code is evaluated and the operation appears as a one way request.

Prepared Read And Write Operations

Prepared read and write operations are modeled similar to prepared statements in databases. The operation is setup in a single preparation phase, where the node identifiers and data types (for the write direction) are specified and tied to local names. After preparation the operation can be executed multiple times without the need to parse node identifiers/data types again. After execution the results can be retrieved, i.e. the data read for read operations or the write status information for write operations.

opcua pread configure phandle name ?value?

Returns the configuration of the item name in phandle as dictionary of a serialized ReadValueId, if no value argument was provided. Otherwise changes the configuration of name according to value which must be a dictionary of a serialized ReadValueId.

opcua pread delete phandle

Deletes the prepared read identified by phandle. This step is implicitly carried out when the OPC/UA client or server handle to which phandle is bound is deleted.

opcua pread execute phandle

Performs the OPC/UA read operation described by phandle and returns an empty string as result. In error cases an exception with the overall error result of the OPC/UA response is returned.

opcua pread get phandle name

Returns the last read value for item name of phandle.

opcua pread getall phandle

Returns a dictionary made up of the last read values of all items in phandle.

opcua pread getx phandle ?name?

Returns the last read value for item name of phandle with all available meta data in the form of a serialized DataValue as dictionary. If name is omitted, a dictionary of all items in handle is returned with a serialized DataValue for each item.

opcua pread info handle|phandle

Returns a list of the prepared reads of the client or server handle handle, or the item names of handle phandle.

opcua pread new handle nodeid name ...

Creates a new prepared read on the client or server identified by handle and returns a handle (phandle) for the prepared read. One or more items identified by name which will read the respective nodeid must be specified for the prepared read.

opcua pread status phandle ?name?

Returns the last status code for item name on phandle. If name is omitted a dictionary keyed by item names of all status codes of phandle is returned.

opcua pwrite configure phandle name ?value?

Returns the configuration of the item name in phandle as dictionary of a serialized WriteValue, if no value argument was provided. Otherwise changes the configuration of name according to value which must be a dictionary of a serialized WriteValue.

opcua pwrite delete phandle

Deletes the prepared write identified by phandle. This step is implicitly carried out when the OPC/UA client or server handle to which phandle is bound is deleted.

opcua pwrite execute phandle

Performs the OPC/UA write operation described by phandle and returns an empty string as result. In error cases an exception with the overall error result of the OPC/UA response is returned.

opcua pwrite info handle|phandle

Returns a list of the prepared writes of the client or server handle handle, or the item names of handle phandle.

opcua pwrite new handle nodeid type name ...

Creates a new prepared write on the client or server identified by handle and returns a handle (phandle) for the prepared write. One or more items identified by name which will write the respective nodeid with data type type must be specified for the prepared write. The data type can be left as an empty string in which case it must later be provided at least once in a opcua pwrite set call.

opcua pwrite set phandle name ?type? value

Sets the value for item name in the prepared write phandle. If no data type type is specified, the data type of value is the last data type used for the item, e.g. the initial type provided in opcua pwrite new.

opcua pwrite setall phandle value

Sets the values for all items in phandle from the dictionary value.

opcua pwrite status phandle ?name?

Returns the last status code for item name on phandle. If name is omitted a dictionary keyed by item names of all status codes of phandle is returned.

Client Example


    package require topcua

    # create client
    opcua new client C

    # connect to server
    opcua connect C opc.tcp://localhost:4840 user pass

    # get MyNamespace
    set ns [opcua namespace C MyNamespace]

    # generate stub procs to methods in server
    # these are created in the client specific ::opcua::C namespace
    opcua genstubs C /Root/Objects/${ns}:MyObject/${ns}:

    # list all procs in client specific namespace
    puts stderr [info procs ::opcua::C::*]

    # call stubs
    puts stderr [::opcua::C::Reverse esreveR]
    puts stderr [::opcua::C::WordSplit "word\n\nsplit"]

    # read a variable
    puts stderr [opcua read C "ns=${ns};ItsTclTime"]

    # monitor callback proc
    proc monitor {data} {
        puts stderr "Monitor: $data"
    }

    # make a subscription
    set sub [opcua subscription C new 1 1000.0]

    # make a monitor
    set mon [opcua monitor C new $sub data monitor "ns=${ns};ItsTclTime"]
    puts stderr "Subscription: $sub"
    puts stderr "Monitor: $mon"

    # handle monitors for a few seconds
    set done 0
    after 10000 {set done 1}
    vwait done

    # delete monitor and subscription
    opcua monitor C destroy $sub $mon
    opcua subscription C destroy $sub

    # shut down the server using a method call
    ::opcua::C::Exit

    # destroy the client
    opcua destroy C

Server Object And Event Loop

A server object obtained with opcua new server requires a running event loop as long as it is in running state (started with opcua start). Depending on the support of the underlying open62541 library, the opcua server's network handler re-dispatches itself using a Tcl timer callback whose interval is controlled by the protocol timers of the OPC/UA stack implementation, or it spins up a dedicated thread which deals with the network traffic. In the latter case, a running event loop is required, too, for processing method and datasource callbacks.

Server Example


    package require topcua

    # create server
    opcua new server 4840 S

    # setup access control
    opcua acl S user pass

    # implementations of methods etc.
    namespace eval ::opcua::S {
        # method callback
        proc _reverse {obj meth string} {
            return [string reverse $string]
        }
        # method callback
        proc _wordsplit {obj meth string} {
            set w [regexp -all -inline {\S+} $string]
            # return code break makes into an array result
            return -code break $w
        }
        # method callback
        proc _exit {obj meth} {
            after 1000 [namespace current]::_real_exit
            return {}
        }
        # helper proc
        proc _real_exit {} {
            catch {
                ::opcua::stop S
                ::opcua::destroy S
            }
            exit 0
        }
        # data source callback
        proc _its_tcl_time {node op {value {}}} {
            if {$op eq "read"} {
                return [list String [clock format [clock seconds]]]
            }
            return {}
        }
    }

    # create our OPC/UA namespace
    set ns [opcua add S Namespace MyNamespace]

    # get Objects folder
    set OF [lindex [opcua translate S [opcua root] / Objects] 0]

    # create an object in our namespace in Objects folder
    set obj [opcua add S Object "ns=$ns;s=MyObject" $OF Organizes \
        "$ns:MyObject"]

    # create methods on object
    set meth [opcua add S Method "ns=$ns;s=Reverse" \
                  $obj HasComponent \
                  {String !out} "$ns:Reverse" {String !in} \
                  ::opcua::S::_reverse]
    set meth [opcua add S Method "ns=$ns;s=WordSplit" \
                  $obj HasComponent \
                  {String !out} "$ns:WordSplit" {String !in} \
                  ::opcua::S::_wordsplit]
    set meth [opcua add S Method "ns=$ns;s=Exit" \
                  $obj HasComponent \
                  {} "$ns:Exit" {} \
                  ::opcua::S::_exit]

    # create a variable in our namespace in Objects folder
    set var [opcua add S Variable "ns=$ns;s=ItsTclTime" \
                 $OF Organizes \
                 "$ns:ItsTclTime" {} {} \
                 ::opcua::S::_its_tcl_time]

    # dump methods
    puts stderr [opcua methods S]

    # generate stubs to methods in server
    # these are created in the server specific ::opcua::S namespace
    opcua genstubs S /Root/Objects/${ns}:MyObject/${ns}:

    # list all procs in server specific namespace
    puts stderr [info procs ::opcua::S::*]

    # call stubs directly on server
    puts stderr [::opcua::S::Reverse esreveR]
    puts stderr [::opcua::S::WordSplit "word\n\nsplit"]

    # read our variable
    puts stderr [opcua read S $var]

    # start server
    opcua start S

    # enter event loop
    vwait forever

Defining Custom Data Structures


    package require topcua

    # create server
    opcua new server 4840 S

    # create our namespace
    set NS http://www.androwish.org/TestNS/
    set nsidx [opcua add S Namespace $NS]

    # create structs etc., field names prefixed with '*' are arrays
    # CAUTION: no comments allowed in the definition list
    opcua deftypes S $NS {
        typedef WORD UInt16
        struct KVPair {
            String name
            String value
        }
        struct RGB {
            WORD red
            WORD green
            WORD blue
        }
        struct NamedColor {
            String name
            RGB color
        }
        struct WithArray {
            String name
            String *values
        }
        enum SimpleEnum { Red Green Blue }
        union Various {
            KVPair pair
            RGB color
            NamedColor ncolor
        }
        optstruct OptColor {
            mandatory String name
            optional RGB color
        }
    }

    # import type defs
    opcua gentypes S

    # make some variables using the structs from above
    set OF [lindex [opcua translate S [opcua root] / Objects] 0]
    foreach {name type} {
        X1 KVPair
        X2 RGB
        X3 NamedColor
        X4 WithArray
    } {
        set att [opcua attrs default VariableAttributes]
        dict set att dataType [opcua types nodeid S $type]
        dict set att value [list $type [opcua types empty S $type]]
        opcua add S Variable "ns=${nsidx};s=$name" $OF Organizes \
            "${nsidx}:$name" {} $att
    }

    opcua write S "${nsidx}:X4" Value WithArray {
        name {A B C D E}
        values {A B C D E}
    }

    # start server
    opcua start S

    # enter event loop
    vwait forever