From 7164e156e505632753d0d5b4cadb709d0350ed43 Mon Sep 17 00:00:00 2001 From: SF Date: Wed, 18 Nov 2026 21:00:15 +0800 Subject: [PATCH] feat: wrap alpha HC APIs (mindfulness, skin temp, intensity, matchmaking, PHR) Add MindfulnessSession, SkinTemperature and ActivityIntensity record CRUD, getFeatureStatus, Matchmaking helpers, and Personal Health Record (MedicalDataSource / MedicalResource) APIs against connect-client 1.2.0-alpha06. Co-authored-by: Cursor --- README.md | 110 ++++++-- .../AndroidHealthConnectModule.kt | 197 ++++++++++++++- .../androidhealthconnect/FeatureSupport.kt | 68 +++++ .../com/androidhealthconnect/PhrMapper.kt | 187 ++++++++++++++ .../com/androidhealthconnect/RecordMapper.kt | 123 +++++++++ .../androidhealthconnect/RecordMapperTest.kt | 27 ++ src/NativeAndroidHealthConnect.ts | 38 +++ src/__tests__/index.test.tsx | 71 ++++++ src/__tests__/recordTypes.test.ts | 51 +++- src/index.tsx | 124 ++++++++++ src/types.ts | 234 +++++++++++++++++- 11 files changed, 1197 insertions(+), 33 deletions(-) create mode 100644 android/src/main/java/com/androidhealthconnect/FeatureSupport.kt create mode 100644 android/src/main/java/com/androidhealthconnect/PhrMapper.kt diff --git a/README.md b/README.md index 7324f29..3205c06 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ Official notes ([full changelog](https://developer.android.com/jetpack/androidx/ | **1.2.0-alpha01** | 2025-07-30 | Skin temperature / mindfulness compat; activity intensity (Android 14+) | | **1.1.0** (stable) | 2025-10-08 | First stable `connect-client` | -JS API still covers the [19 record types](#supported-record-types) below. Alpha-only APIs (matchmaking, mindfulness, skin temperature, activity intensity, PHR) are **not** wrapped yet. +JS API covers the [22 record types](#supported-record-types) below, plus feature checks, Matchmaking, and Personal Health Record (PHR) helpers. Feature-gated types require `getFeatureStatus(...) === 'available'` on the device. ## Installation @@ -271,27 +271,77 @@ await deleteRecordsById('Steps', ['record-id-1', 'record-id-2']); ## Supported record types -| Record type | Read | Write | -|---|---|---| -| `Steps` | ✅ | ✅ | -| `HeartRate` | ✅ | ✅ | -| `SleepSession` | ✅ | ✅ | -| `ActiveCaloriesBurned` | ✅ | ✅ | -| `TotalCaloriesBurned` | ✅ | ✅ | -| `Distance` | ✅ | ✅ | -| `Weight` | ✅ | ✅ | -| `Height` | ✅ | ✅ | -| `BloodPressure` | ✅ | ✅ | -| `BloodGlucose` | ✅ | ✅ | -| `OxygenSaturation` | ✅ | ✅ | -| `BodyTemperature` | ✅ | ✅ | -| `BodyFat` | ✅ | ✅ | -| `Hydration` | ✅ | ✅ | -| `ExerciseSession` | ✅ | ✅ | -| `RestingHeartRate` | ✅ | ✅ | -| `RespiratoryRate` | ✅ | ✅ | -| `FloorsClimbed` | ✅ | ✅ | -| `ElevationGained` | ✅ | ✅ | +| Record type | Read | Write | Notes | +|---|---|---|---| +| `Steps` | ✅ | ✅ | | +| `HeartRate` | ✅ | ✅ | | +| `SleepSession` | ✅ | ✅ | | +| `ActiveCaloriesBurned` | ✅ | ✅ | | +| `TotalCaloriesBurned` | ✅ | ✅ | | +| `Distance` | ✅ | ✅ | | +| `Weight` | ✅ | ✅ | | +| `Height` | ✅ | ✅ | | +| `BloodPressure` | ✅ | ✅ | | +| `BloodGlucose` | ✅ | ✅ | | +| `OxygenSaturation` | ✅ | ✅ | | +| `BodyTemperature` | ✅ | ✅ | | +| `BodyFat` | ✅ | ✅ | | +| `Hydration` | ✅ | ✅ | | +| `ExerciseSession` | ✅ | ✅ | | +| `RestingHeartRate` | ✅ | ✅ | | +| `RespiratoryRate` | ✅ | ✅ | | +| `FloorsClimbed` | ✅ | ✅ | | +| `ElevationGained` | ✅ | ✅ | | +| `MindfulnessSession` | ✅ | ✅ | Requires `getFeatureStatus('mindfulnessSession')` | +| `SkinTemperature` | ✅ | ✅ | Requires `getFeatureStatus('skinTemperature')` | +| `ActivityIntensity` | ✅ | ✅ | Requires `getFeatureStatus('activityIntensity')` | + +### Feature-gated APIs + +```ts +import { + getFeatureStatus, + checkIfMatchmakingIsPossible, + launchMatchmaking, + createMedicalDataSource, + upsertMedicalResources, + readMedicalResources, + MedicalResourceType, +} from '@solutionforest/android-health-connect'; + +// Feature availability (skin temperature, mindfulness, activity intensity, matchmaking, PHR, …) +const skinTemp = await getFeatureStatus('skinTemperature'); // 'available' | 'unavailable' + +// Matchmaking (experimental) — discover apps/devices that can write data you can read +if ((await getFeatureStatus('matchmaking')) === 'available') { + const { isMatchmakingPossible } = await checkIfMatchmakingIsPossible({ + recordTypes: ['Steps', 'HeartRate'], + }); + if (isMatchmakingPossible) { + await launchMatchmaking({ recordTypes: ['Steps', 'HeartRate'] }); + } +} + +// Personal Health Record / medical (experimental) — FHIR MedicalDataSource + MedicalResource +if ((await getFeatureStatus('personalHealthRecord')) === 'available') { + const source = await createMedicalDataSource({ + displayName: 'Clinic FHIR', + fhirBaseUri: 'https://example.com/fhir/', + fhirVersion: { major: 4, minor: 0, patch: 1 }, + }); + await upsertMedicalResources([ + { + dataSourceId: source.id, + fhirVersion: source.fhirVersion, + data: JSON.stringify({ resourceType: 'AllergyIntolerance', id: '1', /* … */ }), + }, + ]); + const page = await readMedicalResources({ + medicalResourceType: MedicalResourceType.ALLERGIES_INTOLERANCES, + medicalDataSourceIds: [source.id], + }); +} +``` ## Upgrade reminders @@ -340,7 +390,21 @@ Maintainers: CI, CodeQL, Release, and the weekly version-check Action run on **G | `deleteRecordsById(type, ids)` | `Promise` | Delete by IDs | | `readSteps(options?)` | `Promise>` | Convenience helper | | `readHeartRate(options?)` | … | Convenience helper | -| *(and one per record type)* | | | +| *(and one per record type, including Mindfulness / SkinTemperature / ActivityIntensity)* | | | + +### Features / Matchmaking / PHR + +| Function | Returns | Description | +|---|---|---| +| `getFeatureStatus(feature)` | `Promise<'available' \| 'unavailable'>` | Check HC feature flags | +| `checkIfMatchmakingIsPossible(opts?)` | `Promise<{ isMatchmakingPossible }>` | Whether Matchmaking UI has candidates | +| `launchMatchmaking(opts?)` | `Promise` | Launch Matchmaking activity | +| `createMedicalDataSource(req)` | `Promise` | Create FHIR data source | +| `getMedicalDataSources(req?)` | `Promise` | List medical data sources | +| `deleteMedicalDataSourceWithData(id)` | `Promise` | Delete source + its resources | +| `upsertMedicalResources(reqs)` | `Promise` | Insert/update FHIR resources | +| `readMedicalResources(req)` | `Promise` | Paged medical resource read | +| `deleteMedicalResources(req)` | `Promise` | Delete by IDs or filters | ## Contributing diff --git a/android/src/main/java/com/androidhealthconnect/AndroidHealthConnectModule.kt b/android/src/main/java/com/androidhealthconnect/AndroidHealthConnectModule.kt index a8b4da6..ff46bdd 100644 --- a/android/src/main/java/com/androidhealthconnect/AndroidHealthConnectModule.kt +++ b/android/src/main/java/com/androidhealthconnect/AndroidHealthConnectModule.kt @@ -4,8 +4,12 @@ import android.app.Activity import android.content.Intent import android.net.Uri import android.util.Log +import androidx.health.connect.client.ExperimentalMatchmakingApi import androidx.health.connect.client.HealthConnectClient import androidx.health.connect.client.PermissionController +import androidx.health.connect.client.feature.ExperimentalPersonalHealthRecordApi +import androidx.health.connect.client.matchmaking.MatchmakingRequest +import androidx.health.connect.client.records.metadata.DataOrigin import com.facebook.react.bridge.ActivityEventListener import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.Promise @@ -20,12 +24,14 @@ import org.json.JSONArray import org.json.JSONObject import java.time.Instant +@OptIn(ExperimentalMatchmakingApi::class, ExperimentalPersonalHealthRecordApi::class) class AndroidHealthConnectModule(reactContext: ReactApplicationContext) : NativeAndroidHealthConnectSpec(reactContext), ActivityEventListener { companion object { const val NAME = NativeAndroidHealthConnectSpec.NAME private const val PERMISSION_REQUEST_CODE = 21432 + private const val MATCHMAKING_REQUEST_CODE = 21433 private const val TAG = "AndroidHealthConnect" private const val HC_PACKAGE = "com.google.android.apps.healthdata" private const val HC_PLAY_STORE_URI = @@ -47,6 +53,10 @@ class AndroidHealthConnectModule(reactContext: ReactApplicationContext) : @Volatile private var pendingPermissionPromise: Promise? = null + /** Pending promise for an in-flight matchmaking flow. */ + @Volatile + private var pendingMatchmakingPromise: Promise? = null + init { reactContext.addActivityEventListener(this) } @@ -215,6 +225,150 @@ class AndroidHealthConnectModule(reactContext: ReactApplicationContext) : } } + // ─── Feature availability ───────────────────────────────────────────────── + + override fun getFeatureStatus(feature: String, promise: Promise) { + if (!isAvailable(promise)) return + moduleScope.launch { + try { + promise.resolve(FeatureSupport.getStatus(healthConnectClient, feature)) + } catch (e: Exception) { + promise.reject("FEATURE_STATUS_ERROR", e.message, e) + } + } + } + + // ─── Matchmaking ────────────────────────────────────────────────────────── + + override fun checkIfMatchmakingIsPossible(options: String, promise: Promise) { + if (!isAvailable(promise)) return + moduleScope.launch { + try { + val request = parseMatchmakingRequest(JSONObject(options)) + val response = healthConnectClient.checkIfMatchmakingIsPossible(request) + promise.resolve( + JSONObject().put("isMatchmakingPossible", response.isMatchmakingPossible).toString() + ) + } catch (e: Exception) { + Log.e(TAG, "checkIfMatchmakingIsPossible error", e) + promise.reject("MATCHMAKING_ERROR", e.message, e) + } + } + } + + override fun launchMatchmaking(options: String, promise: Promise) { + val activity = reactApplicationContext.currentActivity + if (activity == null) { + promise.reject("NO_ACTIVITY", "No foreground Activity available") + return + } + if (!isAvailable(promise)) return + moduleScope.launch { + try { + val request = parseMatchmakingRequest(JSONObject(options)) + val intent = healthConnectClient.createMatchmakingIntent(request) + pendingMatchmakingPromise = promise + activity.runOnUiThread { + activity.startActivityForResult(intent, MATCHMAKING_REQUEST_CODE) + } + } catch (e: Exception) { + Log.e(TAG, "launchMatchmaking error", e) + promise.reject("MATCHMAKING_ERROR", e.message, e) + } + } + } + + // ─── Personal Health Record ─────────────────────────────────────────────── + + override fun createMedicalDataSource(request: String, promise: Promise) { + if (!isAvailable(promise)) return + moduleScope.launch { + try { + val source = healthConnectClient.createMedicalDataSource( + PhrMapper.createRequestFromJson(JSONObject(request)) + ) + promise.resolve(PhrMapper.medicalDataSourceToJson(source).toString()) + } catch (e: Exception) { + Log.e(TAG, "createMedicalDataSource error", e) + promise.reject("PHR_ERROR", e.message, e) + } + } + } + + override fun deleteMedicalDataSourceWithData(id: String, promise: Promise) { + if (!isAvailable(promise)) return + moduleScope.launch { + try { + healthConnectClient.deleteMedicalDataSourceWithData(id) + promise.resolve(true) + } catch (e: Exception) { + Log.e(TAG, "deleteMedicalDataSourceWithData error", e) + promise.reject("PHR_ERROR", e.message, e) + } + } + } + + override fun getMedicalDataSources(request: String, promise: Promise) { + if (!isAvailable(promise)) return + moduleScope.launch { + try { + val result = PhrMapper.getMedicalDataSources( + healthConnectClient, JSONObject(request.ifEmpty { "{}" }) + ) + promise.resolve(result.toString()) + } catch (e: Exception) { + Log.e(TAG, "getMedicalDataSources error", e) + promise.reject("PHR_ERROR", e.message, e) + } + } + } + + override fun upsertMedicalResources(requests: String, promise: Promise) { + if (!isAvailable(promise)) return + moduleScope.launch { + try { + val upserted = healthConnectClient.upsertMedicalResources( + PhrMapper.upsertRequestsFromJson(JSONArray(requests)) + ) + val arr = JSONArray().apply { + upserted.forEach { put(PhrMapper.medicalResourceToJson(it)) } + } + promise.resolve(arr.toString()) + } catch (e: Exception) { + Log.e(TAG, "upsertMedicalResources error", e) + promise.reject("PHR_ERROR", e.message, e) + } + } + } + + override fun readMedicalResources(request: String, promise: Promise) { + if (!isAvailable(promise)) return + moduleScope.launch { + try { + val result = PhrMapper.readMedicalResources( + healthConnectClient, JSONObject(request) + ) + promise.resolve(result.toString()) + } catch (e: Exception) { + Log.e(TAG, "readMedicalResources error", e) + promise.reject("PHR_ERROR", e.message, e) + } + } + } + + override fun deleteMedicalResources(request: String, promise: Promise) { + if (!isAvailable(promise)) return + moduleScope.launch { + try { + PhrMapper.deleteMedicalResources(healthConnectClient, JSONObject(request)) + promise.resolve(true) + } catch (e: Exception) { + Log.e(TAG, "deleteMedicalResources error", e) + promise.reject("PHR_ERROR", e.message, e) + } + } + } + // ─── ActivityEventListener ──────────────────────────────────────────────── override fun onActivityResult( @@ -223,12 +377,19 @@ class AndroidHealthConnectModule(reactContext: ReactApplicationContext) : resultCode: Int, data: Intent?, ) { - if (requestCode != PERMISSION_REQUEST_CODE) return - val granted = requestPermissionsContract.parseResult(resultCode, data) - val array = Arguments.createArray() - granted.forEach { array.pushString(it) } - pendingPermissionPromise?.resolve(array) - pendingPermissionPromise = null + when (requestCode) { + PERMISSION_REQUEST_CODE -> { + val granted = requestPermissionsContract.parseResult(resultCode, data) + val array = Arguments.createArray() + granted.forEach { array.pushString(it) } + pendingPermissionPromise?.resolve(array) + pendingPermissionPromise = null + } + MATCHMAKING_REQUEST_CODE -> { + pendingMatchmakingPromise?.resolve(resultCode == Activity.RESULT_OK) + pendingMatchmakingPromise = null + } + } } override fun onNewIntent(intent: Intent) {} @@ -265,4 +426,28 @@ class AndroidHealthConnectModule(reactContext: ReactApplicationContext) : Log.e(TAG, "Could not start activity: ${e.message}") } } + + private fun parseMatchmakingRequest(options: JSONObject): MatchmakingRequest { + val recordTypesArr = options.optJSONArray("recordTypes") + val recordTypes = + if (recordTypesArr != null) { + (0 until recordTypesArr.length()) + .map { FeatureSupport.recordClassForType(recordTypesArr.getString(it)) } + .toSet() + } else { + emptySet() + } + val included = parseDataOrigins(options.optJSONArray("includedDataSources")) + val excluded = parseDataOrigins(options.optJSONArray("excludedDataSources")) + return MatchmakingRequest( + recordTypes = recordTypes, + includedDataSources = included, + excludedDataSources = excluded, + ) + } + + private fun parseDataOrigins(arr: JSONArray?): Set { + if (arr == null) return emptySet() + return (0 until arr.length()).map { DataOrigin(arr.getString(it)) }.toSet() + } } diff --git a/android/src/main/java/com/androidhealthconnect/FeatureSupport.kt b/android/src/main/java/com/androidhealthconnect/FeatureSupport.kt new file mode 100644 index 0000000..2214bc1 --- /dev/null +++ b/android/src/main/java/com/androidhealthconnect/FeatureSupport.kt @@ -0,0 +1,68 @@ +package com.androidhealthconnect + +import androidx.health.connect.client.ExperimentalMatchmakingApi +import androidx.health.connect.client.HealthConnectClient +import androidx.health.connect.client.HealthConnectFeatures +import androidx.health.connect.client.feature.ExperimentalPersonalHealthRecordApi +import androidx.health.connect.client.records.* +import kotlin.reflect.KClass + +@OptIn(ExperimentalMatchmakingApi::class, ExperimentalPersonalHealthRecordApi::class) +internal object FeatureSupport { + + fun statusToString(status: Int): String = + when (status) { + HealthConnectFeatures.FEATURE_STATUS_AVAILABLE -> "available" + else -> "unavailable" + } + + fun featureFromName(name: String): Int = + when (name) { + "activityIntensity" -> HealthConnectFeatures.FEATURE_ACTIVITY_INTENSITY + "matchmaking" -> HealthConnectFeatures.FEATURE_MATCHMAKING + "mindfulnessSession" -> HealthConnectFeatures.FEATURE_MINDFULNESS_SESSION + "personalHealthRecord" -> HealthConnectFeatures.FEATURE_PERSONAL_HEALTH_RECORD + "plannedExercise" -> HealthConnectFeatures.FEATURE_PLANNED_EXERCISE + "readHealthDataHistory" -> HealthConnectFeatures.FEATURE_READ_HEALTH_DATA_HISTORY + "readHealthDataInBackground" -> + HealthConnectFeatures.FEATURE_READ_HEALTH_DATA_IN_BACKGROUND + "skinTemperature" -> HealthConnectFeatures.FEATURE_SKIN_TEMPERATURE + "extendedDeviceTypes" -> HealthConnectFeatures.FEATURE_EXTENDED_DEVICE_TYPES + "exerciseSessionImprovements" -> + HealthConnectFeatures.FEATURE_EXERCISE_SESSION_IMPROVEMENTS + else -> throw IllegalArgumentException("Unknown Health Connect feature: $name") + } + + fun getStatus(client: HealthConnectClient, featureName: String): String { + val feature = featureFromName(featureName) + return statusToString(client.features.getFeatureStatus(feature)) + } + + /** Maps JS recordType strings to HC Record KClasses for MatchmakingRequest. */ + fun recordClassForType(recordType: String): KClass = + when (recordType) { + "Steps" -> StepsRecord::class + "HeartRate" -> HeartRateRecord::class + "SleepSession" -> SleepSessionRecord::class + "ActiveCaloriesBurned" -> ActiveCaloriesBurnedRecord::class + "TotalCaloriesBurned" -> TotalCaloriesBurnedRecord::class + "Distance" -> DistanceRecord::class + "Weight" -> WeightRecord::class + "Height" -> HeightRecord::class + "BloodPressure" -> BloodPressureRecord::class + "BloodGlucose" -> BloodGlucoseRecord::class + "OxygenSaturation" -> OxygenSaturationRecord::class + "BodyTemperature" -> BodyTemperatureRecord::class + "BodyFat" -> BodyFatRecord::class + "Hydration" -> HydrationRecord::class + "ExerciseSession" -> ExerciseSessionRecord::class + "RestingHeartRate" -> RestingHeartRateRecord::class + "RespiratoryRate" -> RespiratoryRateRecord::class + "FloorsClimbed" -> FloorsClimbedRecord::class + "ElevationGained" -> ElevationGainedRecord::class + "MindfulnessSession" -> MindfulnessSessionRecord::class + "SkinTemperature" -> SkinTemperatureRecord::class + "ActivityIntensity" -> ActivityIntensityRecord::class + else -> throw IllegalArgumentException("Unsupported record type: $recordType") + } +} diff --git a/android/src/main/java/com/androidhealthconnect/PhrMapper.kt b/android/src/main/java/com/androidhealthconnect/PhrMapper.kt new file mode 100644 index 0000000..4d2fae0 --- /dev/null +++ b/android/src/main/java/com/androidhealthconnect/PhrMapper.kt @@ -0,0 +1,187 @@ +package com.androidhealthconnect + +import android.net.Uri +import androidx.health.connect.client.HealthConnectClient +import androidx.health.connect.client.feature.ExperimentalPersonalHealthRecordApi +import androidx.health.connect.client.records.FhirResource +import androidx.health.connect.client.records.FhirVersion +import androidx.health.connect.client.records.MedicalDataSource +import androidx.health.connect.client.records.MedicalResource +import androidx.health.connect.client.records.MedicalResourceId +import androidx.health.connect.client.request.CreateMedicalDataSourceRequest +import androidx.health.connect.client.request.DeleteMedicalResourcesRequest +import androidx.health.connect.client.request.GetMedicalDataSourcesRequest +import androidx.health.connect.client.request.ReadMedicalResourcesInitialRequest +import androidx.health.connect.client.request.ReadMedicalResourcesPageRequest +import androidx.health.connect.client.request.UpsertMedicalResourceRequest +import org.json.JSONArray +import org.json.JSONObject + +@OptIn(ExperimentalPersonalHealthRecordApi::class) +internal object PhrMapper { + + fun fhirVersionFromJson(json: JSONObject): FhirVersion = + FhirVersion( + json.getInt("major"), + json.getInt("minor"), + json.getInt("patch"), + ) + + fun fhirVersionToJson(version: FhirVersion): JSONObject = + JSONObject().apply { + put("major", version.major) + put("minor", version.minor) + put("patch", version.patch) + } + + fun medicalDataSourceToJson(source: MedicalDataSource): JSONObject = + JSONObject().apply { + put("id", source.id) + put("displayName", source.displayName) + put("fhirBaseUri", source.fhirBaseUri.toString()) + put("fhirVersion", fhirVersionToJson(source.fhirVersion)) + put("packageName", source.packageName) + } + + fun medicalResourceIdToJson(id: MedicalResourceId): JSONObject = + JSONObject().apply { + put("dataSourceId", id.dataSourceId) + put("fhirResourceType", id.fhirResourceType) + put("fhirResourceId", id.fhirResourceId) + } + + fun medicalResourceIdFromJson(json: JSONObject): MedicalResourceId = + MedicalResourceId( + dataSourceId = json.getString("dataSourceId"), + fhirResourceType = json.getInt("fhirResourceType"), + fhirResourceId = json.getString("fhirResourceId"), + ) + + fun fhirResourceToJson(resource: FhirResource): JSONObject = + JSONObject().apply { + put("type", resource.type) + put("id", resource.id) + put("data", resource.data) + } + + fun medicalResourceToJson(resource: MedicalResource): JSONObject = + JSONObject().apply { + put("type", resource.type) + put("id", medicalResourceIdToJson(resource.id)) + put("dataSourceId", resource.dataSourceId) + put("fhirVersion", fhirVersionToJson(resource.fhirVersion)) + put("fhirResource", fhirResourceToJson(resource.fhirResource)) + } + + fun createRequestFromJson(json: JSONObject): CreateMedicalDataSourceRequest = + CreateMedicalDataSourceRequest( + fhirBaseUri = Uri.parse(json.getString("fhirBaseUri")), + displayName = json.getString("displayName"), + fhirVersion = fhirVersionFromJson(json.getJSONObject("fhirVersion")), + ) + + fun upsertRequestsFromJson(arr: JSONArray): List = + (0 until arr.length()).map { i -> + val j = arr.getJSONObject(i) + UpsertMedicalResourceRequest( + dataSourceId = j.getString("dataSourceId"), + fhirVersion = fhirVersionFromJson(j.getJSONObject("fhirVersion")), + data = j.getString("data"), + ) + } + + suspend fun getMedicalDataSources( + client: HealthConnectClient, + options: JSONObject, + ): JSONArray { + val idsArr = options.optJSONArray("medicalDataSourceIds") + val sources = + if (idsArr != null && idsArr.length() > 0) { + val ids = (0 until idsArr.length()).map { idsArr.getString(it) } + client.getMedicalDataSources(ids) + } else { + val packagesArr = options.optJSONArray("packageNames") + val packageNames = + if (packagesArr != null) { + (0 until packagesArr.length()).map { packagesArr.getString(it) } + } else { + emptyList() + } + client.getMedicalDataSources(GetMedicalDataSourcesRequest(packageNames)) + } + return JSONArray().apply { + sources.forEach { put(medicalDataSourceToJson(it)) } + } + } + + suspend fun readMedicalResources( + client: HealthConnectClient, + options: JSONObject, + ): JSONObject { + val pageToken = options.optString("pageToken", "").ifEmpty { null } + val pageSize = options.optInt("pageSize", 100) + val request = + if (pageToken != null) { + ReadMedicalResourcesPageRequest(pageToken = pageToken, pageSize = pageSize) + } else { + val type = options.getInt("medicalResourceType") + val sourceIdsArr = options.optJSONArray("medicalDataSourceIds") + val sourceIds = + if (sourceIdsArr != null) { + (0 until sourceIdsArr.length()).map { sourceIdsArr.getString(it) }.toSet() + } else { + emptySet() + } + ReadMedicalResourcesInitialRequest( + medicalResourceType = type, + medicalDataSourceIds = sourceIds, + pageSize = pageSize, + ) + } + val response = client.readMedicalResources(request) + return JSONObject().apply { + put( + "medicalResources", + JSONArray().apply { + response.medicalResources.forEach { put(medicalResourceToJson(it)) } + }, + ) + put("nextPageToken", response.nextPageToken ?: JSONObject.NULL) + } + } + + suspend fun deleteMedicalResources( + client: HealthConnectClient, + options: JSONObject, + ) { + val idsArr = options.optJSONArray("ids") + if (idsArr != null && idsArr.length() > 0) { + val ids = + (0 until idsArr.length()).map { + medicalResourceIdFromJson(idsArr.getJSONObject(it)) + } + client.deleteMedicalResources(ids) + return + } + val dataSourceIdsArr = options.optJSONArray("dataSourceIds") + val typesArr = options.optJSONArray("medicalResourceTypes") + val dataSourceIds = + if (dataSourceIdsArr != null) { + (0 until dataSourceIdsArr.length()).map { dataSourceIdsArr.getString(it) }.toSet() + } else { + emptySet() + } + val types = + if (typesArr != null) { + (0 until typesArr.length()).map { typesArr.getInt(it) }.toSet() + } else { + emptySet() + } + client.deleteMedicalResources( + DeleteMedicalResourcesRequest( + dataSourceIds = dataSourceIds, + medicalResourceTypes = types, + ) + ) + } +} diff --git a/android/src/main/java/com/androidhealthconnect/RecordMapper.kt b/android/src/main/java/com/androidhealthconnect/RecordMapper.kt index 8b9677b..6390703 100644 --- a/android/src/main/java/com/androidhealthconnect/RecordMapper.kt +++ b/android/src/main/java/com/androidhealthconnect/RecordMapper.kt @@ -202,6 +202,33 @@ internal object RecordMapper { buildResponse(res.pageToken) { res.records.map(::elevationGainedToJson) } } + "MindfulnessSession" -> { + val req = ReadRecordsRequest( + MindfulnessSessionRecord::class, timeRangeFilter, dataOriginFilter, + ascendingOrder, pageSize, pageToken + ) + val res = client.readRecords(req) + buildResponse(res.pageToken) { res.records.map(::mindfulnessSessionToJson) } + } + + "SkinTemperature" -> { + val req = ReadRecordsRequest( + SkinTemperatureRecord::class, timeRangeFilter, dataOriginFilter, + ascendingOrder, pageSize, pageToken + ) + val res = client.readRecords(req) + buildResponse(res.pageToken) { res.records.map(::skinTemperatureToJson) } + } + + "ActivityIntensity" -> { + val req = ReadRecordsRequest( + ActivityIntensityRecord::class, timeRangeFilter, dataOriginFilter, + ascendingOrder, pageSize, pageToken + ) + val res = client.readRecords(req) + buildResponse(res.pageToken) { res.records.map(::activityIntensityToJson) } + } + else -> throw IllegalArgumentException("Unsupported record type: $recordType") } } @@ -229,6 +256,9 @@ internal object RecordMapper { "RespiratoryRate" -> jsonToRespiratoryRate(json) "FloorsClimbed" -> jsonToFloorsClimbed(json) "ElevationGained" -> jsonToElevationGained(json) + "MindfulnessSession" -> jsonToMindfulnessSession(json) + "SkinTemperature" -> jsonToSkinTemperature(json) + "ActivityIntensity" -> jsonToActivityIntensity(json) else -> throw IllegalArgumentException("Unsupported record type: $type") } } @@ -260,6 +290,9 @@ internal object RecordMapper { "RespiratoryRate" -> client.deleteRecords(RespiratoryRateRecord::class, filter) "FloorsClimbed" -> client.deleteRecords(FloorsClimbedRecord::class, filter) "ElevationGained" -> client.deleteRecords(ElevationGainedRecord::class, filter) + "MindfulnessSession" -> client.deleteRecords(MindfulnessSessionRecord::class, filter) + "SkinTemperature" -> client.deleteRecords(SkinTemperatureRecord::class, filter) + "ActivityIntensity" -> client.deleteRecords(ActivityIntensityRecord::class, filter) else -> throw IllegalArgumentException("Unsupported record type: $recordType") } } @@ -289,6 +322,9 @@ internal object RecordMapper { "RespiratoryRate" -> client.deleteRecords(RespiratoryRateRecord::class, ids, emptyList()) "FloorsClimbed" -> client.deleteRecords(FloorsClimbedRecord::class, ids, emptyList()) "ElevationGained" -> client.deleteRecords(ElevationGainedRecord::class, ids, emptyList()) + "MindfulnessSession" -> client.deleteRecords(MindfulnessSessionRecord::class, ids, emptyList()) + "SkinTemperature" -> client.deleteRecords(SkinTemperatureRecord::class, ids, emptyList()) + "ActivityIntensity" -> client.deleteRecords(ActivityIntensityRecord::class, ids, emptyList()) else -> throw IllegalArgumentException("Unsupported record type: $recordType") } } @@ -569,6 +605,47 @@ internal object RecordMapper { put("metadata", metadataToJson(r.metadata)) } + private fun mindfulnessSessionToJson(r: MindfulnessSessionRecord) = JSONObject().apply { + put("recordType", "MindfulnessSession") + put("mindfulnessSessionType", r.mindfulnessSessionType) + put("startTime", r.startTime.toString()) + put("endTime", r.endTime.toString()) + put("title", r.title ?: JSONObject.NULL) + put("notes", r.notes ?: JSONObject.NULL) + r.startZoneOffset?.let { put("startZoneOffset", it.toString()) } + r.endZoneOffset?.let { put("endZoneOffset", it.toString()) } + put("metadata", metadataToJson(r.metadata)) + } + + private fun skinTemperatureToJson(r: SkinTemperatureRecord) = JSONObject().apply { + put("recordType", "SkinTemperature") + val deltas = JSONArray() + r.deltas.forEach { d -> + deltas.put(JSONObject().apply { + put("time", d.time.toString()) + put("delta", d.delta.inCelsius) + }) + } + put("deltas", deltas) + put("baseline", r.baseline?.inCelsius ?: JSONObject.NULL) + put("measurementLocation", r.measurementLocation) + put("startTime", r.startTime.toString()) + put("endTime", r.endTime.toString()) + r.startZoneOffset?.let { put("startZoneOffset", it.toString()) } + r.endZoneOffset?.let { put("endZoneOffset", it.toString()) } + put("metadata", metadataToJson(r.metadata)) + } + + private fun activityIntensityToJson(r: ActivityIntensityRecord) = JSONObject().apply { + put("recordType", "ActivityIntensity") + put("activityIntensityType", r.activityIntensityType) + put("startTime", r.startTime.toString()) + put("endTime", r.endTime.toString()) + r.startZoneOffset?.let { put("startZoneOffset", it.toString()) } + r.endZoneOffset?.let { put("endZoneOffset", it.toString()) } + put("metadata", metadataToJson(r.metadata)) + } + // ───────────────────────────────────────────────────────────────────────── // JSON → Record conversions // ───────────────────────────────────────────────────────────────────────── @@ -791,4 +868,50 @@ internal object RecordMapper { endZoneOffset = parseZoneOffset(j.optString("endZoneOffset")), metadata = jsonToMetadata(j.optJSONObject("metadata")) ) + + private fun jsonToMindfulnessSession(j: JSONObject) = MindfulnessSessionRecord( + mindfulnessSessionType = j.getInt("mindfulnessSessionType"), + startTime = parseInstant(j, "startTime"), + endTime = parseInstant(j, "endTime"), + title = j.optString("title").ifEmpty { null }, + notes = j.optString("notes").ifEmpty { null }, + startZoneOffset = parseZoneOffset(j.optString("startZoneOffset")), + endZoneOffset = parseZoneOffset(j.optString("endZoneOffset")), + metadata = jsonToMetadata(j.optJSONObject("metadata")) + ) + + private fun jsonToSkinTemperature(j: JSONObject): SkinTemperatureRecord { + val deltasArr = j.getJSONArray("deltas") + val deltas = (0 until deltasArr.length()).map { i -> + val d = deltasArr.getJSONObject(i) + SkinTemperatureRecord.Delta( + time = Instant.parse(d.getString("time")), + delta = TemperatureDelta.celsius(d.getDouble("delta")) + ) + } + val baseline = if (j.isNull("baseline") || !j.has("baseline")) null + else Temperature.celsius(j.getDouble("baseline")) + return SkinTemperatureRecord( + deltas = deltas, + baseline = baseline, + measurementLocation = j.optInt( + "measurementLocation", + SkinTemperatureRecord.MEASUREMENT_LOCATION_UNKNOWN + ), + startTime = parseInstant(j, "startTime"), + endTime = parseInstant(j, "endTime"), + startZoneOffset = parseZoneOffset(j.optString("startZoneOffset")), + endZoneOffset = parseZoneOffset(j.optString("endZoneOffset")), + metadata = jsonToMetadata(j.optJSONObject("metadata")) + ) + } + + private fun jsonToActivityIntensity(j: JSONObject) = ActivityIntensityRecord( + activityIntensityType = j.getInt("activityIntensityType"), + startTime = parseInstant(j, "startTime"), + endTime = parseInstant(j, "endTime"), + startZoneOffset = parseZoneOffset(j.optString("startZoneOffset")), + endZoneOffset = parseZoneOffset(j.optString("endZoneOffset")), + metadata = jsonToMetadata(j.optJSONObject("metadata")) + ) } diff --git a/android/src/test/java/com/androidhealthconnect/RecordMapperTest.kt b/android/src/test/java/com/androidhealthconnect/RecordMapperTest.kt index 817034c..4b9f851 100644 --- a/android/src/test/java/com/androidhealthconnect/RecordMapperTest.kt +++ b/android/src/test/java/com/androidhealthconnect/RecordMapperTest.kt @@ -191,6 +191,33 @@ class RecordMapperTest { interval("ElevationGained") { put("elevation", 40.0) }, ElevationGainedRecord::class.java ), + Case( + "MindfulnessSession", + interval("MindfulnessSession") { + put("mindfulnessSessionType", 1) + put("title", "Lake meditation") + }, + MindfulnessSessionRecord::class.java + ), + Case( + "SkinTemperature", + interval("SkinTemperature") { + put( + "deltas", + JSONArray().put( + JSONObject().put("time", TIME).put("delta", 0.2) + ) + ) + put("baseline", 33.5) + put("measurementLocation", 3) + }, + SkinTemperatureRecord::class.java + ), + Case( + "ActivityIntensity", + interval("ActivityIntensity") { put("activityIntensityType", 0) }, + ActivityIntensityRecord::class.java + ), ) private fun interval(type: String, extra: JSONObject.() -> Unit = {}) = diff --git a/src/NativeAndroidHealthConnect.ts b/src/NativeAndroidHealthConnect.ts index 383d0df..ea53778 100644 --- a/src/NativeAndroidHealthConnect.ts +++ b/src/NativeAndroidHealthConnect.ts @@ -53,6 +53,44 @@ export interface Spec extends TurboModule { recordType: string, recordIds: ReadonlyArray ): Promise; + + /** + * Checks whether a Health Connect feature is available on this device. + * @param feature - feature name (e.g. "skinTemperature", "matchmaking") + * @returns "available" | "unavailable" + */ + getFeatureStatus(feature: string): Promise; + + /** + * Checks whether the Matchmaking UI can show relevant apps/devices. + * @param options - JSON-serialised MatchmakingRequest + */ + checkIfMatchmakingIsPossible(options: string): Promise; + + /** + * Launches the Health Connect Matchmaking flow. + * Resolves true when the user finishes with RESULT_OK (at least one permission granted). + * @param options - JSON-serialised MatchmakingRequest + */ + launchMatchmaking(options: string): Promise; + + /** Creates a MedicalDataSource. @param request JSON CreateMedicalDataSourceRequest */ + createMedicalDataSource(request: string): Promise; + + /** Deletes a MedicalDataSource and all of its MedicalResources. */ + deleteMedicalDataSourceWithData(id: string): Promise; + + /** Lists MedicalDataSources. @param request JSON GetMedicalDataSourcesRequest */ + getMedicalDataSources(request: string): Promise; + + /** Upserts MedicalResources. @param requests JSON UpsertMedicalResourceRequest[] */ + upsertMedicalResources(requests: string): Promise; + + /** Reads MedicalResources. @param request JSON ReadMedicalResourcesRequest */ + readMedicalResources(request: string): Promise; + + /** Deletes MedicalResources by id or by type/data-source filter. */ + deleteMedicalResources(request: string): Promise; } export default TurboModuleRegistry.getEnforcing('AndroidHealthConnect'); diff --git a/src/__tests__/index.test.tsx b/src/__tests__/index.test.tsx index fba1cd4..dd4e494 100644 --- a/src/__tests__/index.test.tsx +++ b/src/__tests__/index.test.tsx @@ -9,6 +9,11 @@ import { deleteRecordsById, openHealthConnectSettings, openHealthConnectApp, + getFeatureStatus, + checkIfMatchmakingIsPossible, + launchMatchmaking, + createMedicalDataSource, + readMedicalResources, } from '../index'; import type { Spec } from '../NativeAndroidHealthConnect'; @@ -29,6 +34,15 @@ jest.mock( writeRecords: jest.fn(), deleteRecordsByTime: jest.fn(), deleteRecordsById: jest.fn(), + getFeatureStatus: jest.fn(), + checkIfMatchmakingIsPossible: jest.fn(), + launchMatchmaking: jest.fn(), + createMedicalDataSource: jest.fn(), + deleteMedicalDataSourceWithData: jest.fn(), + getMedicalDataSources: jest.fn(), + upsertMedicalResources: jest.fn(), + readMedicalResources: jest.fn(), + deleteMedicalResources: jest.fn(), }; return { @@ -242,3 +256,60 @@ describe('navigation helpers', () => { expect(mockNative.openHealthConnectApp).toHaveBeenCalledTimes(1); }); }); + +describe('feature / matchmaking / PHR helpers', () => { + it('getFeatureStatus forwards feature name', async () => { + mockNative.getFeatureStatus.mockResolvedValue('available'); + await expect(getFeatureStatus('skinTemperature')).resolves.toBe( + 'available' + ); + expect(mockNative.getFeatureStatus).toHaveBeenCalledWith('skinTemperature'); + }); + + it('checkIfMatchmakingIsPossible parses JSON response', async () => { + mockNative.checkIfMatchmakingIsPossible.mockResolvedValue( + JSON.stringify({ isMatchmakingPossible: true }) + ); + const result = await checkIfMatchmakingIsPossible({ + recordTypes: ['Steps'], + }); + expect(result.isMatchmakingPossible).toBe(true); + expect(mockNative.checkIfMatchmakingIsPossible).toHaveBeenCalledWith( + JSON.stringify({ recordTypes: ['Steps'] }) + ); + }); + + it('launchMatchmaking forwards options', async () => { + mockNative.launchMatchmaking.mockResolvedValue(true); + await expect(launchMatchmaking({})).resolves.toBe(true); + expect(mockNative.launchMatchmaking).toHaveBeenCalledWith('{}'); + }); + + it('createMedicalDataSource parses JSON response', async () => { + const source = { + id: 'ds-1', + displayName: 'Clinic', + fhirBaseUri: 'https://example.com/fhir/', + fhirVersion: { major: 4, minor: 0, patch: 1 }, + }; + mockNative.createMedicalDataSource.mockResolvedValue( + JSON.stringify(source) + ); + await expect( + createMedicalDataSource({ + displayName: 'Clinic', + fhirBaseUri: 'https://example.com/fhir/', + fhirVersion: { major: 4, minor: 0, patch: 1 }, + }) + ).resolves.toEqual(source); + }); + + it('readMedicalResources parses JSON response', async () => { + mockNative.readMedicalResources.mockResolvedValue( + JSON.stringify({ medicalResources: [], nextPageToken: null }) + ); + const page = await readMedicalResources({ medicalResourceType: 2 }); + expect(page.medicalResources).toEqual([]); + expect(page.nextPageToken).toBeNull(); + }); +}); diff --git a/src/__tests__/recordTypes.test.ts b/src/__tests__/recordTypes.test.ts index 4949a81..2ec14cd 100644 --- a/src/__tests__/recordTypes.test.ts +++ b/src/__tests__/recordTypes.test.ts @@ -21,6 +21,12 @@ import { readRespiratoryRate, readFloorsClimbed, readElevationGained, + readMindfulnessSessions, + readSkinTemperature, + readActivityIntensity, + MindfulnessSessionType, + ActivityIntensityType, + SkinTemperatureMeasurementLocation, } from '../index'; import type { HealthRecord, RecordType } from '../types'; import type { Spec } from '../NativeAndroidHealthConnect'; @@ -40,6 +46,15 @@ jest.mock( writeRecords: jest.fn(), deleteRecordsByTime: jest.fn(), deleteRecordsById: jest.fn(), + getFeatureStatus: jest.fn(), + checkIfMatchmakingIsPossible: jest.fn(), + launchMatchmaking: jest.fn(), + createMedicalDataSource: jest.fn(), + deleteMedicalDataSourceWithData: jest.fn(), + getMedicalDataSources: jest.fn(), + upsertMedicalResources: jest.fn(), + readMedicalResources: jest.fn(), + deleteMedicalResources: jest.fn(), }; return { @@ -198,14 +213,44 @@ const RECORD_CASES: RecordCase[] = [ sample: { recordType: 'ElevationGained', elevation: 40, ...interval }, readHelper: readElevationGained, }, + { + recordType: 'MindfulnessSession', + sample: { + recordType: 'MindfulnessSession', + mindfulnessSessionType: MindfulnessSessionType.MEDITATION, + title: 'Lake meditation', + ...interval, + }, + readHelper: readMindfulnessSessions, + }, + { + recordType: 'SkinTemperature', + sample: { + recordType: 'SkinTemperature', + deltas: [{ time: instant.time, delta: 0.2 }], + baseline: 33.5, + measurementLocation: SkinTemperatureMeasurementLocation.WRIST, + ...interval, + }, + readHelper: readSkinTemperature, + }, + { + recordType: 'ActivityIntensity', + sample: { + recordType: 'ActivityIntensity', + activityIntensityType: ActivityIntensityType.MODERATE, + ...interval, + }, + readHelper: readActivityIntensity, + }, ]; beforeEach(() => jest.clearAllMocks()); describe('Supported record types (README table)', () => { - it('covers all 19 documented record types', () => { - expect(RECORD_CASES).toHaveLength(19); - expect(new Set(RECORD_CASES.map((c) => c.recordType)).size).toBe(19); + it('covers all 22 documented record types', () => { + expect(RECORD_CASES).toHaveLength(22); + expect(new Set(RECORD_CASES.map((c) => c.recordType)).size).toBe(22); }); describe.each(RECORD_CASES)( diff --git a/src/index.tsx b/src/index.tsx index c155d76..d9cf297 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -26,6 +26,21 @@ import type { RespiratoryRateRecord, FloorsClimbedRecord, ElevationGainedRecord, + MindfulnessSessionRecord, + SkinTemperatureRecord, + ActivityIntensityRecord, + HealthConnectFeature, + FeatureStatus, + MatchmakingRequest, + MatchmakingPossibleResponse, + CreateMedicalDataSourceRequest, + MedicalDataSource, + GetMedicalDataSourcesRequest, + UpsertMedicalResourceRequest, + MedicalResource, + ReadMedicalResourcesRequest, + ReadMedicalResourcesResponse, + DeleteMedicalResourcesRequest, } from './types'; export * from './types'; @@ -225,3 +240,112 @@ export const readFloorsClimbed = (options?: ReadRecordsOptions) => export const readElevationGained = (options?: ReadRecordsOptions) => readRecords('ElevationGained', options); + +export const readMindfulnessSessions = (options?: ReadRecordsOptions) => + readRecords('MindfulnessSession', options); + +export const readSkinTemperature = (options?: ReadRecordsOptions) => + readRecords('SkinTemperature', options); + +export const readActivityIntensity = (options?: ReadRecordsOptions) => + readRecords('ActivityIntensity', options); + +// ─── Feature availability ───────────────────────────────────────────────────── + +/** + * Returns whether a Health Connect feature is available on this device. + * Prefer checking before using alpha-gated APIs (skin temperature, mindfulness, + * activity intensity, matchmaking, personal health record). + */ +export async function getFeatureStatus( + feature: HealthConnectFeature +): Promise { + const status = await NativeAndroidHealthConnect.getFeatureStatus(feature); + return status as FeatureStatus; +} + +// ─── Matchmaking (experimental) ─────────────────────────────────────────────── + +/** + * Returns whether the Matchmaking UI can show apps/devices that write data + * this app has permission to read. Requires FEATURE_MATCHMAKING. + */ +export async function checkIfMatchmakingIsPossible( + options: MatchmakingRequest = {} +): Promise { + const json = await NativeAndroidHealthConnect.checkIfMatchmakingIsPossible( + JSON.stringify(options) + ); + return JSON.parse(json) as MatchmakingPossibleResponse; +} + +/** + * Launches the Health Connect Matchmaking flow. + * Resolves `true` when the user finishes successfully (RESULT_OK). + * Requires FEATURE_MATCHMAKING and granted read permissions for the requested types. + */ +export async function launchMatchmaking( + options: MatchmakingRequest = {} +): Promise { + return NativeAndroidHealthConnect.launchMatchmaking(JSON.stringify(options)); +} + +// ─── Personal Health Record / medical (experimental) ────────────────────────── + +/** Creates a MedicalDataSource. Requires FEATURE_PERSONAL_HEALTH_RECORD. */ +export async function createMedicalDataSource( + request: CreateMedicalDataSourceRequest +): Promise { + const json = await NativeAndroidHealthConnect.createMedicalDataSource( + JSON.stringify(request) + ); + return JSON.parse(json) as MedicalDataSource; +} + +/** Deletes a MedicalDataSource and all MedicalResources written under it. */ +export async function deleteMedicalDataSourceWithData( + id: string +): Promise { + await NativeAndroidHealthConnect.deleteMedicalDataSourceWithData(id); +} + +/** Lists MedicalDataSources visible to this app. */ +export async function getMedicalDataSources( + request: GetMedicalDataSourcesRequest = {} +): Promise { + const json = await NativeAndroidHealthConnect.getMedicalDataSources( + JSON.stringify(request) + ); + return JSON.parse(json) as MedicalDataSource[]; +} + +/** Inserts or updates FHIR MedicalResources. */ +export async function upsertMedicalResources( + requests: UpsertMedicalResourceRequest[] +): Promise { + const json = await NativeAndroidHealthConnect.upsertMedicalResources( + JSON.stringify(requests) + ); + return JSON.parse(json) as MedicalResource[]; +} + +/** + * Reads MedicalResources by type (first page) or by pageToken (subsequent pages). + */ +export async function readMedicalResources( + request: ReadMedicalResourcesRequest +): Promise { + const json = await NativeAndroidHealthConnect.readMedicalResources( + JSON.stringify(request) + ); + return JSON.parse(json) as ReadMedicalResourcesResponse; +} + +/** Deletes MedicalResources by id list or by data-source / type filter. */ +export async function deleteMedicalResources( + request: DeleteMedicalResourcesRequest +): Promise { + await NativeAndroidHealthConnect.deleteMedicalResources( + JSON.stringify(request) + ); +} diff --git a/src/types.ts b/src/types.ts index c216a20..c8248c4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -47,6 +47,25 @@ export type HealthPermission = | 'android.permission.health.WRITE_FLOORS_CLIMBED' | 'android.permission.health.READ_ELEVATION_GAINED' | 'android.permission.health.WRITE_ELEVATION_GAINED' + | 'android.permission.health.READ_MINDFULNESS' + | 'android.permission.health.WRITE_MINDFULNESS' + | 'android.permission.health.READ_SKIN_TEMPERATURE' + | 'android.permission.health.WRITE_SKIN_TEMPERATURE' + | 'android.permission.health.READ_ACTIVITY_INTENSITY' + | 'android.permission.health.WRITE_ACTIVITY_INTENSITY' + | 'android.permission.health.WRITE_MEDICAL_DATA' + | 'android.permission.health.READ_MEDICAL_DATA_ALLERGIES_INTOLERANCES' + | 'android.permission.health.READ_MEDICAL_DATA_CONDITIONS' + | 'android.permission.health.READ_MEDICAL_DATA_LABORATORY_RESULTS' + | 'android.permission.health.READ_MEDICAL_DATA_MEDICATIONS' + | 'android.permission.health.READ_MEDICAL_DATA_PERSONAL_DETAILS' + | 'android.permission.health.READ_MEDICAL_DATA_PRACTITIONER_DETAILS' + | 'android.permission.health.READ_MEDICAL_DATA_PREGNANCY' + | 'android.permission.health.READ_MEDICAL_DATA_PROCEDURES' + | 'android.permission.health.READ_MEDICAL_DATA_SOCIAL_HISTORY' + | 'android.permission.health.READ_MEDICAL_DATA_VACCINES' + | 'android.permission.health.READ_MEDICAL_DATA_VISITS' + | 'android.permission.health.READ_MEDICAL_DATA_VITAL_SIGNS' | (string & {}); // allow custom / future permissions // ─── Common ─────────────────────────────────────────────────────────────────── @@ -332,6 +351,53 @@ export type ElevationGainedRecord = { metadata?: RecordMetadata; }; +/** Requires FEATURE_MINDFULNESS_SESSION on the device. */ +export type MindfulnessSessionRecord = { + recordType: 'MindfulnessSession'; + /** MindfulnessSessionType constant (0–5). */ + mindfulnessSessionType: number; + startTime: string; + endTime: string; + title?: string | null; + notes?: string | null; + startZoneOffset?: string; + endZoneOffset?: string; + metadata?: RecordMetadata; +}; + +export type SkinTemperatureDelta = { + time: string; // ISO 8601 + /** Delta in Celsius degrees (−30 to 30). */ + delta: number; +}; + +/** Requires FEATURE_SKIN_TEMPERATURE on the device. */ +export type SkinTemperatureRecord = { + recordType: 'SkinTemperature'; + deltas: SkinTemperatureDelta[]; + /** Optional baseline in Celsius. */ + baseline?: number | null; + /** SkinTemperatureMeasurementLocation (0–3). */ + measurementLocation?: number; + startTime: string; + endTime: string; + startZoneOffset?: string; + endZoneOffset?: string; + metadata?: RecordMetadata; +}; + +/** Requires FEATURE_ACTIVITY_INTENSITY on the device. */ +export type ActivityIntensityRecord = { + recordType: 'ActivityIntensity'; + /** ActivityIntensityType: 0 = moderate, 1 = vigorous. */ + activityIntensityType: number; + startTime: string; + endTime: string; + startZoneOffset?: string; + endZoneOffset?: string; + metadata?: RecordMetadata; +}; + // ─── Union & discriminant helpers ───────────────────────────────────────────── export type HealthRecord = @@ -353,7 +419,10 @@ export type HealthRecord = | RestingHeartRateRecord | RespiratoryRateRecord | FloorsClimbedRecord - | ElevationGainedRecord; + | ElevationGainedRecord + | MindfulnessSessionRecord + | SkinTemperatureRecord + | ActivityIntensityRecord; export type RecordType = HealthRecord['recordType']; @@ -463,3 +532,166 @@ export const RecordingMethod = { */ MANUAL_ENTRY: 3, } as const; + +// ─── Feature availability (connect-client 1.1+ / 1.2 alpha) ─────────────────── + +/** + * Feature names accepted by {@link getFeatureStatus}. + * Maps to `HealthConnectFeatures.FEATURE_*` on Android. + */ +export type HealthConnectFeature = + | 'activityIntensity' + | 'matchmaking' + | 'mindfulnessSession' + | 'personalHealthRecord' + | 'plannedExercise' + | 'readHealthDataHistory' + | 'readHealthDataInBackground' + | 'skinTemperature' + | 'extendedDeviceTypes' + | 'exerciseSessionImprovements'; + +export type FeatureStatus = 'available' | 'unavailable'; + +export const MindfulnessSessionType = { + UNKNOWN: 0, + MEDITATION: 1, + BREATHING: 2, + MUSIC: 3, + MOVEMENT: 4, + UNGUIDED: 5, +} as const; + +export const SkinTemperatureMeasurementLocation = { + UNKNOWN: 0, + FINGER: 1, + TOE: 2, + WRIST: 3, +} as const; + +export const ActivityIntensityType = { + MODERATE: 0, + VIGOROUS: 1, +} as const; + +// ─── Matchmaking (experimental) ─────────────────────────────────────────────── + +export type MatchmakingRequest = { + /** + * Record type names the app can read (e.g. `'Steps'`). + * Empty / omitted → all record types the app has read permission for. + */ + recordTypes?: RecordType[]; + /** Package names to exclusively include as data sources. */ + includedDataSources?: string[]; + /** Package names to exclude as data sources. */ + excludedDataSources?: string[]; +}; + +export type MatchmakingPossibleResponse = { + isMatchmakingPossible: boolean; +}; + +// ─── Personal Health Record / medical (experimental) ────────────────────────── + +export const MedicalResourceType = { + VACCINES: 1, + ALLERGIES_INTOLERANCES: 2, + PREGNANCY: 3, + SOCIAL_HISTORY: 4, + VITAL_SIGNS: 5, + LABORATORY_RESULTS: 6, + CONDITIONS: 7, + PROCEDURES: 8, + MEDICATIONS: 9, + PERSONAL_DETAILS: 10, + PRACTITIONER_DETAILS: 11, + VISITS: 12, +} as const; + +export type FhirVersion = { + major: number; + minor: number; + patch: number; +}; + +export type MedicalDataSource = { + id: string; + displayName: string; + fhirBaseUri: string; + fhirVersion: FhirVersion; + packageName?: string; +}; + +export type CreateMedicalDataSourceRequest = { + displayName: string; + /** e.g. `https://example.com/fhir/` or `myapp://source`. */ + fhirBaseUri: string; + fhirVersion: FhirVersion; +}; + +export type UpsertMedicalResourceRequest = { + dataSourceId: string; + fhirVersion: FhirVersion; + /** Valid FHIR resource JSON string. */ + data: string; +}; + +export type MedicalResourceId = { + dataSourceId: string; + /** `FhirResource` type constant (int). */ + fhirResourceType: number; + fhirResourceId: string; +}; + +export type FhirResource = { + /** `FhirResource` type constant (int). */ + type: number; + id: string; + /** FHIR resource JSON string. */ + data: string; +}; + +export type MedicalResource = { + type: number; + id: MedicalResourceId; + dataSourceId: string; + fhirVersion: FhirVersion; + fhirResource: FhirResource; +}; + +export type ReadMedicalResourcesRequest = { + /** + * Initial page: set `medicalResourceType`. + * Subsequent pages: set `pageToken` from the previous response. + */ + medicalResourceType?: number; + medicalDataSourceIds?: string[]; + pageSize?: number; + pageToken?: string | null; +}; + +export type ReadMedicalResourcesResponse = { + medicalResources: MedicalResource[]; + nextPageToken?: string | null; +}; + +export type DeleteMedicalResourcesRequest = { + /** Delete by IDs (takes precedence when non-empty). */ + ids?: MedicalResourceId[]; + dataSourceIds?: string[]; + medicalResourceTypes?: number[]; +}; + +export type GetMedicalDataSourcesRequest = { + /** + * When set, fetch these data sources by ID + * (`HealthConnectClient.getMedicalDataSources(ids)`). + */ + medicalDataSourceIds?: string[]; + /** + * When IDs are omitted, filter by writing-app package names + * (`GetMedicalDataSourcesRequest`). Empty / omitted → all visible sources. + */ + packageNames?: string[]; +};