Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -14,9 +14,7 @@ app.secret_key = os.urandom(24) # For session management
|
|
14 |
|
15 |
# Firebase Admin SDK initialization
|
16 |
FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
|
17 |
-
|
18 |
-
cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
|
19 |
-
firebase_admin.initialize_app(cred)
|
20 |
|
21 |
# Firestore client
|
22 |
db = firestore.client()
|
@@ -31,14 +29,6 @@ TO_PHONE = '+916382792828'
|
|
31 |
with open('model.pkl', 'rb') as f:
|
32 |
loaded_model = pickle.load(f)
|
33 |
|
34 |
-
# ThingSpeak Configuration
|
35 |
-
THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
|
36 |
-
CHANNEL_ID = "2784385"
|
37 |
-
|
38 |
-
# Global variable to track the last entry ID
|
39 |
-
last_entry_id = None
|
40 |
-
|
41 |
-
|
42 |
def predict_conc(pdiff):
|
43 |
try:
|
44 |
if pdiff > 3.19:
|
@@ -52,7 +42,6 @@ def predict_conc(pdiff):
|
|
52 |
print(f"Error in predict_conc: {e}")
|
53 |
return None
|
54 |
|
55 |
-
|
56 |
def send_msg(field1, suggestion):
|
57 |
client = Client(ACCOUNT_SID, AUTH_TOKEN)
|
58 |
try:
|
@@ -65,7 +54,6 @@ def send_msg(field1, suggestion):
|
|
65 |
except Exception as e:
|
66 |
print(f"Failed to send message: {e}")
|
67 |
|
68 |
-
|
69 |
def on_snapshot(doc_snapshot, changes, read_time):
|
70 |
for change in changes:
|
71 |
if change.type.name == 'ADDED':
|
@@ -78,11 +66,10 @@ def on_snapshot(doc_snapshot, changes, read_time):
|
|
78 |
print(f"New data detected: {new_data}")
|
79 |
concentration = predict_conc(float(field1))
|
80 |
if concentration == "0":
|
81 |
-
send_msg(0, "The water is safe for use
|
82 |
else:
|
83 |
send_msg(concentration, "You may boil the water to 50\u00b0C to eradicate the bacteria.")
|
84 |
|
85 |
-
|
86 |
def start_firestore_listener():
|
87 |
try:
|
88 |
thingspeak_ref = db.collection('thingspeak_data')
|
@@ -91,47 +78,82 @@ def start_firestore_listener():
|
|
91 |
except Exception as e:
|
92 |
print(f"Error starting Firestore listener: {e}")
|
93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
|
95 |
def fetch_thingspeak_data():
|
96 |
"""Fetch data from ThingSpeak"""
|
97 |
global last_entry_id
|
98 |
try:
|
99 |
-
url = f"https://api.thingspeak.com/channels/
|
100 |
response = requests.get(url)
|
101 |
response.raise_for_status() # Raise an exception for bad responses
|
102 |
data = response.json()
|
103 |
-
|
104 |
# Check if there are feeds
|
105 |
if not data.get('feeds'):
|
106 |
print("No new feeds found.")
|
107 |
return None
|
108 |
-
|
109 |
# Get the latest feed
|
110 |
latest_feed = data['feeds'][-1]
|
111 |
-
|
112 |
# Check if this is a new entry
|
113 |
current_entry_id = latest_feed.get('entry_id')
|
114 |
-
|
115 |
if current_entry_id != last_entry_id:
|
116 |
last_entry_id = current_entry_id
|
117 |
return latest_feed
|
118 |
-
|
119 |
print("No new entries since last check.")
|
120 |
return None
|
121 |
-
|
122 |
except requests.RequestException as e:
|
123 |
print(f"ThingSpeak data fetch error: {e}")
|
124 |
return None
|
125 |
|
126 |
-
|
127 |
-
def store_data_in_firestore(data):
|
128 |
"""Store data in Firestore"""
|
129 |
try:
|
130 |
# Validate data
|
131 |
if not data:
|
132 |
print("No data to store.")
|
133 |
return
|
134 |
-
|
135 |
# Create a document with timestamp
|
136 |
doc_data = {
|
137 |
'field1': data.get('field1'),
|
@@ -139,48 +161,38 @@ def store_data_in_firestore(data):
|
|
139 |
'entry_id': data.get('entry_id'),
|
140 |
'timestamp': firestore.SERVER_TIMESTAMP
|
141 |
}
|
142 |
-
|
143 |
# Add to Firestore collection
|
144 |
-
|
145 |
print("New data successfully stored in Firestore")
|
146 |
except Exception as e:
|
147 |
print(f"Firestore storage error: {e}")
|
148 |
|
149 |
|
150 |
-
|
151 |
-
def index():
|
152 |
-
return render_template('index.html')
|
153 |
|
|
|
|
|
|
|
154 |
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
|
|
|
|
|
|
|
|
|
160 |
|
161 |
if __name__ == '__main__':
|
162 |
-
|
163 |
-
import threading
|
164 |
-
listener_thread = threading.Thread(target=start_firestore_listener)
|
165 |
-
listener_thread.start()
|
166 |
-
|
167 |
-
# Main data collection loop
|
168 |
-
try:
|
169 |
-
while True:
|
170 |
-
# Fetch data from ThingSpeak
|
171 |
-
thingspeak_data = fetch_thingspeak_data()
|
172 |
-
|
173 |
-
if thingspeak_data:
|
174 |
-
# Store data in Firestore only if there's a new entry
|
175 |
-
store_data_in_firestore(thingspeak_data)
|
176 |
-
|
177 |
-
# Wait before next iteration
|
178 |
-
time.sleep(5) # Adjust interval as needed
|
179 |
-
|
180 |
-
except KeyboardInterrupt:
|
181 |
-
print("Data collection stopped by user.")
|
182 |
-
except Exception as e:
|
183 |
-
print(f"Unexpected error: {e}")
|
184 |
-
|
185 |
-
# Run Flask app
|
186 |
app.run(host='0.0.0.0', port=7860, debug=True)
|
|
|
14 |
|
15 |
# Firebase Admin SDK initialization
|
16 |
FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
|
17 |
+
firebase_admin.initialize_app(cred)
|
|
|
|
|
18 |
|
19 |
# Firestore client
|
20 |
db = firestore.client()
|
|
|
29 |
with open('model.pkl', 'rb') as f:
|
30 |
loaded_model = pickle.load(f)
|
31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
def predict_conc(pdiff):
|
33 |
try:
|
34 |
if pdiff > 3.19:
|
|
|
42 |
print(f"Error in predict_conc: {e}")
|
43 |
return None
|
44 |
|
|
|
45 |
def send_msg(field1, suggestion):
|
46 |
client = Client(ACCOUNT_SID, AUTH_TOKEN)
|
47 |
try:
|
|
|
54 |
except Exception as e:
|
55 |
print(f"Failed to send message: {e}")
|
56 |
|
|
|
57 |
def on_snapshot(doc_snapshot, changes, read_time):
|
58 |
for change in changes:
|
59 |
if change.type.name == 'ADDED':
|
|
|
66 |
print(f"New data detected: {new_data}")
|
67 |
concentration = predict_conc(float(field1))
|
68 |
if concentration == "0":
|
69 |
+
send_msg(0, "The water is safe for use!!")
|
70 |
else:
|
71 |
send_msg(concentration, "You may boil the water to 50\u00b0C to eradicate the bacteria.")
|
72 |
|
|
|
73 |
def start_firestore_listener():
|
74 |
try:
|
75 |
thingspeak_ref = db.collection('thingspeak_data')
|
|
|
78 |
except Exception as e:
|
79 |
print(f"Error starting Firestore listener: {e}")
|
80 |
|
81 |
+
@app.route('/')
|
82 |
+
def index():
|
83 |
+
return render_template('index.html')
|
84 |
+
|
85 |
+
@app.route('/logout')
|
86 |
+
def logout():
|
87 |
+
session.pop('user_phone', None)
|
88 |
+
return redirect(url_for('index'))
|
89 |
+
|
90 |
+
|
91 |
+
|
92 |
+
import requests
|
93 |
+
import firebase_admin
|
94 |
+
from firebase_admin import credentials, firestore
|
95 |
+
import time
|
96 |
+
|
97 |
+
# Replace with your actual credentials
|
98 |
+
THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
|
99 |
+
CHANNEL_ID = "2784385"
|
100 |
+
FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
|
101 |
+
|
102 |
+
# Global variable to track the last entry ID
|
103 |
+
last_entry_id = None
|
104 |
+
|
105 |
+
def initialize_firebase():
|
106 |
+
"""Initialize Firebase connection"""
|
107 |
+
try:
|
108 |
+
# Initialize Firebase app (only once)
|
109 |
+
cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
|
110 |
+
firebase_admin.initialize_app(cred)
|
111 |
+
|
112 |
+
# Create Firestore client
|
113 |
+
return firestore.client()
|
114 |
+
except Exception as e:
|
115 |
+
print(f"Firebase initialization error: {e}")
|
116 |
+
return None
|
117 |
|
118 |
def fetch_thingspeak_data():
|
119 |
"""Fetch data from ThingSpeak"""
|
120 |
global last_entry_id
|
121 |
try:
|
122 |
+
url = f"https://api.thingspeak.com/channels/2784385/feeds.json?api_key=P54KXM40TA3CB6W4"
|
123 |
response = requests.get(url)
|
124 |
response.raise_for_status() # Raise an exception for bad responses
|
125 |
data = response.json()
|
126 |
+
|
127 |
# Check if there are feeds
|
128 |
if not data.get('feeds'):
|
129 |
print("No new feeds found.")
|
130 |
return None
|
131 |
+
|
132 |
# Get the latest feed
|
133 |
latest_feed = data['feeds'][-1]
|
134 |
+
|
135 |
# Check if this is a new entry
|
136 |
current_entry_id = latest_feed.get('entry_id')
|
137 |
+
|
138 |
if current_entry_id != last_entry_id:
|
139 |
last_entry_id = current_entry_id
|
140 |
return latest_feed
|
141 |
+
|
142 |
print("No new entries since last check.")
|
143 |
return None
|
144 |
+
|
145 |
except requests.RequestException as e:
|
146 |
print(f"ThingSpeak data fetch error: {e}")
|
147 |
return None
|
148 |
|
149 |
+
def store_data_in_firestore(firestore_client, data):
|
|
|
150 |
"""Store data in Firestore"""
|
151 |
try:
|
152 |
# Validate data
|
153 |
if not data:
|
154 |
print("No data to store.")
|
155 |
return
|
156 |
+
|
157 |
# Create a document with timestamp
|
158 |
doc_data = {
|
159 |
'field1': data.get('field1'),
|
|
|
161 |
'entry_id': data.get('entry_id'),
|
162 |
'timestamp': firestore.SERVER_TIMESTAMP
|
163 |
}
|
164 |
+
|
165 |
# Add to Firestore collection
|
166 |
+
firestore_client.collection('thingspeak_data').add(doc_data)
|
167 |
print("New data successfully stored in Firestore")
|
168 |
except Exception as e:
|
169 |
print(f"Firestore storage error: {e}")
|
170 |
|
171 |
|
172 |
+
firestore_client = initialize_firebase()
|
|
|
|
|
173 |
|
174 |
+
if not firestore_client:
|
175 |
+
print("Failed to initialize Firestore. Exiting.")
|
176 |
+
return
|
177 |
|
178 |
+
# Main data collection loop
|
179 |
+
try:
|
180 |
+
while True:
|
181 |
+
# Fetch data from ThingSpeak
|
182 |
+
thingspeak_data = fetch_thingspeak_data()
|
183 |
+
|
184 |
+
if thingspeak_data:
|
185 |
+
# Store data in Firestore only if there's a new entry
|
186 |
+
store_data_in_firestore(firestore_client, thingspeak_data)
|
187 |
+
|
188 |
+
# Wait before next iteration
|
189 |
+
time.sleep(5) # Adjust interval as needed
|
190 |
|
191 |
+
except KeyboardInterrupt:
|
192 |
+
print("Data collection stopped by user.")
|
193 |
+
except Exception as e:
|
194 |
+
print(f"Unexpected error: {e}")
|
195 |
|
196 |
if __name__ == '__main__':
|
197 |
+
start_firestore_listener()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
198 |
app.run(host='0.0.0.0', port=7860, debug=True)
|