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}") def main(): # Initialize Firebase firestore_client = initialize_firebase() if not firestore_client: print("Failed to initialize Firestore. Exiting.") return # 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}") if __name__ == "__main__": main()