IO7: Device-to-cloud messaging: MQTT and CoAP

Lesson 2 of 5 · reading 15–25 minutes; practice and project time is on the module page

MQTT: topics, QoS, retained messages, wills and keepalive

🎯You'll be able to

Use MQTT's main features correctly: topics and wildcards, QoS 0, 1 and 2, retained messages, last wills, keepalive and sessions.

🏠The everyday picture

A noticeboard has sections ("water", "electricity"). A note can be pinned to stay up for latecomers. A neighbour might leave a sealed note with the caretaker: "if I don't come back by evening, tell my family". That's a last will.

📘What it really is

📝A worked example

Input: JalSetu connects once an hour.

Steps:

  1. Connect with a last will: topic jalsetu/S01/T07/status, payload {"state":"offline"}, retained.
  2. Publish a retained status {"state":"online", ...}, then readings with QoS 1, each waiting for its PUBACK.
  3. Before disconnecting, publish a retained {"state":"asleep", ...}, then disconnect properly so the will isn't sent.

Expected output: a dashboard that shows "asleep" between contacts and "offline" only when something went wrong.

🌍Where it's used

📝Case scenario

A dashboard showed every device "online" all night, though they were asleep. Their last status message was "online", retained. Adding an "asleep" status before each disconnect, and a will for real failures, made the dashboard honest.

🖱️Try it

Run python tools/broker.py and subscribe to jalsetu/# with any MQTT client (or the test's paho client). Write down what a new subscriber sees first on a topic with a retained message. Success: the retained message arrives at once.

⚠️Common mistakes

🛠️For your project

Project 2's tests 5, 6 and 8 check QoS 1, the topic and format, the status and the last will.

✅Quick check

What does QoS 1 promise?

Show the answer

At least once: the message is resent until acknowledged, so duplicates are possible.

When does the broker publish a client's last will?

Show the answer

When the connection drops without a proper disconnect.

← PreviousWhy not HTTP for everything?
ProLearners Assist