File size: 5,602 Bytes
5bda095
09a71ce
 
e18c564
e33f692
09a71ce
 
 
e33f692
 
5bda095
79c9006
5bda095
 
e33f692
09a71ce
 
 
 
35b9301
e33f692
35b9301
79c9006
59cbdd5
 
 
 
 
 
e33f692
 
 
59cbdd5
09a71ce
 
 
 
 
 
 
 
e33f692
 
 
 
 
 
 
 
 
 
 
 
59cbdd5
09a71ce
e33f692
59cbdd5
 
 
 
e33f692
59cbdd5
 
 
 
 
 
09a71ce
59cbdd5
 
e33f692
59cbdd5
e33f692
 
 
 
 
59cbdd5
e33f692
 
09a71ce
59cbdd5
e33f692
59cbdd5
09a71ce
59cbdd5
e33f692
 
 
 
 
 
59cbdd5
8226f54
 
 
 
 
09a71ce
8226f54
 
 
09a71ce
8226f54
 
 
 
09a71ce
8226f54
 
09a71ce
8226f54
 
09a71ce
8226f54
 
 
09a71ce
8226f54
 
09a71ce
8226f54
 
 
 
09a71ce
 
8226f54
 
 
 
 
 
09a71ce
8226f54
 
 
 
 
 
 
09a71ce
8226f54
09a71ce
8226f54
 
 
 
 
09a71ce
 
 
8226f54
 
09a71ce
 
 
 
8226f54
 
79c9006
09a71ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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"
if not firebase_admin._apps:
    cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
    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)

# ThingSpeak Configuration
THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
CHANNEL_ID = "2784385"

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


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}")


def fetch_thingspeak_data():
    """Fetch data from ThingSpeak"""
    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()  # 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(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
        db.collection('thingspeak_data').add(doc_data)
        print("New data successfully stored in Firestore")
    except Exception as e:
        print(f"Firestore storage error: {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'))


if __name__ == '__main__':
    # Start the Firestore listener in a separate thread
    import threading
    listener_thread = threading.Thread(target=start_firestore_listener)
    listener_thread.start()

    # 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(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}")

    # Run Flask app
    app.run(host='0.0.0.0', port=7860, debug=True)