# Run your first MQTT loop on your computer

I’m Bex. First prove one local receipt, then change the clients and test the alert.
Allow about 60 minutes for the local loop and Python extension. The source and
connection follow-ons below are optional inspection work.

## Files and setup

Save publisher.py, subscriber.py and this README.md in one new lab folder.
There is no main.py or requirements.txt in this lab. The website’s generic
three-file Python instructions do not describe these two clients; use this guide.
The scripts are the original chapter’s complete examples, unchanged. Install
Mosquitto broker and its command-line clients before starting. You also need
Python 3 and virtual-environment support. No sensor or account is required.

This packet was run for real on 2026-11-04 with Mosquitto 2.0.20, Python 3.12.16
and paho-mqtt 2.1.0 on Linux, using three Xfce Terminal windows and 127.0.0.1 only;
the step screenshots on the lab page are captures of that run. The original author
runtime record, dated 2026-10-25, lists Mosquitto 2.0.11, Python 3.13.2 and
paho-mqtt 2.1.0. Timestamps, client IDs and random readings differ on every run.
Record your own versions and observations.

Open three terminals in the lab folder: A for your foreground broker, B for
the receiver and C for the sender. Stop only your own foreground programs with
Control-C. If port 1883 is occupied, leave that service running; choose a separate
lab host or an unused port and change every command and both scripts consistently.
The unchanged downloads use 127.0.0.1:1883 and iotclass/sensors/temperature.

## Step 1

Prepare one computer and terminals 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 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.

Expected: Expect timestamped `Starting in local only mode.` and `Opening ipv4 listen socket on port 1883.` messages.

Why: 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.

## Step 2

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

Expected: 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: 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.

## Step 3

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

Expected: 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: Exact topic spelling controls this route. Raising QoS cannot repair the missing letter. Keep the failed and repaired topic for comparison later.

## Step 4

Stop only your broker in A with Control-C and repeat the correct send in C.

Expected: Expect a connection-refused error.

Why: This is a transport refusal, not a refused MQTT connection acknowledgement. Check the broker terminal, destination host and port before debugging the payload.

## Step 5

Restart your broker in A and restart the receiver in B using steps 1 and 2. Wait for a successful QoS 0 grant, then resend 24.0 in C. If receipt does not return, check host, port and exact topic again. Write down the last successful checkpoint before changing anything.

Expected: Expect the payload line to return after the broker and receiver restart and a fresh send.

Why: 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.

## Step 6

Save tool versions, host, port, exact topic, SUBACK grant code, received payload and the failure/recovery observations. 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.

Expected: Expect both terminals to return to their shells and a new send to fail after your broker stops.

Why: 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.

## Step 7

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.

Expected: Expect your Python version and `2.1.0` from the version commands.

Why: 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.

## Step 8

Use terminal A's broker; if stopped run `mosquitto -p 1883 -v`. In 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.

Expected: 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: 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.

## Step 9

Keep the Python subscriber running. In 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.

Expected: 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: 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.

## Step 10

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

Expected: Expect the shells to return and a new send to fail after the broker stops.

Why: 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.

## Connection and receipt worksheet (step 10)

Record your actual observations; leave an unobserved item marked unobserved.

| Item | Your record |
| --- | --- |
| Mosquitto broker and client versions; Python and Paho versions | |
| Host and port; exact subscribed and published topics | |
| CONNECT client identifier, clean-session setting, keep-alive | |
| CONNACK acceptance or refusal; Session Present result | |
| SUBACK grant code (CLI requests and checks QoS 0) | |
| Receiver topic and payload; interpreted value | |
| Wrong topic; repaired topic; two-send count | |
| Stopped-broker refusal; restarted receipt | |
| 24.0 without warning; 30.0 with warning | |
| Cleanup and post-stop send result | |

Read the exchange in order: the client sends CONNECT to ask for a session,
then the broker replies with CONNACK. Later PINGREQ and PINGRESP check an
otherwise quiet connection; none of those packets proves payload receipt.
Write the chosen client identifier beside clean-session settings and the broker’s
Session Present result. A same-name restart does not prove old state survived.
Use one copy per identifier (TempSensor_001 and Dashboard_001 in the downloads).

Compare two records. Keep a broker log or packet trace of client identifier,
session settings, keep-alive, connection acceptance and the publish-subscribe
path. The broker trace can show acceptance and the subscription exchange;
the receiver trace can show payload parsing. The provided Python subscriber
prints its subscription request and does not log SUBACK or Session Present;
use the CLI debug output/broker trace for those checkpoints and do not label its
request print as acceptance. Missing acknowledgement means acceptance is unknown.

Label the local receipt: mosquitto_pub (then Python) is publisher, Mosquitto is
broker, mosquitto_sub (then Python) is subscriber, iotclass/sensors/temperature
is topic, 24.0 is payload, and the receiver’s topic/payload line is delivery
evidence. The Paho library supplies Python MQTT clients; Client ID identifies a
connection and is separate from a topic. Installation precedes listening,
subscription precedes the non-retained send, and receipt precedes interpretation.

Keep transport refusal separate from refused CONNACK. Test credential refusal
only in a separate exercise on a controlled authenticated broker. This local
packet uses no credentials and does not perform that test.

## Source inspection and next steps (step 10, optional)

Keep these written source findings separate from simulation, hardware and local
runtime evidence. Read the existing files alongside the sensor lab:

- Circuit: /practice/mqtt-sensor-publish/diagram.json
- Sketch: /practice/mqtt-sensor-publish/sketch.ino
- Library list: /practice/mqtt-sensor-publish/libraries.txt
- Guided sensor lab: /labs/mqtt-sensor-publish.html

Find the diagram’s temperature attribute (24), humidity (40), ESP32, DHT22 and
D4 label. Trace Serial.begin(115200). Locate the connection branch: Connected
requires client.connect returning true; failure prints a code and retries.
Locate DHT read failure and temperature/humidity output; OK or FAIL follows
the publish result and is not subscriber receipt. Trace thirty degrees through
dtostrf: width six, two decimal places. Find mqtt_server, topic_root and the
/temperature suffix. Keep this environment’s broker and current generated topic
together; do not substitute the local Python topic or treat a source finding as
a remote receipt. Source alone proves neither a build nor a browser run.

If choosing physical measurement later, the original kit is an ESP32
DevKit-class board, a DHT22 with the required data-line pull-up, breadboard and
jumper wires, and a board-compatible USB cable. Complete the sensor lab’s
safety check and hardware handover before applying power. This local lab needs
no hardware.

Before reviewing roles, assign them for this source example: a garden ESP32
sends {"moisture": 45, "status": "needs_water"} on garden/moisture/plant1 and
a phone should notify its owner. Then compare: the ESP32 publishes, the broker
routes to authorized matching subscriptions, and the phone or supporting service
subscribes and interprets the payload. Forty-five is an example, not a calibrated
watering threshold.

For the original publisher completion exercise, fill these two blanks on paper:

```python
# Separate fragment, not either runnable download.
# This fragment uses iot/sensors/temperature (without "class").
PORT = ____
# TOPIC = "iot/sensors/temperature"
# Complete the publish call:
____(TOPIC, str(random.uniform(20, 30)))
```

Compare your answers with PORT = 1883 and
client.publish(TOPIC, str(random.uniform(20, 30))). The original quiz fragment
names a public test broker; do not run it as the local baseline. Complete clients
need network loops. Save and run the supplied publisher.py and subscriber.py
instead. The receiver’s loop_forever() dispatches numeric messages; nonnumeric
text fails at float(...). If that happens, restart and send valid numeric data;
production code needs input validation.

For the next recovery exercise, carry the known host, exact topic and receiver
trace while adding recovery logic. Carry both the failed topic and repaired topic;
a changed broker address or regenerated sensor root may explain silence before
a delivery-policy change is needed. Prove the receiver prints the intended value
before adding more moving parts. Benchmark the actual broker before making a
capacity decision; a worksheet estimate is not a measured broker ceiling.
