forked from normen/homebridge-433-arduino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket-client.js
79 lines (77 loc) · 2.26 KB
/
websocket-client.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
const WebSocket = require('ws');
function WebSocketClient (log) {
this.log = log;
this.number = 0; // Message number
this.autoReconnectInterval = 20 * 1000; // ms
this.pongReturned = true;
}
WebSocketClient.prototype.open = function (url) {
const self = this;
this.url = url;
this.instance = new WebSocket(this.url);
this.instance.on('open', () => {
this.onopen();
self.pongReturned = true;
self.checkPing();
});
this.instance.on('message', (data, flags) => {
this.number++;
this.onmessage(data, flags, this.number);
});
this.instance.on('close', (e) => {
switch (e.code) {
case 1000: // CLOSE_NORMAL
this.reconnect(e);
break;
default: // Abnormal closure
this.reconnect(e);
break;
}
this.onclose(e);
});
this.instance.on('error', (e) => {
switch (e.code) {
case 'ECONNREFUSED':
this.reconnect(e);
break;
default:
this.reconnect(e);
break;
}
this.onerror(e);
});
this.instance.on('pong', (e) => {
self.pongReturned = true;
});
};
WebSocketClient.prototype.checkPing = function () {
if (!this.pongReturned) {
this.instance.terminate();
} else {
this.pongReturned = false;
this.instance.ping('ping');
clearTimeout(this.pingTimeout);
this.pingTimeout = setTimeout(this.checkPing.bind(this), this.autoReconnectInterval);
}
};
WebSocketClient.prototype.send = function (data, option) {
try {
this.instance.send(data, option);
} catch (e) {
this.instance.emit('error', e);
}
};
WebSocketClient.prototype.reconnect = function (e) {
const self = this;
this.instance.removeAllListeners();
var that = this;
setTimeout(function () {
self.log('WebSocketClient: reconnecting...');
that.open(that.url);
}, this.autoReconnectInterval);
};
WebSocketClient.prototype.onopen = function (e) { this.log('WebSocketClient: open', arguments); };
WebSocketClient.prototype.onmessage = function (data, flags, number) { this.log('WebSocketClient: message', arguments); };
WebSocketClient.prototype.onerror = function (e) { this.log('WebSocketClient: error', arguments); };
WebSocketClient.prototype.onclose = function (e) { this.log('WebSocketClient: closed', arguments); };
module.exports = WebSocketClient;