【发布时间】:2019-05-27 14:24:09
【问题描述】:
我使用以下脚本作为自制能源监控系统的基础。该脚本充当连接到串行端口的基于 arduino 的接收器之间的网关,并通过 MQTT 和 http POST 将其传递。该脚本旨在无限期运行。但是,它会随机崩溃,从一小时到一周不等。我不知道为什么。任何有关如何确定为什么以及如何记录错误的指针都将不胜感激。这是脚本:
import time
import datetime
import requests
import paho.mqtt.publish as publish
#import csv
import logging
logging.basicConfig(level=logging.ERROR, filename='serial-read.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
device = '/dev/ttyUSB0' #this will have to be changed to the serial port you are using
data = ""
pieces = ""
while True:
while True:
try:
receiver = serial.Serial(device, 57600)
receiver.flushInput()
except serial.SerialException:
print "cannot connect. will try again..."
time.sleep(10)
else:
break
try:
data = receiver.readline()
#print (data)
#print repr(data)
#with open ("data_log.csv","a") as f:
#writer = csv.writer(f,delimiter=",")
#writer.writerow([time.time(),data])
pieces = data.split(" ")
try:
nodeid = int(pieces[0])
except ValueError:
pass
try:
data1 = int(pieces[1])
data2 = int(pieces[2])
data3 = int(pieces[3])
data4 = int(pieces[4])
except IndexError:
pass
#print nodeid
if nodeid == 6:
#print "Power:"
Irms = data3 + data4
print Irms
localtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
localtime = "'" + localtime + "'"
#print localtime
payload = {"timestamp" : localtime, "Irms" : Irms}
r = requests.post('http://www.********.ca/*****.php', params=payload)
#print(r.url)
publish.single("myHome/energy/power", Irms, hostname="192.168.1.120")
elif nodeid == 2:
temp = float(data1)/10
#print "temp:"
#print temp
hum = data3
publish.single("myHome/garage/temperature", temp, hostname="192.168.1.120")
publish.single("myHome/garage/humidity", hum, hostname="192.168.1.120")
temphum = str(temp) + " " + str(hum)
publish.single("myHome/garage/temphum", temphum, hostname="192.168.1.120")
#print temphum
except serial.serialutil.SerialException:
print "no device connected. Please reconnect device..."
receiver.close()
time.sleep(5)
谢谢!
猴面包树
【问题讨论】:
-
崩溃时出现什么错误?
-
我不知道 - 这就是问题所在。很可能是通过串行端口传入的数据存在问题,因此我尝试处理这些错误 - 但这只是一个猜测。不知道如何设置错误日志记录以将所有错误保存到日志文件中......
标签: python logging mqtt gateway