Fix halfopen websocket (#18934)

* initial suggestion

* Refactored implementation

* Updated implementation

* Cancel existing inverval
This commit is contained in:
leonardmgh 2024-07-19 12:07:55 +02:00 committed by GitHub
parent 1faa1480e4
commit 677cffd650
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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 = <T extends Constructor<HassBaseEl>>(
superClass: T
) =>
class extends superClass {
private __backendPingInterval?: ReturnType<typeof setInterval>;
protected initializeHass(auth: Auth, conn: Connection) {
const language = getLocalLanguage();
@ -269,6 +272,21 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
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 = <T extends Constructor<HassBaseEl>>(
super.hassDisconnected();
this._updateHass({ connected: false });
broadcastConnectionStatus("disconnected");
clearInterval(this.__backendPingInterval);
}
};