Archived
1
0

Pushing existing body of work.

This commit is contained in:
Shaun Setlock
2021-10-30 14:47:10 -04:00
parent 09314bb08f
commit 05d4525047
3 changed files with 125 additions and 0 deletions

55
main.py Executable file
View File

@@ -0,0 +1,55 @@
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import adafruit_dht
import time
from datetime import datetime
import pytz
from writer import get_db_creds, connect_db, insert_data
def get_sensor_data(dht22):
try:
temperature = 9./5. * dht22.temperature + 32.
humidity = dht22.humidity
return temperature, humidity
except RuntimeError as e:
print("Reading from DHT failure: ", e.args)
return None
if __name__ == "__main__":
# Setup for Hardware
DHT22_PIN = 4
dht_device = adafruit_dht.DHT22(4)
file = '/home/pi/code/dht22/log.csv'
with open(file,'a') as f:
try:
while True:
data = get_sensor_data(dht22=dht_device)
if data:
temperature, humidity = get_sensor_data(dht22=dht_device)
# current_time = datetime.now().strftime("%D %H:%M:%S")
current_time = datetime.now(pytz.timezone('UTC')).strftime("%D %H:%M:%S")
print(f'{humidity:.2f}% {temperature:.2f}degF')
f.write(f'{current_time},{temperature:.2f},{humidity:.2f}\n')
try:
data_dict = {
"datetime": current_time,
"temperature": temperature,
"humidity": humidity,
"location": "basement"
}
creds = get_db_creds("./.creds.json")
conn = connect_db(creds["db"], creds["host"], creds["user"], creds["passwd"])
insert_data(conn, data_dict)
except (Exception, psycopg2.Error) as err:
print ("\npsycopg2 connect error:", err)
time.sleep(14.9)
else:
time.sleep(0.1)
finally:
GPIO.cleanup()

8
setup.sh Normal file
View File

@@ -0,0 +1,8 @@
# Install base OS (Debian) packages.
apt update && apt upgrade -y && apt install python3-dev python3-pip python3-psycopg2 libgpiod2 -y
# Install Python modules.
pip3 install RPi.GPIO psycopg2 adafruit-circuitpython-dht
# Start the python script.
/usr/bin/python3 main.py

62
writer.py Normal file
View File

@@ -0,0 +1,62 @@
#! env/bin/python3
# import the psycopg2 database adapter for PostgreSQL
import psycopg2
from psycopg2.extras import Json
import json
import sys
def connect_db(db: str,host: str,user: str,passwd: str):
try:
# declare a new PostgreSQL connection object
conn = psycopg2.connect(
dbname = db,
user = user,
host = host,
password = passwd,
# attempt to connect for 3 seconds then raise exception
connect_timeout = 3
)
except (Exception, psycopg2.Error) as err:
# print ("\npsycopg2 connect error:", err)
conn = None
return conn
def get_db_creds(file: str):
with open(file) as cred_file:
creds = json.load(cred_file)
return creds
def insert_data(conn, data):
# insert a new vendor into the vendors table
sql = """
INSERT INTO
air(datetime, temperature, humidity, location)
VALUES
(%s, %s, %s, %s)
"""
try:
# open cursor on our db connection
cur = conn.cursor()
# execute the INSERT statement
data = (data["datetime"], data["temperature"], data["humidity"], data["location"])
cur.execute(sql,data)
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
# print(error)
pass
finally:
if conn is not None:
conn.close()