Skip to content

Commit

Permalink
Close client sessions
Browse files Browse the repository at this point in the history
Resolves

Logger: homeassistant
Source: runner.py:145
First occurred: 00:02:26 (2 occurrences)
Last logged: 00:02:26

Error doing job: Unclosed client session
  • Loading branch information
codyc1515 committed Feb 3, 2024
1 parent 0453cd1 commit bd0a8a7
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
19 changes: 16 additions & 3 deletions custom_components/managemyhealth/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,12 +228,12 @@ async def _api_wrapper(
headers=headers,
)
if response.status in (400, 401, 403):
raise MmhApiAuthenticationError(
"Invalid credentials",
)
raise MmhApiAuthenticationError()
response.raise_for_status()
return await response.json()

except MmhApiAuthenticationError as exception:
raise MmhApiAuthenticationError("Invalid credentials") from exception
except asyncio.TimeoutError as exception:
raise MmhApiCommunicationError(
"Timeout error fetching information: %s", exception
Expand All @@ -246,3 +246,16 @@ async def _api_wrapper(
raise MmhApiError(
"Something really wrong happened!: %s", exception
) from exception

async def disconnect(self) -> None:
"""Disconnect from the client."""
_LOGGER.debug("Invoked close manually")
await self.__aexit__()

async def __aexit__(self, *excinfo):
"""Destroy the device and http sessions."""
_LOGGER.debug("Invoked close automatically")
if not self._session:
return

await self._session.close()
8 changes: 8 additions & 0 deletions custom_components/managemyhealth/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from datetime import timedelta

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator,
Expand Down Expand Up @@ -40,6 +41,13 @@ def __init__(
update_interval=timedelta(minutes=30),
)

async def disconnect() -> None:
"""Close ClientSession."""
await self.api.disconnect()

# Disconnect the ClientSession on stop
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, disconnect)

async def _async_update_data(self):
"""Update data via library."""
try:
Expand Down
2 changes: 1 addition & 1 deletion custom_components/managemyhealth/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@
"documentation": "https://github.com/codyc1515/ha-managemyhealth",
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/codyc1515/ha-managemyhealth/issues",
"version": "2.1.0"
"version": "2.2.0"
}

0 comments on commit bd0a8a7

Please sign in to comment.