/**
* @file
* @copyright 2016 Motivation Science Inc., All Rights Reserved
* This software is supplied to you by Motivation Science, Inc. (operating as "Validic") under terms of your
* contract with Validic. This software may not be shared or redistributed, in part or as a whole, except
* as explicitly stated by contract with Validic. This software is provided by Validic on an "as is" basis.
* Validic makes no warranties, express or implied, including without limitation the implied warranties of
* non-infringement, merchantability and fitness for a particular purpose, regarding this Validic software
* or its use and operation alone or in combination with your products. In no event shall Validic be liable
* for any special, indirect, incidental or consequential damages (including, but not limited to, procurement
* of substitute goods for services; loss of use, data or profits; or business interruption) arising in any
* way out of the use, reproduction, modification and/or distribution of the Validic software, however caused
* and whether under theory of contract, tort (including negligence), strict liability or otherwise, even if
* Validic has been advised of the possibility of such damage.
*/
// Object descriptions
/**
* @fileoverview Cordova plugin for the Validic Mobile library.
*/
/**
* @typedef {Object} Peripheral
* @property {number} ID - A unique identifer for a particular peripheral model.
* @property {number} Type - The type of the peripheral, used to identify its function. {@link PeripheralType}
* @property {string} Model - Model number of the peripheral.
* @property {string} Manufacturer - Manufacturer name of the peripheral.
* @property {string} PeripheralImageURL - URL for an image of the peripheral.
*/
/**
* @typedef {Object} BluetoothPeripheral - Subtype of {@link Peripheral}. Adds the following additional properties
* @property {boolean} RequiresPairing - Indicates if a peripheral model requires a Bluetooth pairing before it can be used.
* @property {string} Instruction - Text to be presented to the user when BLE.read is called.
* @property {string} ReadingInstruction - Text to be presented to the user when the BLE.ON_READY_TO_READ event is received.
* @property {string} PairingInstruction - Text to be presented to the user when BLE.pair is called.
/**
* @typedef {Object} Record
* @property {string} activity_id - Unique ID generated by the orginal source.
* @property {string} recordType - Type of record. This field not present on server. Added for use by Cordova plugin. Possible values
are "biometrics", "diabetes", "weight", "routine", "nutrition", "fitness", "sleep".
* @property {string} timestamp - Timestamp for the measurement set.
* @property {string} source - The short name of the Validic integration that created the record (validicmobile).
* @property {string} source_name - The display name of the Validic integration that created the record (ValidicMobile).
* @property {string} original_source - The name of the peripheral manufacturer, for records sourced from HealthKit this will be
* the name of the application that originally wrote the data to HealthKit.
* @property {string} intermediary_source - The name of the library technology used to create the record
* (eg "ValidicMobile Bluetooth", "ValidicMobile Apple Health").
* @property {string} device - The model number of the peripheral, for records sourced from HealthKit this will be
* the bundle ID of the application that originally wrote the data to HealthKit.
* @property {string} last_updated - Date and time when the measurement set was last updated.
* @property {boolean} validated - Indicates the data you are receiving was generated using a device,
* opposed to being manually entered by a end user.
* @property {string} _id - Record ID. Assigned after being upload to the server.
* @property {Object} extras - Map of additional extra information.
* @property {Object} media - Object containing URL to image associated with this record if any.
*/
/**
* @typedef {Object} BiometricsRecord - Subtype of {@link Record}. Adds the following additional properties
* @property {number} blood_calcium - The value of the measured quantity in mg/dL.
* @property {number} blood_chromium - The value of the measured quantity in µg/L.
* @property {number} blood_folic_acid - The value of the measured quantity in ng/mL.
* @property {number} blood_magnesium - The value of the measured quantity mg/dL.
* @property {number} blood_potassium - The value of the measured quantity in mEq/L.
* @property {number} blood_sodium - The value of the measured quantity in mEq/L.
* @property {number} blood_vitamin_b12 - The value of the measured quantity in pg/mL.
* @property {number} blood_zinc - The value of the measured quantity in µg/dL.
* @property {string} creatine_kinase - The value of the measured quantity in U/L.
* @property {string} crp - The value of the measured quantity in mg/L.
* @property {string} diastolic - The value of the measured quantity in mmHg.
* @property {string} ferritin - The value of the measured quantity in ng/mL.
* @property {string} hdl - The value of the measured quantity in mg/dL.
* @property {string} hscrp - The value of the measured quantity in mg/L .
* @property {string} il6 - The value of the measured quantity in pg/mL.
* @property {string} ldl - The value of the measured quantity in mg/dL.
* @property {string} resting_heartrate - The value of the measured quantity in bpm.
* @property {string} systolic - The value of the measured quantity in mmHg.
* @property {string} testosterone - The value of the measured quantity in ng/dL.
* @property {string} total_cholesterol - The value of the measured quantity in mg/dL.
* @property {string} tsh - The value of the measured quantity in mIU/L.
* @property {string} uric_acid - The value of the measured quantity in mg/dL.
* @property {string} vitamin_d - The value of the measured quantity in ng/mL.
* @property {string} white_cell_count - The value of the measured quantity in cells/µL.
* @property {string} spo2 - The value of the measured quantity in %.
* @property {string} temperature - The value of the measured quantity in Celsius.
*/
/**
* @typedef {Object} DiabetesRecord - Subtype of {@link Record}. Adds the following additional properties
* @property {number} c_peptide - The value of the measured quantity in ng/mL.
* @property {number} fasting_plasma_glucose_test - The value of the measured quantity in mg/dL.
* @property {number} hba1c - The value of the measured quantity in %.
* @property {number} insulin - The value of the measured quantity U.
* @property {number} oral_glucose_tolerance_test - The value of the measured quantity in mg/dL.
* @property {number} random_plasma_glucose_test - The value of the measured quantity in mg/dL.
* @property {number} triglyceride - The value of the measured quantity in mg/dL.
* @property {number} blood_glucose - The value of the measured quantity mg/dL.
* @property {string} relationship_to_meal - The value of the measured quantity.
*/
/**
* @typedef {Object} WeightRecord - Subtype of {@link Record}. Adds the following additional properties
* @property {number} weight - The value of the measured quantity in kg.
* @property {number} height - The value of the measured quantity in cm.
* @property {number} free_mass - The value of the measured quantity in kg.
* @property {number} fat_percent - The value of the measured quantity.
* @property {number} mass_weight - The value of the measured quantity.
* @property {number} bmi - The value of the measured quantity.
*/
/**
* @typedef {Object} NutritionRecord - Subtype of {@link Record}. Adds the following additional properties
* @property {number} calories - Calories consumed per food intake.
* @property {number} carbohydrates - Grams of carbohydrates consumed.
* @property {number} fat - Grams of fat consumed.
* @property {number} fiber - Grams of fiber consumed.
* @property {number} protein - Grams of protein consumed.
* @property {number} sodium - Grams of sodium consumed.
* @property {number} water - Grams of water consumed.
* @property {number} meal - Meal consumed: Breakfast, Lunch, or Dinner.
*/
/**
* @typedef {Object} RoutineRecord - Subtype of {@link Record}. Adds the following additional properties
* @property {number} steps - Number of steps taken during routine.
* @property {number} distance - The value of the measured quantity in meters.
* @property {number} floors - The value of the measured quantity.
* @property {number} elevation - Elevation climbed in meters.
* @property {number} calories_burned - Calories burned during fitness activity.
*/
/**
* @typedef {Object} FitnessRecord - Subtype of {@link Record}. Adds the following additional properties
* @property {string} type - Type of fitness activity: Walking, Running, Swimming, etc.
* @property {string} intensity - Subjective intensity with which an activity was performed.
* Examples are: low, medium, high. Returned as provided by source.
* @property {string} start_time - Timestamp of when fitness activity started in ISO08601 format.
* @property {number} distance - Distance in meters.
* @property {number} duration - Duration of fitness activity in seconds.
* @property {number} calories - Calories burned during fitness activity.
*/
// Callback definitions and returned properties
// Covers both success and fail callbacks from BLE wrapped as events
/**
* @callback EventCallback
* @property {string} event - Name of event to fire in the window.
* @property {Object} payload - The payload of the event.
* @property {number} payload.peripheralID - Id of the peripheral the event came from.
* @property {Record} [payload.record] - Record returned by event.
* @property {Record[]} [payload.records] - Array of records returned by the event.
* @property {string} [payload.error] - Error message returned by the event.
*/
/**
* @typedef NotificationOptions - Notifications options to be displayed on android. These have no affect on iOS
* @property {Number} id - identifier for the notification to be posted to
* @property {string} title - Title to be displayed in the Notification
* @property {string} message - Message to be displayed in the Notification
* @property {string} icon - Icon to be displayed by the Notification. Can be in the form or a uri. Default looks for 'res://ic_launcher.png'
* @property {string} clearText - Text to be displayed as a notification action. If set, the action will stop the associated foreground service.
*/
/**
* @callback HKCallback
* @property {string} event - Name of event to fire in the window, 'validicOnHealthKitRecordsProcessed'
* @property {Object} payload - The payload of the event.
* @property {number} payload.recordType - Value of ValidicMobile.RecordType indicating type of
* records processed.
* @property {number} payload.count - Number of records processed.
*/
/**
* @callback HKHistoricalFetchCallback
* @property {string} {RecordType} - Number of records fetched of type ValidicMobile.RecordType. The property name is a string
* containing the numeric value from ValidicMobile.RecordType.
*/
/**
* SHealth permission change handler.
* @callback PermissionChangeHandler
* @property {DataType[]} accepted - An array of accepted {@link DataType}.
* @property {DataType[]} denied - An array of denied {@link DataType}.
*/
/**
* SHealth handler for records gathered by Shealth
* @callback SHealthRecordsHandler
* @param {Object} summary - A dictionary of how many records were collected by SHealth keyed by {@link RecordType}
*/
/**
* SHealth error function
* @callback SHealthErrorHandler
* @property {SHealthError} error - The error returned by SHealth
*/
/**
* SHealth History handler
* @typedef SHealthHistoryHandler
* @property {Object} summary - a dictionary of how many records were collected by SHealth and keyed by {@link RecordType}
*/
/**
* SHealth listeners for successful events
* @typedef SHealthHandlers
* @property {PermissionChangeHandler} onPermissionChanged
* @property {SHealthRecordsHandler} onSHealthRecords
* @property {SHealthErrorHandler} onSHealthError
* @property {SHealthHistoryHandler} onSHealthHistory
*/
/**
* Generic callback indicating feature availability.
* @callback AvailableCallback
* @property {boolean} isAvailable - True for is available, false for not
*/
/**
* Callback with a list of peripherals.
* @callback PeripheralsOfTypeCallback
* @property {Peripheral[]} peripherals - List of {@link Peripheral}s returned.
* @property {number} type - Type of peripheral requested.
*/
/**
* Callback with a list of peripherals.
* @callback PeripheralsCallback
* @property {Peripheral[]} peripherals - List of peripherals returned.
*/
/**
* Callback with a single peripheral.
* @callback PeripheralCallback
* @property {Peripheral} peripheral - Returned peripheral.
*/
/**
* @callback InvalidIDCallback
* @property {string} error - The String representation of the error that occured.
* @property {number} [peripheralID] - The peripheral that the error occured with.
*/
/**
* @callback InvalidTypeCallback
* @property {string} error - The String representation of the error that occured.
* @property {number} type - The peripheral type that the error is related to.
*/
/**
* Callback response from BLE.inProgress.
* @callback InProgressCallback
* @property {boolean} inProgress - Indicates if BLE operation is currently in progress.
*/
/**
* Callback response from BLE.getPassiveReadPeripheralIDs
* @callback getPassiveReadPeripheralIDsCallback
* @property {number[]} peripheralIDs - Array of peripheral IDs that are currently being passively read.
*/
/**
* Callback for Passive Bluetooth callbacks
* @callback PassiveBluetoothCallback
* @property event - Name of the event being returned
* @property payload - payload of the event
* @property {number} payload.peripheralID - Id of the peripheral the callback event is related to
* @property {Record[]} payload.records - Records returned by the passive bluetooth manager
* @property {string} payload.error - error returned from the passive read failure
* @
*/
/**
* Passive Bluetooth Options
* @typedef {Object} PassiveBluetoothOptions
* @property {Number[]} peripheralIDs - Array of peripheral IDs to scan for
* @property {NotificationOptions} notificationOptions
*/
/**
*
*/
// OCR related callbacks - responses
/**
* Callback response from OCR.read.
* @callback OCRReadCallback
* @property {number} peripheralID - ID of the peripheral which was read.
* @property {object} record - Record scanned by OCR process.
* @property {string} image - Base 64 encoded string representation of the image who's values were read.
*/
// FailCallback for fail case
/**
* Fail callback
* @callback FailCallback
* @property {string} error - Message describing the error.
*/
// HealthKit related responses
/**
* Callback response from HealthKit.getSubscriptions
* @callback HKSampleTypesCallback
* @property {string[]} sampleTypes - Array of strings representing HealthKit sample types. Values match
* constants defined in ValidicMobile.HealthKit.SampleType.
*/
/**
* Callback response from HealthKit.setSubscriptions
* @callback HKSetSubscriptionsCallback
* @property {string[]} unknownIdentifiers - Array of strings representing HealthKit sample types which
* could not be subscribed to.
*/
/**
* Callback response from availability checks
* @callback AvailableCallback
* @property {boolean} isAvailable - Indicates if the requested service is available.
*/
/**
* Callback for data type requests
* @callback DataTypeCallback
* @property {string[]} dataTypes - Array of strings representing SHealth data types associated with a subscription set
*/
/**
* Callback response to obtain version information.
* @callback VersionCallback
* @property {string} version - Version number of the native Validic Mobile library the plugin is using.
*/
/**
* Callback response checking if service is active.
* @callback IsActiveCallback
* @property {boolean} isActive - Indicates if the requested service is active.
*/
/**
* Records returned from read operations include a record type value. Records submitted to the session
* requires the record type property to be set to one of these values.
* @enum {string}
*/
exports.RecordTypeString = {
BIOMETRICS: "biometrics",
DIABETES: "diabetes",
WEIGHT: "weight",
ROUTINE: "routine",
NUTRITION: "nutrition",
FITNESS: "fitness",
SLEEP: "sleep"
};
/**
* For use with HealthKit.getSampleTypesForRecordType
* @enum {number}
*/
exports.RecordType = {
NONE: 0,
BIOMETRICS: 1,
DIABETES: 2,
WEIGHT: 3,
ROUTINE: 4,
NUTRITION: 5,
FITNESS: 6,
SLEEP: 7
};
/**
* @enum {number}
*/
exports.PeripheralType = {
NONE: 0,
THERMOMETER: 1,
BLOOD_PRESSURE: 2,
HEART_RATE: 3,
GLUCOSE: 4,
WEIGHT_SCALE: 5,
PULSE_OXIMETER: 6
};
/**
* Used for setting units for ocr.
* @enum {string}
*/
exports.GlucoseUnits = {
MGDL: "mg/dL",
MMOLL: "mmol/L"
};
var exec = require('cordova/exec');
// Default event handler, callback for all listeners, posts window event
var eventHandler = function (event) {
console.log("Event handler " + JSON.stringify(event));
if (event.hasOwnProperty("event")) {
cordova.fireWindowEvent(event.event, event.payload);
}
};
var isInitialized = false;
var initializeListeners = function() {
if (!isInitialized) {
// Register default event listeners
exec(eventHandler, eventHandler, "ValidicMobile", "BLE_setBluetoothPassiveListener", []);
exec(eventHandler, eventHandler, "ValidicMobile", "setSessionListener", []);
exec(eventHandler, eventHandler, "ValidicMobile", "setHealthKitListener", []);
exec(eventHandler, eventHandler, "ValidicMobile", "setSHealthListener", []);
isInitialized = true;
}
};
document.addEventListener('deviceReady', initializeListeners);
/**
* @exports BLE
* Represents Validic Bluetooth functionality
* */
exports.BLE = {
/**
* Callback response checking if service is active.
* @callback IsActiveCallback
* @property {boolean} isActive - Indicates if the requested service is active.
*/
/**
* Bluetooth event names that can be subscribed to for using window.addEventListener to receive bluetooth events.
* @enum {string}
*/
EventName: {
ON_PAIR_SUCCESS: "validicOnPairSuccessful",
ON_PAIR_FAIL: "validicOnPairFailed",
ON_PAIR_START: "validicOnPairingStarted",
ON_READ_SUCCESS: "validicOnReadSuccessful",
ON_READ_FAIL: "validicOnReadFailed",
ON_READY_TO_READ: "validicOnReadyToRead",
ON_READ_CANCEL: "validicOnReadCancelled",
ON_PASSIVE_DID_READ: "validicOnBluetoothPassiveDidRead",
ON_PASSIVE_DID_FAIL: "validicOnBluetoothPassiveDidFail",
ON_PASSIVE_DID_CANCEL: "validicOnBluetoothPassiveDidCancel",
ON_PASSIVE_READY_TO_READ: "validicOnBluetoothPassiveIsReadyToRead"
},
/**
* Gets an array of supported peripherals for use with bluetooth.
* @param {PeripheralsCallback} success - Callback function containing an array of peripheral devices.
*/
getSupportedPeripherals: function(success) {
exec(success, null, "ValidicMobile", "BLE_getSupportedPeripherals", []);
},
/**
* Gets an array of supported peripherals matching a peripheral type.
* @param {number} type - Type of peripheral to return list for. See ValidicMobile.PeripheralType.
* @param {PeripheralsOfTypeCallback} success - Callback function containing an array of all peripherals matching given type.
* @param {FailCallback} error callback function indicating invalid type.
* */
getPeripheralsOfType: function(type, success, error) {
exec(success, error, "ValidicMobile", "BLE_getPeripheralsOfType", [type]);
},
/**
* Gets information about a peripheral with a given id.
* @param {number} id - Id of peripheral to retrieve information about.
* @param {PeripheralCallback} success - Callback function including peripheral information.
* @param {FailCallback} error - Callback function indicating an error trying to receive info about peripheral or if id is not an integer.
*/
getPeripheral: function(id, success, error) {
exec(success, error, "ValidicMobile", "BLE_getPeripheral", [id]);
},
/**
* Pairs a bluetooth device.
* @param id {number} id of the device to pair with.
* @param {EventCallback} success - All bluetooth pair success methods flow through this callback.
* @param {EventCallback} fail - All bluetooth pair failure/cancel methods flow through this callback.
*/
pair: function(id, success, fail) {
var successful = function(obj) {
if (success != null && success != 'undefined') {
success(obj);
}
if (obj.hasOwnProperty("event")) {
cordova.fireWindowEvent(obj.event, obj.payload);
}
};
var error = function(obj) {
if (fail != null && fail != 'undefined') {
fail(obj);
}
if (obj.hasOwnProperty("event")) {
cordova.fireWindowEvent(obj.event, obj.payload);
}
};
exec(successful, error, "ValidicMobile", "BLE_pair", [id]);
},
/**
* Reads from a paired bluetooth device.
* @param {number} id - Peripheral Id to read from.
* @param {EventCallback} success - All bluetooth read success callbacks flow through this callback.
* @param {EventCallback} fail - All bluetooth read fail and cancel callbacks flow through this callback.
*/
read: function(id, success, fail) {
var successful = function(obj) {
if (success != null && success != 'undefined') {
success(obj);
}
if (obj.hasOwnProperty("event")) {
cordova.fireWindowEvent(obj.event, obj.payload);
}
};
var error = function(obj) {
if (fail != null && fail != 'undefined') {
fail(obj);
}
if (obj.hasOwnProperty("event")) {
cordova.fireWindowEvent(obj.event, obj.payload);
}
};
exec(successful, error, "ValidicMobile", "BLE_read", [id]);
},
/**
* Cancels a bluetooth reading or pairing. Listeners should receive an onReadCancel event after cancelling
* reading or pairing.
*/
cancel: function() {
exec(null, null, "ValidicMobile", "BLE_cancel", []);
},
/**
* Indicates a reading is being taken from a paired peripheral.
* @param {InProgressCallback} success - Callback containing a boolean value containing true when a reading is being taken, otherwise false.
*/
isInProgress: function(success) {
exec(success, null, "ValidicMobile", "BLE_inProgress", []);
},
/**
* Set list of Bluetooth peripheral IDs which should be passively read. Once set, the library will listen for and read from
* these devices when the app is in foreground or background.
* To stop passive Bluetooth read, pass an empty array of IDs or null.
* @param {PassiveBluetoothOptions} params - Options for passive Bluetooth Scanning. For
* @param {Object} success -
* @param {FailCallback} error - Invalid parameters were given.
*/
setPassiveReadPeripheralIDs: function(params, success, error) {
exec(success, error, "ValidicMobile", "BLE_setPassiveReadPeripheralIDs", [params]);
},
/**
* @param {getPassiveReadPeripheralIDsCallback} success - Response containing array of currently subscribed sample types.
*/
getPassiveReadPeripheralIDs: function(success) {
exec(success, null, "ValidicMobile", "BLE_getPassiveReadPeripheralIDs", []);
},
/**
* Registers listener for passive bluetooth read events. It is recommended to use event listeners instead.
* @param {PassiveBluetoothCallback} success - Function invoked when passive bluetooth records have been processed and submitted
* or when peripheral becomes ready to read.
* @param {PassiveBluetoothCallback} fail - Function invoked when passive bluetooth read is attempted but fails.
*/
setBluetoothPassiveListener: function(success, fail) {
var successful = function(obj) {
if (success != null && success != 'undefined') {
success(obj);
}
if (obj.hasOwnProperty("event")) {
cordova.fireWindowEvent(obj.event, obj.payload);
}
};
var error = function(obj) {
if (fail != null && fail != 'undefined') {
fail(obj);
}
if (obj.hasOwnProperty("event")) {
cordova.fireWindowEvent(obj.event, obj.payload);
}
};
initializeListeners();
exec(successful, error, "ValidicMobile", "BLE_setBluetoothPassiveListener", []);
}
};
/**
* @exports OCR
* Represents Validic OCR functionality.
*/
exports.OCR = {
/**
* Gets an array of supported peripherals for use with OCR.
* @param {PeripheralsCallback} success - Callback function containing an array of peripheral devices.
*/
getSupportedPeripherals: function(success) {
exec(success, null, "ValidicMobile", "OCR_getSupportedPeripherals", []);
},
/**
* Gets an array of supported peripherals matching a given type.
* @param {number} type - Peripheral Type.
* @param {PeripheralsCallback} success - Callback function containing an array of all peripherals matching given type.
* @param {FailCallback} error - Callback function indicating invalid type.
*/
getPeripheralsOfType: function(type, success, error) {
exec(success, error, "ValidicMobile", "OCR_getPeripheralsOfType", [type]);
},
/**
* Gets information on a supported peripheral with a given id.
* @param {number} id - Peripheral ID.
* @param {PeripheralsCallback} success callback function containing the peripheral's information.
* @param {FailCallback} error callback function with a n error message indicating failure reason.
*/
getPeripheral: function(id, success, error) {
exec(success, error, "ValidicMobile", "OCR_getPeripheral", [id]);
},
/**
* Launches the OCR view to take a reading.
* @param {number} id - Id of peripheral to take a reading from.
* @param {OCRReadCallback} success Callback indicates the capture screen was loaded successfully.
* @param {FailCallback} error - Indicates the capture screen was not loaded successfully. Includes failure reason in message.
*/
read: function(id, success, error) {
exec(success, error, "ValidicMobile", "OCR_read", [id]);
},
/**
* Launches the OCR view to take a reading that is displayed in the provided unit.
* @param {number} id - Id of peripheral to take a reading from.
* @param {GlucoseUnit} unit - The unit that the device is displaying in.
* @param {OCRReadCallback} success Callback indicates the capture screen was loaded successfully.
* @param {FailCallback} error - Indicates the capture screen was not loaded successfully. Includes failure reason in message.
*/
readWithGlucoseUnit: function(id, unit, success, error) {
exec(success, error, "ValidicMobile", "OCR_read", [id, unit])
}
};
/**
* @exports HealthKit
* Represents Validic HealthKit functionality.
*/
exports.HealthKit = {
/**
*
* @param {string[]} params - Array of Strings which map to sample types. See {@link HealthKit.SampleType}
* @param {HKSetSubscriptionsCallback} success - Subscriptions were set successfully
* @param {FailCallback} error - Invalid parameters were given
*/
setSubscriptions: function(params, success, error) {
exec(success, error, "ValidicMobile", "setHealthKitSubscriptions", [params]);
},
/**
* @param {HKSampleTypesCallback} success - Response containing array of currently subscribed sample types.
*/
getSubscriptions: function(success) {
exec(success, null, "ValidicMobile", "subscriptions", []);
},
/**
* Indicates the availability of HealthKit
* @param {AvailableCallback} callback - Callback function including whether healthkit is available for the platform
* the application is running on. For Android and iPad this callback will always contain {isAvailable: false}
*/
isHealthKitAvailable: function(callback) {
exec(callback, null, "ValidicMobile", "isHealthKitAvailable", []);
},
/**
* Initiate new queries against HealthKit.
*/
fetchLatestData: function(success) {
exec(success, null, "ValidicMobile", "fetchLatestData", []);
},
/**
* Fetch historical data for the specified sets.
* @param {HistoricalSet[]} historicalSets - Array of HistoricalSet values indicating information to retrieve
* @param {HKHistoricalFetchCallback} success - Response containing count of records for each record type keyed by
record type values from ValidicMobile.RecordType.
* @param {FailCallback} error - Error response if invalid historical sets are provided.
*/
fetchHistoricalSets: function(historicalSets, success, error) {
exec(success, error, "ValidicMobile", "fetchHistoricalSets", [historicalSets]);
},
/**
* Returns sample types associated with a subscription set. See ValidicMobile library documentation for description of sets.
* @param {SubscriptionSet} subscriptionSetID - String representing one of the available subscription sets from SubscriptionSet.
* @param {HKSampleTypesCallback} success - Response containing array of sample types for given subscription set.
* @param {FailCallback} error - Error response if invalid subscription set provided.
*/
getSampleTypesForSubscriptionSet: function(subscriptionSetID, success, error) {
exec(success, error, "ValidicMobile", "sampleTypesForSubscriptionSet", [subscriptionSetID]);
},
/**
* Returns sample types associated with a record type.
* @deprecated getSampleTypesForRecordType is deprecated, please use getSampleTypesForSubscriptionSet instead.
* @param {RecordType} recordType - Number representing one of the available record types from RecordType.
* @param {HKSampleTypesCallback} success - Response containing array of sample types for given record type.
* @param {FailCallback} error - Error response is invalid subscription set provided.
*/
getSampleTypesForRecordType: function(recordType, success, error) {
console.warn("getSampleTypesForRecordType is deprecated, please use getSampleTypesForSubscriptionSet instead.")
exec(success, error, "ValidicMobile", "sampleTypesForRecordType", [recordType]);
},
/**
* Registers listener for HealthKit records processed event. It is recommended to use event listeners instead.
* @param {HKCallback} success - Function invoked when HealthKit records have been processed and submitted.
*/
setHealthKitListener: function(success) {
var successful = function(obj) {
if (success != null && success != 'undefined') {
success(obj);
}
if (obj.hasOwnProperty("event")) {
cordova.fireWindowEvent(obj.event, obj.payload);
}
};
initializeListeners();
exec(successful, null, "ValidicMobile", "setHealthKitListener", []);
},
/**
* @enum {string} HealthKit record processed event name.
*/
EventName: {
ON_HEALTHKIT_RECORD_PROCESSED: "validicOnHealthKitRecordsProcessed"
},
/**
* Identifiers for available subscription sets.
* @enum {number}
*/
SubscriptionSet: {
ROUTINE: 0,
DIABETES: 1,
WEIGHT: 2,
FITNESS: 3,
SLEEP: 4,
BASIC_NUTRITION: 5,
REPRODUCTIVE_HEALTH: 6,
BIOMETRICS: 7
},
/**
* Identifiers for available historical fetch sets.
* @enum {string}
*/
HistoricalSet: {
ROUTINE: "routine",
FITNESS: "fitness"
},
/**
String constants representing HealthKit sample types.
@enum {string}
*/
SampleType: {
HKQuantityTypeIdentifierBodyMassIndex: "HKQuantityTypeIdentifierBodyMassIndex",
HKQuantityTypeIdentifierBodyFatPercentage: "HKQuantityTypeIdentifierBodyFatPercentage",
HKQuantityTypeIdentifierHeight: "HKQuantityTypeIdentifierHeight",
HKQuantityTypeIdentifierBodyMass: "HKQuantityTypeIdentifierBodyMass",
HKQuantityTypeIdentifierLeanBodyMass: "HKQuantityTypeIdentifierLeanBodyMass",
HKQuantityTypeIdentifierStepCount: "HKQuantityTypeIdentifierStepCount",
HKQuantityTypeIdentifierDistanceWalkingRunning: "HKQuantityTypeIdentifierDistanceWalkingRunning",
HKQuantityTypeIdentifierDistanceCycling: "HKQuantityTypeIdentifierDistanceCycling",
HKQuantityTypeIdentifierBasalEnergyBurned: "HKQuantityTypeIdentifierBasalEnergyBurned",
HKQuantityTypeIdentifierActiveEnergyBurned: "HKQuantityTypeIdentifierActiveEnergyBurned",
HKQuantityTypeIdentifierFlightsClimbed: "HKQuantityTypeIdentifierFlightsClimbed",
HKQuantityTypeIdentifierNikeFuel: "HKQuantityTypeIdentifierNikeFuel",
HKQuantityTypeIdentifierAppleExerciseTime: "HKQuantityTypeIdentifierAppleExerciseTime",
HKQuantityTypeIdentifierHeartRate: "HKQuantityTypeIdentifierHeartRate",
HKQuantityTypeIdentifierBodyTemperature: "HKQuantityTypeIdentifierBodyTemperature",
HKQuantityTypeIdentifierBasalBodyTemperature: "HKQuantityTypeIdentifierBasalBodyTemperature",
HKQuantityTypeIdentifierBloodPressureSystolic: "HKQuantityTypeIdentifierBloodPressureSystolic",
HKQuantityTypeIdentifierBloodPressureDiastolic: "HKQuantityTypeIdentifierBloodPressureDiastolic",
HKQuantityTypeIdentifierRespiratoryRate: "HKQuantityTypeIdentifierRespiratoryRate",
HKQuantityTypeIdentifierOxygenSaturation: "HKQuantityTypeIdentifierOxygenSaturation",
HKQuantityTypeIdentifierPeripheralPerfusionIndex: "HKQuantityTypeIdentifierPeripheralPerfusionIndex",
HKQuantityTypeIdentifierBloodGlucose: "HKQuantityTypeIdentifierBloodGlucose",
HKQuantityTypeIdentifierNumberOfTimesFallen: "HKQuantityTypeIdentifierNumberOfTimesFallen",
HKQuantityTypeIdentifierElectrodermalActivity: "HKQuantityTypeIdentifierElectrodermalActivity",
HKQuantityTypeIdentifierInhalerUsage: "HKQuantityTypeIdentifierInhalerUsage",
HKQuantityTypeIdentifierBloodAlcoholContent: "HKQuantityTypeIdentifierBloodAlcoholContent",
HKQuantityTypeIdentifierForcedVitalCapacity: "HKQuantityTypeIdentifierForcedVitalCapacity",
HKQuantityTypeIdentifierForcedExpiratoryVolume1: "HKQuantityTypeIdentifierForcedExpiratoryVolume1",
HKQuantityTypeIdentifierPeakExpiratoryFlowRate: "HKQuantityTypeIdentifierPeakExpiratoryFlowRate",
HKQuantityTypeIdentifierDietaryFatTotal: "HKQuantityTypeIdentifierDietaryFatTotal",
HKQuantityTypeIdentifierDietaryFatPolyunsaturated: "HKQuantityTypeIdentifierDietaryFatPolyunsaturated",
HKQuantityTypeIdentifierDietaryFatMonounsaturated: "HKQuantityTypeIdentifierDietaryFatMonounsaturated",
HKQuantityTypeIdentifierDietaryFatSaturated: "HKQuantityTypeIdentifierDietaryFatSaturated",
HKQuantityTypeIdentifierDietaryCholesterol: "HKQuantityTypeIdentifierDietaryCholesterol",
HKQuantityTypeIdentifierDietarySodium: "HKQuantityTypeIdentifierDietarySodium",
HKQuantityTypeIdentifierDietaryCarbohydrates: "HKQuantityTypeIdentifierDietaryCarbohydrates",
HKQuantityTypeIdentifierDietaryFiber: "HKQuantityTypeIdentifierDietaryFiber",
HKQuantityTypeIdentifierDietarySugar: "HKQuantityTypeIdentifierDietarySugar",
HKQuantityTypeIdentifierDietaryEnergyConsumed: "HKQuantityTypeIdentifierDietaryEnergyConsumed",
HKQuantityTypeIdentifierDietaryProtein: "HKQuantityTypeIdentifierDietaryProtein",
HKQuantityTypeIdentifierDietaryVitaminA: "HKQuantityTypeIdentifierDietaryVitaminA",
HKQuantityTypeIdentifierDietaryVitaminB6: "HKQuantityTypeIdentifierDietaryVitaminB6",
HKQuantityTypeIdentifierDietaryVitaminB12: "HKQuantityTypeIdentifierDietaryVitaminB12",
HKQuantityTypeIdentifierDietaryVitaminC: "HKQuantityTypeIdentifierDietaryVitaminC",
HKQuantityTypeIdentifierDietaryVitaminD: "HKQuantityTypeIdentifierDietaryVitaminD",
HKQuantityTypeIdentifierDietaryVitaminE: "HKQuantityTypeIdentifierDietaryVitaminE",
HKQuantityTypeIdentifierDietaryVitaminK: "HKQuantityTypeIdentifierDietaryVitaminK",
HKQuantityTypeIdentifierDietaryCalcium: "HKQuantityTypeIdentifierDietaryCalcium",
HKQuantityTypeIdentifierDietaryIron: "HKQuantityTypeIdentifierDietaryIron",
HKQuantityTypeIdentifierDietaryThiamin: "HKQuantityTypeIdentifierDietaryThiamin",
HKQuantityTypeIdentifierDietaryRiboflavin: "HKQuantityTypeIdentifierDietaryRiboflavin",
HKQuantityTypeIdentifierDietaryNiacin: "HKQuantityTypeIdentifierDietaryNiacin",
HKQuantityTypeIdentifierDietaryFolate: "HKQuantityTypeIdentifierDietaryFolate",
HKQuantityTypeIdentifierDietaryBiotin: "HKQuantityTypeIdentifierDietaryBiotin",
HKQuantityTypeIdentifierDietaryPantothenicAcid: "HKQuantityTypeIdentifierDietaryPantothenicAcid",
HKQuantityTypeIdentifierDietaryPhosphorus: "HKQuantityTypeIdentifierDietaryPhosphorus",
HKQuantityTypeIdentifierDietaryIodine: "HKQuantityTypeIdentifierDietaryIodine",
HKQuantityTypeIdentifierDietaryMagnesium: "HKQuantityTypeIdentifierDietaryMagnesium",
HKQuantityTypeIdentifierDietaryZinc: "HKQuantityTypeIdentifierDietaryZinc",
HKQuantityTypeIdentifierDietarySelenium: "HKQuantityTypeIdentifierDietarySelenium",
HKQuantityTypeIdentifierDietaryCopper: "HKQuantityTypeIdentifierDietaryCopper",
HKQuantityTypeIdentifierDietaryManganese: "HKQuantityTypeIdentifierDietaryManganese",
HKQuantityTypeIdentifierDietaryChromium: "HKQuantityTypeIdentifierDietaryChromium",
HKQuantityTypeIdentifierDietaryMolybdenum: "HKQuantityTypeIdentifierDietaryMolybdenum",
HKQuantityTypeIdentifierDietaryChloride: "HKQuantityTypeIdentifierDietaryChloride",
HKQuantityTypeIdentifierDietaryPotassium: "HKQuantityTypeIdentifierDietaryPotassium",
HKQuantityTypeIdentifierDietaryCaffeine: "HKQuantityTypeIdentifierDietaryCaffeine",
HKQuantityTypeIdentifierDietaryWater: "HKQuantityTypeIdentifierDietaryWater",
HKQuantityTypeIdentifierUVExposure: "HKQuantityTypeIdentifierUVExposure",
HKCategoryTypeIdentifierSleepAnalysis: "HKCategoryTypeIdentifierSleepAnalysis",
HKCategoryTypeIdentifierAppleStandHour: "HKCategoryTypeIdentifierAppleStandHour",
HKCategoryTypeIdentifierCervicalMucusQuality: "HKCategoryTypeIdentifierCervicalMucusQuality",
HKCategoryTypeIdentifierOvulationTestResult: "HKCategoryTypeIdentifierOvulationTestResult",
HKCategoryTypeIdentifierMenstrualFlow: "HKCategoryTypeIdentifierMenstrualFlow",
HKCategoryTypeIdentifierIntermenstrualBleeding: "HKCategoryTypeIdentifierIntermenstrualBleeding",
HKCategoryTypeIdentifierSexualActivity: "HKCategoryTypeIdentifierSexualActivity",
HKQuantityTypeIdentifierPushCount: "HKQuantityTypeIdentifierPushCount",
HKQuantityTypeIdentifierDistanceWheelchair: "HKQuantityTypeIdentifierDistanceWheelchair",
HKCategoryTypeIdentifierMindfulSession: "HKCategoryTypeIdentifierMindfulSession",
HKQuantityTypeIdentifierSwimmingStrokeCount: "HKQuantityTypeIdentifierSwimmingStrokeCount",
HKQuantityTypeIdentifierDistanceSwimming: "HKQuantityTypeIdentifierDistanceSwimming",
HKCorrelationTypeIdentifierBloodPressure: "HKCorrelationTypeIdentifierBloodPressure",
HKCorrelationTypeIdentifierFood: "HKCorrelationTypeIdentifierFood",
HKWorkoutTypeIdentifier: "HKWorkoutTypeIdentifier"
}
};
/**
* @exports SHealth
* Represents Validic Mobile's Samsung SHealth Functionality.
*/
exports.SHealth = {
/**
* Checks whether this device is an Android device and if SHealth is installed.
* @param {AvailableCallback} callback
*/
isSHealthAvailable: function(callback) {
exec(callback, null, "ValidicMobile", "isSHealthAvailable", []);
},
/**
* @param {NotificationOptions} notificationOptions for foreground service notification.
* Starts the SHealth Service if it is not already started. It will report back gathered permissions through
* onPermissionChanged with a {@link PermissionChangeHandler} or OnPermission error with an {@link SHealthError}.
*/
observeCurrentSubscriptions: function(notificationOptions) {
exec(null, null, "ValidicMobile", "observeSHealthSubscriptions", [notificationOptions]);
},
/**
* Add an array of {@link SubscriptionSet} values to receive records through SHealth for.
* @param {SubscriptionSet[]} subscriptionSet
* @param {NotificationOptions} notificationOptions for foreground service notification.
*/
addSubscriptionSets: function(subscriptionSet, notificationOptions) {
exec(null, null, "ValidicMobile", "addSHealthSubscriptionSets", [subscriptionSet, notificationOptions]);
},
/**
* Add an array of {@link DataType} values to receive records through SHealth for.
* @param {DataType[]} dataTypes - An array of DataType to add a subscription for to receive records through SHealth.
* @param {NotificationOptions} notificationOptions for foreground service notification.
*/
addSubscriptions: function(dataTypes, notificationOptions) {
exec(null, null, "ValidicMobile", "addSHealthSubscriptions", [dataTypes, notificationOptions]);
},
/**
* Remove subscriptions to a group of {@link DataType} from SHealth.
* @param {DataType[]} dataTypes
*/
removeSubscriptions: function(dataTypes) {
exec(null, null, "ValidicMobile", "removeSHealthSubscriptions", [dataTypes]);
},
/**
* Remove an array of {@link SubscriptionSet} values from SHealth.
* @param subscriptionSets
*/
removeSubscriptionSets: function(subscriptionSets) {
exec(null, null, "ValidicMobile", "removeSHealthSubscriptionSets", [subscriptionSets]);
},
/**
* Set a listener for SHealth events from SHealth.
* @param {SHealthHandlers} listeners - Callbacks for events from SHealth
*/
setSHealthListener: function(listeners) {
var successful = function(obj) {
if (obj.hasOwnProperty("event")) {
cordova.fireWindowEvent(obj.event, obj.payload);
if (obj.event == ValidicMobile.SHealth.EventName.ON_SHEALTH_PERMISSIONS) {
ValidicMobile.SHealth.onPermissionChanged(obj.payload);
if (listeners != null && listeners.hasOwnProperty("onPermissionChanged")) {
listeners.onPermissionChanged(obj.payload);
}
} else if (obj.event == ValidicMobile.SHealth.EventName.ON_SHEALTH_RECORDS && listeners != null && listeners.hasOwnProperty("onSHealthRecords")) {
listeners.onSHealthRecords(obj.payload);
} else if (obj.event == ValidicMobile.SHealth.EventName.ON_SHEALTH_HISTORY && listeners != null && listeners.hasOwnProperty('onSHealthHistory')) {
listeners.onSHealthHistory(obj.payload);
}
}
};
var error = function(obj) {
if (obj.hasOwnProperty("event")) {
cordova.fireWindowEvent(obj.event, obj.payload);
if (obj.event == ValidicMobile.SHealth.EventName.ON_SHEALTH_ERROR) {
ValidicMobile.SHealth.onPermissionError(obj.payload);
if (listeners != null && listeners.hasOwnProperty("onSHealthError")) {
listeners.onSHealthError(obj.payload);
}
}
}
}
exec(successful, error, "ValidicMobile", "setSHealthListener", []);
},
/**
* @deprecated
* use {@link setSHealthListener}
* Error callback for SHealth. Overload this function to receive notifications for SHealth Permission Errors.
* @param {SHealthError} err - Error from SHealth.
*/
onPermissionError: function(err) {},
/**
* @deprecated
* use {@link setSHealthListener}
* Success callback for SHealth. Overload this function to receive notifications for SHealth Permission changes.
* @param {PermissionChangeHandler} obj - Callback with gathered permissions.
*/
onPermissionChanged: function(obj) {
},
/**
* Returns the set of {@link #DataType} associated with a {@link #SubscriptionSet}
* @param {SubscriptionSet} - set - The subscription set to return data types for
* @param {DataTypeCallback} - success - The success callback for returning the array of datatypes
* @param {FailCallback} - err - The error callback
*/
getSubscriptionsFromSet: function(set, success, err) {
exec(success, err, "ValidicMobile", "getSubscriptionDataTypes", [set]);
},
/**
* @param {HistoricalSet[]} historicalSets - Array of {@link HistoricalSet} to pull 6 months of history from SHealth. Currently only
* {@link HistoricalSet.ROUTINE} and {@link HistoricalSet.FITNESS} are supported. If a listener has been set using
* {@link SHealth.setSHealthListener} a summary will be returned for any records pulled from history.
*/
fetchHistoricalSets: function(historicalSets) {
exec(null, null, "ValidicMobile", "fetchHistory", [historicalSets]);
},
/**
* The window event names for events generated by SHealth
* @enum {string}
*/
EventName: {
ON_SHEALTH_PERMISSIONS: "validicOnSHealthPermissions",
ON_SHEALTH_ERROR: "validicOnSHealthError",
ON_SHEALTH_RECORDS: "validicOnSHealthRecords",
ON_SHEALTH_HISTORY: "validicOnSHealthHistory"
},
/**
* Each Subscription set is a collection of SHealth DataType that when used add subscriptions for multiple DataTypes.
* @enum {number}
*/
SubscriptionSet: {
ROUTINE: 0,
DIABETES: 1,
WEIGHT: 2,
FITNESS: 3,
SLEEP: 4,
NUTRITION: 5,
BLOOD_PRESSURE: 6
},
/**
* Each Historical set is a collection of SHealth DataType that is used to fetch 6 months of corresponding data from SHealth.
* @enum {string}
*/
HistoricalSet: {
ROUTINE: "ROUTINE",
FITNESS: "FITNESS",
},
/**
* Represents the SHealth HealthConstants string representation.
* @enum {string}
*/
DataType: {
DAILY_STEP_COUNT: "com.samsung.shealth.step_daily_trend",
BLOOD_PRESSURE: "com.samsung.health.blood_pressure",
TEMPERATURE: "com.samsung.health.body_temperature",
HEART_RATE: "com.samsung.health.heart_rate",
SPO2: "com.samsung.health.oxygen_saturation",
GLUCOSE: "com.samsung.health.blood_glucose",
HBA1C: "com.samsung.health.hba1c",
WEIGHT: "com.samsung.health.weight",
FOOD_INFO: "com.samsung.health.food_info",
FOOD_INTAKE: "com.samsung.health.food_intake",
WATER_INTAKE: "com.samsung.health.water_intake",
CAFFEINE_INTAKE: "com.samsung.health.caffeine_intake",
EXERCISE: "com.samsung.health.exercise",
SLEEP: "com.samsung.health.sleep",
SLEEP_STAGE: "com.samsung.health.sleep_stage"
},
/**
* The SHealth errors that can be reported through {@link onPermissionError}.
* @enum {string}
*/
SHealthError: {
MISSING_USER: "MISSING_USER",
RESOLVING_CONNECTION_FAILED: "RESOLVING_CONNECTION_FAILED",
CONNECTION_FAILED: "CONNECTION_FAILED",
INVALID_DATA_TYPE: "INVALID_DATA_TYPE",
INVALID_PERMISSION: "INVALID_PERMISSION"
}
};
/** @exports Session
* Represents a users session.
*/
exports.Session = {
/**
* @enum {string}
*/
EventName: {
ON_RECORD_SUBMIT: "validicOnRecordSubmitted",
ON_RECORD_SUBMIT_FAIL: "validicOnRecordSubmitFailed"
},
/**
* Starts a session with a User's credentials.
* @param {string} userId - Id of the user.
* @param {string} orgId - Organization Id.
* @param {string} accessToken - Security Access Token.
* @param {function} success - Callback. No parameters passed.
* @param {FailCallback} fail - Callback if parameters are invalid types or are missing. This function does
* NOT verify that the credentials are valid.
*/
startSession: function(userId, orgId, accessToken, success, fail) {
exec(success, fail, "ValidicMobile", "startSession", [userId, orgId, accessToken]);
},
/**
* Ends a user's session
* @param {Callback} success - Callback function indicating method invoked.
*/
endSession: function(success) {
exec(success, null, "ValidicMobile", "endSession", []);
},
/**
* Registers listeners for record upload success and failure callbacks. It is recommended to use event listeners instead.
* @param {EventCallback} success - Function invoked for each record successfully uploaded to the server. The uploaded
* record is included in the payload.
* @param {EventCallback} fail - Callback invoked for each record which experiences a non-recoverable upload error.
*/
setSessionListener: function(success, fail) {
var successful = function(obj) {
if (success != null && success != 'undefined') {
success(obj);
}
if (obj.hasOwnProperty("event")) {
cordova.fireWindowEvent(obj.event, obj.payload);
}
};
var error = function(obj) {
if (fail != null && fail != 'undefined') {
fail(obj);
}
if (obj.hasOwnProperty("event")) {
cordova.fireWindowEvent(obj.event, obj.payload);
}
};
initializeListeners();
exec(successful, error, "ValidicMobile", "setSessionListener", []);
},
/**
* Submits a record to the validic backend
* @param {Record} record - Record to upload.
* @param {string} [img] - Base64 encoded image associated with a record.
* @param {function} successValidate - Invoked on successful submission (not upload).
* @param {FailCallback} errorValidate - Invoked on invalid record or other record submission issues.
*/
submitRecord: function(record, img, successValidate, errorValidate) {
exec(successValidate, errorValidate, "ValidicMobile", "submitRecord", [record, img]);
},
/**
* Submits an array of records to the Validic backend
* @param {Record[]} records - Array of records to be submitted.
* @param {function} successValidate - Callback acknowledging record submission.
* @param {FailCallback} errorValidate - Invoked on submission error. Invalid parameters, etc.
*/
submitRecords: function(records, successValidate, errorValidate) {
exec(successValidate, errorValidate, "ValidicMobile", "submitRecords", [records]);
},
/**
* Indicates there is an active Session with a user
* @param {IsActiveCallback} success - Callback function indicating whether an active session is available
*/
isSessionActive: function(success) {
exec(success, null, "ValidicMobile", "isSessionActive", []);
},
/**
* returns a string representation of the sdk version. 1.3 currently.
* @param {VersionCallback} success - Callback passed the version number of the native library the plugin is
* interacting with.
*/
getVersion: function(success) {
exec(success, null, "ValidicMobile", "getVersion", []);
}
};