Skip to main content

Neurosity

@neurosity/sdk


@neurosity/sdk / Neurosity

Class: Neurosity

Defined in: Neurosity.ts:77

Example

import { Neurosity } from "@neurosity/sdk";

const neurosity = new Neurosity();

Constructors

Constructor

new Neurosity(options): Neurosity

Defined in: Neurosity.ts:120

Creates new instance of the Neurosity SDK

const neurosity = new Neurosity();

Parameters

options

SDKOptions = {}

Returns

Neurosity

Accessors

training

Get Signature

get training(): Training

Defined in: Neurosity.ts:1533

Streaming modes:Wi-Fi
neurosity.training.record({
metric: "kinesis",
label: "push"
});

neurosity.training.stop({
metric: "kinesis",
label: "push"
});
Returns

Training

Training methods

Methods

__getApp()

__getApp(): FirebaseApp

Defined in: Neurosity.ts:396

Internal

Not user facing.

Returns

FirebaseApp


accelerometer()

accelerometer(): Observable<Accelerometer>

Defined in: Neurosity.ts:830

Streaming modes:Wi-FiBluetooth

Observes accelerometer data Supported by the Crown and Notion 2 devices.

neurosity.accelerometer().subscribe(accelerometer => {
console.log(accelerometer);
});

// { acceleration: ..., inclination: ..., orientation: ..., pitch: ..., roll: ..., x: ..., y: ..., z: ... }

Returns

Observable<Accelerometer>

Observable of accelerometer metric events


addDevice()

addDevice(deviceId): Promise<void>

Defined in: Neurosity.ts:422

Add a device to the user's account

await neurosity.addDevice("[deviceId]");

Parameters

deviceId

string

Returns

Promise<void>


addMarker()

addMarker(label): Promise<Action>

Defined in: Neurosity.ts:701

Streaming modes:Wi-FiBluetooth

Injects an EEG marker to data stream

neurosity.addMarker("eyes-closed");

// later...

neurosity.addMarker("eyes-open");

Parameters

label

string

Name the label to inject

Returns

Promise<Action>


brainwaves()

brainwaves(label): Observable<Epoch | PSD | PowerByBand>

Defined in: Neurosity.ts:910

Streaming modes:Wi-FiBluetooth

The raw brainwaves parameter emits epochs of 16 samples for Crown and 25 for Notion 1 and 2.

Example

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

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

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

neurosity.brainwaves("psd").subscribe(brainwaves => {
console.log(brainwaves);
});

Parameters

label

BrainwavesLabel

Name of metric properties to filter by

Returns

Observable<Epoch | PSD | PowerByBand>

Observable of brainwaves metric events


calm()

calm(): Observable<Calm>

Defined in: Neurosity.ts:1194

Streaming modes:Wi-FiBluetooth

Example

neurosity.calm().subscribe(calm => {
console.log(calm.probability);
});

// 0.45
// 0.47
// 0.53
// 0.51
// ...

Returns

Observable<Calm>

Observable of calm events - awareness/calm alias


changeSettings()

changeSettings(settings): Promise<void>

Defined in: Neurosity.ts:1498

Streaming modes:Wi-Fi

Changes device settings programmatically. These settings can be also changed from the developer console under device settings.

Available settings [[Settings]]

Example

neurosity.changeSettings({
lsl: true
});

Parameters

settings

Settings

Returns

Promise<void>


createAccount()

createAccount(credentials): Promise<any>

Defined in: Neurosity.ts:1626

Creates user account and automatically signs in with same credentials

Parameters

credentials

EmailAndPassword

Returns

Promise<any>

user credential


createApiKey()

createApiKey(data): Promise<ApiKeyRecord>

Defined in: Neurosity.ts:1677

Creates API key to use to login with { apiKey }.

Parameters

data

CreateApiKeyRequest

Returns

Promise<ApiKeyRecord>

API key record


createBluetoothToken()

createBluetoothToken(): Promise<string>

Defined in: Neurosity.ts:1646

Internal

Not user facing

Creates token (JWT) designed to authenticate and authorize Bluetooth clients/centrals.

Returns

Promise<string>

token


createCustomToken()

createCustomToken(): Promise<CustomToken>

Defined in: Neurosity.ts:1658

Internal

Not user facing yet

Creates custom token (JWT) to use to login with { customToken }.

Returns

Promise<CustomToken>

custom token


createOAuthURL()

createOAuthURL(config): Promise<string>

Defined in: Neurosity.ts:1770

Create OAuth URL 💡 OAuth requires developers to register their apps with Neurosity Read full OAuth guide

Creates client-specific OAuth URL. This is the first step of the OAuth workflow. Use this function to create a URL you can use to redirect users to the Neurosity sign-in page. 💡 This function is designed to only run on the server side for security reasons, as it requires your client secret.

const { Neurosity } = require("@neurosity/sdk");

const neurosity = new Neurosity({
autoSelectDevice: false
});

exports.handler = async function (event) {
return neurosity
.createOAuthURL({
clientId: process.env.NEUROSITY_OAUTH_CLIENT_ID,
clientSecret: process.env.NEUROSITY_OAUTH_CLIENT_SECRET,
redirectUri: process.env.NEUROSITY_OAUTH_CLIENT_REDIRECT_URI,
responseType: "token",
state: Math.random().toString().split(".")[1],
scope: [
"read:devices-info",
"read:devices-status",
"read:signal-quality",
"read:brainwaves"
]
})
.then((url) => ({
statusCode: 200,
body: JSON.stringify({ url })
}))
.catch((error) => ({
statusCode: 400,
body: JSON.stringify(error.response.data)
}));
};

Parameters

config

OAuthConfig

Returns

Promise<string>

custom token


deleteAccount()

deleteAccount(): Promise<void>

Defined in: Neurosity.ts:1634

Removes all devices from an account and then deletes the account

Returns

Promise<void>


deleteUserExperiment()

deleteUserExperiment(experimentId): Promise<void>

Defined in: Neurosity.ts:1892

Streaming modes:Wi-Fi

Deletes a specific experiment provided an experiment ID

await neurosity.deleteUserExperiment(experiment.id);

Parameters

experimentId

string

The ID of the Experiment

Returns

Promise<void>

void


disconnect()

disconnect(): Promise<void>

Defined in: Neurosity.ts:653

Streaming modes:Wi-FiBluetooth

Ends database connection

await neurosity.disconnect();

Returns

Promise<void>


focus()

focus(): Observable<Focus>

Defined in: Neurosity.ts:1375

Streaming modes:Wi-FiBluetooth

Example

neurosity.focus().subscribe(focus => {
console.log(focus.probability);
});

// 0.56
// 0.46
// 0.31
// 0.39
// ...

Returns

Observable<Focus>

Observable of focus events - awareness/focus alias


getDevices()

getDevices(): Promise<DeviceInfo[]>

Defined in: Neurosity.ts:527

Get user devices

Returns a list of devices claimed by the user authenticated.

const devices = await neurosity.getDevices();
console.log(devices);

Returns

Promise<DeviceInfo[]>


getHapticEffects()

getHapticEffects(): HapticEffects

Defined in: Neurosity.ts:810

const effects = neurosity.getHapticEffects();

Returns

HapticEffects


getInfo()

getInfo(): Promise<DeviceInfo>

Defined in: Neurosity.ts:600

const info = await neurosity.getInfo();

Returns

Promise<DeviceInfo>


getOAuthToken()

getOAuthToken(query): Promise<OAuthQueryResult>

Defined in: Neurosity.ts:1821

Get OAuth Token 💡 OAuth requires developers to register their apps with Neurosity Read full OAuth guide

Gets client-specific OAuth token for a given userId.

💡 This function is designed to only run on the server side for security reasons, as it requires your client secret. Here's an example of a cloud function that receives a userId via query params and loads the client id and client secret securely via environment variables.

const { Neurosity } = require("@neurosity/sdk");

const neurosity = new Neurosity({
autoSelectDevice: false
});

exports.handler = async function (event) {
const userId = event.queryStringParameters?.userId;

return neurosity
.getOAuthToken({
clientId: process.env.NEUROSITY_OAUTH_CLIENT_ID,
clientSecret: process.env.NEUROSITY_OAUTH_CLIENT_SECRET,
userId
})
.then((token) => ({
statusCode: 200,
body: JSON.stringify(token)
}))
.catch((error) => ({
statusCode: 200,
body: JSON.stringify(error.response.data)
}));
};

Parameters

query

OAuthQuery

Returns

Promise<OAuthQueryResult>

custom token


getSelectedDevice()

getSelectedDevice(): Promise<DeviceInfo>

Defined in: Neurosity.ts:581

Get selected device

const selectedDevice = await neurosity.getSelectedDevice();
console.log(selectedDevice);

Returns

Promise<DeviceInfo>


getTimesyncOffset()

getTimesyncOffset(): number

Defined in: Neurosity.ts:1720

Internal

Not user facing yet

Gets the offset between the device's clock and the client's clock Requires option.timesync to be true

Returns

number

timesyncOffset


goOffline()

goOffline(): void

Defined in: Neurosity.ts:1607

Internal

Proof of Concept for disconnecting db

Returns

void


goOnline()

goOnline(): void

Defined in: Neurosity.ts:1615

Internal

Proof of Concept for resuming db connection

Returns

void


haptics()

haptics(effects): Promise<any>

Defined in: Neurosity.ts:761

Streaming modes:Wi-FiBluetooth

Queue haptic motor commands

To queue haptic P7 only,

await neurosity.haptics({
P7: ["tripleClick100"]
});

To queue both motors at the same time

await neurosity.haptics({
P7: [neurosity.getHapticEffects().strongClick100],
P8: [neurosity.getHapticEffects().strongClick100]
});

You can queue different commands to the motors too

const effects = neurosity.getHapticEffects();
await neurosity.haptics({
P7: [effects.transitionRampUpLongSmooth1_0_to_100,
effects.transitionRampDownLongSmooth1_100_to_0],
P8: [effects.strongClick100]
});

Parameters

effects

any

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!

Returns

Promise<any>


kinesis()

kinesis(label): Observable<Kinesis>

Defined in: Neurosity.ts:1403

Streaming modes:Wi-Fi

Parameters

label

string

Name of metric properties to filter by

Returns

Observable<Kinesis>

Observable of kinesis metric events


login()

login(credentials): Promise<void>

Defined in: Neurosity.ts:375

Starts user session

await neurosity.login({
email: "...",
password: "..."
});

Parameters

credentials

Credentials

Returns

Promise<void>


logout()

logout(): Promise<void>

Defined in: Neurosity.ts:388

Ends user session

await neurosity.logout();
// session has ended

Returns

Promise<void>


onAuthStateChanged()

onAuthStateChanged(): Observable<any>

Defined in: Neurosity.ts:411

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.

neurosity.onAuthStateChanged().subscribe((user) => {
console.log(user);
});

Returns

Observable<any>


onDeviceChange()

onDeviceChange(): Observable<DeviceInfo>

Defined in: Neurosity.ts:630

Observes selected device

neurosity.onDeviceChange().subscribe(device => {
console.log(device);
});

Returns

Observable<DeviceInfo>


onUserClaimsChange()

onUserClaimsChange(): Observable<UserClaims>

Defined in: Neurosity.ts:513

Subscribe to user claims changes

neurosity.onUserClaimsChange().subscribe((userClaims) => {
console.log(userClaims);
});

Returns

Observable<UserClaims>


onUserDevicesChange()

onUserDevicesChange(): Observable<DeviceInfo[]>

Defined in: Neurosity.ts:490

Subscribe to user devices changes

neurosity.onUserDevicesChange().subscribe((devices) => {
console.log(devices);
});

Returns

Observable<DeviceInfo[]>


onUserExperiments()

onUserExperiments(): Observable<Experiment[]>

Defined in: Neurosity.ts:1876

Streaming modes:Wi-Fi

Observes and returns a list of all Kinesis experiments and all subsequent experiment changes. Here's an example of how to get a list of all Kinesis labels that have been trained:


const getUniqueLabels = (experiments) => {
const labels = experiments.flatMap((experiment) => experiment.labels);
// only return unique labels
return [...new Set(labels)];
}

neurosity.onUserExperiments().subscribe((experiments) => {
console.log(experiments);
console.log("labels", getUniqueLabels(experiments));
});

// [{ id: '...', deviceId: '...', labels: [ 'drop' ], name: 'Lightgray cheetah', timestamp: 1577908381552, totalTrials: 16, userId: '...' }]
// ["drop", "lift", "push"]

Returns

Observable<Experiment[]>

Observable of experiments events


osVersion()

osVersion(): Observable<string>

Defined in: Neurosity.ts:1343

Streaming modes:Wi-Fi

Observes the current OS version and all subsequent version changes in real-time.

neurosity.osVersion().subscribe((osVersion) => {
console.log(osVersion);
});

// "16.0.0"

Returns

Observable<string>

Observable of osVersion events. e.g 16.0.0


predictions()

predictions(label): Observable<any>

Defined in: Neurosity.ts:1429

Streaming modes:Wi-Fi

Parameters

label

string

Name of metric properties to filter by

Returns

Observable<any>

Observable of predictions metric events


record()

record(options): Promise<RecordingResult>

Defined in: Neurosity.ts:967

Streaming modes:Wi-Fi

Records raw brainwave data for a specified duration and saves it as a dataset. The recording is stored in cloud storage and a metadata record is created in Firestore. If the network is unavailable, the recording is saved locally on the device and uploaded automatically when connectivity is restored.

const result = await neurosity.record({
label: "eyes-closed",
duration: 60000
});

console.log(result.id); // Firestore record ID

With all options:

const result = await neurosity.record({
name: "Morning session",
label: "focus-training",
duration: 120000,
experimentId: "exp-001"
});

Parameters

options

RecordingOptions

Recording options including label and duration

Returns

Promise<RecordingResult>

Promise resolving to the recording result


removeApiKey()

removeApiKey(apiKeyId): Promise<RemoveApiKeyResponse>

Defined in: Neurosity.ts:1697

Removes API key

Parameters

apiKeyId

string

Returns

Promise<RemoveApiKeyResponse>

void


removeDevice()

removeDevice(deviceId): Promise<void>

Defined in: Neurosity.ts:443

Remove a device from the user's account

await neurosity.removeDevice("[deviceId]");

Parameters

deviceId

string

Returns

Promise<void>


removeOAuthAccess()

removeOAuthAccess(): Promise<OAuthRemoveResponse>

Defined in: Neurosity.ts:1847

Remove OAuth Access 💡 OAuth requires developers to register their apps with Neurosity Read full OAuth guide

Removes client-specific OAuth token for a given userId. Requires SDK to be signed in with OAuth custom token.

await neurosity.removeOAuthAccess().catch((error) => {
// handle error here...
});

Returns

Promise<OAuthRemoveResponse>

custom token


selectDevice()

selectDevice(deviceSelector): Promise<DeviceInfo>

Defined in: Neurosity.ts:556

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.
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.

Parameters

deviceSelector

(devices) => DeviceInfo

Returns

Promise<DeviceInfo>


settings()

settings(): Observable<Settings>

Defined in: Neurosity.ts:1314

Streaming modes:Wi-Fi

Observes last state of settings and all subsequent settings changes

neurosity.settings().subscribe(settings => {
console.log(settings.lsl);
});

// true
// ...

Returns

Observable<Settings>

Observable of settings metric events


signalQuality()

signalQuality(): Observable<SignalQuality>

Defined in: Neurosity.ts:1233

Streaming modes:Wi-FiBluetooth

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

neurosity.signalQuality().subscribe(signalQuality => {
console.log(signalQuality);
});

// { FC6: { standardDeviation: 3.5, status: "good" }, C3: {...}, ... }

Returns

Observable<SignalQuality>

Observable of signalQuality metric events


signalQualityV2()

signalQualityV2(): Observable<SignalQualityV2>

Defined in: Neurosity.ts:1274

Streaming modes:Wi-FiBluetooth

Observes signal quality with normalized scores (0-1) per channel and an overall score.

neurosity.signalQualityV2().subscribe(quality => {
console.log(quality.overall.score); // 0-1
console.log(quality.byChannel.CP3.score); // 0-1
});

// { timestamp: 1234567890, overall: { score: 0.85 }, byChannel: { CP3: { score: 0.9 }, ... } }

Returns

Observable<SignalQualityV2>

Observable of signalQualityV2 metric events


startRecording()

startRecording(options): Promise<RecordingHandle>

Defined in: Neurosity.ts:1049

Streaming modes:Wi-Fi

Starts a variable-length brainwave recording and returns a handle for controlling it. Use this when you need UI control over the recording lifecycle (progress, cancel, stop-and-save).

const recording = await neurosity.startRecording({
label: "eyes-closed",
maxDuration: 120000 // 2 minute max
});

// Track progress
recording.elapsed$.subscribe(ms => {
console.log(`Recording: ${(ms / 1000).toFixed(0)}s`);
});

// Stop and save after some time
const result = await recording.stop();
console.log(result.id);

// Or cancel without saving
await recording.cancel();

Parameters

options

StartRecordingOptions

Recording options including label and maxDuration

Returns

Promise<RecordingHandle>

Promise resolving to a RecordingHandle


status()

status(): Observable<DeviceStatus>

Defined in: Neurosity.ts:1465

Streaming modes:Wi-FiBluetooth

Observes last state of status and all subsequent status changes

neurosity.status().subscribe(status => {
console.log(status.state);
});

// "online"
// ...

Returns

Observable<DeviceStatus>

Observable of status metric events


streamingState()

streamingState(): Observable<{ activeMode: STREAMING_TYPE; connected: boolean; streamingMode: STREAMING_MODE; }>

Defined in: Neurosity.ts:204

Subscribe to the device's streaming state changes and the current strategy

Streams the current mode of streaming (wifi or bluetooth).

neurosity.streamingState().subscribe((streamingState) => {
console.log(streamingState);
// { streamingMode: "wifi-only", activeMode: "wifi", connected: true }
});

Returns

Observable<{ activeMode: STREAMING_TYPE; connected: boolean; streamingMode: STREAMING_MODE; }>


transferDevice()

transferDevice(options): Promise<void>

Defined in: Neurosity.ts:467

Transfer a device to the user's account

await neurosity.transferDevice({
deviceId: "[deviceId]",
newOwnerEmail: "[newOwnerEmail]"
});

Parameters

options

TransferDeviceOptions

Returns

Promise<void>