Neurolingua commited on
Commit
4f0ef76
·
verified ·
1 Parent(s): ef44cec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -95
app.py CHANGED
@@ -1,109 +1,132 @@
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
- # Initialize Firebase
12
- # try:
13
- # firebase_admin.get_app()
14
- # except ValueError:
15
- # cred = credentials.Certificate({
16
- # "type": "service_account",
17
- # "project_id": "snippetscript-37175",
18
- # "private_key_id": "your_private_key_id",
19
- # "private_key": "your_private_key",
20
- # "client_email": "your_client_email",
21
- # "client_id": "your_client_id",
22
- # "auth_uri": "https://accounts.google.com/o/oauth2/auth",
23
- # "token_uri": "https://oauth2.googleapis.com/token",
24
- # "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
25
- # "client_x509_cert_url": "your_cert_url"
26
- # })
27
- # firebase_admin.initialize_app(cred)
28
-
29
- # Initialize Firestore
30
- # db = firestore.client()
31
 
32
- @app.route('/')
33
- def index():
34
- return render_template('index.html')
 
 
 
 
 
 
 
 
35
 
36
- @app.route('/user-dashboard.html')
37
- def user_dashboard():
38
- return render_template('user-dashboard.html')
 
39
 
40
- @app.route('/get-previous-results', methods=['GET'])
41
- def get_previous_results():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  try:
43
- # Simulating a ThingSpeak API call or shared data
44
- # response = requests.get("https://api.thingspeak.com/...", params=...)
45
- # thingspeak_data = response.json()
 
 
 
 
 
 
 
 
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,27 +134,22 @@ 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
  if __name__ == '__main__':
137
- app.run(host='0.0.0.0', port=7860, debug=True)
 
 
 
 
 
 
1
  import os
2
+ import time
3
+ import threading
4
+ import requests
5
  import folium
6
+ from flask import Flask, render_template, jsonify, redirect, url_for, session
7
  import firebase_admin
8
  from firebase_admin import credentials, firestore
9
+ from twilio.rest import Client
10
 
11
+ # Flask app initialization
12
  app = Flask(__name__)
13
+ app.secret_key = os.urandom(24)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ # Firebase and Firestore Initialization
16
+ FIREBASE_CREDENTIALS_PATH = "snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
17
+ cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
18
+ firebase_admin.initialize_app(cred)
19
+ db = firestore.client()
20
+
21
+ # Twilio Configuration
22
+ ACCOUNT_SID = 'AC97ad50edcf94fdd7d4576be9651bf4bf'
23
+ AUTH_TOKEN = '6d8b2559ffbbdbc5d06542e545220aaa'
24
+ FROM_PHONE = '+12708175529'
25
+ TO_PHONE = '+916382792828'
26
 
27
+ # ThingSpeak Configuration
28
+ THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
29
+ CHANNEL_ID = "2784385"
30
+ last_entry_id = None
31
 
32
+
33
+ # Function to fetch data from ThingSpeak
34
+ def fetch_thingspeak_data():
35
+ global last_entry_id
36
+ try:
37
+ url = f"https://api.thingspeak.com/channels/{CHANNEL_ID}/feeds.json?api_key={THINGSPEAK_API_KEY}"
38
+ response = requests.get(url)
39
+ response.raise_for_status()
40
+ data = response.json()
41
+
42
+ # Check for new data
43
+ if data.get('feeds'):
44
+ latest_feed = data['feeds'][-1]
45
+ current_entry_id = latest_feed.get('entry_id')
46
+
47
+ if current_entry_id != last_entry_id:
48
+ last_entry_id = current_entry_id
49
+ return latest_feed
50
+ return None
51
+ except requests.RequestException as e:
52
+ print(f"Error fetching ThingSpeak data: {e}")
53
+ return None
54
+
55
+
56
+ # Function to store data in Firestore
57
+ def store_data_in_firestore(data):
58
  try:
59
+ if data:
60
+ doc_data = {
61
+ 'field1': data.get('field1'),
62
+ 'field2': data.get('field2'),
63
+ 'entry_id': data.get('entry_id'),
64
+ 'timestamp': firestore.SERVER_TIMESTAMP
65
+ }
66
+ db.collection('thingspeak_data').add(doc_data)
67
+ print("New data successfully stored in Firestore")
68
+ except Exception as e:
69
+ print(f"Error storing data in Firestore: {e}")
70
 
71
+
72
+ # Twilio SMS Sending Function
73
+ def send_sms(field1):
74
+ client = Client(ACCOUNT_SID, AUTH_TOKEN)
75
+ try:
76
+ message = client.messages.create(
77
+ from_=FROM_PHONE,
78
+ body=f"""E.coli Level: {field1}
79
+ Status: safe
80
+ Suggestions:
81
+ You may heat your water to eradicate the bacteria.""",
82
+ to=TO_PHONE
83
+ )
84
+ print(f"Message sent successfully! SID: {message.sid}")
85
  except Exception as e:
86
+ print(f"Failed to send message: {e}")
87
+
88
+
89
+ # Firestore Listener
90
+ def start_firestore_listener():
91
+ def on_snapshot(doc_snapshot, changes, read_time):
92
+ for change in changes:
93
+ if change.type.name == 'ADDED':
94
+ new_data = change.document.to_dict()
95
+ field1 = new_data.get('field1', 'N/A')
96
+ print(f"New Firestore data: {new_data}")
97
+ send_sms(field1)
98
+
99
+ thingspeak_ref = db.collection('thingspeak_data')
100
+ thingspeak_ref.on_snapshot(on_snapshot)
101
+ print("Listening for Firestore changes...")
102
+
103
+
104
+ # Background Task for Fetching ThingSpeak Data
105
+ def background_thingspeak_to_firestore():
106
+ while True:
107
+ thingspeak_data = fetch_thingspeak_data()
108
+ if thingspeak_data:
109
+ store_data_in_firestore(thingspeak_data)
110
+ time.sleep(10) # Adjust interval as needed
111
+
112
+
113
+ # Flask Routes
114
+ @app.route('/')
115
+ def index():
116
+ return render_template('index.html')
117
+
118
+
 
 
 
 
 
 
 
 
 
 
119
  @app.route('/admin.html')
120
  def admin():
 
121
  delhi_coordinates = [28.6139, 77.2090]
122
  folium_map = folium.Map(location=delhi_coordinates, zoom_start=12)
123
 
 
124
  markers = [
125
  {"name": "India Gate", "coordinates": [28.6129, 77.2295]},
126
  {"name": "Red Fort", "coordinates": [28.6562, 77.2410]},
127
  {"name": "Qutub Minar", "coordinates": [28.5245, 77.1855]},
128
  ]
129
 
 
130
  for marker in markers:
131
  folium.Marker(
132
  location=marker["coordinates"],
 
134
  icon=folium.Icon(color="blue", icon="info-sign"),
135
  ).add_to(folium_map)
136
 
 
137
  folium.TileLayer('OpenStreetMap').add_to(folium_map)
 
 
138
  folium.LayerControl().add_to(folium_map)
 
 
139
  map_html = folium_map._repr_html_()
 
 
140
  return render_template('admin.html', map=map_html)
141
 
142
+
143
  @app.route('/logout')
144
  def logout():
 
145
  session.pop('user_phone', None)
 
 
146
  return redirect(url_for('index'))
147
 
148
 
 
149
  if __name__ == '__main__':
150
+ # Start background threads
151
+ threading.Thread(target=background_thingspeak_to_firestore, daemon=True).start()
152
+ threading.Thread(target=start_firestore_listener, daemon=True).start()
153
+
154
+ # Run the Flask app
155
+ app.run(host='0.0.0.0', port=7860, debug=True)