← Back to team overview

mosquitto-users team mailing list archive

Re: Connection resilient client

 

Hi Jon,

I presume by "crash" you mean it complains about a broken pipe or
similar socket error rather than something more dramatic :)

There are a couple of things I can suggest, the first is that you need
to use one of the loop*() functions. You need to use these to ensure
that the background network traffic is processed. You have a couple of
options - you can use loop() which you would call yourself in your
loop. You can also use loop_start() once after calling connect().
loop_start() creates a thread that calls loop() for you. The final
choice which isn't appropriate in your case is to use loop_forever(),
which is a blocking call and means your loop couldn't work.

The Python client queues up messages that you send with publish() even
if the client isn't connected.

If you use loop() yourself, you need to check the return value to see
whether you need to reconnect. If you do, call reconnect().

Using loop_start() takes this out of your hands because it will do the
reconnection for you, no problem. Likewise loop_forever().

For ease, I'd do:

mqttclient.connect(HOST, PORT, 60)
mqttclient.loop_start()
while True:
    payload = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print('About to publish: {P}'.format(P=payload))
    mqttclient.publish("Jon", payload, 1, retain=False)
    # wait for 10 seconds
    time.sleep(10)

Cheers,

Roger

On Tue, Feb 4, 2014 at 7:34 PM, Jon McDermott <jonmc56@xxxxxxxxx> wrote:
> Hello,
>
> I am trying to understand how to create a Python client that is resilient to
> connection/connectivity problems.
>
> I'm using the latest Paho MQTT client on Win8 and Python 2.7.4.  This is
> just my development platform, my plan is to deploy the code on RaspberryPi
> with a WiFi adapter.
>
> When I try this simple publish code:
>
> mqttclient.connect(HOST, PORT, 60)
> while True:
> payload = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
> print('About to publish: {P}'.format(P=payload))
> mqttclient.publish("Jon", payload, 1, retain=False)
> # wait for 10 seconds
> time.sleep(10)
>
>
> it publishes to my Mosquitto broker every 10 seconds, and I'm able to
> subscribe to these messages by topic.
>
> If I break the connection, however, or stop the broker service - it crashes
> the client on the next attempt to publish.  (this happens using all 3 QOS
> options)
>
> Is there anything in the Paho MQTT client that can help me queue these
> published messages until the broker becomes available again?  Any example
> code available that would show me how to gracefully handle these connection
> errors?
>
> Thanks in advance.
> Jon
>
> --
> Mailing list: https://launchpad.net/~mosquitto-users
> Post to     : mosquitto-users@xxxxxxxxxxxxxxxxxxx
> Unsubscribe : https://launchpad.net/~mosquitto-users
> More help   : https://help.launchpad.net/ListHelp
>


Follow ups

References