Skip to content

Commit

Permalink
Rework heartbeat logic to be more robust
Browse files Browse the repository at this point in the history
  • Loading branch information
Sam Day committed Apr 9, 2015
1 parent 527c7cf commit cb3df25
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions lib/controllers/heartbeat.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ var TIMEOUT_FACTOR = 3; // timeouts after 3 intervals
function HeartbeatController(client, sourceId, destinationId) {
JsonController.call(this, client, sourceId, destinationId, 'urn:x-cast:com.google.cast.tp.heartbeat');

this.interval = null;
this.pingTimer = null;
this.timeout = null;
this.intervalValue = DEFAULT_INTERVAL;

Expand All @@ -35,16 +35,24 @@ util.inherits(HeartbeatController, JsonController);
HeartbeatController.prototype.ping = function() {
var self = this;

this.once('pong', onpong);

function onpong() {
clearTimeout(self.timeout);
self.timeout = setTimeout(ontimeout, self.intervalValue * 1000 * TIMEOUT_FACTOR);
if (this.timeout) {
// We already have a ping in progress.
return;
}

function ontimeout() {
this.timeout = setTimeout(function ontimeout() {
self.emit('timeout');
}
}, self.intervalValue * 1000 * TIMEOUT_FACTOR);

this.once('pong', function onpong() {
clearTimeout(self.timeout);
self.timeout = null;

self.pingTimer = setTimeout(function() {
self.pingTimer = null;
self.ping();
}, self.intervalValue * 1000);
});

this.send({ type: 'PING' });
};
Expand All @@ -56,17 +64,17 @@ HeartbeatController.prototype.start = function(intervalValue) {
this.intervalValue = intervalValue;
}

function oninterval() {
self.ping();
}

this.interval = setInterval(oninterval, this.intervalValue * 1000);
this.ping();
};

HeartbeatController.prototype.stop = function() {
clearInterval(this.interval);
clearTimeout(this.timeout);
if (this.pingTimer) {
clearTimeout(this.pingTimer);
}
if (this.timeout) {
clearTimeout(this.timeout);
}
this.removeAllListeners('pong');
};

module.exports = HeartbeatController;

0 comments on commit cb3df25

Please sign in to comment.