Uni-Directional OPCUA to MQTT Publisher using JavaScript (RAW Payload)

Last Code Revision Date: 03-Sep-2025

OPC UA to MQTT Raw Payload Publisher

This project connects to an OPC UA server, reads node values, and publishes each value as a raw payload to its own MQTT topic. Each tag gets its own topic, and the payload is the raw value (not JSON). The application is designed for reliability, automatic reconnection, and easy configuration.

Features

  • Reads multiple OPC UA nodes at regular intervals
  • Publishes each tag’s value as a raw payload to its own MQTT topic
  • Automatic reconnection for both OPC UA and MQTT connections (startup and runtime)
  • Supports MQTT authentication (username/password) and TLS/SSL
  • Easily extendable for OPC UA authentication (username/password)
  • Clean, modular, and maintainable code

Configuration

Edit config.json to set up OPC UA and MQTT connection details:

{
    "opcua": {
        "endpointUrl": "opc.tcp://Parrot:4840/OPCUA/SimulationServer",
        "nodesToRead": [
            { "name": "Constant", "nodeId": "ns=3;i=1001" },
            { "name": "Counter", "nodeId": "ns=3;i=1002" }
            // ... more nodes ...
        ],
        "username": "",         // Optional: for OPC UA authentication
        "password": ""          // Optional: for OPC UA authentication
    },
    "mqtt": {
        "hostname": "mqtt://broker.hivemq.com",
        "port": 1883,
  "masterTopic": "opcua_data", // Used as a prefix for each tag's topic
        "username": "",         // Optional: for MQTT authentication
        "password": "",         // Optional: for MQTT authentication
        "qos": 1,               // Optional: 0, 1, or 2
        "tls": false            // Optional: true for secure connection
        // "ca": "path/to/ca.crt",    // Optional for TLS
        // "cert": "path/to/client.crt", // Optional for TLS
        // "key": "path/to/client.key"   // Optional for TLS
    }
}

Usage

  1. Install dependencies:
    npm install
    
  2. Run the publisher:
    node index.js
    

Extending Authentication

  • MQTT: Add username and password in the mqtt section of config.json.
  • OPC UA: Add username and password in the opcua section and update the code to use these when creating the session.

Reliability

  • The application will automatically reconnect to the OPC UA server and MQTT broker if connections are lost at startup or during runtime.
  • All resources are cleaned up before reconnecting.

Example MQTT Output

Each tag’s value is published as a raw payload to its own topic. The topic format is:

<masterTopic>/<tagName>

or, if no masterTopic is set:

<tagName>

The payload is the raw value of the tag, e.g.:

Topic: opcua_data/Constant
Payload: 42

Topic: opcua_data/Counter
Payload: 123

Each tag is published individually to its own topic, not as a JSON array.

34.03$

SKU 91 Categories ,

Your Automation Partner. Streamline workflows, and drive productivity. Explore our innovative solutions.