Thanks. This and adding the # or id in the results part and adding the UID as authentication did the trick. My working code is now:
import time
import serial
import requests
import datetime
import json
Open serial connection to sensor
ser = serial.Serial(‘/dev/ttyUSB0’, baudrate=9600)
Your sensor’s coordinates
latitude = 12.34567890123
longitude = 1.23456789012
Format the coordinates as a string
location = str(latitude) + “,” + str(longitude)
UID = “raspi-1234”
while True:
# Put sensor in measurement mode (the 6th byte is 0x01 which means the sensor is in measuring mode)
ser.write(b’\xAA\xB4\x06\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\x05\xAB’)
print(“Putting sensor in measurement mode”)
# Wait 60 seconds for sensor to warm up
print("Wait 1 minute for the sensor to warm up and turn on the fan")
time.sleep(60)
# Read data from sensor
data = ser.read(10)
# Extract PM2.5 and PM10 values from data
pm25 = data[2] + data[3]/10
pm10 = data[4] + data[5]/10
# Print timestamp
now = datetime.datetime.now()
print("Timestamp: ", now)
# Print values on screen
print("PM2.5: ", pm25, "ug/m^3")
print("PM10: ", pm10, "ug/m^3")
# Put sensor in sleeping mode (the 6th byte is 0x00 which means the sensor is in sleeping mode)
ser.write(b'\xAA\xB4\x06\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\x05\xAB')
print("Putting sensor in sleeping mode which also turns off the fan")
# Sense data to sensor community server
api_endpoint = "https://api.sensor.community/v1/push-sensor-data/"
data = {
"id": 12345,
"sensordatavalues": [
{
"value_type": "P1",
"value": pm10
},
{
"value_type": "P2",
"value": pm25
}
],
"location": location,
"sensor_id": 12345,
"timestamp": now.isoformat()
}
auth = {
"X-Sensor": UID
}
# Send data to API and print response
response = requests.post(api_endpoint, json=data, headers=auth)
print("Response:", response.text)
# Take reading every 10 minutes
print("Waiting 10 minutes (including warm-up) for next reading cycle")
time.sleep(540)