Spaces:
Sleeping
Sleeping
import os | |
import time | |
import requests | |
import firebase_admin | |
from firebase_admin import credentials, firestore | |
from flask import Flask, render_template | |
from twilio.rest import Client | |
# Flask App Initialization | |
app = Flask(__name__) | |
# Firebase Configuration | |
FIREBASE_CREDENTIALS_PATH = "snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json" | |
THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4" | |
CHANNEL_ID = "2784385" | |
# Twilio Configuration | |
ACCOUNT_SID = "AC97ad50edcf94fdd7d4576be9651bf4bf" | |
AUTH_TOKEN = "6d8b2559ffbbdbc5d06542e545220aaa" | |
FROM_PHONE = "+12708175529" | |
TO_PHONE = "+916382792828" | |
# Global Variable | |
last_entry_id = None | |
# Firebase Initialization | |
cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH) | |
firebase_admin.initialize_app(cred) | |
db = firestore.client() | |
# Function to 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 | |
# Function to 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"), | |
"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}") | |
# Function to Send SMS via Twilio | |
def send_sms(field1, suggestion): | |
client = Client(ACCOUNT_SID, AUTH_TOKEN) | |
try: | |
message = client.messages.create( | |
from_=FROM_PHONE, | |
body=f"""Test Results: | |
E.coli Level: {field1} CFU/mL | |
Status: {"Safe" if float(field1) <= 0 else "Unsafe"} | |
Suggestions: {suggestion}""", | |
to=TO_PHONE, | |
) | |
print(f"Message sent successfully! SID: {message.sid}") | |
except Exception as e: | |
print(f"Twilio message send error: {e}") | |
# Firestore Listener | |
def on_firestore_snapshot(doc_snapshot, changes, read_time): | |
for change in changes: | |
if change.type.name == "ADDED": | |
new_data = change.document.to_dict() | |
field1 = new_data.get("field1") | |
if field1 is None: | |
print("field1 is missing in the document.") | |
continue | |
print(f"New Firestore Data: {new_data}") | |
# Logic for sending SMS based on field1 value | |
if float(field1) <= 0: | |
send_sms(field1, "The water is safe for use.") | |
else: | |
send_sms( | |
field1, | |
"You may boil the water to 50°C to eradicate bacteria.", | |
) | |
# Start Firestore Listener | |
def start_firestore_listener(): | |
thingspeak_ref = db.collection("thingspeak_data") | |
thingspeak_ref.on_snapshot(on_firestore_snapshot) | |
def index(): | |
return render_template("index.html") | |
def admin(): | |
return render_template("admin.html") | |
# Background Loop for ThingSpeak Data Fetch | |
def fetch_and_store_thingspeak_data(): | |
global last_entry_id | |
while True: | |
thingspeak_data = fetch_thingspeak_data() | |
if thingspeak_data: | |
store_data_in_firestore(thingspeak_data) | |
time.sleep(5) # Fetch data every 5 seconds | |
if __name__ == "__main__": | |
# Start Firestore Listener in a Background Thread | |
start_firestore_listener() | |
# Start Flask App | |
app.run(host="0.0.0.0", port=7860, debug=True) | |