Files
skills/public/protocols-mqtt-messaging.html
zeekayandHanzo Dev 9e10c1c10e Each llms index points at the other two
hanzoskills.com/llms.txt now opens with the install line, the API
reference index and the company index, so an agent that lands on any
one of the three can find the rest.

robots.txt claimed 537 documents while llms.txt counts 920. The number
is gone from robots.txt; llms.txt derives it.

public/ is regenerated from scripts/site.py, which it had fallen
behind: the copy-prompt menu and agent bar were in the generator and
not in the committed pages. tests/site.mjs passes against the result.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-11 00:27:59 -07:00

778 lines
42 KiB
HTML

<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>protocols-mqtt-messaging</title>
<meta name="color-scheme" content="dark">
<style>
/* Committed to one visual world: a dark instrument panel. No light variant —
the dot field and the hairline rules only read on black, and a naive
inversion would wash both out. Every colour is painted explicitly so the page
never borrows a host background. */
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
:root{
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
--font-zen-pixel-square:'Zen Pixel Square',monospace;
--mono:var(--font-zen-mono);
--sans:var(--font-zen-sans);
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
--r:999px; --r-soft:14px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
/* The dot field. A halftone made of one repeating radial-gradient, faded out
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
/* No overflow clip here: the dot field is inset to the box already, and a clip
would cut off the copy-prompt menu. */
.hero{position:relative;border-bottom:1px solid var(--line)}
.hero::before{content:"";position:absolute;inset:0;
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
background-size:7px 7px;
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
pointer-events:none}
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
nav{border-bottom:1px solid var(--line)}
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
justify-content:space-between;align-items:center;gap:1rem}
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--ink);text-decoration:none;
display:inline-flex;align-items:center;gap:.6rem}
.brand i{font-style:normal;color:var(--faint)}
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--soft);text-decoration:none}
nav a.up:hover{color:var(--ink)}
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
h1 em{font-style:normal;color:var(--faint)}
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
line-height:1.2;font-weight:400}
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
.btn.solid:hover{background:#d8d8d4}
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
/* Copy-prompt selector. Each row copies the prompt for its own target. */
.copy{position:relative;display:inline-flex}
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
padding:.4rem;display:flex;flex-direction:column;
box-shadow:0 12px 32px rgba(0,0,0,.75)}
.menu[hidden]{display:none}
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
white-space:nowrap}
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
.mi:hover .mark{color:var(--ink)}
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
letter-spacing:.1em;text-transform:uppercase}
/* Works-with bar: one scrolling row, name and mark per agent. */
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
display:flex;align-items:center}
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
-webkit-overflow-scrolling:touch;
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
.bar::-webkit-scrollbar{display:none}
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
text-decoration:none;background:var(--ground)}
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
.agent .mark{width:.95rem;height:.95rem}
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
p{margin:0 0 1rem;max-width:70ch}
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
li{margin:.22rem 0}
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
text-decoration-color:var(--line-hi)}
a:hover{text-decoration-color:var(--ink)}
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
display:block;overflow-x:auto}
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
.curl{display:block;background:var(--panel);border:1px solid var(--line);
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
white-space:pre;line-height:1.9}
.curl b{color:var(--ink);font-weight:400}
.curl i{font-style:normal;color:var(--faint)}
/* index */
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
#q:focus{outline:none;border-color:var(--soft)}
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
text-transform:uppercase;margin:0 0 2rem}
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
padding-bottom:.45rem}
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
border-radius:var(--r-soft);text-decoration:none}
.row:hover{background:#0a0a0a}
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
color:var(--faint);font-size:.85rem}
footer a{color:var(--soft)}
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
margin:0 0 2rem;font-size:.85rem}
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
border-bottom:1px solid var(--line);padding-bottom:.4rem}
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
.fmap a:hover{text-decoration:underline}
.fmap div{color:var(--faint);line-height:1.5}
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
@media (max-width:640px){
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
.btns{gap:.5rem}
.btn{padding:.75rem 1.15rem;font-size:.68rem}
.copy,.copy .btn{width:100%;justify-content:center}
.menu{left:0;right:0;min-width:0}
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
.strip b{border-right:0;padding-right:0}
.bar{width:100%}
}
</style>
<link rel="alternate" type="text/markdown" href="/protocols-mqtt-messaging.md">
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/protocols-mqtt-messaging">
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/protocols-mqtt-messaging.md
Index: https://hanzoskills.com/llms.txt
Corpus: https://hanzoskills.com/all.md
Append .md to any path for the markdown twin. -->
<body>
<nav><div class="in">
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
<a class="up" href="/">All skills</a>
</div></nav>
<div class="wrap">
<h1>protocols-mqtt-messaging</h1><p class="lede">MQTT pub-sub messaging for IoT and real-time applications</p><h1>MQTT Messaging</h1>
<p><strong>Scope</strong>: MQTT protocol, pub-sub patterns, QoS levels, broker configuration, IoT integration <strong>Lines</strong>: ~400 <strong>Last Updated</strong>: 2025-10-27</p>
<h2>When to Use This Skill</h2>
<p>Activate this skill when:</p>
<ul><li>Implementing MQTT pub-sub messaging systems</li><li>Building IoT device communication</li><li>Designing lightweight messaging protocols</li><li>Implementing real-time sensor data collection</li><li>Setting up MQTT brokers (Mosquitto, EMQX, HiveMQ)</li><li>Configuring QoS levels and message delivery guarantees</li><li>Implementing retained messages and last will</li><li>Designing topic hierarchies and wildcard subscriptions</li><li>Securing MQTT with TLS and authentication</li><li>Integrating with cloud IoT platforms (AWS IoT Core, Azure IoT Hub)</li></ul>
<h2>Core Concepts</h2>
<h3>MQTT Architecture</h3>
<p><strong>MQTT</strong> (Message Queuing Telemetry Transport): Lightweight pub-sub protocol designed for constrained devices and unreliable networks.</p>
<p><strong>Key characteristics</strong>:</p>
<ul><li><strong>Publish-Subscribe</strong>: Decoupled message pattern (publishers don&#x27;t know subscribers)</li><li><strong>Lightweight</strong>: Minimal 2-byte header overhead</li><li><strong>QoS levels</strong>: Three levels of delivery guarantees (0, 1, 2)</li><li><strong>TCP/IP transport</strong>: Reliable, ordered delivery (or WebSocket for browsers)</li><li><strong>Broker-based</strong>: Central broker routes messages between clients</li><li><strong>Topic-based routing</strong>: Hierarchical topics with wildcard subscriptions</li></ul>
<p><strong>Architecture components</strong>:</p>
<pre><code>Publisher → Broker → Subscriber(s)
↓
Topics + QoS
↓
Retained Messages
Last Will Testament</code></pre>
<hr>
<h2>MQTT Basics</h2>
<h3>Connection Flow</h3>
<pre><code>Client Broker
| |
|-- CONNECT (clientId, auth) -----&gt;|
| |
|&lt;-- CONNACK (session present) -----|
| |
|-- SUBSCRIBE (topic, QoS) --------&gt;|
| |
|&lt;-- SUBACK (granted QoS) ----------|
| |
|-- PUBLISH (topic, payload, QoS) -&gt;|
| |
|&lt;-- PUBACK (if QoS 1+) ------------|
| |
|-- DISCONNECT ----------------------&gt;|</code></pre>
<h3>QoS Levels</h3>
<p><strong>QoS 0 - At Most Once</strong> (Fire and forget):</p>
<ul><li>No acknowledgment or retransmission</li><li>Message may be lost</li><li>Fastest, lowest overhead</li><li>Use case: Non-critical data (sensor readings where loss is acceptable)</li></ul>
<p><strong>QoS 1 - At Least Once</strong> (Acknowledged delivery):</p>
<ul><li>Message acknowledged with PUBACK</li><li>Message may be delivered multiple times</li><li>Moderate overhead</li><li>Use case: Important messages where duplicates are acceptable</li></ul>
<p><strong>QoS 2 - Exactly Once</strong> (Assured delivery):</p>
<ul><li>Four-way handshake (PUBLISH → PUBREC → PUBREL → PUBCOMP)</li><li>Message delivered exactly once</li><li>Highest overhead</li><li>Use case: Critical messages (billing, alarms)</li></ul>
<pre><code class="lang-python"># QoS comparison
qos_0 = client.publish(&quot;sensor/temp&quot;, &quot;22.5&quot;, qos=0) # No ACK
qos_1 = client.publish(&quot;sensor/temp&quot;, &quot;22.5&quot;, qos=1) # PUBACK required
qos_2 = client.publish(&quot;alarm/fire&quot;, &quot;triggered&quot;, qos=2) # 4-way handshake</code></pre>
<hr>
<h2>Topic Design</h2>
<h3>Topic Hierarchy</h3>
<p>Topics are UTF-8 strings using <code>/</code> as separator:</p>
<pre><code># Good topic hierarchy
home/bedroom/temperature
home/bedroom/humidity
home/livingroom/temperature
factory/line1/machine5/status
factory/line1/machine5/telemetry
# Topic components
{domain}/{location}/{device}/{measurement}</code></pre>
<h3>Wildcards</h3>
<p><strong>Single-level wildcard (<code>+</code>)</strong>:</p>
<ul><li>Matches one topic level</li><li><code>home/+/temperature</code> matches <code>home/bedroom/temperature</code> and <code>home/kitchen/temperature</code></li></ul>
<p><strong>Multi-level wildcard (<code>#</code>)</strong>:</p>
<ul><li>Matches zero or more topic levels (must be last character)</li><li><code>home/#</code> matches <code>home/bedroom/temperature</code> and <code>home/bedroom/humidity</code></li></ul>
<pre><code class="lang-python"># Wildcard subscriptions
client.subscribe(&quot;home/+/temperature&quot;) # All rooms&#x27; temperature
client.subscribe(&quot;home/bedroom/#&quot;) # All bedroom sensors
client.subscribe(&quot;#&quot;) # All topics (expensive!)</code></pre>
<h3>Topic Best Practices</h3>
<p><strong>DO</strong>:</p>
<ul><li>Use hierarchical structure: <code>domain/location/device/metric</code></li><li>Keep topics descriptive and consistent</li><li>Use lowercase with underscores: <code>home/living_room/temp</code></li><li>Limit topic depth (3-7 levels)</li><li>Avoid leading/trailing slashes</li></ul>
<p><strong>DON&#x27;T</strong>:</p>
<ul><li>Don&#x27;t use spaces or special characters</li><li>Don&#x27;t use topics starting with <code>$</code> (reserved for broker)</li><li>Don&#x27;t subscribe to <code>#</code> wildcard (high load)</li><li>Don&#x27;t embed data in topics: <code>sensor/temp/22.5</code> (use payload)</li></ul>
<hr>
<h2>Python Client Implementation</h2>
<h3>Basic Publisher</h3>
<pre><code class="lang-python">import paho.mqtt.client as mqtt
import json
import time
class MQTTPublisher:
def __init__(self, broker, port=1883, client_id=None):
self.broker = broker
self.port = port
self.client = mqtt.Client(client_id=client_id)
# Callbacks
self.client.on_connect = self.on_connect
self.client.on_publish = self.on_publish
self.client.on_disconnect = self.on_disconnect
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
print(f&quot;Connected to {self.broker}:{self.port}&quot;)
else:
print(f&quot;Connection failed: {rc}&quot;)
def on_publish(self, client, userdata, mid):
print(f&quot;Message {mid} published&quot;)
def on_disconnect(self, client, userdata, rc):
if rc != 0:
print(f&quot;Unexpected disconnect: {rc}&quot;)
def connect(self):
self.client.connect(self.broker, self.port, keepalive=60)
self.client.loop_start()
def publish(self, topic, payload, qos=0, retain=False):
&quot;&quot;&quot;Publish message to topic&quot;&quot;&quot;
if isinstance(payload, dict):
payload = json.dumps(payload)
result = self.client.publish(topic, payload, qos=qos, retain=retain)
return result.mid
def disconnect(self):
self.client.loop_stop()
self.client.disconnect()
# Usage
publisher = MQTTPublisher(&quot;mqtt.example.com&quot;)
publisher.connect()
# Publish sensor data
publisher.publish(&quot;home/bedroom/temperature&quot;, &quot;22.5&quot;, qos=1)
publisher.publish(&quot;home/bedroom/humidity&quot;, &quot;65&quot;, qos=1)
# Publish JSON
publisher.publish(&quot;sensor/data&quot;, {
&quot;device_id&quot;: &quot;sensor_01&quot;,
&quot;temperature&quot;: 22.5,
&quot;humidity&quot;: 65,
&quot;timestamp&quot;: time.time()
}, qos=1)
time.sleep(2)
publisher.disconnect()</code></pre>
<h3>Basic Subscriber</h3>
<pre><code class="lang-python">import paho.mqtt.client as mqtt
import json
class MQTTSubscriber:
def __init__(self, broker, port=1883, client_id=None):
self.broker = broker
self.port = port
self.client = mqtt.Client(client_id=client_id)
# Callbacks
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.on_subscribe = self.on_subscribe
self.client.on_disconnect = self.on_disconnect
# Message handlers
self.handlers = {}
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
print(f&quot;Connected to {self.broker}:{self.port}&quot;)
# Resubscribe on reconnect
for topic, qos in self.handlers.keys():
client.subscribe(topic, qos)
else:
print(f&quot;Connection failed: {rc}&quot;)
def on_message(self, client, userdata, msg):
topic = msg.topic
payload = msg.payload.decode()
qos = msg.qos
print(f&quot;Received: {topic} (QoS {qos}): {payload}&quot;)
# Call registered handler
for (handler_topic, handler_qos), handler_func in self.handlers.items():
if self.topic_matches(topic, handler_topic):
handler_func(topic, payload, qos)
def on_subscribe(self, client, userdata, mid, granted_qos):
print(f&quot;Subscribed (QoS {granted_qos})&quot;)
def on_disconnect(self, client, userdata, rc):
if rc != 0:
print(f&quot;Unexpected disconnect: {rc}&quot;)
def topic_matches(self, topic, pattern):
&quot;&quot;&quot;Check if topic matches pattern with wildcards&quot;&quot;&quot;
# Simplified matching (paho does this internally)
return mqtt.topic_matches_sub(pattern, topic)
def connect(self):
self.client.connect(self.broker, self.port, keepalive=60)
self.client.loop_start()
def subscribe(self, topic, qos=0, handler=None):
&quot;&quot;&quot;Subscribe to topic with optional handler&quot;&quot;&quot;
self.client.subscribe(topic, qos)
if handler:
self.handlers[(topic, qos)] = handler
def disconnect(self):
self.client.loop_stop()
self.client.disconnect()
# Usage
subscriber = MQTTSubscriber(&quot;mqtt.example.com&quot;)
# Register handler
def handle_temperature(topic, payload, qos):
temp = float(payload)
if temp &gt; 25:
print(f&quot;High temperature alert: {temp}°C&quot;)
subscriber.subscribe(&quot;home/+/temperature&quot;, qos=1, handler=handle_temperature)
subscriber.connect()
# Keep running
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
subscriber.disconnect()</code></pre>
<hr>
<h2>Advanced Features</h2>
<h3>Retained Messages</h3>
<p><strong>Retained messages</strong> are stored by the broker and delivered to new subscribers immediately.</p>
<pre><code class="lang-python"># Publish retained message (e.g., device status)
client.publish(&quot;device/status&quot;, &quot;online&quot;, qos=1, retain=True)
# New subscribers immediately receive last retained message
# Use case: Device status, configuration, last known value</code></pre>
<p><strong>Use cases</strong>:</p>
<ul><li>Device online/offline status</li><li>Last known sensor value</li><li>System configuration</li></ul>
<p><strong>Clear retained message</strong>:</p>
<pre><code class="lang-python">client.publish(&quot;device/status&quot;, &quot;&quot;, qos=1, retain=True) # Empty payload clears</code></pre>
<h3>Last Will and Testament (LWT)</h3>
<p><strong>LWT</strong> is a message automatically sent by broker if client disconnects unexpectedly.</p>
<pre><code class="lang-python">client = mqtt.Client()
# Set last will (sent if client disconnects without DISCONNECT)
client.will_set(
topic=&quot;device/status&quot;,
payload=&quot;offline&quot;,
qos=1,
retain=True
)
client.connect(&quot;mqtt.example.com&quot;)
# If client crashes or loses connection, broker publishes &quot;offline&quot;</code></pre>
<p><strong>Use cases</strong>:</p>
<ul><li>Device presence detection</li><li>Connection monitoring</li><li>Automatic cleanup</li></ul>
<h3>Clean Session vs Persistent Session</h3>
<p><strong>Clean Session = True</strong> (default):</p>
<ul><li>Broker discards all session state on disconnect</li><li>Subscriptions not preserved</li><li>Queued messages discarded</li></ul>
<p><strong>Clean Session = False</strong> (persistent):</p>
<ul><li>Broker stores subscriptions and QoS 1+ messages</li><li>Messages delivered when client reconnects</li><li>Use same client ID to resume session</li></ul>
<pre><code class="lang-python"># Persistent session
client = mqtt.Client(client_id=&quot;sensor_01&quot;, clean_session=False)
client.connect(&quot;mqtt.example.com&quot;)
# Subscribe with QoS 1
client.subscribe(&quot;commands/sensor_01&quot;, qos=1)
# Even if disconnected, messages are queued and delivered on reconnect</code></pre>
<hr>
<h2>Security</h2>
<h3>TLS/SSL Encryption</h3>
<pre><code class="lang-python">import ssl
client = mqtt.Client()
# TLS with server certificate verification
client.tls_set(
ca_certs=&quot;/path/to/ca.crt&quot;,
certfile=&quot;/path/to/client.crt&quot;, # Optional client cert
keyfile=&quot;/path/to/client.key&quot;, # Optional client key
tls_version=ssl.PROTOCOL_TLSv1_2
)
client.connect(&quot;mqtt.example.com&quot;, port=8883) # TLS port</code></pre>
<h3>Username/Password Authentication</h3>
<pre><code class="lang-python">client = mqtt.Client()
client.username_pw_set(username=&quot;sensor_01&quot;, password=&quot;secret&quot;)
client.connect(&quot;mqtt.example.com&quot;)</code></pre>
<h3>Token-Based Authentication (AWS IoT Core)</h3>
<pre><code class="lang-python"># AWS IoT Core uses mutual TLS (certificate-based)
client = mqtt.Client()
client.tls_set(
ca_certs=&quot;AmazonRootCA1.pem&quot;,
certfile=&quot;device.pem.crt&quot;,
keyfile=&quot;device.pem.key&quot;,
tls_version=ssl.PROTOCOL_TLSv1_2
)
client.connect(&quot;xxxxxx-ats.iot.us-east-1.amazonaws.com&quot;, port=8883)</code></pre>
<hr>
<h2>MQTT Brokers</h2>
<h3>Mosquitto (Open Source)</h3>
<p><strong>Lightweight broker</strong> for development and small deployments.</p>
<pre><code class="lang-bash"># Install
sudo apt-get install mosquitto mosquitto-clients
# Start broker
mosquitto -c /etc/mosquitto/mosquitto.conf
# Test with CLI
mosquitto_sub -h localhost -t &quot;test/topic&quot;
mosquitto_pub -h localhost -t &quot;test/topic&quot; -m &quot;Hello&quot;</code></pre>
<p><strong>Configuration</strong> (<code>/etc/mosquitto/mosquitto.conf</code>):</p>
<pre><code># Basic config
listener 1883
allow_anonymous true
# TLS config
listener 8883
cafile /path/to/ca.crt
certfile /path/to/server.crt
keyfile /path/to/server.key
require_certificate false
# Authentication
password_file /etc/mosquitto/passwd</code></pre>
<h3>EMQX (Scalable, Enterprise)</h3>
<p><strong>High-performance broker</strong> for large-scale IoT deployments.</p>
<pre><code class="lang-bash"># Docker deployment
docker run -d --name emqx \
-p 1883:1883 \
-p 8083:8083 \
-p 8084:8084 \
-p 8883:8883 \
-p 18083:18083 \
emqx/emqx:latest
# Dashboard: http://localhost:18083 (admin/public)</code></pre>
<p><strong>Features</strong>:</p>
<ul><li>Clustering and scalability (millions of connections)</li><li>Rule engine for data processing</li><li>Built-in authentication (JWT, database, HTTP)</li><li>Metrics and monitoring</li></ul>
<h3>HiveMQ (Enterprise)</h3>
<p><strong>Production-grade broker</strong> with enterprise features.</p>
<p><strong>Features</strong>:</p>
<ul><li>High availability and clustering</li><li>Kafka integration</li><li>Security (TLS, OAuth, LDAP)</li><li>Management dashboard</li></ul>
<hr>
<h2>Common Patterns</h2>
<h3>Request-Response Pattern</h3>
<p>MQTT is pub-sub, but request-response can be implemented:</p>
<pre><code class="lang-python"># Client sends request with reply topic
request_payload = json.dumps({
&quot;command&quot;: &quot;get_status&quot;,
&quot;reply_to&quot;: f&quot;responses/{client_id}&quot;
})
client.subscribe(f&quot;responses/{client_id}&quot;, qos=1)
client.publish(&quot;commands/device_01&quot;, request_payload, qos=1)
# Device responds to reply_to topic
def on_message(client, userdata, msg):
request = json.loads(msg.payload)
reply_topic = request.get(&quot;reply_to&quot;)
response = {&quot;status&quot;: &quot;online&quot;, &quot;uptime&quot;: 3600}
client.publish(reply_topic, json.dumps(response), qos=1)</code></pre>
<h3>IoT Device Telemetry</h3>
<pre><code class="lang-python"># Device sends periodic telemetry
def send_telemetry():
while True:
telemetry = {
&quot;device_id&quot;: &quot;sensor_01&quot;,
&quot;temperature&quot;: read_temperature(),
&quot;humidity&quot;: read_humidity(),
&quot;battery&quot;: get_battery_level(),
&quot;timestamp&quot;: time.time()
}
client.publish(
f&quot;devices/{device_id}/telemetry&quot;,
json.dumps(telemetry),
qos=1
)
time.sleep(60) # Every minute</code></pre>
<h3>Command and Control</h3>
<pre><code class="lang-python"># Backend sends commands to devices
client.publish(
&quot;commands/sensor_01/update_config&quot;,
json.dumps({&quot;interval&quot;: 30}),
qos=1
)
# Device subscribes to commands
client.subscribe(&quot;commands/sensor_01/#&quot;, qos=1)
def on_message(client, userdata, msg):
command = msg.topic.split(&quot;/&quot;)[-1]
payload = json.loads(msg.payload)
if command == &quot;update_config&quot;:
update_config(payload)
elif command == &quot;reboot&quot;:
reboot_device()</code></pre>
<hr>
<h2>Anti-Patterns</h2>
<p>❌ <strong>Subscribing to <code>#</code> wildcard</strong>: Receives all messages (broker load) ✅ Use specific wildcards: <code>home/+/temperature</code></p>
<p>❌ <strong>Using QoS 2 everywhere</strong>: Highest overhead (4-way handshake) ✅ Use QoS 0 for non-critical data, QoS 1 for most cases, QoS 2 only when required</p>
<p>❌ <strong>Large payloads (&gt;1 MB)</strong>: MQTT is for small messages ✅ Keep payloads small (&lt;10 KB), use external storage for large data</p>
<p>❌ <strong>Embedding data in topics</strong>: <code>sensor/temp/22.5</code> ✅ Use topics for routing, payloads for data: <code>sensor/temp</code> with payload <code>22.5</code></p>
<p>❌ <strong>No authentication</strong>: Open broker accessible to anyone ✅ Use TLS + username/password or client certificates</p>
<p>❌ <strong>Ignoring connection failures</strong>: No reconnection logic ✅ Implement exponential backoff reconnection</p>
<p>❌ <strong>Not using retained messages for status</strong>: Subscribers miss status ✅ Use retained messages for device status, config</p>
<hr>
<h2>Level 3: Resources</h2>
<h3>Overview</h3>
<p>This skill includes comprehensive Level 3 resources for deep MQTT implementation knowledge and practical tools.</p>
<p><strong>Resources include</strong>:</p>
<ul><li><strong>REFERENCE.md</strong> (3,200+ lines): Complete technical reference covering MQTT protocol, brokers, patterns</li><li><strong>3 executable scripts</strong>: Config validation, QoS testing, broker benchmarking</li><li><strong>7 production examples</strong>: Complete implementations across brokers, platforms, languages</li></ul>
<h3>REFERENCE.md</h3>
<p><strong>Location</strong>: <code>skills/protocols/mqtt-messaging/resources/REFERENCE.md</code></p>
<p><strong>Comprehensive technical reference</strong> (3,200+ lines) covering:</p>
<p><strong>Core Topics</strong>:</p>
<ul><li>MQTT protocol fundamentals (v3.1.1, v5.0)</li><li>Pub-sub architecture and message flow</li><li>QoS levels (0, 1, 2) and delivery guarantees</li><li>Topic design and wildcard patterns</li><li>Connection management and keep-alive</li><li>Retained messages and last will</li><li>Clean vs persistent sessions</li><li>Security (TLS, authentication, authorization)</li><li>MQTT brokers (Mosquitto, EMQX, HiveMQ)</li><li>MQTT over WebSocket</li><li>AWS IoT Core integration</li><li>Azure IoT Hub integration</li><li>MQTT v5.0 features</li><li>Performance optimization</li><li>Testing strategies</li><li>Anti-patterns</li></ul>
<p><strong>Key Sections</strong>:</p>
<ol><li><strong>Protocol Fundamentals</strong>: MQTT v3.1.1/v5.0, packet types, control packets</li><li><strong>QoS Levels</strong>: Detailed flow diagrams for QoS 0/1/2</li><li><strong>Topic Design</strong>: Hierarchies, wildcards, best practices</li><li><strong>Broker Setup</strong>: Mosquitto, EMQX, HiveMQ configuration</li><li><strong>Security</strong>: TLS/mTLS, authentication methods, authorization</li><li><strong>Client Implementation</strong>: Python, Node.js, Go examples</li><li><strong>Cloud Integration</strong>: AWS IoT Core, Azure IoT Hub</li><li><strong>MQTT v5.0</strong>: New features (user properties, reason codes, shared subscriptions)</li><li><strong>Performance</strong>: Connection pooling, batching, compression</li><li><strong>Anti-Patterns</strong>: Common mistakes and solutions</li></ol>
<p><strong>Format</strong>: Markdown with extensive code examples in Python, Node.js, and shell scripts</p>
<h3>Scripts</h3>
<p>Three production-ready executable scripts in <code>resources/scripts/</code>:</p>
<h4>1. validate_mqtt_config.py (550 lines)</h4>
<p><strong>Purpose</strong>: Validate MQTT broker and topic configurations</p>
<p><strong>Features</strong>:</p>
<ul><li>Parse Mosquitto and EMQX config files</li><li>Validate topic naming conventions</li><li>Check security settings (TLS, auth)</li><li>Detect misconfigurations</li><li>Validate ACL rules</li><li>Output as JSON or human-readable text</li></ul>
<p><strong>Usage</strong>:</p>
<pre><code class="lang-bash"># Validate Mosquitto config
./validate_mqtt_config.py --config /etc/mosquitto/mosquitto.conf
# JSON output
./validate_mqtt_config.py --config /etc/mosquitto/mosquitto.conf --json
# Check topics
./validate_mqtt_config.py --check-topics --topics-file topics.txt
# Validate ACL
./validate_mqtt_config.py --config mosquitto.conf --check-acl</code></pre>
<p><strong>Checks</strong>:</p>
<ul><li><strong>Config</strong>: Listener ports, TLS settings, auth configuration</li><li><strong>Topics</strong>: Naming conventions, hierarchy depth, wildcard usage</li><li><strong>Security</strong>: TLS version, certificate paths, password files</li><li><strong>ACL</strong>: Permission rules, topic patterns, user access</li></ul>
<h4>2. test_mqtt_qos.py (600 lines)</h4>
<p><strong>Purpose</strong>: Test MQTT QoS levels and message delivery</p>
<p><strong>Features</strong>:</p>
<ul><li>Test QoS 0, 1, 2 delivery</li><li>Measure message loss and duplicates</li><li>Test retained messages</li><li>Test last will and testament</li><li>Connection reliability testing</li><li>Latency measurements</li><li>JSON output for CI/CD</li></ul>
<p><strong>Usage</strong>:</p>
<pre><code class="lang-bash"># Test all QoS levels
./test_mqtt_qos.py --broker mqtt.example.com --test-all
# Test QoS 1
./test_mqtt_qos.py --broker mqtt.example.com --qos 1 --count 100
# Test retained messages
./test_mqtt_qos.py --broker mqtt.example.com --test-retained
# Test LWT
./test_mqtt_qos.py --broker mqtt.example.com --test-lwt
# JSON output
./test_mqtt_qos.py --broker mqtt.example.com --test-all --json</code></pre>
<p><strong>Metrics</strong>: Delivery rate, message loss, duplicates, latency (min, avg, p95, max)</p>
<h4>3. benchmark_mqtt_broker.py (650 lines)</h4>
<p><strong>Purpose</strong>: Benchmark MQTT broker performance and scalability</p>
<p><strong>Features</strong>:</p>
<ul><li>Test concurrent connections (100s to 1000s)</li><li>Measure throughput (messages/sec)</li><li>Pub-sub latency testing</li><li>Connection establishment time</li><li>Memory and CPU monitoring</li><li>Ramp-up testing</li><li>JSON output for reporting</li></ul>
<p><strong>Usage</strong>:</p>
<pre><code class="lang-bash"># Benchmark with 1000 connections
./benchmark_mqtt_broker.py --broker mqtt.example.com --connections 1000 --duration 60
# Test throughput
./benchmark_mqtt_broker.py --broker mqtt.example.com --test throughput --messages 10000
# Test latency
./benchmark_mqtt_broker.py --broker mqtt.example.com --test latency --count 100
# Ramp-up test
./benchmark_mqtt_broker.py --broker mqtt.example.com --connections 5000 --ramp-up 120 --duration 300
# JSON output
./benchmark_mqtt_broker.py --broker mqtt.example.com --connections 1000 --json</code></pre>
<p><strong>Metrics</strong>: Connections/sec, messages/sec, latency (p50, p95, p99), memory usage</p>
<h3>Examples</h3>
<p>Seven production-ready examples in <code>resources/examples/</code>:</p>
<h4>1. python/publisher.py</h4>
<p>Complete Python publisher implementation:</p>
<ul><li>Connection management with reconnection</li><li>QoS 0/1/2 support</li><li>Retained messages</li><li>JSON payload serialization</li><li>Error handling and logging</li><li>CLI interface</li></ul>
<h4>2. python/subscriber.py</h4>
<p>Complete Python subscriber implementation:</p>
<ul><li>Topic subscription with wildcards</li><li>Message handlers</li><li>Persistent sessions</li><li>Automatic reconnection</li><li>Message queueing</li><li>CLI interface</li></ul>
<h4>3. mosquitto/mosquitto.conf</h4>
<p>Production Mosquitto configuration:</p>
<ul><li>Multiple listeners (1883, 8883, 9001 WebSocket)</li><li>TLS/SSL configuration</li><li>Password authentication</li><li>ACL file for authorization</li><li>Logging and persistence</li><li>Connection limits</li></ul>
<h4>4. emqx/docker-compose.yml</h4>
<p>EMQX deployment with Docker:</p>
<ul><li>EMQX broker with clustering support</li><li>Prometheus metrics</li><li>Grafana dashboards</li><li>MQTT over WebSocket</li><li>Health checks</li><li>Volume mounts for persistence</li></ul>
<h4>5. aws_iot/iot_device.py</h4>
<p>AWS IoT Core integration:</p>
<ul><li>Certificate-based authentication (mutual TLS)</li><li>Device shadows</li><li>Thing registry</li><li>Job execution</li><li>Fleet provisioning</li><li>Telemetry publishing</li></ul>
<h4>6. node/mqtt_client.js</h4>
<p>Node.js client implementation:</p>
<ul><li>MQTT.js library</li><li>Async/await patterns</li><li>Reconnection logic</li><li>Event handlers</li><li>TypeScript types</li></ul>
<h4>7. tls/generate_certs.sh</h4>
<p>TLS certificate generation script:</p>
<ul><li>CA certificate creation</li><li>Server certificate</li><li>Client certificates</li><li>Mosquitto configuration for TLS</li><li>Testing with mosquitto_pub/sub</li></ul>
<h3>Quick Start</h3>
<p><strong>1. Validate broker config</strong>:</p>
<pre><code class="lang-bash">cd skills/protocols/mqtt-messaging/resources/scripts
./validate_mqtt_config.py --config ../examples/mosquitto/mosquitto.conf --json</code></pre>
<p><strong>2. Test QoS levels</strong>:</p>
<pre><code class="lang-bash">./test_mqtt_qos.py --broker localhost --test-all</code></pre>
<p><strong>3. Run examples</strong>:</p>
<pre><code class="lang-bash">cd ../examples
# Start Mosquitto
mosquitto -c mosquitto/mosquitto.conf
# Run publisher (in another terminal)
python python/publisher.py --broker localhost --topic test/topic --message &quot;Hello MQTT&quot;
# Run subscriber (in another terminal)
python python/subscriber.py --broker localhost --topic test/#</code></pre>
<p><strong>4. Deploy with Docker</strong>:</p>
<pre><code class="lang-bash">cd emqx
docker-compose up -d
# Dashboard: http://localhost:18083 (admin/public)</code></pre>
<p><strong>5. Benchmark broker</strong>:</p>
<pre><code class="lang-bash">cd ../scripts
./benchmark_mqtt_broker.py --broker localhost --connections 100 --duration 30</code></pre>
<h3>File Structure</h3>
<pre><code>skills/protocols/mqtt-messaging/
├── mqtt-messaging.md (this file)
└── resources/
├── REFERENCE.md (3,200+ lines)
├── scripts/
│ ├── validate_mqtt_config.py (550 lines) - Config validation
│ ├── test_mqtt_qos.py (600 lines) - QoS testing
│ └── benchmark_mqtt_broker.py (650 lines) - Broker benchmarking
└── examples/
├── python/
│ ├── publisher.py - Python publisher
│ └── subscriber.py - Python subscriber
├── mosquitto/
│ ├── mosquitto.conf - Mosquitto config
│ └── acl.conf - ACL rules
├── emqx/
│ └── docker-compose.yml - EMQX deployment
├── aws_iot/
│ └── iot_device.py - AWS IoT Core client
├── node/
│ └── mqtt_client.js - Node.js client
└── tls/
└── generate_certs.sh - TLS certificate generation</code></pre>
<h3>Resources Summary</h3>
<p>| Category | Item | Lines | Description | |----------|------|-------|-------------| | <strong>Reference</strong> | REFERENCE.md | 3,200+ | Complete technical reference | | <strong>Scripts</strong> | validate_mqtt_config.py | 550 | Config validation tool | | | test_mqtt_qos.py | 600 | QoS testing tool | | | benchmark_mqtt_broker.py | 650 | Broker benchmarking tool | | <strong>Examples</strong> | python/publisher.py | 180 | Python publisher | | | python/subscriber.py | 200 | Python subscriber | | | mosquitto.conf | 120 | Mosquitto configuration | | | docker-compose.yml | 100 | EMQX deployment | | | iot_device.py | 250 | AWS IoT Core client | | | mqtt_client.js | 150 | Node.js client | | | generate_certs.sh | 100 | TLS cert generation |</p>
<p><strong>Total</strong>: 6,100+ lines of production-ready resources</p>
<hr>
<h2>Related Skills</h2>
<ul><li><code>protocols-grpc-implementation.md</code> - gRPC for microservice communication</li><li><code>realtime-websocket-implementation.md</code> - WebSocket for bidirectional messaging</li><li><code>pubsub-patterns.md</code> - Pub-sub architecture patterns</li><li><code>iot-device-management.md</code> - IoT device lifecycle management</li><li><code>message-queue-patterns.md</code> - Message queuing architectures</li></ul>
<hr>
<p><strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic)</p>
<footer>
<div class="fmap">
<div><b>Build</b>
<a href="https://hanzo.app">hanzo.app</a> app builder
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
<div><b>Run</b>
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
<div><b>Account</b>
<a href="https://hanzo.id">hanzo.id</a> sign in
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
<div><b>Company</b>
<a href="https://hanzo.ai">hanzo.ai</a> canonical
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
</div>
<div class="fend"><a href="/protocols-mqtt-messaging.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>