4
4
For more details about this integration, please refer to
5
5
https://github.com/golles/ha-knmi/
6
6
"""
7
- import asyncio
8
- from datetime import timedelta
9
- import logging
7
+ from typing import Any , Callable
10
8
11
9
from homeassistant .config_entries import ConfigEntry
12
10
from homeassistant .const import CONF_LATITUDE , CONF_LONGITUDE , CONF_API_KEY
13
11
from homeassistant .core import Config , HomeAssistant
14
12
from homeassistant .exceptions import ConfigEntryNotReady
15
13
from homeassistant .helpers .aiohttp_client import async_get_clientsession
14
+ from homeassistant .helpers .device_registry import DeviceEntryType
15
+ from homeassistant .helpers .entity import DeviceInfo
16
16
from homeassistant .helpers .update_coordinator import DataUpdateCoordinator , UpdateFailed
17
17
18
18
from .api import KnmiApiClient
19
- from .const import DOMAIN , PLATFORMS
19
+ from .const import _LOGGER , DOMAIN , NAME , VERSION , PLATFORMS , SCAN_INTERVAL
20
20
21
- SCAN_INTERVAL = timedelta (seconds = 300 )
22
21
23
- _LOGGER : logging .Logger = logging .getLogger (__package__ )
24
-
25
-
26
- async def async_setup (_hass : HomeAssistant , _config : Config ):
22
+ async def async_setup (_hass : HomeAssistant , _config : Config ) -> bool :
27
23
"""Set up this integration using YAML is not supported."""
28
24
return True
29
25
30
26
31
- async def async_setup_entry (hass : HomeAssistant , entry : ConfigEntry ):
32
- """Set up this integration using UI ."""
27
+ async def async_setup_entry (hass : HomeAssistant , entry : ConfigEntry ) -> bool :
28
+ """Set up KNMI as config entry ."""
33
29
if hass .data .get (DOMAIN ) is None :
34
30
hass .data .setdefault (DOMAIN , {})
35
31
@@ -40,62 +36,76 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
40
36
session = async_get_clientsession (hass )
41
37
client = KnmiApiClient (api_key , latitude , longitude , session )
42
38
43
- coordinator = KnmiDataUpdateCoordinator (hass , client = client )
44
- await coordinator .async_refresh ()
39
+ device_info = DeviceInfo (
40
+ entry_type = DeviceEntryType .SERVICE ,
41
+ identifiers = {(DOMAIN , entry .entry_id )},
42
+ manufacturer = NAME ,
43
+ name = NAME ,
44
+ model = VERSION ,
45
+ configuration_url = "http://weerlive.nl/api/toegang/account.php" ,
46
+ )
47
+
48
+ coordinator = KnmiDataUpdateCoordinator (
49
+ hass = hass , client = client , device_info = device_info
50
+ )
51
+ await coordinator .async_config_entry_first_refresh ()
45
52
46
53
if not coordinator .last_update_success :
47
54
raise ConfigEntryNotReady
48
55
49
- hass .data [DOMAIN ][entry .entry_id ] = coordinator
56
+ entry .async_on_unload (entry .add_update_listener (async_reload_entry ))
57
+
58
+ hass .data .setdefault (DOMAIN , {})[entry .entry_id ] = coordinator
50
59
51
60
for platform in PLATFORMS :
52
61
if entry .options .get (platform , True ):
53
62
coordinator .platforms .append (platform )
54
63
hass .async_add_job (
55
64
hass .config_entries .async_forward_entry_setup (entry , platform )
56
65
)
57
-
58
- entry .async_on_unload (entry .add_update_listener (async_reload_entry ))
59
66
return True
60
67
61
68
69
+ async def async_unload_entry (hass : HomeAssistant , entry : ConfigEntry ) -> bool :
70
+ """Unload KNMI config entry."""
71
+ unload_ok = await hass .config_entries .async_unload_platforms (entry , PLATFORMS )
72
+ if unload_ok :
73
+ del hass .data [DOMAIN ][entry .entry_id ]
74
+ return unload_ok
75
+
76
+
77
+ async def async_reload_entry (hass : HomeAssistant , entry : ConfigEntry ) -> None :
78
+ """Reload config entry."""
79
+ await async_unload_entry (hass , entry )
80
+ await async_setup_entry (hass , entry )
81
+
82
+
62
83
class KnmiDataUpdateCoordinator (DataUpdateCoordinator ):
63
84
"""Class to manage fetching data from the API."""
64
85
65
- def __init__ (self , hass : HomeAssistant , client : KnmiApiClient ) -> None :
86
+ def __init__ (
87
+ self , hass : HomeAssistant , client : KnmiApiClient , device_info : DeviceInfo
88
+ ) -> None :
66
89
"""Initialize."""
67
90
self .api = client
91
+ self .device_info = device_info
68
92
self .platforms = []
69
93
70
- super ().__init__ (hass , _LOGGER , name = DOMAIN , update_interval = SCAN_INTERVAL )
94
+ super ().__init__ (
95
+ hass = hass , logger = _LOGGER , name = DOMAIN , update_interval = SCAN_INTERVAL
96
+ )
71
97
72
- async def _async_update_data (self ):
98
+ async def _async_update_data (self ) -> dict [ str , Any ] :
73
99
"""Update data via library."""
74
100
try :
75
101
return await self .api .async_get_data ()
76
102
except Exception as exception :
77
103
raise UpdateFailed () from exception
78
104
79
-
80
- async def async_unload_entry (hass : HomeAssistant , entry : ConfigEntry ) -> bool :
81
- """Handle removal of an entry."""
82
- coordinator = hass .data [DOMAIN ][entry .entry_id ]
83
- unloaded = all (
84
- await asyncio .gather (
85
- * [
86
- hass .config_entries .async_forward_entry_unload (entry , platform )
87
- for platform in PLATFORMS
88
- if platform in coordinator .platforms
89
- ]
90
- )
91
- )
92
- if unloaded :
93
- hass .data [DOMAIN ].pop (entry .entry_id )
94
-
95
- return unloaded
96
-
97
-
98
- async def async_reload_entry (hass : HomeAssistant , entry : ConfigEntry ) -> None :
99
- """Reload config entry."""
100
- await async_unload_entry (hass , entry )
101
- await async_setup_entry (hass , entry )
105
+ def get_value (
106
+ self , key : str , convert_to : Callable = str
107
+ ) -> float | int | str | None :
108
+ """Get a value from the retrieved data and convert to given type"""
109
+ if self .data and self .data [key ]:
110
+ return convert_to (self .data [key ])
111
+ return None
0 commit comments