【发布时间】:2020-11-04 21:13:11
【问题描述】:
因此,我目前正在我的 Raspberry Pi 4 上使用 ThingSpeak(IoT) 进行一个大学项目。我已经设置了我的 ThingSpeak 频道,并且有另一个程序可以正常工作,为它提供数据权限。现在我正在尝试编写另一个从中读取数据的程序,但我遇到了一个非常奇怪的问题。
这是代码:(我已经“审查”了它们的相关键,这样人们就不能滥用频道了)
import urllib.request
import requests
from time import sleep
import json
def read_from_thingspeak():
URL='https://api.thingspeak.com/channels/1152832/fields/1.json?api_key='
KEY='READ KEY'
HEADER='&results=2'
NEW_URL=URL+KEY+HEADER
get_data=requests.get(NEW_URL).json()
data = []
for x in get_data['feeds']:
print(x['field1'])
data.append(float(x['field1']))
#END FOR
return (data[0], data[1])
#END read_from_thingspeak
def check_if_crossed(data1, data2, threshold):
print ("checking if data crossed threshold")
if (data1 < threshold and data2 > threshold):
write_lightstatus(0)
write_blindsstatus(0)
elif (data1 > threshold and data2 < threshold):
write_lightstatus(1)
write_blindsstatus(1)
else:
print("data did not cross threshold")
#END IF
#END check_if_crossed
def write_lightstatus(on):
URl='https://api.thingspeak.com/update?api_key='
KEY='WRITE KEY'
HEADER='&field2={}'.format(on)
NEW_URL=URl+KEY+HEADER
urllib.request.urlopen(NEW_URL)
print("successfully written light status")
#END write_lightstatus
def write_blindsstatus(on):
URl='https://api.thingspeak.com/update?api_key='
KEY='WRITE KEY'
HEADER='&field3={}'.format(on)
NEW_URL=URl+KEY+HEADER
urllib.request.urlopen(NEW_URL)
print("successfully written blinds status")
#END write_blindsstatus
#MAIN
threshold = 100 #NOTE: this is a default value. This value can be changed by the user
while(1):
(data1, data2) = read_from_thingspeak()
check_if_crossed(data1, data2, threshold)
sleep(4)
#END WHILE
所以在程序结束时,我让它循环执行此操作。在程序第一次运行时,它会正常运行,输出如下:
67.54235
136.22669
checking if data crossed threshold
successfully written light status
successfully written blinds status
在循环的第二次迭代中,会发生这种情况:
136.22669
None
Traceback (most recent call last):
File "/home/pi/Documents/Projects/Project testing/RPI4_test.py", line 58, in <module>
(data1, data2) = read_from_thingspeak()
File "/home/pi/Documents/Projects/Project testing/RPI4_test.py", line 18, in read_from_thingspeak
data.append(float(x['field1']))
TypeError: float() argument must be a string or a number, not 'NoneType'
它坏了。如果我然后尝试重新运行程序,它现在会跳过它工作的部分,并直接进入损坏的部分。
只有重新运行将数据点馈送到 ThingSpeak 频道的程序,它才会再次正常运行
欢迎提出任何想法。
【问题讨论】:
标签: python raspberry-pi iot