Skip to content

Commit 12e7b79

Browse files
authored
Merge pull request #36 from neojski/make-heartbeat-interval-configurable
Make heartbeat interval configurable
2 parents b497de0 + 77f13a2 commit 12e7b79

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/device.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,10 @@ class Device extends EventEmitter implements Device {
2525

2626
private _lastHeartbeat: Date;
2727

28-
constructor({ip, id, gwId = id, key, version = 3.1, port = 6668}: {
29-
ip: string; port?: number; key: string; id: string; gwId?: string; version?: number;
28+
private readonly _heartbeatInterval: number;
29+
30+
constructor({ip, id, gwId = id, key, version = 3.1, port = 6668, heartbeatInterval = 1000}: {
31+
ip: string; port?: number; key: string; id: string; gwId?: string; version?: number; heartbeatInterval?: number;
3032
}) {
3133
super();
3234

@@ -53,6 +55,9 @@ class Device extends EventEmitter implements Device {
5355
// Set last heartbeat
5456
this._lastHeartbeat = new Date();
5557

58+
// Set up heartbeating interval
59+
this._heartbeatInterval = heartbeatInterval;
60+
5661
// Set up socket handlers
5762
this._socket.on('connect', this._handleSocketConnect.bind(this));
5863
this._socket.on('close', this._handleSocketClose.bind(this));
@@ -124,8 +129,7 @@ class Device extends EventEmitter implements Device {
124129
}
125130

126131
private _recursiveHeartbeat(): void {
127-
// TODO: variable timeout, i.e. this.heartbeatTimeout = 2000
128-
if (new Date().getTime() - this._lastHeartbeat.getTime() > 2000) {
132+
if (new Date().getTime() - this._lastHeartbeat.getTime() > this._heartbeatInterval * 2) {
129133
// Heartbeat timeout
130134
// Should we emit error on timeout?
131135
return this.disconnect();
@@ -137,7 +141,7 @@ class Device extends EventEmitter implements Device {
137141

138142
this.send(this._messenger.encode(frame));
139143

140-
setTimeout(this._recursiveHeartbeat.bind(this), 1000);
144+
setTimeout(this._recursiveHeartbeat.bind(this), this._heartbeatInterval);
141145
}
142146

143147
private _handleSocketConnect(): void {

0 commit comments

Comments
 (0)