Skip to content

Commit

Permalink
feat: add heartbeat to the moonraker websocket (#2003)
Browse files Browse the repository at this point in the history
  • Loading branch information
meteyou authored Sep 11, 2024
1 parent 55ae60c commit f4bbe45
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/plugins/webSocketClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export class WebSocketClient {
timerId: number | null = null
store: Store<RootState> | null = null
waits: Wait[] = []
heartbeatTimer: number | null = null

constructor(options: WebSocketPluginOptions) {
this.url = options.url
Expand Down Expand Up @@ -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 = () => {
Expand All @@ -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)
}
}

Expand Down Expand Up @@ -194,6 +200,17 @@ 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()
this.store?.dispatch('socket/onClose')
}, 10000)
}
}

export function WebSocketPlugin(Vue: typeof _Vue, options: WebSocketPluginOptions): void {
Expand Down

0 comments on commit f4bbe45

Please sign in to comment.