From 24c5613a5092fcd37d0a020002235759a024921e Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 20 Jul 2023 06:43:44 -0500 Subject: [PATCH] Switch to using the get core state api call to check if the API is up (#4445) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Joakim Sørensen Co-authored-by: Franck Nijhof --- supervisor/homeassistant/api.py | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/supervisor/homeassistant/api.py b/supervisor/homeassistant/api.py index f26d8d7d5..ed3a29ce7 100644 --- a/supervisor/homeassistant/api.py +++ b/supervisor/homeassistant/api.py @@ -7,6 +7,7 @@ from typing import Any, AsyncContextManager import aiohttp from aiohttp import hdrs +from awesomeversion import AwesomeVersion from ..coresys import CoreSys, CoreSysAttributes from ..exceptions import HomeAssistantAPIError, HomeAssistantAuthError @@ -17,6 +18,8 @@ from .const import LANDINGPAGE _LOGGER: logging.Logger = logging.getLogger(__name__) +GET_CORE_STATE_MIN_VERSION: AwesomeVersion = AwesomeVersion("2023.8.0.dev20230720") + class HomeAssistantAPI(CoreSysAttributes): """Home Assistant core object for handle it.""" @@ -106,15 +109,23 @@ class HomeAssistantAPI(CoreSysAttributes): raise HomeAssistantAPIError() - async def get_config(self) -> dict[str, Any]: - """Return Home Assistant config.""" - async with self.make_request("get", "api/config") as resp: + async def _get_json(self, path: str) -> dict[str, Any]: + """Return Home Assistant get API.""" + async with self.make_request("get", path) as resp: if resp.status in (200, 201): return await resp.json() else: _LOGGER.debug("Home Assistant API return: %d", resp.status) raise HomeAssistantAPIError() + async def get_config(self) -> dict[str, Any]: + """Return Home Assistant config.""" + return await self._get_json("api/config") + + async def get_core_state(self) -> dict[str, Any]: + """Return Home Assistant core state.""" + return await self._get_json("api/core/state") + async def check_api_state(self) -> bool: """Return True if Home Assistant up and running.""" # Skip check on landingpage @@ -134,8 +145,15 @@ class HomeAssistantAPI(CoreSysAttributes): # Check if API is up with suppress(HomeAssistantAPIError): - data = await self.get_config() + # get_core_state is available since 2023.8.0 and preferred + # since it is significantly faster than get_config because + # it does not require serializing the entire config + if self.sys_homeassistant.version >= GET_CORE_STATE_MIN_VERSION: + data = await self.get_core_state() + else: + data = await self.get_config() # Older versions of home assistant does not expose the state if data and data.get("state", "RUNNING") == "RUNNING": return True + return False