From f5bff44e94db21d5edb0e5d20f6aa4170a10cfd5 Mon Sep 17 00:00:00 2001 From: leonardmgh Date: Wed, 6 Dec 2023 21:18:06 +0000 Subject: [PATCH] Refactored implementation --- src/state/connection-mixin.ts | 36 ++++++++++++++--------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/src/state/connection-mixin.ts b/src/state/connection-mixin.ts index 1e27828a46..5f8b11d70e 100644 --- a/src/state/connection-mixin.ts +++ b/src/state/connection-mixin.ts @@ -33,13 +33,12 @@ import { fetchWithAuth } from "../util/fetch-with-auth"; import { getState } from "../util/ha-pref-storage"; import hassCallApi from "../util/hass-call-api"; import { HassBaseEl } from "./hass-base-mixin"; +import { promiseTimeout } from "../common/util/promise-timeout"; export const connectionMixin = >( superClass: T ) => class extends superClass { - pingInterval: ReturnType | undefined; - protected initializeHass(auth: Auth, conn: Connection) { const language = getLocalLanguage(); @@ -278,29 +277,22 @@ export const connectionMixin = >( this._updateHass({ userData }) ); - if (this.pingInterval !== undefined) { - clearInterval(this.pingInterval); - } + const pingBackend = async () => { + if (this.hass?.connected) { + promiseTimeout(5000, this.hass?.connection.ping()).catch(() => { + if (!this.hass?.connected) { + return; + } - this.pingInterval = setInterval(async () => { - // eslint-disable-next-line no-console - console.log("This function is called periodically."); - - if (!this.hass!.connected) { - return; + // eslint-disable-next-line no-console + console.log("Websocket died, forcing reconnect..."); + this.hass?.connection.reconnect(true); + }); } + setTimeout(pingBackend, 5000); + }; - // Force reconnection since socket in some cases can be closed gracefully - const timeout = setTimeout(() => { - if (!this.hass?.connected) { - return; - } - this.hass?.connection.reconnect(true); - }, 5000); - - await this.hass?.connection.ping(); - clearTimeout(timeout); - }, 20000); + pingBackend(); } protected hassReconnected() {