diff --git a/main.js b/main.js index ead9eaca63331a268e34cf2e8a432052a71cae12..7763ee355ff6d2346503e345a39b94bc30e949d4 100644 --- a/main.js +++ b/main.js @@ -12,7 +12,7 @@ const uuid = require('uuid'); class ModuleInstance extends InstanceBase { isInitialized = false // language=RegExp - wsRegex = '^wss?:\\/\\/([\\da-z\\.-]+)(:\\d{1,5})?(?:\\/(.*))?$' + wsRegex = '^wss?:\\/\\/([\\da-z.-]+)(:\\d{1,5})?(?:\\/(.*))?$' messageHandlers = { 'project-current': new ProjectUpdate(), @@ -39,7 +39,10 @@ class ModuleInstance extends InstanceBase { // When module gets deleted async destroy() { this.isInitialized = false - + if (this.reconnect_timer) { + clearTimeout(this.reconnect_timer) + this.reconnect_timer = null + } if (this.ws) { this.ws.close(1000) delete this.ws @@ -75,6 +78,14 @@ class ModuleInstance extends InstanceBase { tooltip: 'Log incomming and outcomming messages', width: 6, }, + { + type: 'checkbox', + id: 'reconnect', + label: 'Reconnect', + tooltip: 'Reconnect on WebSocket error (after 5 secs)', + width: 6, + default: true, + }, ] } @@ -88,6 +99,17 @@ class ModuleInstance extends InstanceBase { // Websocket handling + maybeReconnect() { + if (this.isInitialized && this.config.reconnect) { + if (this.reconnect_timer) { + clearTimeout(this.reconnect_timer) + } + this.reconnect_timer = setTimeout(() => { + this.initWebSocket() + }, 1000) + } + } + initWebSocket() { if (this.reconnect_timer) { clearTimeout(this.reconnect_timer) @@ -123,6 +145,7 @@ class ModuleInstance extends InstanceBase { this.ws.on('close', (code) => { this.log('debug', `Connection closed with code ${code}`) this.updateStatus(InstanceStatus.Disconnected, `Connection closed with code ${code}`) + this.maybeReconnect(); }) this.ws.on('message', this.messageReceivedFromWebSocket.bind(this))