Files
weather-info/app/web/wlan.py
2025-11-12 13:59:07 +01:00

67 lines
1.8 KiB
Python

import time
import network # type: ignore
import urequests # type: ignore
from ..classes.location import Location
from ..classes.weather import CurrentCondition, Weather
import json
API_KEY = '3545ce42d0ba436e8dc164532250410'
ACTUAL_WEATHER_URL = 'http://api.weatherapi.com/v1/current.json?key={API_KEY}&q={city}&aqi=yes&lang={lang}'
class Wlan:
def __init__(self, ssid, password):
self.wlan = network.WLAN(network.STA_IF)
self.ssid = ssid
self.password = password
def mock_weather_data(self):
filepath = 'restapi/mock-weather.json'
try:
with open(filepath, 'r', encoding='utf-8') as file:
return json.load(file)
except OSError: # Use OSError instead of FileNotFoundError
print(f"Error: File '{filepath}' not found.")
return None
except FileNotFoundError:
print(f"Error: File '{filepath}' not found.")
return None
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in '{filepath}': {e}")
return None
def connect(self):
self.wlan.active(True)
self.wlan.connect(self.ssid, self.password)
while not self.wlan.isconnected:
print('connecting, please wait ...')
time.sleep(1)
print('connected! IP=', self.wlan.ifconfig()[0])
def actual_weather(self, city='grosshansdorf', lang='de', test_mode=False) -> Weather:
weather_url = ACTUAL_WEATHER_URL.format(API_KEY=API_KEY, city=city, lang=lang)
if not test_mode:
if not self.wlan.isconnected:
self.connect()
print(f'query: {weather_url}')
r = urequests.get(weather_url)
print('Status-Code:', r.status_code)
json_resp = r.json()
r.close()
else:
print('Status-Code: test_mode')
# json_resp = WEATHER_QUERY_MOCK
json_resp = self.mock_weather_data()
loc = Location(**json_resp['location'])
cc = CurrentCondition(**json_resp['current'])
weather = Weather(location=loc, current=cc)
return weather