Skip to content

Commit

Permalink
Merge pull request #134 from dbrgn/morebikes-improvements
Browse files Browse the repository at this point in the history
morebikes: Close aiohttp connections when probing API
  • Loading branch information
CoMPaTech authored Aug 21, 2024
2 parents 2991ce8 + a1a9e0c commit 18b1198
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
6 changes: 4 additions & 2 deletions custom_components/stromer/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ async def validate_input(_: HomeAssistant, data: dict[str, Any]) -> dict:
client_id = data[CONF_CLIENT_ID]
client_secret = data.get(CONF_CLIENT_SECRET, None)

# Initialize connection to stromer
# Initialize connection to stromer to validate credentials
stromer = Stromer(username, password, client_id, client_secret)
if not await stromer.stromer_connect():
raise InvalidAuth
LOGGER.debug("Credentials validated successfully")
await stromer.stromer_disconnect()

# All bikes information available
all_bikes = await stromer.stromer_detect()
Expand Down Expand Up @@ -67,7 +69,7 @@ async def async_step_bike(
self.user_input_data["nickname"] = nickname
self.user_input_data["model"] = self.all_bikes[bike_id]["biketype"]

LOGGER.info(f"Using {selected_bike} (i.e. bike ID {bike_id} to talk to the Stromer API")
LOGGER.info(f"Using {selected_bike} (i.e. bike ID {bike_id}) to talk to the Stromer API")

await self.async_set_unique_id(f"stromerbike-{bike_id}")
self._abort_if_unique_id_configured()
Expand Down
8 changes: 8 additions & 0 deletions custom_components/stromer/stromer.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ def __init__(self, username: str, password: str, client_id: str, client_secret:
self._api_version = "v3"
self.base_url: str = "https://api3.stromer-portal.ch"

LOGGER.debug("Initializing Stromer with API version %s", self._api_version)

self._timeout: int = timeout
self._username: str = username
self._password: str = password
Expand All @@ -43,6 +45,7 @@ def __init__(self, username: str, password: str, client_id: str, client_secret:

async def stromer_connect(self) -> dict:
"""Connect to stromer API."""
LOGGER.debug("Creating aiohttp session")
aio_timeout = aiohttp.ClientTimeout(total=self._timeout)
self._websession = aiohttp.ClientSession(timeout=aio_timeout)

Expand All @@ -56,6 +59,11 @@ async def stromer_connect(self) -> dict:

return True

async def stromer_disconnect(self) -> None:
"""Close API web session."""
LOGGER.debug("Closing aiohttp session")
await self._websession.close()

async def stromer_detect(self) -> dict:
"""Get full data (to determine bike(s))."""
try:
Expand Down

0 comments on commit 18b1198

Please sign in to comment.