1 """Shared utilities for different supported platforms."""
3 from datetime
import datetime, timedelta
4 from http
import HTTPStatus
9 from buienradar.buienradar
import parse_data
10 from buienradar.constants
import (
27 from buienradar.urls
import JSON_FEED_URL, json_precipitation_forecast_url
35 from .const
import DEFAULT_TIMEOUT, SCHEDULE_NOK, SCHEDULE_OK
38 _LOGGER = logging.getLogger(__name__)
41 Log at WARN level after WARN_THRESHOLD failures, otherwise log at
48 """Log at warn level after WARN_THRESHOLD failures, debug otherwise."""
49 if count >= WARN_THRESHOLD:
50 _LOGGER.warning(*args, **kwargs)
52 _LOGGER.debug(*args, **kwargs)
56 """Get the latest data and updates the states."""
59 load_error_count: int = WARN_THRESHOLD
60 rain_error_count: int = WARN_THRESHOLD
62 def __init__(self, hass: HomeAssistant, coordinates, timeframe, devices) ->
None:
63 """Initialize the data object."""
65 self.
datadata: dict[str, Any] |
None = {}
72 """Update all devices/sensors."""
78 dev.data_updated(self)
82 """Schedule an update after minute minutes."""
83 _LOGGER.debug(
"Scheduling next update in %s minutes", minute)
84 nxt = dt_util.utcnow() +
timedelta(minutes=minute)
90 """Load data from specified url."""
91 _LOGGER.debug(
"Calling url: %s", url)
92 result = {SUCCESS:
False, MESSAGE:
None}
96 async
with websession.get(
97 url, timeout=aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)
99 result[STATUS_CODE] = resp.status
100 result[CONTENT] = await resp.text()
101 if resp.status == HTTPStatus.OK:
102 result[SUCCESS] =
True
104 result[MESSAGE] = f
"Got http statuscode: {resp.status}"
107 except (TimeoutError, aiohttp.ClientError)
as err:
108 result[MESSAGE] =
str(err)
115 """Update the data from buienradar."""
116 content = await self.
get_dataget_data(JSON_FEED_URL)
118 if content.get(SUCCESS)
is not True:
123 "Unable to retrieve json data from Buienradar (Msg: %s, status: %s)",
124 content.get(MESSAGE),
125 content.get(STATUS_CODE),
133 rainurl = json_precipitation_forecast_url(lat, lon)
134 raincontent = await self.
get_dataget_data(rainurl)
136 if raincontent.get(SUCCESS)
is not True:
141 "Unable to retrieve rain data from Buienradar (Msg: %s, status: %s)",
142 raincontent.get(MESSAGE),
143 raincontent.get(STATUS_CODE),
149 content.get(CONTENT),
150 raincontent.get(CONTENT),
157 _LOGGER.debug(
"Buienradar parsed data: %s", result)
158 if result.get(SUCCESS)
is not True:
159 if int(datetime.now().strftime(
"%H")) > 0:
161 "Unable to parse data from Buienradar. (Msg: %s)",
169 """Update the data from buienradar and schedule the next update."""
182 """Return the attribution."""
183 return self.
datadata.
get(ATTRIBUTION)
187 """Return the name of the selected weatherstation."""
188 return self.
datadata.
get(STATIONNAME)
192 """Return the condition."""
193 return self.
datadata.
get(CONDITION)
197 """Return the temperature, or None."""
200 except (ValueError, TypeError):
205 """Return the pressure, or None."""
208 except (ValueError, TypeError):
213 """Return the humidity, or None."""
216 except (ValueError, TypeError):
221 """Return the visibility, or None."""
224 except (ValueError, TypeError):
229 """Return the windspeed, or None."""
232 except (ValueError, TypeError):
237 """Return the wind bearing, or None."""
240 except (ValueError, TypeError):
245 """Return the forecast data."""
246 return self.
datadata.
get(FORECAST)
def async_schedule_update(self, minute=1)
def async_update(self, *_)
None __init__(self, HomeAssistant hass, coordinates, timeframe, devices)
None threshold_log(int count, *args, **kwargs)
web.Response get(self, web.Request request, str config_key)
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)
CALLBACK_TYPE async_track_point_in_utc_time(HomeAssistant hass, HassJob[[datetime], Coroutine[Any, Any, None]|None]|Callable[[datetime], Coroutine[Any, Any, None]|None] action, datetime point_in_time)