-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathultrasonic_water.py
203 lines (158 loc) · 7.35 KB
/
ultrasonic_water.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
# AquaFusion - BSIT 4A - CPSTONE
import RPi.GPIO as GPIO
import time
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db, firestore
from config import FIREBASE_CONFIG, WORKGROUP_ID, FIREBASE_WATER
TRIG = 23
ECHO = 24
# Initialize Firebase Admin for Realtime Database
cred = credentials.Certificate(FIREBASE_CONFIG['serviceAccountKeyPath'])
firebase_admin.initialize_app(cred, {
'databaseURL': FIREBASE_CONFIG['databaseURL']
}, name='realtime')
# Initialize Firebase Admin for Firestore
cred_firestore = credentials.Certificate(FIREBASE_CONFIG['serviceAccountKeyPath'])
firebase_admin.initialize_app(cred_firestore, {
'projectId': FIREBASE_CONFIG['projectId'], # Add your Firebase project ID
}, name='firestore')
# Initialize Realtime Database
realtime_db = db.reference(FIREBASE_WATER['sensorCollection'], app=firebase_admin.get_app(name='realtime'))
realtime_db_threshold_lower = db.reference(FIREBASE_WATER['sensorLower'], app=firebase_admin.get_app(name='realtime'))
realtime_db_threshold_upper = db.reference(FIREBASE_WATER['sensorUpper'], app=firebase_admin.get_app(name='realtime'))
realtime_db_threshold_normal = db.reference(FIREBASE_WATER['sensorNormal'], app=firebase_admin.get_app(name='realtime'))
water_normal = realtime_db_threshold_normal.get()
water_limits_lower = realtime_db_threshold_lower.get()
water_limits_upper = realtime_db_threshold_upper.get()
unique_Id = WORKGROUP_ID['uniqueId']
# Initialize Firestore
db = firestore.client(app=firebase_admin.get_app(name='firestore'))
last_firestore_upload_time = time.time()
def on_threshold_change_lower(event):
global water_limits_lower
if event.data is not None:
water_limits_lower = str(event.data)
print("Threshold lower levels updated:", water_limits_lower)
else:
print("Threshold levels data not available in the database.")
def on_threshold_change_upper(event):
global water_limits_upper
if event.data is not None:
water_limits_upper = str(event.data)
print("Threshold upper levels updated:", water_limits_upper)
else:
print("Threshold levels data not available in the database.")
threshold_listener_lower = realtime_db_threshold_lower.listen(on_threshold_change_lower)
threshold_listener_upper = realtime_db_threshold_upper.listen(on_threshold_change_upper)
prev_water_status = None
prev_sensor_status = None
notif_title = "Water Volume Alert"
notif_type = "alert"
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
while True:
utc_offset = 8
curr_time = time.gmtime(time.time() + utc_offset * 3600)
form_time = time.strftime("%H:%M:%S", curr_time)
time_period = time.strftime("%Y:%m:%d", curr_time)
date_time = time.strftime("%m/%d/%Y", curr_time)
try:
GPIO.output(TRIG, False)
time.sleep(2)
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
if distance >= 0:
checkStatus = True
sensor_status = "On"
if sensor_status != prev_sensor_status:
prev_sensor_status = sensor_status
data_firestore_status = {
"notificationDate": date_time,
"notificationDescription": prev_sensor_status,
"notificationTitle": notif_title,
"notificationTimestamp": form_time,
"notificationType": notif_type,
"workgroupId": unique_Id
}
doc_ref_alert_status = db.collection('notifications').add(data_firestore_status)
lower_key = FIREBASE_WATER['sensorConditionalLower']
upper_key = FIREBASE_WATER['sensorConditionalUpper']
if water_normal and lower_key in water_normal and upper_key in water_normal:
lower_limit = water_normal[lower_key]
upper_limit = water_normal[upper_key]
if distance <= 0:
water_status = "Error: Distance is not valid."
elif distance < lower_limit:
water_status = "Warning: High water volume!"
elif lower_limit <= distance <= upper_limit:
water_status = "Optimal"
else:
water_status = "Warning: Low water volume! Please refill."
if water_status != prev_water_status:
prev_water_status = water_status
data_firestore_alert = {
"notificationDate": date_time,
"notificationDescription": prev_water_status,
"notificationTitle": notif_title,
"notificationTimestamp": form_time,
"notificationType": notif_type,
"workgroupId": unique_Id
}
doc_ref_alert = db.collection('notifications').add(data_firestore_alert)
print("Distance:", distance, "cm")
print(form_time)
print(water_status)
# Dictionary with the data to send to Firebase Realtime Database
data_realtime_db = {
"Status": checkStatus,
"distance": distance,
"status_notif": water_status
}
# Send the data to Firebase Realtime Database
realtime_db.update(data_realtime_db)
# Get the current time
current_time = time.time()
firestore_upload_interval = 5 #60 seconds = 1 minute
if (current_time - last_firestore_upload_time >= firestore_upload_interval):
last_firestore_upload_time = current_time
data_firestore = {
"distance": distance,
"timestamp": form_time,
"timeperiod": time_period,
"workgroupId": unique_Id
}
doc_ref = db.collection('ultrasonic_water').add(data_firestore)
except KeyboardInterrupt:
threshold_listener_lower.close()
threshold_listener_upper.close()
print("Measurement stopped by the user.")
checkStatus = False
sensor_off = "Water Sensor is Off"
data_realtime_db = {
"Status": checkStatus,
}
realtime_db.update(data_realtime_db)
data_firestore_off = {
"notificationDate": date_time,
"notificationDescription": sensor_off,
"notificationTitle": notif_title,
"notificationTimestamp": form_time,
"notificationType": notif_type,
"workgroupId": unique_Id
}
doc_ref_alert_off = db.collection('notifications').add(data_firestore_off)
break
finally:
GPIO.cleanup()
time.sleep(1)