-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolarnetwork-d3.js
7051 lines (7051 loc) · 250 KB
/
solarnetwork-d3.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
(function(root, factory) {
if (typeof define === "function" && define.amd) {
define([ "colorbrewer", "d3", "queue-async", "crypto-js", "uri-js" ], factory);
} else if (typeof module === "object" && module.exports) {
module.exports = factory(require("colorbrewer"), require("d3"), require("queue-async"), require("crypto-js"), require("uri-js"));
} else {
root.sn = factory(root.colorbrewer, root.d3, root.queue, root.CryptoJS, root.URI);
}
})(this, function(colorbrewer, d3, queue, CryptoJS, URI) {
"use strict";
var sn = {
version: "0.16.0"
};
sn.api = {};
var sn_api_timestampFormat = d3.time.format.utc("%Y-%m-%d %H:%M:%S.%LZ");
sn.api.control = {};
sn.api.user = {};
sn.api.node = {};
var global = function() {
if (typeof self !== "undefined") {
return self;
}
if (typeof global !== "undefined") {
return global;
}
return new Function("return this")();
}();
var sn_config = {
debug: false,
host: "data.solarnetwork.net",
tls: true,
path: "/solarquery",
solarUserPath: "/solaruser",
secureQuery: false
};
sn.config = sn_config;
function sn_config_getConfig() {
return sn_config;
}
sn.util = {
arraysAreEqual: sn_util_arraysAreEqual,
copy: sn_util_copy,
copyAll: sn_util_copyAll,
merge: sn_util_merge,
superMethod: sn_util_superMethod
};
/**
* Copy the enumerable own properties of `obj1` onto `obj2` and return `obj2`.
*
* @param {Object} obj1 - The object to copy enumerable properties from.
* @param {Object} [obj2] - The optional object to copy the properties to. If not
* provided a new object will be created.
* @returns {Object} The object whose properties were copied to.
* @since 0.0.5
* @preserve
*/
function sn_util_copy(obj1, obj2) {
var prop, desc;
if (obj2 === undefined) {
obj2 = {};
}
for (prop in obj1) {
if (obj1.hasOwnProperty(prop)) {
desc = Object.getOwnPropertyDescriptor(obj1, prop);
if (desc) {
Object.defineProperty(obj2, prop, desc);
} else {
obj2[prop] = obj1[prop];
}
}
}
return obj2;
}
/**
* Copy the enumerable and non-enumerable own properties of `obj` onto `obj2` and return `obj2`.
*
* @param {Object} obj1 - The object to copy enumerable properties from.
* @param {Object} [obj2] - The optional object to copy the properties to. If not
* provided a new object will be created.
* @returns {Object} The object whose properties were copied to.
* @since 0.0.5
* @preserve
*/
function sn_util_copyAll(obj1, obj2) {
var keys = Object.getOwnPropertyNames(obj1), i, len, key, desc;
if (obj2 === undefined) {
obj2 = {};
}
for (i = 0, len = keys.length; i < len; i += 1) {
key = keys[i];
desc = Object.getOwnPropertyDescriptor(obj1, key);
if (desc) {
Object.defineProperty(obj2, key, desc);
} else {
obj2[key] = obj1[key];
}
}
return obj2;
}
/**
* Copy the enumerable own properties of `obj1` that don't already exist on `obj2` into `obj2` and return `obj2`.
*
* @param {Object} obj1 - The object to copy enumerable properties from.
* @param {Object} [obj2] - The optional object to copy the properties to. If not
* provided a new object will be created.
* @returns {Object} The object whose properties were copied to.
* @since 0.14.0
* @preserve
*/
function sn_util_merge(obj1, obj2) {
var prop, desc;
if (obj2 === undefined) {
obj2 = {};
}
for (prop in obj1) {
if (obj1.hasOwnProperty(prop) && obj2[prop] === undefined) {
desc = Object.getOwnPropertyDescriptor(obj1, prop);
if (desc) {
Object.defineProperty(obj2, prop, desc);
} else {
obj2[prop] = obj1[prop];
}
}
}
return obj2;
}
/**
* Compare two arrays for equality, that is they have the same length and same values
* using strict quality.
*
* @param {Array} a1 The first array to compare.
* @param {Array} a2 The second array to compare.
* @return {Boolean} True if the arrays are equal.
* @since 0.2.0
* @preserve
*/
function sn_util_arraysAreEqual(a1, a2) {
var i, len;
if (!(Array.isArray(a1) && Array.isArray(a2))) {
return false;
}
if (a1.length !== a2.length) {
return false;
}
for (i = 0, len = a1.length; i < len; i += 1) {
if (Array.isArray(a1[i]) && Array.isArray(a2[i]) && arraysAreEqual(a1[i], a2[i]) !== true) {
return false;
} else if (a1[i] !== a2[i]) {
return false;
}
}
return true;
}
/**
* Get a proxy method for a "super" class' method on the `this` objct.
*
* @param {String} name - The name of the method to get a proxy for.
* @returns {Function} A function that calls the `name` function of the `this` object.
* @since 0.0.4
* @preserve
*/
function sn_util_superMethod(name) {
var that = this, method = that[name];
return function() {
return method.apply(that, arguments);
};
}
sn.api.node.registerUrlHelperFunction = sn_api_node_registerUrlHelperFunction;
var sn_api_node_urlHelperFunctions;
sn.api.node.nodeUrlHelper = function(node, configuration) {
var that = {
version: "1.1.0"
};
var nodeId = node;
var config = sn.util.copy(configuration, {
host: "data.solarnetwork.net",
tls: true,
path: "/solarquery",
secureQuery: false
});
function hostURL() {
return "http" + (config.tls === true ? "s" : "") + "://" + config.host;
}
function baseURL() {
return hostURL() + config.path + "/api/v1/" + (config.secureQuery === true ? "sec" : "pub");
}
function reportableIntervalURL(sourceId) {
var url = baseURL() + "/range/interval?nodeId=" + nodeId;
if (Array.isArray(sourceId)) {
sourceId = sourceId[0];
}
if (sourceId) {
url += "&sourceId=" + encodeURIComponent(sourceId);
}
return url;
}
function availableSourcesURL(startDate, endDate) {
var url = baseURL() + "/range/sources?nodeId=" + nodeId;
if (startDate !== undefined) {
url += "&start=" + encodeURIComponent(sn.format.dateFormat(startDate));
}
if (endDate !== undefined) {
url += "&end=" + encodeURIComponent(sn.format.dateFormat(endDate));
}
return url;
}
function dateTimeListURL(startDate, endDate, agg, sourceIds, pagination) {
var url = baseURL() + "/datum/list?nodeId=" + nodeId;
if (startDate) {
url += "&startDate=" + encodeURIComponent(sn.format.dateTimeFormatURL(startDate));
}
if (endDate) {
url += "&endDate=" + encodeURIComponent(sn.format.dateTimeFormatURL(endDate));
}
if (agg) {
url += "&aggregate=" + encodeURIComponent(agg);
}
if (Array.isArray(sourceIds) && sourceIds.length > 0) {
url += "&sourceIds=" + sourceIds.map(function(e) {
return encodeURIComponent(e);
}).join(",");
}
if (pagination !== undefined) {
if (pagination.max > 0) {
url += "&max=" + encodeURIComponent(pagination.max);
}
if (pagination.offset > 0) {
url += "&offset=" + encodeURIComponent(pagination.offset);
}
}
return url;
}
function mostRecentURL(sourceIds) {
var url = baseURL() + "/datum/mostRecent?nodeId=" + nodeId;
if (Array.isArray(sourceIds)) {
url += "&sourceIds=" + sourceIds.map(function(e) {
return encodeURIComponent(e);
}).join(",");
}
return url;
}
function nodeID(value) {
if (!arguments.length) return nodeId;
nodeId = value;
return that;
}
function keyDescription() {
return "node " + nodeId;
}
Object.defineProperties(that, {
secureQuery: {
get: function() {
return config.secureQuery === true;
},
enumerable: true
},
keyDescription: {
value: keyDescription
},
nodeId: {
get: function() {
return nodeId;
},
enumerable: true
},
nodeID: {
value: nodeID
},
hostURL: {
value: hostURL
},
baseURL: {
value: baseURL
},
reportableIntervalURL: {
value: reportableIntervalURL
},
availableSourcesURL: {
value: availableSourcesURL
},
dateTimeListURL: {
value: dateTimeListURL
},
mostRecentURL: {
value: mostRecentURL
}
});
(function() {
if (Array.isArray(sn_api_node_urlHelperFunctions)) {
sn_api_node_urlHelperFunctions.forEach(function(helper) {
if (that.hasOwnProperty(helper.name) === false) {
Object.defineProperty(that, helper.name, {
value: function() {
return helper.func.apply(that, arguments);
}
});
}
});
}
})();
return that;
};
function sn_api_node_registerUrlHelperFunction(name, func) {
if (typeof func !== "function") {
return;
}
if (sn_api_node_urlHelperFunctions === undefined) {
sn_api_node_urlHelperFunctions = [];
}
name = name.replace(/[^0-9a-zA-Z_]/, "");
sn_api_node_urlHelperFunctions.push({
name: name,
func: func
});
}
sn.api.user.registerUrlHelperFunction = sn_api_user_registerUrlHelperFunction;
var sn_api_user_urlHelperFunctions;
function sn_api_user_baseURL(urlHelper) {
return urlHelper.hostURL() + (sn.config && sn.config.solarUserPath ? sn.config.solarUserPath : "/solaruser") + "/api/v1/sec";
}
/**
* An active user-specific URL utility object. This object does not require
* any specific user ID to be configured, as all requests are assumed to apply
* to the active user credentials.
*
* @class
* @constructor
* @param {Object} configuration The configuration options to use.
* @returns {sn.api.user.userUrlHelper}
* @preserve
*/
sn.api.user.userUrlHelper = function(configuration) {
var self = {
version: "1.0.0"
};
var config = sn.util.copy(configuration, {
host: "data.solarnetwork.net",
tls: true,
path: "/solaruser",
secureQuery: true
});
/**
* Get a URL for just the SolarNet host, without any path.
*
* @returns {String} the URL to the SolarNet host
* @memberOf sn.api.user.userUrlHelper
* @preserve
*/
function hostURL() {
return "http" + (config.tls === true ? "s" : "") + "://" + config.host;
}
/**
* Get a URL for the SolarNet host and the base API path, e.g. <code>/solaruser/api/v1/sec</code>.
*
* @returns {String} the URL to the SolarUser base API path
* @memberOf sn.api.user.userUrlHelper
* @preserve
*/
function baseURL() {
return hostURL() + config.path + "/api/v1/" + (config.secureQuery === true ? "sec" : "pub");
}
/**
* Get a description of this helper object.
*
* @return {String} The description of this object.
* @memberOf sn.api.user.userUrlHelper
* @preserve
*/
function keyDescription() {
return "user";
}
/**
* Generate a SolarUser {@code /nodes} URL.
*
* @return {String} the URL to access the active user's nodes
* @memberOf sn.api.user.userUrlHelper
* @preserve
*/
function viewNodesURL() {
var url = baseURL() + "/nodes";
return url;
}
Object.defineProperties(self, {
keyDescription: {
value: keyDescription
},
hostURL: {
value: hostURL
},
baseURL: {
value: baseURL
},
viewNodesURL: {
value: viewNodesURL
}
});
(function() {
if (Array.isArray(sn_api_user_urlHelperFunctions)) {
sn_api_user_urlHelperFunctions.forEach(function(helper) {
if (self.hasOwnProperty(helper.name) === false) {
Object.defineProperty(self, helper.name, {
value: function() {
return helper.func.apply(self, arguments);
}
});
}
});
}
})();
return self;
};
/**
* Register a custom function to generate URLs with {@link sn.api.user.userUrlHelper}.
*
* @param {String} name The name to give the custom function. By convention the function
* names should end with 'URL'.
* @param {Function} func The function to add to sn.api.user.userUrlHelper instances.
* @preserve
*/
function sn_api_user_registerUrlHelperFunction(name, func) {
if (typeof func !== "function") {
return;
}
if (sn_api_user_urlHelperFunctions === undefined) {
sn_api_user_urlHelperFunctions = [];
}
name = name.replace(/[^0-9a-zA-Z_]/, "");
sn_api_user_urlHelperFunctions.push({
name: name,
func: func
});
}
sn_api_node_registerUrlHelperFunction("viewInstruction", sn_api_user_viewInstruction);
sn_api_node_registerUrlHelperFunction("viewActiveInstructionsURL", sn_api_user_viewActiveInstructionsURL);
sn_api_node_registerUrlHelperFunction("viewPendingInstructionsURL", sn_api_user_viewPendingInstructionsURL);
sn_api_node_registerUrlHelperFunction("updateInstructionStateURL", sn_api_user_updateInstructionStateURL);
sn_api_node_registerUrlHelperFunction("queueInstructionURL", sn_api_user_queueInstructionURL);
function sn_api_user_viewInstruction(instructionID) {
return sn_api_user_baseURL(this) + "/instr/view?id=" + encodeURIComponent(instructionID);
}
function sn_api_user_viewActiveInstructionsURL() {
return sn_api_user_baseURL(this) + "/instr/viewActive?nodeId=" + this.nodeId;
}
function sn_api_user_viewPendingInstructionsURL() {
return sn_api_user_baseURL(this) + "/instr/viewPending?nodeId=" + this.nodeId;
}
function sn_api_user_updateInstructionStateURL(instructionID, state) {
return sn_api_user_baseURL(this) + "/instr/updateState?id=" + encodeURIComponent(instructionID) + "&state=" + encodeURIComponent(state);
}
/**
* Generate a URL for posting an instruction request.
*
* @param {String} topic - The instruction topic.
* @param {Array} parameters - An array of parameter objects in the form <code>{name:n1, value:v1}</code>.
* @preserve
*/
function sn_api_user_queueInstructionURL(topic, parameters) {
var url = sn_api_user_baseURL(this) + "/instr/add?nodeId=" + this.nodeId + "&topic=" + encodeURIComponent(topic);
if (Array.isArray(parameters)) {
var i, len;
for (i = 0, len = parameters.length; i < len; i++) {
url += "&" + encodeURIComponent("parameters[" + i + "].name") + "=" + encodeURIComponent(parameters[i].name) + "&" + encodeURIComponent("parameters[" + i + "].value") + "=" + encodeURIComponent(parameters[i].value);
}
}
return url;
}
sn_api_node_registerUrlHelperFunction("viewNodeMetadataURL", sn_api_user_viewNodeMetadataURL);
function sn_api_user_viewNodeMetadataURL() {
return sn_api_user_baseURL(this) + "/nodes/meta/" + this.nodeId;
}
/**
* Manage the state of a boolean control switch using SolarNetwork SetControlParameter instructions.
*
* @preserve
*/
sn.api.control.toggler = function(urlHelper) {
"use strict";
var self = {
version: "1.3.0"
};
var timer;
var lastKnownStatus;
var lastKnownInstruction;
var lastHadCredentials;
var callback;
var refreshMs = 2e4;
var pendingRefreshMs = 5e3;
var controlID = "/power/switch/1";
var nodeUrlHelper = urlHelper;
var secHelper = sn.net.sec;
function notifyDelegate(error) {
if (callback !== undefined) {
try {
callback.call(self, error);
} catch (callbackError) {
sn.log("Error in callback: {0}", callbackError);
}
}
}
function getActiveInstruction(data) {
if (!Array.isArray(data) || data.length === 0) {
return undefined;
}
var instruction = data.reduce(function(prev, curr) {
if (curr.topic === "SetControlParameter" && Array.isArray(curr.parameters) && curr.parameters.length > 0 && curr.parameters[0].name === controlID && (prev === undefined || prev.created < curr.created)) {
return curr;
}
return prev;
}, undefined);
if (instruction !== undefined) {
sn.log("Active instruction for {3} found in state {0} (set control {1} to {2})", instruction.state, controlID, instruction.parameters[0].value, nodeUrlHelper.keyDescription());
}
return instruction;
}
function lastKnownInstructionState() {
return lastKnownInstruction === undefined ? undefined : lastKnownInstruction.state;
}
function lastKnownInstructionValue() {
return lastKnownInstruction === undefined ? undefined : Number(lastKnownInstruction.parameters[0].value);
}
function currentRefreshMs() {
return [ "Queued", "Received", "Executing" ].indexOf(lastKnownInstructionState()) < 0 ? refreshMs : pendingRefreshMs;
}
function value(desiredValue) {
if (!arguments.length) return lastKnownStatus === undefined ? undefined : lastKnownStatus.val;
var q = queue();
var currentValue = lastKnownStatus === undefined ? undefined : lastKnownStatus.val;
var pendingState = lastKnownInstructionState();
var pendingValue = lastKnownInstructionValue();
if (pendingState === "Queued" && pendingValue !== desiredValue) {
sn.log("Canceling {2} pending control {0} switch to {1}", controlID, pendingValue, nodeUrlHelper.keyDescription());
q.defer(secHelper.json, nodeUrlHelper.updateInstructionStateURL(lastKnownInstruction.id, "Declined"), "POST");
lastKnownInstruction = undefined;
pendingState = undefined;
pendingValue = undefined;
}
if (currentValue !== desiredValue && pendingValue !== desiredValue) {
sn.log("Request {2} to change control {0} to {1}", controlID, desiredValue, nodeUrlHelper.keyDescription());
q.defer(secHelper.json, nodeUrlHelper.queueInstructionURL("SetControlParameter", [ {
name: controlID,
value: String(desiredValue)
} ]), "POST");
}
q.awaitAll(function(error, results) {
if (error) {
sn.log("Error updating {2} control toggler {0}: {1}", controlID, error.status, nodeUrlHelper.keyDescription());
notifyDelegate(error);
return;
}
if (results.length < 1) {
return;
}
var cancelResult = results[0];
if (cancelResult.data == null && cancelResult.success === true) {
lastKnownInstruction = undefined;
}
var instructionResult = results[results.length - 1].data;
if (!(instructionResult == null)) {
lastKnownInstruction = instructionResult;
}
notifyDelegate();
if (timer) {
self.stop();
self.start(currentRefreshMs());
}
});
return self;
}
function mostRecentValue(controlStatus, instruction) {
var statusDate, instructionDate;
if (!instruction || instruction.status === "Declined") {
return controlStatus ? controlStatus.val : undefined;
} else if (!controlStatus) {
return Number(instruction.parameters[0].value);
}
statusDate = sn_api_timestampFormat.parse(controlStatus.created);
instructionDate = sn_api_timestampFormat.parse(instruction.created);
return statusDate.getTime() > instructionDate.getTime() ? controlStatus.val : Number(instruction.parameters[0].value);
}
function update() {
var q = queue();
q.defer(nodeUrlHelper.secureQuery ? secHelper.json : d3.json, nodeUrlHelper.mostRecentURL([ controlID ]));
if (secHelper.hasTokenCredentials() === true) {
q.defer(secHelper.json, nodeUrlHelper.viewPendingInstructionsURL(), "GET");
if (lastKnownInstruction && [ "Completed", "Declined" ].indexOf(lastKnownInstructionState()) < 0) {
q.defer(secHelper.json, nodeUrlHelper.viewInstruction(lastKnownInstruction.id));
}
}
q.await(function(error, status, active, executing) {
if (error) {
sn.log("Error querying control toggler {0} for {2} status: {1}", controlID, error.status, nodeUrlHelper.keyDescription());
notifyDelegate(error);
} else {
var i, len;
var controlStatus = undefined;
if (status.data && Array.isArray(status.data.results)) {
for (i = 0, len = status.data.results.length; i < len && controlStatus === undefined; i++) {
if (status.data.results[i].sourceId === controlID) {
controlStatus = status.data.results[i];
}
}
}
var execInstruction = executing ? executing.data : undefined;
var pendingInstruction = active ? getActiveInstruction(active.data) : undefined;
var newValue = mostRecentValue(controlStatus, execInstruction ? execInstruction : pendingInstruction ? pendingInstruction : lastKnownInstruction);
var currValue = value();
if (newValue !== currValue || lastHadCredentials !== secHelper.hasTokenCredentials()) {
sn.log("Control {0} for {1} value is currently {2}", controlID, nodeUrlHelper.keyDescription(), newValue !== undefined ? newValue : "N/A");
lastKnownStatus = controlStatus;
if (lastKnownStatus && !pendingInstruction) {
lastKnownStatus.val = newValue;
}
lastKnownInstruction = execInstruction ? execInstruction : pendingInstruction;
lastHadCredentials = secHelper.hasTokenCredentials();
notifyDelegate();
}
}
if (timer !== undefined) {
timer = setTimeout(update, currentRefreshMs());
}
});
return self;
}
/**
* Start automatically updating the status of the configured control.
*
* @param {Number} when - An optional offset in milliseconds to start at, defaults to 20ms.
* @return this object
* @memberOf sn.api.control.toggler
* @preserve
*/
self.start = function(when) {
if (timer === undefined) {
timer = setTimeout(update, when || 20);
}
return self;
};
/**
* Stop automatically updating the status of the configured control.
*
* @return this object
* @memberOf sn.api.control.toggler
* @preserve
*/
self.stop = function() {
if (timer !== undefined) {
clearTimeout(timer);
timer = undefined;
}
return self;
};
/**
* Get or set the control ID.
*
* @param {String} [value] the control ID to set
* @return when used as a getter, the current control ID value, otherwise this object
* @memberOf sn.api.control.toggler
* @preserve
*/
self.controlID = function(value) {
if (!arguments.length) return controlID;
controlID = value;
return self;
};
/**
* Get or set the refresh rate, in milliseconds.
*
* @param {Number} [value] the millisecond value to set
* @return when used as a getter, the current refresh millisecond value, otherwise this object
* @memberOf sn.api.control.toggler
* @preserve
*/
self.refreshMs = function(value) {
if (!arguments.length) return refreshMs;
if (typeof value === "number") {
refreshMs = value;
}
return self;
};
/**
* Get or set the refresh rate, in milliseconds, when a toggle instruction is queued.
*
* @param {Number} [value] the millisecond value to set
* @return when used as a getter, the current refresh millisecond value, otherwise this object
* @memberOf sn.api.control.toggler
* @since 1.2
* @preserve
*/
self.pendingRefreshMs = function(value) {
if (!arguments.length) return pendingRefreshMs;
if (typeof value === "number") {
pendingRefreshMs = value;
}
return self;
};
/**
* Get or set the {@link sn.api.node.urlHelper} to use.
*
* @param {Object} [value] the {@link sn.api.node.urlHelper} to set
* @return when used as a getter, the current helper value, otherwise this object
* @memberOf sn.api.control.toggler
* @preserve
*/
self.nodeUrlHelper = function(value) {
if (!arguments.length) return nodeUrlHelper;
nodeUrlHelper = value;
return self;
};
/**
* Get or set the callback function, which is called after the state of the control changes.
* The `this` reference will be set to this object.
*
* @param {function} [value] the callback
* @return when used as a getter, the current callback function, otherwise this object
* @memberOf sn.api.control.toggler
* @preserve
*/
self.callback = function(value) {
if (!arguments.length) return callback;
if (typeof value === "function") {
callback = value;
}
return self;
};
Object.defineProperties(self, {
pendingInstructionState: {
value: lastKnownInstructionState
},
pendingInstructionValue: {
value: lastKnownInstructionValue
},
lastKnownInstructionState: {
value: lastKnownInstructionState
},
lastKnownInstructionValue: {
value: lastKnownInstructionValue
},
value: {
value: value
}
});
return self;
};
sn.api.datum = {};
sn.api.datum.aggregateNestedDataLayers = sn_api_datum_aggregateNestedDataLayers;
/**
* Combine the layers resulting from a d3.nest() operation into a single, aggregated
* layer. This can be used to combine all sources of a single data type, for example
* to show all "power" sources as a single layer of chart data. The resulting object
* has the same structure as the input <code>layerData</code> parameter, with just a
* single layer of data.
*
* @param {object} layerData - An object resulting from d3.nest().entries()
* @param {string} resultKey - The <code>key</code> property to assign to the returned layer.
* @param {array} copyProperties - An array of string property names to copy as-is from
* the <b>first</b> layer's data values.
* @param {array} sumProperties - An array of string property names to add together from
* <b>all</b> layer data.
* @param {object} staticProperties - Static properties to copy as-is to all output data.
* @return {object} An object with the same structure as returned by d3.nest().entries()
* @since 0.0.4
* @preserve
*/
function sn_api_datum_aggregateNestedDataLayers(layerData, resultKey, copyProperties, sumProperties, staticProperties) {
var layerCount = layerData.length, dataLength, i, j, k, copyPropLength = copyProperties.length, sumPropLength = sumProperties.length, d, val, clone, array;
dataLength = layerData[0].values.length;
if (dataLength > 0) {
array = [];
for (i = 0; i < dataLength; i += 1) {
d = layerData[0].values[i];
clone = {};
if (staticProperties !== undefined) {
for (val in staticProperties) {
if (staticProperties.hasOwnProperty(val)) {
clone[val] = staticProperties[val];
}
}
}
for (k = 0; k < copyPropLength; k += 1) {
clone[copyProperties[k]] = d[copyProperties[k]];
}
for (k = 0; k < sumPropLength; k += 1) {
clone[sumProperties[k]] = 0;
}
for (j = 0; j < layerCount; j += 1) {
for (k = 0; k < sumPropLength; k += 1) {
val = layerData[j].values[i][sumProperties[k]];
if (val !== undefined) {
clone[sumProperties[k]] += val;
}
}
}
array.push(clone);
}
layerData = [ {
key: resultKey,
values: array
} ];
}
return layerData;
}
sn.format = {};
sn.format.dateTimeFormat = d3.time.format.utc("%Y-%m-%d %H:%M");
sn.format.timestampFormat = d3.time.format.utc("%Y-%m-%d %H:%M:%S.%LZ");
sn.format.timestampSecsFormat = d3.time.format.utc("%Y-%m-%d %H:%M:%SZ");
sn.format.dateTimeFormatLocal = d3.time.format("%Y-%m-%d %H:%M");
sn.format.dateTimeFormatURL = d3.time.format.utc("%Y-%m-%dT%H:%M");
sn.format.dateFormat = d3.time.format.utc("%Y-%m-%d");
sn.format.parseTimestamp = sn_format_parseTimestamp;
/**
* Parse a timestamp string into a Date object.
*
* @param {String} s the date string to parse
* @returns {Date} the parsed date, or `null`
* @preserve
*/
function sn_format_parseTimestamp(s) {
var result = sn.format.timestampFormat.parse(s);
if (!result) {
result = sn.format.timestampSecsFormat.parse(s);
}
return result;
}
sn.api.datum.datumDate = sn_api_datum_datumDate;
/**
* Get a Date object for a datum. This function will return the first available date according
* to the first available property found according to these rules:
*
* <ol>
* <li><code>date</code> - assumed to be a Date object already</li>
* <li><code>localDate</code> - a string in <b>yyyy-MM-dd</b> form, optionally with a String
* <code>localTime</code> property for an associated time in <b>HH:mm</b> form.</li>
* <li><code>created</code> - a string in <b>yyyy-MM-dd HH:mm:ss.SSS'Z'</b> form.</li>
* </ul>
*
* @param {Object} d The datum to get the Date for.
* @returns {Date} The found Date, or <em>null</em> if not available
* @preserve
*/
function sn_api_datum_datumDate(d) {
if (d) {
if (d.date) {
return d.date;
} else if (d.localDate) {
return sn.format.dateTimeFormat.parse(d.localDate + (d.localTime ? " " + d.localTime : " 00:00"));
} else if (d.created) {
return sn.format.parseTimestamp(d.created);
}
}
return null;
}
sn.log = sn_log;
function sn_log() {
if (sn.config.debug === true && console !== undefined) {
console.log(sn.format.fmt.apply(this, arguments));
}
}
sn.net = {};
/**
* Load data for a set of source IDs, date range, and aggregate level using the
* {@code dateTimeListURL} endpoint. This object is designed
* to be used once per query. After creating the object and configuring an asynchronous
* callback function with {@link #callback(function)}, call {@link #load()} to start
* loading the data. The callback function will be called once all data has been loaded.
*
* @class
* @param {string[]} sourceIds - array of source IDs to load data for
* @param {function} urlHelper - a {@link sn.api.node.nodeUrlHelper} or {@link sn.api.loc.locationUrlHelper}
* @param {date} start - the start date, or {@code null}
* @param {date} end - the end date, or {@code null}
* @param {string} aggregate - aggregate level
* @returns {sn.api.datum.loader}
* @preserve
*/
sn.api.datum.loader = function(sourceIds, urlHelper, start, end, aggregate) {
var that = load;
var jsonClient = d3.json;
var finishedCallback;
var urlParameters;
var state = 0;
var results;
Object.defineProperties(that, {
version: {
value: "1.1.0"
}
});
function load(callback) {
if (typeof callback === "function") {
finishedCallback = callback;
}
state = 1;
loadData();
return load;
}
function requestCompletionHandler(error) {
state = 2;
if (finishedCallback) {
finishedCallback.call(that, error, results);
}
}
function loadData(offset) {
var pagination = {}, url, dataExtractor, offsetExtractor;
if (offset) {
pagination.offset = offset;
}
url = urlHelper.dateTimeListURL(start, end, aggregate, sourceIds, pagination);
if (urlParameters) {
(function() {
var tmp = sn_net_encodeURLQueryTerms(urlParameters);
if (tmp.length) {
url += "&" + tmp;
}
})();
}
dataExtractor = function(json) {
if (json.success !== true || json.data === undefined || Array.isArray(json.data.results) !== true) {
return undefined;
}
return json.data.results;
};
offsetExtractor = function(json) {
return json.data.returnedResultCount + json.data.startingOffset < json.data.totalResults ? json.data.returnedResultCount + json.data.startingOffset : 0;
};
jsonClient(url, function(error, json) {
var dataArray, nextOffset;
if (error) {
sn.log("Error requesting data for {0}: {2}", urlHelper.keyDescription(), error);
requestCompletionHandler(error);
return;
}
dataArray = dataExtractor(json);
if (dataArray === undefined) {
sn.log("No data available for {0}", urlHelper.keyDescription());
requestCompletionHandler(error);
return;
}
if (results === undefined) {
results = dataArray;
} else {
results = results.concat(dataArray);
}
nextOffset = offsetExtractor(json);
if (nextOffset > 0) {
loadData(nextOffset);
} else {
requestCompletionHandler(error);
}
});
}
/**
* Get or set the callback function, invoked after all data has been loaded. The callback
* function will be passed two arguments: an error and the results.
*
* @param {function} [value] the callback function to use
* @return when used as a getter, the current callback function, otherwise this object
* @memberOf sn.api.datum.loader
* @preserve
*/
that.callback = function(value) {
if (!arguments.length) {
return finishedCallback;
}
if (typeof value === "function") {
finishedCallback = value;
}
return that;
};
/**
* Get or set additional URL parameters. The parameters are set as object properties.
* If a property value is an array, multiple parameters for that property will be added.
*
* @param {object} [value] the URL parameters to include with the JSON request
* @return when used as a getter, the URL parameters, otherwise this object
* @memberOf sn.api.datum.loader
* @preserve
*/
that.urlParameters = function(value) {
if (!arguments.length) return urlParameters;
if (typeof value === "object") {
urlParameters = value;
}
return that;
};
/**
* Get or set a JSON client function to use. The function must be compatible with <code>d3.json</code>
* and in fact defaults to that. You could set it to a <code>sn.net.securityHelper</code> instance
* to use security token API requests, for example.
*
* @param {function} [value] the JSON client function, compatible with <code>d3.json</code>.
* @return when used as a getter, the JSON client function, otherwise this object
* @since 1.1
* @preserve
*/
that.jsonClient = function(value) {
if (!arguments.length) return jsonClient;
if (typeof value === "function") {
jsonClient = value;
}
return that;
};