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, localhost is 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)

Full source

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
    }
  }
}

Full source

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

  • http://hostname:port/path

  • https://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.TcpBinary is used with the opc.tcp scheme.

  • ua.TranportProfileUri.HttpsBinary

  • ua.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")

Full source

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

Full source

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")

Full source

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, or ua.SecurityPolicy.Basic256Sha256.

SecurityMode:

(number) Message security mode. Use ua.MessageSecurityMode.None, ua.MessageSecurityMode.Sign, or ua.MessageSecurityMode.SignAndEncrypt.

RemoteCert:

Optional remote server certificate. Required by secure policies that need the server certificate before the session response supplies it.

MsgCallback:

Message callback

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")

Full source

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

Full source

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

Full source

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:

Message callback

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

Full source

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:

Message callback

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.."'")

Full source

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() or client: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 ActivateSession request body. Use this form when constructing ClientSignature, UserIdentityToken, UserTokenSignature, or Locales yourself.

MsgCallback:

Message callback

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

Full source

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:

Message callback

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

Full source

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:

Message callback

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

Full source

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:

Message callback

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()

Full source

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:

Message callback

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

Full source

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:

Message callback

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. 0 requests no limit.

PublishingEnabled (boolean)

true to publish queued notifications. false creates the Subscription with publishing disabled.

Priority (Byte)

Relative publishing priority when several Subscriptions are ready. 0 is the lowest priority.

MsgCallback:

Message callback

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.

error is nil on success. A service-level failure is returned as an OPC UA StatusCode in error.

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. 0 requests no limit.

Priority (Byte)

New relative publishing priority.

MsgCallback:

Message callback

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.

error is nil on 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:

Message callback

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 in subscriptionIds in the same order. A result can fail even when the service call succeeds.

DiagnosticInfos[] (array)

Optional diagnostic information corresponding to Results.

error is nil on 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)

true to enable publishing or false to stop publishing queued notifications. Sampling is not disabled.

SubscriptionIds[] (UInt32 array)

Identifiers of the Subscriptions to update.

MsgCallback:

Message callback

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.

error is nil on 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, or Neither.

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, or Reporting.

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. 0 requests 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 a Body with these fields:

Trigger (DataChangeTrigger)

Status, StatusValue, or StatusValueTimestamp selects which changes produce notifications.

DeadbandType (DeadbandType)

None, Absolute, or Percent selects 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 DeadbandType is None.

QueueSize (UInt32)

Requested number of notifications retained for this item.

DiscardOldest (boolean)

When the queue is full, true discards its oldest value; false discards the newest value.

MsgCallback:

Message callback

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 StatusCode is ua.StatusCode.Good and 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.

error is nil when the service call succeeds. Inspect every Results[].StatusCode for 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, or Neither.

ItemsToModify[] (array)

MonitoredItems to modify. Each element contains:

MonitoredItemId (UInt32)

createMonitoredItems.Results[].MonitoredItemId.

RequestedParameters (table)

New sampling, filter, and queue parameters. This table replaces the existing settings; it is not a partial update. All fields below except Filter must 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. 0 requests 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 a Body containing DataChangeTrigger, DeadbandType, and DeadbandValue.

QueueSize (UInt32)

New requested number of notifications retained for this MonitoredItem.

DiscardOldest (boolean)

When the queue is full, true discards its oldest value; false discards the newest value.

MsgCallback:

Message callback

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.

error is nil when the service call succeeds. Inspect every Results[].StatusCode for 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: Disabled stops sampling, Sampling samples without reporting, and Reporting samples and reports queued notifications.

MonitoredItemIds[] (UInt32 array)

Identifiers of the MonitoredItems to update. Each value comes from createMonitoredItems.Results[].MonitoredItemId.

MsgCallback:

Message callback

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.

error is nil on 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:

Message callback

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.

error is nil on 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:

Message callback

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)

true when 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.

error is nil on 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:

Message callback

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.

error is nil on 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:call(objectId, methodId, inputArguments[, msgCallback])
ObjectId:

(NodeId) NodeId of the object that owns the method.

MethodId:

(NodeId) NodeId of the method to call.

InputArguments:

(array) Input argument values for the method.

MsgCallback:

Message callback

Returns:

Call response, error

client:renewSecureChannel

Renew the current OPC UA TCP secure channel token.

client:renewSecureChannel(timeoutMs[, msgCallback])
TimeoutMs:

(uint32) Requested token lifetime in milliseconds.

MsgCallback:

Message callback

Returns:

OpenSecureChannelResponse, error

client:checkSecureChannel

Renew the secure channel if the internal renewal timer has marked it as stale.

client:checkSecureChannel()
Returns:

error, or nil when no renewal was required or renewal succeeded.

client:connected

Check whether the underlying transport is connected.

client:connected()
Returns:

true when connected, otherwise false.

client:closeSession

Terminate an active Session.

client:closeSession([msgCallback])
MsgCallback:

Message callback

Returns:

CloseSessionResponse,error

Example:

resp, err = client:closeSession()
if err == nil then
  trace("Session closed")
end

Full source

client:closeSecureChannel

Terminate a SecureChannel.

client:closeSecureChannel([msgCallback])
MsgCallback:

Message callback

Returns:

CloseSecureChannelResponse,error

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.