Skip to content

Commit 9d35a79

Browse files
authored
feat: Use Home Assistant's shared aiohttp client session (#210)
* feat: Use Home Assistant's shared aiohttp client session * Instantiate GasBuddy API client once before the price lookup loop.
1 parent 6c112e3 commit 9d35a79

File tree

4 files changed

+27
-14
lines changed

4 files changed

+27
-14
lines changed

custom_components/gasbuddy/config_flow.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@
1111

1212
from homeassistant import config_entries
1313
from homeassistant.config_entries import ConfigFlowResult
14-
from homeassistant.core import callback
14+
from homeassistant.core import HomeAssistant, callback
1515
from homeassistant.helpers import config_validation as cv
16+
from homeassistant.helpers.aiohttp_client import async_get_clientsession
1617

1718
from .const import (
1819
CONF_GPS,
@@ -49,16 +50,22 @@ async def validate_url(url: str) -> bool:
4950
return bool(re.match(pattern, url))
5051

5152

52-
async def validate_station(station: int, solver: str | None = None) -> bool:
53+
async def validate_station(
54+
hass: HomeAssistant, station: int, solver: str | None = None
55+
) -> bool:
5356
"""Validate statation ID."""
54-
check = await py_gasbuddy.GasBuddy(solver_url=solver, station_id=station).price_lookup()
57+
check = await py_gasbuddy.GasBuddy(
58+
solver_url=solver,
59+
station_id=station,
60+
session=async_get_clientsession(hass),
61+
).price_lookup()
5562

5663
if "errors" in check:
5764
return False
5865
return True
5966

6067

61-
async def _get_station_list(hass, user_input) -> dict[str, Any]:
68+
async def _get_station_list(hass: HomeAssistant, user_input) -> dict[str, Any]:
6269
"""Return list of utilities by lat/lon."""
6370
lat = None
6471
lon = None
@@ -77,9 +84,10 @@ async def _get_station_list(hass, user_input) -> dict[str, Any]:
7784
solver = user_input[CONF_SOLVER]
7885
_LOGGER.debug("Using solver URL: %s", solver)
7986

80-
stations = await py_gasbuddy.GasBuddy(solver_url=solver).location_search(
81-
lat=lat, lon=lon, zipcode=postal
82-
)
87+
stations = await py_gasbuddy.GasBuddy(
88+
solver_url=solver,
89+
session=async_get_clientsession(hass),
90+
).location_search(lat=lat, lon=lon, zipcode=postal)
8391
stations_list = {}
8492
_LOGGER.debug("search reply: %s", stations)
8593

@@ -267,7 +275,7 @@ async def async_step_manual(self, user_input=None):
267275
self._errors[CONF_SOLVER] = "invalid_url"
268276
return await self._show_config_manual(user_input)
269277

270-
validate = await validate_station(user_input[CONF_STATION_ID], user_input[CONF_SOLVER])
278+
validate = await validate_station(self.hass, user_input[CONF_STATION_ID], user_input[CONF_SOLVER])
271279
if not validate:
272280
self._errors[CONF_STATION_ID] = "station_id"
273281
else:
@@ -427,7 +435,7 @@ async def async_step_reconfigure(self, user_input: dict[str, Any] | None = None)
427435
else:
428436
user_input[CONF_SOLVER] = None
429437

430-
validate = await validate_station(user_input[CONF_STATION_ID], user_input[CONF_SOLVER])
438+
validate = await validate_station(self.hass, user_input[CONF_STATION_ID], user_input[CONF_SOLVER])
431439
if not validate:
432440
self._errors[CONF_STATION_ID] = "station_id"
433441

custom_components/gasbuddy/coordinator.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
from homeassistant.config_entries import ConfigEntry
1313
from homeassistant.core import HomeAssistant
14+
from homeassistant.helpers.aiohttp_client import async_get_clientsession
1415
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
1516

1617
from .const import CONF_INTERVAL, CONF_SOLVER, CONF_STATION_ID, CONF_TIMEOUT, DOMAIN
@@ -33,6 +34,7 @@ def __init__(self, hass: HomeAssistant, config: ConfigEntry) -> None:
3334
station_id=config.data[CONF_STATION_ID],
3435
cache_file=self._cache_file,
3536
timeout=config.data[CONF_TIMEOUT],
37+
session=async_get_clientsession(hass),
3638
)
3739

3840
_LOGGER.debug("Data will be update every %s", self.interval)

custom_components/gasbuddy/manifest.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
"iot_class": "cloud_polling",
99
"issue_tracker": "https://github.com/firstof9/ha-gasbuddy/issues",
1010
"loggers": ["gasbuddy"],
11-
"requirements": ["aiofiles", "backoff", "py_gasbuddy==0.4.2"],
11+
"requirements": ["aiofiles", "backoff", "py_gasbuddy==0.4.3"],
1212
"version": "0.0.0-dev"
1313
}
1414

custom_components/gasbuddy/services.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
callback,
1717
)
1818
from homeassistant.helpers import config_validation as cv, device_registry as dr
19+
from homeassistant.helpers.aiohttp_client import async_get_clientsession
1920

2021
from .const import (
2122
ATTR_DEVICE_ID,
@@ -99,13 +100,14 @@ async def _price_lookup_gps(self, service: ServiceCall) -> ServiceResponse:
99100
solver = service.data[ATTR_SOLVER]
100101

101102
results = {}
103+
api = GasBuddy(solver_url=solver, session=async_get_clientsession(self.hass))
102104
for entity_id in entity_ids:
103105
try:
104106
entity = self.hass.states.get(entity_id)
105107
if entity:
106108
lat = entity.attributes[ATTR_LATITUDE]
107109
lon = entity.attributes[ATTR_LONGITUDE]
108-
results[entity_id] = await GasBuddy(solver_url=solver).price_lookup_service(
110+
results[entity_id] = await api.price_lookup_service(
109111
lat=lat, lon=lon, limit=limit
110112
)
111113
except (APIError, LibraryError, CSRFTokenMissing) as ex:
@@ -128,9 +130,10 @@ async def _price_lookup_zip(self, service: ServiceCall) -> ServiceResponse:
128130

129131
results = {}
130132
try:
131-
results = await GasBuddy(solver_url=solver).price_lookup_service(
132-
zipcode=zipcode, limit=limit
133-
)
133+
results = await GasBuddy(
134+
solver_url=solver,
135+
session=async_get_clientsession(self.hass),
136+
).price_lookup_service(zipcode=zipcode, limit=limit)
134137
except (APIError, LibraryError, CSRFTokenMissing) as ex:
135138
_LOGGER.error("Error checking prices: %s", ex)
136139

0 commit comments

Comments
 (0)