Main Content

OPC UA Components

Overview

Industrial Communication Toolbox™ provides an OPC UA client to connect to OPC UA servers. Using the client, you connect to the server, query server status, browse the server namespace, read and write current values, and read historical values from nodes on the server. The client retrieves historical data from the server as OPC data objects, which you can use to process historical data for common analysis tasks.

OPC UA Client

You construct the OPC UA client using the opcua function. You set the security configuration for the connection using setSecurityModel. You connect the client to the server using connect, optionally passing user authentication credentials. You can also query the server for extended status information using getServerStatus. The client includes a number of properties describing the server capabilities, including supported security models and user authentication options. You can set these properties in the client objects.

PropertyDescription
Server Information
NameServer name.
HostnameServer host name or IP address.
PortPort number used for TCP/IP connections to the server.
EndpointUrlURL to use for connection to the server.
Connection Information
TimeoutTime to wait for all operations on the server to complete.
StatusStatus of the client: 'Connected' or 'Disconnected'.
ServerStateState of the server: 'Running', 'Failed', 'No Configuration','Suspended', 'Shutdown', 'Test', 'Comms Fault', 'Unknown'.
Security Information
MessageSecurityModeMessage security mode specified for connection.
ChannelSecurityPolicyChannel security policy specified for connection.
EndpointsAvailable endpoints for server.
Server Limits (These properties are available only after you connect the client to the server)
MinSampleRateMinimum sample rate in seconds that the server can generally support.
MaxReadNodesMaximum number of nodes supported per read operation.
MaxWriteNodesMaximum number of nodes supported per write operation.
MaxHistoryValuesPerNodeMaximum number of nodes supported by historical read operations.
MaxHistoryValuesPerNodeMaximum history values returned per node in historical read operations.

You can use the client to communicate with the server, including browsing the server name space, reading and writing current values, and reading historical values from the server.

OPC UA Node

The OPC UA client includes a Namespace property, which contains the top level information of the server’s namespace as an array of nodes. You can graphically browse through the server's namespace and select nodes using the browseNamespace function. An OPC UA node variable describes the node on the server and contains other subnodes in the Children property. You create a new OPC UA node object using the opcuanode function.

Nodes have a NodeType that can be 'Object', 'Variable', or 'Method'. Object nodes have no value associated with them and are used purely for organizing the namespace of the server. Variable nodes store current values, representing a sensor or actuator value associated with the server. Method nodes represent function calls to object, which can be invoked to execute object specific processes.

You can get these properties in the node objects.

PropertyDescription
Node Information
NameDisplay name for the node.
DescriptionCharacter vector describing the node.
NamespaceIndexNamespace index for the node.
IdentifierUnique identifier with data type as a character vector or integer.
NodeTypeType of node: 'Object', 'Method', or 'Variable'.
Hierarchy Information
ParentParent node of the node.
ChildrenChild nodes of the node.
Variable Information
ServerDataTypeOPC UA data type for node.
AccessLevelCurrentUser access level to current value: 'none', 'read', 'write', 'read/write'.
AccessLevelHistoryUser access level to historical values: 'none', 'read', 'write', 'read/write'.
HistorizingTrue if the server is storing history for the node data.
Method Information
ExecutableTrue if the node is executable.
UserExecutableTrue if the node is executable by the current user.
NumInputsNumber of inputs required by the node.
InputTypesData types of input arguments.
NumOutputsNumber of outputs returned by the node.
OutputTypesData types of output arguments.

Servers can choose to historize nodes (store previous data values for that node). The Historizing property of a Node defines whether a server is historizing the node. If you try to retrieve historical data from a Variable node with Historizing set to false, the server does not return data and the client displays an error.

You can read and write current values, and retrieve historical data, using the node variables directly. This is simply a short-hand for performing the same operations on the node Client property. Use these functions to perform various operations on Node objects.

FunctionSyntaxDescription
findNodeByIdFoundNode = findNodeById(NodeList,NsInd,Id)Find a node by namespace index and identifier.
findNodeByNameFoundNodes = findNodeByName(NodeList,NodeName)Find a node by name.
getAllChildrenAllChildNodes = getAllChildren(StartNode)Recursively retrieve all children of this node.
getNodeAttributesValues = getNodeAttributes(UaClient,NodeList,AttributeIds)Retrieve all or selected attributes from the node as a structure.
invoke[Value,Timestamp,Quality] = invoke(uaClient,uaNode)Call a method node for execution.
isEmptyNodetf = isEmptyNode(NodeObj)True if the node is empty.
isObjectTypetf = isObjectType(NodeObj)True if the node is an object node.
isVariableTypetf = isVariableType(NodeObj)True if the node is a variable node.
readAtTimeUaData = readAtTime(UaClient,NodeList,TimeVector)Read interpolated history data from the server at specific times.
readHistoryUaData = readHistory(UaClient,NodeList,StartTime,EndTime)Read historical data stored on the server for the node.
readProcessedUaData = readProcessed(UaClient,NodeList,AggregateFn,AggrInterval,StartTime,EndTime)Read processed history data from the server.
readValue[Values,Timestamps,Qualities] = readValue(UaClient,NodeList)Read current value of the node, including quality and timestamp.
subscribeSubscrObj = subscribe(UaClient,NodeList,DataChangeFcn)Subscribe to data changes on variable nodes.
writeValuewriteValue(UaClient,NodeList,Values)Write values to nodes on the server.

OPC UA Data

Data retrieved from OPC UA servers includes the data value accompanied by a measure of data quality and a timestamp. The Quality property represents how accurately the data Value property reflects the actual source value attached to the server. The Timestamp property represents the time at which the server recorded the value or received a notification from the data source that the value is current.

When you retrieve current values, the Value, Quality, and Timestamp properties are retrieved as separate arrays. When you retrieve historical values, OPC UA servers might return a different number of Value, Quality, and Timestamp arrays for each node. This data is packaged into an OPC UA data object, which allows you to process this data for common analysis tasks. You can construct OPC UA data objects using the readHistory, readAtTime, or readProcessed functions of an OPC UA client. You can get these properties in the data objects.

PropertyDescription
NameName of the node, specified as character vector.
Timestampm-by-1 datetime vector of time stamps.
Valuem-by-1 vector of data values.
Qualitym-by-1 cell array of OPC UA Qualities.

You can process the data packaged into an OPC UA data object using these functions.

FunctionSyntaxDescription
summarysummary(DObj)Display a summary of the OPC data object.
plotplot(DObj)Plot OPC data using line series plots.
stairsstairs(DObj)Plot stairstep graph of OPC data.
single, double, int8, int16, int32, int64, uint8, uint16, uint32, uint64, logicalnewData = single(DObj)Convert OPC data object to specified data type.
tableDataTable = table(DObj)Convert OPC data object to an m-by-3 table.
tsunionNewObj = tsunion(DObj)Timestamp union of OPC data object.
tsintersectNewObj = tsintersect(DObj)Timestamp intersection of OPC data object.
resampleNewObj = resample(DObj,NewTS)Resample OPC data object to defined timestamps.
appendNewObj = append(DObj1,DObj2)Combine OPC data objects in the time dimension without adding or removing data.
arrayHasSameTimestamptf = arrayHasSameTimeStamp(DObj)True if all elements of OPC HDA data object have the same timestamp vector.
filterByQualityNewObj = filterByQuality(DObj,'QualityID')Filter OPC data by quality characteristics.
getIndexFromNameind = getIndexFromName(DObj,'Name')Return OPC data with matching names.

For an example of working with OPC UA data, see Visualize and Preprocess OPC UA Data.

OPC UA Quality

OPC UA quality values are unsigned 32-bit integer values. These values encapsulate various characteristics about the quality of the data obtained from current or historical data read operations. The characteristics include the major quality, quality substatus, value limits, and history origin. You can query these characteristics individually by using their corresponding function with the Quality variable that is returned in the read operation.

FunctionSyntaxDescription
getMajorStringQualIdmStr = getMajorString(QualIdObj)Return major string for quality: 'Good', 'Bad' or 'Uncertain'.
getSubStringQualIdsStr = getSubString(QualIdObj)Return quality sub-string, describing the condition of the specific quality.
getLimitStringQualIdlStr = getLimitString(QualIdObj)Return limit string for quality: 'Low Limit', 'High Limit', 'Constant', or empty.
getHistoryStringQualIdhStr=getHistoryString(QualIdObj)Return history origin as 'Raw', 'Calculated' or 'Interpolated' and characteristics as 'Extra Data', 'Partial' or 'Multi Value'.
getFullStringQualIdfStr = getFullString(QualIdObj)Return the full quality string composed of 'major:sub (limit, history)'.
cellstrIdCell = cellstr(QualIdObj)Convert Quality ID into cell array of string descriptions.
uint32IdInt = uint32(QualIdObj)Return raw quality integer.
isGoodtf = isGood(QualityId)True if the major quality is good.
isBadtf = isBad(QualityId)True if the major quality is bad.
isUncertaintf = isUncertain(QualityId)True if the major quality is uncertain.
isLimitedtf = isLimited(QualityId)True if the limit status is nonzero. Can be qualified with 'high', 'low', or 'constant'.
isRawtf = isRaw(QualityId)True if the quality history origin is Raw.
isCalculatedtf = isCalculated(QualityId)True if the quality history origin is Calculated.
isInterpolatedtf = isInterpolated(QualityId)True if the quality history origin is Interpolated.
isPartialtf = isPartial(QualityId)True if the history Partial bit is set. The server sets this bit during history reads, when the returned value is calculated with an incomplete interval.
isExtraDatatf = isExtraData(QualityId)True if the history Extra Data bit is set. The server sets this bit during history reads, when the returned value is a raw data value that masks other data at the same timestamp.
isMultiValuetf = isMultiValue(QualityId)True if the history Multi Value bit is set. The server sets this bit during history reads, when multiple data values match the required processed data criteria.

Working with Time in OPC UA

OPC UA servers return timestamps for server status and for all current and historical read operations. The timestamp represents the time at which the server recorded the data value returned in the read operation. Timestamps are represented in MATLAB® as datetime values. The OPC UA server always returns the datetime values in the time zone of the MATLAB client used to retrieve the data. OPC UA historical read functions require time ranges or specific timestamp arrays over which to retrieve historical data. You can specify time ranges using MATLAB datetime values or as MATLAB date numbers. Any numeric value passed as a timestamp is interpreted as a MATLAB date number. For functions requiring a start and end timestamp, you can also pass a start timestamp and a duration.