Custom Payload
  • 15 Jul 2025
  • 4 Minutes to read
  • PDF

Custom Payload

  • PDF

Article summary

A custom payload for MQTT Client refers to a user-defined structure or format for the data transmitted in the MQTT protocol message's payload field. MQTT itself does not impose any restriction or standard on payload content—payloads can be plain text, binary data, JSON, or any encoding required by your application. The format and content are fully customizable to match the needs of the devices or services communicating over MQTT.

Utilities

All scripts in custom parsers have access to these utilities:

  • Buffer

This represents a Node.js Buffer object. This can be used to manipulate a Buffer instance directly, for example when the serialization format is set to None and deserialization has not occurred. More information about buffer can be found in the Node.js Buffer Section.

  • Moment

Moment.js is a Javascript library used to easily format and parse timestamps. The provided version of Moment also includes Moment timezone, by using moment.tz(). More information can be found at Moment.js and Moment Timezone.

  • Sprint

Sprintf is a function used to format strings using a format string and one or more variables. It is similar to the behaviour of the C++ sprintf function. Format strings can use placeholders by means of special characters preceded by a % character. These placeholders will be substituted by variables passed as arguments. This function has the following signature: sprintf(format, …args)

See below for the valid placeholders for format strings.

  • Integer: %d or %i
  • String: %s
  • Binary: %b
  • JSON: %j
  • ASCII character in decimal: %c
  • Scientific notation: %e 
  • Floating point: %f
  • Fixed point: %g
  • Octal: %o
  • Unsigned integer: %u
  • Hexadecimal lowercase: %x
  • Hexadecimal uppercase: %X
  • Node buffer: %r

All formats that admit decimal numbers, such as floating point or scientific notation, can be configured to specify the required number of decimals to be displayed by using the format %.xY, where x is the number of decimals, and Y is the format used (f, for floating point; e, for exponential, etc.). For example, to show a floating-point number with 2 decimals, the following format must be used: %.2f.

  • $.logger
     
    The 
    $.logger object is used to log messages to disk, which can be used for both debugging and informative purposes. The log file can be found at N3uron/log/MqttClientInstance/. It is shared by both the internal module code and any messages written by the custom parsers. The following are all functions that can be used to write to the log file:
  • $.logger.error(message, …arguments)
  • $.logger.warn(message, …arguments)
  • $.logger.info(message, …arguments)
  • $.logger.debug(message, …arguments)
  • $.logger.trace(message, …arguments)

     Each of these functions takes a format string (in the same format as sprintf) and an optional list of arguments used to replace the placeholders in the format string. 

Publisher Custom Payload

To define a custom payload for the MQTT Client Publisher in N3uron, you will create a JavaScript script that precisely structures the data to be sent as the MQTT payload. 

Steps to Create Your Custom Payload Script

  1. Access the MQTT Client Configuration and choose the appropriate Publisher agent configuration.
  2. Navigate to the Message format section and set Serialization to Custom, which enables custom scripting.
  3. Open the javascript editor by clicking the button next to the Script field.
  4. Create a JavaScript script to generate a payload tailored to specific requirements. Within the MQTT Client Publisher Custom payload context, the objects $.input and $.output are structured as follows:
    • $.input: The array of events. Every event have this structure:
      {
        "tagName": "TAG_ADDRESS",
        "data": {
          "value": "TAG_VALUE",
          "quality": "TAG_QUALITY",
          "ts": "EPOCH_TIMESTAMP"
        }
      }
      • tagName: This is the path of the tag.
      • value: The actual tag value (any type).
      • quality: This is the quality of the tag for this event..
      • ts: This value is the timestamp of the event. It is a number in epoch format with milliseconds.
    • $.output: The payload to send is the result of the parsing function and must be either a string or a Buffer.

      Example of a custom payload script:
      // Log how many wind‐turbine events we're processing
      $.logger.debug("Parsing %d turbine events", $.input.length);
      
      // Build the result array for turbine telemetry
      const result = [];
      
      for (const event of $.input) {
        // Convert tag path from “/turbine/rotorSpeed” → “turbine.rotorSpeed”
        const tagPath = event.tagName.replace(/\//g, ".");
        
        result.push({
          t:  tagPath,                              // sensor path (e.g. "turbine.bladeAngle")
          v:  event.data.value,                     // measurement value (e.g. RPM, °)
          q:  event.data.quality,                   // OPC quality code (decimal)
          ts: new Date(event.data.ts).toISOString() // ISO timestamp of reading
        });
      }
      
      // Serialize array to JSON string for MQTT payload
      $.output = JSON.stringify(result);
      
      // Example final $.output (string):
      // '[{"t":"turbine.rotorSpeed","v":1530,"q":192,"ts":"2025-07-15T14:30:00.000Z"}, …]'
      

  5. Compression: Reduces the size of the payload data before sending, optimizing for bandwidth and transmission time. 
    • None: No compression is applied (data is sent as-is).
    • GZip: Compresses data using the GZip algorithm.
    • Deflate: Uses the Deflate compression method.
  6. Compression Level: Defines the degree of data compression, balancing the trade-off between processing speed and resulting output size.
    • Best speed: Fastest operation, but larger output size.
    • Default compression: Balanced speed and compression.
    • Best compression: Smallest output size, but slower to process.
  7. Encoding: Defines how the final payload is represented for transmission and compatibility on the receiver side.
    • UTF8: : Encodes the message into an UTF8 string. Only recommended for uncompressed JSON (since JSON is serialized by default into an UTF8).
    • Binary: : Encodes the message into a binary buffer, which offers the smallest possible size. This is the recommended format for everything but uncompressed JSON. However, not all brokers support this feature, as some will convert the message into a string, dropping the non-printable characters and making it impossible to parse at the endpoint.
    • Base64: : Encodes the message as a Base64 string. Compatible with all brokers that accept strings, at the expense of a larger message size (4/3 of the original size) and needing to transform the Base64 string back into a binary buffer at the endpoint.
    • Hex: : Encodes the message as a hexadecimal string. In general, this is not recommended since it doubles the message size. However, converting from hexadecimal back to binary is simpler than from Base64 to binary.
  8. Save the script and test the Publisher Custom Payload to verify that the outgoing message format aligns with expectations.



MQTT Client Full Product Details 


Was this article helpful?