Last active
August 29, 2015 14:26
-
-
Save dalanmiller/7d6bb95e70721d70e6d9 to your computer and use it in GitHub Desktop.
Python script to run via cronjob, read sensor data, and push data into RethinkDB.
This file contains hidden or 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 socket | |
import rethinkdb as r | |
import time | |
import Adafruit_DHT | |
import datetime | |
import logging | |
import sys | |
logging.basicConfig( | |
level=logging.INFO, | |
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', | |
datefmt='%m-%d %H:%M' | |
) | |
sensor = Adafruit_DHT.AM2302 | |
pin = 22 | |
HOSTNAME = socket.gethostname() | |
DB_HOST = "0.0.0.0" | |
DB_PORT = 28015 | |
DB_NAME = "telemetry_pi" | |
logging.info("Attempting db connection...") | |
conn = r.connect(DB_HOST, DB_PORT, DB_NAME) | |
logging.info("Successful DB connection") | |
logging.info("Checking if db exists") | |
if DB_NAME not in list(r.db_list().run(conn)): | |
logging.info("db does not exist, creating...") | |
r.db_create(DB_NAME).run(conn) | |
logging.info("db exists") | |
logging.info("Checking to see if table exists") | |
if 'observations' not in list(r.table_list().run(conn)): | |
logging.info("table does not exist, creating...") | |
r.table_create("observations").run(conn) | |
logging.info("table exists") | |
conn.close() | |
logging.info("Attempting to read from sensor") | |
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) | |
if humidity is not None and temperature is not None: | |
conn = r.connect(DB_HOST, DB_PORT, DB_NAME) | |
timezone = time.strftime("%z") | |
reql_tz = r.make_timezone(timezone[:3] + ":" + timezone[3:]) #You need to modify this if you are not in Pacific Standard Time! | |
r.table("observations").insert(dict( | |
hostname=HOSTNAME, | |
temp=temperature, | |
humidity=humidity, | |
datetime=datetime.datetime.now(reql_tz) | |
)).run(conn, durability='soft') #Soft durability since losing one observation wouldn't be the end of the world. | |
conn.close() | |
logging.info("Successful sensor read (Temp: {:+.2f}, Humid: {:+.2f}) and insert into DB.".format( | |
temperature, humidity)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment