Skip to main content

buildfire.services.health

The Buildfire Health Service allows plugins to query HealthKit and Google Health Connect data.

Requirements

Adding Health Feature

note

Android Health Connect Requires sub-features along side the "health" feature in order to read the user health data.

Android Permission Declaration

Android Health Connect requires declaration of permissions for each datatype the app wants to read, to simplify the process we grouped them into main categories. However, iOS does not require such declaration.

In plugin.json, add {"name" : "health"} along with the desired sub-feature in your features array.

caution

Remember to add "health" feature when adding a health sub-feature

Examples

Example of an app that needs to read nutrition records to suggest nutrition daily recommendations:

"features" : [
{"name" : "health"},
{"name" : "health->Android-Nutrition"}
]

Example of an app that keeps track of user workout routine and fitness:

"features" : [
{"name" : "health"},
{"name" : "health->Android-Activity"},
{"name" : "health->Android-BodyMeasurements"}
]

Widget

Include healthAPI.js file in your widget's <head>, right after buildfire.min.js

<head>
<script src="../../../scripts/buildfire.min.js"></script>
<script src="../../../scripts/buildfire/services/health/healthAPI.js"></script>
</head>

Methods

requestAuthorization()

function buildfire.services.health.requestAuthorization(dataTypes<Array>, callback<Function>)

Requests read and write access to a set of data types. This method must be called before using the query methods, even if the authorization has already been given at some point in the past.

Arguments

NameTypeRequiredDescriptionDefault
dataTypesArrayYesArray of data types you want to be granted access to. You can also specify read or write only permissions.N/A
callbackFunctionNoExecuted when the request is complete. Returns an error if something went wrong.N/A

dataTypes

NameTypeRequiredDescriptionDefault
STRING_VALUEStringN/AData type string to request. Grants read and write access.N/A
OBJECT_VALUEObjectN/AObject of separate read and write permissions.N/A

dataTypes[OBJECT_VALUE]

NameTypeRequiredDescriptionDefault
readArrayN/AArray of data type strings to request read access for.N/A
writeArrayN/AArray of data type strings to request write access for.N/A
warning

Currently, we only support reading data

callback(error<String>)

NameTypeDescription
errorStringerror string, null when operation is successful.

Example

// Data types to request read permission for
const dataTypes = [{
read: ['steps', 'height', 'weight']
}];

// Request permissions
buildfire.services.health.requestAuthorization(dataTypes, (err) => {
if (err) console.log(err);
});

query()

function buildfire.services.health.query(options<Object>, callback<Function>)

Fetches all the data points of a certain data type within a certain time window.

Arguments

NameTypeRequiredDescriptionDefault
optionsObjectYesAn object that defines the search parametrs, along with the dataTypes to query.N/A
callbackFunctionNoReturns an array of result objects when the request is sucessful. Returns an error if something went wrong.N/A

options

NameTypeRequiredDescriptionDefault
dataTypestringyesData type to query. See Data Types.N/A
limitnumbernoSets a maximum number of returned values.1000
startDateDateyesStart date for the query.N/A
endDateDateyesEnd date for the query.N/A

callback(error<String>, results<Array>)

NameTypeDescription
errorStringError string, null when operation is successful.
resultsArrayArray of result objects.

results

NameTypeDescription
idStringUnique Identifier.
unitStringThe unit of measure.
valueNumberMeasured value.
sourceNameStringMeasuring device name.
sourceBundleIdStringMeasuring application bundleId.
sourceProductTypeStringMeasuring device product identifier (ex: iPhone 12,2).
sourceOSVersionStringMeasuring device OS version.
startDateStringStarting date string.
endDateStringEnding date string.
deviceNameStringName of the device that generated the data.
deviceModelStringModel of the device that generated the data.
deviceManufacturerStringManufacturer of the device that generated the data.
deviceHardwareVersionStringString representing the hardware version of the device.
deviceSoftwareVersionStringString representing the software version of the device.
deviceFirmwareVersionStringString representing the current version of the firmware running on the device.
metadataObjectMetadata object.

Example

const options = {
dataType: 'steps',
limit: 1000,
startDate: new Date(new Date().getTime() - 3 * 864e5),
endDate: new Date(),
};

buildfire.services.health.query(options, (error, results) => {
if (error) return console.error(error);

results.forEach(result => {
console.log(result);
});
});

queryAggregated()

function buildfire.services.health.queryAggregated(options<Object>, callback<Function>)

Fetches all the data points of a certain data type within a certain time window. Aggregates results into buckets.

Arguments

NameTypeRequiredDescriptionDefault
optionsObjectYesAn object that defines the search parametrs, along with the dataTypes to query.N/A
callbackFunctionNoReturns an array of result objects when the request is sucessful. Returns an error if something went wrong.N/A

options

NameTypeRequiredDescriptionDefault
dataTypeStringyesData type to query. See Supported Data Types.N/A
bucketStringnoTime scale to segment data by.N/A
startDateDateyesStart date for the query.N/A
endDateDateyesEnd date for the query.N/A

callback(error<String>, results<Array>)

NameTypeDescription
errorStringError string, null when operation is successful.
resultsArrayArray of results. If no bucket is passed, returns only the first object.

results

NameTypeDescription
unitStringThe unit of measure
valueNumberMeasured value
startDateStringStarting date string
endDateStringEnding date string

Example

const options = {
dataType: 'steps',
bucket: 'day',
startDate: new Date(new Date().getTime() - 3 * 864e5),
endDate: new Date(),
};

buildfire.services.health.queryAggregated(options, (error, results) => {
if (error) return console.error(error);

results.forEach(result => {
console.log(result);
});
});

Data Types

The Health service supports the following data types:

Body and Physical

Data TypeUnitHealthKitHealth Connect
abdominal_crampsSeverity     
acneSeverity     
activityactivityType                 
activitySummaryN/A     
appetite_changesSeverity     
appleExerciseTimemin     
audio_exposure_eventN/A     
bladder_incontinenceSeverity     
bloatingSeverity     
blood_alcohol_contentpercent     
blood_glucosemg/dL                 
blood_pressuremmHg                 
blood_pressure_diastolicmmHg     
blood_pressure_systolicmmHg     
bmicount     
body_acheSeverity     
breast_painSeverity     
calorieskcal                 
calories.activekcal                 
calories.basalkcal                 
cervical_mucus_qualitySeverity                 
chillsSeverity     
constipationSeverity     
contraceptivesContraceptiveType     
coughingSeverity     
date_of_birth     
diarrheaSeverity     
distancem                 
distance.walkingRunningm     
distance.cyclingm     
distance.wheelchairm     
dizzinessSeverity     
dry_skinSeverity     
electrocardiogram     
electrodermal_activitymcS     
environmental_audio_exposuredB     
environmental_audio_exposure_eventN/A     
faintingSeverity     
fat_percentage%                 
fatigueSeverity     
feverSeverity     
flights_climbedcount     
forced_expiratory_volume1L     
forced_vital_capacityL     
gender     
hair_lossSeverity     
handwashing_eventN/A     
headacheSeverity     
headphone_audio_exposuredB     
headphone_audio_exposure_eventN/A     
heart_ratecount/min                 
heart_rate_variability_sdnnms     
heart_rate.restingcount/min                 
heart_rate.variabilityms                 
heartburnSeverity     
heightm                 
high_heart_rate_eventN/A     
hot_flashesSeverity     
inhaler_usagecount     
insulinIU     
intermenstrual_bleedingSeverity                 
irregular_heart_rhythm_eventN/A     
lactationN/A     
lean_body_masskg                 
loss_of_smellSeverity     
loss_of_tasteSeverity     
low_cardio_eventN/A     
low_heart_rate_eventN/A     
lower_back_painSeverity     
memory_lapseSeverity     
menstrual_flowFlow            
mindfulnessmin     
mindfulnesssec     
mood_changesSeverity     
nauseaSeverity     
night_sweatsSeverity     
number_of_alcoholic_beveragescount     
number_of_times_fallencount     
nutritionnutrition            
nutrition.biotinmcg                 
nutrition.caffeineg                 
nutrition.calciummg                 
nutrition.calorieskcal                 
nutrition.carbs.totalg                 
nutrition.chloridemg                 
nutrition.cholesterolmg                 
nutrition.chromiummcg                 
nutrition.coppermg                 
nutrition.dietary_fiberg                 
nutrition.fat.monounsaturatedg                 
nutrition.fat.polyunsaturatedg                 
nutrition.fat.saturatedg                 
nutrition.fat.unsaturatedg            
nutrition.fat.transg            
nutrition.fat.totalg                 
nutrition.folatemcg                 
nutrition.iodinemcg                 
nutrition.ironmg                 
nutrition.magnesiummg                 
nutrition.molybdenummg                 
nutrition.niacinmg                 
nutrition.pantothenic_acidmg                 
nutrition.phosphorusmg                 
nutrition.potassiummg                 
nutrition.proteing                 
nutrition.riboflavinmg                 
nutrition.seleniummcg                 
nutrition.sodiummg                 
nutrition.sugarg                 
nutrition.thiaminmg                 
nutrition.vitamin_amcg (HK), IU (GF)                 
nutrition.vitamin_B12mcg                 
nutrition.vitamin_B6mg                 
nutrition.vitamin_cmg                 
nutrition.vitamin_Dmcg                 
nutrition.vitamin_Emg                 
nutrition.vitamin_Kmcg                 
nutrition.waterml                 
nutrition.zincmg                 
nutrition.manganesemg            
ovulation_test_resultTestResult                 
oxygen_saturation%                 
peak_expiratory_flow_rateL/min     
pelvic_painSeverity     
peripheral_perfusion_indexpercent     
pregnancyN/A     
pregnancy_test_resultTestResult     
progesterone_test_resultTestResult     
rapid_or_fluttering_heartbeatSeverity     
resp_ratecount/min                 
runny_noseSeverity     
sexual_activityN/A                 
shortness_of_breathSeverity     
sinus_congestionSeverity     
six_minute_walk_test_distancem     
skipped_heartbeatSeverity     
sleepSleepStages                 
sleep_changesSeverity     
sore_throatSeverity     
stair_ascent_speedm/s     
stair_descent_speedm/s     
stairscount     
stand_times     
stepscount                 
temperaturedegC                 
temperature.basaldegC                 
tightness_or_painSeverity     
toothbrushing_eventN/A     
uv_exposurecount     
vaginal_drynessSeverity     
vo2maxml/(kg * min)                 
vomitingSeverity     
waist_circumferencem     
walking_asymmetry_percentagepercent     
walking_double_support_percentagepercent     
walking_speedm/s     
walking_steadinesspercent     
walking_steadiness_eventN/A     
walking_step_lengthcm     
weightkg                 
wheezingSeverity     
menstruation_periodcount            
wheelchair_pushespushes            
floors_climbedfloors            
bone_masskg            
cycling_pedaling_cadencerpm            
elevationm            
powerwatts            
speedm/s            
water_masskg            
steps_cadencem/s            

Units

Severity

ValueDescription
1not present
2mild
3moderate
4severe
0unspecified

OvulationTestResult

ValueDescription
1negative
2luteinizing hormone surge
3indeterminate
4estrogen surge

Flow

ValueDescription
1unspecified
2light
3medium
4heavy
5none

TestResult

ValueDescription
1negative
2positive
3indeterminate

ContraceptiveType

ValueDescription
1unspecified
2implant
3injection
4intrauterine device
5intravaginal ring
6oral
7patch

SleepStages

ValueDescription
0in bed
1unspecified
2awake
3core
4deep
5REM

Activities

Activity NameHealthKitHealth Connect
archery     
badminton              
barre     
baseball              
basketball              
biking              
biking.hand              
biking.mountain     
biking.road     
biking.spinning     
biking.stationary              
biking.utility     
bowling     
boxing              
cooldown     
core_training              
cricket              
crossfit     
curling     
dancing              
dancing.social              
disc_sports     
diving     
elliptical              
fencing              
fishing     
fitness_gaming     
flexibility              
football.american              
football.australian              
football.soccer              
functional_strength     
golf              
gymnastics              
handball              
hiking              
hockey              
horseback_riding     
hunting     
ice_skating              
interval_training     
interval_training.high_intensity              
jump_rope     
kayaking     
kick_scooter     
kickboxing     
lacrosse     
martial_arts              
martial_arts.mixed     
meditation     
mixed_metabolic_cardio     
other              
paddle_sports              
pickleball              
pilates              
play     
preparation_and_recovery     
racquetball              
rock_climbing              
rowing              
rowing.machine              
rugby              
running              
running.jogging     
running.sand     
running.treadmill              
sailing              
scuba_diving              
skateboarding     
skating              
skating.cross     
skating.indoor     
skating.inline     
skiing              
skiing.back_country     
skiing.cross_country     
skiing.downhill     
skiing.kite     
skiing.roller     
sledding     
sleep     
sleep.awake     
sleep.deep     
sleep.inBed     
sleep.light     
sleep.rem     
snow_sports     
snowboarding              
snowmobile     
snowshoeing              
softball     
squash              
stair_climbing              
stair_climbing.machine              
stairs              
standup_paddleboarding     
strength_training              
surfing              
swimming     
swimming.open_water              
swimming.pool              
table_tennis              
tai_chi     
tennis              
track_and_field              
volleyball              
volleyball.beach     
volleyball.indoor     
wakeboarding     
walking              
walking.fitness     
walking.nordic     
walking.stroller     
walking.treadmill     
water_fitness     
water_polo     
water_sports     
weightlifting              
wheelchair              
wheelchair.runpace     
wheelchair.walkpace     
windsurfing     
wrestling     
yoga     

Android Permission Sub-Features

caution

To reduce the likelihood of Google rejecting your app, only include the necessary sub-features.

Android Permission Sub-FeaturesDatatypes
health->Android-Activityactivity, steps, calories, calories.active, vo2max, floors_climbed, distance, power, speed, elevation, wheelchair_pushes, cycling_pedaling_cadence, steps_cadence
health->Android-BodyMeasurementsweight, height, calories.basal, fat_percentage, water_mass, lean_body_mass, bone_mass
health->Android-Vitalstemperature.basal, blood_glucose, blood_pressure, temperature, heart_rate, heart_rate.variability, oxygen_saturation, resp_rate, heart_rate.resting
health->Android-CycleTrackingcervical_mucus_quality, intermenstrual_bleeding, menstruation_period, menstrual_flow, ovulation_test_result, sexual_activity
health->Android-Nutritionnutrition, nutrition.water, nutrition.biotin, nutrition.caffeine, nutrition.calcium, nutrition.carbs.total, nutrition.chloride, nutrition.cholesterol, nutrition.chromium, nutrition.copper, nutrition.dietary_fiber, nutrition.fat.monounsaturated, nutrition.fat.polyunsaturated, nutrition.fat.saturated, nutrition.fat.unsaturated, nutrition.fat.trans, nutrition.fat.total, nutrition.folate, nutrition.iodine, nutrition.iron, nutrition.magnesium, nutrition.molybdenum, nutrition.niacin, nutrition.pantothenic_acid, nutrition.phosphorus, nutrition.potassium, nutrition.protein, nutrition.riboflavin, nutrition.selenium, nutrition.sodium, nutrition.sugar, nutrition.thiamin, nutrition.vitamin_a, nutrition.vitamin_B12, nutrition.vitamin_B6, nutrition.vitamin_c, nutrition.vitamin_D, nutrition.vitamin_E, nutrition.vitamin_K, nutrition.zinc
health->Android-Sleepsleep

Electrocardiograms (iOS Only)

The health service can query for electrocardiogram as a data type. Electrocardiogram samples contain the following data:

NameTypeDescription
algorithmVersionNumberVersion numbers for the algorithm Apple Watch uses to generate an ECG reading
averageHeartRateNumberAverage heart rate over ECG duration
classificationStringECG’s classification (ex: "SinusRhythm")
samplingFrequencyNumberThe frequency at which the voltage is sampled
voltageMeasurementsArrayCollection of voltage values representing waveforms
{
id: "ECF3C1B4-AEFA-4656-B7F2-B110951835EA",
startDate: "2021-06-06T11:11:43.000Z",
endDate: "2021-06-06T11:12:13.000Z",
algorithmVersion: 1,
averageHeartRate: 62,
classification: "SinusRhythm",
samplingFrequency: 513.7265625,
sourceName: "ECG",
sourceBundleId: "com.apple.NanoHeartRhythm",
sourceProductType: "Watch5,4",
sourceOSVersion: "7.4.1",
deviceName: "Apple Watch",
deviceModel: "Watch",
deviceManufacturer: "Apple Inc.",
deviceLocalIdentifier: "",
deviceHardwareVersion: "Watch5,4",
deviceSoftwareVersion: "7.4.1",
deviceFirmwareVersion: "",
voltageMeasurements: [
[0,-0.00016570074462890624],
[0.0019465608224219476,-0.00019473405456542969],
[0.003893121644843895,-0.00021828952026367186],
[0.005839682467265842,-0.00023469168090820312],
[0.00778624328968779,-0.00024280212402343749]
// ...
]
}