-
Notifications
You must be signed in to change notification settings - Fork 15
/
openBCIGanglion.js
2852 lines (2680 loc) · 84.1 KB
/
openBCIGanglion.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
"use strict";
const EventEmitter = require("events").EventEmitter;
const _ = require("lodash");
let noble;
let SerialPort;
const util = require("util");
// Local imports
const { utilities, constants, debug } = require("@openbci/utilities");
const k = constants;
const clone = require("clone");
const bufferEqual = require("buffer-equal");
// const Buffer = require('buffer/');
/**
* @typedef {Object} InitializationObject Board optional configurations.
* @property {Boolean} bled112 Whether to use bled112 as bluetooth driver or default to first available. (Default `false`)
*
* @property {Boolean} debug Print out a raw dump of bytes sent and received. (Default `false`)
*
* @property {Boolean} driverAutoInit Used to auto start either noble or the bled112 drivers (Default `true`)
*
* @property {Boolean} nobleAutoStart Automatically initialize `noble`. Subscribes to blue tooth state changes and such.
* (Default `true`)
*
* @property {Boolean} nobleScanOnPowerOn Start scanning for Ganglion BLE devices as soon as power turns on.
* (Default `true`)
*
* @property {Boolean} sendCounts Send integer raw counts instead of scaled floats.
* (Default `false`)
*
* @property {Boolean} simulate (IN-OP) Full functionality, just mock data. (Default `false`)
*
* @property {Boolean} simulatorBoardFailure (IN-OP) Simulates board communications failure. This occurs when the RFduino on
* the board is not polling the RFduino on the dongle. (Default `false`)
*
* @property {Boolean} simulatorHasAccelerometer Sets simulator to send packets with accelerometer data. (Default `true`)
*
* @property {Boolean} simulatorInjectAlpha Inject a 10Hz alpha wave in Channels 1 and 2 (Default `true`)
*
* @property {String} simulatorInjectLineNoise Injects line noise on channels.
* 3 Possible Options:
* `60Hz` - 60Hz line noise (Default) [America]
* `50Hz` - 50Hz line noise [Europe]
* `none` - Do not inject line noise.
*
* @property {Number} simulatorSampleRate The sample rate to use for the simulator. Simulator will set to 125 if
* `simulatorDaisyModuleAttached` is set `true`. However, setting this option overrides that
* setting and this sample rate will be used. (Default is `250`)
*
* @property {Boolean} - Print out useful debugging events. (Default `false`)
*/
/**
* Options object
* @type {InitializationObject}
* @private
*/
const _options = {
bled112: false,
debug: false,
driverAutoInit: true,
nobleAutoStart: true,
nobleScanOnPowerOn: true,
sendCounts: false,
simulate: false,
simulatorBoardFailure: false,
simulatorHasAccelerometer: true,
simulatorInternalClockDrift: 0,
simulatorInjectAlpha: true,
simulatorInjectLineNoise: [
k.OBCISimulatorLineNoiseHz60,
k.OBCISimulatorLineNoiseHz50,
k.OBCISimulatorLineNoiseNone
],
simulatorSampleRate: 200,
verbose: false
};
/**
* @description The initialization method to call first, before any other method.
* @param options {InitializationObject} (optional) - Board optional configurations.
* @param callback {function} (optional) - A callback function used to determine if the noble module was able to be started.
* This can be very useful on Windows when there is no compatible BLE device found.
* @constructor
* @author AJ Keller (@pushtheworldllc)
*/
function Ganglion(options, callback) {
if (!(this instanceof Ganglion)) {
return new Ganglion(options, callback);
}
if (options instanceof Function) {
callback = options;
options = {};
}
options = (typeof options !== "function" && options) || {};
let opts = {};
/** Configuring Options */
let o;
for (o in _options) {
let userOption = o in options ? o : o.toLowerCase();
let userValue = options[userOption];
delete options[userOption];
if (typeof _options[o] === "object") {
// an array specifying a list of choices
// if the choice is not in the list, the first one is defaulted to
if (_options[o].indexOf(userValue) !== -1) {
opts[o] = userValue;
} else {
opts[o] = _options[o][0];
}
} else {
// anything else takes the user value if provided, otherwise is a default
if (userValue !== undefined) {
opts[o] = userValue;
} else {
opts[o] = _options[o];
}
}
}
for (o in options)
throw new Error('"' + o + '" is not a valid option');
// Set to global options object
/**
* @type {InitializationObject}
*/
this.options = clone(opts);
/** Private Properties (keep alphabetical) */
this._accelArray = [0, 0, 0];
this._bled112Characteristics = [];
this._bled112Connected = false;
this._bled112Connection = -1;
this._bled112GanglionGroup = null;
this._bled112ParsingMode = kOBCIBLED112ParsingNormal;
this._bled112ParseParallelProcedureComplete = false;
this._bled112ParsingAttributeValue = {
buffer: Buffer.from([]),
ignore: 1,
length: 0,
lengthPosition: 8,
verify: {
position: 1,
comparePosition: 8,
difference: 5
},
word: bleEvtAttclientAttributeValue
};
this._bled112ParsingAttributeWrite = {
buffer: Buffer.from([]),
length: 7,
word: bleRspAttclientAttributeWrite
};
this._bled112ParsingConnectionStatus = {
buffer: Buffer.from([]),
length: 20,
word: bleEvtConnectionStatus
};
this._bled112ParsingConnectDirect = {
buffer: Buffer.from([]),
length: 7,
word: bleRspGapConnectDirect
};
this._bled112ParsingDisconnect = {
buffer: Buffer.from([]),
length: 7,
word: bleRspGapDisconnect
};
this._bled112ParsingDiscover = {
buffer: Buffer.from([]),
length: 30,
word: bleEvtGapScanResponse
};
this._bled112ParsingFindInfoLong = {
buffer: Buffer.from([]),
length: 24,
verify: {
position: 7,
value: 0x10
},
word: bleEvtAttclientFindInformationFoundLong
};
this._bled112ParsingFindInfoShort = {
buffer: Buffer.from([]),
length: 10,
verify: {
position: 7,
value: 0x02
},
word: bleEvtAttclientFindInformationFoundShort
};
this._bled112ParsingGroup = {
buffer: Buffer.from([]),
length: 12,
word: bleEvtAttclientGroupFound
};
this._bled112ParsingProcedureComplete = {
buffer: Buffer.from([]),
length: 9,
word: bleEvtAttclientProcedureCompleted
};
/** @type {BLED112FindInformationFound} */
this._bled112WriteCharacteristic = null;
this._connected = false;
this._decompressedSamples = new Array(3);
this._droppedPacketCounter = 0;
this._firstPacket = true;
this._localName = null;
this._packetCounter = k.OBCIGanglionByteId18Bit.max;
this._peripheral = null;
this._rawDataPacketToSample = k.rawDataToSampleObjectDefault(
k.numberOfChannelsForBoardType(k.OBCIBoardGanglion)
);
this._rawDataPacketToSample.scale = !this.options.sendCounts;
this._rawDataPacketToSample.sendCounts = this.options.sendCounts;
this._rawDataPacketToSample.protocol = k.OBCIProtocolBLE;
this._rawDataPacketToSample.verbose = this.options.verbose;
this._rfduinoService = null;
this._receiveCharacteristic = null;
this._scanning = false;
this._sendCharacteristic = null;
this._streaming = false;
/** Public Properties (keep alphabetical) */
this.buffer = null;
this.ganglionPeripheralArray = [];
this.manualDisconnect = false;
this.peripheralArray = [];
this.previousPeripheralArray = [];
/** Initializations */
for (let i = 0; i < 3; i++) {
this._decompressedSamples[i] = [0, 0, 0, 0];
}
if (this.options.driverAutoInit) {
this.initDriver()
.then(() => {
if (callback) callback();
})
.catch(err => {
if (callback) callback(err);
});
} else {
if (callback) callback();
}
}
// This allows us to use the emitter class freely outside of the module
util.inherits(Ganglion, EventEmitter);
/**
* Used to enable the accelerometer. Will result in accelerometer packets arriving 10 times a second.
* Note that the accelerometer is enabled by default.
* @return {Promise}
*/
Ganglion.prototype.accelStart = function() {
return this.write(k.OBCIAccelStart);
};
/**
* Used to disable the accelerometer. Prevents accelerometer data packets from arriving.
* @return {Promise}
*/
Ganglion.prototype.accelStop = function() {
return this.write(k.OBCIAccelStop);
};
/**
* Used to start a scan if power is on. Useful if a connection is dropped.
*/
Ganglion.prototype.autoReconnect = function() {
// TODO: send back reconnect status, or reconnect fail
if (noble.state === k.OBCINobleStatePoweredOn) {
this._nobleScanStart();
} else {
console.warn("BLE not AVAILABLE");
}
};
/**
* @description Send a command to the board to turn a specified channel off
* @param channelNumber
* @returns {Promise.<T>}
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.channelOff = function(channelNumber) {
return k.commandChannelOff(channelNumber).then(charCommand => {
// console.log('sent command to turn channel ' + channelNumber + ' by sending command ' + charCommand)
return this.write(charCommand);
});
};
/**
* @description Send a command to the board to turn a specified channel on
* @param channelNumber
* @returns {Promise.<T>|*}
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.channelOn = function(channelNumber) {
return k.commandChannelOn(channelNumber).then(charCommand => {
// console.log('sent command to turn channel ' + channelNumber + ' by sending command ' + charCommand)
return this.write(charCommand);
});
};
/**
* Used to clean up emitters
*/
Ganglion.prototype.cleanupEmitters = function() {
this.removeAllListeners("droppedPacket");
this.removeAllListeners("accelerometer");
this.removeAllListeners("sample");
this.removeAllListeners("message");
this.removeAllListeners("impedance");
this.removeAllListeners("close");
this.removeAllListeners("error");
this.removeAllListeners("ganglionFound");
this.removeAllListeners("ready");
};
/**
* @description The essential precursor method to be called initially to establish a
* ble connection to the OpenBCI ganglion board.
* @param id {String | Object} - a string local name or peripheral object
* @returns {Promise} If the board was able to connect.
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.connect = function(id) {
return new Promise((resolve, reject) => {
if (_.isString(id)) {
if (this.options.bled112) {
let gPerih = null;
_.forEach(this.peripheralArray, peripheral => {
if (peripheral.advertisementDataString === id) {
gPerih = peripheral;
}
});
if (gPerih) {
this._bled112Connect(gPerih)
.then(resolve)
.catch(reject);
}
} else {
k.getPeripheralWithLocalName(this.ganglionPeripheralArray, id)
.then(p => {
return this._nobleConnect(p);
})
.then(resolve)
.catch(reject);
}
} else if (_.isObject(id)) {
let func;
if (this.options.bled112) func = this._bled112Connect.bind(this);
else func = this._nobleConnect.bind(this);
func(id)
.then(resolve)
.catch(reject);
} else {
reject(k.OBCIErrorInvalidByteLength);
}
});
};
/**
* Destroys the noble!
*/
Ganglion.prototype.destroyNoble = function() {
this._nobleDestroy();
};
/**
* Destroys the noble!
*/
Ganglion.prototype.destroyBLED112 = function() {
if (this.options.verbose) console.log("destroyBLED112");
this._bled112SerialClose();
};
/**
* Destroys the multi packet buffer.
*/
Ganglion.prototype.destroyMultiPacketBuffer = function() {
this._rawDataPacketToSample.multiPacketBuffer = null;
};
/**
* @description Closes the connection to the board. Waits for stop streaming command to
* be sent if currently streaming.
* @param stopStreaming {Boolean} (optional) - True if you want to stop streaming before disconnecting.
* @returns {Promise} - fulfilled by a successful close, rejected otherwise.
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.disconnect = function(stopStreaming) {
// no need for timeout here; streamStop already performs a delay
return Promise.resolve()
.then(() => {
if (stopStreaming) {
if (this.isStreaming()) {
if (this.options.verbose) console.log("stop streaming");
return this.streamStop();
}
}
return Promise.resolve();
})
.then(() => {
return new Promise((resolve, reject) => {
// serial emitting 'close' will call _disconnected
if (this._bled112Connection >= 0) {
if (this.options.verbose)
console.log("Calling disconnect on bled112");
let disconnectTimeout = null;
this.once(kOBCIEmitterBLED112RspGapDisconnect, () => {
if (this.options.verbose)
console.log("Disconnected as clean as possible");
clearTimeout(disconnectTimeout);
this._disconnected();
resolve();
});
this._bled112Disconnect()
.then(() => {
disconnectTimeout = setTimeout(() => {
reject(Error("Failed to get disconnect message"));
}, 1000);
})
.catch(err => {
this._disconnected();
reject(err);
});
} else if (this._peripheral) {
this._peripheral.disconnect(err => {
if (err) {
this._disconnected();
reject(err);
} else {
this._disconnected();
resolve();
}
});
} else {
reject("no peripheral to disconnect");
}
});
});
};
/**
* Return the local name of the attached Ganglion device.
* @return {null|String}
*/
Ganglion.prototype.getLocalName = function() {
return this._localName;
};
/**
* Get's the multi packet buffer.
* @return {null|Buffer} - Can be null if no multi packets received.
*/
Ganglion.prototype.getMutliPacketBuffer = function() {
return this._rawDataPacketToSample.multiPacketBuffer;
};
/**
* Call to start testing impedance.
* @return {global.Promise|Promise}
*/
Ganglion.prototype.impedanceStart = function() {
return this.write(k.OBCIGanglionImpedanceStart);
};
/**
* Call to stop testing impedance.
* @return {global.Promise|Promise}
*/
Ganglion.prototype.impedanceStop = function() {
return this.write(k.OBCIGanglionImpedanceStop);
};
/**
* Initialize the drivers
* @returns {Promise<any>}
*/
Ganglion.prototype.initDriver = function(portName) {
return new Promise((resolve, reject) => {
try {
if (this.options.bled112) {
SerialPort = require("serialport");
if (portName) {
this._bled112Init(portName)
.then(() => {
resolve();
})
.catch(reason => {
reject(reason);
});
} else {
SerialPort.list((err, ports) => {
if (err) {
reject(err);
} else {
const portPre = /\/dev\/tty.usbmodem/;
let bledPort = null;
for (let port of ports) {
if (process.platform === "win32") {
if (port.pnpId === "USB\\VID_2458&PID_0001\\1") {
bledPort = port;
break;
}
} else if (process.platform === "linux") {
if (
port.pnpId ===
"usb-Bluegiga_Low_Energy_Dongle_1-if00"
) {
bledPort = port;
break;
}
} else {
if (port.comName.match(portPre) !== null) {
bledPort = port;
break;
}
}
}
if (bledPort) {
this._bled112Init(bledPort.comName)
.then(() => {
resolve();
})
.catch(reason => {
reject(reason);
});
} else {
reject(Error("No BLED112 port found"));
}
}
});
}
} else {
noble = require("noble-mac");
if (this.options.nobleAutoStart) this._nobleInit(); // It get's the noble going
resolve();
}
} catch (e) {
reject(e);
}
});
};
/**
* @description Checks if the driver is connected to a board.
* @returns {boolean} - True if connected.
*/
Ganglion.prototype.isConnected = function() {
return this._connected;
};
/**
* @description Checks if bluetooth is powered on.
* @returns {boolean} - True if bluetooth is powered on.
*/
Ganglion.prototype.isNobleReady = function() {
return this._nobleReady();
};
/**
* @description Checks if noble is currently scanning.
* @returns {boolean} - True if streaming.
*/
Ganglion.prototype.isSearching = function() {
return this._scanning;
};
/**
* @description Checks if the board is currently sending samples.
* @returns {boolean} - True if streaming.
*/
Ganglion.prototype.isStreaming = function() {
return this._streaming;
};
/**
* @description This function is used as a convenience method to determine how many
* channels the current board is using.
* @returns {Number} A number
* Note: This is dependent on if you configured the board correctly on setup options
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.numberOfChannels = function() {
return k.OBCINumberOfChannelsGanglion;
};
/**
* @description To print out the register settings to the console
* @returns {Promise.<T>|*}
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.printRegisterSettings = function() {
return this.write(k.OBCIMiscQueryRegisterSettings);
};
/**
* @description Get the the current sample rate is.
* @returns {Number} The sample rate
* Note: This is dependent on if you configured the board correctly on setup options
*/
Ganglion.prototype.sampleRate = function() {
if (this.options.simulate) {
return this.options.simulatorSampleRate;
} else {
return k.OBCISampleRate200;
}
};
/**
* @description List available peripherals so the user can choose a device when not
* automatically found.
* @param `maxSearchTime` {Number} - The amount of time to spend searching. (Default is 20 seconds)
* @returns {Promise} - If scan was started
*/
Ganglion.prototype.searchStart = function(maxSearchTime) {
const searchTime = maxSearchTime || k.OBCIGanglionBleSearchTime;
return new Promise((resolve, reject) => {
this._searchTimeout = setTimeout(() => {
if (this.options.bled112) {
this._bled112ScanStop().catch(reject);
} else {
this._nobleScanStop().catch(reject);
}
reject("Timeout: Unable to find Ganglion");
}, searchTime);
if (this.options.bled112) {
this._bled112ScanStart()
.then(() => {
resolve();
})
.catch(err => {
if (err !== k.OBCIErrorNobleAlreadyScanning) {
// If it's already scanning
clearTimeout(this._searchTimeout);
reject(err);
}
});
} else {
this._nobleScanStart()
.then(() => {
resolve();
})
.catch(err => {
if (err !== k.OBCIErrorNobleAlreadyScanning) {
// If it's already scanning
clearTimeout(this._searchTimeout);
reject(err);
}
});
}
});
};
/**
* Called to end a search.
* @return {global.Promise|Promise}
*/
Ganglion.prototype.searchStop = function() {
if (this.options.bled112) {
return this._bled112ScanStop();
} else {
return this._nobleScanStop();
}
};
/**
* @description Sends a soft reset command to the board
* @returns {Promise} - Fulfilled if the command was sent to board.
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.softReset = function() {
return this.write(k.OBCIMiscSoftReset);
};
/**
* @description Sends a start streaming command to the board.
* @returns {Promise} indicating if the signal was able to be sent.
* Note: You must have successfully connected to an OpenBCI board using the connect
* method. Just because the signal was able to be sent to the board, does not
* mean the board will start streaming.
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.streamStart = function() {
return new Promise((resolve, reject) => {
if (this.isStreaming())
return reject("Error [.streamStart()]: Already streaming");
this.once("sample", () => {
this._streaming = true;
});
this.write(k.OBCIStreamStart)
.then(() => {
if (this.options.verbose)
console.log("Sent stream start to board.");
if (this.options.bled112) this._bled112ParseForNormal();
resolve();
})
.catch(reject);
});
};
/**
* @description Sends a stop streaming command to the board.
* @returns {Promise} indicating if the signal was able to be sent.
* Note: You must have successfully connected to an OpenBCI board using the connect
* method. Just because the signal was able to be sent to the board, does not
* mean the board stopped streaming.
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.streamStop = function() {
return new Promise((resolve, reject) => {
if (!this.isStreaming())
return reject("Error [.streamStop()]: No stream to stop");
this._streaming = false;
this.write(k.OBCIStreamStop)
.then(() => {
resolve();
})
.catch(reject);
});
};
/**
* @description Puts the board in synthetic data generation mode. Must call streamStart still.
* @returns {Promise} indicating if the signal was able to be sent.
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.syntheticEnable = function() {
return new Promise((resolve, reject) => {
this.write(k.OBCIGanglionSyntheticDataEnable)
.then(() => {
if (this.options.verbose)
console.log("Enabled synthetic data mode.");
resolve();
})
.catch(reject);
});
};
/**
* @description Takes the board out of synthetic data generation mode. Must call streamStart still.
* @returns {Promise} - fulfilled if the command was sent.
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.syntheticDisable = function() {
return new Promise((resolve, reject) => {
this.write(k.OBCIGanglionSyntheticDataDisable)
.then(() => {
if (this.options.verbose)
console.log("Disabled synthetic data mode.");
resolve();
})
.catch(reject);
});
};
/**
* @description Used to send data to the board.
* @param data {Array | Buffer | Number | String} - The data to write out
* @returns {Promise} - fulfilled if command was able to be sent
* @author AJ Keller (@pushtheworldllc)
*/
Ganglion.prototype.write = function(data) {
return new Promise((resolve, reject) => {
if (this._sendCharacteristic) {
if (!Buffer.isBuffer(data)) {
data = new Buffer(data);
}
this._sendCharacteristic.write(data, true, err => {
if (err) {
reject(err);
} else {
if (this.options.debug) debug.default(">>>", data);
resolve();
}
});
} else if (this._bled112WriteCharacteristic) {
this.once(kOBCIEmitterBLED112RspAttclientAttributeWrite, res => {
if (bufferEqual(res.result, bleResultNoError)) {
resolve();
} else {
reject(
Error(
"Unable to write to BLED112 attribute",
res.result[0] | res.result[1]
)
);
}
});
this._bled112ParseForNormal();
this._bled112WriteAndDrain(
this._bled112GetAttributeWrite({
characteristicHandleRaw: this._bled112WriteCharacteristic
.characteristicHandleRaw,
connection: this._bled112WriteCharacteristic.connection,
value: data
})
).catch(reject);
} else {
reject("Send characteristic not set, please call connect method");
}
});
};
// //////// //
// PRIVATES //
/**
* @description Called once when for any reason the ble connection is no longer open.
* @private
*/
Ganglion.prototype._disconnected = function() {
this._streaming = false;
this._connected = false;
// Clean up _noble
// TODO: Figure out how to fire function on process ending from inside module
// noble.removeListener('discover', this._nobleOnDeviceDiscoveredCallback);
if (this._receiveCharacteristic) {
this._receiveCharacteristic.removeAllListeners(
k.OBCINobleEmitterServiceRead
);
}
this._receiveCharacteristic = null;
if (this._rfduinoService) {
this._rfduinoService.removeAllListeners(
k.OBCINobleEmitterServiceCharacteristicsDiscover
);
}
this._rfduinoService = null;
if (this._peripheral) {
this._peripheral.removeAllListeners(
k.OBCINobleEmitterPeripheralConnect
);
this._peripheral.removeAllListeners(
k.OBCINobleEmitterPeripheralDisconnect
);
this._peripheral.removeAllListeners(
k.OBCINobleEmitterPeripheralServicesDiscover
);
}
this._peripheral = null;
if (!this.manualDisconnect) {
// this.autoReconnect();
}
if (this.options.verbose) console.log(`Private disconnect clean up`);
this.emit("close");
};
/**
* Call to destroy the noble event emitters.
* @private
*/
Ganglion.prototype._nobleDestroy = function() {
if (noble) {
noble.removeAllListeners(k.OBCINobleEmitterStateChange);
noble.removeAllListeners(k.OBCINobleEmitterDiscover);
}
};
Ganglion.prototype._nobleConnect = function(peripheral) {
return new Promise((resolve, reject) => {
if (this.isConnected()) return reject("already connected!");
this._peripheral = peripheral;
this._localName = peripheral.advertisement.localName;
// if (_.contains(_peripheral.advertisement.localName, rfduino.localNamePrefix)) {
// TODO: slice first 8 of localName and see if that is ganglion
// here is where we can capture the advertisement data from the rfduino and check to make sure its ours
if (this.options.verbose)
console.log(
"Device is advertising '" +
this._peripheral.advertisement.localName +
"' service."
);
// TODO: filter based on advertising name ie make sure we are looking for the right thing
// if (this.options.verbose) console.log("serviceUUID: " + this._peripheral.advertisement.serviceUuids);
this._peripheral.on(k.OBCINobleEmitterPeripheralConnect, () => {
// if (this.options.verbose) console.log("got connect event");
this._peripheral.discoverServices();
if (this.isSearching()) this._nobleScanStop();
});
this._peripheral.on(k.OBCINobleEmitterPeripheralDisconnect, () => {
if (this.options.verbose) console.log("Peripheral disconnected");
this._disconnected();
});
this._peripheral.on(
k.OBCINobleEmitterPeripheralServicesDiscover,
services => {
for (let i = 0; i < services.length; i++) {
if (services[i].uuid === k.SimbleeUuidService) {
this._rfduinoService = services[i];
// if (this.options.verbose) console.log("Found simblee Service");
break;
}
}
if (!this._rfduinoService) {
reject("Couldn't find the simblee service.");
}
this._rfduinoService.once(
k.OBCINobleEmitterServiceCharacteristicsDiscover,
characteristics => {
if (this.options.verbose)
console.log(
"Discovered " +
characteristics.length +
" service characteristics"
);
for (let i = 0; i < characteristics.length; i++) {
// console.log(characteristics[i].uuid);
if (characteristics[i].uuid === k.SimbleeUuidReceive) {
if (this.options.verbose)
console.log("Found receiveCharacteristicUUID");
this._receiveCharacteristic = characteristics[i];
}
if (characteristics[i].uuid === k.SimbleeUuidSend) {
if (this.options.verbose)
console.log("Found sendCharacteristicUUID");
this._sendCharacteristic = characteristics[i];
}
}
if (
this._receiveCharacteristic &&
this._sendCharacteristic
) {
this._receiveCharacteristic.on(
k.OBCINobleEmitterServiceRead,
data => {
// TODO: handle all the data, both streaming and not
this._processBytes(data);
}
);
// if (this.options.verbose) console.log('Subscribing for data notifications');
this._receiveCharacteristic.notify(true);
this._connected = true;
this.emit(k.OBCIEmitterReady);
resolve();
} else {
reject(
"unable to set both receive and send characteristics!"
);
}
}
);
this._rfduinoService.discoverCharacteristics();
}
);
// if (this.options.verbose) console.log("Calling connect");
this._peripheral.connect(err => {
if (err) {
if (this.options.verbose)
console.log(`Unable to connect with error: ${err}`);
this._disconnected();
reject(err);
}
});
});
};
/**
* Call to add the noble event listeners.
* @private
*/
Ganglion.prototype._nobleInit = function() {
noble.on(k.OBCINobleEmitterStateChange, state => {
// TODO: send state change error to gui
// If the peripheral array is empty, do a scan to fill it.