forked from wagnerin/Plant-Monitoring-System-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
216 lines (178 loc) · 5.37 KB
/
database.py
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# database.py
# Handles database operations for the Plant Monitoring System.
import sqlite3
from datetime import datetime
# Constants
DATABASE_FILE = "plant_monitoring.db"
def initialize_database():
"""
Initializes the database and creates necessary tables.
"""
try:
connection = sqlite3.connect(DATABASE_FILE)
cursor = connection.cursor()
# Create sensors data table
cursor.execute("""
CREATE TABLE IF NOT EXISTS sensor_data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
soil_moisture INTEGER,
light_level INTEGER,
temperature REAL,
humidity REAL
)
""")
# Create logs table
cursor.execute("""
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
action TEXT
)
""")
# Create schedule table
cursor.execute("""
CREATE TABLE IF NOT EXISTS schedules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device TEXT,
schedule_time DATETIME,
duration INTEGER
)
""")
connection.commit()
connection.close()
print("Database initialized successfully.")
except sqlite3.Error as e:
print(f"Error initializing database: {e}")
def add_sensor_data(soil_moisture, light_level, temperature, humidity):
"""
Adds new sensor data to the database.
"""
try:
connection = sqlite3.connect(DATABASE_FILE)
cursor = connection.cursor()
cursor.execute("""
INSERT INTO sensor_data (soil_moisture, light_level, temperature, humidity)
VALUES (?, ?, ?, ?)
""", (soil_moisture, light_level, temperature, humidity))
connection.commit()
connection.close()
print("Sensor data added successfully.")
except sqlite3.Error as e:
print(f"Error adding sensor data: {e}")
def get_sensor_data_history(limit=10):
"""
Retrieves the most recent sensor data from the database.
"""
try:
connection = sqlite3.connect(DATABASE_FILE)
cursor = connection.cursor()
cursor.execute("""
SELECT * FROM sensor_data
ORDER BY timestamp DESC
LIMIT ?
""", (limit,))
rows = cursor.fetchall()
connection.close()
return rows
except sqlite3.Error as e:
print(f"Error retrieving sensor data: {e}")
return []
def add_log(action):
"""
Adds a new log entry to the database.
"""
try:
connection = sqlite3.connect(DATABASE_FILE)
cursor = connection.cursor()
cursor.execute("""
INSERT INTO logs (action)
VALUES (?)
""", (action,))
connection.commit()
connection.close()
print("Log added successfully.")
except sqlite3.Error as e:
print(f"Error adding log: {e}")
def get_logs(limit=10):
"""
Retrieves the most recent logs from the database.
"""
try:
connection = sqlite3.connect(DATABASE_FILE)
cursor = connection.cursor()
cursor.execute("""
SELECT * FROM logs
ORDER BY timestamp DESC
LIMIT ?
""", (limit,))
rows = cursor.fetchall()
connection.close()
return rows
except sqlite3.Error as e:
print(f"Error retrieving logs: {e}")
return []
def add_schedule(device, schedule_time, duration):
"""
Adds a new schedule to the database.
"""
try:
connection = sqlite3.connect(DATABASE_FILE)
cursor = connection.cursor()
cursor.execute("""
INSERT INTO schedules (device, schedule_time, duration)
VALUES (?, ?, ?)
""", (device, schedule_time, duration))
connection.commit()
connection.close()
print("Schedule added successfully.")
except sqlite3.Error as e:
print(f"Error adding schedule: {e}")
def get_schedules():
"""
Retrieves all schedules from the database.
"""
try:
connection = sqlite3.connect(DATABASE_FILE)
cursor = connection.cursor()
cursor.execute("""
SELECT * FROM schedules
ORDER BY schedule_time ASC
""")
rows = cursor.fetchall()
connection.close()
return rows
except sqlite3.Error as e:
print(f"Error retrieving schedules: {e}")
return []
def delete_schedule(schedule_id):
"""
Deletes a schedule from the database by ID.
"""
try:
connection = sqlite3.connect(DATABASE_FILE)
cursor = connection.cursor()
cursor.execute("""
DELETE FROM schedules
WHERE id = ?
""", (schedule_id,))
connection.commit()
connection.close()
print("Schedule deleted successfully.")
except sqlite3.Error as e:
print(f"Error deleting schedule: {e}")
# Example usage
if __name__ == "__main__":
initialize_database()
add_sensor_data(45, 300, 25.5, 60)
print("Recent Sensor Data:")
for row in get_sensor_data_history():
print(row)
add_log("Test log entry")
print("Recent Logs:")
for row in get_logs():
print(row)
add_schedule("watering", "2024-11-19 08:00:00", 15)
print("Schedules:")
for row in get_schedules():
print(row)