From 107a33b06f28129675abc687bbaffd7a74eaa8a4 Mon Sep 17 00:00:00 2001 From: Stefan Dej Date: Mon, 9 Sep 2024 22:40:08 +0200 Subject: [PATCH 1/2] feat: add heartbeat to the moonraker websocket Signed-off-by: Stefan Dej --- src/plugins/webSocketClient.ts | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/plugins/webSocketClient.ts b/src/plugins/webSocketClient.ts index 6e4820240..bb717441e 100644 --- a/src/plugins/webSocketClient.ts +++ b/src/plugins/webSocketClient.ts @@ -14,6 +14,7 @@ export class WebSocketClient { timerId: number | null = null store: Store | null = null waits: Wait[] = [] + heartbeatTimer: number | null = null constructor(options: WebSocketPluginOptions) { this.url = options.url @@ -89,7 +90,7 @@ export class WebSocketClient { isConnecting: true, }) - await this.instance?.close() + this.instance?.close() this.instance = new WebSocket(this.url) this.instance.onopen = () => { @@ -116,14 +117,19 @@ export class WebSocketClient { this.instance.onmessage = (msg) => { if (this.store === null) return + // websocket is alive + this.heartbeat() + const data = JSON.parse(msg.data) if (Array.isArray(data)) { for (const message of data) { this.handleMessage(message) } - } else { - this.handleMessage(data) + + return } + + this.handleMessage(data) } } @@ -194,6 +200,16 @@ export class WebSocketClient { this.instance.send(JSON.stringify(body)) } + + heartbeat(): void { + if (this.heartbeatTimer) clearInterval(this.heartbeatTimer) + + this.heartbeatTimer = window.setTimeout(() => { + if (this.instance?.readyState !== WebSocket.OPEN || !this.store) return + + this.close() + }, 10000) + } } export function WebSocketPlugin(Vue: typeof _Vue, options: WebSocketPluginOptions): void { From f01dd424f674b1f7a8b85878a5a73412b7fe5fba Mon Sep 17 00:00:00 2001 From: Stefan Dej Date: Wed, 11 Sep 2024 22:31:41 +0200 Subject: [PATCH 2/2] fix: close socket in store direct in the heartbeat timeout Signed-off-by: Stefan Dej --- src/plugins/webSocketClient.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/plugins/webSocketClient.ts b/src/plugins/webSocketClient.ts index bb717441e..a2a6addbc 100644 --- a/src/plugins/webSocketClient.ts +++ b/src/plugins/webSocketClient.ts @@ -208,6 +208,7 @@ export class WebSocketClient { if (this.instance?.readyState !== WebSocket.OPEN || !this.store) return this.close() + this.store?.dispatch('socket/onClose') }, 10000) } }