Skip to content

Commit

Permalink
Remaster nearest city detection method
Browse files Browse the repository at this point in the history
  • Loading branch information
Limych committed Feb 15, 2021
1 parent 113cc30 commit 3a55630
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 11 deletions.
34 changes: 23 additions & 11 deletions custom_components/gismeteo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,10 @@ def __init__(
self._mode = mode
self._cache = Cache(params) if params.get("cache_dir") is not None else None

self._city_id = self._get_city_id(latitude, longitude)
self._latitude = latitude
self._longitude = longitude
self._city_id = None
self._detect_city_id()
_LOGGER.debug("Nearest city ID: %s", self._city_id)

self._current = {}
Expand Down Expand Up @@ -155,19 +158,26 @@ def _get(var: dict, ind: str, func: Optional[Callable] = None) -> Any:
return None
return res

def _get_city_id(self, lat, lng):
"""Return the nearest city ID."""
url = (BASE_URL + "/cities/?lat={}&lng={}&count=1&lang=en").format(lat, lng)
cache_fname = f"city_{lat}_{lng}"
def _detect_city_id(self):
"""Detect the nearest city ID."""
url = (BASE_URL + "/cities/?lat={}&lng={}&count=1&lang=en").format(
self._latitude, self._longitude
)
cache_fname = f"city_{self._latitude}_{self._longitude}"

response = self._http_request(url, cache_fname)
if not response:
_LOGGER.error("Can't detect nearest city!")
return None
_LOGGER.error("Can't detect nearest city! Invalid server response.")
return False

xml = etree.fromstring(response)
item = xml.find("item")
return self._get(item, "id", int)
try:
xml = etree.fromstring(response)
item = xml.find("item")
self._city_id = self._get(item, "id", int)
return True
except etree.ParseError:
_LOGGER.warning("Can't detect nearest city! Invalid server response.")
return False

@staticmethod
def _is_day(testing_time, sunrise_time, sunset_time):
Expand Down Expand Up @@ -323,7 +333,9 @@ def _get_utime(source, tzone):
def update(self):
"""Get the latest data from Gismeteo."""
if self._city_id is None:
return
if not self._detect_city_id():
_LOGGER.warning("Can't update weather data!")
return

url = (BASE_URL + "/forecast/?city={}&lang=en").format(self._city_id)
cache_fname = f"forecast_{self._city_id}"
Expand Down
3 changes: 3 additions & 0 deletions custom_components/gismeteo/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
https://github.com/Limych/ha-gismeteo/
"""
import logging
from random import randint
from time import sleep

import voluptuous as vol
from homeassistant.components.weather import ATTR_FORECAST_CONDITION, PLATFORM_SCHEMA
Expand Down Expand Up @@ -70,6 +72,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
forecast = config.get(CONF_FORECAST)
cache_dir = config.get(CONF_CACHE_DIR, hass.config.path(STORAGE_DIR))

sleep(randint(0, 5))
gism = Gismeteo(
latitude,
longitude,
Expand Down
3 changes: 3 additions & 0 deletions custom_components/gismeteo/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
https://github.com/Limych/ha-gismeteo/
"""
import logging
from random import randint
from time import sleep

import voluptuous as vol
from homeassistant.components.weather import PLATFORM_SCHEMA, WeatherEntity
Expand Down Expand Up @@ -58,6 +60,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
cache_dir = config.get(CONF_CACHE_DIR, hass.config.path(STORAGE_DIR))
mode = config.get(CONF_MODE)

sleep(randint(0, 5))
gism = Gismeteo(
latitude,
longitude,
Expand Down

0 comments on commit 3a55630

Please sign in to comment.