on_disconnect mqtt client side not ever being called

3.6k views Asked by At

I am trying to monitor an mqtt broker so I can fire a notification if there is a connection interruption.

My approach was to create a cloud client who does nothing besides monitor the broker. "on_disconnect" seems like the appropriate method however I cannot get it to trigger. (I have been loading and unloading the broker service in a different terminal).

The method is a skeleton:

import random
import time


def RepresentsInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False
def on_message(client, userdata, message):
        print message
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    mqttc.subscribe('control/iterate',qos=0)
def on_disconnect(client, userdata,  rc):
        print("Disconnected")
mqttc = mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect('10.147.17.234', port=1883, keepalive=1)



print("test")
mqttc.loop_forever()

Obviously there are easy ways to do this but I feel like there is an elegant solution to this problem that I am just missing.

1

There are 1 answers

0
hardillb On

You've not actually added the on_disconnect call back in your code:

import random
import time


def RepresentsInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False
def on_message(client, userdata, message):
        print message
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    mqttc.subscribe('control/iterate',qos=0)
def on_disconnect(client, userdata,  rc):
        print("Disconnected")
mqttc = mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
#added the following line
mqttc.on_disconnect = on_disconnect
mqttc.connect('10.147.17.234', port=1883, keepalive=1)



print("test")
mqttc.loop_forever()