Neurosity
@neurosity/sdk / Neurosity
Class: Neurosity
Defined in: Neurosity.ts:71
Example
import { Neurosity } from "@neurosity/sdk";
const neurosity = new Neurosity();
Constructors
Constructor
new Neurosity(
options):Neurosity
Defined in: Neurosity.ts:114
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:1287
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:390
Internal
Not user facing.
Returns
FirebaseApp
accelerometer()
accelerometer():
Observable<Accelerometer>
Defined in: Neurosity.ts:824
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:416
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:695
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:904
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
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:948
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:1252
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
Returns
Promise<void>
createAccount()
createAccount(
credentials):Promise<any>
Defined in: Neurosity.ts:1380
Creates user account and automatically signs in with same credentials
Parameters
credentials
Returns
Promise<any>
user credential
createApiKey()
createApiKey(
data):Promise<ApiKeyRecord>
Defined in: Neurosity.ts:1431
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:1400
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:1412
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:1524
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
Returns
Promise<string>
custom token
deleteAccount()
deleteAccount():
Promise<void>
Defined in: Neurosity.ts:1388
Removes all devices from an account and then deletes the account
Returns
Promise<void>
deleteUserExperiment()
deleteUserExperiment(
experimentId):Promise<void>
Defined in: Neurosity.ts:1646
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:647
Ends database connection
await neurosity.disconnect();
Returns
Promise<void>
focus()
focus():
Observable<Focus>
Defined in: Neurosity.ts:1129
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:521
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:804
const effects = neurosity.getHapticEffects();
Returns
getInfo()
getInfo():
Promise<DeviceInfo>
Defined in: Neurosity.ts:594
const info = await neurosity.getInfo();
Returns
Promise<DeviceInfo>
getOAuthToken()
getOAuthToken(
query):Promise<OAuthQueryResult>
Defined in: Neurosity.ts:1575
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
Returns
Promise<OAuthQueryResult>
custom token
getSelectedDevice()
getSelectedDevice():
Promise<DeviceInfo>
Defined in: Neurosity.ts:575
Get selected device
const selectedDevice = await neurosity.getSelectedDevice();
console.log(selectedDevice);
Returns
Promise<DeviceInfo>
getTimesyncOffset()
getTimesyncOffset():
number
Defined in: Neurosity.ts:1474
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:1361
Internal
Proof of Concept for disconnecting db
Returns
void
goOnline()
goOnline():
void
Defined in: Neurosity.ts:1369
Internal
Proof of Concept for resuming db connection
Returns
void
haptics()
haptics(
effects):Promise<any>
Defined in: Neurosity.ts:755
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:1157
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:369
Starts user session
await neurosity.login({
email: "...",
password: "..."
});
Parameters
credentials
Returns
Promise<void>
logout()
logout():
Promise<void>
Defined in: Neurosity.ts:382
Ends user session
await neurosity.logout();
// session has ended
Returns
Promise<void>
onAuthStateChanged()
onAuthStateChanged():
Observable<any>
Defined in: Neurosity.ts:405
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:624
Observes selected device
neurosity.onDeviceChange().subscribe(device => {
console.log(device);
});
Returns
Observable<DeviceInfo>
onUserClaimsChange()
onUserClaimsChange():
Observable<UserClaims>
Defined in: Neurosity.ts:507
Subscribe to user claims changes
neurosity.onUserClaimsChange().subscribe((userClaims) => {
console.log(userClaims);
});
Returns
Observable<UserClaims>
onUserDevicesChange()
onUserDevicesChange():
Observable<DeviceInfo[]>
Defined in: Neurosity.ts:484
Subscribe to user devices changes
neurosity.onUserDevicesChange().subscribe((devices) => {
console.log(devices);
});
Returns
Observable<DeviceInfo[]>
onUserExperiments()
onUserExperiments():
Observable<Experiment[]>
Defined in: Neurosity.ts:1630
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:1097
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:1183
Parameters
label
string
Name of metric properties to filter by
Returns
Observable<any>
Observable of predictions metric events
removeApiKey()
removeApiKey(
apiKeyId):Promise<RemoveApiKeyResponse>
Defined in: Neurosity.ts:1451
Removes API key
Parameters
apiKeyId
string
Returns
Promise<RemoveApiKeyResponse>
void
removeDevice()
removeDevice(
deviceId):Promise<void>
Defined in: Neurosity.ts:437
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:1601
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:550
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
autoSelectDeviceto false when instantiating theNeurosityclass. - 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:1068
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:987
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:1028
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
status()
status():
Observable<DeviceStatus>
Defined in: Neurosity.ts:1219
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:198
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:461
Transfer a device to the user's account
await neurosity.transferDevice({
deviceId: "[deviceId]",
newOwnerEmail: "[newOwnerEmail]"
});
Parameters
options
TransferDeviceOptions
Returns
Promise<void>