-
Notifications
You must be signed in to change notification settings - Fork 43
/
heartbeat.js
104 lines (87 loc) · 2.22 KB
/
heartbeat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
var mbus = require('mbus');
module.exports = function(signaller, opts) {
opts = opts || {};
/**
Creates a new heartbeat
**/
function create(id) {
var heartbeat = mbus();
var delay = (typeof opts.heartbeat === 'number' ? opts.heartbeat : 2500);
var ignoreDisconnection = (opts || {}).ignoreDisconnection || false; //if you want to rely on your switchboard to tell if the call is still going
var timer = null;
var connected = false;
var lastping = 0;
/**
Pings the target peer
**/
function ping() {
signaller.to(id).send('/ping');
}
/**
Checks the state of the signaller connection
**/
function check() {
if (!heartbeat) return;
var tickInactive = (Date.now() - (delay * 4)); //doesnt always work
var currentlyConnected = ignoreDisconnection ? ignoreDisconnection : (lastping >= tickInactive);
// If we have changed connection state, flag the change
if (connected !== currentlyConnected) {
heartbeat(currentlyConnected ? 'connected' : 'disconnected');
heartbeat('signalling:state', currentlyConnected);
connected = currentlyConnected;
}
}
/**
Checks the state of the connection, and pings as well
**/
function beat() {
check();
ping();
}
/**
Starts the heartbeat
**/
heartbeat.start = function() {
if (timer) heartbeat.stop();
if (delay <= 0) return;
timer = setInterval(beat, delay);
beat();
};
/**
Stops the heartbeat
**/
heartbeat.stop = function() {
if (!timer) return;
clearInterval(timer);
timer = null;
};
/**
Destroys the heartbeat
**/
heartbeat.destroy = function() {
// Stop the heartbeat
heartbeat.stop();
// Destroy the mbus events
heartbeat.clear();
}
/**
Registers the receipt on a ping
**/
heartbeat.touch = function() {
lastping = Date.now();
check();
};
/**
Updates the delay interval
**/
heartbeat.updateDelay = function(value) {
delay = value;
heartbeat.start();
};
heartbeat.start();
return heartbeat;
}
return {
create: create
};
};