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.
133 lines
4.2 KiB
133 lines
4.2 KiB
import requests
|
|
import mysql.connector
|
|
from datetime import datetime, timezone
|
|
from dotenv import load_dotenv
|
|
import os
|
|
|
|
# Laad .env bestand
|
|
load_dotenv()
|
|
|
|
# Configuratie
|
|
GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY")
|
|
WEATHER_API_KEY = os.getenv("WEATHER_API_KEY")
|
|
HOME_ADDRESS = os.getenv("HOME_ADDRESS")
|
|
WORK_ADDRESS = os.getenv("WORK_ADDRESS")
|
|
|
|
LOG_FILE = "log.txt"
|
|
SCRIPT_NAME = "LogTravelTime.py"
|
|
|
|
db_config = {
|
|
"host": os.getenv("DB_HOST"),
|
|
"user": os.getenv("DB_USER"),
|
|
"password": os.getenv("DB_PASSWORD"),
|
|
"database": os.getenv("DB_NAME")
|
|
}
|
|
|
|
|
|
def log_message(message):
|
|
with open(LOG_FILE, "a") as log_file:
|
|
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
|
|
log_file.write(f"[{timestamp}] {SCRIPT_NAME}: {message}\n")
|
|
|
|
|
|
def create_table():
|
|
connection = mysql.connector.connect(**db_config)
|
|
cursor = connection.cursor()
|
|
query = """
|
|
CREATE TABLE IF NOT EXISTS travel_times (
|
|
utc_datetime CHAR(16),
|
|
origin VARCHAR(255),
|
|
destination VARCHAR(255),
|
|
travel_time INT,
|
|
direction ENUM('heen', 'terug'),
|
|
mode ENUM('driving', 'bicycling', 'transit'),
|
|
temperature FLOAT,
|
|
weather VARCHAR(255),
|
|
PRIMARY KEY (utc_datetime, mode, direction)
|
|
)
|
|
"""
|
|
cursor.execute(query)
|
|
connection.commit()
|
|
cursor.close()
|
|
connection.close()
|
|
|
|
|
|
def get_weather():
|
|
url = f"https://api.openweathermap.org/data/2.5/weather?q=Amsterdam&appid={WEATHER_API_KEY}&units=metric"
|
|
response = requests.get(url)
|
|
data = response.json()
|
|
|
|
if data["cod"] == 200:
|
|
temperature = data["main"]["temp"]
|
|
weather = data["weather"][0]["description"]
|
|
return temperature, weather
|
|
else:
|
|
log_message("Error fetching weather data")
|
|
return None, None
|
|
|
|
|
|
def get_travel_time(origin, destination, mode):
|
|
url = "https://maps.googleapis.com/maps/api/distancematrix/json"
|
|
params = {
|
|
"origins": origin,
|
|
"destinations": destination,
|
|
"mode": mode,
|
|
"departure_time": "now",
|
|
"traffic_model": "best_guess",
|
|
"key": GOOGLE_MAPS_API_KEY
|
|
}
|
|
response = requests.get(url, params=params)
|
|
data = response.json()
|
|
|
|
if data["status"] == "OK":
|
|
if mode == "driving":
|
|
duration = data["rows"][0]["elements"][0]["duration_in_traffic"]["value"]
|
|
else:
|
|
duration = data["rows"][0]["elements"][0]["duration"]["value"]
|
|
return duration // 60 # Minuten
|
|
else:
|
|
log_message(f"Error fetching travel time for {mode}")
|
|
return None
|
|
|
|
|
|
def save_travel_time(origin, destination, travel_time, direction, mode, temperature, weather):
|
|
connection = mysql.connector.connect(**db_config)
|
|
cursor = connection.cursor()
|
|
query = """
|
|
INSERT INTO travel_times (utc_datetime, origin, destination, travel_time, direction, mode, temperature, weather)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
|
ON DUPLICATE KEY UPDATE travel_time = VALUES(travel_time), direction = VALUES(direction), temperature = VALUES(temperature), weather = VALUES(weather)
|
|
"""
|
|
utc_now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M")
|
|
cursor.execute(query, (utc_now, origin, destination,
|
|
travel_time, direction, mode, temperature, weather))
|
|
connection.commit()
|
|
cursor.close()
|
|
connection.close()
|
|
log_message(
|
|
f"Saved travel time for {mode} {direction}: {travel_time} minutes, weather: {weather}, temp: {temperature}°C")
|
|
|
|
|
|
def main():
|
|
create_table()
|
|
temperature, weather = get_weather()
|
|
|
|
if temperature is None or weather is None:
|
|
log_message("Skipping travel time logging due to missing weather data")
|
|
return
|
|
|
|
for mode in ["driving", "bicycling", "transit"]:
|
|
travel_time_morning = get_travel_time(HOME_ADDRESS, WORK_ADDRESS, mode)
|
|
if travel_time_morning:
|
|
save_travel_time(HOME_ADDRESS, WORK_ADDRESS,
|
|
travel_time_morning, "heen", mode, temperature, weather)
|
|
|
|
travel_time_evening = get_travel_time(WORK_ADDRESS, HOME_ADDRESS, mode)
|
|
if travel_time_evening:
|
|
save_travel_time(WORK_ADDRESS, HOME_ADDRESS,
|
|
travel_time_evening, "terug", mode, temperature, weather)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|