Reliable MQTT connections

Posted

So try this, go and restart your local MQTT broker. I'll wait

So how did that go?

If you like me based your MQTT clients code on the example code then you probably have some hung clients than need resetting.

So the Arduino/C examples has this code..

void loop()
{
    client.loop();
}

And the python examples have this..

while 1:
    client.loop()

Both simple to understand for starting out but if anything happens to you broker or there is a network problem etc your client is borked.

It fairly easy to fix though, we just don't assume we have a connection when we call client.loop and if we don't have a connection then lets connect.

Arduino/C

  if (client.connected ()){
     client.loop();
  }
  else {
    Serial.println("MQTT Broker Connection Down");
    if (client.connect("Shed_Temp","shed/will",0,0,"Shed Temp Fail")) {
       client.publish("Status","ShedTemp ReStart");
       Serial.println("MQTT Broker Connection Restated");
    }
    else {
      // Don't flood the broker with connections and it's already down so we don't need to worry about a delay disconnecting the client
      delay(15*1000);
      Serial.println("MQTT Connection Delay");
    }
  }

Python

def connectToBroker():
    client.will_set('jarvis/will/local', payload="Jarvis Local Fail", qos=0)
    try:
        if not client.connect("127.0.0.1"):
            client.subscribe("temperature/#", 0)
    except socket.error, (value,message):
        print "Could not open socket: " + message
        time.sleep(5)

while 1:
    try:
        if client.loop():
            print("Broker Connection Error")
            connectToBroker()
    except socket.error, (value,message):
        print "Could not open socket: " + message

While updating my clients code I've also taken the opportunity to setup last will and testament so i get a MQTT message when the clients disconnect. I intend to hook this up to MQTT Warn so I get notifications when MQTT clients disconnect unexpectedly.

Author
Categories ,

Comments

comments powered by Disqus

← Older Newer →