Spaces:
Sleeping
Sleeping
File size: 7,304 Bytes
5bda095 95b65a4 ef44cec 4c5bc9a 95b65a4 09a71ce e16d77a 09a71ce e33f692 95b65a4 96a710d 95b65a4 96a710d 95b65a4 4c5bc9a bd088af 4c5bc9a 95b65a4 96a710d 95b65a4 96a710d 95b65a4 96a710d 95b65a4 ef44cec 95b65a4 4f0ef76 4c5bc9a 4f0ef76 4c5bc9a 95b65a4 4c5bc9a ef44cec 2feef86 ef44cec 2feef86 ef44cec 2feef86 ef44cec 2feef86 4c5bc9a 4f0ef76 ef44cec 2feef86 95b65a4 2feef86 95b65a4 4c5bc9a 2ca70b1 b731f58 |
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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 |
import os
import time
import requests
import folium
from flask import Flask, render_template, jsonify, request, redirect, url_for, session
from twilio.rest import Client
import firebase_admin
import pickle
from firebase_admin import credentials, firestore
# Twilio Configuration
ACCOUNT_SID = 'AC175419b901537d8dcca5321386e58aa9'
AUTH_TOKEN = 'e5f750f99a87e84ca5b87ddd0c421560'
FROM_PHONE = '+13613093564'
TO_PHONE = '+919080522395'
# Firebase Configuration
FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
CHANNEL_ID = "2784385"
# Global variable to track the last entry ID
last_entry_id = None
with open('model.pkl', 'rb') as f:
loaded_model = pickle.load(f)
def predict_conc(pdiff):
try:
if pdiff > 3.19:
return 0
pdiff_value = pdiff # Input for "Average Potential Difference"
new_data = np.array([[pdiff_value]])
prediction = loaded_model.predict(new_data)
concentration = 10**prediction[0] # Reverse log transformation
return f"{concentration:.4f}"
except Exception as e:
print(f"Error in predict_conc: {e}")
return None
# Initialize Firebase
cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
firebase_admin.initialize_app(cred)
db = firestore.client()
# Initialize Flask app
app = Flask(__name__)
app.secret_key = os.urandom(24) # For session management
# Function to send SMS using Twilio
def send_msg(doc_id, field1):
try:
field1 = str(field1)
# Fetch the document with the given doc_id
doc_ref = db.collection('thingspeak_data').document(doc_id)
doc = doc_ref.get()
if doc.exists:
data = doc.to_dict()
msg_status = data.get('msg_status', 0)
# Check if the message status is 0
if msg_status == 0:
concen=predict_conc(int(field1))
client = Client(ACCOUNT_SID, AUTH_TOKEN)
if concen!=0:
sugges="You may heat your water to eradicate the bacteria."
else:
sugges="Your water is safe.It can be used for drinking purpose!."
# Send the message
message = client.messages.create(
from_=FROM_PHONE,
body=f"""E.coli Level: {concen} CFU/mL\nStatus: Safe\nSuggestions:\n{sugges}\n--Ministry of Jal Shakthi.""",
to=TO_PHONE
)
print(f"Message sent successfully! SID: {message.sid}")
# Update the msg_status to 1
doc_ref.update({'msg_status': 1})
print("Message status updated to 1 in Firestore.")
else:
print("Message already sent for this entry. Skipping...")
else:
print(f"No document found with ID: {doc_id}")
except Exception as e:
print(f"Failed to send message or update status: {e}")
# Firestore Listener for new data
def on_snapshot(doc_snapshot, changes, read_time):
for change in changes:
if change.type.name == 'ADDED':
new_data = change.document.to_dict()
print(f"New data detected: {new_data}") # Add this for more debugging info
field1 = new_data.get('field1', 'N/A')
print(f"Field1: {field1}") # Check the type and value of field1
send_msg(change.document.id, field1)
# Firestore Listener Initialization
def start_firestore_listener():
thingspeak_ref = db.collection('thingspeak_data')
thingspeak_ref.on_snapshot(on_snapshot)
print("Listening for new data in Firestore...")
# Fetch data from ThingSpeak
def fetch_thingspeak_data():
global last_entry_id
try:
url = f"https://api.thingspeak.com/channels/{CHANNEL_ID}/feeds.json?api_key={THINGSPEAK_API_KEY}"
response = requests.get(url)
response.raise_for_status()
data = response.json()
if not data.get('feeds'):
print("No new feeds found.")
return None
latest_feed = data['feeds'][-1]
current_entry_id = latest_feed.get('entry_id')
if current_entry_id != last_entry_id:
last_entry_id = current_entry_id
return latest_feed
print("No new entries since last check.")
return None
except requests.RequestException as e:
print(f"ThingSpeak data fetch error: {e}")
return None
# Store data in Firestore
def store_data_in_firestore(data):
try:
if not data:
print("No data to store.")
return
doc_data = {
'field1': data.get('field1'),
'field2': data.get('field2'),
'entry_id': data.get('entry_id'),
'msg_status':0,
'timestamp': firestore.SERVER_TIMESTAMP
}
db.collection('thingspeak_data').add(doc_data)
print("New data successfully stored in Firestore")
except Exception as e:
print(f"Firestore storage error: {e}")
# Flask Routes
@app.route('/')
def index():
return render_template('index.html')
@app.route('/user-dashboard.html')
def user_dashboard():
return render_template('user-dashboard.html')
@app.route('/get-previous-results', methods=['GET'])
def get_previous_results():
try:
# Simulate ThingSpeak API call or shared data
data = fetch_thingspeak_data()
return jsonify({"status": "success", "data": data})
except Exception as e:
return jsonify({"status": "error", "message": str(e)})
@app.route('/admin.html')
def admin():
delhi_coordinates = [28.6139, 77.2090]
folium_map = folium.Map(location=delhi_coordinates, zoom_start=12)
markers = [
{"name": "India Gate", "coordinates": [28.6129, 77.2295]},
{"name": "Red Fort", "coordinates": [28.6562, 77.2410]},
{"name": "Qutub Minar", "coordinates": [28.5245, 77.1855]},
]
for marker in markers:
folium.Marker(
location=marker["coordinates"],
popup=marker["name"],
icon=folium.Icon(color="blue", icon="info-sign"),
).add_to(folium_map)
folium.TileLayer('OpenStreetMap').add_to(folium_map)
folium.LayerControl().add_to(folium_map)
map_html = folium_map._repr_html_()
return render_template('admin.html', map=map_html)
@app.route('/logout')
def logout():
session.pop('user_phone', None)
return redirect(url_for('index'))
# Main Function for Continuous Data Fetching
def main():
try:
start_firestore_listener()
while True:
thingspeak_data = fetch_thingspeak_data()
if thingspeak_data:
store_data_in_firestore(thingspeak_data)
time.sleep(5)
except KeyboardInterrupt:
print("Process interrupted by user.")
except Exception as e:
print(f"Unexpected error: {e}")
if __name__ == '__main__':
from threading import Thread
# Run the main data-fetching loop in a separate thread
data_thread = Thread(target=main, daemon=True)
data_thread.start()
# Run Flask app in the main thread with debugging enabled
app.run(host='0.0.0.0', port=7860, debug=True)
|