diff --git a/adhan-webapp/app.py b/adhan-webapp/app.py index 2981ee5..3487221 100644 --- a/adhan-webapp/app.py +++ b/adhan-webapp/app.py @@ -6,6 +6,9 @@ from hijridate import Gregorian from functools import lru_cache import time from concurrent.futures import ThreadPoolExecutor +import asyncio +import aiohttp +from functools import wraps app = Flask(__name__) @@ -15,6 +18,12 @@ last_api_call = {} cached_data = {} executor = ThreadPoolExecutor(max_workers=3) # Voor parallelle API calls +def async_route(f): + @wraps(f) + def wrapped(*args, **kwargs): + return asyncio.run(f(*args, **kwargs)) + return wrapped + def get_cached_data(key, fetch_func, duration=CACHE_DURATION): """Haal data uit cache of voer fetch_func uit als cache verlopen is""" current_time = time.time() @@ -28,14 +37,67 @@ def get_cached_data(key, fetch_func, duration=CACHE_DURATION): last_api_call[key] = current_time return data -def fetch_data_parallel(): - """Haal alle data parallel op""" - futures = { - 'weather': executor.submit(fetch_weather_data), - 'sonos': executor.submit(fetch_sonos_zones), - 'date': executor.submit(get_date_info) +async def fetch_weather_data_async(): + """Asynchrone versie van weather data ophalen""" + try: + async with aiohttp.ClientSession() as session: + params = { + 'q': WEATHER_LOCATION, + 'appid': OPENWEATHER_API_KEY, + 'units': 'metric', + 'lang': 'nl' + } + async with session.get('https://api.openweathermap.org/data/2.5/weather', params=params, timeout=5) as response: + data = await response.json() + + weather_info = { + 'temperature': round(data['main']['temp']), + 'feels_like': round(data['main']['feels_like']), + 'description': data['weather'][0]['description'].capitalize(), + 'humidity': data['main']['humidity'], + 'wind_speed': round(data['wind']['speed'] * 3.6), + 'icon': data['weather'][0]['icon'] + } + return weather_info + except Exception as e: + print(f"⚠️ Fout bij ophalen weerdata: {e}") + return { + 'temperature': '--', + 'feels_like': '--', + 'description': 'Weer niet beschikbaar', + 'humidity': '--', + 'wind_speed': '--', + 'icon': '01d' + } + +async def fetch_sonos_zones_async(): + """Asynchrone versie van Sonos zones ophalen""" + try: + async with aiohttp.ClientSession() as session: + async with session.get(f'http://{SONOS_API_IP}:5005/zones', timeout=5) as response: + data = await response.json() + zones = [] + for group in data: + for player in group['members']: + zones.append(player['roomName']) + return sorted(set(zones)) + except Exception as e: + print(f'Fout bij ophalen Sonos-zones: {e}') + return ['Woonkamer', 'Slaapkamer', 'Keuken'] + +async def fetch_data_parallel_async(): + """Haal alle data parallel op met asyncio""" + weather_task = asyncio.create_task(fetch_weather_data_async()) + sonos_task = asyncio.create_task(fetch_sonos_zones_async()) + date_task = asyncio.create_task(asyncio.to_thread(get_date_info)) + + weather, sonos, date = await asyncio.gather(weather_task, sonos_task, date_task) + + return { + 'weather': weather, + 'sonos': sonos, + 'date': date } - return {key: future.result() for key, future in futures.items()} # Voeg cache-control headers toe voor statische bestanden @app.after_request @@ -332,7 +394,8 @@ def index(): date_info=date_info) @app.route('/instellingen', methods=['GET', 'POST']) -def instellingen(): +@async_route +async def instellingen(): if request.method == 'POST': try: # Nieuwe volume instellingen @@ -409,9 +472,9 @@ def instellingen(): print(f"❌ Fout bij opslaan instellingen: {e}") # Probeer alsnog door te gaan zonder de Pi volume instelling return redirect('/instellingen') - - # Haal alle data parallel op - data = fetch_data_parallel() + + # Haal alle data parallel op met asyncio + data = await fetch_data_parallel_async() return render_template('settings.html', settings=load_settings(), diff --git a/adhan-webapp/done b/adhan-webapp/done index 81119f5..d582ecc 100644 --- a/adhan-webapp/done +++ b/adhan-webapp/done @@ -15,3 +15,4 @@ Mon May 26 18:17:57 CEST 2025: Tijdzone probleem opgelost - Container gebruikt n Wed May 28 14:09:12 CEST 2025: Sonos debug tijd synchronisatie geïmplementeerd - get_current_volume functie en cron script gebruiken nu debug tijd API, volume bepaling werkt correct in debug mode 2025-05-29 21:24:37 - Performance optimalisaties toegevoegd: caching voor API calls en instellingen 2025-05-29 21:27:02 - UI optimalisaties toegevoegd: lazy loading, parallelle API calls en caching +2025-05-29 21:30:24 - Geavanceerde optimalisaties toegevoegd: async/await, debouncing en DOM caching diff --git a/adhan-webapp/templates/settings.html b/adhan-webapp/templates/settings.html index 9c085d9..a3174e4 100644 --- a/adhan-webapp/templates/settings.html +++ b/adhan-webapp/templates/settings.html @@ -327,37 +327,134 @@