eclipse / paho.mqtt.python

paho.mqtt.python
Other
2.17k stars 723 forks source link

Publish global helper function: 'Single' and 'Multiple' #689

Open kami0601 opened 1 year ago

kami0601 commented 1 year ago

In the 'single' or 'multiple' global helper functions for Publish, is there concern if it gets called every second? My system is having trouble with 'loop_start' or 'loop_forever' so I just opted to use the 'single' or 'multiple' helper functions instead. The only functionality needed for my system is for the topic and payload to be published every second. Given that the 'single' and 'multiple' helper functions connect and disconnect on each call, would calling it every second be ok?

ralight commented 1 year ago

I would definitely recommend against a regular reconnect like this, especially if you are using SSL - the SSL handshake is very CPU intensive. Something like this should work using the general functions:

import paho.mqtt.client as mqtt

mqttc = mqtt.Client()
mqttc.connect("localhost", 1883, 60)
mqttc.loop_start()

topic = "my/topic"

while True:
    payload = get_data()
    mqttc.publish(topic, payload)
    time.sleep(1)