1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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)
|