Skip to content

Run your first MQTT loop on your computer

Follow a local synthetic reading through three terminals, break and repair its route, then replace the clients with Python and test a temperature alert.

Broker Bex, your practice guide

Broker Bex
Broker Bex: I have shown how a reading travels; now let's run the loop on your own computer.
Predict the reading, then compare it with the measurement.

Mosquitto and Python 3 on your computer

Python

Tier 2 · Python · install required · No account

Last tested November 2026.

Download publisher.py, subscriber.py and README.md; follow README.md to run the three-terminal Mosquitto loop, then the two Python clients.

Open the Python run guide (new tab)

Get the files

Download all three prepared files into one folder. No account or paid service is required.

publisher.py

901 bytes · Run guide

Download

subscriber.py

979 bytes · Run guide

Download

README.md

14,920 bytes · Run guide

Download

  1. Put main.py, requirements.txt, and README.md in the same folder.
  2. Create and activate a Python virtual environment, then install requirements.txt.
  3. Run python3 main.py and compare its output with each observed result below.

Steps

The tool may have moved on since the screenshots were taken — the text steps are the contract.

  1. 1 Step 1

    Do
    Prepare one computer and terminal window panels A, B and C. Install Mosquitto broker and command-line clients and put them on your path before testing. Complete this CLI loop before replacing either client with Python. In terminal window panel A run mosquitto -p 1883 -v and keep it running in the foreground. If the address is in use, leave the other service running; use a separate lab host or an unused port consistently in every command and both Python scripts.
    You will see
    • Expect timestamped Starting in local only mode. and Opening ipv4 listen socket on port 1883. messages.
    Why it matters
    Installation comes before the observable exchange. Mosquitto routes messages; mosquitto_pub produces them and mosquitto_sub receives them. These are synthetic values, with no sensor required.
    Real terminal capture for step 1: Expect timestamped Starting in local only mode. and Opening ipv4 listen socket on port 1883. messages.
    Step 1 · Mosquitto and Python 3 on your computer; numbered callout added to a real capture.
  2. 2 Step 2

    Do
    In terminal window panel B run mosquitto_sub -h 127.0.0.1 -p 1883 -t iotclass/sensors/temperature -v -d. Wait for a successful QoS 0 grant. In terminal window panel C run mosquitto_pub -h 127.0.0.1 -p 1883 -t iotclass/sensors/temperature -m 24.0. If the payload is absent, compare exact topics, wait for grant 0 and send again. Resolve subscription denial with the lab broker administrator before retrying.
    You will see
    • Expect CONNACK (0), SUBACK and Subscribed (mid: 1): 0 for the first subscription. Grant 128 or All subscription requests were denied. means refusal. The sender normally exits silently; B should print iotclass/sensors/temperature 24.0.
    Why it matters
    Subscribe before this non-retained send. Label publisher, broker, subscriber, topic, payload and delivery evidence: B displaying the topic and payload proves receipt of those bytes; publisher exit alone does not.
    Real terminal capture for step 2: Expect CONNACK (0), SUBACK and Subscribed (mid: 1): 0 for the first subscription.
    Step 2 · Mosquitto and Python 3 on your computer; numbered callout added to a real capture.
  3. 3 Step 3

    Do
    In terminal window panel C run mosquitto_pub -h 127.0.0.1 -p 1883 -t iotclass/sensors/temperatur -m 24.0. Restore the final e by repeating the correct send from step 2. Then send the correct command twice.
    You will see
    • Expect no new receiver payload line for the misspelled topic, a new reading after repair, and two received-value lines for two correct sends.
    Why it matters
    Exact topic spelling controls this route. Raising QoS cannot repair the missing letter. Keep the failed and repaired topic for comparison later.
    Real terminal capture for step 3: Expect no new receiver payload line for the misspelled topic, a new reading after repair, and two received-value lines for two correct sends.
    Step 3 · Mosquitto and Python 3 on your computer; numbered callout added to a real capture.
  4. 4 Step 4

    Do
    Stop only your broker in terminal window panel A with Control-C and repeat the correct send in terminal window panel C.
    You will see
    • Expect a connection-refused error.
    Why it matters
    This is a transport refusal, not a refused MQTT connection acknowledgement. Check the broker terminal, destination host and port before debugging the payload.
    Real terminal capture for step 4: Expect a connection-refused error.
    Step 4 · Mosquitto and Python 3 on your computer; numbered callout added to a real capture.
  5. 5 Step 5

    Do
    Restart your broker in terminal window panel A and restart the receiver in terminal window panel B using steps 1 and 2. Wait for a successful QoS 0 grant, then resend 24.0 in terminal window panel C. If receipt does not return, check host, port and exact topic again. Write down the last successful checkpoint before changing anything.
    You will see
    • Expect the payload line to return after the broker and receiver restart and a fresh send.
    Why it matters
    No CONNACK calls for endpoint checks. Accepted connection without a successful SUBACK calls for inspecting the grant: missing acknowledgement leaves acceptance unknown; 128 means refusal. After a successful grant, compare topics and resend while the receiver waits. If bytes arrive but the application fails, inspect the numeric format.
    Real terminal capture for step 5: Expect the payload line to return after the broker and receiver restart and a fresh send.
    Step 5 · Mosquitto and Python 3 on your computer; numbered callout added to a real capture.
  6. 6 Step 6

    Do
    Save tool versions, host, port, exact topic, SUBACK grant code, received payload and the failure/recovery observations. In each terminal window panel, stop your receiver and only your broker with Control-C, then repeat the correct send. If it succeeds, check the destination and whether another broker is listening. Restart your own broker for the Python extension.
    You will see
    • Expect both terminals to return to their shells and a new send to fail after your broker stops.
    Why it matters
    Keep receipt and recovery together. This plaintext local test establishes neither TLS nor authentication nor physical measurement. The downloadable README has a worksheet for the connection record and source-inspection follow-ons.
    Real terminal capture for step 6: Expect both terminals to return to their shells and a new send to fail after your broker stops.
    Step 6 · Mosquitto and Python 3 on your computer; numbered callout added to a real capture.
  7. 7 Step 7

    Do
    Download publisher.py, subscriber.py and README.md into a new lab folder. Read README.md before using the generic file-panel commands: this lab runs two named clients, not main.py. Run python3 -m venv .venv, then . .venv/bin/activate, then python -m pip install paho-mqtt==2.1.0. Run python --version and python -c 'from importlib.metadata import version; print(version("paho-mqtt"))'. Record differing versions. If venv is missing, install platform support. Activate the environment in both Python terminals; check that selection for an import failure. Run one copy per client identifier.
    You will see
    • Expect your Python version and 2.1.0 from the version commands.
    Why it matters
    Save a script, run it and stop your own foreground program with Control-C. The supplied files preserve the original examples. Both use loopback, port 1883 and iotclass/sensors/temperature; keep the broker and topic together when changing environments.
    Real terminal capture for step 7: Expect your Python version and 2.1.0 from the version commands.
    Step 7 · Mosquitto and Python 3 on your computer; numbered callout added to a real capture.
  8. 8 Step 8

    Do
    Use terminal window panel A's broker; if stopped run mosquitto -p 1883 -v. In terminal window panel C activate the environment and run python -u publisher.py. Stop B's CLI receiver if it is still running, activate the environment there and run python -u subscriber.py. Compare received values with publisher output. If only the sender prints, inspect receiver host/topic, its network loop and errors. For connection refusal, check A and the port. Stop the publisher with Control-C after comparison.
    You will see
    • Expect Published: ...C about every five seconds, then Stopping publisher... on Control-C. The subscriber prints Connected with reason code Success, Subscribed to iotclass/sensors/temperature and incoming readings.
    Why it matters
    The broker and topic stay fixed while the clients change. The publisher network loop processes traffic during sleeps; loop_forever dispatches numeric messages at the receiver. Subscribed to reports a request, not a successful SUBACK: acceptance requires grant 0, 1 or 2 in MQTT 3.1.1, rather than refusal code 128. Send completion differs from receipt.
    Real terminal capture for step 8: Expect Published: ...C about every five seconds, then Stopping publisher... on Control-C.
    Step 8 · Mosquitto and Python 3 on your computer; numbered callout added to a real capture.
  9. 9 Step 9

    Do
    Keep the Python subscriber running. In terminal window panel C repeat the CLI 24.0 command, then run mosquitto_pub -h 127.0.0.1 -p 1883 -t iotclass/sensors/temperature -m 30.0. If no warning appears, check that you sent thirty: the random publisher generates only fifteen through twenty-five. Repeat the misspelled-topic send with this receiver, restore the topic and resend. Repeat the stopped-broker test; restart your broker and subscriber and resend to recover. Nonnumeric text fails at float(...); restart and send valid data if this happens.
    You will see
    • Expect Received: 24.0C from iotclass/sensors/temperature without a warning. For 30.0 expect Received: 30.0C from iotclass/sensors/temperature and Warning: High temperature detected!. The wrong topic gives silence; repair gives a new reading. A stopped broker gives connection refusal.
    Why it matters
    The alert tests a strict greater-than-twenty-five threshold. Receiving numeric bytes and applying that comparison do not establish who supplied them. The random publisher cannot exceed this threshold; use the controlled 30.0 send.
    Real terminal capture for step 9: Expect Received: 24.0C from iotclass/sensors/temperature without a warning.
    Step 9 · Mosquitto and Python 3 on your computer; numbered callout added to a real capture.
  10. 10 Step 10

    Do
    Record evidence: keep both threshold results with CLI receipt, wrong-topic failure and recovery. Complete the README connection worksheet and source-inspection follow-ons separately from runtime evidence. In each terminal window panel, stop your Python clients and only your own broker with Control-C, then repeat a send to check cleanup. Run deactivate in each Python shell. Carry your working host, failed/repaired topics and receiver trace into the next exercise before adding recovery logic.
    You will see
    • Expect the shells to return and a new send to fail after the broker stops. Stopping the Python subscriber with Control-C prints a KeyboardInterrupt traceback because the script does not catch it; that is expected here.
    Why it matters
    Prove the receiver prints the intended value before adding more moving parts. A different broker or regenerated sensor topic root can explain later silence before changing delivery policy. Benchmark the actual broker before making a capacity decision.
    Real terminal capture for step 10: Expect the shells to return and a new send to fail after the broker stops.
    Step 10 · Mosquitto and Python 3 on your computer; numbered callout added to a real capture.

Chapter checks

These questions refer to the chapter’s examples. Use the return links to review their answers.

  1. In an MQTT-based temperature monitoring system, an ESP32 sensor node reads temperature data and sends it to a broker. A Python dashboard running on a laptop displays the readings. Which statement correctly identifies each component's role?

    Return to the chapter’s knowledge check
  2. This chapter's 'Common Mistake' warning concerns the unauthenticated, plaintext port 1883 listener at test.mosquitto.org. Which of the following is one of its four production dangers?

    Return to the chapter’s knowledge check

Caution

Before you start

Read this before you start.

Use synthetic values on your own local broker. These QoS 0, non-retained clients configure no Will and provide no TLS or authentication. The subscriber expects numeric text and needs input validation for production. Stop only your own foreground processes; leave an occupied port and its service alone.

Technical details
Version tested
Version tested: Mosquitto broker and clients 2.0.20; Python 3.12.16; paho-mqtt 2.1.0; Xfce Terminal 1.0.4 on Xvfb; local 127.0.0.1 only.. Date: 2026-11-04.
QR code that opens the Run your first MQTT loop on your computer lab page
Open this lab online: https://iotclass.org/labs/mqtt-local-first-loop.html

Return to MQTT Publish-Subscribe Basics · Browse Labs