@@ -107,7 +107,10 @@ def __init__(
107107 self ._mode = mode
108108 self ._cache = Cache (params ) if params .get ("cache_dir" ) is not None else None
109109
110- self ._city_id = self ._get_city_id (latitude , longitude )
110+ self ._latitude = latitude
111+ self ._longitude = longitude
112+ self ._city_id = None
113+ self ._detect_city_id ()
111114 _LOGGER .debug ("Nearest city ID: %s" , self ._city_id )
112115
113116 self ._current = {}
@@ -155,19 +158,26 @@ def _get(var: dict, ind: str, func: Optional[Callable] = None) -> Any:
155158 return None
156159 return res
157160
158- def _get_city_id (self , lat , lng ):
159- """Return the nearest city ID."""
160- url = (BASE_URL + "/cities/?lat={}&lng={}&count=1&lang=en" ).format (lat , lng )
161- cache_fname = f"city_{ lat } _{ lng } "
161+ def _detect_city_id (self ):
162+ """Detect the nearest city ID."""
163+ url = (BASE_URL + "/cities/?lat={}&lng={}&count=1&lang=en" ).format (
164+ self ._latitude , self ._longitude
165+ )
166+ cache_fname = f"city_{ self ._latitude } _{ self ._longitude } "
162167
163168 response = self ._http_request (url , cache_fname )
164169 if not response :
165- _LOGGER .error ("Can't detect nearest city!" )
166- return None
170+ _LOGGER .error ("Can't detect nearest city! Invalid server response. " )
171+ return False
167172
168- xml = etree .fromstring (response )
169- item = xml .find ("item" )
170- return self ._get (item , "id" , int )
173+ try :
174+ xml = etree .fromstring (response )
175+ item = xml .find ("item" )
176+ self ._city_id = self ._get (item , "id" , int )
177+ return True
178+ except etree .ParseError :
179+ _LOGGER .warning ("Can't detect nearest city! Invalid server response." )
180+ return False
171181
172182 @staticmethod
173183 def _is_day (testing_time , sunrise_time , sunset_time ):
@@ -323,7 +333,9 @@ def _get_utime(source, tzone):
323333 def update (self ):
324334 """Get the latest data from Gismeteo."""
325335 if self ._city_id is None :
326- return
336+ if not self ._detect_city_id ():
337+ _LOGGER .warning ("Can't update weather data!" )
338+ return
327339
328340 url = (BASE_URL + "/forecast/?city={}&lang=en" ).format (self ._city_id )
329341 cache_fname = f"forecast_{ self ._city_id } "
0 commit comments