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", 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
- securityPolicyUri (string)
- Public known URI of a policy that is used to secure messages
- 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", 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
Example without callback:
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
- Message callback
- 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) client:disconnect() done = true end local function connectCallback(err) if err == nil then local secureChannelTimeout = 60000 -- ms client:openSecureChannel(secureChannelTimeout, onChannelOpened) end end
Blocking example (no callback):
local err = client:connect(endpointUrl) if err ~= nil then trace("connection error: "..err) return end -- Open secure channel with timeout 120 seconds local resp, err = client:openSecureChannel(120000) if err ~= nil then trace("Opening secure channel failed: "..err) end trace("Opened secure channel with id: "..resp.securityToken.channelId)
- 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
- Message callback
- 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
- Message callback
- 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)
- browseParameters
- msgCallback
- Message callback
- Result
- Browsing Result,error
Example:
resp, err = client:browse({nodeIds.RootFolder, nodeIds.TypesFolder}) if err ~= nil then return end for _,res in ipairs(resp.results) do if res.statusCode ~= ua.StatusCode.Good then trace(string.format("Cannot browse node: 0x%X", res.statusCode)) else trace("References:") 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
- 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
- Message callback
- Result
- readResponse,error
Example:
local readParams = { nodesToRead = { {nodeId=nodeIds.ObjectsFolder, attributeId=ua.Types.AttributeId.DisplayName}, {nodeId=nodeIds.ObjectsFolder, attributeId=ua.Types.AttributeId.BrowseName}, {nodeId=nodeIds.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
- Message callback
- Result
- writeResponse,error
Example:
local nodes = { nodesToWrite = { { nodeId = nodeIds.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")) end
- 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)
- Possible values: scalar, array. More information can be found in section :ref:ValueRank
- 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
- Message callback
- Result
- addNodesResponse,error
Example:
local folderParams = { parentNodeId = nodeIds.ObjectsFolder, referenceTypeId = nodeIds.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 = nodeIds.FolderType } local request = { nodesToAdd = {folderParams} } local 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
- client:translateBrowsePaths(params[, msgCallback])
This Service is used when requesting that the Server translates one or more browse paths to NodeIds.
- msgCallback
- Message callback
- client:closeSession([msgCallback])
Terminate an active Session.
- msgCallback
- Message callback
- Result
- closeSessionResponse,error
Example:
resp, err = client:closeSession() if err == nil then trace("Session closed") end
- client:closeSecureChannel()
Terminate a SecureChannel.
- Result
- closeSecureChannelResponse,error
- 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.