編輯:為了清楚起見:問題不在于MQTT,而在于Pi Zero上的python腳本剛剛死亡。經(jīng)過一段時(shí)間后,腳本將停止存在,并且sudo ps -ax | grep python 不再列出運(yùn)行腳本的進(jìn)程。原始問題:我寫了一個(gè)簡單的腳本,從pi zero讀取DHT22傳感器,并每分鐘將溫度和濕度發(fā)布到單獨(dú)的MQTT主題上。在某些時(shí)候,腳本只是停止,因?yàn)樗粫?huì)讀取或發(fā)布更多的讀數(shù),即使它在一段時(shí)間內(nèi)運(yùn)行 True 循環(huán)。在我的經(jīng)紀(jì)人中,pi然后顯示為“離線”,因?yàn)檫@是最后一個(gè) will 消息。日志文件不包含任何有用的信息,從某種意義上說,只要寫入日志文件,腳本就會(huì)按預(yù)期工作,然后突然出現(xiàn)空白。def on_connect(client, userdata, flags, rc): message = "connected with rc: " + str(rc) print(message) log(message, mqtt_log_file) mqttPub.publish(topicStatusBedroom, "Online", 1, True)def on_publish(client, obj, mid): message = "published with mid: " + str(mid) print(message) log(message, mqtt_log_file)def on_disconnect(client, userdata, rc): print("client disconnected ok") log("client disconnected\n", mqtt_log_file) while True: try: mqttPub.connect(url_str, url_port) break # break the while loop, if reconnect works except: time.sleep(2) # otherwise sleep and retrydef log(message, file): file = open(file, "a") file.write(message) file.close() mqttPub = mqtt.Client()mqttPub.on_connect = on_connectmqttPub.on_publish = on_publishmqttPub.on_disconnect = on_disconnectmqttPub.username_pw_set(username, givenPassword)mqttPub.will_set(topicStatusBedroom, 'Offline', 1, True)mqttPub.connect(url_str, url_port)mqttPub.loop_start() # loop_start handles reconnects automaticallyif __name__ == "__main__": pin = 22 sensor = Adafruit_DHT.DHT22 log_file = 'dht_22_logging.txt'
1 回答

茅侃侃
TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超22個(gè)贊
答:腳本因 SSH 連接而死機(jī)。有效的方法是創(chuàng)建腳本的服務(wù)并使用systemd啟動(dòng)它。我確實(shí)按照本教程進(jìn)行了操作:https://learn.sparkfun.com/tutorials/how-to-run-a-raspberry-pi-program-on-startup/all
該腳本已經(jīng)運(yùn)行了一周,沒有任何問題。
添加回答
舉報(bào)
0/150
提交
取消