Visualizing Focus with Neurosity's Notion and AWS Amplify
Tags: neurosity, aws, amplify, javascript
Published: 2020-01-16 16:36:44

---
title: Visualizing Focus with Neurosity's Notion and AWS Amplify
published: true
description: Measuring focus with brainwaves may seem like something out of a sci-fi movie, but I assure you this is no movie. In this post I'll show how I used AWS Amplify to track my focus.
tags: neurosity, aws, amplify, javascript
---

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/n1ihbioag6hpsiuk46ve.jpg)

**That brain of mine is something more than merely mortal, as time will show.** - *Ada Lovelace*

Right now, billions of people around the world are tracking their health with some sort of device. Heart rate, sleeping patterns, exercise, steps taken, calories in and out, all kinds of metrics are recorded to help individuals better understand what their body is doing.

However, none of this data can help you understand what's going on in your brain. It's unfortunately difficult to monitor your brain activity, this is where [Neurosity](https://neurosity.co/) comes in. I was lucky enough to be selected to try out the first edition of their headset, the Notion.

The Notion reads your brainwaves and allows you to collection data about things like your calmness or focus, as well as train models to execute certain commands when it encounters the corresponding brainwaves. Essentially turning thought into action.

I really like data-driven health and it's been a really big part of my life over the last few years. There is something about graphing the body that really appeals to me, so when I discovered Neurosity I was extremely excited about being selected for the first round of devices released.

The Notion has APIs that allow you to interact with your device and receive all the data from it. I thought a good first experiment would be to wear the Notion while I'm at my computer working and try to figure out when I'm most focused. This seemed like a good first run as I plan to do a lot of experiments around focus and how different factors can affect it.

In this post I'll talk about setting up and recording the data, and in the next post I'll cover reading the data and visualizing it!

## Creating the Project

Because I want to visualize this data I decided to spin up a new React app using [`create-react-app`](https://github.com/facebook/create-react-app). I also knew that I would need to store the data from the headset so that I could read it back out later when I wanted to visualize it. For that part I set up a GraphQL API with [Amplify](I set up a GraphQL API with [Amplify](https://aws-amplify.github.io/) and [AWS AppSync](https://aws.amazon.com/appsync/) via the [Amplify CLI](https://aws-amplify.github.io/docs/cli-toolchain/quickstart?sdk=js).  

## Setting Up the Infrastructure

To record the data :

To set up my app and GraphQL API, I ran the following commands:

```bash
npx create-react-app visualizing-focus
amplify init
amplify add api
```

I also created a DynamoDB table by using the `@model` directive in my GraphQL schema during API set up, like so:

```graphql
type FocusDataPoint @model {
  id: ID!
  timestamp: String!
  value: Float!
}
```

Not only is a table created, but all the queries and mutations needed to perform CRUD operations on this data point were created in AppSync for me and the CLI generated those queries, mutations, and subscriptions for me for use in my app and Node script.

> For more on creating GraphQL APIs with Amplify and AppSync, check out the [docs](https://aws-amplify.github.io/docs/js/api#automated-configuration-with-cli)!

Once I had the infrastructure in place it was time to create a script to run during the day to record the data coming out of the Notion.

## Creating the Tracking Script

All that I needed to start tracking my focus was a small NodeJS script that would listen for the focus events coming out of my Notion headset and send them to AppSync. It took less than 70 lines of code in total.

```javascript
// in src/track-focus.js

// Get deviceId, email, and password for Notion login
require("dotenv").config();

// polyfill fetch for node env
const fetch = require("node-fetch");
global.fetch = fetch;
global.navigator = {};

const { Notion } = require("@neurosity/notion");
const AWSAppSyncClient = require("aws-appsync").default;
const gql = require("graphql-tag");

// get all config
const amplifyConfig = require("./aws-exports").default;
const deviceId = process.env.DEVICE_ID || "";
const email = process.env.EMAIL || "";
const password = process.env.PASSWORD || "";

// set up Notion
const mind = new Notion({
  deviceId
});

// set up client to send data to AppSync
const client = new AWSAppSyncClient({
  disableOffline: true,
  url: amplifyConfig.aws_appsync_graphqlEndpoint,
  region: amplifyConfig.aws_appsync_region,
  auth: {
    type: amplifyConfig.aws_appsync_authenticationType,
    apiKey: amplifyConfig.aws_appsync_apiKey
  }
});

// copy the mutation out of the generated graphql operations created by Amplify CLI
const mutation = gql(`mutation CreateFocusDataPoint($input: CreateFocusDataPointInput!) {
    createFocusDataPoint(input: $input) {
      id
      value
      timestamp
    }
  }
`);

client.hydrated().then(async () => {
  // login to Neurosity
  await mind.login({ email, password });

  // listen for focus events
  mind.focus().subscribe(async focus => {
    // { probability: 0.51, metric: "awareness", label: "focus", timestamp:  1569961321102 }
    console.log(focus);
    try {
      const result = await client.mutate({
        mutation,
        variables: {
          input: {
            value: focus.probability,
            timestamp: focus.timestamp
          }
        }
      });

      console.log(result);
    } catch (error) {
      console.log(error);
    }
  });
});
```

First I set up the API client and Notion SDK and then set up the listener for `focus` events coming from the headset. Now whenever I sit down to work, I can turn on the Notion, run this script, and all the data will be collected for me and stored in the cloud.

We can verify that the data is being stored by running a query in the AppSync console.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/zsaiirt133gztkm7zvos.png)

Now all that's left is to record some data! Stay tuned for the second part of this series where I build out the frontend and data visualizations!