因此,我目前正在进行一个大学项目,在我的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频道的程序,它才能再次正常运行
欢迎提出任何意见
我查看了您的公共频道,您的field1数据中有一些空值。为什么要读取最后两个值?最好将数据放在多个字段中,读取一个提要条目,然后从中解析出正确的字段
我建议您在ThingSpeak上使用MQTT功能,然后您可以订阅该频道并仅在频道更改时获取更新
相关问题 更多 >
编程相关推荐