Link Search Menu Expand Document
Developer | Sahha

SDK

Learn how to use the Sahha SDK in your React Native app.


Table of contents
  1. Repository
  2. Installation
    1. React Native Project
    2. Android Project
    3. iOS Project
    4. React Native Module Import
  3. Configure
    1. Environment Settings
    2. (Android) Custom Notification Icon
    3. (Android) Custom Notification Settings
    4. (Android) Default Notification Settings
    5. Sensor Settings
    6. Sensor Data Settings
  4. Profile
    1. Authenticate
    2. Demographic
  5. Sensors
    1. Sensor Status
    2. Enable Sensors
    3. (iOS) Sleep Sensor - IMPORTANT INFO
    4. Open App Settings
    5. Post Sensor Data
  6. Analyze

Repository

You can browse the Sahha React Native SDK on Github.

React Native SDK [Github]


Installation

You will need to install the Sahha SDK into each platform project.


React Native Project

Install the Sahha NPM Package inside the root folder of your React Native project.

React Native SDK [NPM Registry]

Terminal

$ npm i sahha-react-native

Android Project

Add the required permissions to your Android project’s AndroidManifest.xml.

AndroidManifest.xml

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />

iOS Project

Step 1.) Install the Sahha SDK to your Xcode workspace via CocoaPods.

Run pod install inside your Xcode project root folder.

Terminal

$ pod install

Step 2.) Add NSMotionUsageDescription to your Xcode project’s Info.plist.

Step 3.) Add NSHealthShareUsageDescription to your Xcode project’s Info.plist.

Step 4.) Add NSHealthUpdateUsageDescription to your Xcode project’s Info.plist.

You will need to write a message explaining to the user why they should approve these permissions.

Info.plist

<key>NSMotionUsageDescription</key>
  <string>This app would like access to your motion activity for analysis.</string>
<key>NSHealthShareUsageDescription</key>
  <string>This app would like access to your health activity for analysis.</string>
<key>NSHealthUpdateUsageDescription</key>
  <string>This app would like access to your health activity for analysis.</string>

Step 5.) Add HealthKit entitlement to your Xcode project. Select your App Target in the Project panel, then Signing & Capabilities, then tap the + button, then select HealthKit from the list. You must also set Background Delivery to true.

App.entitlements

<dict>
 <key>com.apple.developer.healthkit</key>
  <true/>
 <key>com.apple.developer.healthkit.access</key>
  <array/>
 <key>com.apple.developer.healthkit.background-delivery</key>
  <true/>
</dict>

React Native Module Import

Import the Sahha module into any files inside your React Native project that use the SDK.

import Sahha from "sahha-react-native";

Configure

The Sahha SDK must be configured immediately on app launch. We suggest you configure Sahha inside your App’s export function.

You may pass an optional list of settings to the configure method.

Option A) Use Default Values

import Sahha, { SahhaEnvironment, SahhaSensor } from "sahha-react-native";

export default function App() {
  // Use default values
  const settings = {
    environment: SahhaEnvironment.development,
  };
  Sahha.configure(settings, (error: string, success: boolean) => {
    console.log(`Success: ${success}`);
    if (error) {
      console.error(`Error: ${error}`);
    }
  });
}

Option B) Use Custom Values

import Sahha, { SahhaEnvironment, SahhaSensor } from "sahha-react-native";

export default function App() {
  // Use custom values
  const settings = {
    environment: SahhaEnvironment.production,
    // Notification Settings are for Android only
    notificationSettings: {
      icon: "ic_test",
      title: "Test Title",
      shortDescription: "Test description.",
    },
    sensors: [SahhaSensor.sleep, SahhaSensor.pedometer],
    postSensorDataManually: true,
  };
  Sahha.configure(settings, (error: string, success: boolean) => {
    console.log(`Success: ${success}`);
    if (error) {
      console.error(`Error: ${error}`);
    }
  });
}

Environment Settings

The SahhaEnvironment determines if the SDK connects to the development or production server of the API. Setting this incorrectly will send data to the wrong server.

SahhaEnvironment Description
development For development and testing
production For submission to the App store
enum SahhaEnvironment { development, production }

(Android) Custom Notification Icon

You can add an optional custom notification icon to your Android app.

More information regarding supported image types can be found here: Create app icons with Image Asset Studio

Step 1) Open your project in Android Studio.

Step 2) With the app folder highlighted, selectFileNewImage Asset.

Step 3) Select Notification Icons for Icon Type, enter a Name, select Image as Asset Type and alter the Padding as desired.

Step 4) This page can typically be left as it is. Select Finish.


(Android) Custom Notification Settings

You can specify optional custom notificationSettings for your Android app. If notificationSettings are not specified, then the app will use the default notification settings.

const customNotificationSettings = {
  icon: "ic_test", // The name of the icon file as string
  title: "Custom Title",
  shortDescription: "Custom description",
};

(Android) Default Notification Settings

If custom notificationSettings are not specified for your Android app, then the app will use the default notification settings. If custom notificationSettings are only partially specified, then the app will use the default notification settings.The app will fill in the missing notification parameters with default values. E.g. if an icon and title are provided but a shortDescription is not, then the shortDescription will use the default value.

const defaultNotificationSettings = {
  icon: "ic_sahha_no_bg",
  title: "Analytics are running",
  shortDescription: "Swipe for options to hide this notification.",
};

Sensor Settings

You can specify which sensors for the Sahha SDK to use. To optimize your analysis result, we suggest enabling all sensors. Leave this value null to enable all sensors by default.

Some sensors are not available on all platforms.

SahhaSensor Description Android iOS
sleep For tracking sleep patterns
pedometer For tracking walking patterns
device For tracking device usage patterns X
enum SahhaSensor { sleep, pedometer, device }

Sensor Data Settings

If you would like to handle posting of sensor data to the Sahha API manually, set postSensorDataManually to true. You will then need to post sensor data to the Sahha API manually by calling postSensorData.

If you would like the Sahha SDK to handle posting of sensor data to the Sahha API automatically, set postSensorDataManually to false.

postSensorDataManually defaults to false.

postSensorDataManually Description
true You will post sensor data to the Sahha API manually by calling postSensorData
false The Sahha SDK will post sensor data to the Sahha API automatically

Profile

Each user of your app will be assigned a Sahha Profile for analyzation. This is not handled by the Sahha SDK. Please refer to the separate Sahha API documentation for steps to generate profiles and profile tokens.


Authenticate

The Sahha SDK must be authenticated in order to connect to the Sahha API. Do this once per user profile. Once the user is successfully authenticated, the SDK will take care of automatically refreshing expired tokens.

Sahha.authenticate(
  "PROFILE_TOKEN",
  "REFRESH_TOKEN",
  (error: string, success: boolean) => {
    console.log(`Success: ${success}`);
    if (error) {
      console.error(`Error: ${error}`);
    }
  }
);

Demographic

Each authenticated profile includes an optional demographic which can be used to increase the accuracy of analyzation. This data is not collected automatically. Your app can choose to GET or POST this demographic to the Sahha API.

All values are optional. String values are case insensitive (for example: 'us' and 'US' are equal and valid).

age : number

Age must be a valid number between 1 - 99.

gender : string

Gender must be a valid string from this list:

  • 'male'
  • 'female'
  • 'gender diverse'

country : string

Country must be a valid 2 character ISO string from this list:

ISO Country Codes

birthCountry : string

Birth Country must be a valid 2 character ISO string from this list:

ISO Country Codes

ethnicity : string

Any string value.

occupation : string

Any string value.

industry : string

Any string value.

incomeRange : string

Any string value.

education : string

Any string value.

relationship : string

Any string value.

locale : string

Any string value.

livingArrangement : string

Any string value.

birthDate : string

Birth Date must be a string in the format 'YYYY-MM-DD'. For example, '1990-05-20'.

MODEL

// All values are optional
const demographic = {
  age: 35, // number
  gender: "Female", // string, "Male", "Female", "Gender Diverse",
  country: "NZ", // ISO 2 digit code, i.e. "US", "UK", "AU", etc.
  birthCountry: "UK", // ISO 2 digit code, i.e. "US", "UK", "AU", etc.
  birthDate: "1990-05-20" // must be in format "YYYY-MM-DD", i.e. "1990-05-20"
}

// Post a JSON object
Sahha.postDemographic(demographic, (error: string, success: boolean) => {
  if error {
    console.error(`Error: $ {error}`);
  } else if success {
    console.log(`Success: $ {success}`);
  }
});

// Get a JSON object
Sahha.getDemographic((error: string, value: string) => {
  if error {
    console.error(`Error: $ {error}`);
  } else if value {
    console.log(`Value: $ {value}`);
  }
});

Sensors

The Sahha SDK acts as a bridge between your app and the device sensors.


Sensor Status

The sensors have multiple possible statuses.

export enum SahhaSensorStatus {
  pending = 0, /// Sensors pending User permission
  unavailable = 1, /// Sensors not supported by the User's device
  disabled = 2, /// Sensors disabled by the User
  enabled = 3, /// Sensors enabled by the User
}

You can check the current status of the sensors by calling getSensorStatus. This method is asynchronous and will return the updated SahhaSensorStatus in its callback.

import Sahha, { SahhaSensor, SahhaSensorStatus } from 'sahha-react-native';

...

Sahha.getSensorStatus((error: string, value: SahhaSensorStatus) => {
        if (error) {
          console.error(`Error: ${error}`);
        } else if (value) {
          console.log(`Sensor Status: ${value}`);
        }
      }
    );

Enable Sensors

Before the SDK can start collecting data, you will need to enable sensors by calling enableSensors. This method is asynchronous and will return the updated SahhaSensorStatus in its callback.

import Sahha, { SahhaSensor, SahhaSensorStatus } from 'sahha-react-native';

...

Sahha.enableSensors((error: string, value: SahhaSensorStatus) => {
                if (error) {
                  console.error(`Error: ${error}`);
                } else if (value) {
                  console.log(`Sensor Status: ${value}`);
                  setSensorStatus(value);
                }
              }
            );

(iOS) Sleep Sensor - IMPORTANT INFO

In order for the Sahha SDK to collect data from the sleep sensor, Sleep functionality must be enabled by your mobile user BEFORE calling Sahha.enableSensor(SahhaSensor.sleep).

Please read the official Apple documentation to help your users setup Sleep for iOS.

Sleep for iOS

We suggest checking if your user has seen the HealthKit permission screen before enabling the sleep sensor. If the status is pending, this is the perfect time to show your custom UI asking your user to setup Sleep in the Health App.

Sahha.getSensorStatus((error: string, value: SahhaSensorStatus) => {
  if (error) {
    console.error(`Error: ${error}`);
  } else if (value) {
    if (value == SahhaSensorStatus.pending) {
      // Show your custom UI asking your user to setup Sleep in the Health App
    }
  }
});

Open App Settings

It’s possible for your app user to disable a sensor. In this case, you must send the user to the app settings to manually enable the sensor.

Sahha.openAppSettings();

NOTICE for iOS: If the user enables / disables a sensor permission from the device settings menu while your app is in the background, the iOS system will force your app to terminate. This is intentional behavior and your app will need to be relaunched.


Post Sensor Data

By default, the Sahha SDK will post sensor data automatically. However, if you set postSensorDataManually to true, you will need to post sensor data manutally to the Sahha API by calling postSensorData at a regular interval of your choosing.

Sahha.postSensorData((error: string, success: boolean) => {
  console.log(`Success: ${success}`);
  if (error) {
    console.error(`Error: ${error}`);
  }
});

Analyze

You can analyze a user’s activities over a period of time and receive a mental health personalized report which you can display or action within your app. The default time period for an analysis is the previous 24 hours.

You can set (includeSourceData: true) if you would like to receive an array of the source data that was used to generate the analysis in the response. The default value is false.

// Analyze previous 24 Hours
// Leave date range empty
Sahha.analyze(
  {
    includeSourceData: true,
  },
  (error: string, value: string) => {
    if (error) {
      console.error(`Error: ${error}`);
    } else if (value) {
      console.log(`Value: ${value}`);
    }
  }
);

You can provide an optional data range if you would like to receive multiple analysis over a specific time period. The response will include an array of analysis for each 24 hour segment in that time period.

// Analyze previous 7 Days
// Add date range as milliseconds since epoch time
let endDate: Date = new Date();
let days = endDate.getDate() - 7;
var startDate = new Date();
startDate.setDate(days);
const settings = {
  startDate: startDate.getTime(),
  endDate: endDate.getTime(),
  includeSourceData: true,
};

Sahha.analyze(settings, (error: string, value: string) => {
  if (error) {
    console.error(`Error: ${error}`);
  } else if (value) {
    console.log(`Value: ${value}`);
  }
});

The response will be in JSON format. An example response includes these fields:

{
  "inferences": [
    {
      "createdAt": "2022-05-20T00:30:00+00:00",
      "predictionState": "not_depressed",
      "predictionSubState": "",
      "predictionRange": -1,
      "predictionConfidence": 0.8,
      "dataSource": ["sleep", "screenTime"]
    }
  ]
}

The analysis engine requires a minimum amount of device sensor data to be uploaded and processed before an analysis can be determined. If you call analyze for a new user profile, it’s possible for the response to be 204 No Content. This is not an error. You will need to wait and try again every 24 hours until an analysis is available.

// An analysis is not ready yet
// Try again in 24 hours
// Empty JSON
{}