MQTT Setup: Reference
More
Depth: Practitioner
Progress saves as you read. Mark sections complete as you go; your progress appears in the sidebar.
Reference notes for publish-subscribe basics, Python reliability, the local loop lab and the sensor lab.
Receipt and diagnosis
A blank dashboard can mean several things: no broker, no subscription, a different topic, or a payload the program cannot parse. Changing all of them at once makes diagnosis harder.
This receiver expects numeric text, so receiving arbitrary bytes is not enough.
A receiver line establishes receipt of those bytes on this route. It does not establish TLS, authentication or physical measurement. The stopped-broker error is a transport refusal; it is not a refused MQTT connection acknowledgement.
Starter client scope
- MQTT: a publish-subscribe messaging protocol. Clients send messages through a broker.
- Broker: the service that routes a publication to matching subscriptions.
- Topic: the message address. Here the Python clients use
iotclass/sensors/temperature. - Quality of service, or QoS: the delivery level. These starter clients use level zero, which permits message loss.
- Retained message: a value explicitly kept for later matching subscribers. The local test does not request retention.
- Last Will: a configured message for an abnormal disconnection. The local Python examples configure no Will.
- Persistent session: broker-side subscription and pending-delivery state that can survive a connection. It does not store readings a disconnected publisher has yet to send.
The publisher generates numbers; the subscriber interprets them as temperatures.
The subscriber warns only when the value is greater than twenty-five.
Generated values span fifteen through twenty-five degrees Celsius, below the alert trigger. Send completion differs from receipt.
Component roles
| Component | Role | In the local test | In the sensor path |
|---|---|---|---|
| Publisher | Produces a payload on a topic | mosquitto_pub, then Python | ESP32 with DHT22 |
| Broker | Routes to matching subscriptions | Local Mosquitto | Public test broker for synthetic data |
| Subscriber | Receives and interprets the payload | mosquitto_sub, then Python | Laptop receiver |
The publisher produces the temperature payload. The broker routes it by topic. The laptop subscriber receives it and checks the threshold. A client can perform both sending and receiving roles; these examples separate them so you can observe each boundary.
Message frequency and broker load
Receiving one payload establishes the route. To reason about many receivers, count each forwarded copy. This worksheet assumes every publication has the same number of matching subscribers. It excludes retries and protocol overhead.
For devices publishing at messages per second, with subscribers receiving each publication:
- Incoming rate: devices times each device’s publication rate.
- Outgoing rate: incoming rate times matching subscribers per publication.
- Topic count: does not enter this simplified calculation on its own.
With one thousand sensors sending one message every ten seconds, and three subscribers per message:
- Input: messages per second.
- Output: messages per second.
- Fan-out: three outgoing copies per incoming publication.
The existing CPU worksheet uses assumed coefficients, not measurements of Mosquitto:
The coefficients represent percentage points per outgoing message per second and per active connection, respectively.
- One thousand connections: three hundred outgoing messages per second gives three plus five, or eight percent modeled CPU.
- Eight thousand connections: two thousand outgoing messages per second gives twenty plus forty, or sixty percent.
- Ten thousand devices at the same per-device rate: one thousand incoming and three thousand outgoing messages per second gives thirty plus fifty, or eighty percent.
Dropping the connection term would turn the last estimate into thirty percent. Keep both terms in the estimate. Benchmark the actual broker before making a capacity decision.
Connection evidence boundaries
A payload line is one checkpoint in a longer exchange. CONNECT carries the client identifier, session intent, keep-alive and optional Will or credentials. CONNACK reports acceptance or refusal and whether a session was resumed. Neither packet proves that a subscriber processed a reading.
Read the arrows from top to bottom. The client first sends CONNECT to ask for a session. The broker replies with CONNACK to report the result. The later PINGREQ and PINGRESP pair checks that the connection is still active when the client needs a ping. None of these arrows shows a temperature payload reaching a receiver. Keep the connection result in your log, then look for a separate receiver line to show message receipt.
The existing connection sequence separates session acceptance from later keep-alive traffic. Message receipt needs its own evidence.
Changing a client identifier prevents resuming the old identity’s session. Reusing an identifier concurrently can disconnect the existing client. Check Session Present before assuming old subscriptions exist; subscribe when no session resumed. Log a refused CONNACK separately from a failed TCP connection. See MQTT 3.1.1 sections 3.1 and 3.2.
Use the effective keep-alive: the client-declared value in MQTT 3.1.1; in MQTT 5, the Server Keep Alive from CONNACK overrides the declared value if present. For a nonzero effective keep-alive, the client sends an MQTT control packet within the interval. If otherwise quiet, it sends PINGREQ; the broker replies with PINGRESP. A publisher sending every twenty seconds fits a sixty-second interval without separate pings. With no client control packet for one and a half times the interval, the broker must disconnect. Setting keep-alive to zero disables this MQTT timeout.
A configured Will follows the protocol’s disconnection rules. MQTT 3.1.1 publishes it on abnormal disconnection. MQTT 5 can delay it until the Will Delay Interval elapses or the session ends, whichever comes first; reconnecting to the same session before that delay can suppress it. See MQTT 5 sections 3.1.2.10, 3.2.2.3.14 and 3.1.3.2.2.
For a connection record, write the chosen client identifier beside the clean-session setting and the broker’s Session Present result. A restart with the same spelling is not enough: a clean session can still discard earlier state. A new identity avoids colliding with another learner but cannot resume that learner’s old session.
Then compare two records. The broker trace can show acceptance and the subscription exchange. The receiver trace can show that the application parsed the payload. A missing payload after accepted subscription points you toward the publication’s topic and timing. A refused connection requires a different diagnosis, before application delivery can begin.
For a deeper connection test, keep a broker log or packet trace of the client identifier, session settings, keep-alive, accepted connection and publish-subscribe path. Test credential refusal only on a controlled authenticated broker. The local stopped-broker exercise establishes a transport refusal and cannot substitute for that test.
Publisher buffering
A persistent session is broker-side subscription and pending-delivery state that can survive a connection. It does not store readings a disconnected publisher has yet to send.
Queues depend on QoS, session state and limits. Reconnects need a loop and retry policy. Unsent readings need a buffer at the publisher.
Broker locations and receivers
The broker can run locally for this command-line loop, on a public test service for synthetic data, or in a controlled, secured deployment.
The Python publisher generates numbers. The ESP32 sketch reads the DHT22. Either needs a matching receiver.
Other receivers can include a dashboard, a logger, and an alert service. Each needs an authorized matching subscription.
Garden payload roles
A garden ESP32 sends {"moisture": 45, "status": "needs_water"} on garden/moisture/plant1. A phone should notify its owner.
- Publisher: the ESP32 reads the sensor and publishes the payload.
- Broker: receives the publication and routes it to authorized matching subscriptions.
- Subscriber: the phone app or a supporting service interprets the payload and decides whether to notify.
- Payload boundary: forty-five is an example value here, not a calibrated watering threshold.
Several family members can receive the same topic without adding their addresses to the ESP32. Their subscriptions belong at the broker.
Public broker limits
A prototype’s dashboard receives a reading through a public broker. That success tempts its developer to send customer data through the same connection.
The warning concerns the port 1883 listener used by these public examples. The service’s own listener list identifies it as unencrypted and unauthenticated. Other ports have different properties.
- Exposure: another user can subscribe to the same ordinary topic.
- Plaintext: an observer on the network path can read unencrypted traffic.
- Availability: the test service gives your project no uptime guarantee.
- Shared namespace: another experiment can publish on your topic or leave retained state there.
Suppose another experiment sends 30.0 on your shared temperature topic. The subscriber would print a high-temperature warning even though your own sensor did not supply that reading. The numeric conversion and threshold comparison could both work correctly while the application trusts the wrong source. Receipt answers whether bytes arrived; it does not answer who was allowed to send them.
Do not repair this by choosing a less obvious topic name. A production design needs TLS, client authentication, topic authorization and an operating plan. The security chapter separates those controls; the secured-broker lab provides the next exercise.
A Mosquitto configuration file is not a shell script. Certificate paths must name real, readable files. A listener number alone does not create TLS or restrict topic access. Use the configuration reference when preparing that separate deployment.
Sensor source limits
Read the circuit and sketch as source files. Trace what they intend to do. This is an offline walkthrough. It does not prove a build, a browser run or receipt at a remote client.
The library list names PubSubClient and DHT sensor library; pins no versions and proves no build compatibility.
The ESP32 sketch attempts DHT22 reads at a five-second interval; reconnects can delay the loop.
The sketch generates a topic root at boot. A receiver would need the current root; a random suffix can repeat.
Before the local lab
Review the route and delivery basics before you run the lab. You also need to save and run a short Python script.
- Publish-subscribe basics: follow a topic from its publisher through the broker to a receiver.
- QoS and sessions: distinguish a live level-zero test from queued delivery after reconnecting.
- Python and terminals: save a script, run it, and stop your own foreground program with Control-C. The lab lists its software prerequisites before the commands.
Run the local lab for the observable exchange.
Source inspection and hardware path
The sensor-publishing lab provides the sensor path. Read the supplied circuit and sketch as source files, not an independently verified Wokwi workflow.
Intended route
Trace the sketch’s intended route through the three roles.
ESP32 (Publisher) → Broker (test.mosquitto.org) → Your Laptop (Subscriber)
"Temp: 24°C" [Routes message] "Display: 24°C"
Follow the reading from left to right. The ESP32 is the source, the broker is the router and the laptop is the receiver. The text shows the intended path through these roles. It does not show a trace from a live run. To check that path, compare the topic used by the source with the topic requested by the receiver. Then look for the value in the receiver output, rather than relying on the sender alone.
Circuit and connection source
Find the diagram’s temperature attribute and the sketch’s publish call. Record source findings separately from simulation or hardware evidence.
Circuit: find ESP32, DHT22, D4, temperature 24 and humidity 40.
Trace: find Serial.begin(115200). MQTT Connected requires client.connect returning true; failure prints a code and retries.
Reading, formatting and destination source
These sketch branches describe intended behavior, not a verified current browser run.
Observe: find DHT read failure and temperature/humidity prints: OK or FAIL follows the publish result; source alone establishes neither result.
Change: trace thirty degrees through dtostrf: width six, two decimal places. This predicts formatting, not control response.
Receive: find mqtt_server, topic_root and /temperature: intended destination, not receipt evidence.
Stop: find retained online and no Will. A stored status would survive publisher shutdown.
OK proves no subscriber or hardware result. Observe receipt, recovery and cleanup in the local lab.
Physical measurement kit and handover
For a physical measurement:
- ESP32 DevKit-class board.
- DHT22 with the required data-line pull-up.
- Breadboard and jumper wires.
- Board-compatible USB cable.
Complete the safety and hardware handover before applying power. Follow the sensor-publishing lab for the hardware path.
Publisher code check caption
The Publisher Code Check fragment is in the MQTT setup check page.
This fragment uses iot/sensors/temperature; complete scripts need their network loops.
Where to go next
Choose a next step: move from local receipt to source inspection, hardware, or secured deployment according to what you need to test.
For remote access, test transport protection, client identity and topic permission separately.
Use the sensor-publishing lab for the sensor and hardware path, the local lab for receipt, and the secured-broker lab for secured deployment.
Subscription acceptance
Subscribed to reports a request; broker acceptance requires a successful SUBACK grant (0, 1 or 2 in MQTT 3.1.1), not failure code 128.
Missing acknowledgement means acceptance is unknown; code 128 means refusal, not a waiting receiver.
Numeric receiver
loop_forever() dispatches numeric temperature messages.
Nonnumeric text fails at float(...). Production needs validation.
Legacy section links
The retired objectives, prerequisites, beginner loop, publisher and subscriber procedures, and exercise are in the local loop lab. Sensor source inspection and hardware guidance are in the sensor lab. The reference connection details appear under Connection evidence boundaries.
