--- title: "MQTT Client | Custom Payload Example | N3uron KB V1.22" slug: "mqtt-client-custom-payload-example" description: "MQTT Client is a N3uron module designed to connect to any MQTT broker in order to send and receive tag events. Mqtt Client implements a bidirectional…" updated: 2026-11-24T09:56:00Z published: 2026-11-24T09:56:00Z canonical: "docs.n3uron.com/mqtt-client-custom-payload-example" --- > ## Documentation Index > Fetch the complete documentation index at: https://docs.n3uron.com/llms.txt > Use this file to discover all available pages before exploring further. # Custom Payload This article shows how to make a publisher with a custom payload, and gives examples of scripts. For the script objects, the utilities and the settings, refer to [**Custom Payload**](/v122/docs/mqtt-client-custom-payload). ## **Create a custom payload publisher** To make a publisher with a custom payload, do these steps: 1. **Make** an **MQTT Client** module instance. Refer to [**MQTT Client Configuration**](/v122/docs/mqtt-client-configuration). 2. **Add** a connection to the broker. 3. In the **Model** panel, **add a publisher** to the connection. 4. **Set the Topic** of the publisher, for example **greenlake/bess01/bb01/rack01**. 5. **Add the Tag Filters** of the publisher, for example **/GREENLAKE/BESS01/BB01/BMS01/RACK01/**. 6. In the **Message format** section, **set Serialization to** **Custom**. 7. To get the engineering units and the format of the tags in the script, **set Include tag metadata to** **Yes**. ![Publisher with Serialization set to Custom and Include tag metadata set to Yes](https://cdn.document360.io/54093ab5-6b22-4542-a265-04377931f11a/Images/Documentation/MQTT-CustomPayload-Publisher.webp) 8. **Click** the button next to the **Script** field. The **Script editor** opens. 9. **Paste** the [**Script template**](/v122/docs/mqtt-client-custom-payload#script-template) or the script of an example. ![Script editor with the script template](https://cdn.document360.io/54093ab5-6b22-4542-a265-04377931f11a/Images/Documentation/MQTT-CustomPayload-ScriptEditor.webp) 10. **Click Save** in the **Script editor**. 11. **Save the configuration**. **Click Yes** to restart the module. 12. **Published** to the topic with an MQTT client. With the script template, the topic is **greenlake/bess01/bb01/rack01/starter**. 13. **Make sure** that the messages arrive. ## **Examples** Most examples use the tags of a battery rack in a BESS plant (**/GREENLAKE/BESS01/BB01/BMS01/RACK01/**). Each of these examples shows the script and a message that the broker received during a test. Some examples also show the settings to change. ### **Replace the slashes of the tag path with dots** This example replaces each slash (/) of the tag path with a dot. For example, **/turbine/rotorSpeed** becomes **.turbine.rotorSpeed**. The script sends an array of records with short property names. ```javascript // Write the number of wind-turbine events to the log $.logger.debug("Parsing %d turbine events", $.input.length); // Make the array of turbine telemetry records. Set its length one time. const input = $.input; const result = new Array(input.length); for (let i = 0; i < input.length; i++) {  const event = input[i];  result[i] = {    t:  event.tagName.replace(/\//g, "."),    // "/turbine/rotorSpeed" becomes ".turbine.rotorSpeed"    v:  event.data.value,                     // measured value, for example RPM or °    q:  event.data.quality,                   // OPC quality code (decimal)    ts: new Date(event.data.ts).toISOString() // timestamp of the measurement (ISO 8601)  }; } // Change the array into a JSON string for the MQTT payload $.output = JSON.stringify(result); // Example of the final $.output (string): // '[{"t":".turbine.rotorSpeed","v":1530,"q":192,"ts":"2025-07-15T14:30:00.000Z"}, …]' ``` ### **Add the engineering units and the formatted value (tag metadata)** This example adds the engineering units of each tag. It also formats the value with the **Format** of the tag. The format uses the placeholders of **sprintf**, for example **%i**. **Set Include tag metadata to** **Yes**. ```javascript // Make one JSON record for each event, with the unit and the formatted value of the tag. // The tag metadata is available only when Include tag metadata is set to Yes. const input = $.input; const records = new Array(input.length); for (let i = 0; i < input.length; i++) {  const event = input[i];  const meta = event.metadata; // undefined when Include tag metadata is No  const value = event.data.value;  const unit = meta && meta.engUnits ? meta.engUnits : "";  const text = meta && meta.format ? sprintf(meta.format, value) : String(value);  records[i] = {    tag: event.tagName,    value: value,    unit: unit,    text: unit ? text + " " + unit : text,    quality: event.data.quality,    ts: new Date(event.data.ts).toISOString()  }; } $.output = JSON.stringify(records); ``` Message received (extract): ```json [  {"tag":"/GREENLAKE/BESS01/BB01/BMS01/RACK01/VOLTAGE","value":1280,"unit":"V","text":"1280.00 V","quality":192,"ts":"2026-11-24T05:45:03.050Z"},  {"tag":"/GREENLAKE/BESS01/BB01/BMS01/RACK01/CURRENT","value":-45.0143928527832,"unit":"A","text":"-45.01 A","quality":192,"ts":"2026-11-24T05:45:03.050Z"},  {"tag":"/GREENLAKE/BESS01/BB01/BMS01/RACK01/CELL_V_MAX","value":3220.664794921875,"unit":"mV","text":"3220 mV","quality":192,"ts":"2026-11-24T05:45:03.050Z"},  {"tag":"/GREENLAKE/BESS01/BB01/BMS01/RACK01/STATE","value":1,"unit":"","text":"1","quality":192,"ts":"2026-11-24T05:45:03.050Z"} ] ``` > [!WARNING] > **Note:** > > When **Include tag metadata** is set to **No**, **metadata** is **undefined**. **Before you use a property of metadata, make sure that metadata has a value.** The example does this with **meta && …**. With this check, the script also operates when **Include tag metadata** is **No**: **unit** is empty and **text** is the value without format. ### **Add the asset path to the topic** This example uses **$.topic** to change the topic of the message. The script adds the asset path of the tags to the **Topic** of the publisher. It sends all the values in one object. **Set Topic to** **greenlake/bess01**. **Set Tag Filters** to the tags of one asset. ```javascript // Add the asset path of the tags to the configured Topic. // Example: tag /GREENLAKE/BESS01/BB01/BMS01/RACK01/SOC gives the topic /bb01/bms01/rack01. const input = $.input; const parts = input[0].tagName.split("/"); // ["", "GREENLAKE", "BESS01", "BB01", "BMS01", "RACK01", "SOC"] $.topic = $.topic + "/" + parts.slice(3, -1).join("/").toLowerCase(); // Use the last part of each tag path as the name of the value. const values = {}; for (let i = 0; i < input.length; i++) {  const path = input[i].tagName;  values[path.substring(path.lastIndexOf("/") + 1)] = input[i].data.value; } $.output = JSON.stringify({ ts: input[input.length - 1].data.ts, values: values }); ``` Message received: ```javascript // Topic: greenlake/bess01/bb01/bms01/rack01 {"ts":1795499103050,"values":{"VOLTAGE":1280,"CURRENT":-45.0143928527832,"SOC":26.79222297668457,"SOH":96.30999755859375,"CELL_V_MAX":3220.664794921875,"CELL_V_MIN":3193.6728515625,"CELL_T_MAX":26.396080017089844,"CELL_T_AVG":25.894163131713867,"STATE":1}} ``` ### **Publish each tag to its own topic** In this example each value has its own topic. The topic shows the location of the value in the plant, from the root to the tag. This example adds the tag path to the **Topic** of the publisher. For example, the **Topic** **UNS** and the tag **/GREENLAKE/BESS01/BB01/BMS01/RACK01/SOC** give the topic **UNS/GREENLAKE/BESS01/BB01/BMS01/RACK01/SOC**. **Set Topic to** **UNS**. **Set Events per message to** **1**. ```javascript // Publish each tag to its own topic: + . // Example: Topic "UNS" and tag /GREENLAKE/BESS01/BB01/HVAC/FAN_SPEED // give the topic UNS/GREENLAKE/BESS01/BB01/HVAC/FAN_SPEED. // Set Events per message to 1. Each message has only one topic. if ($.input.length !== 1) {  $.logger.warn("Set Events per message to 1. This message contains %d events", $.input.length); } const event = $.input[0]; $.topic = $.topic + event.tagName; // the tag path starts with "/" $.output = JSON.stringify({  value: event.data.value,  quality: event.data.quality,  ts: event.data.ts }); ``` ![UNS topics of the BESS plant in an MQTT client: one topic for each tag](https://cdn.document360.io/54093ab5-6b22-4542-a265-04377931f11a/Images/Documentation/image(303).png) Message received: ```javascript // Topic: UNS/GREENLAKE/BESS01/BB01/BMS01/RACK01/SOC {"value":85.83834075927734,"quality":192,"ts":1795501903056} ``` To use the same script in many publishers, refer to [**Reuse a publisher with a template**](/docs/mqtt-client-custom-payload-example#reuse-a-publisher-with-a-template). ### **Publish each tag to the topic of its asset** This example publishes each tag to the topic of its asset, for example a battery rack. The topic is the tag path without the tag name. The payload contains the tag name in **name**. For example, all the tags of the rack go to the topic **UNS/GREENLAKE/BESS01/BB01/BMS01/RACK01**. Use this method when the receiver subscribes to one topic for each asset. **Set Topic to** **UNS**. **Set Events per message to** **1**. ```javascript // Publish each tag to the topic of its sensor (asset): + . // The payload contains the tag name. // Example: Topic "UNS" and tag /GREENLAKE/BESS01/BB01/BMS01/RACK01/SOC // give the topic UNS/GREENLAKE/BESS01/BB01/BMS01/RACK01 and "name":"SOC". // Set Events per message to 1. Each message has only one topic. if ($.input.length !== 1) {  $.logger.warn("Set Events per message to 1. This message contains %d events", $.input.length); } const event = $.input[0]; const path = event.tagName; const cut = path.lastIndexOf("/"); $.topic = $.topic + path.substring(0, cut); $.output = JSON.stringify({  name: path.substring(cut + 1),  value: event.data.value,  quality: event.data.quality,  ts: event.data.ts }); ``` Messages received (extract, 3 of 9 messages): ```javascript // Topic: UNS/GREENLAKE/BESS01/BB01/BMS01/RACK01 (9 messages, one for each tag of the rack) {"name":"VOLTAGE","value":1280,"quality":192,"ts":1795501903056} {"name":"SOC","value":85.83834075927734,"quality":192,"ts":1795501903056} {"name":"CELL_V_MAX","value":3456.70947265625,"quality":192,"ts":1795501903056} ``` ### **Publish only tags with good quality** In Events mode, the publisher makes an event each time the value, the quality or the timestamp of a tag changes. Thus, a message can contain events with Bad or Uncertain quality. This example publishes only the events with Good quality. The Good quality codes are **192** and **216**. All the Bad and Uncertain codes are less than **192**. Thus, the script keeps the events with a quality of **192** or more. Refer to [**Quality codes**](/v122/docs/platform-tags-overview#quality-codes). When no event has Good quality, the script sets **$.output** to **null**. Then the publisher does not send a message. ```javascript // Publish only the events with Good quality (192 or more). Bad and Uncertain codes are less than 192. // For example, a tag with Bad quality after a communication failure is not published. const GOOD = 192; const input = $.input; const good = []; for (let i = 0; i < input.length; i++) {  const event = input[i];  if (event.data.quality >= GOOD) {    good.push({ tag: event.tagName, value: event.data.value, ts: event.data.ts });  } } // When no event has Good quality, send no message. $.output = good.length > 0 ? JSON.stringify(good) : null; ``` Message received for the tags of the power plant controller (PPC). RESPONSE_TIME has Bad quality. Thus, it is not in the message (extract): ```javascript // Topic: greenlake/bess01/ppc/good. Tag Filters: /GREENLAKE/BESS01/PPC/ (26 tags). // RESPONSE_TIME has Bad quality (0). The message contains 25 events: RESPONSE_TIME is not in the message. [{"tag":"/GREENLAKE/BESS01/PPC/MODE","value":1,"ts":1795511403057},{"tag":"/GREENLAKE/BESS01/PPC/P_SETPOINT","value":-340,"ts":1795511403057},{"tag":"/GREENLAKE/BESS01/PPC/P_SETPOINT_FEEDBACK","value":-340,"ts":1795511403057},{"tag":"/GREENLAKE/BESS01/PPC/P_TRACKING_ERROR","value":0,"ts":1795511403057},{"tag":"/GREENLAKE/BESS01/PPC/RAMP_RATE_LIMIT","value":1000,"ts":1795511403057},{"tag":"/GREENLAKE/BESS01/PPC/RAMP_RATE_ACTUAL","value":1000,"ts":1795511403057}, ...] ``` > [!WARNING] > **Note:** > > The receiver does not get the events with Bad or Uncertain quality. Thus, the receiver cannot see when a tag changes to Bad quality. ### **Add a header with the plant name and the local time** This example sends one JSON object in each message. The object has a header and the values. The header identifies the plant and the rack, and gives the number of events in the message. The **sent** field shows the time when the script makes the message, in the time zone of the plant (**moment.tz()**). When a message contains more than one event for a tag, **values** keeps the last value. ```javascript // Send one message each time the script runs, with a header and one object with the values of the message. const input = $.input; const values = {}; for (let i = 0; i < input.length; i++) {  const path = input[i].tagName;  values[path.substring(path.lastIndexOf("/") + 1)] = input[i].data.value; // for example "SOC" } $.output = JSON.stringify({  site: "GREENLAKE_BESS01",  rack: "BB01_RACK01",  sent: moment.tz(Date.now(), "Europe/Madrid").format(), // plant local time  events: input.length,  values: values }); ``` Message received. The message contains 18 events, two for each tag. **values** contains the last value of each tag: ```javascript {"site":"GREENLAKE_BESS01","rack":"BB01_RACK01","sent":"2026-11-24T10:00:50+01:00","events":18,"values":{"VOLTAGE":1280,"CURRENT":-45.0143928527832,"SOC":47.24399948120117,"SOH":96.30999755859375,"CELL_V_MAX":3302.612060546875,"CELL_V_MIN":3275.33984375,"CELL_T_MAX":26.450132369995117,"CELL_T_AVG":25.948213577270508,"STATE":1}} ``` ### **Send a binary message with a Buffer** This example uses a **Buffer** to make a compact binary message. Each event uses 13 bytes: | **Bytes** | **Content** | | --- | --- | | 0 to 7 | Timestamp, epoch in milliseconds (Float64, big-endian). | | 8 to 11 | Value (Float32, big-endian). | | 12 | Quality (UInt8). | The value uses Float32. Float32 keeps approximately 7 significant digits. When the quality is Bad, the value can be **null**. Then the script writes **0**. Use the quality byte to find these values. **Set Encoding to** **Binary data**. Some brokers change a binary message into text. Then the receiver cannot decode the message. Refer to **Encoding** in [**Data encoding settings**](/v122/docs/mqtt-client-custom-payload#data-encoding-settings). ```javascript // Make a binary payload: 13 bytes for each event. // Bytes 0-7: timestamp (Float64, big-endian). Bytes 8-11: value (Float32, big-endian). Byte 12: quality (UInt8). // The script writes all the bytes, so Buffer.allocUnsafe() is safe and faster than Buffer.alloc(). const RECORD_SIZE = 13; const input = $.input; const buffer = Buffer.allocUnsafe(input.length * RECORD_SIZE); for (let i = 0, offset = 0; i < input.length; i++, offset += RECORD_SIZE) {  const data = input[i].data;  buffer.writeDoubleBE(data.ts, offset);  buffer.writeFloatBE(Number(data.value), offset + 8);  buffer.writeUInt8(data.quality, offset + 12); } $.output = buffer; ``` Message received and decoded: ```javascript // Message for 9 events: 117 bytes (9 x 13). First record (hexadecimal): // 427a20c16134a000 | 44a00000 | c0 // timestamp 1795499103050 (2026-11-24T05:45:03.050Z) | value 1280.0 (VOLTAGE) | quality 192 ``` ### **Reuse a publisher with a template** Many publishers can use the same settings and the same script. For this, make a publisher template in the configuration of the module. Each publisher of the template gets the settings from the template. In each publisher, set only the custom properties that are different, for example **Topic** and **Script**. Then add the **Tag Filters** of the publisher. For more information, refer to [**Templates Overview**](/v122/docs/platform-templates-overview) and [**Custom Properties**](/v122/docs/platform-templates-custom-properties). To make and use a publisher template, do these steps: 1. In the **Templates** panel of the **MQTT Client** configuration, **make a template** of the type **Publisher**, for example **PUB**. 2. In the **Custom properties** of the template, **add a property** for each setting that can change. For example, add **Topic**, **Events_per_message** and **Script**. **Set the default value** of each property. 3. **Set each related setting** of the template to an expression with the property name in curly brackets. For example, set **Topic** to **={Topic}**. The **Output** column shows the value that the setting gets. ![Publisher template with custom properties and expressions in curly brackets](https://cdn.document360.io/54093ab5-6b22-4542-a265-04377931f11a/Images/Documentation/MQTT-CustomPayload-PublisherTemplate.webp) 4. In the **Model** panel, **add a publisher** of the template to a connection. 5. In the publisher, **set the custom properties** that are different from the template, for example **Script** and **Topic**. The other custom properties show **** and use the values of the template. 6. **Add the Tag Filters** of the publisher. ![Publisher of the template with its own Script, Topic and Tag Filters](https://cdn.document360.io/54093ab5-6b22-4542-a265-04377931f11a/Images/Documentation/MQTT-CustomPayload-TemplateInstance.webp) 7. **Save the configuration**. 8. **Subscribe** to the topics with an MQTT client. **Make sure** that the messages arrive on the correct topics. > [!WARNING] > **Note:** > > When two publishers send the same tag to the same topic, the broker receives each value two times. **Make sure that the Tag Filters of these publishers do not overlap.** [Embedded content](https://www.youtube.com/embed/ynTZn2AMp5c?&t=2s&wmode=opaque&rel=0) [MQTT Client Full Product Details](https://n3uron.com/iiot-platform-modules/mqtt-client/)