Created
January 10, 2020 20:39
-
-
Save mcindea/23177cbff5666c773cb6f5607d0f08d9 to your computer and use it in GitHub Desktop.
Uses SDS011 to get the data and store it to InfluxDB - Tested it from a RaspberryPI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import serial, time, os, traceback | |
from influxdb import InfluxDBClient | |
# InfluxDB details | |
dbname = os.getenv('INFLUXDB_DATABASE', 'airquality') | |
username = os.getenv('INFLUXDB_USER') | |
password = os.getenv('INFLUXDB_PASSWORD') | |
host = os.getenv('INFLUXDB_HOST', '192.168.100.21') | |
port = os.getenv('INFLUXDB_PORT', 8086) | |
print("Connecting to InfluxDB host:{}, DB:{}".format(host, dbname)) | |
influxdb_client = InfluxDBClient(host, port, username, password, dbname) | |
influxdb_client.create_database(dbname) | |
ser = serial.Serial('/dev/ttyUSB0') | |
def get_pm(serial): | |
data = [] | |
fields = {} | |
for index in range(0, 10): | |
datum = serial.read() | |
data.append(datum) | |
fields['pmtwofive'] = int.from_bytes(b''.join(data[2:4]), byteorder='little') / 10 | |
fields['pmten'] = int.from_bytes(b''.join(data[4:6]), byteorder='little') / 10 | |
tags = {'host': os.getenv('HOSTNAME', 'localhost')} | |
return [ | |
{ | |
'measurement': 'pm', | |
'fields': fields, | |
'tags': tags | |
} | |
] | |
while True: | |
data = get_pm(ser) | |
try: | |
print(data) | |
influxdb_client.write_points(data) | |
except: | |
print("Error connecting to InfluxDB.") | |
tb = traceback.format_exc() | |
print(tb) | |
time.sleep(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment