Skip to content

Commit

Permalink
Fix halfopen websocket (#18934)
Browse files Browse the repository at this point in the history
* initial suggestion

* Refactored implementation

* Updated implementation

* Cancel existing inverval
  • Loading branch information
leonardmgh authored Jul 19, 2024
1 parent 1faa148 commit 677cffd
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/state/connection-mixin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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() {
Expand All @@ -293,5 +311,6 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
super.hassDisconnected();
this._updateHass({ connected: false });
broadcastConnectionStatus("disconnected");
clearInterval(this.__backendPingInterval);
}
};

0 comments on commit 677cffd

Please sign in to comment.