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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -129
app.py CHANGED
@@ -1,150 +1,137 @@
1
  import os
2
- import time
3
- import requests
4
  import firebase_admin
5
  from firebase_admin import credentials, firestore
6
- from flask import Flask, render_template
7
- from twilio.rest import Client
8
 
9
- # Flask App Initialization
10
  app = Flask(__name__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- # Firebase Configuration
13
- FIREBASE_CREDENTIALS_PATH = "snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
14
- THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
15
- CHANNEL_ID = "2784385"
16
-
17
- # Twilio Configuration
18
- ACCOUNT_SID = "AC97ad50edcf94fdd7d4576be9651bf4bf"
19
- AUTH_TOKEN = "6d8b2559ffbbdbc5d06542e545220aaa"
20
- FROM_PHONE = "+12708175529"
21
- TO_PHONE = "+916382792828"
22
-
23
- # Global Variable
24
- last_entry_id = None
25
-
26
- # Firebase Initialization
27
- cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
28
- firebase_admin.initialize_app(cred)
29
- db = firestore.client()
30
-
31
 
32
- # Function to Fetch Data from ThingSpeak
33
- def fetch_thingspeak_data():
34
- global last_entry_id
35
  try:
36
- url = f"https://api.thingspeak.com/channels/{CHANNEL_ID}/feeds.json?api_key={THINGSPEAK_API_KEY}"
37
- response = requests.get(url)
38
- response.raise_for_status()
39
- data = response.json()
40
-
41
- if not data.get("feeds"):
42
- print("No new feeds found.")
43
- return None
44
 
45
- latest_feed = data["feeds"][-1]
46
- current_entry_id = latest_feed.get("entry_id")
47
-
48
- if current_entry_id != last_entry_id:
49
- last_entry_id = current_entry_id
50
- return latest_feed
51
-
52
- print("No new entries since last check.")
53
- return None
54
- except requests.RequestException as e:
55
- print(f"ThingSpeak data fetch error: {e}")
56
- return None
57
-
58
-
59
- # Function to Store Data in Firestore
60
- def store_data_in_firestore(data):
61
- try:
62
- if not data:
63
- print("No data to store.")
64
- return
65
-
66
- doc_data = {
67
- "field1": data.get("field1"),
68
- "field2": data.get("field2"),
69
- "entry_id": data.get("entry_id"),
70
- "timestamp": firestore.SERVER_TIMESTAMP,
71
- }
72
-
73
- db.collection("thingspeak_data").add(doc_data)
74
- print("New data successfully stored in Firestore")
75
  except Exception as e:
76
- print(f"Firestore storage error: {e}")
77
-
78
-
79
- # Function to Send SMS via Twilio
80
- def send_sms(field1, suggestion):
81
- client = Client(ACCOUNT_SID, AUTH_TOKEN)
82
- try:
83
- message = client.messages.create(
84
- from_=FROM_PHONE,
85
- body=f"""Test Results:
86
- E.coli Level: {field1} CFU/mL
87
- Status: {"Safe" if float(field1) <= 0 else "Unsafe"}
88
- Suggestions: {suggestion}""",
89
- to=TO_PHONE,
90
- )
91
- print(f"Message sent successfully! SID: {message.sid}")
92
- except Exception as e:
93
- print(f"Twilio message send error: {e}")
94
-
95
-
96
- # Firestore Listener
97
- def on_firestore_snapshot(doc_snapshot, changes, read_time):
98
- for change in changes:
99
- if change.type.name == "ADDED":
100
- new_data = change.document.to_dict()
101
- field1 = new_data.get("field1")
102
- if field1 is None:
103
- print("field1 is missing in the document.")
104
- continue
105
-
106
- print(f"New Firestore Data: {new_data}")
107
-
108
- # Logic for sending SMS based on field1 value
109
- if float(field1) <= 0:
110
- send_sms(field1, "The water is safe for use.")
111
- else:
112
- send_sms(
113
- field1,
114
- "You may boil the water to 50°C to eradicate bacteria.",
115
- )
 
 
 
 
 
 
 
 
116
 
 
 
 
 
 
 
117
 
118
- # Start Firestore Listener
119
- def start_firestore_listener():
120
- thingspeak_ref = db.collection("thingspeak_data")
121
- thingspeak_ref.on_snapshot(on_firestore_snapshot)
 
 
 
122
 
 
 
123
 
124
- @app.route("/")
125
- def index():
126
- return render_template("index.html")
127
 
 
 
128
 
129
- @app.route("/admin")
130
- def admin():
131
- return render_template("admin.html")
132
-
133
 
134
- # Background Loop for ThingSpeak Data Fetch
135
- def fetch_and_store_thingspeak_data():
136
- global last_entry_id
 
137
 
138
- while True:
139
- thingspeak_data = fetch_thingspeak_data()
140
- if thingspeak_data:
141
- store_data_in_firestore(thingspeak_data)
142
- time.sleep(5) # Fetch data every 5 seconds
143
 
144
 
145
- if __name__ == "__main__":
146
- # Start Firestore Listener in a Background Thread
147
- start_firestore_listener()
148
 
149
- # Start Flask App
150
- app.run(host="0.0.0.0", port=7860, debug=True)
 
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"],
110
+ popup=marker["name"],
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)