forked from openbci-archive/OpenBCI_NodeJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenBCIBoard.js
1209 lines (1112 loc) · 53.1 KB
/
openBCIBoard.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';
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var stream = require('stream');
var serialPort = require('serialport');
var openBCISample = require('./openBCISample');
var k = openBCISample.k;
var openBCISimulator = require('./openBCISimulator');
/**
* @description SDK for OpenBCI Board {@link www.openbci.com}
* @module 'openbci-sdk'
*/
function OpenBCIFactory() {
var factory = this;
var _options = {
boardType: k.OBCIBoardDefault,
simulate: false,
simulatorSampleRate: 250,
baudrate: 115200,
verbose: false
};
/**
* @description The initialization method to call first, before any other method.
* @param options (optional) - Board optional configurations.
* - `boardType` - Specifies type of OpenBCI board
* 3 Possible Boards:
* `default` - 8 Channel OpenBCI board (Default)
* `daisy` - 8 Channel board with Daisy Module
* (NOTE: THIS IS IN-OP AT THIS TIME DUE TO NO ACCESS TO ACCESSORY BOARD)
* `ganglion` - 4 Channel board
* (NOTE: THIS IS IN-OP TIL RELEASE OF GANGLION BOARD 07/2016)
*
* - `simulate` - Full functionality, just mock data.
*
* - `simulatorSampleRate` - The sample rate to use for the simulator
* (Default is `250`)
*
* - `baudRate` - Baud Rate, defaults to 115200. Manipulating this is allowed if
* firmware on board has been previously configured.
*
* - `verbose` - Print out useful debugging events
* @constructor
* @author AJ Keller (@pushtheworldllc)
*/
function OpenBCIBoard(options) {
//var args = Array.prototype.slice.call(arguments);
options = (typeof options !== 'function') && options || {};
var opts = {};
stream.Stream.call(this);
/** Configuring Options */
opts.boardType = options.boardType || options.boardtype || _options.boardType;
opts.simulate = options.simulate || _options.simulate;
opts.simulatorSampleRate = options.simulatorSampleRate || options.simulatorsamplerate || _options.simulatorSampleRate;
opts.baudRate = options.baudRate || options.baudrate || _options.baudrate;
opts.verbose = options.verbose || _options.verbose;
// Set to global options object
this.options = opts;
/** Properties (keep alphabetical) */
// Arrays
this.writeOutArray = new Array(100);
// Bools
this.isLookingForKeyInBuffer = true;
// Buffers
this.masterBuffer = masterBufferMaker();
this.moneyBuf = new Buffer('$$$');
this.searchingBuf = this.moneyBuf;
// Objects
this.writer = null;
this.impedanceTest = {
active: false,
isTestingPInput: false,
isTestingNInput: false,
onChannel: 0,
sampleNumber: 0
};
// Numbers
this.badPackets = 0;
this.commandsToWrite = 0;
this.impedanceArray = openBCISample.impedanceArray(k.numberOfChannelsForBoardType(this.options.boardType));
this.writeOutDelay = k.OBCIWriteIntervalDelayMSShort;
// Strings
//TODO: Add connect immediately functionality, suggest this to be the default...
}
// This allows us to use the emitter class freely outside of the module
util.inherits(OpenBCIBoard, stream.Stream);
/**
* @description The essential precursor method to be called initially to establish a
* serial connection to the OpenBCI board.
* @param portName - a string that contains the port name of the OpenBCIBoard.
* @returns {Promise} if the board was able to connect. If at any time the serial port
* closes or errors then this promise will be rejected, and this should be
* observed and taken care of in the most front facing user methods.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.connect = function(portName) {
this.connected = false;
return new Promise((resolve,reject) => {
// If we are simulating, set boardSerial to fake name
var boardSerial;
/* istanbul ignore else */
if (this.options.simulate || portName === k.OBCISimulatorPortName) {
this.options.simulate = true;
if (this.options.verbose) console.log('using faux board ' + portName);
boardSerial = new openBCISimulator.OpenBCISimulator(portName, {
verbose: this.options.verbose
});
} else {
/* istanbul ignore if */
if (this.options.verbose) console.log('using real board ' + portName);
boardSerial = new serialPort.SerialPort(portName, {
baudRate: this.options.baudRate
},(err) => {
if (err) reject(err);
});
}
this.serial = boardSerial;
if(this.options.verbose) console.log('Serial port connected');
boardSerial.on('data',(data) => {
this._processBytes(data);
});
this.connected = true;
boardSerial.on('open',() => {
var timeoutLength = this.options.simulate ? 50 : 300;
if(this.options.verbose) console.log('Serial port open');
setTimeout(() => {
if(this.options.verbose) console.log('Sending stop command, in case the device was left streaming...');
this.write(k.OBCIStreamStop);
if (this.serial) this.serial.flush();
},timeoutLength);
setTimeout(() => {
if(this.options.verbose) console.log('Sending soft reset');
this.softReset();
resolve();
if(this.options.verbose) console.log("Waiting for '$$$'");
},timeoutLength + 100);
});
boardSerial.on('close',() => {
if (this.options.verbose) console.log('Serial Port Closed');
this.emit('close')
});
/* istanbul ignore next */
boardSerial.on('error',(err) => {
if (this.options.verbose) console.log('Serial Port Error');
this.emit('error',err);
});
});
};
/**
* @description Closes the serial port
* @returns {Promise} - fulfilled by a successful close of the serial port object, rejected otherwise.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.disconnect = function() {
var timeout = 0;
if (this.streaming) {
if(this.options.verbose) console.log('stop streaming');
this.streaming = false;
this.write(k.OBCIStreamStop);
timeout = 10;
}
return new Promise((resolve, reject) => {
setTimeout(() => {
if(!this.connected) reject('no board connected');
this.connected = false;
if (this.serial) {
this.serial.close(() => {
this.isLookingForKeyInBuffer = true;
resolve();
});
} else {
this.isLookingForKeyInBuffer = true;
resolve();
}
},timeout);
});
};
/**
* @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)
*/
OpenBCIBoard.prototype.streamStart = function() {
this.streaming = true;
this._reset();
return this.write(k.OBCIStreamStart);
};
/**
* @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)
*/
OpenBCIBoard.prototype.streamStop = function() {
this.streaming = false;
return this.write(k.OBCIStreamStop);
};
/**
* @description To start simulating an open bci board
* Note: Must be called after the constructor
* @returns {Promise} - Fulfilled if able to enter simulate mode, reject if not.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.simulatorEnable = function() {
return new Promise((resolve,reject) => {
if (this.options.simulate) reject('Already simulating'); // Are we already in simulate mode?
if (this.connected) {
this.disconnect() // disconnect first
.then(() => {
this.options.simulate = true;
resolve();
})
.catch(err => reject(err));
} else {
this.options.simulate = true;
resolve();
}
});
};
/**
* @description To stop simulating an open bci board
* Note: Must be called after the constructor
* @returns {Promise} - Fulfilled if able to stop simulate mode, reject if not.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.simulatorDisable = function() {
return new Promise((resolve,reject) => {
if (!this.options.simulate) reject('Not simulating'); // Are we already not in simulate mode?
if (this.connected) {
this.disconnect()
.then(() => {
this.options.simulate = false;
resolve();
})
.catch(err => reject(err));
} else {
this.options.simulate = false;
resolve();
}
});
};
/**
* @description To be able to easily write to the board but ensure that we never send a commands
* with less than a 10ms spacing between sends. This uses an array and pops off
* the entries until there are none left.
* @param dataToWrite - Either a single character or an Array of characters
* @returns {Promise}
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.write = function(dataToWrite) {
var writerFunction = () => {
/* istanbul ignore else */
if (this.commandsToWrite > 0) {
var command = this.writeOutArray.shift();
this.commandsToWrite--;
if (this.commandsToWrite === 0) {
this.writer = null;
} else {
this.writer = setTimeout(writerFunction,this.writeOutDelay);
}
this._writeAndDrain.call(this,command)
.catch(err => {
/* istanbul ignore if */
if(this.options.verbose) console.log('write failure: ' + err);
});
} else {
if(this.options.verbose) console.log('Big problem! Writer started with no commands to write');
}
};
return new Promise((resolve,reject) => {
//console.log('write method called');
if (!this.connected) reject('not connected');
if (this.serial === null || this.serial === undefined) {
reject('Serial port not configured');
} else {
var cmd = '';
if (Array.isArray(dataToWrite)) { // Got an input array
var len = dataToWrite.length;
cmd = dataToWrite[0];
for (var i = 0; i < len; i++) {
this.writeOutArray[this.commandsToWrite] = dataToWrite[i];
this.commandsToWrite++;
}
} else {
cmd = dataToWrite;
this.writeOutArray[this.commandsToWrite] = dataToWrite;
this.commandsToWrite++;
}
if(this.writer === null || this.writer === undefined) { //there is no writer started
this.writer = setTimeout(writerFunction,this.writeOutDelay);
}
resolve();
}
});
};
/**
* @description Should be used to send data to the board
* @param data
* @returns {Promise} if signal was able to be sent
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype._writeAndDrain = function(data) {
return new Promise((resolve,reject) => {
//console.log('boardSerial in [writeAndDrain]: ' + JSON.stringify(boardSerial) + ' with command ' + data);
if(!this.serial) reject('Serial port not open');
this.serial.write(data,(error,results) => {
if(results) {
this.serial.drain(function() {
resolve();
});
} else {
console.log('Error [writeAndDrain]: ' + error);
reject(error);
}
})
});
};
/**
* @description Automatically find an OpenBCI board.
* Note: This method is used for convenience and should be used when trying to
* connect to a board. If you find a case (i.e. a platform (linux,
* windows...) that this does not work, please open an issue and
* we will add support!
* @author AJ Keller (@pushtheworldllc)
* @returns {Promise} - Fulfilled with portName, rejected when can't find the board.
*/
OpenBCIBoard.prototype.autoFindOpenBCIBoard = function() {
var macSerialPrefix = 'usbserial-D';
return new Promise((resolve, reject) => {
/* istanbul ignore else */
serialPort.list((err, ports) => {
if(err) {
if (this.options.verbose) console.log('serial port err');
reject(err);
}
if(ports.some(port => {
if(port.comName.includes(macSerialPrefix)) {
this.portName = port.comName;
return true;
}
})) {
if (this.options.verbose) console.log('auto found board');
resolve(this.portName);
}
else {
if (this.options.verbose) console.log('could not find board');
reject('Could not auto find board');
}
});
})
};
/**
* @description List available ports so the user can choose a device when not
* automatically found.
* Note: This method is used for convenience essentially just wrapping up
* serial port.
* @author Andy Heusser (@andyh616)
* @returns {Promise}
*/
OpenBCIBoard.prototype.listPorts = function() {
return new Promise((resolve, reject) => {
serialPort.list((err, ports) => {
if(err) reject(err);
else {
ports.push( {
comName: k.OBCISimulatorPortName,
manufacturer: '',
serialNumber: '',
pnpId: '',
locationId: '',
vendorId: '',
productId: ''
});
resolve(ports);
}
})
})
};
/**
* @description Sends a soft reset command to the board
* @returns {Promise}
* Note: The softReset command MUST be sent to the board before you can start
* streaming.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.softReset = function() {
return this.write(k.OBCIMiscSoftReset);
};
/**
* @description To get the specified channelSettings register data from printRegisterSettings call
* @param channelNumber - a number
* @returns {Promise.<T>|*}
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.getSettingsForChannel = function(channelNumber) {
return k.channelSettingsKeyForChannel(channelNumber).then((newSearchingBuffer) => {
this.searchingBuf = newSearchingBuffer;
return this.printRegisterSettings();
});
};
/**
* @description To print out the register settings to the console
* @returns {Promise.<T>|*}
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.printRegisterSettings = function() {
return this.write(k.OBCIMiscQueryRegisterSettings).then(() => {
this.isLookingForKeyInBuffer = true; //need to wait for key in
});
};
/**
* @description Send a command to the board to turn a specified channel off
* @param channelNumber
* @returns {Promise.<T>}
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.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)
*/
OpenBCIBoard.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);
});
};
/**
* @description To send a channel setting command to the board
* @param channelNumber - Number (1-16)
* @param powerDown - Bool (true -> OFF, false -> ON (default))
* turns the channel on or off
* @param gain - Number (1,2,4,6,8,12,24(default))
* sets the gain for the channel
* @param inputType - String (normal,shorted,biasMethod,mvdd,temp,testsig,biasDrp,biasDrn)
* selects the ADC channel input source
* @param bias - Bool (true -> Include in bias (default), false -> remove from bias)
* selects to include the channel input in bias generation
* @param srb2 - Bool (true -> Connect this input to SRB2 (default),
* false -> Disconnect this input from SRB2)
* Select to connect (true) this channel's P input to the SRB2 pin. This closes
* a switch between P input and SRB2 for the given channel, and allows the
* P input to also remain connected to the ADC.
* @param srb1 - Bool (true -> connect all N inputs to SRB1,
* false -> Disconnect all N inputs from SRB1 (default))
* Select to connect (true) all channels' N inputs to SRB1. This effects all pins,
* and disconnects all N inputs from the ADC.
* @returns {Promise} resolves if sent, rejects on bad input or no board
*/
OpenBCIBoard.prototype.channelSet = function(channelNumber,powerDown,gain,inputType,bias,srb2,srb1) {
var arrayOfCommands = [];
return new Promise((resolve,reject) => {
k.getChannelSetter(channelNumber,powerDown,gain,inputType,bias,srb2,srb1).then((arr) => {
arrayOfCommands = arr;
resolve(this.write(arrayOfCommands));
}, function(err) {
reject(err);
});
});
};
/**
* @description To apply test signals to the channels on the OpenBCI board used to test for impedance. This can take a
* little while to actually run (<8 seconds)!
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.impedanceTestAllChannels = function() {
var upperLimit = k.OBCINumberOfChannelsDefault;
/* istanbul ignore if */
if (this.options.daisy) {
upperLimit = k.OBCINumberOfChannelsDaisy;
}
if (!this.streaming) return Promise.reject('Must be streaming!');
// Recursive function call
var completeChannelImpedanceTest = (channelNumber) => {
return new Promise((resolve,reject) => {
if (channelNumber > upperLimit) { // Base case!
this.emit('impedanceArray',this.impedanceArray);
this.impedanceTest.onChannel = 0;
resolve();
} else {
if (this.options.verbose) console.log('\n\nImpedance Test for channel ' + channelNumber);
this.impedanceTestChannel(channelNumber)
.then(() => {
return completeChannelImpedanceTest(channelNumber + 1);
/* istanbul ignore next */
}).catch(err => reject(err));
}
});
};
return completeChannelImpedanceTest(1);
};
/**
* @description To test specific input configurations of channels!
* @param arrayOfChannels - The array of configurations where:
* 'p' or 'P' is only test P input
* 'n' or 'N' is only test N input
* 'b' or 'B' is test both inputs (takes 66% longer to run)
* '-' to ignore channel
* EXAMPLE:
* For 8 channel board: ['-','N','n','p','P','-','b','b']
* (Note: it doesn't matter if capitalized or not)
* @returns {Promise} - Fulfilled with a loaded impedance object.
*/
OpenBCIBoard.prototype.impedanceTestChannels = function(arrayOfChannels) {
if (!Array.isArray(arrayOfChannels)) return Promise.reject('Input must be array of channels... See Docs!');
if (!this.streaming) return Promise.reject('Must be streaming!');
// Check proper length of array
if (arrayOfChannels.length != this.numberOfChannels()) return Promise.reject('Array length mismatch, should have ' + this.numberOfChannels() + ' but array has length ' + arrayOfChannels.length);
// Recursive function call
var completeChannelImpedanceTest = (channelNumber) => {
return new Promise((resolve,reject) => {
if (channelNumber > arrayOfChannels.length) { // Base case!
this.emit('impedanceArray',this.impedanceArray);
this.impedanceTest.onChannel = 0;
resolve();
} else {
if (this.options.verbose) console.log('\n\nImpedance Test for channel ' + channelNumber);
var testCommand = arrayOfChannels[channelNumber - 1];
if (testCommand === 'p' || testCommand === 'P') {
this.impedanceTestChannelInputP(channelNumber).then(() => {
return completeChannelImpedanceTest(channelNumber + 1);
}).catch(err => reject(err));
} else if (testCommand === 'n' || testCommand === 'N') {
this.impedanceTestChannelInputN(channelNumber).then(() => {
return completeChannelImpedanceTest(channelNumber + 1);
}).catch(err => reject(err));
} else if (testCommand === 'b' || testCommand === 'B') {
this.impedanceTestChannel(channelNumber).then(() => {
return completeChannelImpedanceTest(channelNumber + 1);
}).catch(err => reject(err));
} else { // skip ('-') condition
return completeChannelImpedanceTest(channelNumber + 1);
}
}
});
};
return completeChannelImpedanceTest(1);
};
/**
* @description Run a complete impedance test on a single channel, applying the test signal individually to P & N inputs.
* @param channelNumber - A Number, specifies which channel you want to test.
* @returns {Promise} - Fulfilled with a single channel impedance object.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.impedanceTestChannel = function(channelNumber) {
this.impedanceArray[channelNumber - 1] = openBCISample.impedanceObject(channelNumber);
return new Promise((resolve,reject) => {
this._impedanceTestSetChannel(channelNumber,true,false) // Sends command for P input on channel number.
.then(channelNumber => {
return this._impedanceTestCalculateChannel(channelNumber,true,false); // Calculates for P input of channel number
})
.then(channelNumber => {
return this._impedanceTestSetChannel(channelNumber,false,true); // Sends command for N input on channel number.
})
.then(channelNumber => {
return this._impedanceTestCalculateChannel(channelNumber,false,true); // Calculates for N input of channel number
})
.then(channelNumber => {
return this._impedanceTestSetChannel(channelNumber,false,false); // Sends command to stop applying test signal to P and N channel
})
.then(channelNumber => {
return this._impedanceTestFinalizeChannel(channelNumber,true,true); // Finalize the impedances.
})
.then((channelNumber) => resolve(this.impedanceArray[channelNumber - 1]))
.catch(err => reject(err));
});
};
/**
* @description Run impedance test on a single channel, applying the test signal only to P input.
* @param channelNumber - A Number, specifies which channel you want to test.
* @returns {Promise} - Fulfilled with a single channel impedance object.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.impedanceTestChannelInputP = function(channelNumber) {
this.impedanceArray[channelNumber - 1] = openBCISample.impedanceObject(channelNumber);
return new Promise((resolve,reject) => {
this._impedanceTestSetChannel(channelNumber,true,false) // Sends command for P input on channel number.
.then(channelNumber => {
return this._impedanceTestCalculateChannel(channelNumber,true,false); // Calculates for P input of channel number
})
.then(channelNumber => {
return this._impedanceTestSetChannel(channelNumber,false,false); // Sends command to stop applying test signal to P and N channel
})
.then(channelNumber => {
return this._impedanceTestFinalizeChannel(channelNumber,true,false); // Finalize the impedances.
})
.then((channelNumber) => resolve(this.impedanceArray[channelNumber - 1]))
.catch(err => reject(err));
});
};
/**
* @description Run impedance test on a single channel, applying the test signal to N input.
* @param channelNumber - A Number, specifies which channel you want to test.
* @returns {Promise} - Fulfilled with a single channel impedance object.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.impedanceTestChannelInputN = function(channelNumber) {
this.impedanceArray[channelNumber - 1] = openBCISample.impedanceObject(channelNumber);
return new Promise((resolve,reject) => {
this._impedanceTestSetChannel(channelNumber,false,true) // Sends command for N input on channel number.
.then(channelNumber => {
return this._impedanceTestCalculateChannel(channelNumber,false,true); // Calculates for N input of channel number
})
.then(channelNumber => {
return this._impedanceTestSetChannel(channelNumber,false,false); // Sends command to stop applying test signal to P and N channel
})
.then(channelNumber => {
return this._impedanceTestFinalizeChannel(channelNumber,false,true); // Finalize the impedances.
})
.then((channelNumber) => resolve(this.impedanceArray[channelNumber - 1]))
.catch(err => reject(err));
});
};
/* istanbul ignore next */
/**
* @description To apply the impedance test signal to an input for any given channel
* @param channelNumber - Number - The channel you want to test.
* @param pInput - A bool true if you want to apply the test signal to the P input, false to not apply the test signal.
* @param nInput - A bool true if you want to apply the test signal to the N input, false to not apply the test signal.
* @returns {Promise} - With Number value of channel number
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype._impedanceTestSetChannel = function(channelNumber, pInput, nInput) {
return new Promise((resolve,reject) => {
if(!this.connected) reject('Must be connected');
var delayInMS = 0;
/* istanbul ignore if */
if (this.options.verbose) {
if (pInput && !nInput) {
console.log('\tSending command to apply test signal to P input.');
} else if (!pInput && nInput) {
console.log('\tSending command to apply test signal to N input.');
} else if (pInput && nInput) {
console.log('\tSending command to apply test signal to P and N inputs.');
} else {
console.log('\tSending command to stop applying test signal to both P and N inputs.');
}
}
if (!pInput && !nInput) {
this.impedanceTest.active = false;
this.writeOutDelay = k.OBCIWriteIntervalDelayMSShort;
} else {
this.writeOutDelay = k.OBCIWriteIntervalDelayMSLong;
}
k.getImpedanceSetter(channelNumber,pInput,nInput).then((commandsArray) => {
this.write(commandsArray);
delayInMS += commandsArray.length * k.OBCIWriteIntervalDelayMSLong;
delayInMS += this.commandsToWrite * k.OBCIWriteIntervalDelayMSShort; // Account for commands waiting to be sent in the write buffer
setTimeout(() => {
/**
* If either pInput or nInput are true then we should start calculating impedance. Setting
* this.isCalculatingImpedance to true here allows us to route every sample for an impedance
* calculation instead of the normal sample output.
*/
if (pInput || nInput) this.impedanceTest.active = true;
resolve(channelNumber);
}, delayInMS); // Prevents emitting .impedanceArray before all setting commands have been applied
}, (err) => {
reject(err);
});
});
};
/**
* @description Calculates the impedance for a specified channel for a set time
* @param channelNumber - A Number, the channel number you want to test.
* @param pInput - A bool true if you want to calculate impedance on the P input, false to not calculate.
* @param nInput - A bool true if you want to calculate impedance on the N input, false to not calculate.
* @returns {Promise} - Resolves channelNumber as value on fulfill, rejects with error...
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype._impedanceTestCalculateChannel = function(channelNumber,pInput,nInput) {
/* istanbul ignore if */
if (this.options.verbose) {
if (pInput && !nInput) {
console.log('\tCalculating impedance for P input.');
} else if (!pInput && nInput) {
console.log('\tCalculating impedance for N input.');
} else if (pInput && nInput) {
console.log('\tCalculating impedance for P and N input.');
} else {
console.log('\tNot calculating impedance for either P and N input.');
}
}
return new Promise((resolve, reject) => {
if (channelNumber < 1 || channelNumber > this.numberOfChannels()) reject('Invalid channel number');
if (typeof pInput !== 'boolean') reject('Invalid Input: \'pInput\' must be of type Bool');
if (typeof nInput !== 'boolean') reject('Invalid Input: \'nInput\' must be of type Bool');
this.impedanceTest.onChannel = channelNumber;
this.impedanceTest.sampleNumber = 0; // Reset the sample number
this.impedanceTest.isTestingPInput = pInput;
this.impedanceTest.isTestingNInput = nInput;
//console.log(channelNumber + ' In calculate channel pInput: ' + pInput + ' this.impedanceTest.isTestingPInput: ' + this.impedanceTest.isTestingPInput);
//console.log(channelNumber + ' In calculate channel nInput: ' + nInput + ' this.impedanceTest.isTestingNInput: ' + this.impedanceTest.isTestingNInput);
setTimeout(() => { // Calculate for 250ms
this.impedanceTest.onChannel = 0;
/* istanbul ignore if */
if (this.options.verbose) {
if (pInput && !nInput) {
console.log('\tDone calculating impedance for P input.');
} else if (!pInput && nInput) {
console.log('\tDone calculating impedance for N input.');
} else if (pInput && nInput) {
console.log('\tDone calculating impedance for P and N input.');
} else {
console.log('\tNot calculating impedance for either P and N input.');
}
}
resolve(channelNumber);
}, 250);
});
};
/**
* @description Calculates average and gets textual value of impedance for a specified channel
* @param channelNumber - A Number, the channel number you want to finalize.
* @param pInput - A bool true if you want to finalize impedance on the P input, false to not finalize.
* @param nInput - A bool true if you want to finalize impedance on the N input, false to not finalize.
* @returns {Promise} - Resolves channelNumber as value on fulfill, rejects with error...
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype._impedanceTestFinalizeChannel = function(channelNumber,pInput,nInput) {
/* istanbul ignore if */
if (this.options.verbose) {
if (pInput && !nInput) {
console.log('\tFinalizing impedance for P input.');
} else if (!pInput && nInput) {
console.log('\tFinalizing impedance for N input.');
} else if (pInput && nInput) {
console.log('\tFinalizing impedance for P and N input.');
} else {
console.log('\tNot Finalizing impedance for either P and N input.');
}
}
return new Promise((resolve, reject) => {
if (channelNumber < 1 || channelNumber > this.numberOfChannels()) reject('Invalid channel number');
if (typeof pInput !== 'boolean') reject('Invalid Input: \'pInput\' must be of type Bool');
if (typeof nInput !== 'boolean') reject('Invalid Input: \'nInput\' must be of type Bool');
if (pInput) openBCISample.impedanceSummarize(this.impedanceArray[channelNumber - 1].P);
if (nInput) openBCISample.impedanceSummarize(this.impedanceArray[channelNumber - 1].N);
resolve(channelNumber);
});
};
/**
* @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
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.sampleRate = function() {
if(this.options.boardType === k.OBCIBoardDaisy) {
return k.OBCISampleRate125;
} else {
return k.OBCISampleRate250;
}
};
/**
* @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)
*/
OpenBCIBoard.prototype.numberOfChannels = function() {
if(this.options.boardType === k.OBCIBoardDaisy) {
return k.OBCINumberOfChannelsDaisy;
} else {
return k.OBCINumberOfChannelsDefault;
}
};
/**
* @description Consider the '_processBytes' method to be the work horse of this
* entire framework. This method gets called any time there is new
* data coming in on the serial port. If you are familiar with the
* 'serialport' package, then every time data is emitted, this function
* gets sent the input data.
* @param data - a buffer of unknown size
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype._processBytes = function(data) {
var sizeOfData = data.byteLength;
this.bytesIn += sizeOfData; // increment to keep track of how many bytes we are receiving
if(this.isLookingForKeyInBuffer) { //in a reset state
var sizeOfSearchBuf = this.searchingBuf.byteLength; // then size in bytes of the buffer we are searching for
for (var i = 0; i < sizeOfData - (sizeOfSearchBuf - 1); i++) {
if (this.searchingBuf.equals(data.slice(i, i + sizeOfSearchBuf))) { // slice a chunk of the buffer to analyze
if (this.searchingBuf.equals(this.moneyBuf)) {
if(this.options.verbose) console.log('Money!');
this.isLookingForKeyInBuffer = false; // critical!!!
this.emit('ready'); // tell user they are ready to stream, etc...
} else {
getChannelSettingsObj(data.slice(i)).then((channelSettingsObject) => {
this.emit('query',channelSettingsObject);
}, (err) => {
console.log('Error: ' + err);
});
this.searchingBuf = this.moneyBuf;
break;
}
}
}
} else { // steaming operation should lead here...
// send input data to master buffer
this._bufMerger(data);
// parse the master buffer
while(this.masterBuffer.packetsRead < this.masterBuffer.packetsIn) {
var rawPacket = this._bufPacketStripper();
var newSample = openBCISample.convertPacketToSample(rawPacket);
if(newSample) {
this.emit('rawDataPacket', rawPacket);
newSample._count = this.sampleCount++;
if(this.impedanceTest.active) {
if (this.impedanceTest.onChannel != 0) {
// Get an average of the impedance
openBCISample.impedanceCalculationForChannel(newSample,this.impedanceTest.onChannel)
.then(rawValue => {
impedanceTestApplyRaw.call(this,rawValue);
}).catch(err => {
console.log('Impedance calculation error: ' + err);
});
}
}
this.emit('sample', newSample);
} else {
this.badPackets++;
this._bufAlign(); // fix the buffer to start reading at next start byte
}
}
}
};
/**
* @description Merge an input buffer with the master buffer. Takes into account
* wrapping around the master buffer if we run out of space in
* the master buffer. Note that if you are not reading bytes from
* master buffer, you will lose them if you continue to call this
* method due to the overwrite nature of buffers
* @param inputBuffer
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype._bufMerger = function(inputBuffer) {
// we do a try, catch, paradigm to prevent fatal crashes while trying to read from the buffer
try {
var inputBufferSize = inputBuffer.byteLength;
if (inputBufferSize > k.OBCIMasterBufferSize) { /** Critical error condition */
console.log("input buffer too large...");
} else if (inputBufferSize < (k.OBCIMasterBufferSize - this.masterBuffer.positionWrite)) { /**Normal*/
// debug prints
// console.log('Storing input buffer of size: ' + inputBufferSize + ' to the master buffer at position: ' + this.masterBufferPositionWrite);
//there is room in the buffer, so fill it
inputBuffer.copy(this.masterBuffer.buffer,this.masterBuffer.positionWrite,0);
// update the write position
this.masterBuffer.positionWrite += inputBufferSize;
//store the number of packets read in
this.masterBuffer.packetsIn += Math.floor((inputBufferSize + this.masterBuffer.looseBytes) / k.OBCIPacketSize);
//console.log('Total packets to read: '+ this.masterBuffer.packetsIn);
// loose bytes results when there is not an even multiple of packets in the inputBuffer
// example: The first time this is ran there are only 68 bytes in the first call to this function
// therefore there are only two packets (66 bytes), these extra two bytes need to be saved for the next
// call and be considered in the next iteration so we can keep track of how many bytes we need to read.
this.masterBuffer.looseBytes = (inputBufferSize + this.masterBuffer.looseBytes) % k.OBCIPacketSize;
} else { /** Wrap around condition*/
//console.log('We reached the end of the master buffer');
//the new buffer cannot fit all the way into the master buffer, going to need to break it up...
var bytesSpaceLeftInMasterBuffer = k.OBCIMasterBufferSize - this.masterBuffer.positionWrite;
// fill the rest of the buffer
inputBuffer.copy(this.masterBuffer.buffer,this.masterBuffer.positionWrite,0,bytesSpaceLeftInMasterBuffer);
// overwrite the beginning of master buffer
var remainingBytesToWriteToMasterBuffer = inputBufferSize - bytesSpaceLeftInMasterBuffer;
inputBuffer.copy(this.masterBuffer.buffer,0,bytesSpaceLeftInMasterBuffer);
//this.masterBuffer.write(inputBuffer.slice(bytesSpaceLeftInMasterBuffer,inputBufferSize),0,remainingBytesToWriteToMasterBuffer);
//move the masterBufferPositionWrite
this.masterBuffer.positionWrite = remainingBytesToWriteToMasterBuffer;
// store the number of packets read
this.masterBuffer.packetsIn += Math.floor((inputBufferSize + this.masterBuffer.looseBytes) / k.OBCIPacketSize);
//console.log('Total packets to read: '+ this.masterBuffer.packetsIn);
// see if statement above for explanation of loose bytes
this.masterBuffer.looseBytes = (inputBufferSize + this.masterBuffer.looseBytes) % k.OBCIPacketSize;
}
}
catch (error) {
console.log('Error: ' + error);
}
};
/**
* @description Strip packets from the master buffer
* @returns {Buffer} A buffer containing a packet of 33 bytes long, ready to be read.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype._bufPacketStripper = function() {
try {
// not at end of master buffer
var rawPacket;
if(k.OBCIPacketSize < k.OBCIMasterBufferSize - this.masterBuffer.positionRead) {
// extract packet
rawPacket = this.masterBuffer.buffer.slice(this.masterBuffer.positionRead, this.masterBuffer.positionRead + k.OBCIPacketSize);
// move the read position pointer
this.masterBuffer.positionRead += k.OBCIPacketSize;
// increment packets read
this.masterBuffer.packetsRead++;
//console.log(rawPacket);
// return this raw packet
return rawPacket;
} else { //special case because we are at the end of the master buffer (must wrap)
// calculate the space left to read from for the partial packet
var part1Size = k.OBCIMasterBufferSize - this.masterBuffer.positionRead;
// make the first part of the packet
var part1 = this.masterBuffer.buffer.slice(this.masterBuffer.positionRead, this.masterBuffer.positionRead + part1Size);
// reset the read position to 0
this.masterBuffer.positionRead = 0;
// get part 2 size
var part2Size = k.OBCIPacketSize - part1Size;
// get the second part
var part2 = this.masterBuffer.buffer.slice(0, part2Size);
// merge the two parts
rawPacket = Buffer.concat([part1,part2], k.OBCIPacketSize);
// move the read position pointer
this.masterBuffer.positionRead += part2Size;
// increment packets read
this.masterBuffer.packetsRead++;