Skip to content
You Start with one site
Amounts in Start with one site
Control, Measurement & Energy · Course

MQTT and Sparkplug B

Lesson 7 of 10 26 min read
Found this useful?

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:

  1. Explain publish and subscribe through a broker, and how it differs from poll and response
  2. Choose a quality of service, and say what retained messages, the last will and the keep-alive do
  3. Read a Sparkplug B topic and name the message type, the sender and the content
  4. Trace the messages of an edge node that starts, reports, loses its connection and returns
  5. Estimate the data volume of a device per day, with every assumption stated


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?

BrokerGateway Dedge nodeMeter Aaddress 5AnothersubscriberHostapplicationRS-485ModbusRTUoutbound, TCP with TLS
Gateway D, the broker and the host application

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.

coldstoregateway1meter5readingsstatusmeter6readingsgateway2meter5readingscoldstore/+/meter5/readingsmatches 2 topicscoldstore/gateway1/#matches 3 topics
Topic levels and what two subscriptions match

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.

QoSPromiseWhat happens
0At most onceThe message is sent once. No answer is expected. It may be lost.
1At least onceThe receiver answers with an acknowledgement. Without it, the sender sends again, so a duplicate is possible.
2Exactly onceA four-packet exchange makes sure the message is delivered once and only once.
QoS 0senderPUBLISHreceiverQoS 1senderPUBLISHreceiversenderPUBACKreceiverQoS 2senderPUBLISHreceiversenderPUBRECreceiversenderPUBRELreceiversenderPUBCOMPreceiver
Packets for one publish at each quality of service

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.

How long a dead client can look alive

is the keep-alive time. If the broker receives no packet from the client for one and a half times the keep-alive, it must close the connection, and then it publishes the will. is counted from the last packet that the broker received.

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 typeSent byWhen
NBIRTHEdge nodeDirectly after it connects. It lists every metric of the node.
DBIRTHEdge nodeAfter the NBIRTH, once for each device. It lists every metric of the device.
NDATAEdge nodeWhen a metric of the node changes.
DDATAEdge nodeWhen a metric of a device changes.
DDEATHEdge nodeWhen the edge node can no longer reach a device, for example a meter that stops answering on the bus.
NDEATHBroker, as the will of the edge nodeWhen the connection of the edge node is lost.
NCMDHost applicationTo write a metric of the edge node.
DCMDHost applicationTo write a metric of a device.
STATEHost applicationTo 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

is the sequence number of the NBIRTH and is the number of messages the node has published since then.

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.

received:254255013expected:254255012missinghost asks for a rebirth
A gap in the sequence numbers

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 values passes its deadband with probability in one period, independently of the others, then:

Messages under report by exception

is the fraction of periods in which a message is sent. is the mean number of metrics reported per period.

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
  1. The host is already online. At 07:59:00 it published a retained message on spBv1.0/STATE/host1 with online true and a timestamp. ✅

  2. The gateway registers its will, then connects. The connect packet carries the will: topic spBv1.0/coldstore/NDEATH/gateway1, one metric bdSeq = 0. The broker only stores it. ✅

  3. 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 coldstore and gateway1. ✅

  4. NBIRTH. Topic spBv1.0/coldstore/NBIRTH/gateway1, seq 0. It carries bdSeq = 0, the metric Node Control/Rebirth (Boolean, false) and any metrics of the gateway itself. ✅

  5. DBIRTH. Topic spBv1.0/coldstore/DBIRTH/gateway1/meter5, seq 1, payload timestamp 1,791,705,600,000 ms (08:00:00 UTC). It lists all nine metrics:

    NameAliasTypeValueTimestamp
    Voltage/L1-N1Float240.308:00:00
    Voltage/L2-N2Float239.808:00:00
    Voltage/L3-N3Float241.108:00:00
    Current/L14Float40.1208:00:00
    Current/L25Float39.8708:00:00
    Current/L36Float40.3108:00:00
    Power/Active7Float24.1508:00:00
    Power Factor8Float0.84008:00:00
    Frequency9Float50.0208:00:00

    The timestamps are shown as clock times and travel as milliseconds. ✅

Step 2: Report by exception

Click to reveal the data messages
  1. 08:00:10. Topic spBv1.0/coldstore/DDATA/gateway1/meter5, seq 2. Three metrics, each with its alias, its new value and its timestamp. The six values that stayed inside their deadbands are not sent. ✅

  2. 08:00:20. The same topic, seq 3, one metric with alias 4. ✅

  3. 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
  1. 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. ✅

  2. The will is published. The broker publishes the stored NDEATH on spBv1.0/coldstore/NDEATH/gateway1 with bdSeq = 0. ✅

  3. The host reacts. The bdSeq matches the NBIRTH it holds, so the host marks every metric of gateway1 and meter5 as stale. ✅

  4. 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
  1. A new will. At 08:10:00 the gateway connects again with a new NDEATH as its will, now with bdSeq = 1. ✅

  2. New births. NBIRTH with seq 0 and bdSeq = 1, then DBIRTH with seq 1 and the nine current values. The host marks the metrics as good again. ✅

  3. The complete sequence.

    TimeTopicTypeSenderseqCarries
    07:59:00spBv1.0/STATE/host1STATEHostnoneonline true, retained
    08:00:00spBv1.0/coldstore/NBIRTH/gateway1NBIRTHGateway0bdSeq 0, node metrics
    08:00:00spBv1.0/coldstore/DBIRTH/gateway1/meter5DBIRTHGateway19 metrics: name, alias, type, value
    08:00:10spBv1.0/coldstore/DDATA/gateway1/meter5DDATAGateway2aliases 1, 4, 7
    08:00:20spBv1.0/coldstore/DDATA/gateway1/meter5DDATAGateway3alias 4
    08:06:50spBv1.0/coldstore/NDEATH/gateway1NDEATHBrokernonebdSeq 0, the stored will
    08:10:00spBv1.0/coldstore/NBIRTH/gateway1NBIRTHGateway0bdSeq 1, node metrics
    08:10:00spBv1.0/coldstore/DBIRTH/gateway1/meter5DBIRTHGateway19 metrics, current values
    08:10:10spBv1.0/coldstore/DDATA/gateway1/meter5DDATAGateway2changed values only

    The data messages between 08:00:20 and 08:05:20 are left out of the table. ✅

  4. Check with the script. The Python script builds the topics from the three identifiers, counts seq with one counter and adds 90 s to the last packet. It prints the same rows and the time 08:06:50. ✅

Gateway DBrokerHostSTATE onlineretainedCONNECT + willNDEATH bdSeq 0(stored)NBIRTHseq 0DBIRTHseq 1DDATAseq 2DDATAseq 3Xlink fails 08:05:23NDEATH bdSeq 008:06:50CONNECT + willNDEATH bdSeq 1(stored)NBIRTHseq 0DBIRTHseq 1
Start, report, lost connection and return

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
  1. Messages per day.

    ✅

  2. One publish packet. After the length field come bytes, so the length field needs 2 bytes.

    ✅

  3. 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
  1. Payload. bytes. ✅

  2. One publish packet. There is no packet identifier at QoS 0. After the length field come bytes.

    ✅

  3. 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
  1. Fraction of periods with a message.

    The gateway sends messages per day. ✅

  2. Metrics per day. per period, so metrics per day. ✅

  3. Cost of a message before its metrics. bytes of MQTT, plus 60, gives 113 bytes. ✅

  4. Per day.

    This is 1.13 MB per day and 33.8 MB in 30 days, which is 55 % of the JSON volume. ✅

  5. 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. ✅

  6. 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.

mqtt_sparkplug_volume.py
"""Sparkplug B start-up sequence for gateway D, and a data volume estimate."""
import json
from datetime import datetime, timezone
import numpy as np
import 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 connects
T0 = 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 = 0
log = []
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 receives
will_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 count
back = T0 + 600_000 # 08:10:00, the gateway reconnects
send(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 readings
N_DAY = 86_400 // PERIOD # readings per day
LOWER = 60 # bytes per packet for TCP, IP and TLS (approximation)
N_VALUES = 9
PAYLOAD_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 value
rng = np.random.default_rng(7)
changed = rng.random((N_DAY, N_VALUES)) < P_CHANGE
count = changed.sum(axis=1)
sent = count > 0
simulated = 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]) / 1e6
fig, 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 ms
Host state topic: spBv1.0/STATE/host1
DBIRTH 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.02
Sequence 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 only
Broker waits at most 1.5 x 60 = 90 s; will published by 08:06:50
seq of message number 1000 after an NBIRTH with seq 0: 232
JSON 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 bytes
Readings 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 messages
Saved sparkplug_volume.png

The 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 is under about 0.75.

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 seq from 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) . (b) The step from 255 to 0 is normal. The value 2 is missing, so one message was lost. If it does not arrive after a short wait, the host sends an NCMD with 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

, so messages. Metrics per day: . Bytes: per day, which is 12.9 MB in 30 days.

References



  • OASIS, MQTT Version 3.1.1, OASIS Standard, 2014.
  • Eclipse Foundation, Sparkplug Specification, Version 3.0.0, 2022.
  • Google, Protocol Buffers documentation: Encoding.


© 2021-2026 SiliconWit®. All rights reserved.
Meter Aaddress 5Gateway Dedge nodeRS-485Modbus RTUoutbound, TCP with TLSBrokerHostapplicationAnothersubscriber
Gateway D, the broker and the host application
senderreceiverPUBLISHQoS 0PUBLISHPUBACKQoS 1PUBLISHPUBRECPUBRELPUBCOMPQoS 2
Packets for one publish at each quality of service
receivedexpected254254255255001132missinghost asks for a rebirth
A gap in the sequence numbers
Gateway DBrokerHostSTATE onlineretainedCONNECT + willNDEATH bdSeq 0(stored)NBIRTH seq 0DBIRTH seq 1DDATA seq 2DDATA seq 3link fails 08:05:23NDEATH bdSeq 008:06:50CONNECT + willNDEATH bdSeq 1(stored)NBIRTH seq 0DBIRTH seq 1
Start, report, lost connection and return
Predict first

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?

gatewaybrokerhost link fails NDEATH written at connect posted after 1.5 × keep-alive stale good
plain MQTTSparkplug B 24.15 kW24.15 kW 03:00, looks current STALE The link died at midnight on both sites
See it: what the host believes, against what is true

Broker publishes the NDEATH at
Host shows old values as good for
After the return at 08:10:00
TimeMessageseqCarries

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?

Watch it build: one Sparkplug B topic
meter5 gateway1 broker host deviceedge nodepublish, subscribe spBv1.0/<group>/<type>/<edge>/<device> spBv1.0/coldstore/<type>/gateway1/meter5 spBv1.0/coldstore/DBIRTH/gateway1/meter5 namespace, group, type, edge node, device groupedge nodedevice typeDBIRTH: meter5 and all its metrics payload: timestamp, seq 1, 9 metrics Voltage/L1-N alias 1 Float 240.3
  1. Three participants: gateway1 is the edge node, meter5 a device behind it, the host reads through the broker.
  2. Every topic has one fixed form: namespace, group, message type, edge node, and the device if there is one.
  3. In this course the group is coldstore, the edge node gateway1 and the device meter5.
  4. The message type says what happened. DBIRTH: gateway1 announces meter5 and every metric it has.
  5. The payload is binary (Protocol Buffers): a timestamp, a sequence number and a list of metrics.
  6. Each metric has a name, an alias, a type and a value: Voltage/L1-N, alias 1, Float, 240.3.
Found this useful?

Discussion

    Comments show your name. Be kind, stay on the topic.