Spaces:
Sleeping
Sleeping
File size: 4,235 Bytes
5bda095 bd088af 09a71ce bd088af e33f692 bd088af 97e0f48 bd088af 97e0f48 bd088af 97e0f48 bd088af 8226f54 bd088af 8226f54 bd088af 8226f54 bd088af 8226f54 bd088af 8226f54 bd088af 8226f54 bd088af 8226f54 2feef86 bd088af 8226f54 bd088af 8226f54 bd088af 8226f54 bd088af 8226f54 bd088af 2feef86 bd088af 2feef86 bd088af 2feef86 bd088af 2feef86 bd088af 2feef86 bd088af 2feef86 bd088af 2feef86 bd088af 2feef86 bd088af |
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 |
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)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/admin")
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)
|