From b406cb5b9ee43ec8c702c2f2cae8b1cb504cf8c3 Mon Sep 17 00:00:00 2001
From: "Wortman, Elliot (UG - Comp Sci & Elec Eng)" <ew00710@surrey.ac.uk>
Date: Thu, 30 Nov 2023 22:17:47 +0000
Subject: [PATCH] Write to database every 6 hours

---
 db_sqlite.py | 47 ++++++++++++++++++++++++-----------------------
 1 file changed, 24 insertions(+), 23 deletions(-)

diff --git a/db_sqlite.py b/db_sqlite.py
index 1743cd0..a6008a6 100644
--- a/db_sqlite.py
+++ b/db_sqlite.py
@@ -1,48 +1,49 @@
 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
-- 
GitLab