-
Notifications
You must be signed in to change notification settings - Fork 4
/
fiwareDeviceSimulator.js
1388 lines (1318 loc) · 45.6 KB
/
fiwareDeviceSimulator.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
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2016 Telefónica Investigación y Desarrollo, S.A.U
*
* This file is part of the Short Time Historic (STH) component
*
* STH is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* STH is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with STH.
* If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with: [[email protected]]
*/
'use strict';
var ROOT_PATH = require('app-root-path');
var async = require('async');
var EventEmitter = require('events').EventEmitter;
var lolex = require('lolex');
var mqtt = require('mqtt');
var npmInstall = require('npm-install-package');
var scheduler = require('node-schedule');
var request = require('request');
var time = require('time');
var linearInterpolator = require(ROOT_PATH + '/lib/interpolators/linearInterpolator');
var randomLinearInterpolator = require(ROOT_PATH + '/lib/interpolators/randomLinearInterpolator');
var stepBeforeInterpolator = require(ROOT_PATH + '/lib/interpolators/stepBeforeInterpolator');
var stepAfterInterpolator = require(ROOT_PATH + '/lib/interpolators/stepAfterInterpolator');
var dateIncrementInterpolator = require(ROOT_PATH + '/lib/interpolators/dateIncrementInterpolator');
var multilinePositionInterpolator = require(ROOT_PATH + '/lib/interpolators/multilinePositionInterpolator');
var textRotationInterpolator = require(ROOT_PATH + '/lib/interpolators/textRotationInterpolator');
var attributeFunctionInterpolator = require(ROOT_PATH + '/lib/interpolators/attributeFunctionInterpolator');
var fdsErrors = require(ROOT_PATH + '/lib/errors/fdsErrors');
var fiwareDeviceSimulatorTranspiler = require(ROOT_PATH + '/lib/transpilers/fiwareDeviceSimulatorTranspiler');
var fiwareDeviceSimulatorValidator = require(ROOT_PATH + '/lib/validators/fiwareDeviceSimulatorValidator');
/**
* The loaded configuration
*/
var configuration;
/**
* The lolex clock
*/
var clock;
/**
* The maximum number of not responded update requests before appllying delays
* @type {Number}
*/
var maximumNotRespondedUpdateRequests = 0;
/**
* Delay between requests for a fast-forward simulation
*/
var delay;
/**
* The starting date for a fast-forward simulation
*/
var fromDate;
/**
* The ending date for a fast-forward simulation
*/
var toDate;
/**
* The real starting date for a fast-forward simulation
*/
var realFromDate;
/**
* The progress interval object returned by setInterval()
*/
var progressIntervalObj;
/**
* The MQTT client
*/
var mqttClient;
/**
* Flag indicating if the MQTT client is connected
* @type {Boolean}
*/
var isMQTTClientConnected = false;
/**
* EventEmitter object returned to notify the evolution of the simulation
*/
var eventEmitter = new EventEmitter();
/**
* Flag indicating if the jobs have been already scheduled
* @type {Boolean}
*/
var areJobsScheduled = false;
/**
* Array of update scheduled jobs
* @type {Array}
*/
var updateJobs = [];
/**
* Flag indicating if the current simulation has already ended
* @type {Boolean}
*/
var isEnded = false;
/**
* Number of updates processed
* @type {Number}
*/
var updatesProcessed = 0;
/**
* Number of updates requested
* @type {Number}
*/
var updatesRequested = 0;
/**
* Number of updates responded
* @type {Number}
*/
var updatesResponded = 0;
/**
* Delayed update requests
* @type {Number}
*/
var delayedUpdateRequests = 0;
/**
* Error update requests
* @type {Number}
*/
var errorUpdateRequests = 0;
/**
* Cache of interpolators to avoid instantiating them over and over again
* @type {Object} Object including a property per interpolation type (typically: time-linear-interpolator,
* time-step-before-interpolator, time-step-after-interpolator). Each one of them is an object including
* a property per configuration array where the concrete interpolator is stored, this is:
* {
* "time-linear-interpolator": {
* "[[0,0], [20,25], [21,50], [22,100], [23, 0], [24, 0]]": linearInterpolatorInstance1,
* ...
* "[[0,0], [21,50], [23, 100], [24, 0]]": linearInterpolatorInstanceK
* },
* "time-step-before-interpolator": {
* "[[0,0], [20,25], [21,50], [22,100], [23, 0], [24, 0]]": stepBeforeInterpolatorInstance1,
* ...
* "[[0,0], [21,50], [23, 100], [24, 0]]": : stepBeforeInterpolatorInstanceN
* }
* }
*/
var interpolators = {};
/**
* Clones attributes
* @param {Object} attribute The attribute to clone
* @return {Object} The cloned attribute
*/
function cloneAttribute(attribute) {
/* jshint camelcase: false */
var clonedAttribute = {
value: attribute.value
};
if (attribute.name) {
clonedAttribute.name = attribute.name;
}
if (attribute.type) {
clonedAttribute.type = attribute.type;
}
if (attribute.object_id) {
clonedAttribute.object_id = attribute.object_id;
}
return clonedAttribute;
}
/**
* Clones a device
* @param {Object} device The device to cloned
* @return {Object} The cloned device
*/
function cloneDevice(device) {
/* jshint camelcase: false */
var clonedDevice = {
device_id: device.device_id,
schedule: device.schedule,
protocol: device.protocol,
api_key: device.api_key
};
if (device.attributes) {
device.attributes.forEach(function(attribute) {
clonedDevice.attributes = clonedDevice.attributes || [];
var clonedAttribute = cloneAttribute(attribute);
if (attribute.schedule) {
clonedAttribute.schedule = attribute.schedule;
}
clonedDevice.attributes.push(clonedAttribute);
});
}
return clonedDevice;
}
/**
* Clones a entity
* @param {Object} entity The entity to cloned
* @return {Object} The cloned device
*/
function cloneEntity(entity) {
/* jshint camelcase: false */
var clonedEntity = {
entity_name: entity.entity_name,
entity_type: entity.entity_type,
schedule: entity.schedule
};
if (entity.active) {
entity.active.forEach(function(activeAttribute) {
clonedEntity.active = clonedEntity.active || [];
var clonedActiveAttribute = cloneAttribute(activeAttribute);
if (activeAttribute.schedule) {
clonedActiveAttribute.schedule = activeAttribute.schedule;
}
clonedEntity.active.push(clonedActiveAttribute);
});
}
if (entity.staticAttributes) {
entity.staticAttributes.forEach(function(staticAttribute) {
clonedEntity.staticAttributes = clonedEntity.staticAttributes || [];
var clonedStaticAttribute = cloneAttribute(staticAttribute);
if (staticAttribute.schedule) {
clonedStaticAttribute.schedule = staticAttribute.schedule;
}
clonedEntity.staticAttributes.push(clonedStaticAttribute);
});
}
return clonedEntity;
}
/**
* Cancels all the pending (token request and update) jobs if any
*/
function cancelAllJobs() {
for (var job in scheduler.scheduledJobs) {
if (scheduler.scheduledJobs.hasOwnProperty(job)) {
scheduler.scheduledJobs[job].cancel();
}
}
updateJobs = [];
areJobsScheduled = false;
}
/**
* Returns the API key associated to certain device
* @param {Object} device The device information
* @return {string} The associated device API key
*/
function getDeviceAPIKey(device) {
/* jshint camelcase: false */
switch (device.protocol) {
case 'UltraLight::HTTP':
return device.api_key || configuration.iota.ultralight.api_key;
case 'UltraLight::MQTT':
return device.api_key || configuration.iota.ultralight.api_key;
case 'JSON::HTTP':
return device.api_key || configuration.iota.json.api_key;
case 'JSON::MQTT':
return device.api_key || configuration.iota.json.api_key;
}
}
/**
* Emits an "scheduled" event notifying that new update jobs have been scheduled
* @param {String} schedule The schedule
* @param {Object} elementType The element type
* @param {Object} element The information about the entity to update
* @param {Array} attributes Array of attributes to update
*/
function emitScheduled(schedule, elementType, element, attributes) {
/* jshint camelcase: false */
var clonedAttributes;
var event2Emit = {
schedule: schedule
};
if (element.entity_name) {
event2Emit.entity_name = element.entity_name;
event2Emit.entity_type = element.entity_type;
} else if (element.device_id) {
event2Emit.device_id = element.device_id;
event2Emit.protocol = element.protocol;
event2Emit.api_key = getDeviceAPIKey(element);
}
if (element.staticAttributes) {
element.staticAttributes.forEach(function(staticAttribute) {
clonedAttributes = clonedAttributes || [];
clonedAttributes.push(cloneAttribute(staticAttribute));
});
}
attributes.forEach(function(attribute) {
clonedAttributes = clonedAttributes || [];
clonedAttributes.push(cloneAttribute(attribute));
});
event2Emit.attributes = clonedAttributes;
eventEmitter.emit('update-scheduled', event2Emit);
}
/**
* Emits an "info" event
* @param {Object} info The information to emit
*/
function emitInfo(info) {
eventEmitter.emit(
'info',
{
message: info
}
);
}
/**
* Emits an "error" event
* @param {Object} err The error to emit
*/
function emitError(err) {
eventEmitter.emit(
'error',
{
error: err
}
);
}
/**
* Emits a "token-request" event
* @param {Object} tokenRequest The token request
*/
function emitTokenRequest(tokenRequest) {
eventEmitter.emit(
'token-request',
{
request: tokenRequest
}
);
}
/**
* Emits a "token-response" event
* @param {Date} expirationDate The expiration date
*/
function emitTokenResponse(expirationDate) {
/* jshint camelcase: false */
eventEmitter.emit(
'token-response',
{
expires_at: expirationDate
}
);
}
/**
* Emits a "token-request-scheduled" event
* @param {Date} scheduleDate The schedule date
*/
function emitTokenRequestScheduled(scheduleDate) {
/* jshint camelcase: false */
eventEmitter.emit(
'token-request-scheduled',
{
scheduled_at: scheduleDate
}
);
}
/**
* Emits an "request" event notifying that new update jobs have been requested
* @param {Object} requestOptions The request information
*/
function emitRequest(requestOptions) {
/* jshint camelcase: false */
eventEmitter.emit(
'update-request',
{
request: requestOptions
}
);
}
/**
* Emits an "response" or "error" event notifying that new update jobs have been responded
* @param {Object} error Error, if any
* @param {Object} request The associated request
* @param {Object} body The response body
* @param {Object} response The response
*/
function emitResponse(error, request, body, response) {
/* jshint camelcase: false */
if (error) {
errorUpdateRequests += 1;
eventEmitter.emit(
'error',
{
request: request,
error: error
}
);
} else if (response && response.statusCode.toString().charAt(0) !== '2') {
errorUpdateRequests += 1;
eventEmitter.emit(
'error',
{
request: request,
response: body,
error: {
statusCode: response.statusCode
}
}
);
} else {
eventEmitter.emit(
'update-response',
{
request: request,
response: body
}
);
}
}
/**
* Emits the "info" event
*/
function emitProgressInfo() {
if (!isEnded) {
var realElapsedTime = new time.Date() - realFromDate;
eventEmitter.emit(
'progress-info',
{
updatesProcessed: updatesProcessed,
updatesRequested: updatesRequested,
delayedUpdateRequests: delayedUpdateRequests,
errorUpdateRequests: errorUpdateRequests,
elapsedTime: realElapsedTime,
simulatedElapsedTime: (fromDate ? new Date() - fromDate : realElapsedTime),
updateJobs: updateJobs,
clock: clock
}
);
}
}
/**
* Starts the progress information interval
* @param {Number} interval The interval milliseconds
*/
function startProgressInfo(interval) {
if (interval) {
progressIntervalObj = setInterval(emitProgressInfo, interval);
}
}
/**
* Stops the progress information interval
*/
function stopProgressInfo() {
if (progressIntervalObj) {
clearInterval(progressIntervalObj);
}
}
/**
* Emits the "stop" event
*/
function emitStop() {
eventEmitter.emit('stop');
}
/**
* Emits the "end" event
*/
function emitEnd() {
eventEmitter.emit('end');
}
/**
* Ends a currently running simulation, if any, and emits the "end" event
*/
function end() {
stopProgressInfo();
cancelAllJobs();
if (fromDate) {
clock.uninstall();
}
if (!isEnded) {
isEnded = true;
emitEnd();
}
}
/**
* Stops a currently running simulation, if any, and emits the "stop" event
*/
function stop() {
if (!isEnded) {
emitStop();
end();
}
}
/**
* Helper function for the fast-forward simulation
* @return {Function} [description]
*/
function nextTick() {
if (fromDate) {
if (toDate && Date.now() >= toDate.getTime()) {
emitProgressInfo();
stop();
} else {
clock.next();
}
}
}
/**
* Checks the pending update invocations and emits the "end" if none is pendingInvocations
*/
function checkPendingInvocations() {
for (var ii = 0; ii < updateJobs.length; ii++) {
if (updateJobs[ii].pendingInvocations().length === 0) {
updateJobs.splice(ii, 1);
break;
}
}
if (updateJobs.length === 0) {
return end();
} else {
nextTick();
}
}
/**
* Generates a new device from a device description and a counter
* @param {Object} device The device description
* @param {Number} counter The counter
* @return {Object} The generated device
*/
function generateDevice(device, counter) {
/* jshint camelcase: false */
var clonedDevice = cloneDevice(device);
clonedDevice.device_id = device.entity_type + ':' + counter;
clonedDevice.api_key = device.api_key;
clonedDevice.protocol = device.protocol;
return clonedDevice;
}
/**
* Generates a new entity from a entity description and a counter
* @param {Object} entity The entity description
* @param {Number} counter The counter
* @return {Object} The generated device
*/
function generateEntity(entity, counter) {
/* jshint camelcase: false */
var clonedEntity = cloneEntity(entity);
clonedEntity.entity_name = entity.entity_type + ':' + counter;
return clonedEntity;
}
/**
* Adds an active attribute to certain schedule inside the schedules object
* @param {Object} schedules An object including schedules as properties and arrays of active attributes to update
* as values
* @param {String} schedule The schedule
* @param {Object} attribute Object containing the details of the attribute to update
*/
function addAttribute2Schedule(schedules, schedule, attribute) {
var theSchedule = typeof schedule === 'string' ? schedule : JSON.stringify(schedule);
schedules[theSchedule] = schedules[theSchedule] || [];
schedules[theSchedule].push(attribute);
}
/**
* Returns the decimal date associated to certain date
* @param {date} date The date
* @return {Number} The time in decimal format
*/
function toDecimalHours(date) {
return date.getHours() + (date.getMinutes() / 60) + (date.getSeconds() / 3600);
}
/**
* Returns the interpolated value for certain date based on the passed interpolator and interpolator type
* @param {Object} interpolator The interpolator specification
* @param {Object} interpolationType The interpolator type
* @return {Object} The interpolated value
*/
function interpolate(interpolator, interpolationType) {
var interpolationSpec,
interpolationFunction,
interpolatorInstance,
interpolationTypePlural = interpolationType + 's';
switch(interpolationType) {
case 'time-linear-interpolator':
interpolationFunction = linearInterpolator;
break;
case 'time-random-linear-interpolator':
interpolationFunction = randomLinearInterpolator;
break;
case 'time-step-before-interpolator':
interpolationFunction = stepBeforeInterpolator;
break;
case 'time-step-after-interpolator':
interpolationFunction = stepAfterInterpolator;
break;
case 'date-increment-interpolator':
interpolationFunction = dateIncrementInterpolator;
break;
case 'multiline-position-interpolator':
interpolationFunction = multilinePositionInterpolator;
break;
case 'text-rotation-interpolator':
interpolationFunction = textRotationInterpolator;
break;
case 'attribute-function-interpolator':
interpolationFunction = attributeFunctionInterpolator;
break;
default:
return null;
}
if (interpolationType !== 'time-random-linear-interpolator') {
interpolationSpec = interpolator.substring((interpolationType + '(').length, interpolator.length - 1);
interpolators[interpolationTypePlural] = interpolators[interpolationTypePlural] || {};
interpolatorInstance = interpolators[interpolationTypePlural][interpolationSpec] ||
(interpolators[interpolationTypePlural][interpolationSpec] =
(interpolationType === 'attribute-function-interpolator' ?
interpolationFunction(interpolationSpec, configuration.domain, configuration.contextBroker) :
interpolationFunction(interpolationSpec)));
} else {
interpolationSpec = interpolator.substring((interpolationType + '(').length, interpolator.length - 1);
interpolatorInstance = interpolationFunction(interpolationSpec);
}
return interpolatorInstance.apply(null, Array.prototype.slice.call(arguments, 2));
}
/**
* Resolves a value for an interpolator and the current date
* @param {String} interpolator The value (may be an interpolator specification or concrete value)
* @return {Number} The final value for the interpolator and date specified
*/
function resolveValue(interpolator) {
var value;
if (typeof interpolator !== 'string') {
return interpolator;
}
if (interpolator.indexOf('time-linear-interpolator(') === 0) {
return interpolate(interpolator, 'time-linear-interpolator', toDecimalHours(new Date()));
} else if (interpolator.indexOf('time-random-linear-interpolator(') === 0) {
return interpolate(interpolator, 'time-random-linear-interpolator', toDecimalHours(new Date()));
} else if (interpolator.indexOf('time-step-before-interpolator(') === 0) {
return interpolate(interpolator, 'time-step-before-interpolator', toDecimalHours(new Date()));
} else if (interpolator.indexOf('time-step-after-interpolator(') === 0) {
return interpolate(interpolator, 'time-step-after-interpolator', toDecimalHours(new Date()));
} else if (interpolator.indexOf('date-increment-interpolator(') === 0) {
return interpolate(interpolator, 'date-increment-interpolator');
} else if (interpolator.indexOf('multiline-position-interpolator(') === 0) {
return interpolate(interpolator, 'multiline-position-interpolator', toDecimalHours(new Date()));
} else if (interpolator.indexOf('text-rotation-interpolator(') === 0) {
return interpolate(interpolator, 'text-rotation-interpolator', new Date());
} else if (interpolator.indexOf('attribute-function-interpolator(') === 0) {
try {
value = interpolate(interpolator, 'attribute-function-interpolator',
configuration.authentication && configuration.authentication.token);
} catch (exception) {
emitError(exception);
}
return value;
} else {
return interpolator;
}
}
/**
* Returns the MQTT topic for certain device
* @param {Object} device The device information
* @return {string} The topic
*/
function getMQTTTopic(device) {
/* jshint camelcase: false */
return '/' + getDeviceAPIKey(device) + '/' + device.device_id + '/attrs';
}
/**
* Returns the UltraLight payload
* @param {Object} device The device information
* @return {string} The payload
*/
function getUltraLightPayload(device) {
/* jshint camelcase: false */
var httpMQTTPayload = '',
value;
if (device.protocol === 'UltraLight::HTTP' || device.protocol === 'UltraLight::MQTT') {
device.attributes.forEach(function(attribute) {
value = resolveValue(attribute.value);
/**
* Currently the UltraLight HTTP IoT agent does not support passing objects. Once it does, the "stringified"
* version should be passed:
* if ((typeof value === 'object') && !_.isDate(value)) {
* value = JSON.stringify(value);
* }
*/
httpMQTTPayload = httpMQTTPayload.concat(attribute.object_id + '|' + value + '|');
});
httpMQTTPayload = httpMQTTPayload.substring(0, httpMQTTPayload.length - 1);
}
return httpMQTTPayload;
}
/**
* Returns the JSON payload
* @param {Object} device The device information
* @return {string} The payload
*/
function getJSONPayload(device) {
/* jshint camelcase: false */
var jsonPayload = {},
value;
if (device.protocol === 'JSON::HTTP' || device.protocol === 'JSON::MQTT') {
device.attributes.forEach(function(attribute) {
value = resolveValue(attribute.value);
jsonPayload[attribute.object_id] = value;
});
}
return jsonPayload;
}
/**
* Returns the request package options associated to the update of certain element (device or entity) and some of its
* attributes
* @param {String} elementType The element type
* @param {Object} element Element information
* @param {Array} attributes Array of attributes to update
* @return {Object} The request package options
*/
function getRequestOptions(elementType, element, attributes) {
/* jshint camelcase: false */
var url, path, contentType, body, json, metadatas;
if (elementType === 'entity') {
contentType = 'application/json';
json = true;
if ((configuration.contextBroker && configuration.contextBroker.ngsiVersion === '1.0') ||
(configuration.subscriber && configuration.subscriber.ngsiVersion === '1.0')) {
var contextElement = {};
contextElement.id = element.entity_name;
contextElement.type = element.entity_type;
contextElement.isPattern = false;
if (element.staticAttributes && element.staticAttributes.length) {
contextElement.attributes = [];
element.staticAttributes.forEach(function(staticAttribute) {
metadatas = [];
if (staticAttribute.metadata) {
staticAttribute.metadata.forEach(function(metadata) {
metadatas.push({
name: metadata.name,
type: metadata.type,
value: resolveValue(metadata.value)
});
});
}
contextElement.attributes.push({
name: staticAttribute.name,
type: staticAttribute.type,
value: resolveValue(staticAttribute.value),
metadatas: metadatas
});
});
}
contextElement.attributes = contextElement.attributes || [];
attributes.forEach(function(activeAttribute) {
metadatas = [];
if (activeAttribute.metadata) {
activeAttribute.metadata.forEach(function(metadata) {
metadatas.push({
name: metadata.name,
type: metadata.type,
value: resolveValue(metadata.value)
});
});
}
contextElement.attributes.push({
name: activeAttribute.name,
type: activeAttribute.type,
value: resolveValue(activeAttribute.value),
metadatas: metadatas
});
});
if (configuration.contextBroker) {
path = '/v1/updateContext';
url = configuration.contextBroker.protocol + '://' + configuration.contextBroker.host + ':' +
configuration.contextBroker.port + path;
body = {
contextElements: [
contextElement
],
updateAction: 'APPEND'
};
} else if (configuration.subscriber) {
url = configuration.subscriber.protocol + '://' + configuration.subscriber.host + ':' +
configuration.subscriber.port + configuration.subscriber.path;
body = {
subscriptionId: '1234567890abcdef12345678',
originator: 'fiware-device-simulator',
contextResponses: [
{
contextElement: contextElement,
statusCode: {
code: '200',
reasonPhrase : 'OK'
}
}
]
};
}
} else if (configuration.contextBroker.ngsiVersion === '2.0') {
var ngsiV2Entity = {};
path = '/v2/op/update';
url = configuration.contextBroker.protocol + '://' + configuration.contextBroker.host + ':' +
configuration.contextBroker.port + path;
body = {
actionType: 'APPEND',
entities: []
};
ngsiV2Entity.id = element.entity_name;
ngsiV2Entity.type = element.entity_type;
if (element.staticAttributes && element.staticAttributes.length) {
element.staticAttributes.forEach(function(staticAttribute) {
ngsiV2Entity[staticAttribute.name] = {
type: staticAttribute.type,
value: resolveValue(staticAttribute.value)
};
if (staticAttribute.metadata) {
ngsiV2Entity[staticAttribute.name].metadata = {};
staticAttribute.metadata.forEach(function(metadata) {
ngsiV2Entity[staticAttribute.name].metadata[metadata.name] = {
type: metadata.type,
value: resolveValue(metadata.value)
};
});
}
});
}
attributes.forEach(function(activeAttribute) {
ngsiV2Entity[activeAttribute.name] = {
type: activeAttribute.type,
value: resolveValue(activeAttribute.value)
};
if (activeAttribute.metadata) {
ngsiV2Entity[activeAttribute.name].metadata = {};
activeAttribute.metadata.forEach(function(metadata) {
ngsiV2Entity[activeAttribute.name].metadata[metadata.name] = {
type: metadata.type,
value: resolveValue(metadata.value)
};
});
}
});
body.entities.push(ngsiV2Entity);
} else {
emitError(new fdsErrors.NGSIVersionNotSupported('The provided NGSI version (\'' +
configuration.contextBroker.ngsiVersion + '\') is not supported'));
return null;
}
} else if (elementType === 'device') {
if (element.protocol === 'UltraLight::HTTP') {
contentType = 'text/plain';
url = configuration.iota.ultralight.http.protocol + '://' + configuration.iota.ultralight.http.host + ':' +
configuration.iota.ultralight.http.port + '/iot/d?i=' + element.device_id + '&k=' +
getDeviceAPIKey(element);
json = false;
body = getUltraLightPayload(element);
} else if (element.protocol === 'JSON::HTTP') {
contentType = 'application/json';
url = configuration.iota.json.http.protocol + '://' + configuration.iota.json.http.host + ':' +
configuration.iota.json.http.port + '/iot/json?i=' + element.device_id + '&k=' + getDeviceAPIKey(element);
json = true;
body = getJSONPayload(element);
} else {
emitError(new fdsErrors.ProtocolNotSupported('The provided protocol (\'' +
element.protocol + '\') is not supported'));
return null;
}
}
var options = {
method: 'POST',
url: url,
rejectUnauthorized: false,
headers: {
'Content-Type': contentType,
'Accept': 'application/json',
'Fiware-Service': configuration.domain && configuration.domain.service,
'Fiware-ServicePath': configuration.domain && configuration.domain.subservice,
'X-Auth-Token': configuration.authentication && configuration.authentication.token
},
json: json,
body: body
};
return options;
}
/**
* MQTT publications handler
* @param {Object} request The MQTT publication
* @param {Error} err Error, if any
* @param {[type]} result Result of the operation
*/
function onMQTTPublication(request, err, result) {
emitResponse(err, request, result);
process.nextTick(checkPendingInvocations);
nextTick();
}
/**
* Returns the update job name associated to certain entity and attributes
* @param {Object} element An entity or device
* @param {Array} attributes An array of attributes
* @return {String} The job name
*/
function getJobName(element, attributes) {
/* jshint camelcase: false */
var jobName = '';
var entityOrDeviceName = element.entity_name || element.object_id;
jobName += (entityOrDeviceName + ': ');
for (var ii = 0; ii < attributes.length; ii++) {
if (ii > 0) {
jobName += ', ';
}
jobName += attributes[ii].name;
}
return jobName;
/* jshint camelcase: true */
}
/**
* Updates the attributes associated to certain element (device or entity)
* @param {Object} elementType The element type
* @param {Object} element The element information
* @param {Array} attributes The attributes to update
*/
function update(elementType, element, attributes) {
updatesProcessed++;
if (maximumNotRespondedUpdateRequests >= 0) {
if ((updatesRequested - updatesResponded) > maximumNotRespondedUpdateRequests ||
(updatesProcessed - delayedUpdateRequests - updatesRequested) > (maximumNotRespondedUpdateRequests + 1)) {
delayedUpdateRequests++;
var jobName = getJobName(element, attributes);
var reScheduledJob = scheduler.scheduleJob(
jobName, new Date(Date.now() + delay), update.bind(null, elementType, element, attributes));
updateJobs.push(reScheduledJob);
return;
}
}
var mqttProtocol, mqttHost, mqttPort, mqttUser, mqttPassword, mqttURL, mqttTopic, mqttPayload, mqttRequest;
if (elementType === 'entity' ||
(elementType === 'device' &&
(element.protocol === 'UltraLight::HTTP' || element.protocol === 'JSON::HTTP'))) {
var requestOptions = getRequestOptions(elementType, element, attributes);
if (requestOptions) {
request(requestOptions, function(err, response, body) {
emitResponse(err, requestOptions, body, response);
updatesResponded++;
process.nextTick(checkPendingInvocations);
nextTick();
});
emitRequest(requestOptions);
updatesRequested++;
}
} else if (element.protocol === 'UltraLight::MQTT' || element.protocol === 'JSON::MQTT') {
if (element.protocol === 'UltraLight::MQTT') {
mqttProtocol = configuration.iota.ultralight.mqtt.protocol;
mqttHost = configuration.iota.ultralight.mqtt.host;
mqttPort = configuration.iota.ultralight.mqtt.port;
mqttUser = configuration.iota.ultralight.mqtt.user;
mqttPassword = configuration.iota.ultralight.mqtt.password;