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 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 # Start Flask app in a separate thread flask_thread = Thread(target=app.run, kwargs={'host': '0.0.0.0', 'port': 7860, 'debug': True}) flask_thread.start() # Start main data-fetching loop main()