我在我的 RaspberryPi 上运行一个 systemd unit python 脚本,以便在 Pi 通电时自动发送温度数据。当 time.sleep 为 60 秒时,一切正常。但是当 time.sleep 更长(120 秒或更多)时,它只会在脚本启动时发送一个值,之后我不会再获得任何值。有人可以帮忙吗?
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 = 'ifYmQ8HeUhperGnqXTLEtDSc'
host = '192.168.0.65'
port = 8883
clientID = 'raspi_ka'
assetID = '3nRdM1k6UfjggE0Ga'
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()
您因超时而断开连接。您必须设置
keepalive
参数才能连接。
mqtt_client.connect(host, port=port, keepalive=120)
请注意,
time.sleep()
不准确。它可能会延长任意数量。您可能想改用 MQTT 客户端的 loop
功能。
while True:
...
mqtt_client.loop(timeout=120)