From dd10d3e0375c936a6b5249c5ceea8a6a2e35806d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joakim=20S=C3=B8rensen?= Date: Wed, 14 Apr 2021 14:30:49 +0200 Subject: [PATCH] Guard against multiple client creations (#2809) --- supervisor/homeassistant/websocket.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/supervisor/homeassistant/websocket.py b/supervisor/homeassistant/websocket.py index 793451ae2..ca61770ae 100644 --- a/supervisor/homeassistant/websocket.py +++ b/supervisor/homeassistant/websocket.py @@ -86,17 +86,22 @@ class HomeAssistantWebSocket(CoreSysAttributes): """Initialize Home Assistant object.""" self.coresys: CoreSys = coresys self._client: Optional[WSClient] = None + self._lock: asyncio.Lock = asyncio.Lock() async def _get_ws_client(self) -> WSClient: """Return a websocket client.""" - await self.sys_homeassistant.api.ensure_access_token() - client = await WSClient.connect_with_auth( - self.sys_websession_ssl, - f"{self.sys_homeassistant.api_url}/api/websocket", - self.sys_homeassistant.api.access_token, - ) + async with self._lock: + if self._client is not None: + return self._client - return client + await self.sys_homeassistant.api.ensure_access_token() + client = await WSClient.connect_with_auth( + self.sys_websession_ssl, + f"{self.sys_homeassistant.api_url}/api/websocket", + self.sys_homeassistant.api.access_token, + ) + + return client async def async_send_command(self, message: Dict[str, Any]): """Send a command with the WS client."""