forked from openbci-archive/OpenBCI_NodeJS
-
Notifications
You must be signed in to change notification settings - Fork 6
/
openBCIBoard.js
2273 lines (2089 loc) · 105 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,
util = require('util'),
stream = require('stream'),
serialPort = require('serialport'),
openBCISample = require('./openBCISample'),
k = openBCISample.k,
openBCISimulator = require('./openBCISimulator'),
now = require('performance-now'),
Sntp = require('sntp'),
StreamSearch = require('streamsearch'),
bufferEqual = require('buffer-equal'),
math = require('mathjs');
/**
* @description SDK for OpenBCI Board {@link www.openbci.com}
* @module 'openbci-sdk'
*/
function OpenBCIFactory() {
var factory = this;
var _options = {
boardType: k.OBCIBoardDefault,
baudrate: 115200,
simulate: false,
simulatorBoardFailure: false,
simulatorDaisyModuleAttached: false,
simulatorFirmwareVersion: k.OBCIFirmwareV1,
simulatorHasAccelerometer: true,
simulatorInternalClockDrift: 0,
simulatorInjectAlpha: true,
simulatorInjectLineNoise: '60Hz',
simulatorSampleRate: 250,
simulatorSerialPortFailure:false,
sntpTimeSync: false,
sntpTimeSyncHost: 'pool.ntp.org',
sntpTimeSyncPort: 123,
verbose: false
};
/**
* @description The initialization method to call first, before any other method.
* @param options (optional) - Board optional configurations.
* - `baudRate` {Number} - Baud Rate, defaults to 115200. Manipulating this is allowed if
* firmware on board has been previously configured.
*
* - `boardType` {String} - Specifies type of OpenBCI board.
* 3 Possible Boards:
* `default` - 8 Channel OpenBCI board (Default)
* `daisy` - 8 Channel OpenBCI board with Daisy Module. Total of 16 channels.
* `ganglion` - 4 Channel board
* (NOTE: THIS IS IN-OP TIL RELEASE OF GANGLION BOARD 07/2016)
*
* - `simulate` {Boolean} - Full functionality, just mock data. Must attach Daisy module by setting
* `simulatorDaisyModuleAttached` to `true` in order to get 16 channels. (Default `false`)
*
* - `simulatorBoardFailure` {Boolean} - Simulates board communications failure. This occurs when the RFduino on
* the board is not polling the RFduino on the dongle. (Default `false`)
*
* - `simulatorDaisyModuleAttached` {Boolean} - Simulates a daisy module being attached to the OpenBCI board.
* This is useful if you want to test how your application reacts to a user requesting 16 channels
* but there is no daisy module actually attached, or vice versa, where there is a daisy module
* attached and the user only wants to use 8 channels. (Default `false`)
*
* - `simulatorFirmwareVersion` {String} - Allows simulator to be started with firmware version 2 features
* 2 Possible Options:
* `v1` - Firmware Version 1 (Default)
* `v2` - Firmware Version 2
*
* - `simulatorHasAccelerometer` - {Boolean} - Sets simulator to send packets with accelerometer data. (Default `true`)
*
* - `simulatorInjectAlpha` - {Boolean} - Inject a 10Hz alpha wave in Channels 1 and 2 (Default `true`)
*
* - `simulatorInjectLineNoise` {String} - 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.
*
* - `simulatorSampleRate` {Number} - 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`)
*
* - `simulatorSerialPortFailure` {Boolean} - Simulates not being able to open a serial connection. Most likely
* due to a OpenBCI dongle not being plugged in.
*
* - `sntpTimeSync` - {Boolean} Syncs the module up with an SNTP time server and uses that as single source
* of truth instead of local computer time. If you are running experiements on your local
* computer, keep this `false`. (Default `false`)
*
* - `sntpTimeSyncHost` - {String} The ntp server to use, can be either sntp or ntp. (Defaults `pool.ntp.org`).
*
* - `sntpTimeSyncPort` - {Number} The port to access the ntp server. (Defaults `123`)
*
* - `verbose` {Boolean} - Print out useful debugging events
*
* @constructor
* @author AJ Keller (@pushtheworldllc)
*/
function OpenBCIBoard(options) {
options = (typeof options !== 'function') && options || {};
var opts = {};
stream.Stream.call(this);
/** Configuring Options */
opts.boardType = options.boardType || options.boardtype || _options.boardType;
opts.baudRate = options.baudRate || options.baudrate || _options.baudrate;
opts.simulate = options.simulate || _options.simulate;
opts.simulatorBoardFailure = options.simulatorBoardFailure || options.simulatorboardfailure || _options.simulatorBoardFailure;
opts.simulatorDaisyModuleAttached = options.simulatorDaisyModuleAttached || options.simulatordaisymoduleattached || _options.simulatorDaisyModuleAttached;
opts.simulatorFirmwareVersion = options.simulatorFirmwareVersion || options.simulatorfirmwareversion || _options.simulatorFirmwareVersion;
if (opts.simulatorFirmwareVersion !== k.OBCIFirmwareV1 && opts.simulatorFirmwareVersion !== k.OBCIFirmwareV2) {
opts.simulatorFirmwareVersion = k.OBCIFirmwareV1;
}
if (options.simulatorHasAccelerometer === false || options.simulatorhasaccelerometer === false) {
opts.simulatorHasAccelerometer = false;
} else {
opts.simulatorHasAccelerometer = _options.simulatorHasAccelerometer;
}
opts.simulatorInternalClockDrift = options.simulatorInternalClockDrift || options.simulatorinternalclockdrift || _options.simulatorInternalClockDrift;
if (options.simulatorInjectAlpha === false || options.simulatorinjectalpha === false) {
opts.simulatorInjectAlpha = false;
} else {
opts.simulatorInjectAlpha = _options.simulatorInjectAlpha;
}
opts.simulatorInjectLineNoise = options.simulatorInjectLineNoise || options.simulatorinjectlinenoise || _options.simulatorInjectLineNoise;
if (opts.simulatorInjectLineNoise !== '60Hz' && opts.simulatorInjectLineNoise !== '50Hz' && opts.simulatorInjectLineNoise !== 'None') {
opts.simulatorInjectLineNoise = '60Hz';
}
opts.simulatorSampleRate = options.simulatorSampleRate || options.simulatorsamplerate || _options.simulatorSampleRate;
opts.simulatorSerialPortFailure = options.simulatorSerialPortFailure || options.simulatorserialportfailure || _options.simulatorSerialPortFailure;
opts.sntpTimeSync = options.sntpTimeSync || options.sntptimesync || _options.sntpTimeSync;
opts.sntpTimeSyncHost = options.sntpTimeSyncHost || options.sntptimesynchost || _options.sntpTimeSyncHost;
opts.sntpTimeSyncPort = options.sntpTimeSyncPort || options.sntptimesyncport || _options.sntpTimeSyncPort;
opts.verbose = options.verbose || _options.verbose;
// Set to global options object
this.options = opts;
/** Properties (keep alphabetical) */
// Arrays
this.accelArray = [0,0,0]; // X, Y, Z
this.channelSettingsArray = k.channelSettingsArrayInit(k.numberOfChannelsForBoardType(this.options.boardType));
this.writeOutArray = new Array(100);
// Buffers
this.buffer = null;
this.masterBuffer = masterBufferMaker();
// Objects
this.goertzelObject = openBCISample.goertzelNewObject(k.numberOfChannelsForBoardType(this.options.boardType));
this.impedanceTest = {
active: false,
isTestingPInput: false,
isTestingNInput: false,
onChannel: 0,
sampleNumber: 0,
continuousMode: false,
impedanceForChannel: 0
};
this.info = {
boardType : this.options.boardType,
sampleRate : k.OBCISampleRate125,
firmware : k.OBCIFirmwareV1,
numberOfChannels : k.OBCINumberOfChannelsDefault,
missedPackets : 0
};
if (this.options.boardType === k.OBCIBoardDefault) {
this.info.sampleRate = k.OBCISampleRate250
}
this._lowerChannelsSampleObject = null;
this.sync = {
curSyncObj: null,
objArray: [],
sntpActive: false,
timeOffsetMaster: 0,
timeOffsetAvg: 0,
timeOffsetArray: [],
};
this.writer = null;
// Numbers
this.badPackets = 0;
this.curParsingMode = k.OBCIParsingReset;
this.commandsToWrite = 0;
this.impedanceArray = openBCISample.impedanceArray(k.numberOfChannelsForBoardType(this.options.boardType));
this.writeOutDelay = k.OBCIWriteIntervalDelayMSShort;
this.sampleCount = 0;
this.timeOfPacketArrival = 0;
// Strings
// NTP
if (this.options.sntpTimeSync) {
// establishing ntp connection
this.sntpStart()
.then(() => {
if(this.options.verbose) console.log('SNTP: connected');
})
.catch(err => {
if(this.options.verbose) console.log(`Error [sntpStart] ${err}`);
})
}
//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.
* @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, {
accel: this.options.simulatorHasAccelerometer,
alpha: this.options.simulatorInjectAlpha,
boardFailure:this.options.simulatorBoardFailure,
daisy: this.options.simulatorDaisyModuleAttached,
drift: this.options.simulatorInternalClockDrift,
firmwareVersion: this.options.simulatorFirmwareVersion,
lineNoise: this.options.simulatorInjectLineNoise,
sampleRate: this.options.simulatorSampleRate,
serialPortFailure: this.options.simulatorSerialPortFailure,
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;
this.portName = portName;
if(this.options.verbose) console.log('Serial port connected');
boardSerial.on('data',data => {
this._processBytes(data);
});
this.connected = true;
boardSerial.once('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 + 250);
});
boardSerial.once('close',() => {
if (this.options.verbose) console.log('Serial Port Closed');
this.emit('close')
});
/* istanbul ignore next */
boardSerial.once('error',(err) => {
if (this.options.verbose) console.log('Serial Port Error');
this.emit('error',err);
});
});
};
/**
* @description Closes the serial port. Waits for stop streaming command to
* be sent if currently streaming.
* @returns {Promise} - fulfilled by a successful close of the serial port object, rejected otherwise.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.disconnect = function() {
// if we are streaming then we need to give extra time for that stop streaming command to propagate through the
// system before closing the serial port.
var timeout = 0;
if (this.streaming) {
this.streamStop();
if(this.options.verbose) console.log('stop streaming');
timeout = 15; // Avg time is takes for message to propagate
}
return new Promise((resolve, reject) => {
setTimeout(() => {
if(!this.connected) reject('no board connected');
this.connected = false;
if (this.serial) {
this.serial.close(() => {
resolve();
});
} else {
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() {
return new Promise((resolve, reject) => {
if(this.streaming) reject('Error [.streamStart()]: Already streaming');
this.streaming = true;
this._reset();
this.write(k.OBCIStreamStart)
.then(() => {
setTimeout(() => {
resolve();
}, 10); // allow time for command to get sent
})
.catch(err => reject(err));
});
};
/**
* @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() {
return new Promise((resolve,reject) => {
if(!this.streaming) reject('Error [.streamStop()]: No stream to stop');
this.streaming = false;
this.write(k.OBCIStreamStop)
.then(() => {
setTimeout(() => {
resolve();
}, 10); // allow time for command to get sent
})
.catch(err => reject(err));
});
};
/**
* @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 {Buffer} - The data to write out
* @returns {Promise} if signal was able to be sent
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype._writeAndDrain = function(data) {
return new Promise((resolve,reject) => {
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!
* @returns {Promise} - Fulfilled with portName, rejected when can't find the board.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.autoFindOpenBCIBoard = function() {
var macSerialPrefix = 'usbserial-D';
return new Promise((resolve, reject) => {
/* istanbul ignore else */
if (this.options.simulate) {
this.portName = k.OBCISimulatorPortName;
if (this.options.verbose) console.log('auto found sim board');
resolve(k.OBCISimulatorPortName);
} 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 Convenience method to determine if you can use firmware v2.x.x
* capabilities.
* @returns {boolean} - True if using firmware version 2 or greater. Should
* be called after a `.softReset()` because we can parse the output of that
* to determine if we are using firmware version 2.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.usingVersionTwoFirmware = function() {
if (this.options.simulate) {
return this.options.simulatorFirmwareVersion === k.OBCIFirmwareV2;
} else {
return this.info.firmware === k.OBCIFirmwareV2;
}
};
/**
* @description Used to set the system radio channel number. The function will reject if not
* connected to the serial port of the dongle. Further the function should reject if currently streaming.
* Lastly and more important, if the board is not running the new firmware then this functionality does not
* exist and thus this method will reject. If the board is using firmware 2+ then this function should resolve.
* **Note**: This functionality requires OpenBCI Firmware Version 2.0
* @param `channelNumber` {Number} - The channel number you want to set to, 1-25.
* @since 1.0.0
* @returns {Promise} - Resolves with the new channel number, rejects with err.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.radioChannelSet = function(channelNumber) {
var badCommsTimeout;
return new Promise((resolve,reject) => {
if (!this.connected) return reject("Must be connected to Dongle. Pro tip: Call .connect()");
if (this.streaming) return reject("Don't query for the radio while streaming");
if (!this.usingVersionTwoFirmware()) return reject("Must be using firmware version 2");
if (channelNumber === undefined || channelNumber === null) return reject("Must input a new channel number to switch too!");
if (!k.isNumber(channelNumber)) return reject("Must input type Number");
if (channelNumber > k.OBCIRadioChannelMax) return reject(`New channel number must be less than ${k.OBCIRadioChannelMax}`);
if (channelNumber < k.OBCIRadioChannelMin) return reject(`New channel number must be greater than ${k.OBCIRadioChannelMin}`);
// Set a timeout. Since poll times can be max of 255 seconds, we should set that as our timeout. This is
// important if the module was connected, not streaming and using the old firmware
badCommsTimeout = setTimeout(() => {
reject("Please make sure your dongle is using firmware v2");
}, 1000);
// Subscribe to the EOT event
this.once('eot',data => {
if (this.options.verbose) console.log(data.toString());
// Remove the timeout!
clearTimeout(badCommsTimeout);
badCommsTimeout = null;
if (openBCISample.isSuccessInBuffer(data)) {
resolve(data[data.length - 4]);
} else {
reject(`Error [radioChannelSet]: ${data}`); // The channel number is in the first byte
}
});
this.curParsingMode = k.OBCIParsingEOT;
// Send the radio channel query command
this._writeAndDrain(new Buffer([k.OBCIRadioKey,k.OBCIRadioCmdChannelSet,channelNumber]));
});
};
/**
* @description Used to set the ONLY the radio dongle Host channel number. This will fix your radio system if
* your dongle and board are not on the right channel and bring down your radio system if you take your
* dongle and board are not on the same channel. Use with caution! The function will reject if not
* connected to the serial port of the dongle. Further the function should reject if currently streaming.
* Lastly and more important, if the board is not running the new firmware then this functionality does not
* exist and thus this method will reject. If the board is using firmware 2+ then this function should resolve.
* **Note**: This functionality requires OpenBCI Firmware Version 2.0
* @param `channelNumber` {Number} - The channel number you want to set to, 1-25.
* @since 1.0.0
* @returns {Promise} - Resolves with the new channel number, rejects with err.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.radioChannelSetHostOverride = function(channelNumber) {
var badCommsTimeout;
return new Promise((resolve,reject) => {
if (!this.connected) return reject("Must be connected to Dongle. Pro tip: Call .connect()");
if (this.streaming) return reject("Don't query for the radio while streaming");
if (channelNumber === undefined || channelNumber === null) return reject("Must input a new channel number to switch too!");
if (!k.isNumber(channelNumber)) return reject("Must input type Number");
if (channelNumber > k.OBCIRadioChannelMax) return reject(`New channel number must be less than ${k.OBCIRadioChannelMax}`);
if (channelNumber < k.OBCIRadioChannelMin) return reject(`New channel number must be greater than ${k.OBCIRadioChannelMin}`);
// Set a timeout. Since poll times can be max of 255 seconds, we should set that as our timeout. This is
// important if the module was connected, not streaming and using the old firmware
badCommsTimeout = setTimeout(() => {
reject("Please make sure your dongle is using firmware v2");
}, 1000);
// Subscribe to the EOT event
this.once('eot',data => {
if (this.options.verbose) console.log(`${data.toString()}`);
// Remove the timeout!
clearTimeout(badCommsTimeout);
badCommsTimeout = null;
if (openBCISample.isSuccessInBuffer(data)) {
resolve(data[data.length - 4]);
} else {
reject(`Error [radioChannelSet]: ${data}`); // The channel number is in the first byte
}
});
this.curParsingMode = k.OBCIParsingEOT;
// Send the radio channel query command
this._writeAndDrain(new Buffer([k.OBCIRadioKey,k.OBCIRadioCmdChannelSetOverride,channelNumber]));
});
};
/**
* @description Used to query the OpenBCI system for it's radio channel number. The function will reject if not
* connected to the serial port of the dongle. Further the function should reject if currently streaming.
* Lastly and more important, if the board is not running the new firmware then this functionality does not
* exist and thus this method will reject. If the board is using firmware 2+ then this function should resolve
* an Object. See `returns` below.
* **Note**: This functionality requires OpenBCI Firmware Version 2.0
* @since 1.0.0
* @returns {Promise} - Resolve an object with keys `channelNumber` which is a Number and `err` which contains an error in
* the condition that there system is experiencing board communications failure.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.radioChannelGet = function() {
// The function to run on timeout
var badCommsTimeout;
return new Promise((resolve,reject) => {
if (!this.connected) return reject("Must be connected to Dongle. Pro tip: Call .connect()");
if (this.streaming) return reject("Don't query for the radio while streaming");
if (!this.usingVersionTwoFirmware()) return reject("Must be using firmware v2");
// Set a timeout. Since poll times can be max of 255 seconds, we should set that as our timeout. This is
// important if the module was connected, not streaming and using the old firmware
badCommsTimeout = setTimeout(() => {
reject("Please make sure your dongle is plugged in and using firmware v2");
}, 500);
// Subscribe to the EOT event
this.once('eot',data => {
if (this.options.verbose) console.log(data.toString());
// Remove the timeout!
clearTimeout(badCommsTimeout);
badCommsTimeout = null;
if (openBCISample.isSuccessInBuffer(data)) {
resolve({
channelNumber : data[data.length - 4],
data:data
});
} else {
reject(`Error [radioChannelGet]: ${data.toString()}`);
}
});
this.curParsingMode = k.OBCIParsingEOT;
// Send the radio channel query command
this._writeAndDrain(new Buffer([k.OBCIRadioKey,k.OBCIRadioCmdChannelGet]));
});
};
/**
* @description Used to query the OpenBCI system for it's device's poll time. The function will reject if not
* connected to the serial port of the dongle. Further the function should reject if currently streaming.
* Lastly and more important, if the board is not running the new firmware then this functionality does not
* exist and thus this method will reject. If the board is using firmware 2+ then this function should resolve
* the poll time when fulfilled. It's important to note that if the board is not on, this function will always
* be rejected with a failure message.
* **Note**: This functionality requires OpenBCI Firmware Version 2.0
* @since 1.0.0
* @returns {Promise} - Resolves with the poll time, rejects with an error message.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.radioPollTimeGet = function() {
var badCommsTimeout;
return new Promise((resolve,reject) => {
if (!this.connected) return reject("Must be connected to Dongle. Pro tip: Call .connect()");
if (this.streaming) return reject("Don't query for the poll time while streaming");
if (!this.usingVersionTwoFirmware()) return reject("Must be using firmware v2");
// Set a timeout. Since poll times can be max of 255 seconds, we should set that as our timeout. This is
// important if the module was connected, not streaming and using the old firmware
badCommsTimeout = setTimeout(() => {
reject("Please make sure your dongle is plugged in and using firmware v2");
}, 1000);
// Subscribe to the EOT event
this.once('eot',data => {
if (this.options.verbose) console.log(data.toString());
// Remove the timeout!
clearTimeout(badCommsTimeout);
badCommsTimeout = null;
if (openBCISample.isSuccessInBuffer(data)) {
var pollTime = data[data.length - 4];
resolve(pollTime);
} else {
reject(`Error [radioPollTimeGet]: ${data}`); // The channel number is in the first byte
}
});
this.curParsingMode = k.OBCIParsingEOT;
// Send the radio channel query command
this._writeAndDrain(new Buffer([k.OBCIRadioKey,k.OBCIRadioCmdPollTimeGet]));
});
};
/**
* @description Used to set the OpenBCI poll time. With the RFduino configuration, the Dongle is the Host and the
* Board is the Device. Only the Device can initiate a communication between the two entities. Therefore this
* sets the interval at which the Device polls the Host for new information. Further the function should reject
* if currently streaming. Lastly and more important, if the board is not running the new firmware then this
* functionality does not exist and thus this method will reject. If the board is using firmware 2+ then this
* function should resolve.
* **Note**: This functionality requires OpenBCI Firmware Version 2.0
* @param `pollTime` {Number} - The poll time you want to set for the system. 0-255
* @since 1.0.0
* @returns {Promise} - Resolves with new poll time, rejects with error message.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.radioPollTimeSet = function (pollTime) {
var badCommsTimeout;
return new Promise((resolve,reject) => {
if (!this.connected) return reject("Must be connected to Dongle. Pro tip: Call .connect()");
if (this.streaming) return reject("Don't change the poll time while streaming");
if (!this.usingVersionTwoFirmware()) return reject("Must be using firmware v2");
if (pollTime === undefined || pollTime === null) return reject("Must input a new poll time to switch too!");
if (!k.isNumber(pollTime)) return reject("Must input type Number");
if (pollTime > k.OBCIRadioPollTimeMax) return reject(`New polltime must be less than ${k.OBCIRadioPollTimeMax}`);
if (pollTime < k.OBCIRadioPollTimeMin) return reject(`New polltime must be greater than ${k.OBCIRadioPollTimeMin}`);
// Set a timeout. Since poll times can be max of 255 seconds, we should set that as our timeout. This is
// important if the module was connected, not streaming and using the old firmware
badCommsTimeout = setTimeout(() => {
reject("Please make sure your dongle is plugged in and using firmware v2");
}, 1000);
// Subscribe to the EOT event
this.once('eot',data => {
if (this.options.verbose) console.log(data.toString());
// Remove the timeout!
clearTimeout(badCommsTimeout);
badCommsTimeout = null;
if (openBCISample.isSuccessInBuffer(data)) {
resolve(data[data.length - 4]); // Ditch the eot $$$
} else {
reject(`Error [radioPollTimeSet]: ${data}`); // The channel number is in the first byte
}
});
this.curParsingMode = k.OBCIParsingEOT;
// Send the radio channel query command
this._writeAndDrain(new Buffer([k.OBCIRadioKey,k.OBCIRadioCmdPollTimeSet,pollTime]));
});
};
/**
* @description Used to set the OpenBCI Host (Dongle) baud rate. With the RFduino configuration, the Dongle is the
* Host and the Board is the Device. Only the Device can initiate a communication between the two entities.
* There exists a detrimental error where if the Host is interrupted by the radio during a Serial write, then
* all hell breaks loose. So this is an effort to eliminate that problem by increasing the rate at which serial
* data is sent from the Host to the Serial driver. The rate can either be set to default or fast.
* Further the function should reject if currently streaming. Lastly and more important, if the board is not
* running the new firmware then this functionality does not exist and thus this method will reject.
* If the board is using firmware 2+ then this function should resolve the new baud rate after closing the
* current serial port and reopening one.
* **Note**: This functionality requires OpenBCI Firmware Version 2.0
* @since 1.0.0
* @param speed {String} - The baud rate that to switch to. Can be either `default` (115200) or `fast` (230400)
* @returns {Promise} - Resolves a {Number} that is the new baud rate, rejects on error.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.radioBaudRateSet = function(speed) {
var badCommsTimeout;
return new Promise((resolve,reject) => {
if (!this.connected) return reject("Must be connected to Dongle. Pro tip: Call .connect()");
if (this.streaming) return reject("Don't change the baud rate while streaming");
if (!this.usingVersionTwoFirmware()) return reject("Must be using firmware v2");
if (!k.isString(speed)) return reject("Must input type String");
// Set a timeout. Since poll times can be max of 255 seconds, we should set that as our timeout. This is
// important if the module was connected, not streaming and using the old firmware
badCommsTimeout = setTimeout(() => {
reject("Please make sure your dongle is plugged in and using firmware v2");
}, 1000);
// Subscribe to the EOT event
this.once('eot',data => {
if (this.options.verbose) console.log(data.toString());
// Remove the timeout!
clearTimeout(badCommsTimeout);
badCommsTimeout = null;
var eotBuf = new Buffer('$$$');
var newBaudRateBuf;
for (var i = data.length; i > 3; i--) {
if (bufferEqual(data.slice(i - 3, i),eotBuf)) {
newBaudRateBuf = data.slice(i - 9, i - 3);
break;
}
}
var newBaudRateNum = Number(newBaudRateBuf.toString());
if (newBaudRateNum !== k.OBCIRadioBaudRateDefault && newBaudRateNum !== k.OBCIRadioBaudRateFast) {
return reject("Error parse mismatch, restart your system!");
}
if (openBCISample.isSuccessInBuffer(data)) {
// Change the sample rate here
if (this.options.simulate === false) {
this.serial.update({baudRate:newBaudRateNum},err => {
if (err) reject(err);
else resolve(newBaudRateNum);
});
} else {
resolve(newBaudRateNum);
}
} else {
reject(`Error [radioPollTimeGet]: ${data}`); // The channel number is in the first byte
}
});
this.curParsingMode = k.OBCIParsingEOT;
// Send the radio channel query command
if (speed === k.OBCIRadioBaudRateFastStr) {
this._writeAndDrain(new Buffer([k.OBCIRadioKey,k.OBCIRadioCmdBaudRateSetFast]));
} else {
this._writeAndDrain(new Buffer([k.OBCIRadioKey,k.OBCIRadioCmdBaudRateSetDefault]));
}
});
};
/**
* @description Used to ask the Host if it's radio system is up. This is useful to quickly determine if you are
* in fact ready to start trying to connect and such. The function will reject if not connected to the serial
* port of the dongle. Further the function should reject if currently streaming.
* Lastly and more important, if the board is not running the new firmware then this functionality does not
* exist and thus this method will reject. If the board is using firmware +v2.0.0 and the radios are both on the
* same channel and powered, then this will resolve true.
* **Note**: This functionality requires OpenBCI Firmware Version 2.0
* @since 1.0.0
* @returns {Promise} - Resolves true if both radios are powered and on the same channel; false otherwise.
* @author AJ Keller (@pushtheworldllc)
*/
OpenBCIBoard.prototype.radioSystemStatusGet = function() {
var badCommsTimeout;
return new Promise((resolve,reject) => {
if (!this.connected) return reject("Must be connected to Dongle. Pro tip: Call .connect()");
if (this.streaming) return reject("Don't change the poll time while streaming");
if (!this.usingVersionTwoFirmware()) return reject("Must be using firmware version 2");
// Set a timeout. Since poll times can be max of 255 seconds, we should set that as our timeout. This is
// important if the module was connected, not streaming and using the old firmware
badCommsTimeout = setTimeout(() => {
reject("Please make sure your dongle is plugged in and using firmware v2");
}, 1000);
// Subscribe to the EOT event
this.once('eot',data => {
// Remove the timeout!
clearTimeout(badCommsTimeout);
badCommsTimeout = null;
if (this.options.verbose) console.log(data.toString());
if (openBCISample.isSuccessInBuffer(data)) {
resolve(true);
} else {
resolve(false);
}
});
this.curParsingMode = k.OBCIParsingEOT;
// Send the radio channel query command
this._writeAndDrain(new Buffer([k.OBCIRadioKey,k.OBCIRadioCmdSystemStatus]));
});
};
/**
* @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} - On fulfill will contain an array of Serial ports to use.
*/
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() {
this.curParsingMode = k.OBCIParsingReset;
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)
*/
// TODO: REDO THIS FUNCTION
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.curParsingMode = k.OBCIParsingChannelSettings;
});
};
/**
* @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);