You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
131 lines
4.0 KiB
131 lines
4.0 KiB
import os
|
|
from dotenv import load_dotenv
|
|
from datetime import datetime, timezone
|
|
from weather import fetch_weather_data, estimate_solar_performance, get_sun_times
|
|
from database import create_db_connection, create_table_if_not_exists, insert_or_update_forecast_data
|
|
from logger import setup_logger, logging
|
|
from pprint import pprint
|
|
|
|
|
|
# Initialisatie van variabelen en instellingen
|
|
def initialize_app():
|
|
load_dotenv()
|
|
|
|
app_name = "weather_forecast_app"
|
|
log_format = '%(asctime)s - %(levelname)s - %(message)s'
|
|
|
|
logger = setup_logger(
|
|
app_name, log_level=logging.INFO, log_format=log_format)
|
|
logger.info("Starting weather forecast application...")
|
|
|
|
API_KEY = os.getenv('OPENWEATHER_API_KEY')
|
|
LOCATION = os.getenv('LOCATION', 'Rijswijk')
|
|
|
|
MYSQL_config = {
|
|
'host': os.getenv('MYSQL_HOST'),
|
|
'port': os.getenv('MYSQL_PORT'),
|
|
'user': os.getenv('MYSQL_USER'),
|
|
'password': os.getenv('MYSQL_PASSWORD'),
|
|
'database': os.getenv('MYSQL_NAME')
|
|
}
|
|
|
|
return API_KEY, LOCATION, MYSQL_config, logger
|
|
|
|
|
|
# Database functionaliteit
|
|
def handle_database_operations(MYSQL_config, logger):
|
|
try:
|
|
MYSQL_connection = create_db_connection(MYSQL_config, logger)
|
|
except Exception as e:
|
|
logger.error(f"Failed to connect to the database: {e}")
|
|
raise
|
|
|
|
cursor = MYSQL_connection.cursor()
|
|
|
|
try:
|
|
create_table_if_not_exists(cursor, logger)
|
|
except Exception as e:
|
|
logger.error(f"Error creating table: {e}")
|
|
MYSQL_connection.close()
|
|
raise
|
|
|
|
return MYSQL_connection, cursor
|
|
|
|
|
|
# Weather functionaliteit
|
|
def fetch_and_process_weather_data(API_KEY, LOCATION, logger):
|
|
try:
|
|
logger.info(
|
|
f"Fetching weather forecast from OpenWeatherMap for {LOCATION}...")
|
|
data = fetch_weather_data(API_KEY, LOCATION, logger)
|
|
# pprint(data)
|
|
except Exception as e:
|
|
logger.error(f"Error fetching weather data: {e}")
|
|
raise
|
|
|
|
return data
|
|
|
|
|
|
# Hoofdproces: het verwerken van de weersvoorspellingen en opslaan in de database
|
|
def process_forecasts(data, cursor, logger, location):
|
|
logger.info(
|
|
f"Processing forecast data for {len(data.get('list', []))} entries...")
|
|
|
|
for entry in data.get('list', []):
|
|
utc_dt = datetime.fromtimestamp(entry['dt'], tz=timezone.utc)
|
|
temp = entry['main']['temp']
|
|
weather = entry['weather'][0]['description']
|
|
wind_speed = entry['wind']['speed']
|
|
rain = entry.get('rain', {}).get('3h', 0)
|
|
|
|
logger.debug(
|
|
f"Processing entry at {utc_dt}: Temp={temp}, Weather={weather}, Wind={wind_speed}, Rain={rain}"
|
|
)
|
|
|
|
# Haal de sunrise en sunset tijden op per forecast entry
|
|
sunrise, sunset = get_sun_times(utc_dt, location, logger=logger)
|
|
|
|
solar_performance = estimate_solar_performance(
|
|
entry, utc_dt, location, sunrise, sunset, logger)
|
|
logger.debug(f"Estimated solar performance: {solar_performance}%")
|
|
|
|
insert_or_update_forecast_data(
|
|
cursor, utc_dt, temp, weather, wind_speed, rain, solar_performance, sunrise, sunset, logger)
|
|
|
|
|
|
# Hoofdfunctie
|
|
def main():
|
|
API_KEY, LOCATION, MYSQL_config, logger = initialize_app()
|
|
|
|
try:
|
|
MYSQL_connection, cursor = handle_database_operations(
|
|
MYSQL_config, logger)
|
|
except Exception as e:
|
|
logger.error(f"Error during database operations: {e}")
|
|
return
|
|
|
|
try:
|
|
data = fetch_and_process_weather_data(
|
|
API_KEY, LOCATION, logger)
|
|
except Exception as e:
|
|
logger.error(f"Error fetching weather data: {e}")
|
|
return
|
|
|
|
try:
|
|
process_forecasts(data, cursor, logger, LOCATION)
|
|
except Exception as e:
|
|
logger.error(f"Error processing forecasts: {e}")
|
|
return
|
|
|
|
logger.info("Committing changes to the database...")
|
|
MYSQL_connection.commit()
|
|
logger.info("Changes committed successfully.")
|
|
|
|
cursor.close()
|
|
MYSQL_connection.close()
|
|
logger.info("Database connection closed.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|