0

I have seen a number of examples of paho clients reading sensor data then publishing, e.g., https://github.com/jamesmoulding/motion-sensor/blob/master/open.py. None that I have seen have started a network loop as suggested in https://eclipse.org/paho/clients/python/docs/#network-loop. I am wondering if the network loop is unnecessary for publishing? Perhaps only needed if I am subscribed to something?

fickas
  • 97
  • 4

2 Answers2

0

The network loop is needed for a number of things:

  1. To deal with incoming messages
  2. To send the ping packets needed to keep a connection alive
  3. To handle the extra packets needed for high QOS
  4. Send messages that take up more than one network packet (e.g. bigger than local MTU)

The ping messages are only needed if you have a low message rate (less than 1 msg per keep alive period).

Given you can start the network loop in the background on a separate thread these days, I would recommend starting it regardless

hardillb
  • 54,545
  • 11
  • 67
  • 105
0

To expand on what @hardillb has said a bit, his point 2 "To send the ping packets needed to keep a connection alive" is only strictly necessary if you aren't publishing at a rate sufficient to match the keepalive you set when connecting. In other words, it's entirely possible the client will never need to send a PINGREQ and hence never need to receive a PINGRESP.

However, the more important point is that it is impossible to guarantee that calling publish() will actually complete sending the message without using the network loop. It may work some of the time, but could fail to complete sending a message at any time.

The next version of the client will allow you to do this:

m = mqttc.publish("class", "bar", qos=2)
m.wait_for_publish()

But this will require that the network loop is being processed in a separate thread, as with loop_start().

ralight
  • 11,033
  • 3
  • 49
  • 59
  • I'll keep using the network loop as suggested. But also note that there are a lot of examples floating on the web (in tutorials and such) that do not use it. Perhaps has not bitten enough people yet. Wonder if default should be to start it and force people to turn it off manually. Reverse of what is now. – fickas Apr 22 '16 at 22:20
  • Yep, lots of people that don't read documentation :( I'm not going to break backwards compatibility by changing the behaviour, it'll just have to be an annoying occasional bug for people that don't process the loop. – ralight Apr 23 '16 at 22:27