5

My python script turns on the Raspberry Pi's WiFi and after a short delay tries to connect with Paho MQTT. If the delay isn't long enough, it fails ungracefully.

I'm using paho-mqtt version 1.4.1

EDIT: I've added the line that starts status_con = which should have been present already. I do indeed instantiate the client first, then use .connect() immediately afterward. It's the .connect() that produces the error.

try:

    mqtt_client = mqtt.Client(client_id="Luke, I am your client",
                              clean_session=True, userdata=None, 
                              transport="tcp") 

    status_con  = self.mqtt_client.connect(host=self.mqtt_host_url,
                                           keepalive=self.mqtt_keepalive,
                                           port=self.mqtt_port)  # 5 https://stackoverflow.com/a/35581280/3904031

except:  # never gets here!

    print "connect failed, sleeping for 20 seconds: "
    time.sleep(20)
    print "    now try again: "
    mqtt_client = mqtt.Client(client_id="Luke, I'm no longer your client",
                              clean_session=True, userdata=None, 
                              transport="tcp")

Instead of being caught by the try: it errors and gives the following messages

File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 768, in connect
  return self.reconnect()

File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 895, in reconnect
  sock = socket.create_connection((self._host, self._port), 
  source_address=(self._bind_address, 0))

File "/usr/lib/python2.7/socket.py", line 553, in create_connection
  for res in getaddrinfo(host, port, 0, SOCK_STREAM):gaierror: 
  [Errno -5] No address associated with hostname

If I increase the delay, then it always connects.

Right now my solution is to ping a random internet site every few seconds using socket until it's working, then trying to connect MQTT but I would still like something that doesn't have such catastrophic results.

So what I would like is for a way to catch the problem without Paho crashing, and only then try again in 10 seconds, and again...

Is there a way to have Paho do this for me, or at least to let me handle the exception with try/except?

uhoh
  • 225
  • 4
  • 12

0 Answers0