简体   繁体   中英

strange while loop behavior with time.sleep above 90 s

I'm struggling understanding a "weird" behavior of my simple script. Basically, it works as expected if time.sleep() is set as 60s but as soon as I put a value above 90 (90 is the limit apparently in my case), the loop doesn't work properly. I discovered this when I was trying to pause the script for 3 mins.

Here's my script

from gpiozero import CPUTemperature
import time
import paho.mqtt.client as mqtt #import the client1
import psutil

broker_address="192.168.1.17"
client = mqtt.Client("P1") #create new instance
client.connect(broker_address) #connect to broker

#time.sleep(60)


while True:
    cpu = CPUTemperature()
    print(cpu.temperature)
    #a=cpu.temperature
    #print(psutil.cpu_percent())
    #print(psutil.virtual_memory()[2])
    #print(a)
    client.publish("test/message",cpu.temperature)
    #client.publish("test/ram", psutil.virtual_memory()[2])
    #client.publish("test/cpu", psutil.cpu_percent())
    time.sleep(91)

In this case, with 91s it just prints the value of cpu.temperature every 91s, whereas with a value like 60s, besides printing, it also publishes the value via mqtt every cycle.

Am I doing something wrong here? Or for a longer sleep I need to change my code? I'm running this on a RaspberryPi.

Thanks in advance

EDIT:

I solved modifying the script, in particular how mqtt was handling the timing

here's the new script

mqttc=mqtt.Client("P1")
#mqttc.on_connect = onConnect
#mqttc.on_disconnect = onDisconnect
mqttc.connect("192.168.1.17", port=1883, keepalive=60)
mqttc.loop_start()
while True:
    cpu = CPUTemperature()
    print(cpu.temperature)
    mqttc.publish("test/message",cpu.temperature)
    time.sleep(300)

The MQTT client uses a network thread to handle a number of different aspects of the connection to the broker.

Firstly, it handles sending ping request to the broker in order to keep the connection alive. The default period for the keepalive period is 60 seconds. The connection will be dropped by the broker if it does not receive any messages in 1.5 times this value, which just happens to be 90 seconds.

Secondly, the thread handles any incoming messages that the client may have subscribed to.

Thirdly, if you try to publish a message that is bigger than the MTU of the network link, calling mqttc.publish() will only send the first packet and the loop is needed to send the rest of the payload.

There are 2 ways to run the network tasks.

  1. As you have found, you can start a separate thread with the mqttc.loop_start()
  2. The other option is to call mqttc.loop() within your own while loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM