@droobismit/sdk360 v0.0.27
Droobismit SDK360 Documentation
Installation
To install the SDK, use the following command:
npm install @droobismit/sdk360
To install all the peerdependencies , use the following command
npm i pnpm
pnpm install @droobismit/sdk360
Android Configuration
Set Minimum SDK Version
Update
minSdkVersion
in yourandroid/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"/>
<!-- make it remove so this permission is not required -->
<uses-permission android:name="android.permission.health.READ_HEART_RATE" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_BASAL_METABOLIC_RATE" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_BLOOD_GLUCOSE" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_BLOOD_PRESSURE" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_BODY_FAT" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_BODY_TEMPERATURE" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_BODY_WATER_MASS" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_BONE_MASS" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_DISTANCE" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_ELEVATION_GAINED" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_FLOORS_CLIMBED" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_HEART_RATE_VARIABILITY" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_HEIGHT" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_HYDRATION" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_LEAN_BODY_MASS" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_MENSTRUATION" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_NUTRITION" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_OXYGEN_SATURATION" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_POWER" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_RESPIRATORY_RATE" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_RESTING_HEART_RATE" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_SPEED" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_STEPS_CADENCE" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_SWIMMING_STROKES" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_VO2_MAX" tools:node="remove"/>
<uses-permission android:name="android.permission.health.READ_WEIGHT" tools:node="remove"/>
- 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>
- Update Proguard Rules
-keep class co.tryterra.** { *; }
iOS Configuration
1. Set Minimum Deployment
Update Minimum Deployment Target
for your app to iOS 13.0+.
2. 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>
3. 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>
4. Enable Background Modes
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>processing</string>
</array>
5. Add Background Task Scheduler
Add the following to Info.plist
:
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>co.tryterra.data.post.request</string>
</array>
6. Setup Background Delivery
Add this code to your AppDelegate’s didFinishLaunchingWithOptions
function:
[Terra setUpBackgroundDelivery];
7. Update AppDelegate.m/AppDelegate.mm File
Add the following import statement at the top of your AppDelegate.m/AppDelegate.mm file:
#import <TerraiOS/TerraiOS-Swift.h>
SDK Initialization
initialize the SDK for both Production and Testing environments.
Required Parameters
Parameter | Type | Description | Default |
---|---|---|---|
userId | string | User's unique ID. | Required |
apiKey | string | API key. | Required |
apiSecret | string | API secret. | Required |
language | string | Language for the SDK (en or ar ). | en |
fullName | string | User's full name. | Optional |
autoUpdateIntervalInMinutes | number | Interval (in minutes) to refresh APIs. | Optional |
handleInfoPoints | function | Function to handle Info Points click. | Optional |
handleRedeemPoints | function | Function to handle Redeem Points click. | Optional |
Production Environment Initialization
Use the init360
function to initialize the SDK in the Production environment.
Example
import { init360 } from '@droobismit/sdk360';
// Configuration for Production
const prodConfig = {
userId: 'yourUserId',
apiKey: 'yourApiKey',
apiSecret: 'yourApiSecret',
language: 'en', // or 'ar'
fullName: 'userFullName', // Optional
autoUpdateIntervalInMinutes: 5, // Optional
handleInfoPoints: handleInfoPoints, // Optional
handleRedeemPoints: handleRedeemPoints // Optional
};
// Initialize SDK in Production
init360(prodConfig)
.then(() => console.log('SDK initialized successfully in Production'))
.catch(error => console.error('SDK initialization failed in Production:', error));
Testing Environment Initialization
Use the init360QA
function to initialize the SDK in the Production environment.
Example
import { init360QA } from '@droobismit/sdk360';
// Configuration for Testing (QA)
const testConfig = {
userId: 'testUserId',
apiKey: 'testApiKey',
apiSecret: 'testApiSecret',
language: 'en', // or 'ar'
fullName: 'testUserFullName', // Optional
autoUpdateIntervalInMinutes: 5, // Optional
handleInfoPoints: handleInfoPoints, // Optional
handleRedeemPoints: handleRedeemPoints // Optional
};
// Initialize SDK in Testing
init360QA(testConfig)
.then(() => console.log('SDK initialized successfully in QA mode'))
.catch(error => console.error('SDK initialization failed in QA mode:', error));
Dashboard Screen
Use the HealthScreen
component to display the Droobismit360 plugin:
import { HealthScreen} from '@droobismit/sdk360';
const App = () => {
return <HealthScreen/>;
};
Device Connectivity
Check Device Connection
Verify if a device is connected for the user:
import { checkDeviceConnection } from '@droobismit/sdk360';
checkDeviceConnection()
.then(isConnected=> {
if (isConnected) {
console.log('Device is connected.');
} else {
console.log('No device connected.');
}
})
.catch(error => {
console.error('Error checking device connection:', 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);
});
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
Health Graph Screen
Use the HealthGraphView
component to display the Health Graph Screen:
import { HealthGraphView } from '@droobismit/sdk360';
const App = () => {
return <HealthGraphView />;
};
Quiz Screen
A React Native quiz module that displays daily health questions, handles user responses, shows correct/incorrect feedback with explanations, and rewards points for correct answers through a congratulatory popup.
Required Parameters
successPopupSubmitCallback :Optional callback that runs after user collects points from popup.
import { HealthThreeSixtyQuiz } from '@droobismit/sdk360';
const App = () => {
return <HealthThreeSixtyQuiz />;
};
Success Popup
A modal component that shows a congratulatory message with earned points and a collect button. Displays points in a stylized view with background image.
Required Parameters
showPopup
: Controls modal visibility (boolean)handleClose
: Called when modal is closed (function)handleSubmit
: Called when "Collect Points" is pressed (function)points
: Points to display in popup (number, default: 10)import { Popup } from '@droobismit/sdk360'; const App = () => { return <Popup />; };
Required Parameters
Points Management
The SDK provides several methods to manage and retrieve user scores and rankings.
Get User Points Details
Retrieve detailed points information for a specific activity type:
import { fetchUserPoints } from '@droobismit/sdk360';
try {
const scoreDetails = await fetchUserPoints({
startDate: '2024-03-01',
endDate: '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);
Get Leaderboard
Retrieve user rankings for a specified period:
import { fetchLeaderboard } from '@droobismit/sdk360';
try {
const leaderboard = await fetchLeaderboard({
startDate: '2024-03-01',
endDate: '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);
}
Get Points Summary
Retrieve a summary of user points for a specified period:
import { fetchPointsSummary } from '@droobismit/sdk360';
try {
const summary = await fetchPointsSummary({
startDate: '2024-03-01',
endDate: '2024-03-14'
});
console.log('Score summary:', summary);
} catch (error) {
console.error('Error:', error);
}
Get Reward Rules
Retrieve the current reward rules and conditions:
import { fetchRewardsRules } from '@droobismit/sdk360';
try {
const rules = await fetchRewardsRules();
console.log('Scoring rules:', rules);
} catch (error) {
console.error('Error:', error);
}
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'
If any validation fails, the SDK throws a HealthThreeSixtyError
with appropriate error code and message.
Health Stats Methods
Today's Health Data
Get today's health statistics:
import {
fetchTodaysSteps,
fetchTodaysCalories,
fetchTodaysSleep
} from '@droobismit/sdk360';
// Get today's step count
const stepsData = await fetchTodaysSteps();
// Returns: { date: "2024-03-14", value: 8547 }
// Get today's calories burned
const caloriesData = await fetchTodaysCalories();
// Returns: { date: "2024-03-14", value: 1850 }
// Get today's sleep duration
const sleepData = await fetchTodaysSleep();
// Returns: {
// date: "2024-03-14",
// value: 27000, // seconds
// formatted: "07:30" // HH:MM format
// }
Historical Health Records
Get health data for a specific date range:
import {
fetchStepsRecords,
fetchCaloriesRecords,
fetchSleepRecords
} from '@droobismit/sdk360';
// Get steps data for a date range
const stepsData = await fetchStepsRecords("2024-03-01", "2024-03-07");
// Returns: [
// { date: "2024-03-01", value: 9876 },
// { date: "2024-03-02", value: 10234 },
// ...
// ]
// Get calories data for a date range
const caloriesData = await fetchCaloriesRecords("2024-03-01", "2024-03-07");
// Returns: [
// { date: "2024-03-01", value: 1950 },
// { date: "2024-03-02", value: 2100 },
// ...
// ]
// Get sleep data for a date range
const sleepData = await fetchSleepRecords("2024-03-01", "2024-03-07");
// Returns: [
// {
// date: "2024-03-01",
// value: 27000, // seconds
// formatted: "07:30" // HH:MM format
// },
// ...
// ]
Parameters
For historical records methods:
startDate
: Start date in YYYY-MM-DD formatendDate
: End date in YYYY-MM-DD format
Error Handling
try {
const stepsData = await fetchTodaysSteps();
} catch (error) {
switch (error.code) {
case 7400: // DATA_ERROR
console.error('Failed to fetch health data');
break;
case 7501: // MISSING_PARAMETER
console.error('Missing required parameters');
break;
case 7603: // USER_NOT_INITIALIZED
console.error('User not initialized');
break;
default:
console.error('An unexpected error occurred:', error.message);
}
}
Sync Health Data
Manually sync health data from SDK providers (Apple Health, Google Fit, etc.):
import { syncHealthData } from '@droobismit/sdk360';
try {
// Sync with default dates (today)
const syncResults = await syncHealthData();
// Or sync with specific date range (DD-MM-YYYY format)
const syncResults = await syncHealthData({
startDate: '01-12-2024',
endDate: '31-12-2024'
});
console.log('Sync results:', syncResults);
// Returns: {
// provider: "APPLE", // or other SDK provider
// type: "SDK",
// syncTime: "2024-03-14T10:30:00.000Z",
// dateRange: {
// startDate: "2024-12-01T00:00:00.000Z",
// endDate: "2024-12-31T23:59:59.999Z"
// },
// status:"success"
// }
} catch (error) {
switch (error.code) {
case 7701: // NO_DEVICE_CONNECTED
console.error('No connected devices found');
break;
case 7702: // INVALID_PROVIDER
console.error('Provider not supported for manual sync');
break;
case 7703: // SYNC_FAILED
console.error('Health data synchronization failed');
break;
default:
console.error('An unexpected error occurred:', error.message);
}
}
Parameters
startDate
(optional): Start date in DD-MM-YYYY format. Defaults to start of current dayendDate
(optional): End date in DD-MM-YYYY format. Defaults to current time
Notes
- All methods require the SDK to be initialized with
init360()
orinit360QA()
first - Manual Health Sync works with SDK providers (Apple Health, Google Fit, Health Connect, Samsung Health)
- API providers (Garmin, Fitbit, etc.) are not supported for manual sync
- Sleep duration is provided in both seconds (
value
) and formatted HH:MM string (formatted
) - Delete node_modules inside sdk360 if error comes from react-native(to automate add to the scripts in package.json - "postinstall": "rd /s /q node_modules" (windows OS) , "postinstall": "rm -rf node_modules/sdk360/node_modules" (Mac OS)
Complete Example with State Management
Here's a complete example showing how to initialize the SDK with state management and render health components:
import React, {useEffect, useState} from 'react';
import {init360QA} from '@droobismit/sdk360';
import {HealthScreen, DevicesList} from '@droobismit/sdk360';
import { View } from 'react-native';
const App = () => {
const [isInit360Done, setIsInit360Done] = useState(false);
// Configuration for Testing (QA)
const testConfig = {
userId: 'YOUR_USER_ID',
apiKey: 'YOUR_API_KEY',
apiSecret: 'YOUR_API_SECRET',
fullName: 'User Name', // Optional
autoUpdateIntervalInMinutes: 5, // Optional
handleInfoPoints: '', // Optional
handleRedeemPoints: '', // Optional
};
useEffect(() => {
init360(testConfig);
}, []);
const init360 = async config => {
try {
await init360QA(config);
setIsInit360Done(true);
} catch (error) {
console.error('Error initializing 360QA:', error);
}
};
return isInit360Done ? <HealthScreen /> : <View />;
};
export default App;
This example demonstrates:
- State management for SDK initialization
- Proper error handling
- Conditional rendering based on initialization status
- Integration with health components
5 months ago
5 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
7 months ago
7 months ago
7 months ago
7 months ago
8 months ago
8 months ago
8 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago