编辑:为了清楚起见:问题不在于MQTT,而在于Pi Zero上的python脚本刚刚死亡。经过一段时间后,脚本将停止存在,并且sudo ps -ax | grep python 不再列出运行脚本的进程。原始问题:我写了一个简单的脚本,从pi zero读取DHT22传感器,并每分钟将温度和湿度发布到单独的MQTT主题上。在某些时候,脚本只是停止,因为它不会读取或发布更多的读数,即使它在一段时间内运行 True 循环。在我的经纪人中,pi然后显示为“离线”,因为这是最后一个 will 消息。日志文件不包含任何有用的信息,从某种意义上说,只要写入日志文件,脚本就会按预期工作,然后突然出现空白。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贡献1842条经验 获得超21个赞
答:脚本因 SSH 连接而死机。有效的方法是创建脚本的服务并使用systemd启动它。我确实按照本教程进行了操作:https://learn.sparkfun.com/tutorials/how-to-run-a-raspberry-pi-program-on-startup/all
该脚本已经运行了一周,没有任何问题。
添加回答
举报
0/150
提交
取消