<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kethan on Medium]]></title>
        <description><![CDATA[Stories by Kethan on Medium]]></description>
        <link>https://medium.com/@varmag93?source=rss-fa2b5e7ae099------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ocJr0kTlXjNib1IN.jpg</url>
            <title>Stories by Kethan on Medium</title>
            <link>https://medium.com/@varmag93?source=rss-fa2b5e7ae099------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:03:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varmag93/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Seamlessly Connect to an MQTT Broker]]></title>
            <link>https://medium.com/@varmag93/how-to-connect-to-an-mqtt-broker-seamlessly-1088d56b4c1e?source=rss-fa2b5e7ae099------2</link>
            <guid isPermaLink="false">https://medium.com/p/1088d56b4c1e</guid>
            <category><![CDATA[paho-mqtt]]></category>
            <category><![CDATA[mqtt-client]]></category>
            <category><![CDATA[mqtt-broker]]></category>
            <dc:creator><![CDATA[Kethan]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 16:05:21 GMT</pubDate>
            <atom:updated>2026-07-04T17:02:11.886Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Why this matters</em></strong></blockquote><p>MQTT is great for sending small messages between devices and systems. But in real life, connections can still break due to internet issues, an incorrect security setup, or weak retry handling. This guide explains, in simple terms, how to keep your MQTT connection stable using Python.</p><h4><strong>Version notes (important)</strong></h4><ul><li>MQTT has two common versions: 3.1.1 and 5.0.</li><li>This article uses 3.1.1 because it works with many existing brokers.</li><li>The Python library used is `paho-mqtt`.</li><li>The same stability ideas in this blog also apply to MQTT 5.0.</li></ul><h4><strong>What “seamless” means</strong></h4><p>A seamless MQTT connection should:</p><ul><li>Connect safely.</li><li>Reconnect by itself if the network drops.</li><li>Continue receiving messages after reconnect.</li><li>Keep running without manual restarts.</li><li>Reduce message loss as much as possible.</li></ul><p><strong>Prerequisites</strong></p><ul><li>An MQTT broker endpoint (host + port).</li><li>Credentials (username/password) or client certificate files</li><li>Python package:</li></ul><pre>pip install paho-mqtt</pre><h4><strong>Step 1: Choose the right connection settings</strong></h4><p>Use these beginner-friendly configurations:</p><ul><li><em>keepalive=60</em>: checks every minute that the connection is still alive.</li><li><em>clean_session=False</em>: helps the client continue where it left off.</li><li><em>QoS 1</em> for important data: the message is delivered at least once.</li><li>Use TLS on port <em>8883(</em><strong><em>default</em></strong><em>)</em>: this encrypts traffic.</li></ul><h4><strong>Step 2: Implement a resilient MQTT client (Python)</strong></h4><p>The code below is designed to be practical and easy to follow.</p><pre>import ssl<br>import time<br>import random<br>from paho.mqtt import client as mqtt_client<br><br>BROKER = &quot;mqtt.example.com&quot;<br>PORT = 8883<br>CLIENT_ID = &quot;plant-gateway-001&quot;<br>USERNAME = &quot;your-username&quot;<br>PASSWORD = &quot;your-password&quot;<br>TOPICS = [(&quot;factory/line1/alerts&quot;, 1), (&quot;factory/line1/status&quot;, 1)]<br><br><br>def build_client() -&gt; mqtt_client.Client:<br>    client = mqtt_client.Client(<br>        client_id=CLIENT_ID,<br>        clean_session=False,  # persistent session for MQTT 3.1.1<br>        protocol=mqtt_client.MQTTv311,<br>    )<br><br>    # Authentication<br>    client.username_pw_set(USERNAME, PASSWORD)<br><br>    # TLS (recommended for production)<br>    client.tls_set(<br>        cert_reqs=ssl.CERT_REQUIRED,<br>        tls_version=ssl.PROTOCOL_TLS_CLIENT,<br>    )<br>    client.tls_insecure_set(False)<br><br>    # Automatic reconnect with controlled backoff<br>    client.reconnect_delay_set(min_delay=1, max_delay=30)<br><br>    def on_connect(client, userdata, flags, rc):<br>        if rc == 0:<br>            print(&quot;Connected to broker&quot;)<br>            # Subscribe again after connect to make sure topics are active.<br>            client.subscribe(TOPICS)<br>        else:<br>            print(f&quot;Connect failed with code: {rc}&quot;)<br><br>    def on_disconnect(client, userdata, rc):<br>        print(f&quot;Disconnected (rc={rc})&quot;)<br><br>    def on_log(client, userdata, level, buf):<br>        # Useful debug logs when something goes wrong.<br>        print(f&quot;LOG[{level}] {buf}&quot;)<br><br>    def on_message(client, userdata, msg):<br>        print(f&quot;{msg.topic}: {msg.payload.decode(errors=&#39;replace&#39;)}&quot;)<br><br>    client.on_connect = on_connect<br>    client.on_disconnect = on_disconnect<br>    client.on_log = on_log<br>    client.on_message = on_message<br><br>    return client<br><br><br>def run_forever() -&gt; None:<br>    client = build_client()<br><br>    while True:<br>        try:<br>            client.connect(BROKER, PORT, keepalive=60)<br>            client.loop_forever(retry_first_connection=True)<br>        except Exception as exc:<br>            # Safety retry if the loop exits unexpectedly.<br>            wait_seconds = min(30, 2 + random.randint(0, 4))<br>            print(f&quot;Connection error: {exc}. Retrying in {wait_seconds}s&quot;)<br>            time.sleep(wait_seconds)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    run_forever()</pre><h4><strong>Why `on_log` adds real value</strong></h4><p>`on_log` is not mandatory, but it is extremely useful for real deployments.</p><ol><li>Speeds up root-cause analysis when connections flap.</li></ol><p>2. Shows protocol-level hints (connect/disconnect attempts, retries, handshake details).</p><p>3. Helps correlate app-side behaviour with broker-side logs.</p><p>4. Reduces mean time to recovery during outages because you can see exactly where the flow fails.</p><h4>Recommended practice:</h4><p>- Keep detailed `on_log` enabled in dev/stage.</p><p>- In production, route logs to your logging system and throttle/filter verbosity to avoid noise.</p><h4><strong>Step 3: Publish safely</strong></h4><p>For critical messages:</p><ul><li>Send with `<em>qos=1</em>`.</li><li>Wait for the publish confirmation.</li><li>If data is very important, keep a local backup queue during outages.</li></ul><p>Example:</p><pre>result = client.publish(&quot;factory/line1/heartbeat&quot;, payload=&quot;alive&quot;, qos=1, retain=False)<br>result.wait_for_publish()</pre><h4><strong>Step 4: Design topics for scalability</strong></h4><p>Use a consistent hierarchy:</p><pre>factory/{site}/{line}/{device}/telemetry<br>factory/{site}/{line}/{device}/alerts<br>factory/{site}/{line}/{device}/command</pre><p>Tips:</p><ul><li>Use one naming style everywhere.</li><li>Keep payload format versioned (example: ” schema”: “1.0”`).</li><li>Keep device data topics separate from command topics.</li></ul><h4><strong>Step 5: Add operational guardrails</strong></h4><p>To keep connectivity truly seamless in production:</p><ul><li>Set <em>Last Will and Testament</em> (LWT) so others know when a client goes offline.</li><li>Track simple health numbers: reconnect count and last message time.</li><li>Rotate passwords/certificates safely.</li><li>Alert when reconnect happens too often.</li></ul><h4><strong>Common pitfalls to avoid</strong></h4><ul><li>Using MQTT without TLS in production.</li><li>Trusting default reconnect settings only.</li><li>Not subscribing again after reconnect.</li><li>Using QoS 0 for important data.</li><li>Not handling duplicate messages on the receiving side.</li></ul><h4><strong>MQTT error codes and references</strong></h4><p>If `on_connect` returns a non-zero `rc`, it means the broker rejected the connection.</p><p>Use these references to understand the exact reason code.</p><ul><li>Paho MQTT Python client docs: <a href="https://eclipse.dev/paho/index.php?page=clients/python/docs/index.php">https://eclipse.dev/paho/index.php?page=clients/python/docs/index.php</a></li><li>MQTT 3.1.1 CONNACK return codes (OASIS spec): <a href="https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html">https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html</a></li><li>MQTT 5.0 reason codes (OASIS spec): <a href="https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html">https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html</a></li></ul><p>Tip: always log the code number and a short human-friendly message.</p><h4><strong>Final takeaways</strong></h4><p>A stable MQTT setup is not just one `connect()` call.</p><p>It is about handling disconnects and retries the right way.</p><p>If you use TLS, good reconnect logic, correct QoS, and clear topic naming, your client will stay reliable even when the network is unstable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1088d56b4c1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>