0

I'm currently trying to make sure my Python script stays alive, regardless what situation it lands in to, and as such I'm attempting to catch all exceptions and finding out an apropiate script response.

At this point in my script, I'm attempting to catch errors that might occure when connecting to my MQTT broker, namely an internet connection isn't available (1) either through eth0 not being plugged in, or (2) the router doesn't have internet access.

The error message for 1 is:

socket.gaierror: [Errno -5] No address associated with hostname

And the error message for 2 is:

socket.gaierror: [Errno -2] Name or service not known

Sadly, I haven't been to capture these exceptions. These are the ones I've tried:

def mqtt_listen():
        mqttc = mqtt.Client(machine_id, clean_session=False)
        mqttc.username_pw_set(machine_id, mqtt_pwd)
        mqttc.connect(mqtt_host, mqtt_port)
        mqttc.subscribe(mqttc.topic, qos=1)
        def on_connect(client, userdata, rc):
                print " Attempting to connect to MQTT"
                if rc != 0:
                        print "Unable to connect to MQTT: Connection refused. Error code (" + rc + ")"
                elif rc == 0:
                         print "Connection to MQTT established."
                else:
                         print "Unable to connect to MQTT: Socket error"

It seems however, as the exception (socket.gaierror) is not part of the MQTT (paho) library, I can't seem to catch it. Any help would be really appriciated it!

1 Answer 1

2

The socket connection happens in mqttc.connect(), it's there you need to be trying to catch the exception you're interested in.

The on_connect callback rc parameter is the value provided by the MQTT broker in the CONNACK message, it has nothing to do with sockets.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! You're right. I can't believe I missed that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.