我正在使用以下脚本作为家用能源监控系统的基础。该脚本充当连接到串行端口的基于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)
谢谢!
猴面包树
答案 0 :(得分:2)
您的第二条try
语句捕获以下异常:
except serial.serialutil.SerialException:
但是,如果代码块生成另一个异常怎么办?脚本将退出。与第一个except
循环中一样,添加第二个try
来捕获其他任何异常,并将它们打印到日志中。