How long a dead client can look alive
MQTT and Sparkplug B
On this page
A cold store screen shows 24.15 kW on the compressor feeder all night, and the night supervisor sees nothing wrong. In the morning the room is warm. The gateway lost its uplink at midnight, and the screen went on showing the last number it had received. Nothing in the message said “this value is still alive”. This lesson explains how MQTT carries messages through a broker, what it leaves undefined, and how Sparkplug B adds the rules that let a host know when its data is current and when it is not. #MQTT #SparkplugB #IndustrialIoT
Learning Objectives
By the end of this lesson, you will be able to:
- Explain publish and subscribe through a broker, and how it differs from poll and response
- Choose a quality of service, and say what retained messages, the last will and the keep-alive do
- Read a Sparkplug B topic and name the message type, the sender and the content
- Trace the messages of an edge node that starts, reports, loses its connection and returns
- Estimate the data volume of a device per day, with every assumption stated
Real-World System Problem: A gateway that reports a meter over a weak uplink
Gateway D sits in the plant room of a cold store. It polls energy meter A (Modbus RTU, address 5) on the RS-485 bus and must pass the readings to a host application in another town. The uplink is a mobile data connection. It stops at times, and every megabyte is paid for.
Poll and response does not suit this link. The host would need to open a connection inward to the plant, which the site’s security rules should not permit, and would ask for all nine values every time, even when none has changed.
MQTT reverses the direction. The gateway opens one outbound connection to a broker and publishes. The host connects to the same broker and subscribes. One question remains: when the messages stop, are the values steady or is the gateway dead?
Fundamental Theory: Publish and subscribe, then the rules on top
Broker, clients and topics
In MQTT every program that connects is a client, and the broker is the server in the middle. A client that has data publishes a message to a topic, which is a text label. A client that wants data subscribes to a topic, and the broker passes each message to every client whose subscription matches.
The publisher does not know who reads the message. Both sides know only the broker, as two people who never meet can share a notice board.
A topic is divided into levels by the character /, for example coldstore/gateway1/meter5/readings. Topics are case sensitive. A subscription may use two wildcards:
+stands for exactly one level.#stands for all remaining levels, and must be the last character.
A publisher never uses a wildcard. It publishes to one exact topic.
Quality of service
Each publish carries a quality of service (QoS) of 0, 1 or 2. It describes the exchange between one sender and one receiver: client to broker, or broker to client.
| QoS | Promise | What happens |
|---|---|---|
| 0 | At most once | The message is sent once. No answer is expected. It may be lost. |
| 1 | At least once | The receiver answers with an acknowledgement. Without it, the sender sends again, so a duplicate is possible. |
| 2 | Exactly once | A four-packet exchange makes sure the message is delivered once and only once. |
A subscriber also names a maximum QoS when it subscribes. The broker delivers each message at the lower of the two levels: the level of the publish and the level of the subscription.
Retained messages
A publisher may set the retain flag on a message. The broker then stores it as the last known value of the topic, one for each topic, and gives it at once to every client that subscribes later.
A retained message suits a state, such as “host is online”. For a measurement it is dangerous: a new subscriber receives a reading that may be days old, and nothing in MQTT marks it as old.
The last will, the keep-alive and the session
When a client connects, it may give the broker a last will: a topic and a message that the broker stores. If the connection ends without a disconnect packet from the client, the broker publishes the will. After a proper disconnect the will is discarded.
A link can also fail without closing. For this the client states a keep-alive time in seconds when it connects, and must send some packet within each keep-alive period. If it has no data, it sends a small ping request and the broker answers.
On a mobile data link, choose a keep-alive shorter than the time after which the operator’s network drops a quiet connection, often a few minutes. Otherwise the network can drop a connection that is alive, and the gateway learns of it only when its next packet fails.
The connect packet also has a clean session flag. Set, it makes the broker forget the client’s subscriptions at disconnect. Cleared, the broker keeps a persistent session under the client identifier: the subscriptions, and the QoS 1 and QoS 2 messages that arrive while the client is away. Each client identifier must be unique: if a second client connects with the same identifier, the broker disconnects the first.
What plain MQTT leaves undefined
MQTT moves bytes from publishers to subscribers. Three things are left to each project:
- Topic names. Every integrator invents a different tree.
- Payload format. The payload is a row of bytes: JSON, plain text or a binary structure. The names, units and types of the values are private agreements.
- State. MQTT does not say how a subscriber learns which devices exist, whether they are online, or whether a message was lost.
Two products that both “support MQTT” can therefore exchange nothing until somebody writes down all three. Sparkplug B, published by the Eclipse Foundation, is one written answer.
The Sparkplug B topic namespace
Sparkplug names three participants. An edge node is the MQTT client at the site, here gateway D. A device is equipment behind the edge node, here meter A. The host application is the consumer of the data, such as a SCADA system (supervisory control and data acquisition: the software in a control room that shows and records the plant).
Every topic of an edge node has this form:
spBv1.0/<group_id>/<message_type>/<edge_node_id>[/<device_id>]
The group identifier collects edge nodes, for example one site. The device identifier is present only in messages that concern a device. In this course the group is coldstore, the edge node is gateway1 and the device is meter5.
| Message type | Sent by | When |
|---|---|---|
| NBIRTH | Edge node | Directly after it connects. It lists every metric of the node. |
| DBIRTH | Edge node | After the NBIRTH, once for each device. It lists every metric of the device. |
| NDATA | Edge node | When a metric of the node changes. |
| DDATA | Edge node | When a metric of a device changes. |
| DDEATH | Edge node | When the edge node can no longer reach a device, for example a meter that stops answering on the bus. |
| NDEATH | Broker, as the will of the edge node | When the connection of the edge node is lost. |
| NCMD | Host application | To write a metric of the edge node. |
| DCMD | Host application | To write a metric of a device. |
| STATE | Host application | To say whether the host itself is online. |
Metrics and the payload
The payload is binary, encoded with Google Protocol Buffers, a compact format that needs a decoder to read. This course shows it decoded. A payload carries a timestamp, a list of metrics and, in the messages of an edge node, a sequence number. Each metric can carry a name, an alias, its own timestamp, a data type and a value. The data types include signed and unsigned integers of 8 to 64 bits, Float, Double, Boolean and String. Timestamps are in milliseconds since 1 January 1970, UTC.
The metric names are chosen by whoever configures the edge node. A / in a name, as in Voltage/L1-N, groups metrics into folders. A metric can also carry properties, and many edge nodes put the engineering unit there. Check the edge node’s documents for the property names it uses.
Birth and death certificates
Before it connects, the edge node writes its own NDEATH and gives it to the broker as the MQTT last will, as you might leave a letter with a friend to post if you go silent. The NDEATH carries one metric, bdSeq, the birth and death sequence number, and is registered at QoS 1 and without the retain flag. The node then connects and publishes its NBIRTH with the same bdSeq, so the host can match a death to the birth it ends. The next connection uses the next bdSeq.
A birth message lists every metric that the node or device will report in this session, with its name, data type and current value, so after a birth the host holds a complete picture. A birth may also give each metric an alias, a number that later data messages may carry in place of the name, which makes them shorter.
When the host receives an NDEATH, it marks every metric of that edge node and of its devices as stale.
Sequence numbers
Every message that the edge node publishes carries a sequence number, seq, from 0 to 255. One counter serves the node and all its devices. It rises by one with each message, and after 255 the next value is 0. The NDEATH is the exception: it is written before the session starts, so it carries bdSeq and no seq.
Sequence number of a later message
Sparkplug data messages are published at QoS 0, so one can be lost. The host compares each seq with the one before. If a number is missing and does not arrive within a short wait, the lost message may have carried a change and the host no longer knows the present values, so it sends an NCMD that sets the metric Node Control/Rebirth to true, and the edge node publishes its births again with all current values.
The STATE message of the host
In Sparkplug 3.0 the host application publishes its state on spBv1.0/STATE/<host_id>, as a small JSON text with an online value (true or false) and a timestamp. The message is retained and uses QoS 1. The host registers the offline form as its own last will. Earlier versions of Sparkplug used a different topic and payload for STATE, so check which version your products follow.
An edge node can be configured with a primary host. It then publishes its births only when that host is online, and stores its readings locally while the host is away.
Report by exception
In report by exception (RBE), the edge node sends a metric only when its value has changed. Most edge nodes add a deadband: a change smaller than it is not reported. Its size is a setting of the edge node, not fixed by Sparkplug.
RBE is safe only because of the birth and death messages. Silence now means that the node is alive and no value has changed by more than its deadband.
If each of
Messages under report by exception
Commands and security
An NCMD or a DCMD asks the edge node to write a value. For a Modbus device, the gateway turns a DCMD into a write request on the bus, and a write to a drive or a breaker can start a machine. Commands to plant are made only under the site’s permit and lock-out rules. A remote platform can receive data and can send a command, but fast control and every safety function stay in the local controller. Never publish a command with the retain flag: the broker would deliver it again at every new subscription.
Three security measures are standard. The connection runs inside TLS (port 8883 is registered for MQTT over TLS, and 1883 for MQTT without it), which encrypts the traffic and lets the client verify the broker. Each client proves its identity with a user name and password or with its own certificate. The broker applies topic access control, so that a gateway publishes only under its own edge node identifier, and only the host application publishes commands.
Application 1: Gateway D starts, reports meter A, is lost and returns
Step 1: Connect and give birth
Click to reveal the first messages
-
The host is already online. At 07:59:00 it published a retained message on
spBv1.0/STATE/host1withonlinetrue and a timestamp. ✅ -
The gateway registers its will, then connects. The connect packet carries the will: topic
spBv1.0/coldstore/NDEATH/gateway1, one metricbdSeq= 0. The broker only stores it. ✅ -
The gateway subscribes. It subscribes to the STATE topic of its host and to its own command topics, which have the message types NCMD and DCMD under
coldstoreandgateway1. ✅ -
NBIRTH. Topic
spBv1.0/coldstore/NBIRTH/gateway1,seq0. It carriesbdSeq= 0, the metricNode Control/Rebirth(Boolean, false) and any metrics of the gateway itself. ✅ -
DBIRTH. Topic
spBv1.0/coldstore/DBIRTH/gateway1/meter5,seq1, payload timestamp 1,791,705,600,000 ms (08:00:00 UTC). It lists all nine metrics:Name Alias Type Value Timestamp Voltage/L1-N 1 Float 240.3 08:00:00 Voltage/L2-N 2 Float 239.8 08:00:00 Voltage/L3-N 3 Float 241.1 08:00:00 Current/L1 4 Float 40.12 08:00:00 Current/L2 5 Float 39.87 08:00:00 Current/L3 6 Float 40.31 08:00:00 Power/Active 7 Float 24.15 08:00:00 Power Factor 8 Float 0.840 08:00:00 Frequency 9 Float 50.02 08:00:00 The timestamps are shown as clock times and travel as milliseconds. ✅
Step 2: Report by exception
Click to reveal the data messages
-
08:00:10. Topic
spBv1.0/coldstore/DDATA/gateway1/meter5,seq2. Three metrics, each with its alias, its new value and its timestamp. The six values that stayed inside their deadbands are not sent. ✅ -
08:00:20. The same topic,
seq3, one metric with alias 4. ✅ -
A period with no change. No DDATA is sent. The gateway sends an MQTT ping within each 60 s so that the broker knows it is alive. The ping is not a Sparkplug message and uses no
seq. ✅
Step 3: The connection is lost
Click to reveal when the host learns of it
-
The limit of the broker. The last packet arrived at 08:05:20.
The broker closes the connection at 08:06:50 at the latest. ✅
-
The will is published. The broker publishes the stored NDEATH on
spBv1.0/coldstore/NDEATH/gateway1withbdSeq= 0. ✅ -
The host reacts. The
bdSeqmatches the NBIRTH it holds, so the host marks every metric ofgateway1andmeter5as stale. ✅ -
The blind time. From the failure at 08:05:23 to 08:06:50, the host shows the old values as good for up to 87 s. ✅
Step 4: The gateway returns
Click to reveal the second session and the full table
-
A new will. At 08:10:00 the gateway connects again with a new NDEATH as its will, now with
bdSeq= 1. ✅ -
New births. NBIRTH with
seq0 andbdSeq= 1, then DBIRTH withseq1 and the nine current values. The host marks the metrics as good again. ✅ -
The complete sequence.
Time Topic Type Sender seq Carries 07:59:00 spBv1.0/STATE/host1STATE Host none online true, retained 08:00:00 spBv1.0/coldstore/NBIRTH/gateway1NBIRTH Gateway 0 bdSeq 0, node metrics 08:00:00 spBv1.0/coldstore/DBIRTH/gateway1/meter5DBIRTH Gateway 1 9 metrics: name, alias, type, value 08:00:10 spBv1.0/coldstore/DDATA/gateway1/meter5DDATA Gateway 2 aliases 1, 4, 7 08:00:20 spBv1.0/coldstore/DDATA/gateway1/meter5DDATA Gateway 3 alias 4 08:06:50 spBv1.0/coldstore/NDEATH/gateway1NDEATH Broker none bdSeq 0, the stored will 08:10:00 spBv1.0/coldstore/NBIRTH/gateway1NBIRTH Gateway 0 bdSeq 1, node metrics 08:10:00 spBv1.0/coldstore/DBIRTH/gateway1/meter5DBIRTH Gateway 1 9 metrics, current values 08:10:10 spBv1.0/coldstore/DDATA/gateway1/meter5DDATA Gateway 2 changed values only The data messages between 08:00:20 and 08:05:20 are left out of the table. ✅
-
Check with the script. The Python script builds the topics from the three identifiers, counts
seqwith one counter and adds 90 s to the last packet. It prints the same rows and the time 08:06:50. ✅
Check it before you trust it. A death certificate that has never been tested is a promise, not a fact. At commissioning, disconnect the gateway’s uplink (remove the modem’s antenna cable or the network cable) and time how long the host takes to show the meter as stale: it must be no more than 1.5 times the keep-alive, 90 s here. Reconnect, and the host must receive an NBIRTH with the next bdSeq and show the values as good again. This test only reads; it sends no command to the plant.
Application 2: Data volume for meter A over one day
Step 1: JSON over plain MQTT
Click to reveal the JSON volume
-
Messages per day.
✅
-
One publish packet. After the length field come
bytes, so the length field needs 2 bytes. ✅
-
Per day. With 60 bytes for the lower layers, one message costs 235 bytes.
In 30 days this is 60.9 MB. ✅
Step 2: Sparkplug B with all nine values
Click to reveal the volume without report by exception
-
Payload.
bytes. ✅ -
One publish packet. There is no packet identifier at QoS 0. After the length field come
bytes. ✅
-
Per day.
In 30 days this is 71.5 MB. With these assumptions the binary format is not smaller than the short JSON text, because every metric carries its own timestamp. ✅
Step 3: Sparkplug B with report by exception
Click to reveal the volume with a deadband
-
Fraction of periods with a message.
The gateway sends
messages per day. ✅ -
Metrics per day.
per period, so metrics per day. ✅ -
Cost of a message before its metrics.
bytes of MQTT, plus 60, gives 113 bytes. ✅ -
Per day.
This is 1.13 MB per day and 33.8 MB in 30 days, which is 55 % of the JSON volume. ✅
-
A quiet load. With
, , which gives 1,436 messages and 190,000 bytes per day: 5.7 MB in 30 days, or 9 % of the JSON volume. ✅ -
Check by simulation. The script draws one day of 8,640 periods with nine random values each, builds every packet and adds the bytes. It gives 1,127,637 bytes in 7,505 messages for
, within 0.3 % of the formula. ✅
Verify It in Python
The script builds the message sequence of Application 1, calculates the data volumes of Application 2, checks the formula with a simulated day, and plots the volume against the probability of change.
"""Sparkplug B start-up sequence for gateway D, and a data volume estimate."""import jsonfrom datetime import datetime, timezoneimport numpy as npimport matplotlib.pyplot as plt
# ---------- Application 1: the message sequence ----------GROUP, NODE, DEVICE, HOST = "coldstore", "gateway1", "meter5", "host1"KEEP_ALIVE = 60 # s, set by the gateway when it connectsT0 = int(datetime(2026, 10, 11, 8, 0, 0, tzinfo=timezone.utc).timestamp() * 1000)
def topic(message_type, device=None): parts = ["spBv1.0", GROUP, message_type, NODE] + ([device] if device else []) return "/".join(parts)
def clock(ms): return datetime.fromtimestamp(ms / 1000, tz=timezone.utc).strftime("%H:%M:%S")
names = ["Voltage/L1-N", "Voltage/L2-N", "Voltage/L3-N", "Current/L1", "Current/L2", "Current/L3", "Power/Active", "Power Factor", "Frequency"]readings = [240.3, 239.8, 241.1, 40.12, 39.87, 40.31, 24.15, 0.840, 50.02]
# One counter for the whole edge node: 0 to 255, then 0 again.seq = 0log = []
def send(ms, message_type, device, carries, counted=True, sender="gateway"): global seq shown = "-" if counted: shown, seq = str(seq), (seq + 1) % 256 log.append((clock(ms), topic(message_type, device), sender, shown, carries))
send(T0, "NBIRTH", None, "bdSeq 0, node metrics")send(T0, "DBIRTH", DEVICE, "9 metrics: name, alias, type, value")send(T0 + 10_000, "DDATA", DEVICE, "aliases 1, 4, 7 (3 changed values)")send(T0 + 20_000, "DDATA", DEVICE, "alias 4 (1 changed value)")last_packet = T0 + 320_000 # 08:05:20, last packet the broker receiveswill_time = last_packet + int(1.5 * KEEP_ALIVE * 1000)send(will_time, "NDEATH", None, "bdSeq 0 (the stored will)", counted=False, sender="broker")seq = 0 # a new session starts a new countback = T0 + 600_000 # 08:10:00, the gateway reconnectssend(back, "NBIRTH", None, "bdSeq 1, node metrics")send(back, "DBIRTH", DEVICE, "9 metrics again, current values")send(back + 10_000, "DDATA", DEVICE, "changed values only")
print(f"Timestamp of 08:00:00 UTC on 2026-10-11: {T0} ms")print("Host state topic: " + "/".join(["spBv1.0", "STATE", HOST]))print("DBIRTH metrics (alias, name, type, value):")for alias, (name, value) in enumerate(zip(names, readings), start=1): print(f" {alias} {name:<13} Float {value:g}")print("Sequence of Sparkplug messages:")for when, top, sender, s, carries in log: print(f" {when} {top:<41} {sender:<7} seq {s:>2} {carries}")print(f"Broker waits at most 1.5 x {KEEP_ALIVE} = {1.5 * KEEP_ALIVE:.0f} s; " f"will published by {clock(will_time)}")print(f"seq of message number 1000 after an NBIRTH with seq 0: {1000 % 256}")
# ---------- Application 2: data volume ----------PERIOD = 10 # s between readingsN_DAY = 86_400 // PERIOD # readings per dayLOWER = 60 # bytes per packet for TCP, IP and TLS (approximation)N_VALUES = 9PAYLOAD_BASE = 10 # bytes: Sparkplug payload timestamp and seq (estimate)PER_METRIC = 18 # bytes: alias, timestamp, type, float value (estimate)P_CHANGE = 0.20 # chance that one value passes its deadband in 10 s
def mqtt_publish(topic_name, payload_bytes, qos): """Bytes of one MQTT 3.1.1 PUBLISH packet.""" variable = 2 + len(topic_name.encode()) + (2 if qos > 0 else 0) remaining = variable + payload_bytes length_bytes = 1 if remaining < 128 else 2 # true below 16,384 return 1 + length_bytes + remaining
keys = ["v_l1", "v_l2", "v_l3", "i_l1", "i_l2", "i_l3", "p_kw", "pf", "f_hz"]message = {"ts": T0}message.update(dict(zip(keys, readings)))text = json.dumps(message, separators=(",", ":"))json_topic = "coldstore/gateway1/meter5/readings"json_packet = mqtt_publish(json_topic, len(text.encode()), qos=1)json_day = N_DAY * (json_packet + LOWER)
ddata_topic = topic("DDATA", DEVICE)
def ddata_packet(n_metrics): return mqtt_publish(ddata_topic, PAYLOAD_BASE + PER_METRIC * n_metrics, qos=0)
all_day = N_DAY * (ddata_packet(N_VALUES) + LOWER)
def rbe_day(p): """Expected bytes per day with report by exception, values independent.""" p_message = 1 - (1 - p) ** N_VALUES fixed = ddata_packet(0) + LOWER # cost of a message with no metric return N_DAY * (p_message * fixed + N_VALUES * p * PER_METRIC), N_DAY * p_message
rbe, rbe_messages = rbe_day(P_CHANGE)quiet, quiet_messages = rbe_day(0.02)
print("JSON message:", text)print(f" JSON payload {len(text.encode())} bytes, topic {len(json_topic)} bytes, " f"PUBLISH packet {json_packet} bytes")print(f" DDATA topic {len(ddata_topic)} bytes; packet with 9 metrics " f"{ddata_packet(9)} bytes, with 2 metrics {ddata_packet(2)} bytes")print(f"Readings per day at one every {PERIOD} s: {N_DAY}")print(f" JSON, every reading: {json_day:>9,.0f} bytes/day = " f"{json_day * 30 / 1e6:5.1f} MB in 30 days")print(f" Sparkplug, all nine values: {all_day:>9,.0f} bytes/day = " f"{all_day * 30 / 1e6:5.1f} MB in 30 days")print(f" Sparkplug, RBE at p = 0.20: {rbe:>9,.0f} bytes/day = " f"{rbe * 30 / 1e6:5.1f} MB in 30 days, {rbe_messages:,.0f} messages")print(f" Sparkplug, RBE at p = 0.02: {quiet:>9,.0f} bytes/day = " f"{quiet * 30 / 1e6:5.1f} MB in 30 days, {quiet_messages:,.0f} messages")print(f" RBE at p = 0.20 is {100 * rbe / json_day:.0f} % of the JSON volume; " f"at p = 0.02 it is {100 * quiet / json_day:.0f} %")
# Second method: simulate one day, value by valuerng = np.random.default_rng(7)changed = rng.random((N_DAY, N_VALUES)) < P_CHANGEcount = changed.sum(axis=1)sent = count > 0simulated = sum(ddata_packet(int(n)) + LOWER for n in count[sent])print(f" simulated day at p = 0.20: {simulated:>9,.0f} bytes, {sent.sum():,} messages")
# ---------- Plot ----------p = np.linspace(0.0, 1.0, 201)curve = np.array([rbe_day(x)[0] for x in p]) / 1e6fig, ax = plt.subplots(figsize=(8, 4))ax.plot(p, curve, label="Sparkplug B, report by exception")ax.axhline(json_day / 1e6, color="tab:red", linestyle="--", label="JSON, every reading")ax.axhline(all_day / 1e6, color="tab:gray", linestyle=":", label="Sparkplug B, all nine values")ax.set_xlabel("chance that one value passes its deadband in 10 s")ax.set_ylabel("estimated volume (MB per day)")ax.set_title("Data volume for meter A, one reading every 10 s")ax.legend()ax.grid(alpha=0.3)fig.tight_layout()fig.savefig("sparkplug_volume.png", dpi=120)print("Saved sparkplug_volume.png")Expected output
Timestamp of 08:00:00 UTC on 2026-10-11: 1791705600000 msHost state topic: spBv1.0/STATE/host1DBIRTH metrics (alias, name, type, value): 1 Voltage/L1-N Float 240.3 2 Voltage/L2-N Float 239.8 3 Voltage/L3-N Float 241.1 4 Current/L1 Float 40.12 5 Current/L2 Float 39.87 6 Current/L3 Float 40.31 7 Power/Active Float 24.15 8 Power Factor Float 0.84 9 Frequency Float 50.02Sequence of Sparkplug messages: 08:00:00 spBv1.0/coldstore/NBIRTH/gateway1 gateway seq 0 bdSeq 0, node metrics 08:00:00 spBv1.0/coldstore/DBIRTH/gateway1/meter5 gateway seq 1 9 metrics: name, alias, type, value 08:00:10 spBv1.0/coldstore/DDATA/gateway1/meter5 gateway seq 2 aliases 1, 4, 7 (3 changed values) 08:00:20 spBv1.0/coldstore/DDATA/gateway1/meter5 gateway seq 3 alias 4 (1 changed value) 08:06:50 spBv1.0/coldstore/NDEATH/gateway1 broker seq - bdSeq 0 (the stored will) 08:10:00 spBv1.0/coldstore/NBIRTH/gateway1 gateway seq 0 bdSeq 1, node metrics 08:10:00 spBv1.0/coldstore/DBIRTH/gateway1/meter5 gateway seq 1 9 metrics again, current values 08:10:10 spBv1.0/coldstore/DDATA/gateway1/meter5 gateway seq 2 changed values onlyBroker waits at most 1.5 x 60 = 90 s; will published by 08:06:50seq of message number 1000 after an NBIRTH with seq 0: 232JSON message: {"ts":1791705600000,"v_l1":240.3,"v_l2":239.8,"v_l3":241.1,"i_l1":40.12,"i_l2":39.87,"i_l3":40.31,"p_kw":24.15,"pf":0.84,"f_hz":50.02} JSON payload 134 bytes, topic 34 bytes, PUBLISH packet 175 bytes DDATA topic 39 bytes; packet with 9 metrics 216 bytes, with 2 metrics 89 bytesReadings per day at one every 10 s: 8640 JSON, every reading: 2,030,400 bytes/day = 60.9 MB in 30 days Sparkplug, all nine values: 2,384,640 bytes/day = 71.5 MB in 30 days Sparkplug, RBE at p = 0.20: 1,125,217 bytes/day = 33.8 MB in 30 days, 7,480 messages Sparkplug, RBE at p = 0.02: 190,309 bytes/day = 5.7 MB in 30 days, 1,436 messages RBE at p = 0.20 is 55 % of the JSON volume; at p = 0.02 it is 9 % simulated day at p = 0.20: 1,127,637 bytes, 7,505 messagesSaved sparkplug_volume.pngThe plot shows the report by exception curve rising from zero toward the grey line as the load becomes less steady. With these assumptions it stays below the JSON line while
Common Mistakes
- Believing that QoS 1 or QoS 2 means the host received the message. The level covers one hop. An offline subscriber receives the message later only if it has a persistent session and a subscription at QoS 1 or 2.
- Publishing measurements with the retain flag. A new subscriber then receives an old reading that looks new.
- Treating silence as “no change” on plain MQTT. Without a birth and a death message, silence can also mean a dead gateway.
- Allowing every client to publish to the command topics. Only the host application may publish NCMD and DCMD, and a command to plant needs the site’s permit.
Summary
- MQTT clients publish and subscribe to topics through a broker. The gateway opens the connection outward, so no inbound port is opened toward the plant.
- QoS 0, 1 and 2 mean at most once, at least once and exactly once, for one hop.
- Plain MQTT does not define topic names, payload format or state. Sparkplug B defines all three.
- An edge node registers its NDEATH as the will, then publishes NBIRTH and DBIRTH with every metric. Data messages carry only changes, and a
seqfrom 0 to 255 lets the host find a lost message. - Report by exception reduces the data volume most on a steady load.
Exercises
1. A broker holds the topics coldstore/gateway1/meter5/readings, coldstore/gateway1/meter5/status, coldstore/gateway1/meter6/readings and coldstore/gateway2/meter5/readings. Which of them match the subscription coldstore/gateway1/+/readings, and which match coldstore/+/meter5/#?
Answer
coldstore/gateway1/+/readings matches two: the readings of meter5 and of meter6 under gateway1. coldstore/+/meter5/# matches three: readings and status of meter5 under gateway1, and readings of meter5 under gateway2.
2. An edge node publishes its NBIRTH with seq 0. (a) What is the seq of the 600th message after the NBIRTH? (b) The host receives the values 253, 254, 255, 0, 1, 3. What has happened, and what does the host do?
Answer
(a) Node Control/Rebirth set to true.
3. Write the Sparkplug B topics for: (a) a data message from device meter6 under edge node gateway1 in group coldstore; (b) the death certificate of edge node gateway2 in the same group; (c) a command to the edge node gateway1 itself. Say who publishes each.
Answer
(a) spBv1.0/coldstore/DDATA/gateway1/meter6, published by the edge node. (b) spBv1.0/coldstore/NDEATH/gateway2, published by the broker as the will of that node. (c) spBv1.0/coldstore/NCMD/gateway1, published by the host application.
4. Use the assumptions of Application 2 (113 bytes for a message before its metrics, 18 bytes per metric, nine values, one period every 10 s). After the deadbands are widened, each value passes its deadband with probability 0.05. Estimate the messages and the bytes per day, and the megabytes in 30 days.
Answer
References
- OASIS, MQTT Version 3.1.1, OASIS Standard, 2014.
- Eclipse Foundation, Sparkplug Specification, Version 3.0.0, 2022.
- Google, Protocol Buffers documentation: Encoding.
A gateway publishes through a broker with a keep-alive of 60 s. Its mobile link fails without closing the connection. How long can the host go on showing the gateway's last values as if they were current?
| Time | Message | seq | Carries |
|---|
The times are those of Application 1: the last packet reaches the broker at 08:05:20, the link fails at 08:05:23 without a disconnect, and the gateway returns at 08:10:00. Change the keep-alive and watch the blind time. The second button adds a case that is not in the lesson: the DDATA with seq 3 is lost, an assumed DDATA at 08:00:30 carries seq 4, and the host sees the gap and asks for a rebirth.
Check yourself
Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.
1. An edge node published its NBIRTH with seq 0 and has published 300 messages since then. What seq does the 300th of them carry?
2. The host must mark a gateway stale within 30 s of its last packet. What is the longest keep-alive that the gateway may use?
3. A second host application starts at 09:00 and subscribes to the DDATA topic of meter5. Report by exception is on, and no value has passed its deadband since 08:00:20. What does the new host receive?
- Three participants: gateway1 is the edge node, meter5 a device behind it, the host reads through the broker.
- Every topic has one fixed form: namespace, group, message type, edge node, and the device if there is one.
- In this course the group is coldstore, the edge node gateway1 and the device meter5.
- The message type says what happened. DBIRTH: gateway1 announces meter5 and every metric it has.
- The payload is binary (Protocol Buffers): a timestamp, a sequence number and a list of metrics.
- Each metric has a name, an alias, a type and a value: Voltage/L1-N, alias 1, Float, 240.3.
Discussion
No comments yet. Questions, results from your own build, a better way to explain it: all welcome.
My notes on this page
Kept on this device only. Nothing is sent anywhere.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
Notes on earlier wording
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.