56 lines
1.8 KiB
Python
Executable File
56 lines
1.8 KiB
Python
Executable File
#!/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 = './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(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,
|
|
# Be Sure To Edit Location
|
|
"location": "living_room"
|
|
}
|
|
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()
|