File size: 6,232 Bytes
5bda095
09a71ce
 
e18c564
e33f692
09a71ce
 
 
e33f692
 
5bda095
79c9006
5bda095
 
e33f692
09a71ce
e1e82a5
 
97e0f48
35b9301
e33f692
35b9301
79c9006
59cbdd5
 
 
 
 
 
e33f692
 
 
59cbdd5
e33f692
 
 
 
 
 
 
 
 
 
 
 
59cbdd5
e33f692
59cbdd5
 
 
 
e33f692
59cbdd5
 
 
 
 
 
 
 
e33f692
59cbdd5
e33f692
 
 
 
 
59cbdd5
e33f692
 
97e0f48
59cbdd5
e33f692
59cbdd5
 
e33f692
 
 
 
 
 
59cbdd5
97e0f48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8226f54
 
 
 
 
97e0f48
8226f54
 
 
97e0f48
8226f54
 
 
 
97e0f48
8226f54
 
97e0f48
8226f54
 
97e0f48
8226f54
 
 
97e0f48
8226f54
 
97e0f48
8226f54
 
 
 
97e0f48
8226f54
 
 
 
 
 
97e0f48
8226f54
 
 
 
 
 
 
97e0f48
8226f54
97e0f48
8226f54
 
 
 
 
97e0f48
8226f54
97e0f48
 
580ad3a
97e0f48
 
 
 
 
 
 
 
 
 
 
 
8226f54
97e0f48
 
 
 
d1163ac
79c9006
d1163ac
e33f692
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
import os
import time
import requests
import pickle
import numpy as np
from flask import Flask, render_template, redirect, url_for, session
import firebase_admin
from firebase_admin import credentials, firestore
from twilio.rest import Client

# Initialize Flask app
app = Flask(__name__)
app.secret_key = os.urandom(24)  # For session management

# Firebase Admin SDK initialization
FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
cred = credentials.Certificate("snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json")

firebase_admin.initialize_app(cred)

# Firestore client
db = firestore.client()

# Twilio Configuration
ACCOUNT_SID = 'AC97ad50edcf94fdd7d4576be9651bf4bf'
AUTH_TOKEN = '6d8b2559ffbbdbc5d06542e545220aaa'
FROM_PHONE = '+12708175529'
TO_PHONE = '+916382792828'

# Load model using pickle
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

def send_msg(field1, suggestion):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    try:
        message = client.messages.create(
            from_=FROM_PHONE,
            body=f"""Test Results:\nE.coli Level: {field1} CFU/mL.\nStatus: {'safe' if field1 == 0 else 'unsafe'}\nSuggestions:\n{suggestion}""",
            to=TO_PHONE
        )
        print(f"Message sent successfully! SID: {message.sid}")
    except Exception as e:
        print(f"Failed to send message: {e}")

def on_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 data detected: {new_data}")
            concentration = predict_conc(float(field1))
            if concentration == "0":
                send_msg(0, "The water is safe for use!!")
            else:
                send_msg(concentration, "You may boil the water to 50\u00b0C to eradicate the bacteria.")

def start_firestore_listener():
    try:
        thingspeak_ref = db.collection('thingspeak_data')
        thingspeak_ref.on_snapshot(on_snapshot)
        print("Firestore listener started.")
    except Exception as e:
        print(f"Error starting Firestore listener: {e}")

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/logout')
def logout():
    session.pop('user_phone', None)
    return redirect(url_for('index'))



import requests
import firebase_admin
from firebase_admin import credentials, firestore
import time

# Replace with your actual credentials
THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
CHANNEL_ID = "2784385"
FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"

# Global variable to track the last entry ID
last_entry_id = None

def initialize_firebase():
    """Initialize Firebase connection"""
    try:
        # Initialize Firebase app (only once)
        cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
        firebase_admin.initialize_app(cred)
        
        # Create Firestore client
        return firestore.client()
    except Exception as e:
        print(f"Firebase initialization error: {e}")
        return None

def fetch_thingspeak_data():
    """Fetch data from ThingSpeak"""
    global last_entry_id
    try:
        url = f"https://api.thingspeak.com/channels/2784385/feeds.json?api_key=P54KXM40TA3CB6W4"
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for bad responses
        data = response.json()
        
        # Check if there are feeds
        if not data.get('feeds'):
            print("No new feeds found.")
            return None
        
        # Get the latest feed
        latest_feed = data['feeds'][-1]
        
        # Check if this is a new entry
        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

def store_data_in_firestore(firestore_client, data):
    """Store data in Firestore"""
    try:
        # Validate data
        if not data:
            print("No data to store.")
            return
        
        # Create a document with timestamp
        doc_data = {
            'field1': data.get('field1'),
            'field2': data.get('field2'),
            'entry_id': data.get('entry_id'),
            'timestamp': firestore.SERVER_TIMESTAMP
        }
        
        # Add to Firestore collection
        firestore_client.collection('thingspeak_data').add(doc_data)
        print("New data successfully stored in Firestore")
    except Exception as e:
        print(f"Firestore storage error: {e}")


firestore_client = initialize_firebase()

if not firestore_client:
    print("Failed to initialize Firestore. Exiting.")
    
# Main data collection loop
try:
    while True:
        # Fetch data from ThingSpeak
        thingspeak_data = fetch_thingspeak_data()
        
        if thingspeak_data:
            # Store data in Firestore only if there's a new entry
            store_data_in_firestore(firestore_client, thingspeak_data)
        
        # Wait before next iteration
        time.sleep(5)  # Adjust interval as needed

except KeyboardInterrupt:
    print("Data collection stopped by user.")
except Exception as e:
    print(f"Unexpected error: {e}")
start_firestore_listener()
if __name__ == '__main__':
    
    app.run(host='0.0.0.0', port=7860, debug=True)