主要内容

搜索

Hey, so I have a simple air quality measurement IoT system but the values are not arriving in my ThingSpeak channel. I use basic tutorials for it and tried some kind of variation but the code is so simple, I don't see any problem code-wise. Maybe someone here can help me?
I am working with a Raspberry Pi 3 and the following code for a SDS011 sensor:
import time
from datetime import datetime
import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt
import psutil
from sds011 import *
import aqi
sensor = SDS011("/dev/ttyUSB0", use_query_mode=True)
def get_data(n=3):
sensor.sleep(sleep=False)
pmt_2_5 = 0
pmt_10 = 0
time.sleep(10)
for i in range (n):
x = sensor.query()
pmt_2_5 = pmt_2_5 + x[0]
pmt_10 = pmt_10 + x[1]
time.sleep(2)
pmt_2_5 = round(pmt_2_5/n, 1)
pmt_10 = round(pmt_10/n, 1)
sensor.sleep(sleep=True)
time.sleep(2)
return pmt_2_5, pmt_10
def conv_aqi(pmt_2_5, pmt_10):
aqi_2_5 = aqi.to_iaqi(aqi.POLLUTANT_PM25, str(pmt_2_5))
aqi_10 = aqi.to_iaqi(aqi.POLLUTANT_PM10, str(pmt_10))
return aqi_2_5, aqi_10
def save_log():
with open("/YOUR PATH/air_quality.csv", "a") as log:
dt = datetime.now()
log.write("{},{},{},{},{}\n".format(dt, pmt_2_5, aqi_2_5, pmt_10, aqi_10))
log.close()
channelID = "YOUR CHANNEL ID"
apiKey = "YOUR WRITE KEY"
clientID = "YOUR CLIENT ID"
tUsername = "YOUR USERNAME"
tPassword = "YOUR PASSWORD"
topic = "channels/" + channelID + "/publish/" + apiKey
mqttHost = "mqtt3.thingspeak.com"
tTransport = "tcp"
tPort = 1883
tTLS = None
tProtocol = mqtt.MQTTv311
while True:
pmt_2_5, pmt_10 = get_data()
aqi_2_5, aqi_10 = conv_aqi(pmt_2_5, pmt_10)
print ("AQI2.5 =", aqi_2_5," AQI10 =", aqi_10)
tPayload = "field1=" + str(pmt_2_5)+ "&field2=" + str(aqi_2_5)+ "&field3=" + str(pmt_10)+ "&field4=" + str(aqi_10)
try:
publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, client_id=clientID, auth={'username':tUsername, 'password':tPassword}, tls=tTLS, transport=tTransport, protocol=tProtocol)
print ("[INFO] Published data")
save_log()
time.sleep(60)
except Exception as e:
print ("[INFO] Failure in sending data")
print (e)
time.sleep(60)