Spaces:
Sleeping
Sleeping
Update thingspeak_to_firebase.py
Browse files- thingspeak_to_firebase.py +106 -106
thingspeak_to_firebase.py
CHANGED
@@ -1,107 +1,107 @@
|
|
1 |
-
import requests
|
2 |
-
import firebase_admin
|
3 |
-
from firebase_admin import credentials, firestore
|
4 |
-
import time
|
5 |
-
|
6 |
-
# Replace with your actual credentials
|
7 |
-
THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
|
8 |
-
CHANNEL_ID = "2784385"
|
9 |
-
FIREBASE_CREDENTIALS_PATH = r"
|
10 |
-
|
11 |
-
# Global variable to track the last entry ID
|
12 |
-
last_entry_id = None
|
13 |
-
|
14 |
-
def initialize_firebase():
|
15 |
-
"""Initialize Firebase connection"""
|
16 |
-
try:
|
17 |
-
# Initialize Firebase app (only once)
|
18 |
-
cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
|
19 |
-
firebase_admin.initialize_app(cred)
|
20 |
-
|
21 |
-
# Create Firestore client
|
22 |
-
return firestore.client()
|
23 |
-
except Exception as e:
|
24 |
-
print(f"Firebase initialization error: {e}")
|
25 |
-
return None
|
26 |
-
|
27 |
-
def fetch_thingspeak_data():
|
28 |
-
"""Fetch data from ThingSpeak"""
|
29 |
-
global last_entry_id
|
30 |
-
try:
|
31 |
-
url = f"https://api.thingspeak.com/channels/2784385/feeds.json?api_key=P54KXM40TA3CB6W4"
|
32 |
-
response = requests.get(url)
|
33 |
-
response.raise_for_status() # Raise an exception for bad responses
|
34 |
-
data = response.json()
|
35 |
-
|
36 |
-
# Check if there are feeds
|
37 |
-
if not data.get('feeds'):
|
38 |
-
print("No new feeds found.")
|
39 |
-
return None
|
40 |
-
|
41 |
-
# Get the latest feed
|
42 |
-
latest_feed = data['feeds'][-1]
|
43 |
-
|
44 |
-
# Check if this is a new entry
|
45 |
-
current_entry_id = latest_feed.get('entry_id')
|
46 |
-
|
47 |
-
if current_entry_id != last_entry_id:
|
48 |
-
last_entry_id = current_entry_id
|
49 |
-
return latest_feed
|
50 |
-
|
51 |
-
print("No new entries since last check.")
|
52 |
-
return None
|
53 |
-
|
54 |
-
except requests.RequestException as e:
|
55 |
-
print(f"ThingSpeak data fetch error: {e}")
|
56 |
-
return None
|
57 |
-
|
58 |
-
def store_data_in_firestore(firestore_client, data):
|
59 |
-
"""Store data in Firestore"""
|
60 |
-
try:
|
61 |
-
# Validate data
|
62 |
-
if not data:
|
63 |
-
print("No data to store.")
|
64 |
-
return
|
65 |
-
|
66 |
-
# Create a document with timestamp
|
67 |
-
doc_data = {
|
68 |
-
'field1': data.get('field1'),
|
69 |
-
'field2': data.get('field2'),
|
70 |
-
'entry_id': data.get('entry_id'),
|
71 |
-
'timestamp': firestore.SERVER_TIMESTAMP
|
72 |
-
}
|
73 |
-
|
74 |
-
# Add to Firestore collection
|
75 |
-
firestore_client.collection('thingspeak_data').add(doc_data)
|
76 |
-
print("New data successfully stored in Firestore")
|
77 |
-
except Exception as e:
|
78 |
-
print(f"Firestore storage error: {e}")
|
79 |
-
|
80 |
-
def main():
|
81 |
-
# Initialize Firebase
|
82 |
-
firestore_client = initialize_firebase()
|
83 |
-
|
84 |
-
if not firestore_client:
|
85 |
-
print("Failed to initialize Firestore. Exiting.")
|
86 |
-
return
|
87 |
-
|
88 |
-
# Main data collection loop
|
89 |
-
try:
|
90 |
-
while True:
|
91 |
-
# Fetch data from ThingSpeak
|
92 |
-
thingspeak_data = fetch_thingspeak_data()
|
93 |
-
|
94 |
-
if thingspeak_data:
|
95 |
-
# Store data in Firestore only if there's a new entry
|
96 |
-
store_data_in_firestore(firestore_client, thingspeak_data)
|
97 |
-
|
98 |
-
# Wait before next iteration
|
99 |
-
time.sleep(5) # Adjust interval as needed
|
100 |
-
|
101 |
-
except KeyboardInterrupt:
|
102 |
-
print("Data collection stopped by user.")
|
103 |
-
except Exception as e:
|
104 |
-
print(f"Unexpected error: {e}")
|
105 |
-
|
106 |
-
if __name__ == "__main__":
|
107 |
main()
|
|
|
1 |
+
import requests
|
2 |
+
import firebase_admin
|
3 |
+
from firebase_admin import credentials, firestore
|
4 |
+
import time
|
5 |
+
|
6 |
+
# Replace with your actual credentials
|
7 |
+
THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
|
8 |
+
CHANNEL_ID = "2784385"
|
9 |
+
FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
|
10 |
+
|
11 |
+
# Global variable to track the last entry ID
|
12 |
+
last_entry_id = None
|
13 |
+
|
14 |
+
def initialize_firebase():
|
15 |
+
"""Initialize Firebase connection"""
|
16 |
+
try:
|
17 |
+
# Initialize Firebase app (only once)
|
18 |
+
cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
|
19 |
+
firebase_admin.initialize_app(cred)
|
20 |
+
|
21 |
+
# Create Firestore client
|
22 |
+
return firestore.client()
|
23 |
+
except Exception as e:
|
24 |
+
print(f"Firebase initialization error: {e}")
|
25 |
+
return None
|
26 |
+
|
27 |
+
def fetch_thingspeak_data():
|
28 |
+
"""Fetch data from ThingSpeak"""
|
29 |
+
global last_entry_id
|
30 |
+
try:
|
31 |
+
url = f"https://api.thingspeak.com/channels/2784385/feeds.json?api_key=P54KXM40TA3CB6W4"
|
32 |
+
response = requests.get(url)
|
33 |
+
response.raise_for_status() # Raise an exception for bad responses
|
34 |
+
data = response.json()
|
35 |
+
|
36 |
+
# Check if there are feeds
|
37 |
+
if not data.get('feeds'):
|
38 |
+
print("No new feeds found.")
|
39 |
+
return None
|
40 |
+
|
41 |
+
# Get the latest feed
|
42 |
+
latest_feed = data['feeds'][-1]
|
43 |
+
|
44 |
+
# Check if this is a new entry
|
45 |
+
current_entry_id = latest_feed.get('entry_id')
|
46 |
+
|
47 |
+
if current_entry_id != last_entry_id:
|
48 |
+
last_entry_id = current_entry_id
|
49 |
+
return latest_feed
|
50 |
+
|
51 |
+
print("No new entries since last check.")
|
52 |
+
return None
|
53 |
+
|
54 |
+
except requests.RequestException as e:
|
55 |
+
print(f"ThingSpeak data fetch error: {e}")
|
56 |
+
return None
|
57 |
+
|
58 |
+
def store_data_in_firestore(firestore_client, data):
|
59 |
+
"""Store data in Firestore"""
|
60 |
+
try:
|
61 |
+
# Validate data
|
62 |
+
if not data:
|
63 |
+
print("No data to store.")
|
64 |
+
return
|
65 |
+
|
66 |
+
# Create a document with timestamp
|
67 |
+
doc_data = {
|
68 |
+
'field1': data.get('field1'),
|
69 |
+
'field2': data.get('field2'),
|
70 |
+
'entry_id': data.get('entry_id'),
|
71 |
+
'timestamp': firestore.SERVER_TIMESTAMP
|
72 |
+
}
|
73 |
+
|
74 |
+
# Add to Firestore collection
|
75 |
+
firestore_client.collection('thingspeak_data').add(doc_data)
|
76 |
+
print("New data successfully stored in Firestore")
|
77 |
+
except Exception as e:
|
78 |
+
print(f"Firestore storage error: {e}")
|
79 |
+
|
80 |
+
def main():
|
81 |
+
# Initialize Firebase
|
82 |
+
firestore_client = initialize_firebase()
|
83 |
+
|
84 |
+
if not firestore_client:
|
85 |
+
print("Failed to initialize Firestore. Exiting.")
|
86 |
+
return
|
87 |
+
|
88 |
+
# Main data collection loop
|
89 |
+
try:
|
90 |
+
while True:
|
91 |
+
# Fetch data from ThingSpeak
|
92 |
+
thingspeak_data = fetch_thingspeak_data()
|
93 |
+
|
94 |
+
if thingspeak_data:
|
95 |
+
# Store data in Firestore only if there's a new entry
|
96 |
+
store_data_in_firestore(firestore_client, thingspeak_data)
|
97 |
+
|
98 |
+
# Wait before next iteration
|
99 |
+
time.sleep(5) # Adjust interval as needed
|
100 |
+
|
101 |
+
except KeyboardInterrupt:
|
102 |
+
print("Data collection stopped by user.")
|
103 |
+
except Exception as e:
|
104 |
+
print(f"Unexpected error: {e}")
|
105 |
+
|
106 |
+
if __name__ == "__main__":
|
107 |
main()
|