diff --git a/lib/connection.js b/lib/connection.js index c58c90b..b6fb0c0 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -12,6 +12,7 @@ module.exports = function (ccg) { ccg.prototype.response = ""; ccg.prototype.readyForNextCommand = true; ccg.prototype.waitingForDoubleTerminator = false; + ccg.prototype.reconnectTimeout = null; // ccg.connect // ----------- @@ -41,17 +42,24 @@ module.exports = function (ccg) { if (port) self.options.port = port; if (self.options.reconnect && typeof(self.options.reconnectInterval) != "number") { - self.options.reconnectInterval = 15; + self.options.reconnectInterval = 3; } self.disconnecting = false; var client = self.client = net.connect({port: self.options.port, host: self.options.host}); + + client.on("connect", function () { self.log("Connected to", self.options.host, self.options.port); self.connected = true; + if(self.reconnectTimeout){ + clearInterval(self.reconnectTimeout) + self.reconnectTimeout = null + } + if (cb) { cb(); cb = false; @@ -67,11 +75,7 @@ module.exports = function (ccg) { self.emit("connectionError", err); - if (!self.disconnecting && self.options.reconnect) { - setTimeout(function () { - self.connect(); self.emit("reconnecting"); - }, (self.options.reconnectInterval * 1000)); - } + self.reconnect() }); client.on("reconnecting", function () { @@ -82,13 +86,8 @@ module.exports = function (ccg) { self.log("Disconnected"); self.emit("disconnected"); self.connected = false; - client = false; - if (!self.disconnecting && self.options.reconnect) { - setTimeout(function () { - self.connect(); self.emit("reconnecting"); - }, (self.options.reconnectInterval * 1000)); - } + self.reconnect() }); client.on("data", function (chunk) { @@ -172,8 +171,24 @@ module.exports = function (ccg) { finishedCommand(self); }); + + this.reconnect() }; + ccg.prototype.reconnect = function () { + let self = this + if (!self.disconnecting && self.options.reconnect && !self.reconnectTimeout) { + self.reconnectTimeout = setInterval(function () { + self.client.removeAllListeners() + self.client.end() + self.client.destroy() + self.client = false; + self.emit("reconnecting"); + self.connect(); + }, (self.options.reconnectInterval * 1000)); + } + } + // ccg.disconnect // -------------- // Empties command queue and closes connection to Caspar CG