Reputation: 1620
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!
Upvotes: 0
Views: 3496
Reputation: 11618
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.
Upvotes: 2