-
Notifications
You must be signed in to change notification settings - Fork 0
/
netFIELDWebSocketClient.js
400 lines (360 loc) · 12 KB
/
netFIELDWebSocketClient.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
const { EventEmitter } = require("events");
const WebSocket = require("ws");
const btoa = require("btoa");
const STATES = {
INITIALIZING: "initializing",
CONNECTING: "connecting",
WAITING_FOR_RECONNECT: "waiting-for-reconnect",
AUTHENTICATING: "authenticating",
AUTHENTICATED: "authenticated",
SUBSCRIBING: "subscribing",
SUBSCRIBED: "subscribed",
REVOKED: "revoked",
UNSUBSCRIBING: "unsubscribing",
UNSUBSCRIBED: "unsubscribed",
CLIENT_INITIATED_CLOSE: "client-initiated close",
CLOSED: "closed",
ERROR: "error",
};
/**
* WebSocket client to communicate with the netFIELD Proxy WebSocket.
*
* @class NetFieldProxyWebSocketClient
*/
class netFIELDWebSocketClient extends EventEmitter {
/**
*Creates an instance of NetFieldProxyWebSocketClient.
* @param {string} endpoint - WebSocket endpoint, e.g. wss://api.netfield.io/v1
* @param {string} authorization - Access token or API key.
* @param {string} deviceId - deviceId of the device running netFIELD Proxy.
* @param {string} topic -
* topic to subscribe to (plaintext, converted to base64 automatically)
* @param {string} service - can either be "netfieldproxy" or "platformconnector"
* @param {number} inactivitytimeout - maximum time in seconds for ping inactivity until connection is assumed as timed out
*/
constructor(
endpoint,
authorization,
deviceId,
topic = "#",
service = "platformconnector",
inactivitytimeout,
autoReconnect = true
) {
// extend with super()
super();
this.endpoint = endpoint;
// a random Client ID is needed
this.clientId = (Math.random() + 1).toString(36).substring(7);
// fill internal objects
this.deviceId = deviceId;
this.service = service;
this.topic = topic;
this.authorization = authorization;
this.inactivitytimeout = inactivitytimeout*1000;
this.autoReconnect = autoReconnect;
this.reconnectWaitTime_s = 1;
this._setState = this._setState.bind(this);
this._setState(STATES.INITIALIZING);
this.subscribeToTopic = this.subscribeToTopic.bind(this);
this.send = this.send.bind(this);
this.sendObject = this.sendObject.bind(this);
this.close = this.close.bind(this);
this._reconnect = this._reconnect.bind(this);
this.heartbeat = this._heartbeat.bind(this);
this.pingTimeout = null;
this.reconnectInterval = null;
// create the WebSocket object
this.wsClient = null;
this._initializeWebSocketClient();
}
/**
* Stops all pending timers just in case.
*
* @access private
*
*/
_clearAllPendingTimers() {
if(this.pingTimeout) {
clearTimeout(this.pingTimeout);
this.pingTimeout = null;
}
if(this.reconnectInterval) {
clearInterval(this.reconnectInterval);
this.reconnectInterval = null;
}
}
/**
* Sets the given state as current state of client WebSocket handler.
*
* @param {string} nextState - the state to be set as current
*
* @access private
*
*/
_setState(nextState) {
const currentState = this.state;
this.emit("stateChanged", nextState, currentState);
this.state = nextState;
}
/**
* Initializes the WebSocket client.
*
* @access private
*
* @returns { WebSocket } WebSocket client.
*/
_initializeWebSocketClient() {
this._setState(STATES.CONNECTING);
const client = new WebSocket(this.endpoint);
client.onmessage = this._messageHandler.bind(this);
client.onerror = (error) => {
try {
this.emit("error", error.message);
} catch (err) {
}
}
client.onclose = this._handleWebsocketClose.bind(this);
client.onopen = () => {
this._sayHello();
this.reconnectWaitTime_s = 1;
this.heartbeat();
};
this.wsClient = client;
}
_handleWebsocketClose(closeEvent) {
const { code, wasClean, reason } = closeEvent;
this._clearAllPendingTimers();
// let a short time pass after closing to give the caller the chance to visualize the reason of the closing
setTimeout( () => {
if (this.state === STATES.CLIENT_INITIATED_CLOSE) {
this.wsClient.terminate();
this._setState(STATES.CLOSED);
} else {
if (this.autoReconnect) {
this._reconnect();
}
}
}, 2000 );
}
/**
* Heatbeat timer triggered on each ping received.
*
*/
_heartbeat() {
clearTimeout(this.pingTimeout);
this.pingTimeout = setTimeout(() => {
this.wsClient.terminate();
this._setState(STATES.CLOSED);
}, this.inactivitytimeout );
}
/**
* Function to count down to zero to start a new try to connect.
*
*/
_reconnect() {
const MAX_RECONNECT_WAIT_TIME_S = 60;
this.reconnectWaitTime_s = Math.min(
1 + this.reconnectWaitTime_s,
MAX_RECONNECT_WAIT_TIME_S
);
this.reconnectRemainingTime_s = this.reconnectWaitTime_s;
this._setState(STATES.WAITING_FOR_RECONNECT);
this.reconnectInterval = setInterval(() => {
if(this.reconnectRemainingTime_s -= 1) {
this.emit("reConnect", this.reconnectRemainingTime_s);
} else {
clearInterval(this.reconnectInterval);
this.reconnectInterval = null;
this._initializeWebSocketClient()
}
}, 1000 );
}
/**
* Handler to be invoked on receiving a message on the WebSocket.
*
* @param { WebSocket.MessageEvent } event - WebSocket message event.
* @param { WebSocket.Data } event.data - WebSocket message data.
*
* @access private
*/
_messageHandler({ data }) {
try {
const dataObj = JSON.parse(data);
const { type, message, payload } = dataObj;
if (payload && payload.error) {
this._setState(STATES.ERROR);
try {
this.emit("error", payload.message);
} catch {
}
return;
}
if (type === "ping") {
// got a keep-alive 'ping' heartbeat from the server
this._respondToHeartbeatPing();
this.heartbeat();
return;
}
switch (this.state) {
case STATES.AUTHENTICATING:
if (type === "hello") {
// got a 'hello' response after trying to authenticate
this._setState(STATES.AUTHENTICATED);
this.subscribeToTopic(this.deviceId, this.topic);
} else {
this.emit("error", "invalid authentication response" );
this._setState(STATES.ERROR);
}
break;
case STATES.SUBSCRIBING:
if (type === "sub") {
// got a 'sub' response after successfully subscribing
this._setState(STATES.SUBSCRIBED);
} else if( type === "revoke") {
// got a 'revoke' response and subcription was denied
this._setState(STATES.REVOKED);
this.emit("revoke", message)
}
break;
case STATES.SUBSCRIBED:
if (type == "pub") {
// got a 'pub' message from the server
this.emit("data", message);
}
break;
case STATES.UNSUBSCRIBING:
if (type == "unsub") {
// successfully unsubscribed
this._setState(STATES.UNSUBSCRIBED);
}
break;
default:
break;
}
} catch (error) {
this.emit("error", error);
}
}
/**
* Subscribe to netFIELD proxy messages for the given device on the given topic.
*
* @param {string} deviceId - deviceId of the device running netFIELD Proxy.
* @param {string} topic - topic to subscribe to (plaintext, converted to base64 automatically)
*/
subscribeToTopic(deviceId, topic) {
this._setState(STATES.SUBSCRIBING);
const topicAsBase64 = btoa(topic);
const subscribePayload = {
id: this.clientId,
path: `/devices/${deviceId}/` + this.service + `/${topicAsBase64}`,
type: "sub",
};
this.sendObject(subscribePayload);
}
/**
* Unsubscribe to netFIELD proxy messages for the given device on the given topic.
*
* @param {string} deviceId - deviceId of the device running netFIELD Proxy.
* @param {string} topic - topic to subscribe to (plaintext, converted to base64 automatically)
*/
unsubscribe(deviceId, topic) {
this._setState(STATES.UNSUBSCRIBING);
const topicAsBase64 = btoa(topic);
const subscribePayload = {
id: this.clientId,
path: `/devices/${deviceId}/` + this.service + `/${topicAsBase64}`,
type: "unsub",
};
this.sendObject(subscribePayload);
}
/**
* Send a string message.
*
* @param {string} dataString - string to send.
*/
send(dataString) {
const { wsClient } = this;
if (wsClient && wsClient.readyState === WebSocket.OPEN) {
try {
// for whatever reason, sending might fail even though the WebSocket state has been checked before
wsClient.send(dataString);
} catch (err) {
}
}
}
/**
* Send a message by passing in an object which will be serialized before sending.
*
* @param {Object} dataObj - data object to send.
*/
sendObject(dataObj) {
this.send(JSON.stringify(dataObj));
}
/**
* Close indication from the calling application to close the WebSocket.
*
* @param {number} [code] - reason code
* @param {string} [data] - reason
*/
close(code, data) {
this._clearAllPendingTimers();
this.removeAllListeners();
const { wsClient } = this;
if (wsClient) {
if( wsClient.readyState === wsClient.OPEN) {
this.on("stateChanged", (state) => {
if (state === STATES.UNSUBSCRIBED)
setTimeout( () => {
this._setState(STATES.CLIENT_INITIATED_CLOSE);
this.wsClient.close(code, data);
}, 200);
});
if (this.state === STATES.SUBSCRIBED) {
this.unsubscribe(this.deviceId, this.topic);
}
} else {
wsClient.terminate();
}
}
}
/**
* Send a 'hello' message according the nes protocol which authenticates this client.
*
* https://github.com/hapijs/nes/blob/master/PROTOCOL.md#Hello
*
* @access private
*/
_sayHello() {
this._setState(STATES.AUTHENTICATING);
const helloPayload = {
type: "hello",
auth: {
headers: {
authorization: this.authorization,
},
},
id: this.clientId,
version: "2",
};
this.sendObject(helloPayload);
}
/**
* Send a heartbeat keep-alive ping response according to the nes protocol.
*
* https://github.com/hapijs/nes/blob/master/PROTOCOL.md#Heartbeat
*
* @access private
*/
_respondToHeartbeatPing() {
const pingResponsePayload = {
id: this.clientId,
type: "ping",
};
this.sendObject(pingResponsePayload);
}
}
module.exports = {
netFIELDWebSocketClient,
STATES,
};