Client API
Constructor
A client is created by calling:
- ua.newClient(config, model)
- Config:
Client 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. If detection fails,localhostis used.
- Model:
Address Space API to use. If nil then
ua.baseModel()will be initialized.
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.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 policies that are used to secure messages See the Configuration table for details.
- cosocketMode (bool)
Flag that sets the client in cosocket mode (also known as asynchronous mode).
- bufSize (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.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/pathopc.http://hostname:port/pathopc.https://hostname:port/pathhttp://hostname:port/pathhttps://hostname:port/path
Some servers might require ‘http(s)://’ scheme instead of ‘opc.http(s)://’.
- TransportProfile:
(string) Transport profile to use. It defines the encoding of sending and receiving messages. There are two kinds of encoding possible to specify: binary and JSON.
If this parameter is omitted, the client will use binary encoding.
- Possible values:
ua.TranportProfileUri.TcpBinaryis used with theopc.tcpscheme.ua.TranportProfileUri.HttpsBinaryua.TranportProfileUri.HttpsJson
- ConnectCallback:
function that will be called on success or error.
- Returns:
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.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(timeoutMs, securityPolicyUri, securityMode[, remoteCert][, msgCallback])
- TimeoutMs:
(uint32) How long a channel should be alive/active (in milliseconds).
- SecurityPolicyUri:
(string) Security policy URI. Use constants such as
ua.SecurityPolicy.None,ua.SecurityPolicy.Basic128Rsa15, orua.SecurityPolicy.Basic256Sha256.- SecurityMode:
(number) Message security mode. Use
ua.MessageSecurityMode.None,ua.MessageSecurityMode.Sign, orua.MessageSecurityMode.SignAndEncrypt.- RemoteCert:
Optional remote server certificate. Required by secure policies that need the server certificate before the session response supplies it.
- MsgCallback:
- Returns:
OpenSecureChannelResponse, error
The client automatically schedules secure-channel renewal after a channel has
been established. For opc.http, opc.https, http, and https
connections, the transport has no OPC UA TCP secure channel; the method stores
the selected policy/mode and calls the callback, if one is provided.
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.SecurityPolicy.None, ua.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.SecurityPolicy.None, ua.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:
- Returns:
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])
- client:createSession(params[, msgCallback])
- Name:
(string) Human readable string identifying the Session.
- TimeoutMs:
(double) Requested maximum number of milliseconds that a Session should remain open without activity.
- Params:
a table with the following fields:
- ApplicationUri (string)
Client application URI.
- ProductUri (string)
Client product URI.
- ApplicationName (string)
Human readable client application name.
- ApplicationType (number)
Application type, for example
ua.ApplicationType.Client.- ServerUri (string, optional)
Server URI.
- EndpointUrl (string)
Endpoint URL used for the session.
- SessionName (string)
Human readable session name.
- SessionTimeout (double)
Requested session timeout in milliseconds.
- MsgCallback:
- Returns:
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 a previously created session. This method authenticates the user with one of the token policies returned by the server endpoint description.
- client:activateSession([msgCallback])
- client:activateSession(policyId, token[, token2][, msgCallback])
- client:activateSession(params[, 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()orclient:createSession().- Token:
(string) User identity token data. For username authentication this is the user name. For issued-token authentication this is the token. For certificate authentication this is the user certificate.
- Token2:
(string) Second token value when required. For username authentication this is the password. For certificate authentication this is the private key.
- Params:
(table) Manual
ActivateSessionrequest body. Use this form when constructingClientSignature,UserIdentityToken,UserTokenSignature, orLocalesyourself.- MsgCallback:
- Returns:
ActivateSessionResponse, error
Calling client:activateSession() with no policy arguments selects the
anonymous token policy. Passing a policyId selects the matching token policy
from the endpoint returned during session creation.
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:
- Returns:
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. All possible attributes will be read
- Params:
Table with detailed parameters. For details see Reading Attributes
- MsgCallback:
- Returns:
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.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 write
Value (DataValue) New value of attribute
- MsgCallback:
- Returns:
WriteResponse,error
Example:
-- Update the OPC-UA server's start time.
local nodes = {
NodesToWrite = {
{
NodeId = Server_ServerStatus_StartTime,
AttributeId = ua. AttributeId.Value,
Value = { -- DataValue
Type = ua.VariantType.DateTime,
Value = 0.0,
StatusCode = ua.StatusCode.Good
}
}
}
}
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:disconnect()
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:
- Returns:
AddNodesResponse,error
Example:
local variableId = "i=1000000"
local dataValue = {
Type = ua.VariantType.UInt32,
Value = 30000,
StatusCode = ua.StatusCode.Good
}
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])
- Params:
(table) TranslateBrowsePathsToNodeIds request parameters.
- MsgCallback:
- Returns:
TranslateBrowsePathsToNodeIds response, error
client:createSubscription
Create a subscription on the active session.
- client:createSubscription(params[, msgCallback])
- Params:
(table)
- RequestedPublishingInterval (Double)
Requested publishing interval in milliseconds. The Server returns the interval it can support in RevisedPublishingInterval.
- RequestedLifetimeCount (UInt32)
Requested number of publishing cycles without an available Publish request before the Subscription expires. The Server returns the supported value in RevisedLifetimeCount.
- RequestedMaxKeepAliveCount (UInt32)
Requested maximum number of publishing cycles without a notification before the Server sends a keep-alive. The Server returns the supported value in RevisedMaxKeepAliveCount.
- MaxNotificationsPerPublish (UInt32)
Maximum notifications to return in one Publish response.
0requests no limit.- PublishingEnabled (boolean)
trueto publish queued notifications.falsecreates the Subscription with publishing disabled.- Priority (Byte)
Relative publishing priority when several Subscriptions are ready.
0is the lowest priority.
- MsgCallback:
- Returns:
Response, error
The response table:
- ResponseHeader (ResponseHeader)
Service-level status and diagnostic information.
- SubscriptionId (UInt32)
Server-assigned identifier used by subsequent Subscription and MonitoredItem calls.
- RevisedPublishingInterval (Double)
Publishing interval selected by the Server, in milliseconds.
- RevisedLifetimeCount (UInt32)
Lifetime count selected by the Server.
- RevisedMaxKeepAliveCount (UInt32)
Keep-alive count selected by the Server.
errorisnilon success. A service-level failure is returned as an OPC UA StatusCode inerror.
client:modifySubscription
Modify the publishing parameters of an existing Subscription.
- client:modifySubscription(params[, msgCallback])
- Params:
(table)
- SubscriptionId (UInt32)
Identifier returned by createSubscription.
- RequestedPublishingInterval (Double)
New requested publishing interval in milliseconds.
- RequestedLifetimeCount (UInt32)
New requested lifetime count in publishing cycles.
- RequestedMaxKeepAliveCount (UInt32)
New requested keep-alive count in publishing cycles.
- MaxNotificationsPerPublish (UInt32)
New maximum notifications per Publish response.
0requests no limit.- Priority (Byte)
New relative publishing priority.
- MsgCallback:
- Returns:
Response table and error. The response contains:
- ResponseHeader (ResponseHeader)
Service-level status and diagnostic information.
- RevisedPublishingInterval (Double)
Publishing interval selected by the Server, in milliseconds.
- RevisedLifetimeCount (UInt32)
Lifetime count selected by the Server.
- RevisedMaxKeepAliveCount (UInt32)
Keep-alive count selected by the Server.
errorisnilon success or contains a service-level StatusCode.
client:deleteSubscriptions
Delete one or more Subscriptions from the active Session.
- client:deleteSubscriptions(subscriptionId | subscriptionIds[, msgCallback])
- SubscriptionId:
(UInt32) Identifier of one Subscription to delete.
- SubscriptionIds:
(UInt32 array) Identifiers of multiple Subscriptions to delete.
- MsgCallback:
- Returns:
Response table and error. The response contains:
- ResponseHeader (ResponseHeader)
Service-level status and diagnostic information.
- Results[] (StatusCode array)
One StatusCode for the single
subscriptionId, or one for each entry insubscriptionIdsin the same order. A result can fail even when the service call succeeds.- DiagnosticInfos[] (array)
Optional diagnostic information corresponding to
Results.
errorisnilon success or contains a service-level StatusCode.
client:setPublishingMode
Enable or disable publishing for one or more Subscriptions.
- client:setPublishingMode(params[, msgCallback])
- Params:
(table)
- PublishingEnabled (boolean)
trueto enable publishing orfalseto stop publishing queued notifications. Sampling is not disabled.- SubscriptionIds[] (UInt32 array)
Identifiers of the Subscriptions to update.
- MsgCallback:
- Returns:
Response table and error. The response contains:
- ResponseHeader (ResponseHeader)
Service-level status and diagnostic information.
- Results[] (StatusCode array)
One StatusCode for each requested SubscriptionId, in the same order.
- DiagnosticInfos[] (array)
Optional diagnostic information corresponding to
Results.
errorisnilon success or contains a service-level StatusCode.
client:createMonitoredItems
Create one or more MonitoredItems in a Subscription.
- client:createMonitoredItems(params[, msgCallback])
- Params:
(table)
- SubscriptionId (UInt32)
Identifier of the Subscription that will own the MonitoredItems.
- TimestampsToReturn (TimestampsToReturn)
Timestamps requested in returned DataValues. Use
Source,Server,Both, orNeither.
- ItemsToCreate[] (array)
MonitoredItems to create. Each element contains the following fields.
- ItemToMonitor (table)
Node and Attribute to monitor.
- NodeId (NodeId)
Identifier of the Node to monitor.
- AttributeId (Node Attribute)
Attribute to sample, normally
ua.AttributeId.Value.- IndexRange (string, optional)
Numeric range within an array value. The default is an empty string, which selects the complete value.
- DataEncoding (QualifiedName, optional)
Requested data encoding. Omit it to use the default encoding.
- MonitoringMode (MonitoringMode)
Initial mode:
Disabled,Sampling, orReporting.- RequestedParameters (table)
Requested sampling, filter, and queue parameters.
- ClientHandle (UInt32)
Application-defined identifier returned in every data-change notification for this MonitoredItem.
- SamplingInterval (Double)
Requested sampling interval in milliseconds.
0requests the fastest practical sampling. A negative value requests the Subscription publishing interval.- Filter (ExtensionObject, optional)
Monitoring filter. When omitted, the Client sends a null filter and the default StatusValue trigger is used. A DataChangeFilter uses
TypeId = "i=724"and aBodywith these fields:- Trigger (DataChangeTrigger)
Status,StatusValue, orStatusValueTimestampselects which changes produce notifications.- DeadbandType (DeadbandType)
None,Absolute, orPercentselects how value changes are filtered. The compact Server does not support percent deadband.- DeadbandValue (Double)
Absolute value difference or percentage required to produce a notification. It is ignored when
DeadbandTypeisNone.
- QueueSize (UInt32)
Requested number of notifications retained for this item.
- DiscardOldest (boolean)
When the queue is full,
truediscards its oldest value;falsediscards the newest value.
- MsgCallback:
- Returns:
Response table and error. The response contains:
- ResponseHeader (ResponseHeader)
Service-level status and diagnostic information.
- Results[] (array)
One result for each entry in ItemsToCreate, in the same order.
- StatusCode (StatusCode)
Result of creating this MonitoredItem.
- MonitoredItemId (UInt32)
Server-assigned identifier for the corresponding ItemsToCreate entry. It is valid when
StatusCodeisua.StatusCode.Goodand is passed to modifyMonitoredItems, setMonitoringMode, or deleteMonitoredItems to identify the created item.- RevisedSamplingInterval (Double)
Sampling interval selected by the Server, in milliseconds.
- RevisedQueueSize (UInt32)
Queue size selected by the Server.
- FilterResult (ExtensionObject)
Filter-specific result returned by the Server. No result structure is defined for no filter or a DataChangeFilter, so the compact Server returns a null ExtensionObject with
TypeId = "i=0". Servers supporting other filters can return the corresponding result structure, such as an EventFilterResult or AggregateFilterResult.
- DiagnosticInfos[] (array)
Optional diagnostic information corresponding to
Results.
errorisnilwhen the service call succeeds. Inspect everyResults[].StatusCodefor per-item failures.
client:modifyMonitoredItems
Modify the sampling and queue parameters of existing MonitoredItems.
- client:modifyMonitoredItems(params[, msgCallback])
- Params:
(table)
- SubscriptionId (UInt32)
Identifier of the Subscription that owns the MonitoredItems.
- TimestampsToReturn (TimestampsToReturn)
Timestamps requested in subsequently reported DataValues. Use
Source,Server,Both, orNeither.
- ItemsToModify[] (array)
MonitoredItems to modify. Each element contains:
- MonitoredItemId (UInt32)
- RequestedParameters (table)
New sampling, filter, and queue parameters. This table replaces the existing settings; it is not a partial update. All fields below except
Filtermust be supplied.- ClientHandle (UInt32)
Application-defined identifier to return in subsequent notifications. This replaces the previous ClientHandle.
- SamplingInterval (Double)
New requested sampling interval in milliseconds.
0requests the fastest practical sampling. A negative value requests the Subscription publishing interval.- Filter (ExtensionObject, optional)
New monitoring filter. Omit it to use the default StatusValue trigger. A DataChangeFilter uses
TypeId = "i=724"and aBodycontaining DataChangeTrigger, DeadbandType, andDeadbandValue.- QueueSize (UInt32)
New requested number of notifications retained for this MonitoredItem.
- DiscardOldest (boolean)
When the queue is full,
truediscards its oldest value;falsediscards the newest value.
- MsgCallback:
- Returns:
Response table and error. The response contains:
- ResponseHeader (ResponseHeader)
Service-level status and diagnostic information.
- Results[] (array)
One result for each entry in ItemsToModify, in the same order.
- StatusCode (StatusCode)
Result of modifying this MonitoredItem.
- RevisedSamplingInterval (Double)
Sampling interval selected by the Server, in milliseconds.
- RevisedQueueSize (UInt32)
Queue size selected by the Server.
- FilterResult (ExtensionObject)
Filter-specific result returned by the Server. No result structure is defined for no filter or a DataChangeFilter, so the compact Server returns a null ExtensionObject with
TypeId = "i=0". Servers supporting other filters can return the corresponding result structure, such as an EventFilterResult or AggregateFilterResult.
- DiagnosticInfos[] (array)
Optional diagnostic information corresponding to
Results.
errorisnilwhen the service call succeeds. Inspect everyResults[].StatusCodefor per-item failures.
client:setMonitoringMode
Set the monitoring mode of one or more MonitoredItems.
- client:setMonitoringMode(params[, msgCallback])
- Params:
(table)
- SubscriptionId (UInt32)
Identifier of the Subscription that owns the MonitoredItems.
- MonitoringMode (MonitoringMode)
New mode for every requested item:
Disabledstops sampling,Samplingsamples without reporting, andReportingsamples and reports queued notifications.
- MonitoredItemIds[] (UInt32 array)
Identifiers of the MonitoredItems to update. Each value comes from createMonitoredItems.Results[].MonitoredItemId.
- MsgCallback:
- Returns:
Response table and error. The response contains:
- ResponseHeader (ResponseHeader)
Service-level status and diagnostic information.
- Results[] (StatusCode array)
One StatusCode for each entry in MonitoredItemIds, in the same order.
- DiagnosticInfos[] (array)
Optional diagnostic information corresponding to
Results.
errorisnilon success or contains a service-level StatusCode.
client:deleteMonitoredItems
Delete one or more MonitoredItems from a Subscription.
- client:deleteMonitoredItems(params[, msgCallback])
- Params:
(table)
- SubscriptionId (UInt32)
Identifier of the Subscription that owns the MonitoredItems.
- MonitoredItemIds[] (UInt32 array)
Identifiers of the MonitoredItems to delete. Each value comes from createMonitoredItems.Results[].MonitoredItemId.
- MsgCallback:
- Returns:
Response table and error. The response contains:
- ResponseHeader (ResponseHeader)
Service-level status and diagnostic information.
- Results[] (StatusCode array)
One StatusCode for each entry in MonitoredItemIds, in the same order.
- DiagnosticInfos[] (array)
Optional diagnostic information corresponding to
Results.
errorisnilon success or contains a service-level StatusCode.
client:publish
Submit acknowledgements and wait for a notification or keep-alive from a Subscription in the active Session.
- client:publish(params[, msgCallback])
- Params:
(table)
- SubscriptionAcknowledgements[] (array)
NotificationMessages successfully processed by the application. Use an empty array when there is nothing to acknowledge. Each acknowledgement contains:
- SubscriptionId (UInt32)
Identifier of the Subscription that produced the message.
- SequenceNumber (UInt32)
NotificationMessage.SequenceNumber being acknowledged.
- TimeoutHint (UInt32, optional)
Maximum time in milliseconds that the request should wait for a notification or keep-alive. The Client places this value in the OPC UA RequestHeader.
- MsgCallback:
- Returns:
Response table and error. The response contains:
- ResponseHeader (ResponseHeader)
Service-level status and diagnostic information.
- SubscriptionId (UInt32)
Identifier of the Subscription that supplied the response.
- AvailableSequenceNumbers[] (UInt32 array)
Sequence numbers still retained by the Server for Republish.
- MoreNotifications (boolean)
truewhen more notifications are queued for the Subscription.- NotificationMessage (table)
Notification or keep-alive message.
- SequenceNumber (UInt32)
Sequence number used for acknowledgement and Republish.
- PublishTime (DateTime)
Time at which the Server prepared the message.
- NotificationData[] (NotificationData)
Notification payloads, or an empty array for a keep-alive.
- Results[] (StatusCode array)
One result for every entry in SubscriptionAcknowledgements, in the same order.
- DiagnosticInfos[] (array)
Optional diagnostic information corresponding to
Results.
errorisnilon success or contains a service-level StatusCode.
client:republish
Request a retained NotificationMessage by sequence number.
- client:republish(params[, msgCallback])
- Params:
(table)
- SubscriptionId (UInt32)
Identifier of the Subscription that produced the missing message.
- RetransmitSequenceNumber (UInt32)
NotificationMessage.SequenceNumber of the retained message to retrieve.
- MsgCallback:
- Returns:
Response table and error. The response contains:
- ResponseHeader (ResponseHeader)
Service-level status and diagnostic information.
- NotificationMessage (table)
Retained message. It contains SequenceNumber (UInt32),
PublishTime(DateTime), and NotificationData, with the same layout as a publish response.
errorisnilon success or contains a service-level StatusCode, such as the code returned when the sequence number is no longer available.
client:call
Call a method node on the server.
client:renewSecureChannel
Renew the current OPC UA TCP secure channel token.
- client:renewSecureChannel(timeoutMs[, msgCallback])
- TimeoutMs:
(uint32) Requested token lifetime in milliseconds.
- MsgCallback:
- Returns:
OpenSecureChannelResponse, error
client:checkSecureChannel
Renew the secure channel if the internal renewal timer has marked it as stale.
- client:checkSecureChannel()
- Returns:
error, or
nilwhen no renewal was required or renewal succeeded.
client:connected
Check whether the underlying transport is connected.
- client:connected()
- Returns:
truewhen connected, otherwisefalse.
client:closeSession
Terminate an active Session.
- client:closeSession([msgCallback])
- MsgCallback:
- Returns:
CloseSessionResponse,error
Example:
resp, err = client:closeSession()
if err == nil then
trace("Session closed")
end
client:closeSecureChannel
Terminate a SecureChannel.
- client:closeSecureChannel([msgCallback])
- MsgCallback:
- Returns:
client:disconnect
Close the client’s server socket connection. Calling this method also closes any open channel.
- client:disconnect()
- Returns:
response, 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 occurred during processing of request.