Skip to content

Instantly share code, notes, and snippets.

@mrjoh3
Last active April 9, 2017 03:04
Show Gist options
  • Save mrjoh3/e871c27e7ff43023744831a39d471a25 to your computer and use it in GitHub Desktop.
Save mrjoh3/e871c27e7ff43023744831a39d471a25 to your computer and use it in GitHub Desktop.
Read particle data from a Nova sensor and save to InfluxDB
import time
import serial, re, os
from datetime import datetime
from time import strftime
from influxdb import InfluxDBClient
import geohash
# Set this variables, influxDB should be localhost on Pi
host = "localhost"
port = 8086
user = "root"
password = "root"
# The database we created
dbname = "logger"
# Create the InfluxDB object
client = InfluxDBClient(host, port, user, password, dbname)
# set location
lat = -32
lon = 143
location = geohash.encode(lat, lon)
# set serial connection to sensor
ser = serial.Serial('/dev/ttyS0',
9600,
8,
'N',
1,
timeout = 0.5)
i = 0
#the main sensor reading loop
try:
while True:
out = ser.readline()
print(out)
if len(out) == 10:
PM25 = ((list(out)[3]*256) + list(out)[2]) / 10
PM10 = ((list(out)[5]*256) + list(out)[4]) / 10
iso = time.ctime()
json_body = [{"measurement": 'air_quality',
"tags": {"type": 'particles',
"location": location},
#"time": iso,
"fields": {"PM25" : PM25,
"PM10" : PM10}}]
print(PM10, PM25)
# Write JSON to InfluxDB
try:
assert PM10 < 9999, 'PM10 invalid value'
assert PM25 < 9999, 'PM25 invalid value'
client.write_points(json_body)
except AssertionError as e:
print(e)
pass
except:
print('db error passing')
pass
i += 1
# delay between stream posts time.sleep(0.25)
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment