Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,34 +1,139 @@
|
|
1 |
import os
|
|
|
|
|
2 |
import folium
|
3 |
from flask import Flask, render_template, jsonify, request, redirect, url_for, session
|
|
|
4 |
import firebase_admin
|
5 |
from firebase_admin import credentials, firestore
|
6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
# Initialize Flask app
|
8 |
app = Flask(__name__)
|
9 |
app.secret_key = os.urandom(24) # For session management
|
10 |
|
11 |
-
#
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
#
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
#
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
#
|
28 |
-
|
29 |
-
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
@app.route('/')
|
33 |
def index():
|
34 |
return render_template('index.html')
|
@@ -40,70 +145,23 @@ def user_dashboard():
|
|
40 |
@app.route('/get-previous-results', methods=['GET'])
|
41 |
def get_previous_results():
|
42 |
try:
|
43 |
-
#
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
# Returning shared data for all users
|
48 |
-
return jsonify({"status": "success", "data": thingspeak_data})
|
49 |
except Exception as e:
|
50 |
return jsonify({"status": "error", "message": str(e)})
|
51 |
|
52 |
-
# @app.route('/login', methods=['POST'])
|
53 |
-
# def login():
|
54 |
-
# phone = request.form['loginPhone']
|
55 |
-
# password = request.form['loginPassword']
|
56 |
-
|
57 |
-
# # Query Firestore to find user
|
58 |
-
# users_ref = db.collection('users')
|
59 |
-
# query = users_ref.where('phone', '==', phone).where('password', '==', password)
|
60 |
-
|
61 |
-
# try:
|
62 |
-
# users = query.stream()
|
63 |
-
# user_list = list(users)
|
64 |
-
|
65 |
-
# if len(user_list) > 0:
|
66 |
-
# # User found, start session
|
67 |
-
# session['user_phone'] = phone
|
68 |
-
# return redirect(url_for('user_dashboard'))
|
69 |
-
# else:
|
70 |
-
# return "Invalid credentials", 401
|
71 |
-
|
72 |
-
# except Exception as e:
|
73 |
-
# return str(e), 500
|
74 |
-
|
75 |
-
# @app.route('/dashboard')
|
76 |
-
# def user_dashboard():
|
77 |
-
# if 'user_phone' not in session:
|
78 |
-
# return redirect(url_for('index'))
|
79 |
-
|
80 |
-
# # Fetch user details from Firestore
|
81 |
-
# user_ref = db.collection('users').document(session['user_phone'])
|
82 |
-
# user = user_ref.get()
|
83 |
-
|
84 |
-
# if user.exists:
|
85 |
-
# user_data = user.to_dict()
|
86 |
-
# return render_template('user-dashboard.html', user=user_data)
|
87 |
-
# else:
|
88 |
-
# return "User not found", 404
|
89 |
-
|
90 |
-
# @app.route('/admin.html')
|
91 |
-
# def admin():
|
92 |
-
# return render_template('admin.html')
|
93 |
@app.route('/admin.html')
|
94 |
def admin():
|
95 |
-
# Create a map centered on Delhi
|
96 |
delhi_coordinates = [28.6139, 77.2090]
|
97 |
folium_map = folium.Map(location=delhi_coordinates, zoom_start=12)
|
98 |
|
99 |
-
# Add predefined markers in Delhi
|
100 |
markers = [
|
101 |
{"name": "India Gate", "coordinates": [28.6129, 77.2295]},
|
102 |
{"name": "Red Fort", "coordinates": [28.6562, 77.2410]},
|
103 |
{"name": "Qutub Minar", "coordinates": [28.5245, 77.1855]},
|
104 |
]
|
105 |
|
106 |
-
# Add markers to the map
|
107 |
for marker in markers:
|
108 |
folium.Marker(
|
109 |
location=marker["coordinates"],
|
@@ -111,30 +169,37 @@ def admin():
|
|
111 |
icon=folium.Icon(color="blue", icon="info-sign"),
|
112 |
).add_to(folium_map)
|
113 |
|
114 |
-
# Use a valid Folium tile layer
|
115 |
folium.TileLayer('OpenStreetMap').add_to(folium_map)
|
116 |
-
|
117 |
-
# Add Layer Control for toggling between tile layers
|
118 |
folium.LayerControl().add_to(folium_map)
|
119 |
-
|
120 |
-
# Generate the map HTML
|
121 |
map_html = folium_map._repr_html_()
|
122 |
|
123 |
-
# Render the template with the map
|
124 |
return render_template('admin.html', map=map_html)
|
125 |
|
126 |
@app.route('/logout')
|
127 |
def logout():
|
128 |
-
# Remove the user's phone number from the session
|
129 |
session.pop('user_phone', None)
|
130 |
-
|
131 |
-
# Redirect to the index route (function name, not the file name)
|
132 |
return redirect(url_for('index'))
|
133 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
|
|
|
|
|
135 |
|
|
|
|
|
|
|
136 |
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
app.run(host='0.0.0.0', port=7860, debug=True)
|
|
|
1 |
import os
|
2 |
+
import time
|
3 |
+
import requests
|
4 |
import folium
|
5 |
from flask import Flask, render_template, jsonify, request, redirect, url_for, session
|
6 |
+
from twilio.rest import Client
|
7 |
import firebase_admin
|
8 |
from firebase_admin import credentials, firestore
|
9 |
|
10 |
+
# Twilio Configuration
|
11 |
+
ACCOUNT_SID = 'AC175419b901537d8dcca5321386e58aa9'
|
12 |
+
AUTH_TOKEN = 'e5f750f99a87e84ca5b87ddd0c421560'
|
13 |
+
FROM_PHONE = '+13613093564'
|
14 |
+
TO_PHONE = '+919080522395'
|
15 |
+
|
16 |
+
# Firebase Configuration
|
17 |
+
FIREBASE_CREDENTIALS_PATH = r"shh\snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
|
18 |
+
THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
|
19 |
+
CHANNEL_ID = "2784385"
|
20 |
+
|
21 |
+
# Global variable to track the last entry ID
|
22 |
+
last_entry_id = None
|
23 |
+
|
24 |
+
# Initialize Firebase
|
25 |
+
cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
|
26 |
+
firebase_admin.initialize_app(cred)
|
27 |
+
db = firestore.client()
|
28 |
+
|
29 |
# Initialize Flask app
|
30 |
app = Flask(__name__)
|
31 |
app.secret_key = os.urandom(24) # For session management
|
32 |
|
33 |
+
# Function to send SMS using Twilio
|
34 |
+
def send_msg(doc_id, field1):
|
35 |
+
try:
|
36 |
+
field1 = str(field1)
|
37 |
+
# Fetch the document with the given doc_id
|
38 |
+
doc_ref = db.collection('thingspeak_data').document(doc_id)
|
39 |
+
doc = doc_ref.get()
|
40 |
+
|
41 |
+
if doc.exists:
|
42 |
+
data = doc.to_dict()
|
43 |
+
msg_status = data.get('msg_status', 0)
|
44 |
+
|
45 |
+
# Check if the message status is 0
|
46 |
+
if msg_status == 0:
|
47 |
+
client = Client(ACCOUNT_SID, AUTH_TOKEN)
|
48 |
+
|
49 |
+
# Send the message
|
50 |
+
message = client.messages.create(
|
51 |
+
from_=FROM_PHONE,
|
52 |
+
body=f"""E.coli Level: {field1}\nStatus: Safe\nSuggestions:\nYou may heat your water to eradicate the bacteria.""",
|
53 |
+
to=TO_PHONE
|
54 |
+
)
|
55 |
+
|
56 |
+
print(f"Message sent successfully! SID: {message.sid}")
|
57 |
+
|
58 |
+
# Update the msg_status to 1
|
59 |
+
doc_ref.update({'msg_status': 1})
|
60 |
+
print("Message status updated to 1 in Firestore.")
|
61 |
+
else:
|
62 |
+
print("Message already sent for this entry. Skipping...")
|
63 |
+
else:
|
64 |
+
print(f"No document found with ID: {doc_id}")
|
65 |
+
except Exception as e:
|
66 |
+
print(f"Failed to send message or update status: {e}")
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
|
71 |
+
# Firestore Listener for new data
|
72 |
+
def on_snapshot(doc_snapshot, changes, read_time):
|
73 |
+
for change in changes:
|
74 |
+
if change.type.name == 'ADDED':
|
75 |
+
new_data = change.document.to_dict()
|
76 |
+
print(f"New data detected: {new_data}") # Add this for more debugging info
|
77 |
+
field1 = new_data.get('field1', 'N/A')
|
78 |
+
print(f"Field1: {field1}") # Check the type and value of field1
|
79 |
+
send_msg(change.document.id, field1)
|
80 |
+
|
81 |
+
|
82 |
+
# Firestore Listener Initialization
|
83 |
+
def start_firestore_listener():
|
84 |
+
thingspeak_ref = db.collection('thingspeak_data')
|
85 |
+
thingspeak_ref.on_snapshot(on_snapshot)
|
86 |
+
print("Listening for new data in Firestore...")
|
87 |
+
|
88 |
+
# Fetch data from ThingSpeak
|
89 |
+
def fetch_thingspeak_data():
|
90 |
+
global last_entry_id
|
91 |
+
try:
|
92 |
+
url = f"https://api.thingspeak.com/channels/{CHANNEL_ID}/feeds.json?api_key={THINGSPEAK_API_KEY}"
|
93 |
+
response = requests.get(url)
|
94 |
+
response.raise_for_status()
|
95 |
+
data = response.json()
|
96 |
+
|
97 |
+
if not data.get('feeds'):
|
98 |
+
print("No new feeds found.")
|
99 |
+
return None
|
100 |
+
|
101 |
+
latest_feed = data['feeds'][-1]
|
102 |
+
current_entry_id = latest_feed.get('entry_id')
|
103 |
|
104 |
+
if current_entry_id != last_entry_id:
|
105 |
+
last_entry_id = current_entry_id
|
106 |
+
return latest_feed
|
107 |
+
|
108 |
+
print("No new entries since last check.")
|
109 |
+
return None
|
110 |
+
|
111 |
+
except requests.RequestException as e:
|
112 |
+
print(f"ThingSpeak data fetch error: {e}")
|
113 |
+
return None
|
114 |
+
|
115 |
+
# Store data in Firestore
|
116 |
+
def store_data_in_firestore(data):
|
117 |
+
try:
|
118 |
+
if not data:
|
119 |
+
print("No data to store.")
|
120 |
+
return
|
121 |
+
|
122 |
+
doc_data = {
|
123 |
+
'field1': data.get('field1'),
|
124 |
+
'field2': data.get('field2'),
|
125 |
+
'entry_id': data.get('entry_id'),
|
126 |
+
'msg_status':0,
|
127 |
+
|
128 |
+
'timestamp': firestore.SERVER_TIMESTAMP
|
129 |
+
}
|
130 |
+
|
131 |
+
db.collection('thingspeak_data').add(doc_data)
|
132 |
+
print("New data successfully stored in Firestore")
|
133 |
+
except Exception as e:
|
134 |
+
print(f"Firestore storage error: {e}")
|
135 |
+
|
136 |
+
# Flask Routes
|
137 |
@app.route('/')
|
138 |
def index():
|
139 |
return render_template('index.html')
|
|
|
145 |
@app.route('/get-previous-results', methods=['GET'])
|
146 |
def get_previous_results():
|
147 |
try:
|
148 |
+
# Simulate ThingSpeak API call or shared data
|
149 |
+
data = fetch_thingspeak_data()
|
150 |
+
return jsonify({"status": "success", "data": data})
|
|
|
|
|
|
|
151 |
except Exception as e:
|
152 |
return jsonify({"status": "error", "message": str(e)})
|
153 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
@app.route('/admin.html')
|
155 |
def admin():
|
|
|
156 |
delhi_coordinates = [28.6139, 77.2090]
|
157 |
folium_map = folium.Map(location=delhi_coordinates, zoom_start=12)
|
158 |
|
|
|
159 |
markers = [
|
160 |
{"name": "India Gate", "coordinates": [28.6129, 77.2295]},
|
161 |
{"name": "Red Fort", "coordinates": [28.6562, 77.2410]},
|
162 |
{"name": "Qutub Minar", "coordinates": [28.5245, 77.1855]},
|
163 |
]
|
164 |
|
|
|
165 |
for marker in markers:
|
166 |
folium.Marker(
|
167 |
location=marker["coordinates"],
|
|
|
169 |
icon=folium.Icon(color="blue", icon="info-sign"),
|
170 |
).add_to(folium_map)
|
171 |
|
|
|
172 |
folium.TileLayer('OpenStreetMap').add_to(folium_map)
|
|
|
|
|
173 |
folium.LayerControl().add_to(folium_map)
|
|
|
|
|
174 |
map_html = folium_map._repr_html_()
|
175 |
|
|
|
176 |
return render_template('admin.html', map=map_html)
|
177 |
|
178 |
@app.route('/logout')
|
179 |
def logout():
|
|
|
180 |
session.pop('user_phone', None)
|
|
|
|
|
181 |
return redirect(url_for('index'))
|
182 |
|
183 |
+
# Main Function for Continuous Data Fetching
|
184 |
+
def main():
|
185 |
+
try:
|
186 |
+
start_firestore_listener()
|
187 |
+
while True:
|
188 |
+
thingspeak_data = fetch_thingspeak_data()
|
189 |
+
if thingspeak_data:
|
190 |
+
store_data_in_firestore(thingspeak_data)
|
191 |
+
time.sleep(5)
|
192 |
+
except KeyboardInterrupt:
|
193 |
+
print("Process interrupted by user.")
|
194 |
+
except Exception as e:
|
195 |
+
print(f"Unexpected error: {e}")
|
196 |
|
197 |
+
if __name__ == '__main__':
|
198 |
+
from threading import Thread
|
199 |
|
200 |
+
# Start Flask app in a separate thread
|
201 |
+
flask_thread = Thread(target=app.run, kwargs={'host': '0.0.0.0', 'port': 7860, 'debug': True})
|
202 |
+
flask_thread.start()
|
203 |
|
204 |
+
# Start main data-fetching loop
|
205 |
+
main()
|
|
|
|