#!/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)