-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathSparkCore.js
1342 lines (1131 loc) · 44.4 KB
/
SparkCore.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 (c) 2015 Particle Industries, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
var EventEmitter = require('events').EventEmitter;
var moment = require('moment');
var extend = require("xtend");
var when = require("when");
var fs = require('fs');
var Message = require('h5.coap').Message;
var settings = require("../settings");
var ISparkCore = require("./ISparkCore");
var CryptoLib = require("../lib/ICrypto");
var messages = require("../lib/Messages");
var Handshake = require("../lib/Handshake");
var utilities = require("../lib/utilities.js");
var Flasher = require('../lib/Flasher');
var logger = require('../lib/logger.js');
//Hello — sent first by Core then by Server immediately after handshake, never again
//Ignored — sent by either side to respond to a message with a bad counter value. The receiver of an Ignored message can optionally decide to resend a previous message if the indicated bad counter value matches a recently sent message.
//package flasher
//Chunk — sent by Server to send chunks of a firmware binary to Core
//ChunkReceived — sent by Core to respond to each chunk, indicating the CRC of the received chunk data. if Server receives CRC that does not match the chunk just sent, that chunk is sent again
//UpdateBegin — sent by Server to initiate an OTA firmware update
//UpdateReady — sent by Core to indicate readiness to receive firmware chunks
//UpdateDone — sent by Server to indicate all firmware chunks have been sent
//FunctionCall — sent by Server to tell Core to call a user-exposed function
//FunctionReturn — sent by Core in response to FunctionCall to indicate return value. void functions will not send this message
//VariableRequest — sent by Server to request the value of a user-exposed variable
//VariableValue — sent by Core in response to VariableRequest to indicate the value
//Event — sent by Core to initiate a Server Sent Event and optionally an HTTP callback to a 3rd party
//KeyChange — sent by Server to change the AES credentials
/**
* Implementation of the Spark Core messaging protocol
* @SparkCore
*/
var SparkCore = function (options) {
if (options) {
this.options = extend(this.options, options);
}
EventEmitter.call(this);
this._tokens = {};
};
SparkCore.COUNTER_MAX = settings.message_counter_max;
SparkCore.TOKEN_MAX = settings.message_token_max;
SparkCore.prototype = extend(ISparkCore.prototype, EventEmitter.prototype, {
classname: "SparkCore",
options: {
HandshakeClass: Handshake
},
socket: null,
secureIn: null,
secureOut: null,
sendCounter: null,
sendToken: 0,
_tokens: null,
recvCounter: null,
apiSocket: null,
eventsSocket: null,
/**
* Our state describing which functions take what arguments
*/
coreFnState: null,
spark_product_id: null,
product_firmware_version: null,
/**
* Used to track calls waiting on a description response
*/
_describeDfd: null,
/**
* configure our socket and start the handshake
*/
startupProtocol: function () {
var that = this;
this.socket.setNoDelay(true);
this.socket.setKeepAlive(true, 15 * 1000); //every 15 second(s)
this.socket.on('error', function (err) {
that.disconnect("socket error " + err);
});
this.socket.on('close', function (err) { that.disconnect("socket close " + err); });
this.socket.on('timeout', function (err) { that.disconnect("socket timeout " + err); });
this.handshake();
},
handshake: function () {
var shaker = new this.options.HandshakeClass();
//when the handshake is done, we can expect two stream properties, 'secureIn' and 'secureOut'
shaker.handshake(this,
utilities.proxy(this.ready, this),
utilities.proxy(this.disconnect, this)
);
},
ready: function () {
//oh hai!
this._connStartTime = new Date();
logger.log("on ready", {
coreID: this.getHexCoreID(),
ip: this.getRemoteIPAddress(),
product_id: this.spark_product_id,
firmware_version: this.product_firmware_version,
cache_key: this._connection_key
});
//catch any and all describe responses
this.on('msg_describereturn', this.onDescribeReturn.bind(this));
this.on(('msg_' + 'PrivateEvent').toLowerCase(), this.onCorePrivateEvent.bind(this));
this.on(('msg_' + 'PublicEvent').toLowerCase(), this.onCorePublicEvent.bind(this));
this.on(('msg_' + 'Subscribe').toLowerCase(), this.onCorePublicSubscribe.bind(this));
this.on(('msg_' + 'GetTime').toLowerCase(), this.onCoreGetTime.bind(this));
this.emit("ready");
},
/**
* TODO: connect to API
* @param sender
* @param response
*/
sendApiResponse: function (sender, response) {
//such boom, wow, very events.
try {
this.emit(sender, sender, response);
}
catch (ex) {
logger.error("Error during response ", ex);
}
},
/**
* Handles messages coming from the API over our message queue service
*/
onApiMessage: function (sender, msg) {
if (!msg) {
logger.log('onApiMessage - no message? got ' + JSON.stringify(arguments), { coreID: this.getHexCoreID() });
return;
}
var that = this;
//if we're not the owner, then the socket is busy
var isBusy = (!this._checkOwner(null, function(err) {
logger.error(err + ": " + msg.cmd , { coreID: that.getHexCoreID() });
}));
if (isBusy) {
this.sendApiResponse(sender, { error: "This core is locked during the flashing process." });
return;
}
//TODO: simplify this more?
switch (msg.cmd) {
case "Describe":
if (isBusy) {
if (settings.logApiMessages) {
logger.log('Describe - flashing', { coreID: that.coreID });
}
that.sendApiResponse(sender, {
cmd: "DescribeReturn",
name: msg.name,
state: { f: [], v: [] },
product_id: that.spark_product_id,
firmware_version: that.product_firmware_version
});
}
else {
when(this.ensureWeHaveIntrospectionData()).then(
function () {
that.sendApiResponse(sender, {
cmd: "DescribeReturn",
name: msg.name,
state: that.coreFnState,
product_id: that.spark_product_id,
firmware_version: that.product_firmware_version
});
},
function (msg) {
that.sendApiResponse(sender, {
cmd: "DescribeReturn",
name: msg.name,
err: "Error, no device state"
});
}
);
}
break;
case "GetVar":
if (settings.logApiMessages) {
logger.log('GetVar', { coreID: that.coreID });
}
this.getVariable(msg.name, msg.type, function (value, buf, err) {
//don't forget to handle errors!
//if 'error' is set, then don't return the result.
//so we can correctly handle "Variable Not Found"
that.sendApiResponse(sender, {
cmd: "VarReturn",
name: msg.name,
error: err,
result: value
});
});
break;
case "SetVar":
if (settings.logApiMessages) {
logger.log('SetVar', { coreID: that.coreID });
}
this.setVariable(msg.name, msg.value, function (resp) {
//that.sendApiResponse(sender, resp);
var response = {
cmd: "VarReturn",
name: msg.name,
result: resp.getPayload().toString()
};
that.sendApiResponse(sender, response);
});
break;
case "CallFn":
if (settings.logApiMessages) {
logger.log('FunCall', { coreID: that.coreID });
}
this.callFunction(msg.name, msg.args, function (fnResult) {
var response = {
cmd: "FnReturn",
name: msg.name,
result: fnResult,
error: fnResult.Error
};
that.sendApiResponse(sender, response);
});
break;
case "UFlash":
if (settings.logApiMessages) {
logger.log('FlashCore', { coreID: that.coreID });
}
this.flashCore(msg.args.data, sender);
break;
case "FlashKnown":
if (settings.logApiMessages) {
logger.log('FlashKnown', { coreID: that.coreID, app: msg.app });
}
// Responsibility for sanitizing app names lies with API Service
// This includes only allowing apps whose binaries are deployed and thus exist
fs.readFile('known_firmware/' + msg.app + '_' + settings.environment + '.bin', function (err, buf) {
if (err) {
logger.log("Error flashing known firmware", { coreID: that.coreID, err: err });
that.sendApiResponse(sender, { cmd: "Event", name: "Update", message: "Update failed - " + JSON.stringify(err) });
return;
}
that.flashCore(buf, sender);
});
break;
case "RaiseHand":
if (isBusy) {
if (settings.logApiMessages) {
logger.log('SignalCore - flashing', { coreID: that.coreID });
}
that.sendApiResponse(sender, { cmd: "RaiseHandReturn", result: true });
}
else {
if (settings.logApiMessages) {
logger.log('SignalCore', { coreID: that.coreID });
}
var showSignal = (msg.args && msg.args.signal);
this.raiseYourHand(showSignal, function (result) {
that.sendApiResponse(sender, {
cmd: "RaiseHandReturn",
result: result
});
});
}
break;
case "Ping":
if (settings.logApiMessages) {
logger.log('Pinged, replying', { coreID: that.coreID });
}
this.sendApiResponse(sender, { cmd: "Pong", online: (this.socket != null), lastPing: this._lastCorePing });
break;
default:
this.sendApiResponse(sender, {error: "unknown message" });
}
},
/**
* Deals with messages coming from the core over our secure connection
* @param data
*/
routeMessage: function (data) {
var msg = messages.unwrap(data);
if (!msg) {
logger.error("routeMessage got a NULL coap message ", { coreID: this.getHexCoreID() });
return;
}
this._lastMessageTime = new Date();
//should be adequate
var msgCode = msg.getCode();
if ((msgCode > Message.Code.EMPTY) && (msgCode <= Message.Code.DELETE)) {
//probably a request
msg._type = messages.getRequestType(msg);
}
if (!msg._type) {
msg._type = this.getResponseType(msg.getTokenString());
}
//console.log("core got message of type " + msg._type + " with token " + msg.getTokenString() + " " + messages.getRequestType(msg));
if (msg.isAcknowledgement()) {
if (!msg._type) {
//no type, can't route it.
msg._type = 'PingAck';
}
this.emit(('msg_' + msg._type).toLowerCase(), msg);
return;
}
var nextPeerCounter = ++this.recvCounter;
if (nextPeerCounter > 65535) {
//TODO: clean me up! (I need settings, and maybe belong elsewhere)
this.recvCounter = nextPeerCounter = 0;
}
if (msg.isEmpty() && msg.isConfirmable()) {
this._lastCorePing = new Date();
//var delta = (this._lastCorePing - this._connStartTime) / 1000.0;
//logger.log("core ping @ ", delta, " seconds ", { coreID: this.getHexCoreID() });
this.sendReply("PingAck", msg.getId());
return;
}
if (!msg || (msg.getId() != nextPeerCounter)) {
logger.log("got counter ", msg.getId(), " expecting ", nextPeerCounter, { coreID: this.getHexCoreID() });
if (msg._type == "Ignored") {
//don't ignore an ignore...
this.disconnect("Got an Ignore");
return;
}
//this.sendMessage("Ignored", null, {}, null, null);
this.disconnect("Bad Counter");
return;
}
this.emit(('msg_' + msg._type).toLowerCase(), msg);
},
sendReply: function (name, id, data, token, onError, requester) {
if (!this._checkOwner(requester, onError, name)) {
return;
}
//if my reply is an acknowledgement to a confirmable message
//then I need to re-use the message id...
//set our counter
if (id < 0) {
id = this.getIncrSendCounter();
}
var msg = messages.wrap(name, id, null, data, token, null);
if (!this.secureOut) {
logger.error("SparkCore - sendReply before READY", { coreID: this.getHexCoreID() });
return;
}
this.secureOut.write(msg, null, null);
//logger.log("Replied with message of type: ", name, " containing ", data);
},
sendMessage: function (name, params, data, onResponse, onError, requester) {
if (!this._checkOwner(requester, onError, name)) {
return false;
}
//increment our counter
var id = this.getIncrSendCounter();
//TODO: messages of type 'NON' don't really need a token // alternatively: "no response type == no token"
var token = this.getNextToken();
this.useToken(name, token);
var msg = messages.wrap(name, id, params, data, token, onError);
if (!this.secureOut) {
logger.error("SparkCore - sendMessage before READY", { coreID: this.getHexCoreID() });
return;
}
this.secureOut.write(msg, null, null);
// logger.log("Sent message of type: ", name, " containing ", data,
// "BYTES: " + msg.toString('hex'));
return token;
},
/**
* Same as 'sendMessage', but sometimes the core can't handle Tokens on certain message types.
*
* Somewhat rare / special case, so this seems like a better option at the moment, should converge these
* back at some point
*/
sendNONTypeMessage: function (name, params, data, onResponse, onError, requester) {
if (!this._checkOwner(requester, onError, name)) {
return;
}
//increment our counter
var id = this.getIncrSendCounter();
var msg = messages.wrap(name, id, params, data, null, onError);
if (!this.secureOut) {
logger.error("SparkCore - sendMessage before READY", { coreID: this.getHexCoreID() });
return;
}
this.secureOut.write(msg, null, null);
//logger.log("Sent message of type: ", name, " containing ", data,
// "BYTES: " + msg.toString('hex'));
},
parseMessage: function (data) {
//we're assuming data is a serialized CoAP message
return messages.unwrap(data);
},
/**
* Adds a listener to our secure message stream
* @param name the message type we're waiting on
* @param uri - a particular function / variable?
* @param token - what message does this go with? (should come from sendMessage)
* @param callback what we should call when we're done
* @param [once] whether or not we should keep the listener after we've had a match
*/
listenFor: function (name, uri, token, callback, once) {
var tokenHex = (token) ? utilities.toHexString(token) : null;
var beVerbose = settings.showVerboseCoreLogs;
//TODO: failWatch? What kind of timeout do we want here?
//adds a one time event
var that = this,
evtName = ('msg_' + name).toLowerCase(),
handler = function (msg) {
if (uri && (msg.getUriPath().indexOf(uri) != 0)) {
if (beVerbose) {
logger.log("uri filter did not match", uri, msg.getUriPath(), { coreID: that.getHexCoreID() });
}
return;
}
if (tokenHex && (tokenHex != msg.getTokenString())) {
if (beVerbose) {
logger.log("Tokens did not match ", tokenHex, msg.getTokenString(), { coreID: that.getHexCoreID() });
}
return;
}
if (once) {
that.removeListener(evtName, handler);
}
process.nextTick(function () {
try {
if (beVerbose) {
logger.log('heard ', name, { coreID: that.coreID });
}
callback(msg);
}
catch (ex) {
logger.error("listenFor - caught error: ", ex, ex.stack, { coreID: that.getHexCoreID() });
}
});
};
//logger.log('listening for ', evtName);
this.on(evtName, handler);
return handler;
},
/**
* Gets or wraps
* @returns {null}
*/
getIncrSendCounter: function () {
this.sendCounter++;
if (this.sendCounter >= SparkCore.COUNTER_MAX) {
this.sendCounter = 0;
}
return this.sendCounter;
},
/**
* increments or wraps our token value, and makes sure it isn't in use
*/
getNextToken: function () {
this.sendToken++;
if (this.sendToken >= SparkCore.TOKEN_MAX) {
this.sendToken = 0;
}
this.clearToken(this.sendToken);
return this.sendToken;
},
/**
* Associates a particular token with a message we're sending, so we know
* what we're getting back when we get an ACK
* @param name
* @param token
*/
useToken: function (name, token) {
var key = utilities.toHexString(token);
this._tokens[key] = name;
},
/**
* Clears the association with a particular token
* @param token
*/
clearToken: function (token) {
var key = utilities.toHexString(token);
if (this._tokens[key]) {
delete this._tokens[key];
}
},
getResponseType: function (tokenStr) {
var request = this._tokens[tokenStr];
//logger.log('respType for key ', tokenStr, ' is ', request);
if (!request) {
return null;
}
return messages.getResponseType(request);
},
/**
* Ensures we have introspection data from the core, and then
* requests a variable value to be sent, when received it transforms
* the response into the appropriate type
* @param name
* @param type
* @param callback - expects (value, buf, err)
*/
getVariable: function (name, type, callback) {
var that = this;
var performRequest = function () {
if (!that.HasSparkVariable(name)) {
callback(null, null, "Variable not found");
return;
}
var token = this.sendMessage("VariableRequest", { name: name });
var varTransformer = this.transformVariableGenerator(name, callback);
this.listenFor("VariableValue", null, token, varTransformer, true);
}.bind(this);
if (this.hasFnState()) {
//slight short-circuit, saves ~5 seconds every 100,000 requests...
performRequest();
}
else {
when(this.ensureWeHaveIntrospectionData())
.then(
performRequest,
function (err) { callback(null, null, "Problem requesting variable: " + err);
});
}
},
setVariable: function (name, data, callback) {
/*TODO: data type! */
var payload = messages.ToBinary(data);
var token = this.sendMessage("VariableRequest", { name: name }, payload);
//are we expecting a response?
//watches the messages coming back in, listens for a message of this type with
this.listenFor("VariableValue", null, token, callback, true);
},
callFunction: function (name, args, callback) {
var that = this;
when(this.transformArguments(name, args)).then(
function (buf) {
if (settings.showVerboseCoreLogs) {
logger.log('sending function call to the core', { coreID: that.coreID, name: name });
}
var writeUrl = function(msg) {
msg.setUri("f/" + name);
if (buf) {
msg.setUriQuery(buf.toString());
}
return msg;
};
var token = that.sendMessage("FunctionCall", { name: name, args: buf, _writeCoapUri: writeUrl }, null);
//gives us a function that will transform the response, and call the callback with it.
var resultTransformer = that.transformFunctionResultGenerator(name, callback);
//watches the messages coming back in, listens for a message of this type with
that.listenFor("FunctionReturn", null, token, resultTransformer, true);
},
function (err) {
callback({Error: "Something went wrong calling this function: " + err});
}
);
},
/**
* Asks the core to start or stop its "raise your hand" signal
* @param showSignal - whether it should show the signal or not
* @param callback - what to call when we're done or timed out...
*/
raiseYourHand: function (showSignal, callback) {
var timer = setTimeout(function () { callback(false); }, 30 * 1000);
//TODO: that.stopListeningFor("RaiseYourHandReturn", listenHandler);
//TODO: var listenHandler = this.listenFor("RaiseYourHandReturn", ... );
//logger.log("RaiseYourHand: asking core to signal? " + showSignal);
var token = this.sendMessage("RaiseYourHand", { _writeCoapUri: messages.raiseYourHandUrlGenerator(showSignal) }, null);
this.listenFor("RaiseYourHandReturn", null, token, function () {
clearTimeout(timer);
callback(true);
}, true);
},
flashCore: function (binary, sender) {
var that = this;
if (!binary || (binary.length == 0)) {
logger.log("flash failed! - file is empty! ", { coreID: this.getHexCoreID() });
this.sendApiResponse(sender, { cmd: "Event", name: "Update", message: "Update failed - File was too small!" });
return
}
if (binary && binary.length > settings.MaxCoreBinaryBytes) {
logger.log("flash failed! - file is too BIG " + binary.length, { coreID: this.getHexCoreID() });
this.sendApiResponse(sender, { cmd: "Event", name: "Update", message: "Update failed - File was too big!" });
return;
}
var flasher = new Flasher();
flasher.startFlashBuffer(binary, this,
function () {
logger.log("flash core finished! - sending api event", { coreID: that.getHexCoreID() });
that.sendApiResponse(sender, { cmd: "Event", name: "Update", message: "Update done" });
},
function (msg) {
logger.log("flash core failed! - sending api event", { coreID: that.getHexCoreID(), error: msg });
that.sendApiResponse(sender, { cmd: "Event", name: "Update", message: "Update failed" });
},
function () {
logger.log("flash core started! - sending api event", { coreID: that.getHexCoreID() });
that.sendApiResponse(sender, { cmd: "Event", name: "Update", message: "Update started" });
});
},
_checkOwner: function (requester, onError, messageName) {
if (!this._owner || (this._owner == requester)) {
return true;
}
else {
//either call their callback, or log the error
var msg = "this client has an exclusive lock";
if (onError) {
process.nextTick(function () {
onError(msg);
});
}
else {
logger.error(msg, { coreID: this.getHexCoreID(), cache_key: this._connection_key, msgName: messageName });
}
return false;
}
},
takeOwnership: function (obj, onError) {
if (this._owner) {
logger.error("already owned", { coreID: this.getHexCoreID() });
if (onError) {
onError("Already owned");
}
return false;
}
else {
//only permit 'obj' to send messages
this._owner = obj;
return true;
}
},
releaseOwnership: function (obj) {
logger.log('releasing flash ownership ', { coreID: this.getHexCoreID() });
if (this._owner == obj) {
this._owner = null;
}
else if (this._owner) {
logger.error("cannot releaseOwnership, ", obj, " isn't the current owner ", { coreID: this.getHexCoreID() });
}
},
/**
* makes sure we have our introspection data, then transforms our object into
* the right coap query string
* @param name
* @param args
* @returns {*}
*/
transformArguments: function (name, args) {
var ready = when.defer();
var that = this;
when(this.ensureWeHaveIntrospectionData()).then(
function () {
var buf = that._transformArguments(name, args);
if (buf) {
ready.resolve(buf);
}
else {
//NOTE! The API looks for "Unknown Function" in the error response.
ready.reject("Unknown Function: " + name);
}
},
function (msg) {
ready.reject(msg);
}
);
return ready.promise;
},
transformFunctionResultGenerator: function (name, callback) {
var that = this;
return function (msg) {
that.transformFunctionResult(name, msg, callback);
};
},
/**
*
* @param name
* @param callback -- callback expects (value, buf, err)
* @returns {Function}
*/
transformVariableGenerator: function (name, callback) {
var that = this;
return function (msg) {
that.transformVariableResult(name, msg, callback);
};
},
/**
*
* @param name
* @param msg
* @param callback-- callback expects (value, buf, err)
* @returns {null}
*/
transformVariableResult: function (name, msg, callback) {
//grab the variable type, if the core doesn't say, assume it's a "string"
var fnState = (this.coreFnState) ? this.coreFnState.v : null;
var varType = (fnState && fnState[name]) ? fnState[name] : "string";
var niceResult = null, data = null;
try {
if (msg && msg.getPayload) {
//leaving raw payload in response message for now, so we don't shock our users.
data = msg.getPayload();
niceResult = messages.FromBinary(data, varType);
}
}
catch (ex) {
logger.error("transformVariableResult - error transforming response " + ex);
}
process.nextTick(function () {
try {
callback(niceResult, data);
}
catch (ex) {
logger.error("transformVariableResult - error in callback " + ex);
}
});
return null;
},
/**
* Transforms the result from a core function to the correct type.
* @param name
* @param msg
* @param callback
* @returns {null}
*/
transformFunctionResult: function (name, msg, callback) {
var varType = "int32"; //if the core doesn't specify, assume it's a "uint32"
//var fnState = (this.coreFnState) ? this.coreFnState.f : null;
//if (fnState && fnState[name] && fnState[name].returns) {
// varType = fnState[name].returns;
//}
var niceResult = null;
try {
if (msg && msg.getPayload) {
niceResult = messages.FromBinary(msg.getPayload(), varType);
}
}
catch (ex) {
logger.error("transformFunctionResult - error transforming response " + ex);
}
process.nextTick(function () {
try {
callback(niceResult);
}
catch (ex) {
logger.error("transformFunctionResult - error in callback " + ex);
}
});
return null;
},
/**
* transforms our object into a nice coap query string
* @param name
* @param args
* @private
*/
_transformArguments: function (name, args) {
//logger.log('transform args', { coreID: this.getHexCoreID() });
if (!args) {
return null;
}
if (!this.hasFnState()) {
logger.error("_transformArguments called without any function state!", { coreID: this.getHexCoreID() });
return null;
}
//TODO: lowercase function keys on new state format
name = name.toLowerCase();
var fn = this.coreFnState[name];
if (!fn || !fn.args) {
//maybe it's the old protocol?
var f = this.coreFnState.f;
if (f && utilities.arrayContainsLower(f, name)) {
//logger.log("_transformArguments - using old format", { coreID: this.getHexCoreID() });
//current / simplified function format (one string arg, int return type)
fn = {
returns: "int",
args: [
[null, "string" ]
]
};
}
}
if (!fn || !fn.args) {
//logger.error("_transformArguments: core doesn't know fn: ", { coreID: this.getHexCoreID(), name: name, state: this.coreFnState });
return null;
}
// "HelloWorld": { returns: "string", args: [ {"name": "string"}, {"adjective": "string"} ]} };
return messages.buildArguments(args, fn.args);
},
/**
* Checks our cache to see if we have the function state, otherwise requests it from the core,
* listens for it, and resolves our deferred on success
* @returns {*}
*/
ensureWeHaveIntrospectionData: function () {
if (this.hasFnState()) {
return when.resolve();
}
//if we don't have a message pending, send one.
if (!this._describeDfd) {
this.sendMessage("Describe");
this._describeDfd = when.defer();
}
//let everybody else queue up on this promise
return this._describeDfd.promise;
},
/**
* On any describe return back from the core
* @param msg
*/
onDescribeReturn: function(msg) {
//got a description, is it any good?
var loaded = (this.loadFnState(msg.getPayload()));
if (this._describeDfd) {
if (loaded) {
this._describeDfd.resolve();
}
else {
this._describeDfd.reject("something went wrong parsing function state")
}
}
//else { //hmm, unsolicited response, that's okay. }
},
//-------------
// Core Events / Spark.publish / Spark.subscribe
//-------------
onCorePrivateEvent: function(msg) {
this.onCoreSentEvent(msg, false);
},
onCorePublicEvent: function(msg) {
this.onCoreSentEvent(msg, true);
},
onCoreSentEvent: function(msg, isPublic) {
if (!msg) {
logger.error("CORE EVENT - msg obj was empty?!");
return;
}
//TODO: if the core is publishing messages too fast:
//this.sendReply("EventSlowdown", msg.getId());