Building a Sensor Dashboard with Node-RED and MQTT
A temperature value can look plausible long after its publisher stops. A sensor dashboard should show whether the displayed sample is still usable. Start with one measurement and make its age visible before adding more widgets.
This tutorial builds a monitoring example using Node-RED, an MQTT broker, and FlowFuse Dashboard. The pump-room topic, temperature range, and freshness threshold below are illustrative design choices. Adapt them to your instrument and process. For the broader system decision, see edge gateways versus direct PLC-to-cloud connections.
TL;DR: Connect an MQTT input to a validator, then display the result with FlowFuse Dashboard’s
ui-template. OASIS defines QoS 1 as at-least-once delivery, so duplicates remain possible. This example displays sample age and marks data stale after an illustrative 30 seconds. Test stopped publishers and retained old samples before adding more measurements.
What does this Node-RED MQTT sensor dashboard need?
Use an existing Node-RED installation and a broker you can access from it. Install @flowfuse/node-red-dashboard through Manage Palette → Install, as described in FlowFuse’s Getting Started guide. That is the Dashboard 2.0 package used here. Record your installed Node-RED, dashboard, and broker versions with your project notes.
You also need permission to publish and subscribe to a test topic. Use a development broker or an isolated test namespace. Have its hostname, listener port, TLS settings, and credentials ready. This walkthrough begins with those services available; it does not install Node-RED or provision certificates.
Wire the example as follows:
Inject → Make sample → MQTT Out → broker
↓
MQTT In → Validate → ui-template
The Inject node is the test publisher. Later, a sensor or gateway can publish the same payload contract. Keep this first dashboard read-only: there is no output wired from the template to an actuator. Review OPC UA versus MQTT if you still need to choose how device information reaches the broker.
Validate each sample before display, and keep the measurement timestamp attached throughout the path from publisher to dashboard.
Step 1: Connect the MQTT nodes
Add MQTT In, MQTT Out, and Debug nodes. Configure both MQTT nodes to use your broker connection. Node-RED’s configuration-node documentation explains how MQTT nodes share broker configuration; its MQTT cookbook shows the connection setup.
Use this exact example topic in both nodes:
plant/line-1/sensor-07/temperature
Select MQTT 3.1.1 and QoS 1 for this exercise. Leave MQTT Out’s retain setting false initially. Inspect the incoming payload in Debug before wiring it to the validator below. The example validator accepts JSON text or an already parsed object. Attach Debug to MQTT In and select the complete message for inspection. Deploy and check the node’s connection status.
The MQTT In documentation describes the payload, topic, QoS, and retain properties supplied by incoming messages. For this exercise, compare those properties with your settings rather than inspecting only the temperature value.
Why choose QoS 1 here? OASIS MQTT 3.1.1 defines at-least-once delivery, which can include duplicates. This lets you test a display that replaces state. It does not prove that a sample is recent or valid. Our MQTT QoS 1 guide explains that distinction further.
Step 2: Publish one explicit sample contract
Create an Inject node with a repeat interval of 5 seconds and wire it to a Function node named Make sample. Paste the code below into the Function node, then wire it to MQTT Out. The interval, temperature, unit spelling, and quality vocabulary are example choices, not MQTT requirements.
// Make sample — one Function-node output
msg.payload = {
value: 23.7,
unit: "C",
ts: new Date().toISOString(),
quality: "good"
};
return msg;
MQTT Out serializes object payloads as JSON, according to its official node documentation. With the fixed topic already configured, deploy and trigger Inject. Debug should show a payload containing value, unit, ts, and quality. Each generated sample should carry a new timestamp.
The timestamp represents sample time in this proposed contract. When replacing the simulator with hardware, decide where that timestamp is created and how its clock is maintained. A gateway receive time answers a different question from an instrument measurement time. Label it accordingly.
Keep a valid, unchanged temperature flowing during the first test. If every value changes, animation can distract from a broken freshness indicator. A steady process still needs fresh samples; a moving screen is not the acceptance criterion.
Step 3: Reject malformed data before display
Place a Function node named Validate between MQTT In and the future dashboard widget. The node below accepts the proposed JSON contract and emits a separate display object. Its range of −40 to 150 °C and timestamp tolerance are example validation limits; replace them with documented limits for your application.
// Validate — one Function-node output
let p;
try {
p = typeof msg.payload === "string"
? JSON.parse(msg.payload) : msg.payload;
} catch (error) {
node.warn("Rejected malformed JSON");
return null;
}
const sampledAt = typeof p?.ts === "string" ? Date.parse(p.ts) : NaN;
const valid = p !== null && typeof p === "object"
&& !Array.isArray(p)
&& typeof p.value === "number" && Number.isFinite(p.value)
&& p.value >= -40 && p.value <= 150
&& p.unit === "C"
&& (p.quality === "good" || p.quality === "bad")
&& Number.isFinite(sampledAt)
&& sampledAt <= Date.now() + 5000;
if (!valid) {
node.warn("Rejected sample outside the example contract");
return null;
}
msg.payload = {
value: p.value,
unit: p.unit,
sampledAt,
quality: p.quality,
retained: msg.retain === true
};
return msg;
Rejected messages return no display update. The previous accepted sample therefore continues aging. A rejected message must not reset the freshness clock. Attach another Debug node after Validate while assembling the flow, so you can distinguish a transport problem from a rejected payload.
An accepted quality: "bad" sample is deliberately different from malformed data. It reaches the display with its quality flag intact. Your real publisher needs a documented quality convention; this two-value vocabulary is only the example’s contract.
Step 4: Display temperature, quality, and sample age
Add a Dashboard ui-template node. Configure a dashboard base path of /dashboard, a page path of /sensors, and a group named Pump room using the node’s configuration controls. Put the template in that group. FlowFuse’s Getting Started guide describes the base/page arrangement; open the dashboard page after deployment.
Paste this complete component into ui-template and wire Validate to its input:
<template>
<section aria-label="Pump room temperature">
<h2>Sensor 07 temperature</h2>
<p v-if="!msg?.payload">Waiting for an accepted sample</p>
<div v-else>
<p>{{ msg.payload.value }} °C</p>
<p>Sample age: {{ ageSeconds }} seconds</p>
<p>Quality: {{ msg.payload.quality }}</p>
<p>Retained delivery: {{ msg.payload.retained ? 'yes' : 'no' }}</p>
<p role="status">{{ state }}</p>
</div>
</section>
</template>
<script>
export default {
data() {
return { now: Date.now(), timer: null };
},
computed: {
ageSeconds() {
if (!this.msg?.payload) return 0;
return Math.max(0, Math.floor(
(this.now - this.msg.payload.sampledAt) / 1000
));
},
state() {
if (!this.msg?.payload) return 'WAITING';
if (this.msg.payload.quality !== 'good') return 'BAD QUALITY';
return this.ageSeconds > 30 ? 'STALE' : 'FRESH';
}
},
mounted() {
this.timer = setInterval(() => { this.now = Date.now(); }, 1000);
},
unmounted() {
clearInterval(this.timer);
}
};
</script>
FlowFuse documents that incoming messages are exposed as msg in ui-template. It also warns that payload can be absent at initial load. The guard above handles that case. The component’s timer, status vocabulary, and 30-second threshold are this tutorial’s implementation choices.
The example shows state as text, so color is not needed to distinguish FRESH, STALE, and BAD QUALITY. It uses the browser’s clock for age; compare browser and publisher clocks during commissioning. The five-second future tolerance in Validate is not a substitute for clock synchronization.
Keep age and quality beside the temperature, so a plausible retained reading cannot pass unnoticed as a current measurement.
Step 5: Test the failure states
Stop the repeating Inject node after one accepted sample. Under this example’s logic, its age should keep increasing and the label should change to STALE once the displayed age exceeds 30 seconds. These are acceptance checks for your installation, not a claim that this article’s flow has been tested against your broker.
| Test input or action | Expected result under this example |
|---|---|
| Fresh valid sample, good quality | Temperature displayed; FRESH |
| Stop the publisher | Age increases; eventually STALE |
quality: "bad" with a valid contract |
BAD QUALITY |
| Invalid JSON text | Warning; no accepted-sample update |
value supplied as a string |
Warning; no accepted-sample update |
| Timestamp more than five seconds ahead | Warning; no accepted-sample update |
| Repeat the same accepted sample | Same value and timestamp; age is not reset |
To test retained state, stop repeat publication and change Make sample’s timestamp to a fixed time several minutes in the past. Enable retain in MQTT Out, publish once, then redeploy or reconnect the subscriber. OASIS specifies delivery of retained state to a new matching subscription. The old sample should be accepted but displayed as stale, with retained delivery indicated.
After the test, clear the test topic’s retained value by publishing an empty string with retain enabled. Then restore the sample generator’s current timestamp and turn retain off. Both OASIS and the MQTT Out documentation describe clearing retained state with a zero-length retained publication.
Separate the freshness test from the disconnect test. A broker connection can remain healthy while the publisher sends nothing useful. Conversely, a retained value can arrive immediately after reconnection without representing a new measurement. This example decides freshness from the timestamp.
What should you check before using real sensor data?
Replace the sample limits and timing choices with application requirements. Then review broker authentication, TLS, topic permissions, and access to the Node-RED editor and dashboard. The Mosquitto configuration manual documents listener, certificate, password-file, anonymous-access, and ACL settings. Select those settings for your deployment rather than copying an unqualified public listener configuration.
Give the dashboard identity only the topic access it needs. Keep write access for the simulator separate where practical. When the real publisher replaces it, remove the simulator from the flow. Record which identity owns each publication path so an unexpected value has an identifiable source.
For missing data, work along the path: broker connection status, exact topic, credentials and ACLs, MQTT In Debug, validation warnings, then template input. For unexpected old values, inspect the timestamp and retain flag. For repeated values, distinguish a stable process from repeated delivery before changing broker settings.
A latest-value display is not a historian. Add explicit storage and recovery requirements before promising history across restarts. When expanding the naming scheme, use the Unified Namespace guide to consider topic structure. First keep the acceptance test small: interrupt one publisher and inspect what the dashboard says.
Frequently asked questions
Which Node-RED dashboard package does this tutorial use?
Use @flowfuse/node-red-dashboard, the Dashboard 2.0 package named in FlowFuse’s Getting Started guide. This example uses its ui-template widget to display temperature, sample age, quality, and retained-message status. It does not depend on a chart widget’s history behavior.
Does a retained MQTT message prove the sensor is online?
No. A retained message supplies stored state to a matching subscription under the OASIS MQTT specification. Check sample time and quality before treating it as current. This example marks samples stale after 30 seconds, an illustrative threshold rather than a protocol requirement.
Does MQTT QoS 1 prevent duplicate readings?
No. OASIS MQTT defines QoS 1 as at-least-once delivery, which can produce duplicates. This example replaces displayed state rather than accumulating incoming values. Applications that count events need an explicit duplicate-handling design; a delivery setting alone does not establish it.