Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

publish a message every 10 seconds mqtt

Tags:

python

mqtt

I am new to mqtt and still discovering this interesting protocol. I want to create a client in python that publishes every 10 seconds a message. Until now I succeed to publish only one message and keep the client connected to the broker.

How can I make the publishing part a loop ?

Below is my client:

import mosquitto
mqttc=mosquitto.Mosquitto("ioana")
mqttc.connect("127.0.0.1",1884,60,True)
mqttc.publish("test","Hello")
mqttc.subscribe("test/", 2)

while mqttc.loop() == 0:
pass

Thanks.

like image 356
ioana Avatar asked Sep 08 '25 17:09

ioana


1 Answers

I would suggest:

import paho.mqtt.client as mqtt # mosquitto.py is deprecated
import time

mqttc = mqtt.Client("ioana")
mqttc.connect("127.0.0.1", 1883, 60)
#mqttc.subscribe("test/", 2) # <- pointless unless you include a subscribe callback
mqttc.loop_start()
while True:
    mqttc.publish("test","Hello")
    time.sleep(10)# sleep for 10 seconds before next call
like image 157
ralight Avatar answered Sep 10 '25 08:09

ralight