Hoang Bach in Discussions
Última actividad el 16 de Abr. de 2024

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) Publish via Paho-MQTT publish.single but data is not arriving? Have a look at the documentation for MQTT and the provided examples. You are using syntax from the old broker, which was replaced in July 2021 and deprecated in April. Here is the new publish syntax for publish. The topic you are publishing to is incorrect. Take a look at the examples Christopher has linked to. So is this page in your documentation outdated then: https://se.mathworks.com/help/thingspeak/use-raspberry-pi-board-that-runs-python-websockets-to-publish-to-a-channel.html? Is there any way to use paho_mqtt to publish data in ThingSpeak or is the only option to use MQTT X? The code you reference should work. You can definitely still use paho, im pretty sure ive done it already on a pi. Just set up am MQTT device on the thingSpeak web UI, enable publishing from that device to your channel of interest, and copy the credentials to the pi. Can you tell us where it is failing for you? Now I found it: one extra /. Had f"channels/{channel_ID}/publish/ instead of f"channels/{channel_ID}/publish Damn, it was hard to find it. :P Thanks for help anyway! Ive had that one before, sorry I didnt look close enough to see that. We appreciate you sharing the solution! If its working, can you share an interesting plot from your monitor to inspire others who see this discussion? publish mqtt paho-mqtt air-quality sds011 raspberry pi 3
Roger Notknomuch in MATLAB Answers
Última actividad el 26 de Mayo de 2020

Hello Community, first of all let me admit, that I am - according to python - a "script-kiddie". I recently learned html5, css3 and javascript, but that is not helpful here. That is why I need your help. I found a script that is reading the data from my sds011 sensor. It passes its data to a webpage. So far so good. Now I would like to pass the data to thingspeak. After a couple of hours trying without really understanding I would appreciate help. I think the code line below ist the one I need for updating my channel in thingspeak. But the channel remains empty. No data shown. What have I done wrong? Help appreciated. Learning python is on my "To-Do-List" ;-) Kind regards, Roger Short code: import urllib .... urllib.request.urlopen("https://api.thingspeak.com/update?api_key=RJASGFLWRVM5JKHM&field1=pm25&field2=pm10") The entire code: #!/usr/bin/python -u # coding=utf-8 # "DATASHEET": http://cl.ly/ekot # https://gist.github.com/kadamski/92653913a53baf9dd1a8 from __future__ import print_function import serial, struct, sys, time, json, subprocess import urllib DEBUG = 0 CMD_MODE = 2 CMD_QUERY_DATA = 4 CMD_DEVICE_ID = 5 CMD_SLEEP = 6 CMD_FIRMWARE = 7 CMD_WORKING_PERIOD = 8 MODE_ACTIVE = 0 MODE_QUERY = 1 PERIOD_CONTINUOUS = 0 JSON_FILE = '/var/www/html/aqi.json' MQTT_HOST = '' MQTT_TOPIC = '/weather/particulatematter' ser = serial.Serial() ser.port = "/dev/ttyUSB0" ser.baudrate = 9600 ser.open() ser.flushInput() byte, data = 0, "" def dump(d, prefix=''): print(prefix + ' '.join(x.encode('hex') for x in d)) def construct_command(cmd, data=[]): assert len(data) <= 12 data += [0,]*(12-len(data)) checksum = (sum(data)+cmd-2)%256 ret = "\xaa\xb4" + chr(cmd) ret += ''.join(chr(x) for x in data) ret += "\xff\xff" + chr(checksum) + "\xab" if DEBUG: dump(ret, '> ') return ret def process_data(d): r = struct.unpack('<HHxxBB', d[2:]) pm25 = r[0]/10.0 pm10 = r[1]/10.0 checksum = sum(ord(v) for v in d[2:8])%256 return [pm25, pm10] #print("PM 2.5: {} μg/m^3 PM 10: {} μg/m^3 CRC={}".format(pm25, pm10, "OK" if (checksum==r[2] and r[3]==0xab) else "NOK")) def process_version(d): r = struct.unpack('<BBBHBB', d[3:]) checksum = sum(ord(v) for v in d[2:8])%256 print("Y: {}, M: {}, D: {}, ID: {}, CRC={}".format(r[0], r[1], r[2], hex(r[3]), "OK" if (checksum==r[4] and r[5]==0xab) else "NOK")) def read_response(): byte = 0 while byte != "\xaa": byte = ser.read(size=1) d = ser.read(size=9) if DEBUG: dump(d, '< ') return byte + d def cmd_set_mode(mode=MODE_QUERY): ser.write(construct_command(CMD_MODE, [0x1, mode])) read_response() def cmd_query_data(): ser.write(construct_command(CMD_QUERY_DATA)) d = read_response() values = [] if d[1] == "\xc0": values = process_data(d) return values def cmd_set_sleep(sleep): mode = 0 if sleep else 1 ser.write(construct_command(CMD_SLEEP, [0x1, mode])) read_response() def cmd_set_working_period(period): ser.write(construct_command(CMD_WORKING_PERIOD, [0x1, period])) read_response() def cmd_firmware_ver(): ser.write(construct_command(CMD_FIRMWARE)) d = read_response() process_version(d) def cmd_set_id(id): id_h = (id>>8) % 256 id_l = id % 256 ser.write(construct_command(CMD_DEVICE_ID, [0]*10+[id_l, id_h])) read_response() def pub_mqtt(jsonrow): cmd = ['mosquitto_pub', '-h', MQTT_HOST, '-t', MQTT_TOPIC, '-s'] print('Publishing using:', cmd) with subprocess.Popen(cmd, shell=False, bufsize=0, stdin=subprocess.PIPE).stdin as f: json.dump(jsonrow, f) if __name__ == "__main__": cmd_set_sleep(0) cmd_firmware_ver() cmd_set_working_period(PERIOD_CONTINUOUS) cmd_set_mode(MODE_QUERY); while True: cmd_set_sleep(0) for t in range(15): values = cmd_query_data(); if values is not None and len(values) == 2: print("PM2.5: ", values[0], ", PM10: ", values[1]) time.sleep(2) # open stored data try: with open(JSON_FILE) as json_data: data = json.load(json_data) except IOError as e: data = [] # check if length is more than 100 and delete first element if len(data) > 100: data.pop(0) # append new values jsonrow = {'pm25': values[0], 'pm10': values[1], 'time': time.strftime("%d.%m.%Y %H:%M:%S")} data.append(jsonrow) # save it with open(JSON_FILE, 'w') as outfile: json.dump(data, outfile) if MQTT_HOST != '': pub_mqtt(jsonrow) #!!!!!!!!!!!!!!!!!!! HERE urllib.request.urlopen("https://api.thingspeak.com/update?api_key=RJASGFLWRVM5JKHM&field1=pm25&field2=pm10") print("Going to sleep for 2 min...") # Alter time.sleep = 1200 cmd_set_sleep(1) time.sleep(120)

Acerca de ThingSpeak

The community for students, researchers, and engineers looking to use MATLAB, Simulink, and ThingSpeak for Internet of Things applications. You can find the latest ThingSpeak news, tutorials to jump-start your next IoT project, and a forum to engage in a discussion on your latest cloud-based project. You can see answers to problems other users have solved and share how you solved a problem.