Skip to content

Commit 61e048c

Browse files
committed
Fix shared coordinator for all instances
Share MetAPI for all coordinator instances Use HASS shared aiohttp session
1 parent bf43e6d commit 61e048c

5 files changed

Lines changed: 28 additions & 22 deletions

File tree

custom_components/metnowcast/__init__.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from .const import DOMAIN
99
from .coordinator import MetCoordinator
1010
import asyncio
11+
from .met_api import MetApi
1112

1213
PLATFORMS: list[Platform] = [Platform.WEATHER]
1314
_LOGGER = logging.getLogger(__name__)
@@ -18,13 +19,18 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
1819
lat = entry.data[CONF_LATITUDE]
1920
lon = entry.data[CONF_LONGITUDE]
2021
name = entry.data[CONF_NAME]
21-
coordinator = MetCoordinator(hass, entry, name, lat, lon)
22-
await coordinator.async_config_entry_first_refresh()
2322

24-
if DOMAIN not in hass.data:
25-
hass.data[DOMAIN] = {}
26-
hass.data[DOMAIN]["coordinator"] = coordinator
23+
# Ensure DOMAIN is initialized in hass.data
24+
hass.data.setdefault(DOMAIN, {})
25+
# Create and store a single MetApi instance if not already present
26+
if "api" not in hass.data[DOMAIN]:
27+
hass.data[DOMAIN]["api"] = MetApi(hass)
28+
api = hass.data[DOMAIN]["api"]
29+
30+
coordinator = MetCoordinator(hass, entry, name, lat, lon, api)
31+
await coordinator.async_config_entry_first_refresh()
2732

33+
hass.data[DOMAIN][entry.entry_id] = coordinator
2834
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
2935
return True
3036

@@ -42,9 +48,8 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
4248
)
4349
)
4450
if unloaded:
45-
coordinator = hass.data[DOMAIN]["coordinator"]
46-
if coordinator is not None:
47-
hass.data[DOMAIN]["coordinator"] = None
51+
hass.data[DOMAIN].pop(entry.entry_id)
52+
_LOGGER.debug("pop coordinator")
4853
return unloaded
4954

5055

custom_components/metnowcast/config_flow.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
async def validate_input(hass: HomeAssistant, lat: float, lon: float) -> dict[str, Any]:
2929
"""Validate the user input allows us to connect."""
3030

31-
api = MetApi()
31+
api = MetApi(hass)
3232
forecast = await api.get_now_cast(lat, lon)
3333
radar_coverage = forecast["properties"]["meta"]["radar_coverage"]
3434
if radar_coverage == "no coverage":

custom_components/metnowcast/coordinator.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
class MetCoordinator(DataUpdateCoordinator):
1313
"""Met coordinator."""
1414

15-
def __init__(self, hass, config_entry, name, lat, long):
15+
def __init__(self, hass, config_entry, name, lat, long, met_api):
1616
"""Initialize my coordinator."""
1717
super().__init__(
1818
hass,
@@ -23,7 +23,7 @@ def __init__(self, hass, config_entry, name, lat, long):
2323
# Polling interval. Will only be polled if there are subscribers.
2424
update_interval=timedelta(minutes=7),
2525
)
26-
self._metApi = MetApi()
26+
self._metApi = met_api
2727
self.lat = lat
2828
self.long = long
2929

custom_components/metnowcast/met_api.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from __future__ import annotations
33
import logging
44
from .const import NotFound, VERSION
5-
import aiohttp
5+
from homeassistant.helpers.aiohttp_client import async_get_clientsession
66

77

88
_LOGGER = logging.getLogger(__name__)
@@ -16,16 +16,17 @@
1616
class MetApi:
1717
"""Met.no API"""
1818

19-
def __init__(self) -> None:
20-
"""Init"""
19+
def __init__(self, hass) -> None:
20+
"""Init with Home Assistant instance."""
21+
self.hass = hass
2122

2223
async def get_now_cast(self, lat: float, lon: float):
23-
"""Get Nowcast from met.no using aiohttp """
24+
"""Get Nowcast from met.no using Home Assistant's shared aiohttp session."""
2425
url = f"{BASE_URL}/complete"
2526
param = {"lat": lat, "lon": lon}
26-
async with aiohttp.ClientSession() as session:
27-
async with session.get(url=url, params=param, headers=REQUEST_HEADER) as response:
28-
if response.status != 200:
29-
raise NotFound
30-
data = await response.json()
31-
return data
27+
session = async_get_clientsession(self.hass)
28+
async with session.get(url=url, params=param, headers=REQUEST_HEADER) as response:
29+
if response.status != 200:
30+
raise NotFound
31+
data = await response.json()
32+
return data

custom_components/metnowcast/weather.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ async def async_setup_entry(
4747
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
4848
) -> None:
4949
"""Setup weather platform."""
50-
coordinator = hass.data[DOMAIN]["coordinator"]
50+
coordinator = hass.data[DOMAIN][entry.entry_id]
5151
lat = entry.data[CONF_LATITUDE]
5252
lon = entry.data[CONF_LONGITUDE]
5353
name = entry.data[CONF_NAME]

0 commit comments

Comments
 (0)