Health Tracking

Last updated: November 2026

Device setup on the participant's phone (Apple Health, Health Connect) and sync behaviour are described in Apple Health & Google Health Connect.

The Health Tracking module lets a coaching use health data from Apple Health (iOS) or Health Connect (Android): steps, sleep, heart rate and more. Setting it up has two parts:

Where What you do
CoachStudio Designer → App Modules → Health Tracking choose the data types, decide when they are paired and collected, look up the coach commands
CoachStudio Coaching Editor → your coaching run the commands in a Micro Dialog, read the collected data and use it in messages and rules

Enable, pair, collect

Health data in a coaching goes through three states:

  1. Enable — you choose which data types exist in this coaching. Disabled types are never requested from the participant.
  2. Pair — the participant grants permission for a data type in Apple Health or Health Connect: at onboarding, when the coaching sends a pairing command, or from the app's Health Tracking screen. Pairing only requests the permission; nothing is read yet.
  3. Collect — paired data is read on the phone and uploaded to Pathmate. Collecting needs a one-time configuration of the coaching (see Configure the credentials).

Part 1: CoachStudio Designer

In the CoachStudio Designer, open App Modules → Health Tracking. Two buttons at the top right help you:

  • Guide — a short step-by-step setup that walks you through data types, pairing, collecting and the participant's options. Use it the first time.
  • Coach commands — all commands for this coaching, ready to copy. You paste them into a Micro Dialog in the CoachStudio Coaching Editor, see Part 2.

Afterwards you manage everything in the table on the Data tab. The Screens tab holds the onboarding text shown before the phone's permission dialog and the option Participants control pairing and collecting themselves, which gives the Health Tracking screen a Pair button per unpaired type and a collecting toggle per paired one.

Health Tracking in the CoachStudio Designer: Data tab

The Data tab

The Data tab is one table with all data types, grouped by category, and one column per state:

Column Meaning
Enabled The data type is used in this coaching. Only enabled types appear in the other columns, in the coach commands and on the participant's screen. Disabled types are never requested from the participant.
Pairing at onboarding On: the participant is asked for this permission right after sign-up. Off: nothing is asked until the coaching runs a pairing command (or the participant pairs on the Health Tracking screen).
Collecting after setup On: collecting starts automatically once the type is paired and the configuration command has run (see Configure the credentials). Off: collecting starts only with a start-collecting command or from the Health Tracking screen.

The All data types row switches a whole column at once. Click Save at the bottom of the page to apply your changes.

Available data types

Category Data type Name in commands
Activity Steps steps
Activity Distance (walk, run, cycle) distance
Sleep Sleep (duration, stages, start & end) sleep
Sleep Respiratory rate respiratoryRate
Vitals Heart rate heartRate
Vitals Heart rate variability heartRateVariability
Vitals Resting heart rate restingHeartRate
Vitals Blood glucose bloodGlucose

Heart rate variability is measured differently per platform: Apple Health reports SDNN, Health Connect reports RMSSD. The values are not directly comparable across platforms; the ? icon next to the type says so.

Part 2: CoachStudio Coaching Editor

In the CoachStudio Coaching Editor, the coaching sends the commands to the app and reads the collected data. The app uploads the data directly to Pathmate; the coaching does not write it — it only reads it, turns the values it needs into variables and uses them in messages and rules.

1. Add the commands to a Micro Dialog

Add each command as a message in a Micro Dialog and mark it as a command message (see Commands). The participant does not see these messages; the app executes them.

A typical order: a decision point that creates the health secret, then the configuration command, then the pairing and collecting commands — here each one after a question to the participant.

Micro Dialog with health tracking commands

Configure the credentials

Required once per participant, before anything can be collected:

configure-health-tracking $participantIdentifier $sensing_pmHealthSecret

Run this command first. Without it, pairing works but nothing is collected.

$participantIdentifier is a system variable. $sensing_pmHealthSecret holds the participant's health secret. To create it, first add the variable $sensing_pmHealthSecret in the Variables tab. Then add a decision point before this command, in the same Micro Dialog, with a rule of the type execute javascript in x and store values but result is … (as in step 4) and enter this script. It creates a random 64-character string and stores it in $sensing_pmHealthSecret:

/*
  Creates a random secret for the PM health tracking module
  and stores the same in the variable $sensing_pmHealthSecret
*/

function generateRandomString(length) {
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  const charactersLength = characters.length

  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength))
  }

  return result
}

const randomString = generateRandomString(64)

const o = {
  sensing_pmHealthSecret: randomString
}
o

Pairing

Pair all enabled data types:

connect-health-tracking

Pair selected data types by name:

connect-health-tracking steps distance sleep

Pairing only requests the permission in Apple Health or Health Connect. Collecting then starts automatically (if Collecting after setup is on), from the Health Tracking screen or with a start-collecting command.

Collecting

Start collecting all enabled data types:

start-health-tracking

Start collecting selected data types by name:

start-health-tracking steps distance sleep

Stop collecting (all data types):

stop-health-tracking

Names that are not enabled in the CoachStudio Designer are ignored. Each start and stop is recorded with the uploaded data as a collection event (see What the app uploads), with server as its initiator.

2. Create the JSON data object pmHealth

In the coaching, open the JSON Data tab and create a new entry:

  • Name: pmHealth — exactly this name.
  • Access setting: externally readable. The default is internal only.

The entry only needs to be readable from outside: the app writes the data through a separate interface, not through the coaching.

3. Create the variables

In the Variables tab, create one variable for every value you want to use, for example $sensing_healthStepCountToday. The script in step 4 can only store values in variables that already exist.

What the app uploads

Every uploaded entry is { timestamp, type, uid?, data }: timestamp is the time of the data in epoch milliseconds (never the time of the upload), type names the data type and its granularity, uid identifies a row the app may replace later, and data is a JSON string with the columns below. The suffix of the type says what a row holds: no suffix for a record as Apple Health or Health Connect stored it, Daily for one value per local day, 10Min for a 10-minute slot.

Data type Type One row per Columns in data
Steps stepCount record of the health app start, end, deviceId, platform, stepCount
Steps stepCountDaily day and device, plus the platform total of the day with deviceId 0 date, deviceId, platform, stepCount
Distance distance record start, end, deviceId, platform, activity (iOS: walkingRunning or cycling), meters
Distance distanceDaily day, device and (iOS) activity, plus the platform total with deviceId 0 date, deviceId, platform, activity, meters
Sleep sleep stage segment part, start, end, deviceId, platform, stage
Sleep sleepDaily night, dated by the day it ends: one row per device, on Android also the platform night with deviceId 0 date, bedTime, wakeTime, deviceId, platform, minutesAsleep, minutesInBed
Heart rate heartRate10Min 10-minute slot and device (no platform row) start, deviceId, platform, bpm, min, max
Respiratory rate respiratoryRate measurement deviceId, platform, breathsPerMinute
Heart rate variability heartRateVariability measurement deviceId, platform, sdnn (iOS) or rmssd (Android)
Resting heart rate restingHeartRate measurement deviceId, platform, bpm
Blood glucose bloodGlucose measurement deviceId, platform, mmolPerLiter

Good to know:

  • deviceId points to an entry of the participant's device list (below). 0 is the platform itself: the total Apple Health or Health Connect computes across all apps and devices. Only steps, distance and (Android) sleep have platform rows; heart rate and the measurements exist per device only.
  • platform is 1 for Apple Health and 2 for Health Connect on every row.
  • date is the local day of the phone. The device list carries timeZone events with the phone's time zone.
  • Latest version wins. The app re-sends a day total, a night or a slot when its value changes, dated later than the version before, and replaces a changed record under the same uid. A reader keeps the row with the latest timestamp per type and uid, or per type, date (or start), deviceId and activity for the daily and slot rows.
  • Values are rounded: meters and mmolPerLiter to two decimals, bpm, min, max, sdnn, rmssd and breathsPerMinute to one, steps and minutes to whole numbers.

Devices and events: $$pmHealthConfiguration$$

The app posts the participant's device list and collection history separately. In a script, $$pmHealthConfiguration$$ is replaced by it:

{
  "devices": [
    { "id": 0, "platform": 2, "app": "com.google.android.apps.healthdata", "type": "platform", "manufacturer": "Google" },
    { "id": 1, "platform": 2, "app": "com.fitbit.FitbitMobile", "type": "watch", "manufacturer": "Google", "model": "Google Pixel Watch 3" },
    { "id": 2, "platform": 2, "app": "com.sec.android.app.shealth", "type": "phone", "manufacturer": "samsung", "model": "SM-S921B" }
  ],
  "events": [
    { "event": "collection-start", "platform": 2, "scope": "global", "initiator": "server", "dataTypes": ["stepCount", "sleep"], "timestamp": 1762932000000 },
    { "event": "timeZone", "timeZone": "Europe/Zurich", "timestamp": 1762932001000 }
  ]
}
  • A device is one entry per app and hardware: app is the bundle identifier (iOS) or package name (Android) of the app that wrote the data, type is watch, band, ring, phone, scale, manual (typed in by hand), other or unknown. The same watch written through two apps is two entries. Common apps: com.fitbit.FitbitMobile (Fitbit), com.sec.android.app.shealth (Samsung Health), com.garmin.android.apps.connectmobile (Garmin Connect), com.withings.wiscale2 (Withings), com.google.android.apps.fitness (Google Fit), com.apple.health.<id> (the iPhone or Apple Watch itself).
  • Events record every start and stop of the collection: scope is a data type or global, initiator is participant or server, and timeZone events carry the phone's time zone.

4. Read the data in a decision point

Add a decision point to a Micro Dialog and give it a rule with the type execute javascript in x and store values but result is …. The rule runs the JavaScript in Rule [x]; click Edit next to it to enter the code.

Decision point rule that runs JavaScript and stores values

The script returns an object: every key is the name of a variable, and its value is stored in that variable.

Example: today's step count

This example stores today's step count, as Apple Health or Health Connect counts it across all apps and devices, in sensing_healthStepCountToday:

//+ moment
import moment from 'moment'

const sensorData = {
  $$SENSOR_DATA$$: 'pmHealth',
  types: ['stepCountDaily'],
  startRelativeInclusive: '2d',
  endRelativeExclusive: '0m'
}

const today = moment().format('YYYY-MM-DD')

const todayRows = sensorData
  .map((s) => ({ ...JSON.parse(s.data), timestamp: Number(s.timestamp) }))
  .filter((d) => d.deviceId === 0 && d.date === today)

const latest = todayRows.reduce(
  (best, d) => (!best || d.timestamp > best.timestamp ? d : best),
  null
)

const o = {
  sensing_healthStepCountToday: latest ? latest.stepCount : -1
}
o

How it works:

  • The sensorData object is replaced by the stored data before the script runs: $$SENSOR_DATA$$ names the JSON data object (pmHealth), types the types to read, startRelativeInclusive / endRelativeExclusive the time window (here: the last two days up to now).
  • Each entry carries its values as a JSON string in data; for a day total these are date, deviceId, platform and stepCount. deviceId 0 is the platform total across all apps and devices; the other rows are the totals of single devices.
  • The app re-sends the day total whenever it changes, dated later than the version before, so the script keeps the row with the latest timestamp.
  • The last line (o) is the result. -1 means: no data for today yet.
  • //+ moment makes the moment.js library available for date handling.

All data types at once

This script reads today's values of all data types and stores each one in a simple variable. Use it as a starting point: copy it into the rule and delete the lines of the values you don't need.

For every data type, the script stores two values:

  • all devices — for steps and distance the number Apple Health / Health Connect reports, combined over all apps and devices (deviceId 0); for sleep the platform night on Android, else the longest night of any device; for heart rate and the measurements the average over the rows of every device, since the platforms compute no combined value for them
  • selected app — only the data of one app, e.g. the participant's Fitbit; same variable name with Selected at the end, e.g. sensing_healthStepCountTodaySelected
Data type Variable (all devices) Value
Steps sensing_healthStepCountToday step total of the day
Distance sensing_healthDistanceMetersToday distance total of the day in meters (iOS: walking/running + cycling)
Sleep sensing_healthMinutesAsleepLastNight minutes asleep in the night ending today
Sleep sensing_healthMinutesInBedLastNight minutes in bed in that night
Heart rate sensing_healthHeartRateAvgToday average bpm of today (10-minute slots)
Heart rate sensing_healthHeartRateMinToday lowest bpm of today
Heart rate sensing_healthHeartRateMaxToday highest bpm of today
Respiratory rate sensing_healthRespiratoryRateAvgToday average breaths per minute of today
Heart rate variability sensing_healthHrvAvgToday average HRV of today in ms (RMSSD on Android, SDNN on iOS)
Resting heart rate sensing_healthRestingHeartRateAvgToday average resting bpm of today
Blood glucose sensing_healthBloodGlucoseAvgToday average blood glucose of today in mmol/L

Create all variables you keep in the Variables tab first (see step 3). Every value is -1 when there is no data for today.

Two settings at the top of the script choose the selected app:

  • SELECTED_APP — the identifier of the app as listed under devices in $$pmHealthConfiguration$$, e.g. 'com.fitbit.FitbitMobile', 'com.sec.android.app.shealth'
  • SELECTED_DEVICE_MODEL — optionally one device model of that app, e.g. 'Google Pixel Watch 3'; null accepts every device of the app

Good to know:

  • Sleep counts the night that ended today. On iOS there is no combined night across devices; the script then uses the longest night of any device.
  • Several devices of the selected app (a watch and a phone, say): steps and distance take the device with the largest total, sleep the longest night, heart rate and the measurements average over all of them.
  • Today is the server's day; the rows are dated by the phone's local day. Around midnight the two may differ when the participant is in another time zone (the timeZone events in $$pmHealthConfiguration$$ say which).
//+ moment
import moment from 'moment'

const SELECTED_APP = 'com.fitbit.FitbitMobile'
const SELECTED_DEVICE_MODEL = null

const sensorData = {
  $$SENSOR_DATA$$: 'pmHealth',
  types: [
    'stepCountDaily',
    'distanceDaily',
    'sleepDaily',
    'heartRate10Min',
    'respiratoryRate',
    'heartRateVariability',
    'restingHeartRate',
    'bloodGlucose'
  ],
  startRelativeInclusive: '2d',
  endRelativeExclusive: '0m'
}

const PLATFORM = 0
const DAY = 'YYYY-MM-DD'
const today = moment().format(DAY)

const registry = $$pmHealthConfiguration$$ || {}
const selectedDeviceIds = (registry.devices || [])
  .filter((d) => d.id !== PLATFORM && d.app === SELECTED_APP)
  .filter((d) => !SELECTED_DEVICE_MODEL || d.model === SELECTED_DEVICE_MODEL)
  .map((d) => d.id)

const rows = sensorData.map((s) => ({
  ...JSON.parse(s.data),
  type: s.type,
  uid: s.uid,
  timestamp: Number(s.timestamp)
}))

const rowsOf = (type) => rows.filter((r) => r.type === type)
const platformRows = (list) => list.filter((r) => r.deviceId === PLATFORM)
const deviceRows = (list) => list.filter((r) => r.deviceId !== PLATFORM)
const selectedRows = (list) =>
  list.filter((r) => selectedDeviceIds.includes(r.deviceId))

// The app re-sends a changed row dated later than the version before: the latest row per key wins
const latestPerKey = (list, keyOf) => {
  const latest = {}
  list.forEach((r) => {
    const key = keyOf(r)
    if (!latest[key] || r.timestamp > latest[key].timestamp) latest[key] = r
  })
  return Object.values(latest)
}

const average = (list, valueOf) =>
  list.reduce((sum, r) => sum + valueOf(r), 0) / list.length
const orMissing = (list, compute) => (list.length ? compute() : -1)

// Steps and distance: one total per day and device (+ activity on iOS), deviceId 0 for the platform total;
// with several devices of the selected app, the device with the largest total
const dailyTotal = (list, valueOf) => {
  const totals = latestPerKey(
    list.filter((r) => r.date === today),
    (r) => [r.deviceId, r.activity || ''].join('|')
  )
  const byDevice = {}
  totals.forEach((r) => {
    byDevice[r.deviceId] = (byDevice[r.deviceId] || 0) + valueOf(r)
  })
  const values = Object.values(byDevice)
  return values.length ? Math.round(Math.max(...values)) : -1
}

// Sleep: one night per wake day and device, the longest night among the given rows
const night = (list) =>
  latestPerKey(
    list.filter((r) => r.date === today),
    (r) => r.deviceId
  )
    .filter((r) => r.minutesInBed > 0)
    .reduce((best, r) => (!best || r.minutesAsleep > best.minutesAsleep ? r : best), null)

const nightValues = (list) => {
  const n = night(list)
  return { asleep: n ? n.minutesAsleep : -1, inBed: n ? n.minutesInBed : -1 }
}

// Heart rate: 10-minute slots per device, start = slot start in epoch milliseconds
const heartRateValues = (list) => {
  const slots = latestPerKey(
    list.filter((r) => moment(r.start).format(DAY) === today),
    (r) => [r.deviceId, r.start].join('|')
  )
  return {
    avg: orMissing(slots, () => Math.round(average(slots, (r) => r.bpm))),
    min: orMissing(slots, () => Math.min(...slots.map((r) => r.min))),
    max: orMissing(slots, () => Math.max(...slots.map((r) => r.max)))
  }
}

// Measurements: one row per measurement, timestamp = time of the measurement, uid = its id
const sampleAverage = (list, valueOf, decimals) => {
  const samples = latestPerKey(
    list.filter(
      (r) => moment(r.timestamp).format(DAY) === today && valueOf(r) !== undefined
    ),
    (r) => r.uid || [r.deviceId, r.timestamp].join('|')
  )
  return orMissing(samples, () =>
    Number(average(samples, valueOf).toFixed(decimals))
  )
}

const hrvValue = (r) => (r.rmssd !== undefined ? r.rmssd : r.sdnn)

const steps = rowsOf('stepCountDaily')
const distance = rowsOf('distanceDaily')
const sleep = rowsOf('sleepDaily')
const heartRate = rowsOf('heartRate10Min')
const respiratoryRate = rowsOf('respiratoryRate')
const hrv = rowsOf('heartRateVariability')
const restingHeartRate = rowsOf('restingHeartRate')
const bloodGlucose = rowsOf('bloodGlucose')

const platformNight = nightValues(platformRows(sleep))
const allNight =
  platformNight.asleep !== -1 ? platformNight : nightValues(deviceRows(sleep))
const selectedNight = nightValues(selectedRows(sleep))
const allHeartRate = heartRateValues(heartRate)
const selectedHeartRate = heartRateValues(selectedRows(heartRate))

const o = {
  sensing_healthStepCountToday: dailyTotal(platformRows(steps), (r) => r.stepCount),
  sensing_healthStepCountTodaySelected: dailyTotal(selectedRows(steps), (r) => r.stepCount),
  sensing_healthDistanceMetersToday: dailyTotal(platformRows(distance), (r) => r.meters),
  sensing_healthDistanceMetersTodaySelected: dailyTotal(selectedRows(distance), (r) => r.meters),
  sensing_healthMinutesAsleepLastNight: allNight.asleep,
  sensing_healthMinutesAsleepLastNightSelected: selectedNight.asleep,
  sensing_healthMinutesInBedLastNight: allNight.inBed,
  sensing_healthMinutesInBedLastNightSelected: selectedNight.inBed,
  sensing_healthHeartRateAvgToday: allHeartRate.avg,
  sensing_healthHeartRateAvgTodaySelected: selectedHeartRate.avg,
  sensing_healthHeartRateMinToday: allHeartRate.min,
  sensing_healthHeartRateMinTodaySelected: selectedHeartRate.min,
  sensing_healthHeartRateMaxToday: allHeartRate.max,
  sensing_healthHeartRateMaxTodaySelected: selectedHeartRate.max,
  sensing_healthRespiratoryRateAvgToday: sampleAverage(respiratoryRate, (r) => r.breathsPerMinute, 1),
  sensing_healthRespiratoryRateAvgTodaySelected: sampleAverage(selectedRows(respiratoryRate), (r) => r.breathsPerMinute, 1),
  sensing_healthHrvAvgToday: sampleAverage(hrv, hrvValue, 1),
  sensing_healthHrvAvgTodaySelected: sampleAverage(selectedRows(hrv), hrvValue, 1),
  sensing_healthRestingHeartRateAvgToday: sampleAverage(restingHeartRate, (r) => r.bpm, 0),
  sensing_healthRestingHeartRateAvgTodaySelected: sampleAverage(selectedRows(restingHeartRate), (r) => r.bpm, 0),
  sensing_healthBloodGlucoseAvgToday: sampleAverage(bloodGlucose, (r) => r.mmolPerLiter, 1),
  sensing_healthBloodGlucoseAvgTodaySelected: sampleAverage(selectedRows(bloodGlucose), (r) => r.mmolPerLiter, 1)
}
o

5. Use the values

After the decision point has run, the variables can be used like any other variable:

  • in a message text: Today you walked $sensing_healthStepCountToday steps.
  • in the rules of a later decision point, for example to react when the participant reaches 5,000 steps (send a message, unlock an achievement …).

Message text using the step count variable

The values are only as fresh as the last time the script ran. Run the decision point right before you need the value, for example at the start of the Micro Dialog that talks about it.