OPC-UA Integration
OPC-UA Integration connects ThingsBoard Edge to an OPC UA server. It reads the nodes you subscribe to and converts their values into telemetry and attributes. It also supports downlink, so the Edge can write values and call methods on OPC UA nodes, for example from an RPC command.
This guide connects the Edge to the OPC UA C++ Demo Server, shows the telemetry of its air conditioner units on a dashboard, and switches a unit on and off with an RPC command.
Prerequisites
Section titled “Prerequisites”- A ThingsBoard server with tenant administrator access. The templates are created there.
- A ThingsBoard Edge instance connected to the server.
- The OPC UA C++ Demo Server (Windows only), reachable from the Edge.
After the installation, open the UA Admin Dialog and note the Hostname / IP and Port on its UA Endpoints tab. Then start UaCPPServer. Its console prints the endpoint URL in the form opc.tcp://<host>:<port>, for example opc.tcp://10.7.3.145:48010. You need the host and port for the integration.
Create converter templates
Section titled “Create converter templates”Converter templates are created on the server.
Uplink converter
Section titled “Uplink converter”For each scanned node, the integration passes the node values as the payload and the node details as metadata:
Payload:
{ "temperature": "72.15819999999641"}Metadata:
{ "opcUaNode_namespaceIndex": "3", "opcUaNode_name": "AirConditioner_1", "integrationName": "OPC-UA air conditioners", "opcUaNode_identifier": "AirConditioner_1", "opcUaNode_fqn": "Objects.BuildingAutomation.AirConditioner_1"}The converter uses opcUaNode_name as the device name, saves temperature, humidity, and powerConsumption as telemetry, and state as an attribute. It also saves namespaceIndex as a client attribute, which the downlink converter needs later.
-
On the server, go to Edge management > Templates and open the Converter tab. Click Add data converter and select Create new converter.
-
Set Converter type to Uplink, select OPC-UA as the Integration type, and enter the name
Air conditioner uplink. -
In Main decoding configuration, select TBEL, paste the following script, and click Add:
/** Decoder **/var data = decodeToJson(payload);var deviceName = metadata['opcUaNode_name'];var namespaceIndex = metadata['opcUaNode_namespaceIndex'];var deviceType = 'airconditioner';var result = {deviceName: deviceName,deviceType: deviceType,telemetry: {},attributes: {namespaceIndex: namespaceIndex}};if (data.temperature != null) {result.telemetry.temperature = toFixed(data.temperature, 2);}if (data.humidity != null) {result.telemetry.humidity = toFixed(data.humidity, 2);}if (data.powerConsumption != null) {result.telemetry.powerConsumption = toFixed(data.powerConsumption, 2);}if (data.state != null) {result.attributes.state = data.state == '1' ? true : false;}/** Helper functions 'decodeToString' and 'decodeToJson' are already built-in **/return result;
To change a converter later, open it on the Converter tab, click the pencil icon, edit the script, and click the checkmark icon. The change is pushed to every Edge that uses it.
Downlink converter
Section titled “Downlink converter”The downlink converter turns an RPC command from the Edge into OPC UA write operations and method calls. Its output has this structure:
[{ "contentType": "JSON", "data": "{\"writeValues\":[],\"callMethods\":[{\"objectId\":\"ns=3;s=AirConditioner_1\",\"methodId\":\"ns=3;s=AirConditioner_1.Stop\",\"args\":[]}]}", "metadata": {}}]| Field | Description |
|---|---|
contentType |
JSON, TEXT, or BINARY. OPC-UA uses JSON. |
data.writeValues |
OPC UA write operations. Each has a nodeId (ns=<index>;<type>=<id>) and a value. |
data.callMethods |
OPC UA method calls. Each has an objectId, a methodId, and args. |
metadata |
Not used by the OPC-UA integration. Leave it empty. |
The encoder builds the node IDs from two metadata keys, deviceName and cs_namespaceIndex. The rule chain adds them to the message before it reaches the integration.
-
On the Converter tab, click Add data converter and select Create new converter.
-
Set Converter type to Downlink, select OPC-UA as the Integration type, and enter the name
Air conditioner downlink. -
In Main encoding configuration, select TBEL, paste the following script, and click Add:
/** Encoder **/var data = {writeValues: [],callMethods: []};if (msgType === 'RPC_CALL_FROM_SERVER_TO_DEVICE') {if (msg.method === 'setState') {var targetMethod = msg.params === 'true' ? 'Start' : 'Stop';var writeValue = {nodeId: 'ns=' + metadata['cs_namespaceIndex'] + ';s=' + metadata['deviceName'],value: msg.params};data.writeValues.push(writeValue);var callMethod = {objectId: 'ns=' + metadata['cs_namespaceIndex'] + ';s=' + metadata['deviceName'],methodId: 'ns=' + metadata['cs_namespaceIndex'] + ';s=' + metadata['deviceName'] + '.' + targetMethod,args: []};data.callMethods.push(callMethod);}}var result = {contentType: "JSON",data: JSON.stringify(data),metadata: {}};return result;
Create integration template
Section titled “Create integration template”-
On the server, go to Edge management > Templates, open the Integration tab, and click Add integration.
-
On the Basic settings step, select OPC-UA as the Integration type and enter the name
OPC-UA air conditioners. Click Next. -
On the Uplink data converter step, select Select existing, choose
Air conditioner uplink, and click Next. -
On the Downlink data converter step, select Select existing, choose
Air conditioner downlink, and click Next. -
On the Connection step, fill in the connection and mapping fields:
Field Value Host ${{endpointHost}}. The placeholder is replaced by theendpointHostserver attribute of each Edge.Port The port of the OPC UA server endpoint, for example 48010Endpoint Leave empty Security None Identity Anonymous Mapping type Fully Qualified Name Device Node Pattern Objects\.BuildingAutomation\.AirConditioner_\d+$Device Node Pattern is a regular expression. Nodes whose fully qualified name matches it become devices. This pattern matches
AirConditioner_1toAirConditioner_N. Keep the defaults under Advanced settings (Scan period in seconds10, Timeout in milliseconds5000). -
Under Subscription tags, fill in the empty first row, then click Add subscription tag for each further row. The keys must match the names used in the uplink converter.
Key Path statestatetemperaturetemperaturehumidityhumiditypowerConsumptionpowerConsumption -
Click Add.
Assign the integration to the Edge
Section titled “Assign the integration to the Edge”Add the endpointHost attribute first. Without it, the assignment dialog warns Edge has missing attribute(s) and the Edge receives the literal placeholder.
-
On the server, go to Edge management > Edges and click the Edge. On the Attributes tab, with the Server attributes scope selected, click +. Enter
endpointHostas the key and the host name or IP address of the OPC UA server as the value. Click Add. -
On the Details tab, click Manage integrations, then Assign to edge (+). Select
OPC-UA air conditionersand click Assign. -
Log in to the Edge and go to Integrations > Integrations. Open the integration. Host shows the attribute value instead of the placeholder.
Verify the uplink data
Section titled “Verify the uplink data”As soon as the integration starts on the Edge and connects to the OPC UA server, data flows automatically.
-
On the Edge, go to Integrations > Integrations, open the integration, and select the Events tab. Uplink events with status OK appear on every scan.
-
Go to Devices & assets > Devices. Ten devices, AirConditioner_1 to AirConditioner_10, are listed.
-
Open one of them and select the Latest telemetry tab. The
temperature,humidity, andpowerConsumptionvalues update on every scan. The Attributes tab shows the client attributesstateandnamespaceIndex.
Configure the rule chain for downlinks
Section titled “Configure the rule chain for downlinks”To send an RPC command to an OPC UA node, add three nodes to the root rule chain of the Edge. The downlink converter reads deviceName and cs_namespaceIndex from the message metadata. Two enrichment nodes add these values, and an integration downlink node passes the message to the integration.
-
On the Edge, go to Data processing > Rule chains and open Edge Root Rule Chain.
-
In the node search field, type
originator fieldsand drag the originator fields node onto the canvas. Name itadd device name. In Originator fields mapping, change the target keys of the default rows: Name todeviceNameand Profile name todeviceType. Keep Add mapped originator fields to at Metadata and click Add. -
Search for
originator attributesand drag the originator attributes node onto the canvas. Name itget namespaceIndex. In Client attributes, addnamespaceIndex. Keep Add originator attributes to at Metadata and click Add. Client attributes are added to the metadata with thecs_prefix, so the encoder readscs_namespaceIndex. -
Search for
integration downlinkand drag the integration downlink node onto the canvas. Name itpush to integration, selectOPC-UA air conditionersin the Integration field, and click Add. -
Connect the nodes:
- message type switch to originator fields with the RPC Request to Device label.
- originator fields to originator attributes with the Success label.
- originator attributes to integration downlink with the Success label.
-
Click the checkmark icon (Apply changes) to save the rule chain.
Import the dashboard
Section titled “Import the dashboard”The Airconditioners dashboard shows the telemetry of all units and has a switch that sends the setState RPC command. Import it on the server and assign it to the Edge.
-
Download airconditioners_dashboard.json.
-
On the server, go to Monitor > Dashboards, open the Groups tab, and click Add entity group. Enter the name
Air conditionerand click Add. -
Open the group, click the Import dashboard icon (upload arrow), select the downloaded file, and click Import.
-
Go to Edge management > Edges and click the Edge. On the Details tab, click Manage dashboard groups, then Assign to edge (+). Select the
Air conditionergroup and click Assign.
Send a downlink command
Section titled “Send a downlink command”-
On the Edge, go to Monitor > Dashboards and open the Airconditioners dashboard. It shows the live telemetry of all units.
-
In the Entities table, click the gear icon of a unit to open its details.
-
Click the Round switch. The dashboard sends the
setStateRPC command, the rule chain forwards it to the integration, and the downlink converter calls theStopmethod of the node. The unit turns off: the Airconditioner status light turns gray, the temperature and humidity start to rise, and the power consumption drops to zero. -
To check the downlink on the Edge, open the Events tab of the integration. A Downlink event with status OK appears. The Events tab of
Air conditioner downlinkunder Integrations > Data converters shows the encoded message.
Was this helpful?