Skip to content
Snippets Groups Projects
Commit b406cb5b authored by Wortman, Elliot (UG - Comp Sci & Elec Eng)'s avatar Wortman, Elliot (UG - Comp Sci & Elec Eng)
Browse files

Write to database every 6 hours

parent 55a5680d
No related branches found
No related tags found
No related merge requests found
import sqlite3
import json
from datetime import datetime, timedelta
DB_FILE = "measurements.db"
def insert_measurement(input_values):
""" Insert values into the database and fetch the latest entry """
def insert_measurement(input_values, time_limit=True):
""" Insert values into the database with a timestamp.
Only insert if it's been at least 6 hours since the last entry. """
try:
# Create a database connection
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
# Create table if it doesn't exist
# Create table if it doesn't exist with an additional time_modified column
cursor.execute('''CREATE TABLE IF NOT EXISTS measurements (
nitrogen INTEGER,
phosphorus INTEGER,
potassium INTEGER,
temperature INTEGER,
humidity INTEGER,
moisture INTEGER
moisture INTEGER,
time_modified TEXT
);''')
# Insert new values
# Check the time of the last entry
cursor.execute(
"SELECT time_modified FROM measurements ORDER BY rowid DESC LIMIT 1;")
last_entry = cursor.fetchone()
if time_limit and last_entry:
last_time = datetime.strptime(
last_entry[0], '%Y-%m-%dT%H:%M:%S.%fZ')
if datetime.utcnow() - last_time < timedelta(hours=6):
return False
# Insert new values with current UTC timestamp
cursor.execute('''INSERT INTO measurements
(nitrogen, phosphorus, potassium, temperature, humidity, moisture)
VALUES (?, ?, ?, ?, ?, ?)''', input_values)
(nitrogen, phosphorus, potassium, temperature, humidity, moisture, time_modified)
VALUES (?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))''', input_values)
conn.commit()
# Fetch the latest entry
cursor.execute(
"SELECT * FROM measurements ORDER BY rowid DESC LIMIT 1;")
row = cursor.fetchone()
# Close the connection
conn.close()
# Process and return the result
if row:
column_names = ['nitrogen', 'phosphorus',
'potassium', 'temperature', 'humidity', 'moisture']
data = dict(zip(column_names, row))
return json.dumps(data, indent=4)
else:
return json.dumps({})
return True
except sqlite3.Error as e:
print(e)
......@@ -57,9 +58,9 @@ def read_latest_entry_as_json():
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
# Fetch the latest entry
# Fetch the latest entry excluding the time_modified column
cursor.execute(
"SELECT * FROM measurements ORDER BY rowid DESC LIMIT 1;")
"SELECT nitrogen, phosphorus, potassium, temperature, humidity, moisture FROM measurements ORDER BY rowid DESC LIMIT 1;")
row = cursor.fetchone()
# Close the connection
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment