From 677cffd650d67633e7edb8add30dc7362842ad02 Mon Sep 17 00:00:00 2001 From: leonardmgh Date: Fri, 19 Jul 2024 12:07:55 +0200 Subject: [PATCH] Fix halfopen websocket (#18934) * initial suggestion * Refactored implementation * Updated implementation * Cancel existing inverval --- src/state/connection-mixin.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/state/connection-mixin.ts b/src/state/connection-mixin.ts index ff74eed37a5f..2f6525d4f71e 100644 --- a/src/state/connection-mixin.ts +++ b/src/state/connection-mixin.ts @@ -33,11 +33,14 @@ 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 { + private __backendPingInterval?: ReturnType; + protected initializeHass(auth: Auth, conn: Connection) { const language = getLocalLanguage(); @@ -269,6 +272,21 @@ export const connectionMixin = >( subscribeFrontendUserData(conn, "core", (userData) => this._updateHass({ userData }) ); + + clearInterval(this.__backendPingInterval); + this.__backendPingInterval = setInterval(() => { + if (this.hass?.connected) { + promiseTimeout(5000, this.hass?.connection.ping()).catch(() => { + if (!this.hass?.connected) { + return; + } + + // eslint-disable-next-line no-console + console.log("Websocket died, forcing reconnect..."); + this.hass?.connection.reconnect(true); + }); + } + }, 10000); } protected hassReconnected() { @@ -293,5 +311,6 @@ export const connectionMixin = >( super.hassDisconnected(); this._updateHass({ connected: false }); broadcastConnectionStatus("disconnected"); + clearInterval(this.__backendPingInterval); } };