#!/usr/bin/env python3 # This is for my Rasp Pi weather clock project; this python script runs on a web # server but could easily run on the pi itself too. I run it on my web server because # I use the same functionality for an ESP32 based clock. It does the same thing basically. # 2024 bt -- LostGeek.NET import requests import datetime import os import subprocess # Set the target directory to wherever your www files live TARGET_DIR = "/var/www/html/" # Weather API settings; You must configure these! API_KEY = "your_key_here" ZIP_CODE = "00000" COUNTRY_CODE = "US" WEATHER_URL = f"http://api.openweathermap.org/data/2.5/weather?zip={ZIP_CODE},{COUNTRY_CODE}&appid={API_KEY}&units=imperial" def format_date(): # Get today's date and format it today = datetime.datetime.now() weekday = today.strftime("%A")[:5] # Shorten weekday if necessary month = today.strftime("%B") day = today.day # Build the date string and ensure it doesn't exceed 20 characters full_date = f"{weekday} {month} {day}" return full_date[:20] def get_uptime_and_mem(): # Fetch uptime and memory usage using subprocess try: uptime = subprocess.check_output("uptime | awk '{print $3}'", shell=True).decode('utf-8').strip() mem_usage = subprocess.check_output("free -m | awk '/Mem:/ {print $3 \" MB\"}'", shell=True).decode('utf-8').strip() return uptime, mem_usage except subprocess.CalledProcessError: return None, None def update_weather(): try: # Fetch weather data response = requests.get(WEATHER_URL) response.raise_for_status() data = response.json() if data and data.get("cod") == 200: # Extract relevant data temp_f = round(data["main"]["temp"]) temp_c = round((temp_f - 32) * 5/9) humidity = data["main"]["humidity"] wind_speed = round(data["wind"]["speed"]) wind_deg = data["wind"]["deg"] # Get the formatted date date_str = format_date() # Fetch system info uptime, mem_usage = get_uptime_and_mem() # Write weather data to files weather_files = { "wclock.txt": f"{date_str}\n{temp_f}F | {humidity}% | {wind_speed} Mph\n{mem_usage} up for {uptime} D", "fclock.txt": f" Temp {temp_f}F | Humidity {humidity}% | Wind {wind_speed} Mph", "weather": f"{temp_f}F/{temp_c}C\n{humidity}\n{wind_speed}\n{wind_deg}" } # Overwrite files in the target directory for filename, content in weather_files.items(): file_path = os.path.join(TARGET_DIR, filename) with open(file_path, "w") as file: file.write(content) print("Weather data updated successfully!") else: print("Error fetching weather data.") except requests.exceptions.RequestException as e: print(f"Error fetching weather data: {e}") # Run the update if __name__ == "__main__": update_weather()