I’ve got a question. I’m currently developing a cold storage monitoring system using a PiFace which communicates over MQTT. I want to send a MQTT message on a input state change, and some time after the input state change send another message to the same topic as the first message.
Im trying to get this to work using time.sleep, however the first message isn’t being sent, and after the set time in time.sleep it sends the second message.
Could someone tell me why this is happening? I don’t have very much experience writing Python. This is my code:
if message.topic == MONITOR_REFRESH:
refresh()
elif message.topic == MQTT_TOPIC_DEFROST and message.payload == '1':
mqttc.publish(MQTT_TOPIC_DEFOUT, payload='Defrosting in progress', qos=MQTT_QOS, retain=MQTT_RETAIN)
elif message.topic == MQTT_TOPIC_DEFROST and message.payload == '0':
mqttc.publish(MQTT_TOPIC_DEFOUT, payload='Dripoff in progress', qos=MQTT_QOS, retain=MQTT_RETAIN)
#time.sleep set to 5 seconds for testing purpose
time.sleep(5)
mqttc.publish(MQTT_TOPIC_DEFOUT, payload='Defrost inactive', qos=MQTT_QOS, retain=MQTT_RETAIN)
#some elifs between here
return
What is mqttc? Probably an MQTT client but where does it come from? How is it initialized? Which MQTT library you are using for it? Also it might help to know the values of MQTT_QOS and MQTT_RETAIN, as they make a difference in how messages are delivered.
And how do you observe what’s been published?
Without more details, it is hard to pinpoint an issue with any specificity. The one thing that I see as problematic in your code is time.sleep. Chances are that time.sleep is in fact “working properly”, in the sense that it most likely is doing exactly what you asked it to do. However, the way time.sleep works is that it slams the brakes on the current thread for the amount of time you requested. If your MQTT client library is dependent on the current thread being able to continue running, then it may be that your first mqttc.publish call queues the message, but the code that actually sends it to the wire does not run for five seconds which may be more than an internal time out so that message gets tossed, undelivered. This, however, is speculation. Can’t tell for sure without knowing which MQTT library you are using.
Python sleep() will pause for an hour, day or whatever if given the proper value. It does not allow other processes take place (in same script) however. A better way is to use an event which will create an event on timeout.