-
Notifications
You must be signed in to change notification settings - Fork 10
/
utilities.js
2374 lines (2130 loc) · 88.3 KB
/
utilities.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';
import gaussian from 'gaussian';
import k from './constants';
import StreamSearch from 'streamsearch';
import { Buffer } from 'buffer/';
/** Constants for interpreting the EEG data */
// Reference voltage for ADC in ADS1299.
// Set by its hardware.
const ADS1299_VREF = 4.5;
// Scale factor for aux data
const SCALE_FACTOR_ACCEL = 0.002 / Math.pow(2, 4);
// X, Y, Z
const ACCEL_NUMBER_AXIS = 3;
// Default ADS1299 gains array
let utilitiesModule = {
/**
* @typedef {Object} ProcessedBuffer
* @property {Buffer|SafeBuffer|Buffer2} buffer The remaining buffer. Can be null.
* @property {Array} rawDataPackets The extracted raw data packets
*/
/**
* @typedef {Object} Sample
* @property {Array} accelData of floats of accel data. not always present in object.
* @property {Number} sampleNumber The sample number
* @property {Array} channelData The extracted channel data
* @property {Buffer} rawDataPacket The raw data packet
* @property {Boolean} valid If the sample is valid
*/
/**
* @typedef {Object} Impedance
* @property {Number} channelNumber The channel number
* @property {Number} impedanceValue The impedance in ohms
*/
/**
* @typedef {Object} RawDataToSample
* @property {Array} rawDataPackets - An array of rawDataPackets
* @property {Buffer} rawDataPacket - A single raw data packet
* @property {Buffer} multiPacketBuffer - This buffer is used to build up multiple messages over ble and emit them at once
* @property {Array} channelSettings - The channel settings array
* @property {Number} timeOffset (optional) for non time stamp use cases i.e. 0xC0 or 0xC1 (default and raw aux)
* @property {Array} accelArray (optional) for non time stamp use cases
* @property {Boolean} verbose (optional) for verbose output
* @property {Number} lastSampleNumber (optional) - The last sample number
* @property {Boolean} scale (optional) Default `true`. A gain of 24 for Cyton will be used and 51 for ganglion by default.
* @property {Array} decompressedSamples - An array to hold delta compression items
* @property {Boolean} sendCounts - True if you want raw A/D counts or scaled counts in samples
*/
/**
* @description Used to extract samples out of a buffer of unknown length
* @param dataBuffer {Buffer} - A buffer to parse for samples
* @returns {ProcessedBuffer} - Object with parsed raw packets and remaining buffer. Calling function shall maintain
* the buffer in it's scope.
* @author AJ Keller (@aj-ptw)
*/
extractRawDataPackets: (dataBuffer) => {
if (!dataBuffer) {
return {
'buffer': dataBuffer,
'rawDataPackets': []
};
}
let bytesToParse = dataBuffer.length;
let rawDataPackets = [];
// Exit if we have a buffer with less data than a packet
if (bytesToParse < k.OBCIPacketSize) {
return {
'buffer': dataBuffer,
'rawDataPackets': rawDataPackets
};
}
let parsePosition = 0;
// Begin parseing
while (parsePosition <= bytesToParse - k.OBCIPacketSize) {
// Is the current byte a head byte that looks like 0xA0
if (dataBuffer[parsePosition] === k.OBCIByteStart) {
// Now that we know the first is a head byte, let's see if the last one is a
// tail byte 0xCx where x is the set of numbers from 0-F (hex)
if (isStopByte(dataBuffer[parsePosition + k.OBCIPacketSize - 1])) {
// console.log(dataBuffer[parsePosition+1]);
/** We just qualified a raw packet */
// This could be a time set packet!
// this.timeOfPacketArrival = this.time();
// Grab the raw packet, make a copy of it.
let rawPacket;
rawPacket = Buffer.from(dataBuffer.slice(parsePosition, parsePosition + k.OBCIPacketSize));
// Emit that buffer
// this.emit('rawDataPacket', rawPacket);
rawDataPackets.push(rawPacket);
// Submit the packet for processing
// this._processQualifiedPacket(rawPacket);
// Overwrite the dataBuffer with a new buffer
let tempBuf;
if (parsePosition > 0) {
tempBuf = Buffer.concat([
Buffer.from(dataBuffer.slice(0, parsePosition)),
Buffer.from(dataBuffer.slice(parsePosition + k.OBCIPacketSize))
]);
} else {
tempBuf = Buffer.from(dataBuffer.slice(k.OBCIPacketSize));
}
if (tempBuf.length === 0) {
dataBuffer = null;
} else {
dataBuffer = Buffer.from(tempBuf);
}
// Move the parse position up one packet
parsePosition = -1;
bytesToParse -= k.OBCIPacketSize;
}
}
parsePosition++;
}
return {
'buffer': dataBuffer,
'rawDataPackets': rawDataPackets
};
},
extractRawBLEDataPackets: (dataBuffer) => {
let rawDataPackets = [];
if (k.isNull(dataBuffer)) return rawDataPackets;
// Verify the packet is of length 20
if (dataBuffer.byteLength !== k.OBCIPacketSizeBLECyton) return rawDataPackets;
let sampleNumbers = [0, 0, 0];
sampleNumbers[0] = dataBuffer[1];
sampleNumbers[1] = sampleNumbers[0] + 1;
if (sampleNumbers[1] > 255) sampleNumbers[1] -= 256;
sampleNumbers[2] = sampleNumbers[1] + 1;
if (sampleNumbers[2] > 255) sampleNumbers[2] -= 256;
for (let i = 0; i < k.OBCICytonBLESamplesPerPacket; i++) {
let rawDataPacket = utilitiesModule.samplePacketZero(sampleNumbers[i]);
rawDataPacket[0] = k.OBCIByteStart;
rawDataPacket[k.OBCIPacketPositionStopByte] = dataBuffer[0];
dataBuffer.copy(rawDataPacket, k.OBCIPacketPositionChannelDataStart, k.OBCIPacketPositionChannelDataStart + (i * 6), k.OBCIPacketPositionChannelDataStart + 6 + (i * 6));
rawDataPackets.push(rawDataPacket);
}
return rawDataPackets;
},
transformRawDataPacketToSample,
transformRawDataPacketsToSample,
convertGanglionArrayToBuffer,
getRawPacketType,
getFromTimePacketAccel,
getFromTimePacketTime,
getFromTimePacketRawAux,
ganglionFillRawDataPacket,
parsePacketStandardAccel,
parsePacketStandardRawAux,
parsePacketTimeSyncedAccel,
parsePacketTimeSyncedRawAux,
parsePacketImpedance,
/**
* @description Mainly used by the simulator to convert a randomly generated sample into a std OpenBCI V3 Packet
* @param sample - A sample object
* @returns {Buffer}
*/
convertSampleToPacketStandard: (sample) => {
let packetBuffer = new Buffer(k.OBCIPacketSize);
packetBuffer.fill(0);
// start byte
packetBuffer[0] = k.OBCIByteStart;
// sample number
packetBuffer[1] = sample.sampleNumber;
// channel data
for (let i = 0; i < k.OBCINumberOfChannelsDefault; i++) {
let threeByteBuffer = floatTo3ByteBuffer(sample.channelData[i]);
threeByteBuffer.copy(packetBuffer, 2 + (i * 3));
}
for (let j = 0; j < 3; j++) {
let twoByteBuffer = floatTo2ByteBuffer(sample.auxData[j]);
twoByteBuffer.copy(packetBuffer, (k.OBCIPacketSize - 1 - 6) + (j * 2));
}
// stop byte
packetBuffer[k.OBCIPacketSize - 1] = k.OBCIByteStop;
return packetBuffer;
},
/**
* @description Mainly used by the simulator to convert a randomly generated sample into a std OpenBCI V3 Packet
* @param sample - A sample object
* @param rawAux {Buffer} - A 6 byte long buffer to insert into raw buffer
* @returns {Buffer} - A 33 byte long buffer
*/
convertSampleToPacketRawAux: (sample, rawAux) => {
let packetBuffer = new Buffer(k.OBCIPacketSize);
packetBuffer.fill(0);
// start byte
packetBuffer[0] = k.OBCIByteStart;
// sample number
packetBuffer[1] = sample.sampleNumber;
// channel data
for (let i = 0; i < k.OBCINumberOfChannelsDefault; i++) {
let threeByteBuffer = floatTo3ByteBuffer(sample.channelData[i]);
threeByteBuffer.copy(packetBuffer, 2 + (i * 3));
}
// Write the raw aux bytes
rawAux.copy(packetBuffer, 26);
// stop byte
packetBuffer[k.OBCIPacketSize - 1] = makeTailByteFromPacketType(k.OBCIStreamPacketStandardRawAux);
return packetBuffer;
},
/**
* @description Mainly used by the simulator to convert a randomly generated sample into an accel time sync set buffer
* @param sample {Buffer} - A sample object
* @param time {Number} - The time to inject into the sample.
* @returns {Buffer} - A time sync accel packet
*/
convertSampleToPacketAccelTimeSyncSet: (sample, time) => {
let buf = convertSampleToPacketAccelTimeSynced(sample, time);
buf[k.OBCIPacketPositionStopByte] = makeTailByteFromPacketType(k.OBCIStreamPacketAccelTimeSyncSet);
return buf;
},
/**
* @description Mainly used by the simulator to convert a randomly generated sample into an accel time synced buffer
* @param sample {Buffer} - A sample object
* @param time {Number} - The time to inject into the sample.
* @returns {Buffer} - A time sync accel packet
*/
convertSampleToPacketAccelTimeSynced,
/**
* @description Mainly used by the simulator to convert a randomly generated sample into a raw aux time sync set packet
* @param sample {Buffer} - A sample object
* @param time {Number} - The time to inject into the sample.
* @param rawAux {Buffer} - 2 byte buffer to inject into sample
* @returns {Buffer} - A time sync raw aux packet
*/
convertSampleToPacketRawAuxTimeSyncSet: (sample, time, rawAux) => {
let buf = convertSampleToPacketRawAuxTimeSynced(sample, time, rawAux);
buf[k.OBCIPacketPositionStopByte] = makeTailByteFromPacketType(k.OBCIStreamPacketRawAuxTimeSyncSet);
return buf;
},
convertSampleToPacketRawAuxTimeSynced,
debugPrettyPrint: (sample) => {
if (sample === null || sample === undefined) {
console.log('== Sample is undefined ==');
} else {
console.log('-- Sample --');
console.log('---- Start Byte: ' + sample.startByte);
console.log('---- Sample Number: ' + sample.sampleNumber);
for (let i = 0; i < 8; i++) {
console.log('---- Channel Data ' + (i + 1) + ': ' + sample.channelData[i]);
}
if (sample.accelData) {
for (let j = 0; j < 3; j++) {
console.log('---- Accel Data ' + j + ': ' + sample.accelData[j]);
}
}
if (sample.auxData) {
console.log('---- Aux Data ' + sample.auxData);
}
console.log('---- Stop Byte: ' + sample.stopByte);
}
},
samplePrintHeader: () => {
return (
'All voltages in Volts!' +
'sampleNumber, channel1, channel2, channel3, channel4, channel5, channel6, channel7, channel8, aux1, aux2, aux3\n');
},
samplePrintLine: sample => {
return new Promise((resolve, reject) => {
if (sample === null || sample === undefined) reject(Error('undefined sample'));
resolve(
sample.sampleNumber + ',' +
sample.channelData[0].toFixed(8) + ',' +
sample.channelData[1].toFixed(8) + ',' +
sample.channelData[2].toFixed(8) + ',' +
sample.channelData[3].toFixed(8) + ',' +
sample.channelData[4].toFixed(8) + ',' +
sample.channelData[5].toFixed(8) + ',' +
sample.channelData[6].toFixed(8) + ',' +
sample.channelData[7].toFixed(8) + ',' +
sample.auxData[0].toFixed(8) + ',' +
sample.auxData[1].toFixed(8) + ',' +
sample.auxData[2].toFixed(8) + '\n'
);
});
},
floatTo3ByteBuffer,
floatTo2ByteBuffer,
/**
* @description Calculate the impedance for one channel only.
* @param sampleObject - Standard OpenBCI sample object
* @param channelNumber - Number, the channel you want to calculate impedance for.
* @returns {Promise} - Fulfilled with impedance value for the specified channel.
* @author AJ Keller
*/
impedanceCalculationForChannel: (sampleObject, channelNumber) => {
const sqrt2 = Math.sqrt(2);
return new Promise((resolve, reject) => {
if (sampleObject === undefined || sampleObject === null) reject(Error('Sample Object cannot be null or undefined'));
if (sampleObject.channelData === undefined || sampleObject.channelData === null) reject(Error('Channel cannot be null or undefined'));
if (channelNumber < 1 || channelNumber > k.OBCINumberOfChannelsDefault) reject(Error('Channel number invalid.'));
let index = channelNumber - 1;
if (sampleObject.channelData[index] < 0) {
sampleObject.channelData[index] *= -1;
}
let impedance = (sqrt2 * sampleObject.channelData[index]) / k.OBCILeadOffDriveInAmps;
// if (index === 0) console.log("Voltage: " + (sqrt2*sampleObject.channelData[index]) + " leadoff amps: " + k.OBCILeadOffDriveInAmps + " impedance: " + impedance)
resolve(impedance);
});
},
/**
* @description Calculate the impedance for all channels.
* @param sampleObject - Standard OpenBCI sample object
* @returns {Promise} - Fulfilled with impedances for the sample
* @author AJ Keller
*/
impedanceCalculationForAllChannels: sampleObject => {
const sqrt2 = Math.sqrt(2);
return new Promise((resolve, reject) => {
if (sampleObject === undefined || sampleObject === null) reject(Error('Sample Object cannot be null or undefined'));
if (sampleObject.channelData === undefined || sampleObject.channelData === null) reject(Error('Channel cannot be null or undefined'));
let sampleImpedances = [];
let numChannels = sampleObject.channelData.length;
for (let index = 0; index < numChannels; index++) {
if (sampleObject.channelData[index] < 0) {
sampleObject.channelData[index] *= -1;
}
let impedance = (sqrt2 * sampleObject.channelData[index]) / k.OBCILeadOffDriveInAmps;
sampleImpedances.push(impedance);
// if (index === 0) console.log("Voltage: " + (sqrt2*sampleObject.channelData[index]) + " leadoff amps: " + k.OBCILeadOffDriveInAmps + " impedance: " + impedance)
}
sampleObject.impedances = sampleImpedances;
resolve(sampleObject);
});
},
interpret16bitAsInt32: twoByteBuffer => {
let prefix = 0;
if (twoByteBuffer[0] > 127) {
// console.log('\t\tNegative number')
prefix = 65535; // 0xFFFF
}
return (prefix << 16) | (twoByteBuffer[0] << 8) | twoByteBuffer[1];
},
interpret24bitAsInt32: threeByteBuffer => {
let prefix = 0;
if (threeByteBuffer[0] > 127) {
// console.log('\t\tNegative number')
prefix = 255;
}
return (prefix << 24) | (threeByteBuffer[0] << 16) | (threeByteBuffer[1] << 8) | threeByteBuffer[2];
},
impedanceArray: numberOfChannels => {
let impedanceArray = [];
for (let i = 0; i < numberOfChannels; i++) {
impedanceArray.push(newImpedanceObject(i + 1));
}
return impedanceArray;
},
impedanceObject: newImpedanceObject,
impedanceSummarize: singleInputObject => {
if (singleInputObject.raw > k.OBCIImpedanceThresholdBadMax) { // The case for no load (super high impedance)
singleInputObject.text = k.OBCIImpedanceTextNone;
} else {
singleInputObject.text = k.getTextForRawImpedance(singleInputObject.raw); // Get textual impedance
}
},
newSample,
newSampleNoScale,
/**
* @description Create a configurable function to return samples for a simulator. This implements 1/f filtering injection to create more brain like data.
* @param numberOfChannels {Number} - The number of channels in the sample... either 8 or 16
* @param sampleRateHz {Number} - The sample rate
* @param injectAlpha {Boolean} (optional) - True if you want to inject noise
* @param lineNoise {String} (optional) - A string that can be either:
* `60Hz` - 60Hz line noise (Default) (ex. __United States__)
* `50Hz` - 50Hz line noise (ex. __Europe__)
* `none` - Do not inject line noise.
*
* @returns {Function}
*/
randomSample: (numberOfChannels, sampleRateHz, injectAlpha, lineNoise) => {
const distribution = gaussian(0, 1);
const sineWaveFreqHz10 = 10;
const sineWaveFreqHz50 = 50;
const sineWaveFreqHz60 = 60;
const uVolts = 1000000;
let sinePhaseRad = new Array(numberOfChannels + 1); // prevent index error with '+1'
sinePhaseRad.fill(0);
let auxData = [0, 0, 0];
let accelCounter = 0;
// With 250Hz, every 10 samples, with 125Hz, every 5...
let samplesPerAccelRate = Math.floor(sampleRateHz / 25); // best to make this an integer
if (samplesPerAccelRate < 1) samplesPerAccelRate = 1;
// Init arrays to hold coefficients for each channel and init to 0
// This gives the 1/f filter memory on each iteration
let b0 = new Array(numberOfChannels).fill(0);
let b1 = new Array(numberOfChannels).fill(0);
let b2 = new Array(numberOfChannels).fill(0);
/**
* @description Use a 1/f filter
* @param previousSampleNumber {Number} - The previous sample number
*/
return previousSampleNumber => {
let sample = newSample();
let whiteNoise;
for (let i = 0; i < numberOfChannels; i++) { // channels are 0 indexed
// This produces white noise
whiteNoise = distribution.ppf(Math.random()) * Math.sqrt(sampleRateHz / 2) / uVolts;
switch (i) {
case 0: // Add 10Hz signal to channel 1... brainy
case 1:
if (injectAlpha) {
sinePhaseRad[i] += 2 * Math.PI * sineWaveFreqHz10 / sampleRateHz;
if (sinePhaseRad[i] > 2 * Math.PI) {
sinePhaseRad[i] -= 2 * Math.PI;
}
whiteNoise += (5 * Math.SQRT2 * Math.sin(sinePhaseRad[i])) / uVolts;
}
break;
default:
if (lineNoise === k.OBCISimulatorLineNoiseHz60) {
// If we're in murica we want to add 60Hz line noise
sinePhaseRad[i] += 2 * Math.PI * sineWaveFreqHz60 / sampleRateHz;
if (sinePhaseRad[i] > 2 * Math.PI) {
sinePhaseRad[i] -= 2 * Math.PI;
}
whiteNoise += (8 * Math.SQRT2 * Math.sin(sinePhaseRad[i])) / uVolts;
} else if (lineNoise === k.OBCISimulatorLineNoiseHz50) {
// add 50Hz line noise if we are not in america
sinePhaseRad[i] += 2 * Math.PI * sineWaveFreqHz50 / sampleRateHz;
if (sinePhaseRad[i] > 2 * Math.PI) {
sinePhaseRad[i] -= 2 * Math.PI;
}
whiteNoise += (8 * Math.SQRT2 * Math.sin(sinePhaseRad[i])) / uVolts;
}
}
/**
* See http://www.firstpr.com.au/dsp/pink-noise/ section "Filtering white noise to make it pink"
*/
b0[i] = 0.99765 * b0[i] + whiteNoise * 0.0990460;
b1[i] = 0.96300 * b1[i] + whiteNoise * 0.2965164;
b2[i] = 0.57000 * b2[i] + whiteNoise * 1.0526913;
sample.channelData[i] = b0[i] + b1[i] + b2[i] + whiteNoise * 0.1848;
}
if (previousSampleNumber === 255) {
sample.sampleNumber = 0;
} else {
sample.sampleNumber = previousSampleNumber + 1;
}
/**
* Sample rate of accelerometer is 25Hz... when the accelCounter hits the relative sample rate of the accel
* we will output a new accel value. The approach will be to consider that Z should be about 1 and X and Y
* should be somewhere around 0.
*/
if (accelCounter === samplesPerAccelRate) {
// Initialize a new array
let accelArray = [0, 0, 0];
// Calculate X
accelArray[0] = (Math.random() * 0.1 * (Math.random() > 0.5 ? -1 : 1));
// Calculate Y
accelArray[1] = (Math.random() * 0.1 * (Math.random() > 0.5 ? -1 : 1));
// Calculate Z, this is around 1
accelArray[2] = 1 - ((Math.random() * 0.4) * (Math.random() > 0.5 ? -1 : 1));
// Store the newly calculated value
sample.auxData = accelArray;
// Reset the counter
accelCounter = 0;
} else {
// Increment counter
accelCounter++;
// Store the default value
sample.auxData = auxData;
}
return sample;
};
},
scaleFactorAux: SCALE_FACTOR_ACCEL,
/**
* Calculate the impedance
* @param sample {Object} - Standard sample
* @param impedanceTest {Object} - Impedance Object from openBCIBoard.js
* @return {null | Object} - Null if not enough samples have passed to calculate an accurate
*/
impedanceCalculateArray: (sample, impedanceTest) => {
impedanceTest.buffer.push(sample.channelData);
impedanceTest.count++;
if (impedanceTest.count >= impedanceTest.window) {
let output = [];
for (let i = 0; i < sample.channelData.length; i++) {
let max = 0.0; // sumSquared
for (let j = 0; j < impedanceTest.window; j++) {
if (impedanceTest.buffer[i][j] > max) {
max = impedanceTest.buffer[i][j];
}
}
let min = 0.0;
for (let j = 0; j < impedanceTest.window; j++) {
if (impedanceTest.buffer[i][j] < min) {
min = impedanceTest.buffer[i][j];
}
}
const vP2P = max - min; // peak to peak
output.push(vP2P / 2 / k.OBCILeadOffDriveInAmps);
}
impedanceTest.count = 0;
return output;
}
return null;
},
impedanceTestObjDefault: (impedanceTestObj) => {
let newObj = impedanceTestObj || {};
newObj['active'] = false;
newObj['buffer'] = [];
newObj['count'] = 0;
newObj['isTestingPInput'] = false;
newObj['isTestingNInput'] = false;
newObj['onChannel'] = 0;
newObj['sampleNumber'] = 0;
newObj['continuousMode'] = false;
newObj['impedanceForChannel'] = 0;
newObj['window'] = 40;
return newObj;
},
samplePacket: sampleNumber => {
return new Buffer([0xA0, sampleNumberNormalize(sampleNumber), 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0, 5, 0, 0, 6, 0, 0, 7, 0, 0, 8, 0, 0, 0, 1, 0, 2, makeTailByteFromPacketType(k.OBCIStreamPacketStandardAccel)]);
},
samplePacketZero: sampleNumber => {
return new Buffer([0xA0, sampleNumberNormalize(sampleNumber), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, makeTailByteFromPacketType(k.OBCIStreamPacketStandardAccel)]);
},
samplePacketReal: sampleNumber => {
return new Buffer([0xA0, sampleNumberNormalize(sampleNumber), 0x8F, 0xF2, 0x40, 0x8F, 0xDF, 0xF4, 0x90, 0x2B, 0xB6, 0x8F, 0xBF, 0xBF, 0x7F, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0x94, 0x25, 0x34, 0x20, 0xB6, 0x7D, 0, 0xE0, 0, 0xE0, 0x0F, 0x70, makeTailByteFromPacketType(k.OBCIStreamPacketStandardAccel)]);
},
samplePacketStandardRawAux: sampleNumber => {
return new Buffer([0xA0, sampleNumberNormalize(sampleNumber), 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0, 5, 0, 0, 6, 0, 0, 7, 0, 0, 8, 0, 1, 2, 3, 4, 5, makeTailByteFromPacketType(k.OBCIStreamPacketStandardRawAux)]);
},
samplePacketAccelTimeSyncSet: sampleNumber => {
return new Buffer([0xA0, sampleNumberNormalize(sampleNumber), 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0, 5, 0, 0, 6, 0, 0, 7, 0, 0, 8, 0, 1, 0, 0, 0, 1, makeTailByteFromPacketType(k.OBCIStreamPacketAccelTimeSyncSet)]);
},
samplePacketAccelTimeSynced: sampleNumber => {
return new Buffer([0xA0, sampleNumberNormalize(sampleNumber), 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0, 5, 0, 0, 6, 0, 0, 7, 0, 0, 8, 0, 1, 0, 0, 0, 1, makeTailByteFromPacketType(k.OBCIStreamPacketAccelTimeSynced)]);
},
samplePacketRawAuxTimeSyncSet: sampleNumber => {
return new Buffer([0xA0, sampleNumberNormalize(sampleNumber), 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0, 5, 0, 0, 6, 0, 0, 7, 0, 0, 8, 0x00, 0x01, 0, 0, 0, 1, makeTailByteFromPacketType(k.OBCIStreamPacketRawAuxTimeSyncSet)]);
},
samplePacketRawAuxTimeSynced: sampleNumber => {
return new Buffer([0xA0, sampleNumberNormalize(sampleNumber), 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0, 5, 0, 0, 6, 0, 0, 7, 0, 0, 8, 0x00, 0x01, 0, 0, 0, 1, makeTailByteFromPacketType(k.OBCIStreamPacketRawAuxTimeSynced)]);
},
samplePacketImpedance: channelNumber => {
return new Buffer([0xA0, channelNumber, 54, 52, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, makeTailByteFromPacketType(k.OBCIStreamPacketImpedance)]);
},
samplePacketUserDefined: () => {
return new Buffer([0xA0, 0x00, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, makeTailByteFromPacketType(k.OBCIStreamPacketUserDefinedType)]);
},
samplePacketCytonBLE: sampleNumber => {
return new Buffer([0xC0, sampleNumberNormalize(sampleNumber), 0, 0, 1, 0, 0, 2, 0, 0, 10, 0, 0, 20, 0, 0, 100, 0, 0, 200]);
},
countADSPresent,
doesBufferHaveEOT,
getBiasSetFromADSRegisterQuery,
getBooleanFromRegisterQuery,
getChannelDataArray,
getChannelDataArrayNoScale,
getDataArrayAccel,
getDataArrayAccelNoScale,
getFirmware,
getSRB1FromADSRegisterQuery,
getNumFromThreeCSVADSRegisterQuery,
isEven,
isFailureInBuffer,
isOdd,
isStopByte,
isSuccessInBuffer,
isTimeSyncSetConfirmationInBuffer,
makeDaisySampleObject,
makeDaisySampleObjectWifi,
makeTailByteFromPacketType,
newSyncObject,
setChSetFromADSRegisterQuery,
stripToEOTBuffer,
syncChannelSettingsWithRawData,
/**
* @description Checks to make sure the previous sample number is one less
* then the new sample number. Takes into account sample numbers wrapping
* around at 255.
* @param `previousSampleNumber` {Number} - An integer number of the previous
* sample number.
* @param `newSampleNumber` {Number} - An integer number of the new sample
* number.
* @returns {Array} - Returns null if there is no dropped packets, otherwise,
* or on a missed packet, an array of their packet numbers is returned.
*/
droppedPacketCheck: (previousSampleNumber, newSampleNumber) => {
if (previousSampleNumber === k.OBCISampleNumberMax && newSampleNumber === 0) {
return null;
}
if (newSampleNumber - previousSampleNumber === 1) {
return null;
}
let missedPacketArray = [];
if (previousSampleNumber > newSampleNumber) {
let numMised = k.OBCISampleNumberMax - previousSampleNumber;
for (let i = 0; i < numMised; i++) {
missedPacketArray.push(previousSampleNumber + i + 1);
}
previousSampleNumber = -1;
}
for (let j = 1; j < (newSampleNumber - previousSampleNumber); j++) {
missedPacketArray.push(previousSampleNumber + j);
}
return missedPacketArray;
},
convert18bitAsInt32,
convert19bitAsInt32,
decompressDeltas18Bit,
decompressDeltas19Bit,
sampleCompressedData: (sampleNumber) => {
return new Buffer(
[
sampleNumber, // 0
0b00000000, // 0
0b00000000, // 1
0b00000000, // 2
0b00000000, // 3
0b00001000, // 4
0b00000000, // 5
0b00000101, // 6
0b00000000, // 7
0b00000000, // 8
0b01001000, // 9
0b00000000, // 10
0b00001001, // 11
0b11110000, // 12
0b00000001, // 13
0b10110000, // 14
0b00000000, // 15
0b00110000, // 16
0b00000000, // 17
0b00001000 // 18
]);
},
sampleBLERaw: () => {
return new Buffer([0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0, 4]);
},
sampleImpedanceChannel1: () => {
return new Buffer([k.OBCIGanglionByteIdImpedanceChannel1, 0, 0, 1]);
},
sampleImpedanceChannel2: () => {
return new Buffer([k.OBCIGanglionByteIdImpedanceChannel2, 0, 0, 1]);
},
sampleImpedanceChannel3: () => {
return new Buffer([k.OBCIGanglionByteIdImpedanceChannel3, 0, 0, 1]);
},
sampleImpedanceChannel4: () => {
return new Buffer([k.OBCIGanglionByteIdImpedanceChannel4, 0, 0, 1]);
},
sampleImpedanceChannelReference: () => {
return new Buffer([k.OBCIGanglionByteIdImpedanceChannelReference, 0, 0, 1]);
},
sampleMultiBytePacket: (data) => {
const bufPre = new Buffer([k.OBCIGanglionByteIdMultiPacket]);
return Buffer.concat([bufPre, data]);
},
sampleMultiBytePacketStop: (data) => {
const bufPre = new Buffer([k.OBCIGanglionByteIdMultiPacketStop]);
return Buffer.concat([bufPre, data]);
},
sampleOtherData: (data) => {
const bufPre = new Buffer([255]);
return Buffer.concat([bufPre, data]);
},
sampleUncompressedData: () => {
return new Buffer(
[
0b00000000, // 0
0b00000000, // 1
0b00000000, // 2
0b00000001, // 3
0b00000000, // 4
0b00000000, // 5
0b00000010, // 6
0b00000000, // 7
0b00000000, // 8
0b00000011, // 9
0b00000000, // 10
0b00000000, // 11
0b00000100, // 12
0b00000001, // 13
0b00000010, // 14
0b00000011, // 15
0b00000100, // 16
0b00000101, // 17
0b00000110, // 18
0b00000111 // 19
]);
},
parseGanglion,
processMultiBytePacket,
processMultiBytePacketStop
};
/**
* @description Used transform raw data packets into fully qualified packets
* @param o {RawDataToSample} - Used to hold data and configuration settings
* @return {Array} samples An array of {Sample}
* @author AJ Keller (@aj-ptw)
*/
function parseGanglion (o) {
const byteId = parseInt(o.rawDataPacket[0]);
if (byteId <= k.OBCIGanglionByteId19Bit.max) {
return processRouteSampleData(o);
} else {
switch (byteId) {
case k.OBCIGanglionByteIdMultiPacket:
return processMultiBytePacket(o);
case k.OBCIGanglionByteIdMultiPacketStop:
return processMultiBytePacketStop(o);
case k.OBCIGanglionByteIdImpedanceChannel1:
case k.OBCIGanglionByteIdImpedanceChannel2:
case k.OBCIGanglionByteIdImpedanceChannel3:
case k.OBCIGanglionByteIdImpedanceChannel4:
case k.OBCIGanglionByteIdImpedanceChannelReference:
return processImpedanceData(o);
default:
return null;
}
}
}
/**
* Process an compressed packet of data.
* @param o {RawDataToSample} - Used to hold data and configuration settings
* @private
*/
function processCompressedData (o) {
// Save the packet counter
o.lastSampleNumber = parseInt(o.rawDataPacket[0]);
const samples = [];
// Decompress the buffer into array
if (o.lastSampleNumber <= k.OBCIGanglionByteId18Bit.max) {
decompressSamples(o, decompressDeltas18Bit(o.rawDataPacket.slice(k.OBCIGanglionPacket18Bit.dataStart, k.OBCIGanglionPacket18Bit.dataStop)));
samples.push(buildSample(o.lastSampleNumber * 2 - 1, o.decompressedSamples[1], o.sendCounts));
samples.push(buildSample(o.lastSampleNumber * 2, o.decompressedSamples[2], o.sendCounts));
switch (o.lastSampleNumber % 10) {
case k.OBCIGanglionAccelAxisX:
o.accelArray[0] = o.sendCounts ? o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) : o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) * k.OBCIGanglionAccelScaleFactor;
break;
case k.OBCIGanglionAccelAxisY:
o.accelArray[1] = o.sendCounts ? o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) : o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) * k.OBCIGanglionAccelScaleFactor;
break;
case k.OBCIGanglionAccelAxisZ:
o.accelArray[2] = o.sendCounts ? o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) : o.rawDataPacket.readInt8(k.OBCIGanglionPacket18Bit.auxByte - 1) * k.OBCIGanglionAccelScaleFactor;
if (o.sendCounts) {
samples[0].accelData = o.accelArray;
} else {
samples[0].accelDataCounts = o.accelArray;
}
break;
default:
break;
}
} else {
decompressSamples(o, decompressDeltas19Bit(o.rawDataPacket.slice(k.OBCIGanglionPacket19Bit.dataStart, k.OBCIGanglionPacket19Bit.dataStop)));
samples.push(buildSample((o.lastSampleNumber - 100) * 2 - 1, o.decompressedSamples[1], o.sendCounts));
samples.push(buildSample((o.lastSampleNumber - 100) * 2, o.decompressedSamples[2], o.sendCounts));
}
// Rotate the 0 position for next time
for (let i = 0; i < k.OBCINumberOfChannelsGanglion; i++) {
o.decompressedSamples[0][i] = o.decompressedSamples[2][i];
}
return samples;
}
/**
* Process and emit an impedance value
* @param o {RawDataToSample} - Used to hold data and configuration settings
* @private
*/
function processImpedanceData (o) {
const byteId = parseInt(o.rawDataPacket[0]);
let channelNumber;
switch (byteId) {
case k.OBCIGanglionByteIdImpedanceChannel1:
channelNumber = 1;
break;
case k.OBCIGanglionByteIdImpedanceChannel2:
channelNumber = 2;
break;
case k.OBCIGanglionByteIdImpedanceChannel3:
channelNumber = 3;
break;
case k.OBCIGanglionByteIdImpedanceChannel4:
channelNumber = 4;
break;
case k.OBCIGanglionByteIdImpedanceChannelReference:
channelNumber = 0;
break;
}
let output = {
channelNumber: channelNumber,
impedanceValue: 0
};
let end = o.rawDataPacket.length;
while (Number.isNaN(Number(o.rawDataPacket.slice(1, end))) && end !== 0) {
end--;
}
if (end !== 0) {
output.impedanceValue = Number(o.rawDataPacket.slice(1, end));
}
return output;
}
/**
* Used to stack multi packet buffers into the multi packet buffer. This is finally emitted when a stop packet byte id
* is received.
* @param o {RawDataToSample} - Used to hold data and configuration settings
* @private
*/
function processMultiBytePacket (o) {
if (o.multiPacketBuffer) {
o.multiPacketBuffer = Buffer.concat([Buffer.from(o.multiPacketBuffer), Buffer.from(o.rawDataPacket.slice(k.OBCIGanglionPacket19Bit.dataStart, k.OBCIGanglionPacket19Bit.dataStop))]);
} else {
o.multiPacketBuffer = o.rawDataPacket.slice(k.OBCIGanglionPacket19Bit.dataStart, k.OBCIGanglionPacket19Bit.dataStop);
}
}
/**
* Adds the `data` buffer to the multi packet buffer and emits the buffer as 'message'
* @param o {RawDataToSample} - Used to hold data and configuration settings
* @private
*/
function processMultiBytePacketStop (o) {
processMultiBytePacket(o);
const str = o.multiPacketBuffer.toString();
o.multiPacketBuffer = null;
return {
'message': str
};
}
/**
* Utilize `receivedDeltas` to get actual count values.
* @param receivedDeltas {Array} - An array of deltas
* of shape 2x4 (2 samples per packet and 4 channels per sample.)
* @private
*/
function decompressSamples (o, receivedDeltas) {
// add the delta to the previous value
for (let i = 1; i < 3; i++) {
for (let j = 0; j < 4; j++) {
o.decompressedSamples[i][j] = o.decompressedSamples[i - 1][j] - receivedDeltas[i - 1][j];
}
}
}
/**
* Builds a sample object from an array and sample number.
* @param o {RawDataToSample} - Used to hold data and configuration settings
* @return {Array}
* @private
*/
function buildSample (sampleNumber, rawData, sendCounts) {
let sample;
if (sendCounts) {
sample = newSampleNoScale(sampleNumber);
sample.channelDataCounts = rawData;
} else {
sample = newSample(sampleNumber);
for (let j = 0; j < k.OBCINumberOfChannelsGanglion; j++) {
sample.channelData.push(rawData[j] * k.OBCIGanglionScaleFactorPerCountVolts);
}
}
sample.timestamp = Date.now();
return sample;
}
/**
* Used to route samples for Ganglion
* @param o {RawDataToSample} - Used to hold data and configuration settings
* @returns {*}
*/
function processRouteSampleData (o) {
if (parseInt(o.rawDataPacket[0]) === k.OBCIGanglionByteIdUncompressed) {
return processUncompressedData(o);
} else {
return processCompressedData(o);
}
}
/**
* Process an uncompressed packet of data.
* @param o {RawDataToSample} - Used to hold data and configuration settings
* @private
*/
function processUncompressedData (o) {
// Resets the packet counter back to zero
o.lastSampleNumber = k.OBCIGanglionByteIdUncompressed; // used to find dropped packets
for (let i = 0; i < 4; i++) {
o.decompressedSamples[0][i] = utilitiesModule.interpret24bitAsInt32(o.rawDataPacket.slice(1 + (i * 3), 1 + (i * 3) + 3)); // seed the decompressor
}
return [buildSample(0, o.decompressedSamples[0], o.sendCounts)];
}
/**
* Converts a special ganglion 18 bit compressed number
* The compressions uses the LSB, bit 1, as the signed bit, instead of using
* the MSB. Therefore you must not look to the MSB for a sign extension, one
* must look to the LSB, and the same rules applies, if it's a 1, then it's a
* negative and if it's 0 then it's a positive number.
* @param threeByteBuffer {Buffer}
* A 3-byte buffer with only 18 bits of actual data.
* @return {number} A signed integer.
*/
function convert18bitAsInt32 (threeByteBuffer) {
let prefix = 0;
if (threeByteBuffer[2] & 0x01 > 0) {
// console.log('\t\tNegative number')
prefix = 0b11111111111111;
}
return (prefix << 18) | (threeByteBuffer[0] << 16) | (threeByteBuffer[1] << 8) | threeByteBuffer[2];
}
/**
* Converts a special ganglion 19 bit compressed number
* The compressions uses the LSB, bit 1, as the signed bit, instead of using
* the MSB. Therefore you must not look to the MSB for a sign extension, one
* must look to the LSB, and the same rules applies, if it's a 1, then it's a
* negative and if it's 0 then it's a positive number.
* @param threeByteBuffer {Buffer}
* A 3-byte buffer with only 19 bits of actual data.
* @return {number} A signed integer.
*/
function convert19bitAsInt32 (threeByteBuffer) {
let prefix = 0;
if (threeByteBuffer[2] & 0x01 > 0) {
// console.log('\t\tNegative number')
prefix = 0b1111111111111;
}
return (prefix << 19) | (threeByteBuffer[0] << 16) | (threeByteBuffer[1] << 8) | threeByteBuffer[2];
}
/**
* Called to when a compressed packet is received.
* @param buffer {Buffer} Just the data portion of the sample. So 18 bytes.
* @return {Array} - An array of deltas of shape 2x4 (2 samples per packet
* and 4 channels per sample.)
* @private
*/
function decompressDeltas18Bit (buffer) {
let D = new Array(k.OBCIGanglionSamplesPerPacket); // 2