Skip to content

Commit f7a1a49

Browse files
authored
Merge pull request #13 from golles/handle-failures-better
Handle failures better
2 parents a48aa22 + 81b2360 commit f7a1a49

File tree

8 files changed

+83
-37
lines changed

8 files changed

+83
-37
lines changed

custom_components/knmi/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import logging
1010

1111
from homeassistant.config_entries import ConfigEntry
12-
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, CONF_API_KEY
12+
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_API_KEY
1313
from homeassistant.core import Config, HomeAssistant
1414
from homeassistant.exceptions import ConfigEntryNotReady
1515
from homeassistant.helpers.aiohttp_client import async_get_clientsession

custom_components/knmi/api.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ async def api_wrapper(self, method: str, url: str) -> dict:
3838
if "Vraag eerst een API-key op" in await response.text():
3939
raise KnmiApiKeyException("Invalid API key")
4040

41+
if "Dagelijkse limiet" in await response.text():
42+
raise KnmiApiKeyException("Exceeded Daily Limit")
43+
4144
data = await response.json()
4245
return data.get("liveweer")[0]
4346

@@ -61,7 +64,7 @@ async def api_wrapper(self, method: str, url: str) -> dict:
6164
exception,
6265
)
6366
except KnmiApiKeyException as exception:
64-
_LOGGER.error("Error with configuration! - %s", exception)
67+
_LOGGER.error("Error in API! - %s", exception)
6568
# Raise to pass on to the user.
6669
raise exception
6770
except Exception as exception: # pylint: disable=broad-except

custom_components/knmi/binary_sensor.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Binary sensor platform for knmi."""
22
from homeassistant.components.binary_sensor import BinarySensorEntity
3+
from homeassistant.const import CONF_NAME
34

45
from .const import (
56
BINARY_SENSORS,
@@ -43,8 +44,7 @@ def __init__(
4344
data_key,
4445
):
4546
super().__init__(coordinator, config_entry)
46-
self.config_entry = config_entry
47-
self.location_name = self.coordinator.data["plaats"]
47+
self.entry_name = config_entry.data.get(CONF_NAME)
4848
self._name = name
4949
self._icon = icon
5050
self._device_class = device_class
@@ -54,12 +54,13 @@ def __init__(
5454
@property
5555
def name(self):
5656
"""Return the name of the binary_sensor."""
57-
return f"{DEFAULT_NAME} {self.location_name} {self._name}"
57+
return f"{DEFAULT_NAME} {self.entry_name} {self._name}"
5858

5959
@property
6060
def is_on(self):
6161
"""Return true if the binary_sensor is on."""
62-
return self.coordinator.data[self._data_key] != "0"
62+
if super().getData(self._data_key) is not None:
63+
return super().getData(self._data_key) != "0"
6364

6465
@property
6566
def icon(self):
@@ -78,7 +79,7 @@ def extra_state_attributes(self):
7879
for attribute in self._attributes:
7980
value = None
8081
if "key" in attribute:
81-
value = self.coordinator.data[attribute.get("key", None)]
82+
value = super().getData(attribute.get("key", None))
8283
if "value" in attribute:
8384
value = attribute.get("value", None)
8485
attributes[attribute.get("name", None)] = value

custom_components/knmi/const.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
# Base component constants.
2727
NAME = "KNMI"
2828
DOMAIN = "knmi"
29-
VERSION = "1.1.4"
29+
VERSION = "1.1.5"
3030
ATTRIBUTION = "KNMI Weergegevens via https://weerlive.nl/"
3131

3232
# Platforms.

custom_components/knmi/entity.py

+7
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,15 @@
88
class KnmiEntity(CoordinatorEntity):
99
def __init__(self, coordinator, config_entry):
1010
super().__init__(coordinator)
11+
self.coordinator = coordinator
1112
self.config_entry = config_entry
1213

14+
def getData(self, key):
15+
"""Return the data key from the coordinator."""
16+
if self.coordinator.data is not None:
17+
return self.coordinator.data[key]
18+
return None
19+
1320
@property
1421
def unique_id(self):
1522
"""Return a unique ID to use for this entity."""

custom_components/knmi/manifest.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"documentation": "https://github.com/golles/ha-knmi/",
55
"iot_class": "cloud_polling",
66
"issue_tracker": "https://github.com/golles/ha-knmi//issues",
7-
"version": "1.1.4",
7+
"version": "1.1.5",
88
"config_flow": true,
99
"codeowners": [
1010
"@golles"

custom_components/knmi/sensor.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Sensor platform for knmi."""
2+
from homeassistant.const import CONF_NAME
23
from .const import DEFAULT_NAME, DOMAIN, SENSORS
34
from .entity import KnmiEntity
45

@@ -40,8 +41,7 @@ def __init__(
4041
data_key,
4142
):
4243
super().__init__(coordinator, config_entry)
43-
self.config_entry = config_entry
44-
self.location_name = self.coordinator.data["plaats"]
44+
self.entry_name = config_entry.data.get(CONF_NAME)
4545
self._name = name
4646
self._unit_of_measurement = unit_of_measurement
4747
self._icon = icon
@@ -52,12 +52,12 @@ def __init__(
5252
@property
5353
def name(self):
5454
"""Return the name of the sensor."""
55-
return f"{DEFAULT_NAME} {self.location_name} {self._name}"
55+
return f"{DEFAULT_NAME} {self.entry_name} {self._name}"
5656

5757
@property
5858
def state(self):
5959
"""Return the state of the sensor."""
60-
return self.coordinator.data[self._data_key]
60+
return super().getData(self._data_key)
6161

6262
@property
6363
def unit_of_measurement(self):
@@ -81,7 +81,7 @@ def extra_state_attributes(self):
8181
for attribute in self._attributes:
8282
value = None
8383
if "key" in attribute:
84-
value = self.coordinator.data[attribute.get("key", None)]
84+
value = super().getData(attribute.get("key", None))
8585
if "value" in attribute:
8686
value = attribute.get("value", None)
8787
attributes[attribute.get("name", None)] = value

custom_components/knmi/weather.py

+58-23
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
WeatherEntity,
1414
)
1515
from homeassistant.const import (
16+
CONF_NAME,
1617
TEMP_CELSIUS,
1718
)
1819

@@ -29,11 +30,14 @@ async def async_setup_entry(hass, entry, async_add_devices):
2930
class KnmiWeather(KnmiEntity, WeatherEntity):
3031
"""knmi Weather class."""
3132

33+
def __init__(self, coordinator, config_entry):
34+
super().__init__(coordinator, config_entry)
35+
self.entry_name = config_entry.data.get(CONF_NAME)
36+
3237
@property
3338
def name(self):
3439
"""Return the name of the sensor."""
35-
location = self.coordinator.data["plaats"]
36-
return f"{DEFAULT_NAME} {location}"
40+
return f"{DEFAULT_NAME} {self.entry_name}"
3741

3842
@property
3943
def state(self):
@@ -43,12 +47,14 @@ def state(self):
4347
@property
4448
def condition(self):
4549
"""Return the current condition."""
46-
return CONDITIONS_MAP[self.coordinator.data["d0weer"]]
50+
if super().getData("d0weer") is not None:
51+
return CONDITIONS_MAP[super().getData("d0weer")]
4752

4853
@property
4954
def temperature(self):
5055
"""Return the temperature."""
51-
return float(self.coordinator.data["temp"])
56+
if super().getData("temp") is not None:
57+
return float(super().getData("temp"))
5258

5359
@property
5460
def temperature_unit(self):
@@ -58,27 +64,32 @@ def temperature_unit(self):
5864
@property
5965
def pressure(self):
6066
"""Return the pressure."""
61-
return float(self.coordinator.data["luchtd"])
67+
if super().getData("luchtd") is not None:
68+
return float(super().getData("luchtd"))
6269

6370
@property
6471
def humidity(self):
6572
"""Return the humidity."""
66-
return float(self.coordinator.data["lv"])
73+
if super().getData("lv") is not None:
74+
return float(super().getData("lv"))
6775

6876
@property
6977
def wind_speed(self):
7078
"""Return the wind speed."""
71-
return float(self.coordinator.data["windkmh"])
79+
if super().getData("windkmh") is not None:
80+
return float(super().getData("windkmh"))
7281

7382
@property
7483
def wind_bearing(self):
7584
"""Return the wind direction."""
76-
return WIND_DIRECTION_MAP[self.coordinator.data["windr"]]
85+
if super().getData("windr") is not None:
86+
return WIND_DIRECTION_MAP[super().getData("windr")]
7787

7888
@property
7989
def visibility(self):
8090
"""Return the wind direction."""
81-
return float(self.coordinator.data["zicht"]) / 10
91+
if super().getData("zicht") is not None:
92+
return float(super().getData("zicht")) / 10
8293

8394
@property
8495
def forecast(self):
@@ -88,21 +99,45 @@ def forecast(self):
8899

89100
for i in range(0, 3):
90101
date = today + timedelta(days=i)
91-
nextDay = {
102+
condition = (
103+
CONDITIONS_MAP[super().getData(f"d{i}weer")]
104+
if super().getData(f"d{i}weer") is not None
105+
else None
106+
)
107+
wind_bearing = (
108+
WIND_DIRECTION_MAP[super().getData(f"d{i}windr")]
109+
if super().getData(f"d{i}windr") is not None
110+
else None
111+
)
112+
temp_low = (
113+
float(super().getData(f"d{i}tmin"))
114+
if super().getData(f"d{i}tmin") is not None
115+
else None
116+
)
117+
temp = (
118+
float(super().getData(f"d{i}tmin"))
119+
if super().getData(f"d{i}tmin") is not None
120+
else None
121+
)
122+
precipitation = (
123+
float(super().getData(f"d{i}neerslag"))
124+
if super().getData(f"d{i}neerslag") is not None
125+
else None
126+
)
127+
wind_speed = (
128+
float(super().getData(f"d{i}windkmh"))
129+
if super().getData(f"d{i}windkmh") is not None
130+
else None
131+
)
132+
next_day = {
92133
ATTR_FORECAST_TIME: date.isoformat(),
93-
ATTR_FORECAST_CONDITION: CONDITIONS_MAP[
94-
self.coordinator.data[f"d{i}weer"]
95-
],
96-
ATTR_FORECAST_TEMP_LOW: float(self.coordinator.data[f"d{i}tmin"]),
97-
ATTR_FORECAST_TEMP: float(self.coordinator.data[f"d{i}tmax"]),
98-
ATTR_FORECAST_PRECIPITATION: float(
99-
self.coordinator.data[f"d{i}neerslag"]
100-
),
101-
ATTR_FORECAST_WIND_BEARING: WIND_DIRECTION_MAP[
102-
self.coordinator.data[f"d{i}windr"]
103-
],
104-
ATTR_FORECAST_WIND_SPEED: float(self.coordinator.data[f"d{i}windkmh"]),
134+
ATTR_FORECAST_CONDITION: condition,
135+
ATTR_FORECAST_TEMP_LOW: temp_low,
136+
ATTR_FORECAST_TEMP: temp,
137+
ATTR_FORECAST_PRECIPITATION: precipitation,
138+
ATTR_FORECAST_WIND_BEARING: wind_bearing,
139+
ATTR_FORECAST_WIND_SPEED: wind_speed,
105140
}
106-
forecast.append(nextDay)
141+
forecast.append(next_day)
107142

108143
return forecast

0 commit comments

Comments
 (0)