-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path8dev_restapi.js
More file actions
816 lines (764 loc) · 24.1 KB
/
8dev_restapi.js
File metadata and controls
816 lines (764 loc) · 24.1 KB
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
const EventEmitter = require('events');
const rest = require('node-rest-client');
const express = require('express');
const parser = require('body-parser');
const ip = require('ip');
/**
* This class represents device (endpoint).
* @example
* const restAPI = require('restserver-api');
*
* const service = new restAPI.Service(serviceOptions);
* const device = new restAPI.Device(service, 'deviceId');
*/
class Device extends EventEmitter {
/**
* Constructor initiliazes given service object, device's id
* and starts listening for events emited by service (when device
* registers, updates, deregisters, sends data), handles "async
* responses" and emits "register", "update", "deregister" events.
* @constructor
* @param {object} service - Service object
* @param {string} id - Endpoint id
*/
constructor(service, id) {
super();
this.service = service;
this.id = id;
this.transactions = {};
this.observations = {};
this.service.on('register', (name) => {
if (this.id === name) {
this.emit('register');
}
});
this.service.on('update', (name) => {
if (this.id === name) {
this.emit('update');
}
});
this.service.on('deregister', (name) => {
if (this.id === name) {
this.emit('deregister');
}
});
this.service.on('async-response', (resp) => {
const ID = resp.id;
const code = resp.status;
const data = resp.payload;
if (this.transactions[ID] !== undefined) {
this.transactions[ID](code, data);
delete this.transactions[ID];
}
if (this.observations[ID] !== undefined) {
this.observations[ID](code, data);
}
});
}
/**
* Sends request to get all device's objects.
* @returns {Promise} Promise object with device's objects
* @example
* device.getObjects().then((resp) => {
* // resp = [ { uri: '/1/0' }, { uri: '/2/0' }, ... ]
* }).catch((err) => {
* // err - exception message object or status code
* });
*/
getObjects() {
return new Promise((fulfill, reject) => {
this.service.get(`/endpoints/${this.id}`).then((dataAndResponse) => {
if (dataAndResponse.resp.statusCode === 200) {
fulfill(dataAndResponse.data);
} else {
reject(dataAndResponse.resp.statusCode);
}
}).catch((err) => {
reject(err);
});
});
}
/**
* Adds a callback to transactions list.
* Key value is device's id.
* @private
* @param {string} id - Endpoint id
* @param {function} callback - Callback which will be called when async response is received
* @return {void}
*/
addAsyncCallback(id, callback) {
this.transactions[id] = callback;
}
/**
* Sends request to read device's resource data.
* @param {string} path - Resource path
* @param {function} callback - Callback which will be called when async response is received
* @returns {Promise} Promise with async response id
* @example
* device.read(path, (status, payload) => {
* // status = 200
* // payload = 4RbaAA==
* }).then((asyncResponseId) => {
* // asyncResponseId = 1533889157#42f26784-1a8d-4861-36aa-d88f
* }).catch((err) => {
* // err - exception object or status code
* });
*/
read(path, callback) {
return new Promise((fulfill, reject) => {
this.service.get(`/endpoints/${this.id}${path}`).then((dataAndResponse) => {
if (dataAndResponse.resp.statusCode === 202) {
const id = dataAndResponse.data['async-response-id'];
this.addAsyncCallback(id, callback);
fulfill(id);
} else {
reject(dataAndResponse.resp.statusCode);
}
}).catch((err) => {
reject(err);
});
});
}
/**
* Sends request to write a value into device's resource.
* @param {string} path - Resource path
* @param {function} callback - Callback which will be called when async response is received
* @param {buffer} payload - Data (optional)
* @param {string} type - Content type (optional)
* @returns {Promise} Promise with async response id
* @example
* device.write(path, (status) => {
* // status = 202
* }, payload).then((asyncResponseId) => {
* // asyncResponseId = 1533889926#870a3f17-3e21-b6ad-f63d-5cfe
* }).catch((err) => {
* // err - exception object or status code
* });
*/
write(path, callback, payload, type = 'application/vnd.oma.lwm2m+tlv') {
return new Promise((fulfill, reject) => {
this.service.put(`/endpoints/${this.id}${path}`, payload, type).then((dataAndResponse) => {
if (dataAndResponse.resp.statusCode === 202) {
const id = dataAndResponse.data['async-response-id'];
this.addAsyncCallback(id, callback);
fulfill(id);
} else {
reject(dataAndResponse.resp.statusCode);
}
}).catch((err) => {
reject(err);
});
});
}
/**
* Sends request to execute device's resource.
* @param {string} path - Resource path
* @param {function} callback - Callback which will be called when async response is received
* @param {buffer} payload - Data (optional)
* @param {string} type - Content type (optional)
* @returns {Promise} Promise with async response id
* @example
* device.execute(path, (status) => {
* // status = 202
* }).then((asyncResponseId) => {
* // asyncResponseId = 1533889926#870a3f17-3e21-b6ad-f63d-5cfe
* }).catch((err) => {
* // err - exception object or status code
* });
*/
execute(path, callback, payload, type = 'text/plain') {
return new Promise((fulfill, reject) => {
this.service.post(`/endpoints/${this.id}${path}`, payload, type).then((dataAndResponse) => {
if (dataAndResponse.resp.statusCode === 202) {
const id = dataAndResponse.data['async-response-id'];
this.addAsyncCallback(id, callback);
fulfill(id);
} else {
reject(dataAndResponse.resp.statusCode);
}
}).catch((err) => {
reject(err);
});
});
}
/**
* Sends request to subscribe to resource.
* @param {string} path - Resource path
* @param {function} callback - Callback which will be called when async response is received
* @returns {Promise} Promise with async response id
* @example
* device.observe(path, (status, payload) => {
* // status = 200
* // payload = 4RbaAA==
* }).then((asyncResponseId) => {
* // asyncResponseId = 1533889157#42f26784-1a8d-4861-36aa-d88f
* }).catch((err) => {
* // err - exception object or status code
* });
*/
observe(path, callback) {
return new Promise((fulfill, reject) => {
this.service.put(`/subscriptions/${this.id}${path}`).then((dataAndResponse) => {
if (dataAndResponse.resp.statusCode === 202) {
const id = dataAndResponse.data['async-response-id'];
this.observations[id] = callback;
fulfill(id);
} else {
reject(dataAndResponse.resp.statusCode);
}
}).catch((err) => {
reject(err);
});
});
}
/**
* Sends request to cancel subscriptions.
* @param {string} path - Resource path
* @returns {Promise} Promise with HTTP status code
* @example
* device.cancelObserve(path).then((status) => {
* // status - status code
* }).catch((err) => {
* // err - exception object
* });
*/
cancelObserve(path) {
return new Promise((fulfill, reject) => {
this.service.delete(`/subscriptions/${this.id}${path}`).then((dataAndResponse) => {
// Promise is fulfilled with any status code.
// 204 means observation will be succesfully cancelled.
// 404 means observation will not be deleted because it was not registered or found.
fulfill(dataAndResponse.resp.statusCode);
}).catch((err) => {
reject(err);
});
});
}
}
/**
* This class represents REST API service.
* @example
* const options = {
* // REST server's address
* host: 'http://localhost:8888',
* // CA certificate
* ca: '',
* // authentication (true or false)
* authentication: false,
* username: '',
* password: '',
* // notification polling (true or false)
* polling: false,
* // time between each poll in miliseconds
* interval: 1234,
* // port for socket listener (not relevant if polling is enabled)
* port: 5728,
* };
* new Service(options);
*/
class Service extends EventEmitter {
/**
* Initializes default configurations. Reconfigures with given options.
* @constructor
* @param {object} opts - Options object (optional)
*/
constructor(opts) {
super();
this.config = {
host: 'http://localhost:8888',
ca: '',
authentication: false,
username: '',
password: '',
interval: 1234,
polling: false,
port: 5728,
};
this.authenticationToken = '';
this.tokenValidation = 3600;
if (opts !== undefined) {
this.configure(opts);
}
this.ipAddress = ip.address();
this.configureNodeRestClient();
this.addTlvSerializer();
this.express = express();
this.express.use(parser.json());
}
/**
* Configures service configuration with given options.
* @private
* @param {object} opts - Options object
* @return {void}
*/
configure(opts) {
Object.keys(opts).forEach((opt) => {
this.config[opt] = opts[opt];
});
}
/**
* Initializes node rest client.
* @private
* @return {void}
*/
configureNodeRestClient() {
const opts = {
ca: this.config.ca
};
this.client = new rest.Client({ connection: opts });
}
/**
* (Re)starts authentication,
* socket listener creation and notification callback registration
* or notification polling processes.
* @example
* service.start().then(() => {
* // started service
* }).catch((err) => {
* // err - exception object
* });
* @example <caption>Passing options object</caption>
* const options = {
* // REST server's address
* host: 'http://localhost:8888',
* // CA certificate
* ca: '',
* // authentication (true or false)
* authentication: false,
* username: '',
* password: '',
* // notification polling (true or false)
* polling: false,
* // time between each poll in miliseconds
* interval: 1234,
* // port for socket listener (not relevant if polling is enabled)
* port: 5728,
* };
* service.start(options);
* @param {object} opts - Options object (optional)
* @returns {Promise} Promise which fulfills when service is started
*/
start(opts) {
return new Promise((fulfill, reject) => {
const promises = [];
promises.push(this.stop());
if (opts !== undefined) {
this.configure(opts);
}
if (this.config.authentication) {
const authenticatePromise = this.authenticate().then((data) => {
this.authenticationToken = data.access_token;
this.tokenValidation = data.expires_in;
const authenticateTime = 0.9 * (this.tokenValidation * 1000);
this.authenticateTimer = setInterval(() => {
this.authenticate().then((newData) => {
this.authenticationToken = newData.access_token;
}).catch((err) => {
console.error(`Failed to authenticate user: ${err}`);
});
}, authenticateTime);
}).catch((err) => {
console.error(`Failed to authenticate user: ${err}`);
reject(err);
});
promises.push(authenticatePromise);
}
Promise.all(promises).then(() => {
if (!this.config.polling) {
this.createServer().catch((err) => {
console.error(`Failed to create socket listener: ${err}`);
reject(err);
}).then(() => this.registerNotificationCallback()).catch((err) => {
console.error(`Failed to set notification callback: ${err}`);
reject(err);
})
.then(() => {
fulfill();
});
} else {
this.pollTimer = setInterval(() => {
this.pullNotification().then((data) => {
this._processEvents(data);
}).catch((err) => {
console.error(`Failed to pull notifications: ${err}`);
});
}, this.config.interval);
fulfill();
}
});
});
}
/**
* Stops receiving and processing events
* Stops this service and all it's subservices
* that were started in start().
* Cleans up resources
* @returns {Promise} Promise which fulfills when service is stopped
* @example
* service.stop().then(() => {
* // stopped service
* });
*/
stop() {
const promises = [];
if (this.authenticateTimer !== undefined) {
clearInterval(this.authenticateTimer);
this.authenticateTimer = undefined;
}
if (this.server !== undefined) {
this.server.close();
this.server = undefined;
promises.push(this.deleteNotificationCallback());
}
if (this.pollTimer !== undefined) {
clearInterval(this.pollTimer);
this.pollTimer = undefined;
}
return Promise.all(promises);
}
/**
* Creates socket listener.
* @private
* @returns {Promise} Promise which fulfills when socket listener is created
*/
createServer() {
return new Promise((fulfill, reject) => {
this.express.put('/notification', (req, resp) => {
this._processEvents(req.body);
resp.send();
});
this.server = this.express.listen(this.config.port, fulfill);
this.server.on('error', reject);
});
}
/**
* Sends request to authenticate user.
* @returns {Promise} Promise with authentication data (token and after what time it expires)
* @example
* service.authenticate().then((resp) => {
* // resp = { access_token: 'token-value', expires_in: 3600 }
* }).catch((err) => {
* // err - exception message object or status code
* });
*/
authenticate() {
return new Promise((fulfill, reject) => {
const data = {
name: this.config.username,
secret: this.config.password
};
const type = 'application/json';
this.post('/authenticate', data, type).then((dataAndResponse) => {
if (dataAndResponse.resp.statusCode === 201) {
fulfill(dataAndResponse.data);
} else {
reject(dataAndResponse.resp.statusCode);
}
}).catch((err) => {
reject(err);
});
});
}
/**
* Sends request to register notification callback.
* @returns {Promise} Promise which fulfills when notification callback is registered
* @example
* service.registerNotificationCallback().then(() => {
* // notification callback has been registered
* }).catch((err) => {
* // err - exception object or status code
* });
*/
registerNotificationCallback() {
return new Promise((fulfill, reject) => {
const data = {
url: `http://${this.ipAddress}:${this.config.port}/notification`,
headers: {},
};
const type = 'application/json';
this.put('/notification/callback', data, type).then((dataAndResponse) => {
if (dataAndResponse.resp.statusCode === 204) {
fulfill(dataAndResponse.data);
} else {
reject(dataAndResponse.resp.statusCode);
}
}).catch((err) => {
reject(err);
});
});
}
/**
* Sends request to delete notification callback.
* @returns {Promise} Promise with HTTP status code
* @example
* service.deleteNotificationCallback().then((status) => {
* // status - status code
* }).catch((err) => {
* // err - exception object
* });
*/
deleteNotificationCallback() {
return new Promise((fulfill, reject) => {
this.delete('/notification/callback').then((dataAndResponse) => {
// Promise is fulfilled with any status code.
// 204 means callback will be succesfully removed.
// 404 means callback will not be removed because it was not registered or found.
fulfill(dataAndResponse.resp.statusCode);
}).catch((err) => {
reject(err);
});
});
}
/**
* Sends request to check whether or not notification callback is registered.
* @returns {Promise} Promise with notification callback data
* @example
* service.checkNotificationCallback().then((resp) => {
* // resp = { url: 'http://localhost:5728/notification', headers: {} }
* }).catch((err) => {
* // err - exception message object or status code
* });
*/
checkNotificationCallback() {
return new Promise((fulfill, reject) => {
this.get('/notification/callback').then((dataAndResponse) => {
if (dataAndResponse.resp.statusCode === 200) {
if (dataAndResponse.data.url === `http://${this.ipAddress}:${this.config.port}/notification`) {
fulfill(dataAndResponse.data);
} else {
const err = new Error('Notification callback does not match current configuration');
err.code = 'EINVALIDCALLBACK';
reject(err);
}
} else {
reject(dataAndResponse.resp.statusCode);
}
}).catch((err) => {
reject(err);
});
});
}
/**
* Sends request to get pending/queued notifications.
* @returns {Promise} Promise with notification data (registrations,
* deregistrations, updates, async responses)
* @example
* service.pullNotification().then((resp) => {
* // resp = { registrations: [...], 'reg-updates': [...], ... }
* }).catch((err) => {
* // err - exception object
* });
*/
pullNotification() {
return new Promise((fulfill, reject) => {
this.get('/notification/pull').then((dataAndResponse) => {
fulfill(dataAndResponse.data);
}).catch((err) => {
reject(err);
});
});
}
/**
* Sends request to get all registered endpoints.
* @returns {Promise} Promise with a list of endpoints
* @example
* service.getDevices().then((resp) => {
* // resp = [ { name: 'uuid-4567', type: '8dev_3700', ... }, ... ]
* }).catch((err) => {
* // err - exception message object or status code
* });
*/
getDevices() {
return new Promise((fulfill, reject) => {
this.get('/endpoints').then((dataAndResponse) => {
if (dataAndResponse.resp.statusCode === 200) {
fulfill(dataAndResponse.data);
} else {
reject(dataAndResponse.resp.statusCode);
}
}).catch((err) => {
reject(err);
});
});
}
/**
* Sends request to get REST server version.
* @returns {Promise} Promise with REST server's version
* @example
* service.getVersion().then((resp) => {
* // resp = '1.0.0'
* }).catch((err) => {
* // err - exception object
* });
*/
getVersion() {
return new Promise((fulfill, reject) => {
this.get('/version').then((dataAndResponse) => {
fulfill(dataAndResponse.data);
}).catch((err) => {
reject(err);
});
});
}
/**
* Adds TLV serializer to rest client.
* @private
* @return {void}
*/
addTlvSerializer() {
this.client.serializers.add({
name: 'buffer-serializer',
isDefault: false,
match: request => request.headers['Content-Type'] === 'application/vnd.oma.lwm2m+tlv',
serialize: (data, nrcEventEmitter, serializedCallback) => {
if (data instanceof Buffer) {
nrcEventEmitter('serialized', data);
serializedCallback(data);
}
},
});
}
/**
* Performs GET requests with given path.
* @param {string} path - Request path
* @returns {Promise} Promise with data and response object
* @example
* service.get(path).then((dataAndResponse) => {
* // dataAndResponse.data - data object
* // dataAndResponse.resp - response object
* }).catch((err) => {
* // err - exception object
* });
*/
get(path) {
return new Promise((fulfill, reject) => {
const url = this.config.host + path;
const args = {};
args.headers = {};
if (this.config.authentication) {
args.headers.Authorization = `Bearer ${this.authenticationToken}`;
}
const getRequest = this.client.get(url, args, (data, resp) => {
const dataAndResponse = {};
dataAndResponse.data = data;
dataAndResponse.resp = resp;
fulfill(dataAndResponse);
});
getRequest.on('error', (err) => {
reject(err);
});
});
}
/**
* Performs PUT requests with given path, data and data type.
* @param {string} path - Request path
* @param {object} argument - Data which will be sent (optional)
* @param {string} type - Data type (optional)
* @returns {Promise} Promise with data and response object
*/
put(path, argument, type = 'application/vnd.oma.lwm2m+tlv') {
return new Promise((fulfill, reject) => {
const url = this.config.host + path;
const args = {};
args.headers = {};
if (argument !== undefined) {
args.headers['Content-Type'] = type;
args.data = argument;
}
if (this.config.authentication) {
args.headers.Authorization = `Bearer ${this.authenticationToken}`;
}
const putRequest = this.client.put(url, args, (data, resp) => {
const dataAndResponse = {};
dataAndResponse.data = data;
dataAndResponse.resp = resp;
fulfill(dataAndResponse);
});
putRequest.on('error', (err) => {
reject(err);
});
});
}
/**
* Performs DELETE requests with given path.
* @param {string} path - Request path
* @returns {Promise} Promise with data and response object
*/
delete(path) {
return new Promise((fulfill, reject) => {
const url = this.config.host + path;
const args = {};
args.headers = {};
if (this.config.authentication) {
args.headers.Authorization = `Bearer ${this.authenticationToken}`;
}
const deleteRequest = this.client.delete(url, args, (data, resp) => {
const dataAndResponse = {};
dataAndResponse.data = data;
dataAndResponse.resp = resp;
fulfill(dataAndResponse);
});
deleteRequest.on('error', (err) => {
reject(err);
});
});
}
/**
* Performs POST requests with given path, data and data type.
* @param {string} path - Request path
* @param {object} argument - Data which will be sent (optional)
* @param {string} type - Data type (optional)
* @returns {Promise} Promise with data and response object
*/
post(path, argument, type = 'application/vnd.oma.lwm2m+tlv') {
return new Promise((fulfill, reject) => {
const url = this.config.host + path;
const args = {};
args.headers = {};
if (argument !== undefined) {
args.headers['Content-Type'] = type;
args.data = argument;
}
if (this.config.authentication) {
args.headers.Authorization = `Bearer ${this.authenticationToken}`;
}
const postRequest = this.client.post(url, args, (data, resp) => {
const dataAndResponse = {};
dataAndResponse.data = data;
dataAndResponse.resp = resp;
fulfill(dataAndResponse);
});
postRequest.on('error', (err) => {
reject(err);
});
});
}
/**
* Handles notification data and emits events.
* @private
* @param {object} events - Notifications (registrations,
* reg-updates, de-registrations, async-responses)
* @return {void}
*/
_processEvents(events) {
for (let i = 0; i < events.registrations.length; i += 1) {
const id = events.registrations[i].name;
this.emit('register', id);
}
for (let i = 0; i < events['reg-updates'].length; i += 1) {
const id = events['reg-updates'][i].name;
this.emit('update', id);
}
for (let i = 0; i < events['de-registrations'].length; i += 1) {
const id = events['de-registrations'][i].name;
this.emit('deregister', id);
}
const responses = events['async-responses'].sort((x, y) => x.timestamp - y.timestamp);
for (let i = 0; i < responses.length; i += 1) {
const res = responses[i];
this.emit('async-response', res);
}
}
}
module.exports.Service = Service;
module.exports.Device = Device;