Client API reference
Constructor
A client is created by calling:
- ua.newClient(config)
- config
Configuration table
Example:
local ua = require("opcua.api") local config = { applicationName = 'RealTimeLogic example', applicationUri = "urn:opcua-lua:example", productUri = "urn:opcua-lua:example", securePolicies = { { -- #1 securityPolicyUri = ua.Types.SecurityPolicy.None } } } local client = ua.newClient(config)
Client configuration table
- config - a table with the following:
- applicationName (string)
The client’s application name
- applicationUri (string)
application URI
- productUri
Product URI
- securePolicies (table)
List of polices that is used to secure messages See the Configuration table for details.
- cosocketMode (bool)
Flag that sets client in cosockets mode aka asynchronous mode.
- bufferSize (uint32, optional,default=8192)
Size of internal buffer used for sending and receiving messages.
- logging (table, optional)
Optional client logging. No logging is performed if not set. See the Configuration table for details.
Example:
local config = { applicationName = 'RealTimeLogic example', applicationUri = "urn:opcua-lua:example", productUri = "urn:opcua-lua:example", securePolicies = { { -- #1 securityPolicyUri = ua.Types.SecurityPolicy.None } } }
Methods
A client created by calling ua.newClient() has the following methods:
connect
- client:connect(endpointUrl[, transportProfile][, connectCallback])
- endpointUrl (string)
OPCUA server endpoint URL. it is possible to use the following formats:
opc.tcp://hostname:port/path
opc.http://hostname:port/path
opc.https://hostname:port/path
Some servers might require ‘http(s)://’ scheme instead of ‘opc.http(s)://’.
- transportProfile (string)
Transport profile to use. It is defines encoding of sending and receiving messages. There are two kinds of encoding is possible to specify: binary and JSON.
This parameter is omitted client will use binary encoding.
- Possible values:
ua.Types.TranportProfileUri.TcpBinary is used wotn ‘opc.tcp’ scheme
ua.Types.TranportProfileUri.HttpsBinary
ua.Types.TranportProfileUri.HttpsJon
- connectCallback
function that will be called on success or error.
- Result:
error
Example:
local client = ua.newClient(config) local function connectCallback(err) done = true if err ~= nil then trace("connection failed: "..err) return end trace("Connected sucessfully") client:disconnect() end local function connectToServer() trace("connecting to server") local endpointUrl = "opc.tcp://localhost:4841" client:connect(endpointUrl, connectCallback) end ba.socket.event(connectToServer, "s")
Example without callback:
local client = ua.newClient(config) trace("connecting to server") local endpointUrl = "opc.tcp://localhost:4841" local err = client:connect(endpointUrl) if err ~= nil then trace("connection failed: "..err) else trace("Connected sucessfully") end
Exampls of connecting to server over HTTP and with JSON encoding:
local err = client:connect("opc.https://localhost:"..mako.sslport.."/opcua/", ua.Types.TranportProfileUri.HttpsJson) if err ~= nil then error("connection failed: "..err) end trace("Connected sucessfully")
openSecureChannel
- client:openSecureChannel(timeout[, msgCallback])
Open new secure channel. The client must open at least one channel.
- timeout
How long a channel should be alive/active (in milliseconds).
- msgCallback
- Result
openSecureChannelResponse, error
The client will automatically refresh when the channel has been established.
Callback example:
local client = ua.newClient(config) local function onChannelOpened(resp, err) if err ~= nil then trace("Secure channel error: "..tostring(err)) return end trace("Opened secure channel with id: "..resp.SecurityToken.ChannelId) done = true end local function connectCallback(err) if err == nil then local secureChannelTimeout = 60000 -- ms client:openSecureChannel(secureChannelTimeout, ua.Types.SecurityPolicy.None, ua.Types.MessageSecurityMode.None, nil, onChannelOpened) end end local function connectToServer() trace("connecting to server") local endpointUrl = "opc.tcp://localhost:4841" client:connect(endpointUrl, connectCallback) end ba.socket.event(connectToServer, "s")
Blocking example (no callback):
local resp, err = client:openSecureChannel(120000, ua.Types.SecurityPolicy.None, ua.Types.MessageSecurityMode.None) if err ~= nil then trace("Opening secure channel failed: "..err) else trace("Opened secure channel with id: "..resp.SecurityToken.ChannelId) end
findServers
- client:findServers(params[, msgCallback])
Get the list of the servers known to a Server or Discovery Server
- params table with fields:
- endpointUrl (string, optional)
Endpoint URL.
- localeIds[] (string, optional)
List of locales to use. The Server should return the applicationName in the ApplicationDescription using one of locales specified.
- serverUris[] (string, optional)
The List of servers to return. All known servers are returned if the list is empty.
msgCallback - Message callback
Result: findServersResponse, error
Example:
-- Select known servers local params = { EndpointUrl = "opc.tcp://localhost:4841" } local resp, err = client:findServers(params) if err ~= nil then trace("Find servers error: "..err) else if not resp.Servers[0] then trace("No servers found.") end for i,srv in ipairs(resp.Servers) do trace("server #"..i) trace(" "..srv.ApplicationUri) trace(" "..srv.ProductUri) trace(" "..srv.ApplicationName.Text) end end
getEndpoints
- client:getEndpoints(params[, msgCallback])
Returns the Endpoints supported by a Server and all of the configuration information required to establish a SecureChannel and a Session.
- params a table with the following fields:
- endpointUrl (string, optional)
The network address the Client used when accessing the DiscoveryEndpoint.
- localeIds[] (string, optional)
List of locales to use. Specifies the locale to use when returning human readable strings.
- profileUris[] (string, optional)
List of Transport Profiles that the returned Endpoints support.
- msgCallback
- Result
getEndpointsResponse,error
Example:
-- Select endpoints local params = { EndpointUrl = "opc.tcp://localhost:4841" } local resp, err = client:getEndpoints(params) if err ~= nil then trace("Get endpoints error: "..err) else if not resp.Endpoints[0] then trace("No endpoints found.") end for i,endpoint in ipairs(resp.Endpoints) do trace("enspoint #"..i) trace(" "..endpoint.EndpointUrl) trace(" "..endpoint.TransportProfileUri) trace(" "..endpoint.SecurityPolicyUri) end end
createSession
- client:createSession(name, timeoutMs[, msgCallback])
This Service is used by an OPC UA Client when creating a Session. The Server returns two values which uniquely identifies the Session.
- params a table with the following fields:
- name (string)
Human readable string identifying the Session.
- timeoutMs (double)
Requested maximum number of milliseconds that a Session should remain open without activity.
msgCallback Message callback
Result createSessionResponse, error
Example:
resp, err = client:createSession("test_session", 3600000) if err ~= nil then trace("Creating session failed: "..err) return end trace("created session:") trace(" sessionId='"..resp.SessionId.."'") trace(" authenticationToken='"..resp.AuthenticationToken.."'") trace(" revisedSessionTimeout='"..resp.RevisedSessionTimeout.."'")
activateSession
- client:activateSession([msgCallback])
Activate previously created session.
- msgCallback
- Result
activateSessionResponse, error
Example:
resp, err = client:activateSession() if err ~= nil then trace("Activating session failed: "..err) return end
browse
- client:browse([params| nodeId | nodeId[]] [, msgCallback])
This Service is used for discovering the References of a specified Node.
- nodeId (NodeId)
id of the node to browse.
- nodeId[] (NodeId)
list of node IDs to browse
- params (table)
- msgCallback
- Result
Browsing Result,error
Example:
for i,ref in ipairs(res.References) do trace(string.format("%d: NodeId=%s Name=%s", i, ref.NodeId, ref.DisplayName.Text)) end end end -- Browse array of Node IDs. resp, err = client:browse({RootFolder, TypesFolder}) if err ~= nil then return end for _,res in ipairs(resp.Results) do if res.StatusCode ~= ua.StatusCode.Good then
read
- client:read(params[, msgCallback])
Read one or more Attributes of one or more Nodes.
- params (table)
- NodesToRead[]: (table)
NodeId (NodeId) node identifier AttributeId (Node Attribute) attribute to read
- msgCallback
- Result
readResponse,error
Example:
-- Reading current time on server and product version. local readParams = { NodesToRead = { {NodeId=ObjectsFolder, AttributeId=ua.Types.AttributeId.DisplayName}, {NodeId=ObjectsFolder, AttributeId=ua.Types.AttributeId.BrowseName}, {NodeId=ObjectsFolder, AttributeId=ua.Types.AttributeId.NodeId}, } } local resp,err = client:read(readParams) for i,result in ipairs(resp.Results) do if result.StatusCode == 0 then ua.Tools.printTable("result", result.Value) else trace(string.format("Read value '%s' error: 0x%X", nodes.NodesToRead[i].NodeId, result.StatusCode)) end end
write
- client:write(params[, msgCallback])
This Service is used when writing values to one or more Attributes of one or more Nodes.
- params (table)
NodesToWrite[] (table)
NodeId (NodeId) node identifier
AttributeId (Node Attribute) attribute to read
Value (DataValue) New value of attribute
- msgCallback
- Result
writeResponse,error
Example:
-- Update the OPC-UA server's start time. local nodes = { NodesToWrite = { { NodeId = Server_ServerStatus_StartTime, AttributeId = ua.Types. AttributeId.Value, Value = { -- DataValue Value = { -- Variant DateTime = 0.0 } } } } } local resp,err = client:write(nodes) if resp.Results[1] ~= 0 then trace(string.format("Changing attribute value failed: 0x%X", resp.Results[1])) else trace(string.format("Attribute value changed sucessfully"))
addNodes
- client:addNodes(params[, msgCallback])
Add one or more Nodes into the AddressSpace hierarchy.
- params (table)
- NodesToAdd[] (table)
- ParentNodeId (NodeId)
Parent’s node identifier.
- ReferenceTypeId (NodeId)
Parent’s reference type identifier.
- RequestedNewNodeId (NodeId)
NodeID for the new node. The actual identifier will be automatically assigned by server if NodeId equals ua.NodeId.Null.
- BrowseName (QualifiedName)
Internal name for the node. This name is used in the TranslateBrowsePathsToNodeIdsservice to resolve NodeId by path from some nodes.
- NodeClass (ua.Types.NodeClass)
Node class: Variable, Object, DataType. Only Variable node class is currently supported.
- DisplayName (LocalizedText)
Clients use this attribute if they want to display the name of the node to the user. Can be localized.
- Description (LocalizedText)
The optional description attribute explains the meaning of the node using localised text.
- WriteMask (UInt32)
Bit mask. Every bit defines ability to change corresponding attribute.
- UserWriteMask (UInt32)
Bit mask. Every bit defines ability to change corresponding attribute for current user.
- Value (Variant)
Initial value of a variable node.
- DataType (:ref:node_id_type)
Identifier of a node of type NodeClass DataType that describes the structure of a value. For example encoding/decoding in binary, json, xml formats. This may be an ID of a node of simple type (Int32, UInt,Float, etc), or complex structures (for example certificate, ApplicationDescription, BuildInfo).
- ValueRank (Int32)
The value rank for the field. It shall be Scalar (-1) or a fixed rank Array (>=1). There are next predefined values:
ScalarOrOneDimension = -3,
Any = -2,
Scalar = -1,
OneOrMoreDimensions = 0,
OneDimension = 1,
Greater values are number of dimensions: 2(matrix),3,4..
- ArrayDimensions[] (UInt32)
Array dimensions of the value. For example: {2,2} describes square matrix with size 2*2.
- AccessLevel (type Byte)
Defines the node attributes access mask.
- UserAccessLevel (type Byte)
Current user’s write mask.
- MinimumSamplingInterval (type Double)
TODO
- Historizing (boolean)
TODO
- msgCallback
- Result
addNodesResponse,error
Example:
local folderParams = { -- #1 ParentNodeId = ObjectsFolder, ReferenceTypeId = Organizes, RequestedNewNodeId = "i=1000", BrowseName = {Name="TestFolder", ns=0}, NodeClass = ua.Types.NodeClass.Object, TypeDefinition = FolderType, NodeAttributes = { TypeId = "i=354", Body = { SpecifiedAttributes = ua.Types.ObjectAttributesMask, DisplayName = {Text="DisplayName"}, Description = {Text="Description"}, WriteMask = 0, UserWriteMask = 0, EventNotifier = 0, } } } local request = { NodesToAdd = {folderParams} } resp, err = client:addNodes(request) for i,res in ipairs(resp.Results) do if res.StatusCode ~= 0 then trace(string.format("Adding folder node failed: 0x%X", res.StatusCode)) else trace(string.format("Added new folder node with Id: '%s'", res.AddedNodeId)) end end
translateBrowsePaths
- client:translateBrowsePaths(params[, msgCallback])
This Service is used when requesting that the Server translates one or more browse paths to NodeIds.
- msgCallback
- client:closeSession([msgCallback])
Terminate an active Session.
- msgCallback
- Result
closeSessionResponse,error
Example:
resp, err = client:closeSession() if err == nil then trace("Session closed") end
closeSecureChannel
- client:closeSecureChannel()
Terminate a SecureChannel.
- Result
disconnect
- client:disconnect()
Close the client’s server socket connection. Calling this method also closes any open channel.
- Result
error
Message callback
- msgCallback(response, err)
Callback function that is called when the request has been completed.
- response
Data received from server in response to corresponding request.
- err
Any error that occured during processing of request.