Cordova Framework Wrapper

validic_cordova_1.13.0

📘

Legacy (v1) vs Inform (v2)

The same Validic Mobile SDKs are used by both Legacy (v1) and Inform (v2) API customers. To make the documentation easier to access, the Mobile Getting Started Guides and class documentation are hosted on our Inform (v2) documentation site.

The API documentation, however, is different between Legacy (v1) and Inform (v2). If you are an Inform (v2) API customer, you must use the Inform API documentation.

If you are a Legacy (v1) API customer, be sure to go back to the Legacy API documentation.

Requirements


To get started, download the Cordova framework from the Validic Mobile portal.

This plugin provides a bridge between a Cordova based application and native Validic Mobile libraries. The native libraries are required for use of this plugin.

Plugin requirements:

  • Cordova 6.3 and above.
    cordova-android >= 7.0.0
    cordova-ios >= 5.1
  • Specific supported phones, peripherals, and operating system versions are documented as part of the native libraries.

At minimum, the validic-cordova-session plugin is required to be installed. The following remaining plugins may be used as desired for the specific features you wish to implement in your app:

  • Bluetooth: validic-cordova-ble
  • Google Fit: validic-cordova-googlefit
  • Apple Health: validic-cordova-healthkit
  • VitalSnap: validic-cordova-ocr
  • Samsung Health: validic-cordova-shealth

Migrate from 1.11.0 or lower

Starting with Cordova wrapper version 1.12.x, the Validic Cordova plugin has been split into separate plugins for each of its components. Each Validic Cordova component is now bundled with a version of the Validic Mobile Native SDK for iOS and Android.

To migrate from a Cordova wrapper version of 1.11.0 or lower to 1.12.x:

  1. Remove previous version of plugin cordova: plugin remove "com.validic.mobile" or cordova plugin remove "com.validic.mobile.aggregator"
  • Remove any previously manually added references to previous versions of the Validic Framework
  1. Add new versions of plugin from local npm packages:
  • cordova plugin add validic-cordova-session-1.12.x.tgz
  • cordova plugin add validic-cordova-ble-1.12.x.tgz
  • cordova plugin add validic-cordova-healthkit-1.12.x.tgz
  • cordova plugin add validic-cordova-shealth-1.12.x.tgz --variable SHEALTH_DEPENDENCY=<path to samsung health aar>
  • cordova plugin add validic-cordova-ocr-1.12.x.tgz
  1. Re-add the previous platforms:
cordova platform rm ios
cordova platform rm android 
cordova platform add ios
cordova platform add android

Adding plugin to Cordova project

If you're just getting started with the Cordova wrapper, creating a Cordova project using the ValidicMobile plugin involves the following steps. Additional Cordova commands and options are available. Consult Cordova documentation for additional information.

  1. Install Cordova.
  2. Create Cordova project. cordova create <path> [id name]. id and name are optional. Additional Cordova options are available.
  3. Change directory to the root of the newly created project cd <path>
  4. Add the desired platforms to the project, cordova platform add [ios | android] --save
  5. Add the ValidicMobile plugin(s) to the cordova project, cordova plugin add <path to unzipped plugin> --save.

Upgrading plugin

To upgrade the plugin to a new version, the old version of the plugin should be removed and the new version added.

-cordova plugin remove <plugin_to_remote>
-cordova plugin add <path_to_plugin>

Android

Samsung Health

In order to use Samsung Health with ValidicMobile a valid copy of the Samsung Health SDK must be provided by the developer. This can be downloaded from the Samsung Health developer portal: Samsung Samsung Health Developer.

Deprecated in 1.12. Add plugin with SHEALTH_DEPENDENCY variable to install the shealth dependency
Place the samsung-digital-health-***.jar in the same plugin/lib/samsung folder next to the validicmobile-release.aar described in the Plugin Installation section. If the plugin has previously been added to the project before adding the samsung-digital-health***.jar to the plugin/lib/ folder the plugin must be removed and readded to the project to pull the Samsung Health SDK into the project.

iOS

HealthKit

To enable use of HealthKit in the app, within the build settings of your target, select the ‘Capabilities’ tab and enable ‘HealthKit’.

If HealthKit is not enabled, an error is reported in the console log on app launch but will not report a error during build.

Bluetooth

Passive Bluetooth support requires enabling background mode support. To enable it:

  1. Edit info.plist
  2. Create new top level entry, Required background modes.
  3. Select App communicates using CoreBluetooth as the value.

Info.plist configuration

iOS requires usage descriptions to be declared in project’s Info.plist for usage of the camera, Bluetooth and to access and update health data.

The plugins create these entries in the Info.plist when the iOS platform is added to the project. Custom descriptions can be specified when the plugin is added to the project by specifying values for the following variables in the cordova plugin add CLI command:

  • validic-cordova-ocr
    • CAMERA_USAGE_DESCRIPTION for NSCameraUsageDescription
  • validic-cordova-healthkit
    • HEALTH_SHARE_USAGE_DESCRIPTION for NSHealthShareUsageDescription
    • HEALTH_UPDATE_USAGE_DESCRIPTION for NSHealthUpdateUsageDescription
  • validic-cordova-ble
    • BLUETOOTH_USAGE_DESCRIPTION for NSBluetoothPeripheralUsageDescription
    • BLUETOOTH_ALWAYS_USAGE_DESCRIPTION for NSBluetoothAlwaysUsageDescription

The extended command to add the plugin is of the following form:

cordova plugin add <path to unzipped plugin> --variable CAMERA_USAGE_DESCRIPTION=<usage message> --variable HEALTH_SHARE_USAGE_DESCRIPTION=<usage message> --variable HEALTH_UPDATE_USAGE_DESCRIPTION=<usage message> --variable BLUETOOTH_USAGE_DESCRIPTION=<usage message>

BLUETOOTH_ALWAYS_USAGE_DESCRIPTION=

If you don’t pass a variable on plugin installation, the plugin provides a generic default message.

Session


Provision a User

In order to use the Validic Mobile Library, you will need a valid organization id and valid user credentials.

If you do not already have an organization id, you will need to first apply for one.

After your organization is set up, you will need a Validic user id and access token.

Validic user can be provisioned using the Validic API, documentation is available for both Legacy API (V1) and Inform API (V2) APIs. The credentials needed are a Validic user ID, an organization ID and a user access token. The user access token value you provide to the SDK is the "user access token" value if you use the Legacy (V1) API. The user access token value you provide to the SDK is the "mobile token" value if you use the Inform (V2) API.

Record types

The Validic Mobile library supports the following record types:

  • Biometrics - comprised of a user’s biometric health data such as blood pressure, cholesterol, heart rate, and blood and hormone levels.
  • Diabetes - comprised of a user’s blood glucose and hormone levels related to diabetes treatment and management.
  • Fitness - comprised of a user’s activities that are undertaken with the express purpose of exercising. These activities have a defined duration (time, distance, elevation, etc.)
  • Nutrition - comprised of a user’s activities related to calorie intake and consumption and nutritional information (such as fat, protein, carbohydrates, sodium, etc.)
  • Routine - comprised of a user’s activities that occur regularly throughout the day, without the specific goal of exercise, for example calories burned and consumed, steps taken, stairs climbed. These activities are aggregated throughout the day.
  • Sleep - comprised of a user’s measurements related to the length of time spent in various sleep cycles, as well as number of times awakened during the night.
  • Weight - comprised of a user’s weight and body mass.

Record Identifiers

The Validic Mobile SDK uses log_id (for the Inform/V2 API) or activity_id (for the Legacy/V1 API) as the unique identifier for a given record. These IDs are created by the mobile SDK before submission to the server.

The Validic server also assigns an id (for the Inform/V2 API) or _id (for the Legacy/V1 API) for each unique record. It is recommended to use the server-side id / _id to identify and/or de-duplicate records post-submission.

Manage a Session

Overview

The Session stores a user, their current HealthKit, Google Fit, or Samsung Health subscriptions and all pending record uploads. This data is persisted between app launches but is deleted if the ValidicMobile.Session.endSession() function is called.

A new Session is started by passing previously provisioned Validic user credentials to the startSession function.

ValidicMobile.Session.startSession(user.USER_ID, user.ORGANIZATION_ID, user.USER_ACCESS_TOKEN);

The supplied credentials are not validated when the session is created. Records will fail to upload if invalid credentials have been provided. Credentials are stored persistently. To change credentials, call:

ValidicMobile.Session.endSession();

or uninstall the app. When a new session is created, pending record uploads and subscriptions are reset. For this reason, a new session should only be created if a session is not already active.

The app can be informed of record upload success and failure by registering callbacks using:

ValidicMobile.Session.setSessionListener(logSuccess, logFail)

The success callback is invoked after each record has successfully uploaded to the server. Fail is invoked if a record upload fails. Setting the session listeners is optional.

Registration of listeners is typically done during app initialization to catch events for record uploads which may occur upon app restart.

Session initialization is typically done when your users log in to your (non-Validic) system, and retrieve your user’s Validic authentication information as stored on your system. The Validic authentication information for your user is then used with the Validic Mobile Library to initialize your Session.

The following example starts a session if a session is not already active and registers session listeners.

var user = {
    "USER_ID": "replace with userid",
    "USER_ACCESS_TOKEN": "replace with access token",
    "ORGANIZATION_ID": "replace with organization id"
};
var logSuccess = function (object) {
    console.log(object);
};
var logFail = function (object) {
    console.log(object)
};
ValidicMobile.Session.setSessionListener(logSuccess, logFail);
ValidicMobile.Session.isSessionActive(function (response) {
    if (!response.isActive) {
        // Only do this if your user is logging in
        ValidicMobile.Session.startSession(user.USER_ID, user.ORGANIZATION_ID, user.USER_ACCESS_TOKEN);
    }
});

Logging

Logging can be enabled and messages will be logged to the javascript console. All logs from the Validic SDK begin with ValidicLog#.

ValidicMobile.Logger.enable();

to disable:

ValidicMobile.Logger.disable();

Bluetooth


Requirements

  • Cordova 6.3 and above
  • cordova-android >= 7.0.0
  • cordova-ios >= 4.4
  • validic-cordova-session plugin
  • validic-cordova-ble plugin

Peripherals

Peripheral objects contain information regarding supported Bluetooth peripherals. Several function calls are provided to retrieve one or more peripherals.

A peripheral object contains various properties used during the reading and pairing process:

  • Manufacturer - Manufacturer name.
  • Model - Model number.
  • PairingInstruction - Text telling the user how to pair the peripheral, if the peripheral requires pairing.
  • Instruction - Text telling the user how to initialize the reading process with the peripheral.
  • ReadingInstruction - Text telling the user what to do during the reading process.
  • PeripheralImageURL - URL for an image of the peripheral.
  • RequiresPairing - Boolean indicating if the peripheral requires pairing.
  • ID - Peripheral identifier.

Supported Peripherals

To retrieve an array of supported peripherals:

ValidicMobile.BLE.getSupportedPeripherals(function (response) {
    var peripherals = response.peripherals;
};

To retrieve a specific peripheral:

ValidicMobile.BLE.getPeripheral(3, function (response) {
    var peripheral = response.peripheral;
}, function (err) {
    alert(err.error);
});

Peripherals are grouped by type, such as thermometer, glucose, scale, etc. To retrieve an array of peripherals of a specific type, use the ValidicMobile.BLE.PeripheralType constants and invoke the following function:

ValidicMobile.BLE.getPeripheralsOfType(ValidicMobile.PeripheralType.THERMOMETER, function (response) {
    app.peripheral = response.peripheral;
}, function (err) {
    alert(err.error);
});

Permissions

The following permissions must be in the consuming application's mergedAndroidManifest.xml:

  • android.permission.BLUETOOTH
  • android.permission.BLUETOOTH_ADMIN
  • android.permission.FOREGROUND_SERVICE
  • android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION

Android 10

  • Starting with Android 10, android.permission.ACCESS_FINE_LOCATION is required by the OS.
  • android.permission.ACCESS_BACKGROUND_LOCATION must be requested along with android.permission.ACCESS_FINE_LOCATION in order for Passive Bluetooth reading to succeed if the device is in DOZE mode for devices running api 26 or later

Android 11

  • Starting with Android 11, on devices running api >= Android 11 (api 30), the android.permission.ACCESS_BACKGROUND_LOCATION must be granted manually by end user's in the application settings. To navigate to the application settings use the following code
                       Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                                                Uri.parse("package:" + getApplication().getPackageName())); intent.addCategory(Intent.CATEGORY_DEFAULT);                            startActivityForResult(intent, BLE_BACKGROUND_CODE);

Pair

Certain peripherals require pairing with the mobile device before a reading can be taken. You can check the RequiresPairing property on the peripheral object to know if it must be paired. To begin a pairing process, the PairingInstruction property of a Bluetooth peripheral object can be displayed to the user. To start the pairing process, call:

ValidicMobile.BLE.pair(peripheralID, successCallback(), failCallback())

The pairing process can generate multiple callbacks. A response object is passed to the successCallback which includes an event property and a payload containing information specific to the request.

var success = function (response) {
    console.log('Successful pair with peripheral ID:' + response.payload.peripheralID);
};
var fail = function(response) {
    console.log('Error: ' + response.payload.error);
};
ValidicMobile.BLE.pair(15, success, fail);

Read

When the BLE read process is first initiated, the user should be presented with instructions from the peripheral object using the Instruction property.

When the ValidicMobile.BLE.EventName.ON_READY_TO_READ event is received, the user should be presented with instructions from the peripheral object using the ReadingInstruction property.

Assuming event listeners have been registered as shown below, the BLE read process is initiated as follows:

ValidicMobile.BLE.read(peripheral.ID);

The ValidicMobile.BLE.EventName.ON_READ_SUCCESS event is posted when the read successfully completes and is passed an object with a records property containing an array of records read via BLE.

Some peripherals return a single record while others may return multiple records.

Handle Events

Events are generated for the possible responses from bluetooth pair and read requests. These events are posted from the window. Event names are defined within the ValidicMobile.BLE.EventName set of constants.

Event listeners for the pairing events can be registered as follows:

window.addEventListener(ValidicMobile.BLE.EventName.ON_PAIR_SUCCESS, this.onBLEPairingSuccess);
window.addEventListener(ValidicMobile.BLE.EventName.ON_PAIR_FAIL, this.onBLEPairingFailed);
window.addEventListener(ValidicMobile.BLE.EventName.ON_PAIR_START, this.onBLEPairingStarted);

Note: The ValidicMobile.BLE.Event.ON_PAIR_START event is only posted on Android, not on iOS.

If using event listeners, callbacks can be left off of the pair request. The event listener receives the payload object.

ValidicMobile.BLE.pair(15);

To register for events associated with the BLE reading process:

window.addEventListener(ValidicMobile.BLE.EventName.ON_READY_TO_READ, this.onBLEReadyToRead);
window.addEventListener(ValidicMobile.BLE.EventName.ON_READ_SUCCESS, this.onBLEReadSuccess);
window.addEventListener(ValidicMobile.BLE.EventName.ON_READ_FAIL, this.onBLEReadFailed);
window.addEventListener(ValidicMobile.BLE.EventName.ON_READ_CANCEL, this.onBLEReadCancelled);

Pairing and reading is initiated using pair and read functions which can be invoked with optional success and fail callbacks. These callbacks are invoked passing a response object that described the event. The response includes an event property with the event name, and a payload property containing the appropriate data.

When event listeners are registered, the object passed to the listener is simplified. The passed object is the value of the payload property.

HealthKit


Requirements

  • Cordova 6.3 and above
  • cordova-ios >= 4.4
  • validic-cordova-session plugin
  • validic-cordova-healthkit plugin

Check Heathkit support

Calls to HealthKit functions should only be performed on devices supporting HealthKit. In particular, HealthKit does not function on Android devices. To determine if HealthKit is available on the current device the following call is provided:

var success = function (response) {
    if (response.isAvailable) {
        console.log("HealthKit is available");
    }
}
ValidicMobile.HealthKit.isHealthKitAvailable(success);

Manage subscriptions

The Validic Mobile library provides a simple way to read and upload data from HealthKit to Validic. The ValidicMobile plugin can subscribe to specific HealthKit sample types and automatically upload them to Validic in the background as new data is recorded, even if the app is no longer active.

Subscribing to HealthKit updates only needs to be done once for a user. The subscriptions will be persisted across app launches in the Session object. A typical use of the HealthKit component would be to create a checkbox or equivalent that adds the required subscriptions when turned on and removes them when turned off.

Healthkit subscriptions are based on sample types. Constants representing each available sample type are defined within ValidicMobile.HealthKit.SampleType.

The Validic Mobile library provides subscription sets which are a collection of predefined sample types declared in ValidicMobile.HealthKit.SubscriptionSet. Sample types for a subscription set can be retrieved using the getSampleTypesForSubscriptionSet function. The following subscription sets are available:

  • ROUTINE: Includes Flights Climbed, Active Energy Burned, Distance Walking, Step Count, and Basal Energy Burned. In iOS 9 and later this also includes Apple Stand Hours (from the Apple Watch).
  • DIABETES: Blood Glucose sample type.
  • WEIGHT: Includes Body Mass (weight), Height, Body Fat Percentage, Lean Body Mass, and Body Mass Index.
  • FITNESS: Includes Workout, Nike Fuel, and Cycling Distance.
  • SLEEP: Sleep Analysis sample type, this is the total number of sleep seconds in the “Asleep” Sleep State.
  • BASIC_NUTRITION: Includes Calcium, Carbohydrates, Cholesterol, Fiber, Iron, Potassium, Protein, Saturated Fat, Sodium, Sugar, Total Fat, and Energy Consumed. in iOS 9 and later this will also include Dietary Water.
  • REPRODUCTIVE_HEALTH: Includes Sexual Activity, Cervical Mucus Quality, Intermenstrual Bleeding, Menstrual Flow, Ovulation Test Result, and BasalBodyTemperature. These sample types are only available in iOS 9 and later.
  • BIOMETRICS: Includes Systolic Blood Pressure, Diastolic Blood Pressure, Heart Rate, Body Temperature, and SpO2 (oxygen saturation).

To subscribe to HealthKit sample types:

ValidicMobile.HealthKit.setSubscriptions(sampleTypes, successCallback, errorCallback);

The function accepts an array of strings mapping to HealthKit sample types. Sample types can be aggregated into an array using various calls to retrieve sample types.

The following example retrieves sample types for a subscription set for WEIGHT, adds a specific sample type for step count, and sets those subscriptions.

var success = function (object) {
    var sampleTypes = object.sampleTypes;
    sampleTypes.push(ValidicMobile.HealthKit.SampleType.HKQuantityTypeIdentifierStepCount);
    ValidicMobile.HealthKit.setSubscriptions(sampleTypes);
};
ValidicMobile.HealthKit.getSampleTypesForSubscriptionSet(ValidicMobile.HealthKit.SubscriptionSet.WEIGHT, success);

Note: Calling

ValidicMobile.Session.endSession();

will remove all HealthKit subscriptions and stop listening for new data.

Historical Fetch

The Validic Mobile library provides the ability to query up to 180 days of data for a subset of data types provided by HealthKit by specifying one of more values of the HealthKit.HistoricalSet enum.

Two historical sets are available

  • HealthKit.HistoricalSet.ROUTINE - Step data
  • HealthKit.HistoricalSet.FITNESS - Workout data

To fetch historical HealthKit data, call the HealthKit.fetchHistoricalSets function and pass in an object with the datasets you want to fetch under the historicalSets key. You can also pass ISO8601 date strings in from and to keys to limit the time period that gets fetched. The function accepts a success function parameter which is called when historical records have been queued for upload to the server. The success function is called with an object that contains the number of records processed for each record type. An error function can also be passed which is invoked if invalid parameters are passed.

// Define dates to fetch (optional - if omitted, last 180 days will be fetched)
const start = new Date();
const end = new Date();
start.setDate(end.getDate()-29);

ValidicMobile.HealthKit.fetchHistoricalSets(
    {
        historicalSets: [ValidicMobile.HealthKit.HistoricalSet.ROUTINE, ValidicMobile.HealthKit.HistoricalSet.FITNESS],
        from: start.toISOString(),
        to: end.toISOString()
    }
    function (response) {
        document.getElementById("recordsLog").innerHTML += "HealthKit historical records processed: "
            + JSON.stringify(response) + "<br/><br/>";
    },
    function (response) {
        document.getElementById("recordsLog").innerHTML += "HealthKit historical error: "
            + JSON.stringify(response) + "<br/><br/>";
    });

Doing this may display a permission dialogue from HealthKit, so it's important to call this at an appropriate time in your app. It is recommended to explain to the user why you want this data before attempting to fetch it. This operation may take several seconds to complete, so it would be advisable to display an activity indicator to the user until the completion block is called. When the fetch completes all the data will have been fetched locally and queued up for submission to the server. The amount of time needed to upload the records may vary based on the user's internet speed. The queued records are uploaded automatically by the library based on connectivity, but it is possible for the user to suspend the app before all the records have been uploaded, in which case the remaining records will be uploaded when the user resumes the app. This should be kept in mind when receiving records from the Validic server.

There should be no need to call this method more than once for a user.

When the fetch completes all the data will have been fetched locally and queued up for submission to the server. The amount of time needed to upload the records may vary based on the user’s internet speed.

The queued records are uploaded automatically by the library based on connectivity, but it is possible for the user to suspend the app before all the records have been uploaded, the remaining records will be uploaded when the user resumes the app. This should be kept in mind when receiving records from the Validic server.

Google Fit


Requirements

  • Cordova 6.3 and above
  • cordova-android >= 7.0.0
  • validic-cordova-session plugin
  • validic-cordova-googlefit plugin

Overview

This project integrates Google Fit with the Validic Mobile Aggregator to passively collect data on behalf of an end user. Validic ensures that our Mobile SDK makes use of the minimal scopes needed for our supported data types. Additionally, when using Google Fit version com.google.android.gms:play-services-fitness:19.0.0 or lower, Validic does not request or use any scopes indicated as sensitive or restricted by Google.

With Google Fit version com.google.android.gms:play-services-fitness:20.0.0, all read scopes will be restricted and will require completing Google’s sensitive scope verification or restricted scope verification and security assessment to retrieve data. Please see Google's announcement for further details: https://developers.google.com/fit/improvements

Be aware that Google has an extensive and potentially lengthy verification process. Google manages their own verification process and it is subject to change at any time at their discretion. It is your responsibility to review, understand, and follow Google’s verification process and provide Google with all information they request before sharing your application publicly. Validic does not provide direct support for Google’s verification process, however, Google’s Verification FAQ is detailed and provides you with the information you’ll need to complete the process. See the Customer Requirements section below for highlights on setting up, developing, and verifying for Google Fit.

Customer Requirements

Google Fit is available for Inform (V2) Validic customers. If you are a Legacy customer and are interested in Google Fit, please reach out to your Validic Client Success Manager.

Validic’s Google Fit integration works with Google Fit for Android. Google Fit for Android uses Google’s OAuth API for accessing user data. There is setup that must occur before you implement Google Fit into your mobile project so that your users can consent to sharing and share their data successfully:

Before you start development, in Google Api Console you must:

After completing the above setup, you can start development using the instructions in this tutorial. While you are developing, testing can occur with Google user accounts that are registered to the same domain as the mobile project.

After development and testing are complete and before you launch your app, you will need to submit a request to Google for Oauth API Verification. There are certain instances where this may not be required (see Google’s FAQ for details).

Once you submit your verification request, you may be required to provide some or all of the following:

  • Application Homepage detailing your use of requested scopes
  • Privacy Policy and Terms & Conditions
  • Application Name, Logo, and/or other branding elements
  • Be prepared to provide an Application Demo Video showing the user consent workflow in your app - Google may ask to see this

Google dictates their own verification process so you may be asked to provide additional information as well. See Verification Requirements for more information. Be sure to respond to Google’s requests as quickly as possible to minimize delays in getting your verification approved.

2021 Google Fit Changes

Google announced late in 2020 that they would be changing several scopes and marking a majority of them as "Sensitive" scopes. Requesting access to “Sensitive” scopes requires a more in depth review by the Google Fit team before granting access to end user Google Fit data.

More information about this change can be found here. Changes will be required in the Google Api Console to adjust to the changes in oAuth scopes mentioned in the link/email from Google.

Your app must update to use Google fit dependency version 20.0.0. It is always recommend to update to the latest version of the Validic SDK when updating dependencies.

Initialize

ValidicMobile.GoogleFit will be initialized at app startup and will immediately start listening for previously subscribed data types. It is recommended that you set listeners on the ValidicMobile.GoogleFit events during your onDeviceReady() method:

onDeviceReady {
    document.addListener('validic:googlefit:onrecords',(summary)=>{
        console.log("Proccessed Google Fit Data");
        console.log(summary);
    });
    document.addListener('validic:googlefit:onerror', (callback)=>{
        console.warn(callback.error);
    });

Request Permissions

Before collecting any data from Google Fit, a Google Account must be associated with the ValididMobile.GoogleFit instance, and the end user must authorize the app to collect data on their behalf.

Check previously granted permissions

To check if permissions have already been granted the hasPermissions(dataTypes) method can be used:

ValidicMobile.GoogleFit.hasPermissions(["com.google.step_count.delta"], function(permissions){
        if(permissions["com.google.step_count.delta"]){
            ValidicMobile.GoogleFit.subscribe(["com.google.step_count.delta"], function(){
                console.log("Subscribed to steps")
            
             });
        }
})

The callback returned from hasDataAccess(dataTypes) associates a DataType with true, if a valid Google account exists and permission has previously been granted, or false otherwise.

Request new permissions

To request permission from the end user to authorize data collection the requestPermissions(dataTypes) function can be used to authorize your application

 ValidicMobile.GoogleFit.requestPermissions(["com.google.step_count.delta"], function(permissions){
         if(permissions["com.google.step_count.delta"]){
             ValidicMobile.GoogleFit.subscribe(["com.google.step_count.delta"], function(){
                 console.log("Subscribed to steps")
                 document.getElementById("echo_log").innerHTML += "\nSubscribed to steps\n"
             });
         }
     }, 
     function(error){
         console.log(error)
     }
 )

Android 10

For the Android client Apps that target API 28 the permission below is required in the AndroidManifest.xml. The Validic SDK will add this permission to its manifest so that it will be merged with the client when they add our library to their application.

<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>

This permission is required to subscribe to the following data types:

  • com.google.step_count.delta
  • com.google.step_count.cumulative
  • com.google.step_count.cadence
  • com.google.activity.segment
  • com.google.activity.exercise

For apps targeting Android 10, this permission must be requested from the user at runtime

    if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.ACTIVITY_RECOGNITION)
              != PackageManager.PERMISSION_GRANTED) {
          // Permission is not granted
    }

    ActivityCompat.requestPermissions(thisActivity,
                      arrayOf(Manifest.permission.ACTIVITY_RECOGNITION),
                      MY_PERMISSIONS_REQUEST_ACTIVITY_RECOGNITION);

Manage subscriptions

After Permissions have been granted for a DataType the ValidicMobile.GoogleFit can be used to add subscriptions to data change events from Google Fit. Data will automatically be queued for submission to the Validic API when internet is available on the device.

     ValidicMobile.GoogleFit.subscribe([ValidicMobile.GoogleFit.DataType.STEP_COUNT], function(){
         console.log("Subscribing to steps")
     });

To unregister from receiving data update events use ValidicMobile.GoogleFit.unsubscribe() to unsubscribe

     ValidicMobile.GoogleFit.unsubscribe(ValidicMobile.GoogleFit.DataType.STEP_COUNT);

Get a list of currently subscribed DataTypes

 ValidicMobile.GoogleFit.subscriptions(function(dataTypes){
        console.log(dataTypes)
    })

Currently supported DataTypes

Available DataTypes can be referenced from the ValidicMobile.GoogleFit.datatype

  • STEP_COUNT
  • WEIGHT
  • HEART_RATE
  • CALORIES_EXPENDED
  • MOVE_MINUTES
  • DISTANCE
  • NUTRITION

Records collected are automatically submitted to the Validic Inform API and a summary of records processed will be sent as an event named validic:googlefit:onrecords.

For an example of setting a listener see Initialize.

Historical Fetch

Validic provides the ability to query up to 180 days of data for a subset of data types provided by Google Fit by querying for a HistoryType

  • ValidicMobile.GoogleFit.HistoryType.SUMMARY - Summary record data including steps, distance and calories burned
    ValidicMobile.GoogleFit.fetchHistory(ValidicMobile.GoogleFit.HistoryType.SUMMARY)

To fetch a range of days of historical data, create a HistoryOptions object and pass it as an argument.

        //fetch the last 30 days of data
        const start = new Date();
        const end = new Date();
        start.setDate(end.getDate() - 29);
        ValidicMobile.GoogleFit.fetchHistory(
            {
                historyTypes: [ValidicMobile.GoogleFit.HistoryType.SUMMARY],
                from: start,
                to: end
            }
        );

This will fire a document event with a summary of records gathered that can be registered for

    document.regsiterListener("validic:googlefit:onrecords", function(summary){
        // summary is a dictionary of how many of each record type were processed
        console.log(summary)

    })

Logout

To remove all subscriptions and log an end user out simply call

ValidicGoogleFit.disconnect()

Samsung Health


❗️

Approval Required

The Samsung Health integration requires pre-approval for Samsung's Device SDK.

Currently, Samsung is going through an update to better support their partners and, for that reason, they are not accepting applications for the Partner Apps Program. We will keep this section up to date as we hear any updates from the Samsung team.

The Validic Mobile library provides a simple way to read and upload data from S Health to Validic. Through ValidicMobile.SHealth you can subscribe to specific Samsung Health data types and automatically upload them to Validic in the background as new data is recorded.

Requirements

  • Cordova 6.3 and above
  • cordova-android >= 7.0.0
  • validic-cordova-session plugin
  • samsung-health-data-1.5.0.aar downloaded from Samsung Health

Installation

From the root directory of your application add the plugin to the app with a variable defining the location of the samsung health dependency

cordova plugin add <location of plugin> --variable SHEALTH_DEPENDENCY=<path to samsung health aar>

Developer mode

In order to test, you must enable developer mode in the Samsung Health app on your phone. For instructions on how to enable developer mode please see Samsung's website: https://developer.samsung.com/health/android/data/guide/dev-mode.html

Note: Starting with Samsung Health app version 6.11.0.061 (released August 2020), in order to gain access to Samsung Health data, with or without developer mode enabled, you must first be approved by Samsung and receive a Samsung dev access key.

Prior versions of the Samsung Health app do not require the dev access key when the Samsung Health app is in developer mode.

Check Samsung Health support

Samsung Health is only available if Samsung Health is installed on the device and the Samsung Health SDK Jar is available in the project. To check if both of these are true call:

ValidicMobile.SHealth.isSHealthAvailable(function(response) {
    if (response.isAvailable) {
        // Samsung Health is available
    } else {
        // Samsung Health is not available log error
        console.log(response.error);
    }   
});

Note: Calling a “ValidicMobile.SHealth’ function when Samsung Health is not available will fail and pass the error through the callback.

Manage subscriptions

Samsung provides several data types that can be subscribed to for notification when data changes.

The available data types are:

  • com.samsung.health.blood_glucose
  • com.samsung.health.blood_pressure
  • com.samsung.health.body_temperature
  • com.samsung.health.caffeine_intake
  • com.samsung.health.exercise
  • com.samsung.health.hba1c
  • com.samsung.health.heart_rate
  • com.samsung.health.oxygen_saturation
  • com.samsung.health.sleep
  • com.samsung.health.sleep_stage
  • com.samsung.health.uv_exposure
  • com.samsung.health.water_intake
  • com.samsung.health.weight
  • com.samsung.shealth.step_daily_trend

NOTE: Data types that are going to be used in your application must be added to the AndroidManifest.xml. It is recommended to not manually edit the AndroidManifest.xml directly. It could possibly be overwritten during the Cordova build process. As of Cordova version 6.3.0 it is possible to modify the AndroidManifest.xml file using the <config-file> tag from Cordova

Example

config.xml

    <platform name="android">
        <allow-intent href="market:*"/>
        <config-file parent="./application" target="AndroidManifest.xml">
            <meta-data android:name="com.samsung.android.health.platform_type" android:value="rel"/>
            <meta-data android:name="com.samsung.android.health.permission.read"
                       android:value="com.samsung.health.blood_glucose;com.samsung.health.exercise"/>
        </config-file>
    </platform>

Subscription Sets

Data types are grouped into logical sets, ValidicMobile.SHealth.SubscriptionSet is an Enum that groups several data types together to register for related data types. The available subscription sets are:

  • ROUTINE - Daily step data
    • com.samsung.shealth.step_daily_trend
  • DIABETES - Blood glucose and hba1c data
    • com.samsung.health.blood_glucose
    • com.samsung.health.hba1c
  • WEIGHT - Weight and height data
    • com.samsung.health.weight
  • FITNESS - Exercise data
    • com.samsung.health.exercise
  • SLEEP - Sleep and sleep stage data
    • com.samsung.health.sleep
    • com.samsung.health.sleep_stage
  • NUTRITION - Food and nutrition data
    • com.samsung.health.nutrition
    • com.samsung.health.caffeine_intake
    • com.samsung.health.water_intake
  • BLOOD_PRESSURE - Blood pressure data
    • com.samsung.health.blood_pressure

The group of data types for each subscription set can be found using:

    ValidicMobile.SHealth.getSubscriptionsFromSet(ValidicMobile.SHealth.SubscriptionSet.FITNESS);

Subscribe to data types

Current subscriptions will automatically be restarted inside your application’s initialization.

Data types can be subscribed to individually:

ValidicMobile.SHealth.addSubscriptions("com.samsung.health.exercise");

Or as part of a subscription set:

ValidicMobile.SHealth.addSubscriptionSets([ValidicMobile.SHealth.SubscriptionSet.NUTRITION]);

NOTE: Calling ValidicMobile.Session.endSession() will remove all Samsung Health subscriptions and stop listening for new data.

Historical Fetch

Validic provides the ability to query up to 180 days of historical data for a subset of data types provided by Samsung Health by querying
a group of SHealthSubscription.HistoricalSet

Currently 2 historical sets are available

  • ValidicMobile.SHealth.HistoricalSet.FITNESS - Exercise data
  • ValidicMobile.SHealth.HistoricalSet.ROUTINE - Step data

To Fetch up to 180 days of data in the past, create a HistoryOptions and add a from and to date range

const start = new Date();
const end = new Date();
start.setDate(end.getDate() - 29);
ValidicMobile.SHealth.fetchHistoricalSets({
    historicalSets:[ValidicMobile.SHealth.HistoricalSet.ROUTINE],
    from: start.toISOString(),
    to: end.toISOString()
})

After fetching data for all days requested an event will be emitted to listeners registered to the ValidicMobile.SHealth.EventName.ON_SHEALTH_HISTORY event.

Listener

To listen for events from Samsung Health an eventListener should be added to the window

window.addEventListener(ValidicMobile.SHealth.EventName.ON_SHEALTH_PERMISSIONS, function(event){
    // Samsung Health permissions have changed
});

window.addEventListener(ValidicMobile.SHealth.EventName.ON_SHEALTH_ERROR, function(event){
    // An error has occurred with Samsung Health
});

window.addEventListener(ValidicMobile.SHealth.EventName.ON_SHEALTH_RECORDS, function(event){
    // Validic has gathered records because of a data type subscription change
});

window.addEventListener(ValidicMobile.SHealth.EventName.ON_SHEALTH_HISTORY function(event){
    // Validic data has pulled historical records from Samsung Health
});

VitalSnap (OCR)


OCR provides the capability to obtain readings from devices without requiring Bluetooth, HealthKit, Google Fit, or Samsung Health integration.

Requirements

  • Cordova 6.3 and above
  • cordova-android >= 7.0.0
  • cordova-ios >= 4.4
  • validic-cordova-session plugin
  • validic-cordova-ocr plugin

Peripherals

Peripheral objects contain information regarding supported OCR peripherals. Several function calls are provided to retrieve one or more peripherals.

A peripheral object contains various properties to be displayed to the user:

  • Manufacturer - Manufacturer name.
  • Model - Model number.
  • PeripheralImageURL - URL for an image of the peripheral.
  • ID - Peripheral identifier.

Supported Peripherals

To retrieve a List of supported peripherals:

ValidicMobile.OCR.getSupportedPeripherals(function (response) {
    var peripherals = response.peripherals;
});

To retrieve a specific peripheral:

ValidicMobile.OCR.getPeripheral(3, function (response) {
    var peripheral = response.peripheral;
}, function (err) {
    alert(err.error);
});

Peripherals are grouped by type, such as thermometer, glucose, scale, etc. To retrieve an array of peripherals of a specific type, use the PeripheralType constants and invoke the following function:

ValidicMobile.OCR.getPeripheralsOfType(ValidicMobile.PeripheralType.THERMOMETER, function (response) {
    app.peripheral = response.peripheral;
}, function (err) {
    alert(err.error);
});

Note: OCR and BLE peripheral objects are similar yet different and are not interchangeable.

OCR read

To use OCR to scan a peripheral, the following call is provided:

ValidicMobile.OCR.read(app.peripheral.ID, successCallback, failCallback)

The ID parameter is the ID property from the OCR peripheral object. The successCallback is passed an object containing the generated record in the record property. The image which was recognized is also returned in the image property as a base64 encoded string.

The following snippet initiates a OCR read. On success the image is displayed and record submitted. On failure the error is displayed.

var success = function (obj) {
    var record = obj.record;
    if (obj.hasOwnProperty("image")) {
        document.getElementById("ocrImage").setAttribute("src", "data:image/png;base64," + obj.image);
    }
    var r = confirm("Would you like to submit a blood glucose of " + record.blood_glucose + "mg/dL");
    if (r) {
        ValidicMobile.Session.submitRecord(record, obj.image, function (obj) {
            console.log("Record was added to the processing queue");
        }, function (obj) {
            console.log("Record was not added to queue");
        });
    }
};
/**
 * Failure callback function. This indicates a failure by Validic to take a reading from the device. This could be due to
 * a timeout or for denying permissions for using the camera. Each failure callback e, has the form({peripheralId: 3, error: "..."}
 * @param e
 */
var fail = function (e) {
    alert(e.error);
};
ValidicMobile.OCR.read(app.ocrPeripheral.ID, success, fail); // 3

Runtime unit selection

For any glucose meter in our lineup of supported meters, you can now specify mmol/l or mg/dL at runtime for a given reading. If no unit is provided, mg/dL is assumed.

For the Zewa 11110 thermometer, you can specify Celsius or Fahrenheit at runtime for a given reading. If no unit is provided, Fahrenheit is assumed.

Example:

ValidicMobile.OCR.readWithGlucoseUnit(3, ValidicMobile.GlucoseUnits.MMOLL, success, fail); // Start reading a mmol/L one touch

What’s Next

Review the class documentation:

Did this page help you?