Client API reference
Constructor
A client is created by calling:
- ua.newClient(<config>)
- config:
Configuration table. If nil then default configuration is used with the following options:
One secure policy None
Endpoint URL opc.tcp://<ip_address>:4841. IP address is detected automatically and if failed then localhost is used.
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
}
}
}
client:connect
Establish connection to a server.
- 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.
- return:
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
Example 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")
client:openSecureChannel
Open new secure channel. The client must open at least one channel.
- client:openSecureChannel(timeout[, msgCallback])
- timeout:
(uint32) How long a channel should be alive/active (in milliseconds).
- msgCallback:
- return:
OpenSecureChannelResponse, error
The client instance 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
Get the list of the servers known to a Server or Discovery Server
- client:findServers(params[, msgCallback])
- 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
Returns the Endpoints supported by a Server and all of the configuration information required to establish a SecureChannel and a Session.
- client:getEndpoints(params[, msgCallback])
- 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:
- return:
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
This Service is used by an OPC UA Client when creating a Session. The Server returns two values which uniquely identifies the Session.
- client:createSession(name, timeoutMs[, msgCallback])
- 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:
- return:
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
Activate previously created session. Is used to authenticate user on the server.
- client:activateSession(policyId [, identity, secret] [, msgCallback])
- policyId:
(string)
Token policy to use. This is taken from the server’s endpoint description. Endpoint description can be obtained by calling client:getEndpoints or client:createSession.
- identity:
(string) User identity: username, user certificate, ‘user token’ Empty if token policy is anonymous.
- secret:
(string) User secret. ‘password’, ‘user private key Empty if token policy is anonymous or an issued token.
- msgCallback:
- return:
ActivateSessionResponse, error
Example:
resp, err = client:activateSession()
if err ~= nil then
trace("Activating session failed: "..err)
return
end
client:browse
This Service is used for discovering the References of a specified Node.
- client:browse([nodeId | nodeId[] | params] [, msgCallback])
- nodeId:
(NodeId) id of the node to browse.
- nodeId[]:
(NodeId) array of NodeIDs to browse
- params:
(table) BrowseParameters
- msgCallback:
- Result:
Browsing Result,error
Example:
-- Browse one node by ID.
resp, err = client:browse(RootFolder)
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
Read one or more Attributes of one or more Nodes.
- client:read(<nodeId | nodeId[] | params> [, msgCallback])
- NodeId:
(NodeID) Read possible attributes of one node by NodeId.
- NodeId[]:
(NodeID) Array of NodeIds to read. Will be read all possible attributes
- parameters:
Table with detailed parameters. For details see Reading Attributes
- msgCallback:
- return:
The result from an OPC UA call will be an array. Every element of the array will be a table with two fields: Status code for the current node and the value of the attribute.
Every element of the array contains a table with the following fields:
- StatusCode
The status code from reading the corresponding node.
- Value
The value of the attribute. The value will be nil in case of error.
Example:
resp,err = client:read(ObjectsFolder)
for i,result in ipairs(resp.Results) do
if result.StatusCode == 0 then
ua.Tools.printTable("result", result.Value)
else
trace(string.format("Read attributes error: 0x%X", result.StatusCode))
end
end
client:write
This Service is used when writing values to one or more Attributes of one or more Nodes.
- client:write(params[, msgCallback])
- params:
(table)
NodesToWrite[] (array)
NodeId (NodeId) node identifier
AttributeId (Node Attribute) attribute to read
Value (DataValue) New value of attribute
- msgCallback:
- return:
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"))
end
client:addNodes
Add one or more Nodes into the AddressSpace hierarchy.
- client:addNodes(parameters[, msgCallback])
- parameters:
(table) A table with array of nodes to add. See details in Adding Nodes
- msgCallback:
- return:
AddNodesResponse,error
Example:
local variableId = "i=1000000"
local dataValue = {
Value = {UInt32=30000}
}
local newVariable = ua.newVariableParams(ObjectsFolder, "UInt32", dataValue, variableId)
local request = {
NodesToAdd = {newVariable}
}
resp, err = client:addNodes(request)
for i,res in ipairs(resp.results) do
if res.statusCode ~= 0 then
trace(string.format("Adding variable node failed: 0x%X", res.statusCode))
else
trace(string.format("Added new variable with NodeId: '%s'", res.addedNodeId))
end
end
client:translateBrowsePaths
This Service is used when requesting that the Server translates one or more browse paths to NodeIds.
- client:translateBrowsePaths(params[, msgCallback])
- msgCallback:
client:closeSession
Terminate an active Session.
- client:closeSession([msgCallback])
- msgCallback:
- return:
CloseSessionResponse,error
Example:
resp, err = client:closeSession()
if err == nil then
trace("Session closed")
end
client:closeSecureChannel
Terminate a SecureChannel.
- client:closeSecureChannel()
- return:
client:disconnect
Close the client’s server socket connection. Calling this method also closes any open channel.
- client:disconnect()
- return:
error
Message callback
Callback function that is called when the request has been completed.
- msgCallback(response, err)
- response:
Data received from server in response to corresponding request.
- err:
Any error that occured during processing of request.