0.0.33 • Published 1 year ago

@saikrishnakotagiri/testsdk v0.0.33

Weekly downloads
-
License
ISC
Repository
gitlab
Last release
1 year ago

HealthThreeSixty SDK Documentation

Installation

To install the SDK, use the following command:

npm install sdk360

Note: Update scripts in your package.json

Mac OS
"postinstall": "rm -rf node_modules/sdk360/node_modules"
Windows OS 
"postinstall": "rd /s /q node_modules/sdk360/node_modules"

Android Configuration

  • Set Minimum SDK Version Update minSdkVersion in your android/build.gradle to 28 or above.
  • Add Permissions to AndroidManifest.xml Navigate to android/app/src/main/AndroidManifest.xml and add the following permissions:
   <!-- Essential Health Data Permissions -->
    <uses-permission android:name="android.permission.health.READ_STEPS"/>
    <uses-permission android:name="android.permission.health.READ_SLEEP"/>
    <uses-permission android:name="android.permission.health.READ_EXERCISE"/>
    <uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED"/>
    <uses-permission android:name="android.permission.health.READ_TOTAL_CALORIES_BURNED"/>
  1. Add Privacy Policy Intent Filters

Include these under the MainActivity in AndroidManifest.xml:

In AndroidManifest.xml include the following under the Activity you wish to display to the user when user wants to see your app's privacy policy:

Add them to the MainActivity activity so both will run when the user launches your app

<intent-filter>
    <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
</intent-filter>
<intent-filter>
    <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
    <category android:name="android.intent.category.HEALTH_PERMISSIONS" />
</intent-filter>
  1. Update Proguard Rules
-keep class co.tryterra.** { *; } 

iOS Configuration

1. Enable HealthKit

  • Add HealthKit as a capability to your project.
  • Enable Background Delivery in the HealthKit entitlements.
<dict>
    <key>com.apple.developer.healthkit</key>
    <true/>
    <key>com.apple.developer.healthkit.background-delivery</key>
    <true/>
</dict>

2. Add Privacy Keys

Go to Info.plist and include the following:

  • Go to main app folder > Click on the icon below TARGETS on the sidebar > click on Info on menu bar > go to Custom iOS Target Properties > hover over any key and click + button > add Privacy - Health Share Usage Description, once you add , you info.plist wil have these , you can change the string as per your requirement which will be visible for user
<key>NSHealthShareUsageDescription</key>
<string>We require access to your health data to provide personalized insights.</string>
<key>NSHealthUpdateUsageDescription</key>
<string>We need to update your health data to ensure accuracy.</string>

3. Enable Background Modes

	<key>UIBackgroundModes</key>
	<array>
		<string>fetch</string>
		<string>processing</string>
	</array>

4. Add Background Task Scheduler

Add the following to Info.plist:

<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>co.tryterra.data.post.request</string>
</array>

5. Setup Background Delivery

Add this code to your AppDelegate’s didFinishLaunchingWithOptions function:

  [Terra setUpBackgroundDelivery];

SDK Initialization

To initialize the SDK, provide the required parameters as shown below.

Required Parameters

  • userId: User's unique ID
  • apiKey: API key
  • apiSecret: API secret
  • language (Optional): en (default) or ar
  • fullName (Optional): User's full name

Initialization Example

import { initializeHealthThreeSixty } from '@droobismit/sdk360';

const config = {
  userId: 'yourUserId',
  apiKey: 'yourApiKey',
  apiSecret: 'yourApiSecret',
  language: 'en',
  fullName: 'userFullName',
};

initializeHealthThreeSixty(config)
  .then(() => console.log('SDK initialized successfully'))
  .catch(error => console.error('SDK initialization failed:', error));

Device Connectivity

Check Device Connection

Verify if a device is connected for the user:

import { checkDeviceConnection } from '@droobismit/sdk360';

checkDeviceConnection()
  .then(device=> {
    if (device.isConnected) {
      console.log('Device is connected.');
    } else {
      console.log('No device connected.');
    }
  })
  .catch(error => {
    console.error('Error checking device connection:', error);
  });
  
  
      // Response when user is not initialized:
      // {
      //   isConnected: false,
      //   error: 'User not initialized'
      // }
      
      
     // Response when successful:
    // {
    //   isConnected: true/false,
    //   error: null
    // }
    
        // Response when error occurs:
    // {
    //   isConnected: false,
    //   error: "Error message from the caught error"
    // }

Get Detailed Device Status

Retrieve detailed status of connected devices:

import { getDetailedDeviceStatus } from '@droobismit/sdk360';

getDetailedDeviceStatus()
  .then(response => {
      console.log('response ',response );
  })
  .catch(error => {
    console.error('Error checking device details :', error);
  });
  
  
        // Response when user is not initialized:
      // {
      //   isConnected: false,
      //   connectedDevices: []
      //   error: 'User not initialized'
      // }
      
      
    // {
    //   isConnected: true/false,
    //   connectedDevices: [connected device objects],
    //   error: null
    // }
    
        // Response when error occurs:
    // {
    //   isConnected: false,
    //   connectedDevices: [],
    //   totalDevices: 0,
    //   error: "Error message from the caught error"

Device List Screen

Use the DevicesList component to display the device list component to connect devices:

import { DevicesList } from '@droobismit/sdk360';

const App = () => {
  return <DevicesList />;
};

HealthContentLibrary SDK Documentation

Content Library Screen

Use the HealthContentLibrary component to display the content library screen:

import { HealthContentLibrary } from '@droobismit/sdk360';

const App = () => {
  return <HealthContentLibrary />;
};

Health Graph Card SDK Documentation

Content Library Screen

Use the HealthGraph component to display the content library screen:

import { HealthGraph } from '@droobismit/sdk360';

const App = () => {
  return <HealthGraph />;
};

Score Management

The SDK provides several methods to manage and retrieve user scores and rankings.

Get User Score Details

Retrieve detailed score information for a specific activity type:

import { getUserScoreDetails } from '@droobismit/sdk360';

try {
  const scoreDetails = await getUserScoreDetails({
    fromDate: '2024-03-01',
    toDate: '2024-03-14',
    type: 'STEP',    // Available types: 'STEP', 'SLEEP', 'CALORIES', 'QUIZ'
    page: 1,         // Optional, defaults to 1
    size: 10         // Optional, defaults to 10
  });
  
  console.log('Score details:', scoreDetails);
} catch (error) {
  console.error('Error:', error);
  // Error will include:
  // - error.code: Error code (e.g., '7001' for SCORE_FETCH_FAILED)
  // - error.message: Detailed error message
  // - error.timestamp: When the error occurred
}

// Response structure:
// {
//   content: [{
//     date: "2024-03-01",
//     score: 5,
//     type: "STEP",
//     value: 8000
//   }],
//   page: 1,
//   size: 10,
//   totalElements: 14,
//   totalPages: 2,
//   last: false
// }

Get Leaderboard

Retrieve user rankings for a specified period:

import { getLeaderboard } from '@droobismit/sdk360';

try {
  const leaderboard = await getLeaderboard({
    fromDate: '2024-03-01',
    toDate: '2024-03-14',
    page: 1,    // Optional, defaults to 1
    size: 10    // Optional, defaults to 10
  });
  
  console.log('Leaderboard:', leaderboard);
} catch (error) {
  console.error('Error:', error);
}

// Response structure:
// {
//   content: [{
//     fullName: "John Doe",
//     userId: "user123",
//     rank: 1,
//     totalScore: 65
//   }],
//   page: 1,
//   size: 10,
//   totalElements: 4,
//   totalPages: 1,
//   last: true
// }

Get Score Summary

Retrieve a summary of user scores for a specified period:

import { getScoreSummary } from '@droobismit/sdk360';

try {
  const summary = await getScoreSummary({
    fromDate: '2024-03-01',
    toDate: '2024-03-14'
  });
  
  console.log('Score summary:', summary);
} catch (error) {
  console.error('Error:', error);
}

// Response structure:
// {
//   "sleep": 0,
//   "step": 0,
//   "quiz": 0,
//   "calories": 0,
//   "total": 0
// }

Get Scoring Rules

Retrieve the current scoring rules and conditions:

import { getScoringRules } from '@droobismit/sdk360';

try {
  const rules = await getScoringRules();
  console.log('Scoring rules:', rules);
} catch (error) {
  console.error('Error:', error);
}

Error Handling

All score-related methods use standardized error handling with specific error codes:

try {
  const result = await getUserScoreDetails({
    fromDate: '2024-03-01',
    toDate: '2024-03-14',
    type: 'STEP'
  });
} catch (error) {
  // Error codes for score-related operations
  switch (error.code) {
    case '7001': // SCORE_FETCH_FAILED
      console.error('Failed to fetch score details');
      break;
    case '7002': // LEADERBOARD_FETCH_FAILED
      console.error('Failed to fetch leaderboard');
      break;
    case '7003': // RULES_FETCH_FAILED
      console.error('Failed to fetch scoring rules');
      break;
    case '4001': // INVALID_PARAMETERS
      console.error('Invalid parameters provided');
      break;
    case '4002': // INVALID_DATE_FORMAT
      console.error('Invalid date format');
      break;
    case '4003': // INVALID_TYPE
      console.error('Invalid activity type');
      break;
    case '6002': // USER_NOT_INITIALIZED
      console.error('User not initialized');
      break;
    default:
      console.error('An unexpected error occurred:', error.message);
  }
}

Parameter Validation

The SDK performs strict validation on all parameters:

  • Dates: Must be in 'YYYY-MM-DD' format
  • Activity Types: Must be one of: 'STEP', 'SLEEP', 'CALORIES', 'QUIZ'
  • Page and Size: Must be positive numbers
  • Date Range: Start date must be before or equal to end date

If any validation fails, the SDK throws a DroobiSmit360Error with appropriate error code and message.