Client API reference¶
Creating a Client¶
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:
- client:connect(endpointUrl[, connectCallback])
- endpointUrl (string)
OPCUA server endpoint URL.
- 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
- 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
- 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
- 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
- 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.."'")
- 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
- 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
- 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
- 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"))
- 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:
resp, err = client:activateSession() if err ~= nil then return end -- Insert a folder into the address space local folderParams = { parentNodeId = ObjectsFolder, referenceTypeId = Organizes, requestedNewNodeId = ua.NodeId.Null, browseName = {name="TestFolder", ns=3}, nodeClass = ua.Types.NodeClass.Object, displayName = {text="Folder"}, description = {text="Folder Example"}, writeMask = 0, userWriteMask = 0, eventNotifier = 0, typeDefinition = FolderType } local request = { nodesToAdd = {folderParams} } local resp, err = client:addNodes(request) for i,res in ipairs(resp.results) do
- 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
- client:closeSecureChannel()
Terminate a SecureChannel.
- Result
- 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.