From 437c1179b545927197637c26bb2d87d20401e5f2 Mon Sep 17 00:00:00 2001 From: Matt Kohls Date: Fri, 23 Apr 2021 23:42:42 -0400 Subject: Update based on what is used now Many changes, mostly to make landing page more readable Oh and a file to read a sensor attached via i2c on a Raspberry Pi and add that to the db --- local.py | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 local.py (limited to 'local.py') diff --git a/local.py b/local.py new file mode 100644 index 0000000..fb7803a --- /dev/null +++ b/local.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 + +## Local Sensor Reading +# +# Reads data from sensor attached to Pi and saves in database +# +# Matt Kohls +# 2021 +## + +import sqlite3 +from sqlite3 import Error +from datetime import datetime +import time +import board +import busio +import adafruit_bme280 + + +# Local i2c BME sensor config +i2c = busio.I2C(board.SCL, board.SDA) +bme = adafruit_bme280.Adafruit_BME280_I2C(i2c) + +# Device ID for logging +deviceId = 1 + +# Start with connecting +print("Connecting to db...") +try: + db = sqlite3.connect('sensors.db') + +except Error: + print("DB connect fail: %s" % Error) + exit(-1) + + +# Check if table exists, create if needed +cursor = db.cursor() +try: + cursor.execute('SELECT name from sqlite_master WHERE type = "table" AND name = "house"') + if cursor.fetchall() is []: + print("Empty db. Creating table...") + with open('house_schema.sql', 'r') as schemaFile: + schema = schemaFile.read() + + cursor.executescript(schema) + db.commit() + +except Error: + print("DB cursor issues: %s" % Error) + exit(-1) + +# Main loop +print("Logging...") +while True: + now = datetime.now() + temp = bme.temperature + pressure = bme.pressure + humidity = bme.humidity + try: + cursor.execute('INSERT INTO house (date, temperature, humidity, pressure, deviceId) VALUES (?, ?, ?, ?, ?)', + [now, temp, humidity, pressure, deviceId]) + db.commit() + + except Error: + retryFail = False + for i in range(0, 5): + try: + cursor.execute('INSERT INTO house (date, temperature, humidity, pressure, deviceId) VALUES (?, ?, ?, ?, ?)', + [now, temp, humidity, pressure, deviceId]) + db.commit() + retryFail = False + break + + except Error: + retryFail = True + + time.sleep(5) + + if retryFail: + print("Unable to update db. Assuming the worst") + exit(-1) + time.sleep(300) + -- cgit v1.2.3