Issue
I am running a systemd unit python script at my RaspberryPi to send temperature data automatically when the Pi has power. When time.sleep is at 60 seconds everything works fine. But when time.sleep is longer (120 seconds or more), it only sends one value when the script starts and afterwards I do not get any more values. Can someone help?
import paho.mqtt.client as mqtt
import Adafruit_DHT
import time
import ssl
# Set up DHT22 sensor
dht_sensor = Adafruit_DHT.DHT22
dht_pin = 4 # GPIO pin number the sensor is connected to
username = 'master:mqttuser'
secret = 'ifYrtDSc'
host = '192.168.0.65'
port = 8883
clientID = 'raspi_ka'
assetID = '3nRdfjgE0Ga'
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
mqtt_client.subscribe("$SYS/#")
def on_publish(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
mqtt_client = mqtt.Client(clientID)
mqtt_client.username_pw_set(username, password=secret)
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
mqtt_client.tls_set_context(context)
mqtt_client.on_connect = on_connect
mqtt_client.on_publish = on_publish
mqtt_client.connect(host, port=port)
# Continuously read and send temperature values
while True:
humidity, temperature = Adafruit_DHT.read_retry(dht_sensor, dht_pin)
if humidity is not None and temperature is not None:
mqtt_client.publish(f"master/{clientID}/writeattributevalue/temperature/{assetID}", temperature)
mqtt_client.publish(f"master/{clientID}/writeattributevalue/humidity/{assetID}", humidity)
else:
print("Failed to read temperature sensor data")
time.sleep(120)
# Disconnect MQTT client
mqtt_client.disconnect()
Solution
You are disconnected due to a timeout. You have to set the keepalive
argument to connect.
mqtt_client.connect(host, port=port, keepalive=120)
Note that time.sleep()
is not accurate. It might be prolonged by an arbitrary amount. You probably want to use the loop
function of the MQTT client instead.
while True:
...
mqtt_client.loop(timeout=120)
Answered By - Emanuel P Answer Checked By - Katrina (WPSolving Volunteer)