/
Neurosity.ts
1547 lines (1395 loc) · 41 KB
/
Neurosity.ts
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
import { combineLatest, Observable, of, throwError } from "rxjs";
import { ReplaySubject, firstValueFrom } from "rxjs";
import { map, startWith, switchMap } from "rxjs/operators";
import { distinctUntilChanged } from "rxjs/operators";
import isEqual from "fast-deep-equal";
import { CloudClient, createUser } from "./api/index";
import { credentialWithLink, SERVER_TIMESTAMP } from "./api/index";
import { SDKOptions } from "./types/options";
import { STREAMING_MODE, STREAMING_TYPE } from "./types/streaming";
import { Training } from "./types/training";
import { Credentials, EmailAndPassword } from "./types/credentials";
import { CustomToken } from "./types/credentials";
import { Settings, ChangeSettings } from "./types/settings";
import { SignalQuality } from "./types/signalQuality";
import { Kinesis } from "./types/kinesis";
import { Calm } from "./types/calm";
import { Focus } from "./types/focus";
import { getLabels } from "./utils/subscription";
import { BrainwavesLabel, Epoch, PowerByBand, PSD } from "./types/brainwaves";
import { Accelerometer } from "./types/accelerometer";
import { DeviceInfo, OSVersion } from "./types/deviceInfo";
import { DeviceStatus, STATUS } from "./types/status";
import { Action } from "./types/actions";
import { HapticEffects } from "./types/hapticEffects";
import * as errors from "./utils/errors";
import * as platform from "./utils/platform";
import * as hapticEffects from "./utils/hapticEffects";
import { validateOAuthScopeForFunctionName } from "./utils/oauth";
import { validateOAuthScopeForAction } from "./utils/oauth";
import { createOAuthURL } from "./api/https/createOAuthURL";
import { getOAuthToken } from "./api/https/getOAuthToken";
import { OAuthConfig, OAuthQuery } from "./types/oauth";
import { OAuthQueryResult, OAuthRemoveResponse } from "./types/oauth";
import { UserClaims } from "./types/user";
import { isNode } from "./utils/is-node";
import { getCloudMetric } from "./utils/metrics";
import { Experiment } from "./types/experiment";
import { TransferDeviceOptions } from "./utils/transferDevice";
import { BluetoothClient, osHasBluetoothSupport } from "./api/bluetooth";
import { BLUETOOTH_CONNECTION } from "./api/bluetooth/types";
const defaultOptions = {
timesync: false,
autoSelectDevice: true,
streamingMode: STREAMING_MODE.WIFI_ONLY,
emulator: false,
emulatorHost: "localhost",
emulatorAuthPort: 9099,
emulatorDatabasePort: 9000,
emulatorFunctionsPort: 5001,
emulatorFirestorePort: 8080,
emulatorOptions: {}
};
/**
* import StreamingModes from "@site/src/components/StreamingModes";
*
* Example
* ```typescript
* import { Neurosity } from "@neurosity/sdk";
*
* const neurosity = new Neurosity();
* ```
*/
export class Neurosity {
/**
* @hidden
*/
protected options: SDKOptions;
/**
* @hidden
*/
protected cloudClient: CloudClient;
/**
* @hidden
*/
protected bluetoothClient: BluetoothClient;
/**
* @hidden
*/
protected isMissingBluetoothTransport: boolean;
/**
* @hidden
*/
private streamingMode$ = new ReplaySubject<STREAMING_MODE>(1);
/**
*
* @hidden
*/
static credentialWithLink = credentialWithLink;
/**
*
* @hidden
*/
static createUser = createUser;
/**
*
* @hidden
*/
static SERVER_TIMESTAMP = SERVER_TIMESTAMP;
/**
* Creates new instance of the Neurosity SDK
*
* ```typescript
* const neurosity = new Neurosity();
* ```
* @param options
*/
constructor(options: SDKOptions = {}) {
const { streamingMode, bluetoothTransport } = options;
this.options = Object.freeze({
...defaultOptions,
...options
});
this.cloudClient = new CloudClient(this.options);
if (!!bluetoothTransport) {
this.bluetoothClient = new BluetoothClient({
selectedDevice$: this.onDeviceChange(),
osHasBluetoothSupport$: this._osHasBluetoothSupport(),
createBluetoothToken: this.createBluetoothToken.bind(this),
transport: bluetoothTransport
});
}
this._initStreamingMode(streamingMode, !!bluetoothTransport);
}
/**
*
* @hidden
*/
_initStreamingMode(
streamingMode: STREAMING_MODE,
hasBluetoothTransport: boolean
): void {
const streamingModeFeaturesBluetooth = [
STREAMING_MODE.BLUETOOTH_WITH_WIFI_FALLBACK,
STREAMING_MODE.WIFI_WITH_BLUETOOTH_FALLBACK
].includes(streamingMode);
const isInvalidStreamingMode =
!Object.values(STREAMING_MODE).includes(streamingMode);
const isMissingBluetoothTransport =
streamingModeFeaturesBluetooth && !hasBluetoothTransport;
this.isMissingBluetoothTransport = isMissingBluetoothTransport;
const shouldDefaultToCloud =
!streamingMode || isInvalidStreamingMode || isMissingBluetoothTransport;
// Default to backwards compatible cloud streaming mode if:
// 1. No streaming mode is provided
// 2. An invalid streaming mode is provided
// 3. A streaming mode containing bluetooth is provided, but without a bluetooth transport
if (shouldDefaultToCloud) {
this.streamingMode$.next(STREAMING_MODE.WIFI_ONLY);
} else {
this.streamingMode$.next(streamingMode);
}
}
/**
*
* @hidden
*/
_osHasBluetoothSupport() {
return combineLatest({
selectedDevice: this.onDeviceChange(),
osVersion: this.osVersion().pipe(startWith(null))
}).pipe(
map(({ selectedDevice, osVersion }) =>
osHasBluetoothSupport(selectedDevice, osVersion)
)
);
}
/**
* Subscribe to the device's streaming state changes and the current strategy
*
* Streams the current mode of streaming (wifi or bluetooth).
*
* ```typescript
* neurosity.streamingState().subscribe((streamingState) => {
* console.log(streamingState);
* // { streamingMode: "wifi-only", activeMode: "wifi", connected: true }
* });
* ```
*/
public streamingState(): Observable<{
connected: boolean;
activeMode: STREAMING_TYPE;
streamingMode: STREAMING_MODE;
}> {
const isWifiOnline = (state: STATUS) =>
[STATUS.ONLINE, STATUS.UPDATING].includes(state);
return this.streamingMode$.pipe(
switchMap((streamingMode: STREAMING_MODE) => {
return combineLatest({
selectedDevice: this.onDeviceChange(),
osHasBluetoothSupport: this._osHasBluetoothSupport()
}).pipe(
switchMap(({ selectedDevice, osHasBluetoothSupport }) => {
if (!selectedDevice) {
return of({
connected: false,
streamingMode,
activeMode: STREAMING_TYPE.WIFI
});
}
const isUnableToUseBluetooth =
this.isMissingBluetoothTransport || !osHasBluetoothSupport;
if (isUnableToUseBluetooth) {
return this.cloudClient.status().pipe(
map(({ state }) => ({
connected: isWifiOnline(state),
streamingMode,
activeMode: STREAMING_TYPE.WIFI
}))
);
}
return combineLatest({
wifiStatus: this.cloudClient.status(),
bluetoothConnection: !!this?.bluetoothClient
? this.bluetoothClient.connection()
: of(BLUETOOTH_CONNECTION.DISCONNECTED)
}).pipe(
map(({ wifiStatus, bluetoothConnection }) => {
const isBluetoothConnected =
bluetoothConnection === BLUETOOTH_CONNECTION.CONNECTED;
switch (streamingMode) {
default:
case STREAMING_MODE.WIFI_ONLY:
return {
connected: isWifiOnline(wifiStatus.state),
streamingMode,
activeMode: STREAMING_TYPE.WIFI
};
case STREAMING_MODE.WIFI_WITH_BLUETOOTH_FALLBACK:
return {
connected:
isWifiOnline(wifiStatus.state) || !isBluetoothConnected
? isWifiOnline(wifiStatus.state)
: isBluetoothConnected,
streamingMode,
activeMode:
isWifiOnline(wifiStatus.state) || !isBluetoothConnected
? STREAMING_TYPE.WIFI
: STREAMING_TYPE.BLUETOOTH
};
case STREAMING_MODE.BLUETOOTH_WITH_WIFI_FALLBACK:
return {
connected: isBluetoothConnected
? true
: isWifiOnline(wifiStatus.state),
streamingMode,
activeMode: isBluetoothConnected
? STREAMING_TYPE.BLUETOOTH
: STREAMING_TYPE.WIFI
};
}
}),
distinctUntilChanged((a, b) => isEqual(a, b))
);
})
);
})
);
}
/**
*
* @hidden
*/
_withStreamingModeObservable<T>(streams: {
wifi: () => Observable<T>;
bluetooth: () => Observable<T>;
}): Observable<any> {
const { wifi, bluetooth } = streams;
return this.streamingState().pipe(
switchMap(({ activeMode }) => {
switch (activeMode) {
case STREAMING_TYPE.WIFI:
return wifi();
case STREAMING_TYPE.BLUETOOTH:
return bluetooth();
default:
return wifi();
}
})
);
}
/**
*
* @hidden
*/
async _withStreamingModePromise<T>(promises: {
wifi: () => Promise<T>;
bluetooth: () => Promise<T>;
}): Promise<T> {
const { wifi, bluetooth } = promises;
const { activeMode } = await firstValueFrom(this.streamingState());
switch (activeMode) {
case STREAMING_TYPE.WIFI:
return await wifi();
case STREAMING_TYPE.BLUETOOTH:
return await bluetooth();
default:
return await wifi();
}
}
/**
*
* @hidden
*/
get bluetooth() {
return this?.bluetoothClient;
}
/**
*
* @hidden
*/
private _getCloudMetricDependencies() {
return {
options: this.options,
cloudClient: this.cloudClient,
onDeviceChange: this.onDeviceChange.bind(this),
status: this.status.bind(this)
};
}
/**
* Starts user session
*
* ```typescript
* await neurosity.login({
* email: "...",
* password: "..."
* });
* ```
*
* @param credentials
*/
public async login(credentials: Credentials): Promise<void> {
return await this.cloudClient.login(credentials);
}
/**
* Ends user session
*
* ```typescript
* await neurosity.logout();
* // session has ended
* ```
*
*/
public async logout(): Promise<void> {
return await this.cloudClient.logout();
}
/**
* @internal
* Not user facing.
*/
public __getApp() {
return this.cloudClient.__getApp();
}
/**
* Subscribe to auth state changes
*
* Streams the state of the auth session. If user has logged in, the user object will be set. When logged out, the user object will be null.
*
* ```typescript
* neurosity.onAuthStateChanged().subscribe((user) => {
* console.log(user);
* });
* ```
*/
public onAuthStateChanged(): Observable<any> {
return this.cloudClient.onAuthStateChanged();
}
/**
* @internal
* Not user facing yet
*/
public addDevice(deviceId: string): Promise<void> {
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
"addDevice"
);
if (hasOAuthError) {
return Promise.reject(OAuthError);
}
return this.cloudClient.addDevice(deviceId);
}
/**
* @internal
* Not user facing yet
*/
public removeDevice(deviceId: string): Promise<void> {
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
"removeDevice"
);
if (hasOAuthError) {
return Promise.reject(OAuthError);
}
return this.cloudClient.removeDevice(deviceId);
}
/**
* @internal
* Not user facing yet
*/
public transferDevice(options: TransferDeviceOptions): Promise<void> {
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
"transferDevice"
);
if (hasOAuthError) {
return Promise.reject(OAuthError);
}
return this.cloudClient.transferDevice(options);
}
/**
* @internal
* Not user facing yet
*/
public onUserDevicesChange(): Observable<DeviceInfo[]> {
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
"onUserDevicesChange"
);
if (hasOAuthError) {
return throwError(() => OAuthError);
}
return this.cloudClient.onUserDevicesChange();
}
/**
* @internal
* Not user facing yet
*/
public onUserClaimsChange(): Observable<UserClaims> {
return this.cloudClient.onUserClaimsChange();
}
/**
* Get user devices
*
* Returns a list of devices claimed by the user authenticated.
*
* ```typescript
* const devices = await neurosity.getDevices();
* console.log(devices);
* ```
*/
public async getDevices(): Promise<DeviceInfo[]> {
return await this.cloudClient.getDevices();
}
/**
* Select Device
*
* Rarely necessary, but useful when the user owns multiple devices.
*
* A common use case for manually selecting a device is when you wish to build a device dropdown a user can select from, instead of collecting the Device Id from the user ahead of time.
*
* The 3 steps to manually selecting a device are:
*
* - Set `autoSelectDevice` to false when instantiating the `Neurosity` class.
* - Authenticate with your Neurosity account to access your devices by calling the `neurosity.login(...)` function.
* - Call the `neurosity.selectDevice(...)` function with a device selector function.
*
* ```typescript
* const devices = await neurosity.selectDevice((devices) =>
* devices.find((device) => device.deviceNickname === "Crown-A1B")
* );
*
* console.log(devices);
* ```
*
* > If you own multiple devices, and don't pass `autoSelectDevice`, then the first device on the list will be automatically selected.
*
* For more info, check out the "Device Selection" guide.
*/
public async selectDevice(
deviceSelector: (devices: DeviceInfo[]) => DeviceInfo
): Promise<DeviceInfo> {
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
"selectDevice"
);
if (hasOAuthError) {
return Promise.reject(OAuthError);
}
return await this.cloudClient.selectDevice(deviceSelector);
}
/**
* Get selected device
*
* ```typescript
* const selectedDevice = await neurosity.getSelectedDevice();
* console.log(selectedDevice);
* ```
*/
public async getSelectedDevice(): Promise<DeviceInfo> {
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
"getSelectedDevice"
);
if (hasOAuthError) {
return Promise.reject(OAuthError);
}
return await this.cloudClient.getSelectedDevice();
}
/**
* ```typescript
* const info = await neurosity.getInfo();
* ```
*/
public async getInfo(): Promise<DeviceInfo> {
if (!(await this.cloudClient.didSelectDevice())) {
return Promise.reject(errors.mustSelectDevice);
}
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
"getInfo"
);
if (hasOAuthError) {
return Promise.reject(OAuthError);
}
return await this._withStreamingModePromise({
wifi: () => this.cloudClient.getInfo(),
bluetooth: () => this.bluetoothClient.getInfo()
});
}
/**
* Observes selected device
*
* ```typescript
* neurosity.onDeviceChange().subscribe(device => {
* console.log(device);
* });
* ```
*/
public onDeviceChange(): Observable<DeviceInfo> {
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
"onDeviceChange"
);
if (hasOAuthError) {
return throwError(() => OAuthError);
}
return this.cloudClient.onDeviceChange();
}
/**
* <StreamingModes wifi={true} bluetooth={true} />
*
* Ends database connection
*
* ```typescript
* await neurosity.disconnect();
* ```
*/
public async disconnect(): Promise<void> {
return await this._withStreamingModePromise({
wifi: () => this.cloudClient.disconnect(),
bluetooth: () => this.bluetoothClient.disconnect()
});
}
/**
* <StreamingModes wifi={true} bluetooth={true} />
*
* @internal
* Not user facing
*/
private async dispatchAction(action: Action): Promise<Action> {
if (!(await this.cloudClient.didSelectDevice())) {
return Promise.reject(errors.mustSelectDevice);
}
const [hasOAuthError, OAuthError] = validateOAuthScopeForAction(
this.cloudClient.userClaims,
action
);
if (hasOAuthError) {
return Promise.reject(OAuthError);
}
return await this._withStreamingModePromise({
wifi: () => this.cloudClient.dispatchAction(action),
bluetooth: () => this.bluetoothClient.dispatchAction(action)
});
}
/**
* <StreamingModes wifi={true} bluetooth={true} />
*
* Injects an EEG marker to data stream
*
* ```typescript
* neurosity.addMarker("eyes-closed");
*
* // later...
*
* neurosity.addMarker("eyes-open");
* ```
*
* @param label Name the label to inject
*/
public async addMarker(label: string): Promise<Action> {
if (!(await this.cloudClient.didSelectDevice())) {
throw errors.mustSelectDevice;
}
if (!label) {
throw new Error(`${errors.prefix}A label is required for addMarker`);
}
return await this._withStreamingModePromise({
wifi: () =>
this.cloudClient.dispatchAction({
command: "marker",
action: "add",
message: {
label,
timestamp: this.cloudClient.timestamp
}
}),
bluetooth: () => this.bluetoothClient.addMarker(label)
});
}
/**
* <StreamingModes wifi={true} bluetooth={true} />
*
* Queue haptic motor commands
*
* To queue haptic P7 only,
* ```typescript
* await neurosity.haptics({
* P7: ["tripleClick100"]
* });
* ```
*
* To queue both motors at the same time
* ```typescript
* await neurosity.haptics({
* P7: [neurosity.getHapticEffects().strongClick100],
* P8: [neurosity.getHapticEffects().strongClick100]
* });
* ```
*
* You can queue different commands to the motors too
* ```typescript
* const effects = neurosity.getHapticEffects();
* await neurosity.haptics({
* P7: [effects.transitionRampUpLongSmooth1_0_to_100,
* effects.transitionRampDownLongSmooth1_100_to_0],
* P8: [effects.strongClick100]
* });
* ```
*
* @param effects Effects to queue. The key of the object passed should be the location of the motor
* to queue. Each key can be an array of up to 7 commands. There is no haptic support for model
* version 1, Notion DK1. The Haptic motor's location is positioned in reference to the 10-10 EEG
* system used to label the channels of the Crown's EEG sensors. Notion 2 and Crown have haptics
* at P7 and P8. A list of haptic commands can be found on ./utils/hapticCodes.ts - there
* are about 127 of them!
*/
public async haptics(effects: any): Promise<any> {
const metric = "haptics";
if (!(await this.cloudClient.didSelectDevice())) {
return Promise.reject(errors.mustSelectDevice);
}
const modelVersion = (await this.getSelectedDevice())?.modelVersion;
const supportsHaptics = platform.supportsHaptics(modelVersion);
if (!supportsHaptics) {
return Promise.reject(
errors.metricNotSupportedByModel(metric, modelVersion)
);
}
const newPlatformHapticRequest =
platform.getPlatformHapticMotors(modelVersion);
for (const key in effects) {
if (!Object.keys(newPlatformHapticRequest).includes(key)) {
return Promise.reject(errors.locationNotFound(key, modelVersion));
}
const singleMotorEffects: string[] = effects[key];
const maxItems = 7;
if (singleMotorEffects.length > maxItems) {
return Promise.reject(errors.exceededMaxItems(maxItems));
}
newPlatformHapticRequest[key] = singleMotorEffects;
}
const payload = {
command: metric,
action: "queue",
responseRequired: true,
responseTimeout: 1000,
message: { effects: newPlatformHapticRequest }
};
return await this._withStreamingModePromise({
wifi: () => this.cloudClient.dispatchAction(payload),
bluetooth: () => this.bluetoothClient.dispatchAction(payload)
});
}
/**
* ```typescript
* const effects = neurosity.getHapticEffects();
* ```
*/
public getHapticEffects(): HapticEffects {
return hapticEffects;
}
/**
* <StreamingModes wifi={true} bluetooth={true} />
*
* Observes accelerometer data
* Supported by the Crown and Notion 2 devices.
*
* ```typescript
* neurosity.accelerometer().subscribe(accelerometer => {
* console.log(accelerometer);
* });
*
* // { acceleration: ..., inclination: ..., orientation: ..., pitch: ..., roll: ..., x: ..., y: ..., z: ... }
* ```
*
* @returns Observable of accelerometer metric events
*/
public accelerometer(): Observable<Accelerometer> {
const metric = "accelerometer";
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
metric
);
if (hasOAuthError) {
return throwError(() => OAuthError);
}
return this.onDeviceChange().pipe(
switchMap((selectedDevice: DeviceInfo | null) => {
const modelVersion =
selectedDevice?.modelVersion || platform.MODEL_VERSION_1;
const supportsAccel = platform.supportsAccel(modelVersion);
if (!supportsAccel) {
return throwError(() =>
errors.metricNotSupportedByModel(metric, modelVersion)
);
}
return this._withStreamingModeObservable({
wifi: () =>
getCloudMetric(this._getCloudMetricDependencies(), {
metric,
labels: getLabels(metric),
atomic: true
}),
bluetooth: () => this.bluetoothClient.accelerometer()
});
})
);
}
/**
* <StreamingModes wifi={true} bluetooth={true} />
*
* The `raw` brainwaves parameter emits epochs of 16 samples for Crown and 25 for Notion 1 and 2.
*
* Example
* ```typescript
* neurosity.brainwaves("raw").subscribe(brainwaves => {
* console.log(brainwaves);
* });
* ```
*
* Raw Unfiltered - The `rawUnfiltered` brainwaves parameter emits epochs of 16 samples for Crown and 25 for Notion 1 and 2.
* Example
* ```typescript
* neurosity.brainwaves("rawUnfiltered").subscribe(brainwaves => {
* console.log(brainwaves);
* });
* ```
*
* Power By Band - The `powerByBand` brainwaves parameter emits epochs 4 times a second. Every frequency label (e.g. beta) contains an average power value per channel.
*
* Example
* ```typescript
* neurosity.brainwaves("powerByBand").subscribe(brainwaves => {
* console.log(brainwaves);
* });
* ```
*
* Power Spectral Density (PSD) - The `psd` brainwaves parameter emits epochs 4 times a second. Every frequency label (e.g. alpha) contains the computed FFT (Fast Fourier transform) value per channel (see the `psd` property), as well as the frequency ranges (see the `freqs` property).
*
* Example
* ```typescript
* neurosity.brainwaves("psd").subscribe(brainwaves => {
* console.log(brainwaves);
* });
* ```
*
* @param label Name of metric properties to filter by
* @returns Observable of brainwaves metric events
*/
public brainwaves(
label: BrainwavesLabel
): Observable<Epoch | PowerByBand | PSD> {
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
"brainwaves"
);
if (hasOAuthError) {
return throwError(() => OAuthError);
}
return this._withStreamingModeObservable({
wifi: () =>
getCloudMetric(this._getCloudMetricDependencies(), {
metric: "brainwaves",
labels: label ? [label] : [],
atomic: false
}),
// @TODO: doesn't support multiple labels, we should make the higher
// order function only support one label
bluetooth: () => this.bluetoothClient.brainwaves(label)
});
}
/**
* <StreamingModes wifi={true} bluetooth={true} />
*
* Example
* ```typescript
* neurosity.calm().subscribe(calm => {
* console.log(calm.probability);
* });
*
* // 0.45
* // 0.47
* // 0.53
* // 0.51
* // ...
* ```
*
* @returns Observable of calm events - awareness/calm alias
*/
public calm(): Observable<Calm> {
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
"calm"
);
if (hasOAuthError) {
return throwError(() => OAuthError);
}
return this._withStreamingModeObservable({
wifi: () =>
getCloudMetric(this._getCloudMetricDependencies(), {
metric: "awareness",
labels: ["calm"],
atomic: false
}),
bluetooth: () => this.bluetoothClient.calm()
});
}
/**
* <StreamingModes wifi={true} bluetooth={true} />
*
* Observes signal quality data where each property is the name
* of the channel and the value includes the standard deviation and
* a status set by the device
*
* ```typescript
* neurosity.signalQuality().subscribe(signalQuality => {
* console.log(signalQuality);
* });
*
* // { FC6: { standardDeviation: 3.5, status: "good" }, C3: {...}, ... }
* ```
*
* @returns Observable of signalQuality metric events
*/
public signalQuality(): Observable<SignalQuality> {
const metric = "signalQuality";
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
metric
);
if (hasOAuthError) {
return throwError(() => OAuthError);
}
return this._withStreamingModeObservable({
wifi: () =>
getCloudMetric(this._getCloudMetricDependencies(), {
metric,
labels: getLabels(metric),
atomic: true
}),
bluetooth: () => this.bluetoothClient.signalQuality()
});
}
/**
* <StreamingModes wifi={true} />
*
* Observes last state of `settings` and all subsequent `settings` changes
*
* ```typescript
* neurosity.settings().subscribe(settings => {
* console.log(settings.lsl);
* });
*
* // true
* // ...
* ```
*
* @returns Observable of `settings` metric events
*/
public settings(): Observable<Settings> {
const [hasOAuthError, OAuthError] = validateOAuthScopeForFunctionName(
this.cloudClient.userClaims,
"settings"