1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
"""Utils for AccuWeather."""
from __future__ import annotations
from typing import Any
from .const import (
ENDPOINT,
MAX_API_KEY_LENGTH,
MAX_LATITUDE,
MAX_LONGITUDE,
TEMPERATURES,
URLS,
)
def valid_coordinates(latitude: float | None, longitude: float | None) -> bool:
"""Return True if coordinates are valid."""
if (
isinstance(latitude, int | float)
and isinstance(longitude, int | float)
and abs(latitude) <= MAX_LATITUDE
and abs(longitude) <= MAX_LONGITUDE
):
return True
return False
def valid_api_key(api_key: str) -> bool:
"""Return True if API key is valid."""
if isinstance(api_key, str) and len(api_key) == MAX_API_KEY_LENGTH:
return True
return False
def construct_url(arg: str, **kwargs: str) -> str:
"""Construct AccuWeather API URL."""
return ENDPOINT + URLS[arg].format(**kwargs)
def parse_current_condition(
data: dict[str, Any], to_remove: tuple[str, ...]
) -> dict[str, Any]:
"""Clean current condition API response."""
result = {key: data[key] for key in data if key not in to_remove}
if isinstance(result["PrecipitationType"], str):
result["PrecipitationType"] = result["PrecipitationType"].lower()
result["UVIndexText"] = result["UVIndexText"].lower()
result["PressureTendency"]["LocalizedText"] = result["PressureTendency"][
"LocalizedText"
].lower()
return result
def parse_daily_forecast(
data: dict[str, Any], to_remove: tuple[str, ...]
) -> list[dict[str, Any]]:
"""Parse and clean daily forecast API response."""
parsed_data = [
{key: value for key, value in item.items() if key not in to_remove}
for item in data["DailyForecasts"]
]
for day in parsed_data:
for item in day["AirAndPollen"]:
day[item["Name"]] = item
# Sometimes these values contain a space and an additional description,
# we do not want that.
# https://github.com/home-assistant/core/issues/93115
day[item["Name"]]["Category"] = (
day[item["Name"]]["Category"].split(" ")[0].lower()
)
day[item["Name"]].pop("Name")
day.pop("AirAndPollen")
for temp in TEMPERATURES:
day[f"{temp}Min"] = day[temp]["Minimum"]
day[f"{temp}Max"] = day[temp]["Maximum"]
day.pop(temp)
for item in ("Day", "Night"):
for key, value in day[item].items():
if isinstance(value, str) and key not in ("ShortPhrase", "LongPhrase"):
day[f"{key}{item}"] = value.lower()
else:
day[f"{key}{item}"] = value
day.pop(item)
return parsed_data
def parse_hourly_forecast(
data: list[dict[str, Any]], to_remove: tuple[str, ...]
) -> list[dict[str, Any]]:
"""Parse and clean hourly forecast API response."""
result = [
{key: value for key, value in item.items() if key not in to_remove}
for item in data
]
for hour in result:
for key, value in hour.items():
if isinstance(value, str):
hour[key] = value.lower()
return result
|