698 lines · 38.6 KB · RustRaw
//! What Cotton Health reads, and how each reading becomes a day's number.//!//! One [`Metric`] per daily summary a person sees: its key on the//! `health_day` row, the unit it is kept in, how a day's samples fold into//! one number ([`Fold`]), and where it comes from: the HealthKit type the//! phone asks to read (with the unit string the shell hands `HKUnit(from:)`),//! the name Apple's export.xml gives the same type (the HealthKit identifier//! again), and the Health Connect record a later Android source reads. The//! point measurements (`health_measurement`) and the workouts//! (`health_workout`) name their sources here too, so every reader — the//! phone, the export, Health Connect — lands the same rows.//!//! Units are converted on the way in ([`canonical`]): a row always holds the//! metric's own unit, whatever the source spoke.use serde::Serialize;/// How a day's samples become the day's one number.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "snake_case")]pub enum Fold { /// Added up over the day (steps, distance, energy, flights). Two sources /// counting the same steps are not added together: the day keeps the /// fullest source's total (HealthKit's statistics do this on the phone; /// the export reader by the largest per-source sum). Sum, /// The mean of the day's samples, with their least and most. Average, /// The day's last reading (weight, body fat, VO2 max). Latest, /// Minutes of a sleep stage, from intervals merged across sources, on the /// day the sleep ends (the morning you woke). Sleep, /// Minutes of sessions merged across sources (mindful minutes). Minutes, /// Hours of the day in which the person stood (Apple's stand hours). Hours, /// The day's menstrual flow, a word in `state` (cycle tracking, only /// when the person logs it). Flow, /// How many samples of a category the day holds (an irregular-rhythm /// notification, a handwashing), on the day each starts. Count,}/// What a dimension of a unit is, for [`canonical`].#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Dimension { Count, Length, Energy, Rate, Milliseconds, Mass, Fraction, Pressure, Glucose, Temperature, Oxygen, Duration, Category, /// m/s. Speed, /// W. Power, /// dB(A) sound pressure. Decibel, /// A plain number with no unit (BMI, the UV index). Index, /// g, mg and µg of a nutrient, each kept in its own. Grams, Milligrams, Micrograms, /// mL. Volume, /// METs (kcal per kg per hour), Apple's physical effort. Effort, /// Litres of air (lung function). Litres, /// Litres per minute (peak flow). LitresPerMinute, /// International units (insulin). InternationalUnits,}/// A daily summary metric.#[derive(Debug, Clone, Copy, PartialEq, Serialize)]pub struct Metric { /// The `health_day.metric` value. pub key: &'static str, /// The unit the row keeps (`health_day.unit`). pub unit: &'static str, pub fold: Fold, /// The HealthKit type the phone reads; also the export's `type`. pub healthkit: &'static str, /// The unit string the phone hands `HKUnit(from:)` for a quantity type; /// empty for a category type. pub healthkit_unit: &'static str, /// The HealthKit category value this metric counts, for the several /// metrics one category type makes (sleep's stages). #[serde(skip_serializing_if = "Option::is_none")] pub stage: Option<SleepStage>, /// The Health Connect record a later Android source reads. #[serde(skip_serializing_if = "Option::is_none")] pub health_connect: Option<&'static str>, #[serde(skip)] pub dimension: Dimension,}/// A sleep sample's stage, HealthKit's `HKCategoryValueSleepAnalysis`.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]#[serde(rename_all = "snake_case")]pub enum SleepStage { InBed, /// Asleep, stage not said (an iPhone's own estimate, older watches). Asleep, Awake, Core, Deep, Rem,}impl SleepStage { /// HealthKit's raw value (`HKCategoryValueSleepAnalysis.rawValue`). pub fn of_raw(raw: i64) -> Option<SleepStage> { Some(match raw { 0 => SleepStage::InBed, 1 => SleepStage::Asleep, 2 => SleepStage::Awake, 3 => SleepStage::Core, 4 => SleepStage::Deep, 5 => SleepStage::Rem, _ => return None, }) } /// The export's word (`HKCategoryValueSleepAnalysisAsleepCore`; the /// export of an older phone says `...Asleep`). pub fn of_word(word: &str) -> Option<SleepStage> { Some(match word.strip_prefix("HKCategoryValueSleepAnalysis")? { "InBed" => SleepStage::InBed, "Asleep" | "AsleepUnspecified" => SleepStage::Asleep, "Awake" => SleepStage::Awake, "AsleepCore" => SleepStage::Core, "AsleepDeep" => SleepStage::Deep, "AsleepREM" => SleepStage::Rem, _ => return None, }) } /// Is this stage asleep (counts toward `sleep_asleep`)? pub fn is_asleep(self) -> bool { matches!(self, SleepStage::Asleep | SleepStage::Core | SleepStage::Deep | SleepStage::Rem) }}pub const STEP_COUNT: &str = "HKQuantityTypeIdentifierStepCount";pub const SLEEP: &str = "HKCategoryTypeIdentifierSleepAnalysis";pub const MINDFUL: &str = "HKCategoryTypeIdentifierMindfulSession";pub const STAND_HOUR: &str = "HKCategoryTypeIdentifierAppleStandHour";pub const MENSTRUAL_FLOW: &str = "HKCategoryTypeIdentifierMenstrualFlow";pub const SYSTOLIC: &str = "HKQuantityTypeIdentifierBloodPressureSystolic";pub const DIASTOLIC: &str = "HKQuantityTypeIdentifierBloodPressureDiastolic";pub const BLOOD_PRESSURE: &str = "HKCorrelationTypeIdentifierBloodPressure";pub const BODY_MASS: &str = "HKQuantityTypeIdentifierBodyMass";pub const GLUCOSE: &str = "HKQuantityTypeIdentifierBloodGlucose";pub const TEMPERATURE: &str = "HKQuantityTypeIdentifierBodyTemperature";pub const WORKOUT: &str = "HKWorkoutTypeIdentifier";pub const HEART_RATE: &str = "HKQuantityTypeIdentifierHeartRate";const fn metric(key: &'static str, unit: &'static str, fold: Fold, healthkit: &'static str, healthkit_unit: &'static str, health_connect: Option<&'static str>, dimension: Dimension) -> Metric { Metric { key, unit, fold, healthkit, healthkit_unit, stage: None, health_connect, dimension }}const fn sleep(key: &'static str, stage: SleepStage) -> Metric { Metric { key, unit: "min", fold: Fold::Sleep, healthkit: SLEEP, healthkit_unit: "", stage: Some(stage), health_connect: Some("SleepSessionRecord"), dimension: Dimension::Duration }}/// Every daily metric, in the order a day reads (activity, heart, sleep,/// body, the rest).pub const METRICS: &[Metric] = &[ metric("steps", "steps", Fold::Sum, STEP_COUNT, "count", Some("StepsRecord"), Dimension::Count), metric("distance", "m", Fold::Sum, "HKQuantityTypeIdentifierDistanceWalkingRunning", "m", Some("DistanceRecord"), Dimension::Length), metric("active_energy", "kcal", Fold::Sum, "HKQuantityTypeIdentifierActiveEnergyBurned", "kcal", Some("ActiveCaloriesBurnedRecord"), Dimension::Energy), metric("flights", "flights", Fold::Sum, "HKQuantityTypeIdentifierFlightsClimbed", "count", Some("FloorsClimbedRecord"), Dimension::Count), metric("stand_hours", "h", Fold::Hours, STAND_HOUR, "", None, Dimension::Category), metric("resting_heart_rate", "bpm", Fold::Average, "HKQuantityTypeIdentifierRestingHeartRate", "count/min", Some("RestingHeartRateRecord"), Dimension::Rate), // Health Connect's variability is RMSSD where HealthKit's is SDNN: the // Android reader lands it under its own key when it comes. metric("heart_rate_variability", "ms", Fold::Average, "HKQuantityTypeIdentifierHeartRateVariabilitySDNN", "ms", None, Dimension::Milliseconds), metric("vo2_max", "ml/kg/min", Fold::Latest, "HKQuantityTypeIdentifierVO2Max", "ml/(kg*min)", Some("Vo2MaxRecord"), Dimension::Oxygen), sleep("sleep_asleep", SleepStage::Asleep), sleep("sleep_in_bed", SleepStage::InBed), sleep("sleep_core", SleepStage::Core), sleep("sleep_deep", SleepStage::Deep), sleep("sleep_rem", SleepStage::Rem), sleep("sleep_awake", SleepStage::Awake), metric("weight", "kg", Fold::Latest, BODY_MASS, "kg", Some("WeightRecord"), Dimension::Mass), metric("body_fat", "%", Fold::Latest, "HKQuantityTypeIdentifierBodyFatPercentage", "%", Some("BodyFatRecord"), Dimension::Fraction), metric("blood_pressure_systolic", "mmHg", Fold::Average, SYSTOLIC, "mmHg", Some("BloodPressureRecord"), Dimension::Pressure), metric("blood_pressure_diastolic", "mmHg", Fold::Average, DIASTOLIC, "mmHg", Some("BloodPressureRecord"), Dimension::Pressure), metric("glucose", "mg/dL", Fold::Average, GLUCOSE, "mg/dL", Some("BloodGlucoseRecord"), Dimension::Glucose), metric("mindful_minutes", "min", Fold::Minutes, MINDFUL, "", Some("MindfulnessSessionRecord"), Dimension::Duration), metric("menstrual_flow", "", Fold::Flow, MENSTRUAL_FLOW, "", Some("MenstruationFlowRecord"), Dimension::Category), // ── Added 20 Nov 2026: every other type Apple Health // offers that a person sees as a day's number. Appended, never // reordered: health_day.metric's choices are this list in this order. metric("basal_energy", "kcal", Fold::Sum, "HKQuantityTypeIdentifierBasalEnergyBurned", "kcal", None, Dimension::Energy), metric("exercise_minutes", "min", Fold::Sum, "HKQuantityTypeIdentifierAppleExerciseTime", "min", Some("ExerciseSessionRecord"), Dimension::Duration), metric("stand_minutes", "min", Fold::Sum, "HKQuantityTypeIdentifierAppleStandTime", "min", None, Dimension::Duration), metric("move_minutes", "min", Fold::Sum, "HKQuantityTypeIdentifierAppleMoveTime", "min", None, Dimension::Duration), metric("distance_cycling", "m", Fold::Sum, "HKQuantityTypeIdentifierDistanceCycling", "m", None, Dimension::Length), metric("distance_swimming", "m", Fold::Sum, "HKQuantityTypeIdentifierDistanceSwimming", "m", None, Dimension::Length), metric("distance_wheelchair", "m", Fold::Sum, "HKQuantityTypeIdentifierDistanceWheelchair", "m", Some("WheelchairPushesRecord"), Dimension::Length), metric("distance_snow_sports", "m", Fold::Sum, "HKQuantityTypeIdentifierDistanceDownhillSnowSports", "m", None, Dimension::Length), metric("push_count", "pushes", Fold::Sum, "HKQuantityTypeIdentifierPushCount", "count", None, Dimension::Count), metric("swimming_strokes", "strokes", Fold::Sum, "HKQuantityTypeIdentifierSwimmingStrokeCount", "count", None, Dimension::Count), metric("time_in_daylight", "min", Fold::Sum, "HKQuantityTypeIdentifierTimeInDaylight", "min", None, Dimension::Duration), metric("falls", "falls", Fold::Sum, "HKQuantityTypeIdentifierNumberOfTimesFallen", "count", None, Dimension::Count), metric("heart_rate", "bpm", Fold::Average, HEART_RATE, "count/min", Some("HeartRateRecord"), Dimension::Rate), metric("walking_heart_rate", "bpm", Fold::Average, "HKQuantityTypeIdentifierWalkingHeartRateAverage", "count/min", None, Dimension::Rate), metric("oxygen_saturation", "%", Fold::Average, "HKQuantityTypeIdentifierOxygenSaturation", "%", Some("OxygenSaturationRecord"), Dimension::Fraction), metric("respiratory_rate", "breaths/min", Fold::Average, "HKQuantityTypeIdentifierRespiratoryRate", "count/min", Some("RespiratoryRateRecord"), Dimension::Rate), metric("wrist_temperature", "°C", Fold::Average, "HKQuantityTypeIdentifierAppleSleepingWristTemperature", "degC", None, Dimension::Temperature), metric("breathing_disturbances", "count", Fold::Average, "HKQuantityTypeIdentifierAppleSleepingBreathingDisturbances", "count", None, Dimension::Count), metric("walking_speed", "m/s", Fold::Average, "HKQuantityTypeIdentifierWalkingSpeed", "m/s", Some("SpeedRecord"), Dimension::Speed), metric("walking_step_length", "m", Fold::Average, "HKQuantityTypeIdentifierWalkingStepLength", "m", None, Dimension::Length), metric("walking_asymmetry", "%", Fold::Average, "HKQuantityTypeIdentifierWalkingAsymmetryPercentage", "%", None, Dimension::Fraction), metric("walking_double_support", "%", Fold::Average, "HKQuantityTypeIdentifierWalkingDoubleSupportPercentage", "%", None, Dimension::Fraction), metric("walking_steadiness", "%", Fold::Latest, "HKQuantityTypeIdentifierAppleWalkingSteadiness", "%", None, Dimension::Fraction), metric("stair_ascent_speed", "m/s", Fold::Average, "HKQuantityTypeIdentifierStairAscentSpeed", "m/s", None, Dimension::Speed), metric("stair_descent_speed", "m/s", Fold::Average, "HKQuantityTypeIdentifierStairDescentSpeed", "m/s", None, Dimension::Speed), metric("six_minute_walk", "m", Fold::Latest, "HKQuantityTypeIdentifierSixMinuteWalkTestDistance", "m", None, Dimension::Length), metric("running_speed", "m/s", Fold::Average, "HKQuantityTypeIdentifierRunningSpeed", "m/s", None, Dimension::Speed), metric("running_power", "W", Fold::Average, "HKQuantityTypeIdentifierRunningPower", "W", Some("PowerRecord"), Dimension::Power), metric("running_stride_length", "m", Fold::Average, "HKQuantityTypeIdentifierRunningStrideLength", "m", None, Dimension::Length), metric("running_vertical_oscillation", "m", Fold::Average, "HKQuantityTypeIdentifierRunningVerticalOscillation", "m", None, Dimension::Length), metric("running_ground_contact", "ms", Fold::Average, "HKQuantityTypeIdentifierRunningGroundContactTime", "ms", None, Dimension::Milliseconds), metric("cycling_speed", "m/s", Fold::Average, "HKQuantityTypeIdentifierCyclingSpeed", "m/s", None, Dimension::Speed), metric("cycling_power", "W", Fold::Average, "HKQuantityTypeIdentifierCyclingPower", "W", None, Dimension::Power), metric("cycling_cadence", "rpm", Fold::Average, "HKQuantityTypeIdentifierCyclingCadence", "count/min", Some("CyclingPedalingCadenceRecord"), Dimension::Rate), metric("environmental_audio", "dB", Fold::Average, "HKQuantityTypeIdentifierEnvironmentalAudioExposure", "dBASPL", None, Dimension::Decibel), metric("headphone_audio", "dB", Fold::Average, "HKQuantityTypeIdentifierHeadphoneAudioExposure", "dBASPL", None, Dimension::Decibel), metric("body_mass_index", "BMI", Fold::Latest, "HKQuantityTypeIdentifierBodyMassIndex", "count", None, Dimension::Index), metric("lean_body_mass", "kg", Fold::Latest, "HKQuantityTypeIdentifierLeanBodyMass", "kg", Some("LeanBodyMassRecord"), Dimension::Mass), metric("height", "m", Fold::Latest, "HKQuantityTypeIdentifierHeight", "m", Some("HeightRecord"), Dimension::Length), metric("waist", "m", Fold::Latest, "HKQuantityTypeIdentifierWaistCircumference", "m", None, Dimension::Length), metric("uv_exposure", "UV index", Fold::Average, "HKQuantityTypeIdentifierUVExposure", "count", None, Dimension::Index), metric("dietary_energy", "kcal", Fold::Sum, "HKQuantityTypeIdentifierDietaryEnergyConsumed", "kcal", Some("NutritionRecord"), Dimension::Energy), metric("protein", "g", Fold::Sum, "HKQuantityTypeIdentifierDietaryProtein", "g", Some("NutritionRecord"), Dimension::Grams), metric("carbohydrates", "g", Fold::Sum, "HKQuantityTypeIdentifierDietaryCarbohydrates", "g", Some("NutritionRecord"), Dimension::Grams), metric("fat", "g", Fold::Sum, "HKQuantityTypeIdentifierDietaryFatTotal", "g", Some("NutritionRecord"), Dimension::Grams), metric("saturated_fat", "g", Fold::Sum, "HKQuantityTypeIdentifierDietaryFatSaturated", "g", Some("NutritionRecord"), Dimension::Grams), metric("sugar", "g", Fold::Sum, "HKQuantityTypeIdentifierDietarySugar", "g", Some("NutritionRecord"), Dimension::Grams), metric("fibre", "g", Fold::Sum, "HKQuantityTypeIdentifierDietaryFiber", "g", Some("NutritionRecord"), Dimension::Grams), metric("sodium", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietarySodium", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("dietary_cholesterol", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryCholesterol", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("potassium", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryPotassium", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("calcium", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryCalcium", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("iron", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryIron", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("vitamin_c", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryVitaminC", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("vitamin_d", "µg", Fold::Sum, "HKQuantityTypeIdentifierDietaryVitaminD", "mcg", Some("NutritionRecord"), Dimension::Micrograms), metric("caffeine", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryCaffeine", "mg", None, Dimension::Milligrams), metric("water", "mL", Fold::Sum, "HKQuantityTypeIdentifierDietaryWater", "mL", Some("HydrationRecord"), Dimension::Volume), metric("toothbrushing", "min", Fold::Minutes, "HKCategoryTypeIdentifierToothbrushingEvent", "", None, Dimension::Duration), metric("handwashing", "times", Fold::Count, "HKCategoryTypeIdentifierHandwashingEvent", "", None, Dimension::Category), metric("high_heart_rate_events", "times", Fold::Count, "HKCategoryTypeIdentifierHighHeartRateEvent", "", None, Dimension::Category), metric("low_heart_rate_events", "times", Fold::Count, "HKCategoryTypeIdentifierLowHeartRateEvent", "", None, Dimension::Category), metric("irregular_rhythm_events", "times", Fold::Count, "HKCategoryTypeIdentifierIrregularHeartRhythmEvent", "", None, Dimension::Category), metric("low_cardio_fitness_events", "times", Fold::Count, "HKCategoryTypeIdentifierLowCardioFitnessEvent", "", None, Dimension::Category), metric("walking_steadiness_events", "times", Fold::Count, "HKCategoryTypeIdentifierAppleWalkingSteadinessEvent", "", None, Dimension::Category), metric("loud_environment_events", "times", Fold::Count, "HKCategoryTypeIdentifierAudioExposureEvent", "", None, Dimension::Category), metric("loud_headphone_events", "times", Fold::Count, "HKCategoryTypeIdentifierHeadphoneAudioExposureEvent", "", None, Dimension::Category), metric("sleep_apnea_events", "times", Fold::Count, "HKCategoryTypeIdentifierSleepApneaEvent", "", None, Dimension::Category), metric("sexual_activity", "times", Fold::Count, "HKCategoryTypeIdentifierSexualActivity", "", Some("SexualActivityRecord"), Dimension::Category), metric("intermenstrual_bleeding", "times", Fold::Count, "HKCategoryTypeIdentifierIntermenstrualBleeding", "", Some("IntermenstrualBleedingRecord"), Dimension::Category), // ── Added 20 Nov 2026: the rest of what Apple Health // offers: the other distances, effort, heart recovery and AFib history, // lung function, every nutrient, and cycle tracking's // notifications. Appended. metric("distance_rowing", "m", Fold::Sum, "HKQuantityTypeIdentifierDistanceRowing", "m", None, Dimension::Length), metric("distance_paddling", "m", Fold::Sum, "HKQuantityTypeIdentifierDistancePaddleSports", "m", None, Dimension::Length), metric("distance_skating", "m", Fold::Sum, "HKQuantityTypeIdentifierDistanceSkatingSports", "m", None, Dimension::Length), metric("distance_cross_country_skiing", "m", Fold::Sum, "HKQuantityTypeIdentifierDistanceCrossCountrySkiing", "m", None, Dimension::Length), metric("physical_effort", "MET", Fold::Average, "HKQuantityTypeIdentifierPhysicalEffort", "kcal/(kg*hr)", None, Dimension::Effort), metric("heart_rate_recovery", "bpm", Fold::Latest, "HKQuantityTypeIdentifierHeartRateRecoveryOneMinute", "count/min", None, Dimension::Rate), metric("afib_burden", "%", Fold::Latest, "HKQuantityTypeIdentifierAtrialFibrillationBurden", "%", None, Dimension::Fraction), metric("basal_body_temperature", "°C", Fold::Latest, "HKQuantityTypeIdentifierBasalBodyTemperature", "degC", Some("BasalBodyTemperatureRecord"), Dimension::Temperature), metric("peripheral_perfusion", "%", Fold::Average, "HKQuantityTypeIdentifierPeripheralPerfusionIndex", "%", None, Dimension::Fraction), metric("blood_alcohol", "%", Fold::Latest, "HKQuantityTypeIdentifierBloodAlcoholContent", "%", None, Dimension::Fraction), metric("forced_vital_capacity", "L", Fold::Latest, "HKQuantityTypeIdentifierForcedVitalCapacity", "L", None, Dimension::Litres), metric("forced_expiratory_volume", "L", Fold::Latest, "HKQuantityTypeIdentifierForcedExpiratoryVolume1", "L", None, Dimension::Litres), metric("peak_expiratory_flow", "L/min", Fold::Latest, "HKQuantityTypeIdentifierPeakExpiratoryFlowRate", "L/min", None, Dimension::LitresPerMinute), metric("inhaler_uses", "uses", Fold::Sum, "HKQuantityTypeIdentifierInhalerUsage", "count", None, Dimension::Count), metric("insulin", "IU", Fold::Sum, "HKQuantityTypeIdentifierInsulinDelivery", "IU", None, Dimension::InternationalUnits), metric("cycling_ftp", "W", Fold::Latest, "HKQuantityTypeIdentifierCyclingFunctionalThresholdPower", "W", None, Dimension::Power), metric("environmental_sound_reduction", "dB", Fold::Average, "HKQuantityTypeIdentifierEnvironmentalSoundReduction", "dBASPL", None, Dimension::Decibel), metric("fat_monounsaturated", "g", Fold::Sum, "HKQuantityTypeIdentifierDietaryFatMonounsaturated", "g", Some("NutritionRecord"), Dimension::Grams), metric("fat_polyunsaturated", "g", Fold::Sum, "HKQuantityTypeIdentifierDietaryFatPolyunsaturated", "g", Some("NutritionRecord"), Dimension::Grams), metric("magnesium", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryMagnesium", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("phosphorus", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryPhosphorus", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("zinc", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryZinc", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("copper", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryCopper", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("manganese", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryManganese", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("chloride", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryChloride", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("selenium", "µg", Fold::Sum, "HKQuantityTypeIdentifierDietarySelenium", "mcg", Some("NutritionRecord"), Dimension::Micrograms), metric("iodine", "µg", Fold::Sum, "HKQuantityTypeIdentifierDietaryIodine", "mcg", Some("NutritionRecord"), Dimension::Micrograms), metric("chromium", "µg", Fold::Sum, "HKQuantityTypeIdentifierDietaryChromium", "mcg", Some("NutritionRecord"), Dimension::Micrograms), metric("molybdenum", "µg", Fold::Sum, "HKQuantityTypeIdentifierDietaryMolybdenum", "mcg", Some("NutritionRecord"), Dimension::Micrograms), metric("vitamin_a", "µg", Fold::Sum, "HKQuantityTypeIdentifierDietaryVitaminA", "mcg", Some("NutritionRecord"), Dimension::Micrograms), metric("vitamin_b6", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryVitaminB6", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("vitamin_b12", "µg", Fold::Sum, "HKQuantityTypeIdentifierDietaryVitaminB12", "mcg", Some("NutritionRecord"), Dimension::Micrograms), metric("vitamin_e", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryVitaminE", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("vitamin_k", "µg", Fold::Sum, "HKQuantityTypeIdentifierDietaryVitaminK", "mcg", Some("NutritionRecord"), Dimension::Micrograms), metric("thiamin", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryThiamin", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("riboflavin", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryRiboflavin", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("niacin", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryNiacin", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("folate", "µg", Fold::Sum, "HKQuantityTypeIdentifierDietaryFolate", "mcg", Some("NutritionRecord"), Dimension::Micrograms), metric("biotin", "µg", Fold::Sum, "HKQuantityTypeIdentifierDietaryBiotin", "mcg", Some("NutritionRecord"), Dimension::Micrograms), metric("pantothenic_acid", "mg", Fold::Sum, "HKQuantityTypeIdentifierDietaryPantothenicAcid", "mg", Some("NutritionRecord"), Dimension::Milligrams), metric("alcoholic_drinks", "drinks", Fold::Sum, "HKQuantityTypeIdentifierNumberOfAlcoholicBeverages", "count", None, Dimension::Count), metric("irregular_cycle_events", "times", Fold::Count, "HKCategoryTypeIdentifierIrregularMenstrualCycles", "", None, Dimension::Category), metric("infrequent_cycle_events", "times", Fold::Count, "HKCategoryTypeIdentifierInfrequentMenstrualCycles", "", None, Dimension::Category), metric("prolonged_period_events", "times", Fold::Count, "HKCategoryTypeIdentifierProlongedMenstrualPeriods", "", None, Dimension::Category), metric("persistent_bleeding_events", "times", Fold::Count, "HKCategoryTypeIdentifierPersistentIntermenstrualBleeding", "", None, Dimension::Category),];/// The metric `key` names.pub fn metric_of(key: &str) -> Option<&'static Metric> { METRICS.iter().find(|metric| metric.key == key)}/// The one quantity metric a HealthKit type feeds (sleep's several stages/// and the category types are read by their own rules).pub fn quantity_metric(healthkit: &str) -> Option<&'static Metric> { METRICS.iter().find(|metric| metric.healthkit == healthkit && !metric.healthkit_unit.is_empty())}/// A point measurement's kind (`health_measurement.kind`).#[derive(Debug, Clone, Copy, PartialEq, Serialize)]pub struct Measure { pub kind: &'static str, pub unit: &'static str, /// The HealthKit type it is read from (blood pressure: the correlation). pub healthkit: &'static str, pub healthkit_unit: &'static str, #[serde(skip)] pub dimension: Dimension,}pub const MEASURES: &[Measure] = &[ Measure { kind: "weight", unit: "kg", healthkit: BODY_MASS, healthkit_unit: "kg", dimension: Dimension::Mass }, Measure { kind: "blood_pressure", unit: "mmHg", healthkit: BLOOD_PRESSURE, healthkit_unit: "mmHg", dimension: Dimension::Pressure }, Measure { kind: "glucose", unit: "mg/dL", healthkit: GLUCOSE, healthkit_unit: "mg/dL", dimension: Dimension::Glucose }, Measure { kind: "temperature", unit: "°C", healthkit: TEMPERATURE, healthkit_unit: "degC", dimension: Dimension::Temperature }, // Added 20 Nov 2026: the other sparse readings a person takes, each kept raw. Measure { kind: "body_fat", unit: "%", healthkit: "HKQuantityTypeIdentifierBodyFatPercentage", healthkit_unit: "%", dimension: Dimension::Fraction }, Measure { kind: "body_mass_index", unit: "BMI", healthkit: "HKQuantityTypeIdentifierBodyMassIndex", healthkit_unit: "count", dimension: Dimension::Index }, Measure { kind: "lean_body_mass", unit: "kg", healthkit: "HKQuantityTypeIdentifierLeanBodyMass", healthkit_unit: "kg", dimension: Dimension::Mass }, Measure { kind: "height", unit: "m", healthkit: "HKQuantityTypeIdentifierHeight", healthkit_unit: "m", dimension: Dimension::Length }, Measure { kind: "waist", unit: "m", healthkit: "HKQuantityTypeIdentifierWaistCircumference", healthkit_unit: "m", dimension: Dimension::Length }, Measure { kind: "vo2_max", unit: "ml/kg/min", healthkit: "HKQuantityTypeIdentifierVO2Max", healthkit_unit: "ml/(kg*min)", dimension: Dimension::Oxygen }, Measure { kind: "six_minute_walk", unit: "m", healthkit: "HKQuantityTypeIdentifierSixMinuteWalkTestDistance", healthkit_unit: "m", dimension: Dimension::Length },];pub fn measure_of(kind: &str) -> Option<&'static Measure> { MEASURES.iter().find(|measure| measure.kind == kind)}/// A HealthKit type the app asks to read, and what it feeds.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct ReadType { /// `HKQuantityTypeIdentifier…`, `HKCategoryTypeIdentifier…`, /// `HKCorrelationTypeIdentifier…` or `HKWorkoutTypeIdentifier`. pub healthkit: &'static str, /// quantity, category, correlation or workout: how the shell queries it. pub kind: &'static str, /// The unit string for `HKUnit(from:)`, for a quantity. #[serde(skip_serializing_if = "str::is_empty")] pub unit: &'static str, /// What the phone sends for it, one or more of: `days` (the day's /// statistics, a cumulative sum or a discrete average/min/max/most /// recent), `intervals` (each sample's start, end and value, for whole /// days), `measurements` (each sample) or `workouts`. Weight and glucose /// are both a day's number and measurements. pub sends: Vec<&'static str>, /// For `days`, the statistics option the shell asks: cumulativeSum, /// discreteAverage (with min and max) or mostRecent. #[serde(skip_serializing_if = "Option::is_none")] pub statistics: Option<&'static str>,}fn kind_of(healthkit: &str) -> &'static str { if healthkit.starts_with("HKQuantity") { "quantity" } else if healthkit.starts_with("HKCategory") { "category" } else if healthkit.starts_with("HKCorrelation") { "correlation" } else { "workout" }}/// Every HealthKit type Cotton Health reads, once each: what the app asks/// authorisation for and the anchored queries it keeps. Read-only: the app/// never asks to share (write) a type.pub fn read_types() -> Vec<ReadType> { let mut out: Vec<ReadType> = Vec::new(); for metric in METRICS { if out.iter().any(|known| known.healthkit == metric.healthkit) { continue; } let (sends, statistics) = match metric.fold { Fold::Sum => ("days", Some("cumulativeSum")), Fold::Average => ("days", Some("discreteAverage")), Fold::Latest => ("days", Some("mostRecent")), Fold::Sleep | Fold::Minutes | Fold::Hours | Fold::Flow | Fold::Count => ("intervals", None), }; out.push(ReadType { healthkit: metric.healthkit, kind: kind_of(metric.healthkit), unit: metric.healthkit_unit, sends: vec![sends], statistics }); } for measure in MEASURES { match out.iter_mut().find(|known| known.healthkit == measure.healthkit) { Some(known) => known.sends.push("measurements"), None => out.push(ReadType { healthkit: measure.healthkit, kind: kind_of(measure.healthkit), unit: measure.healthkit_unit, sends: vec!["measurements"], statistics: None }), } } // A workout's average and most heart rate are its own statistics // (`HKWorkout.statistics(for: heartRate)`), which need heart rate read; // the heart-rate stream itself is never sent. out.push(ReadType { healthkit: WORKOUT, kind: "workout", unit: "", sends: vec!["workouts"], statistics: None }); match out.iter_mut().find(|known| known.healthkit == HEART_RATE) { Some(known) => known.sends.push("workouts"), None => out.push(ReadType { healthkit: HEART_RATE, kind: "quantity", unit: "count/min", sends: vec!["workouts"], statistics: None }), } out}/// `value` spoken in `unit`, in `dimension`'s kept unit, or `None` for a/// unit this reader does not know (the sample is left out, never guessed)./// HealthKit's and the export's unit strings both: `km`, `mi`, `kJ`, `lb`,/// `%` (a fraction, kept as a percentage), `mmol<180.15588000005408>/L`,/// `degF`.pub fn canonical(dimension: Dimension, value: f64, unit: &str) -> Option<f64> { if !value.is_finite() { return None; } let unit = unit.trim(); let out = match dimension { Dimension::Count => match unit { "count" | "" => value, _ => return None, }, Dimension::Length => match unit { "m" => value, "km" => value * 1000.0, "cm" => value / 100.0, "mi" => value * 1609.344, "ft" => value * 0.3048, "yd" => value * 0.9144, _ => return None, }, Dimension::Energy => match unit { "kcal" | "Cal" => value, "cal" => value / 1000.0, "kJ" => value / 4.184, "J" => value / 4184.0, _ => return None, }, Dimension::Rate => match unit { "count/min" | "bpm" => value, "count/s" => value * 60.0, _ => return None, }, Dimension::Milliseconds => match unit { "ms" => value, "s" => value * 1000.0, _ => return None, }, Dimension::Mass => match unit { "kg" => value, "g" => value / 1000.0, "lb" => value * 0.453_592_37, "st" => value * 6.350_293_18, _ => return None, }, // HealthKit's percent is a fraction (0.21 for 21 %). Dimension::Fraction => match unit { "%" => value * 100.0, _ => return None, }, Dimension::Pressure => match unit { "mmHg" => value, "kPa" => value * 7.500_615_75, _ => return None, }, Dimension::Glucose => match unit { "mg/dL" | "mg/dl" => value, unit if unit.starts_with("mmol") && unit.ends_with("/L") => value * 18.015_588, _ => return None, }, Dimension::Temperature => match unit { "degC" | "°C" => value, "degF" | "°F" => (value - 32.0) * 5.0 / 9.0, _ => return None, }, Dimension::Oxygen => match unit { "ml/(kg*min)" | "mL/min·kg" | "mL/(kg*min)" | "ml/(kg·min)" => value, _ => return None, }, Dimension::Duration => match unit { "min" => value, "s" => value / 60.0, "hr" | "h" => value * 60.0, _ => return None, }, Dimension::Category => value, Dimension::Speed => match unit { "m/s" => value, "km/hr" | "km/h" => value / 3.6, "mi/hr" | "mph" => value * 0.447_04, _ => return None, }, Dimension::Power => match unit { "W" => value, "kW" => value * 1000.0, _ => return None, }, Dimension::Decibel => match unit { "dBASPL" | "dB" | "dBA" => value, _ => return None, }, Dimension::Index => match unit { "count" | "" => value, _ => return None, }, Dimension::Grams => match unit { "g" => value, "mg" => value / 1000.0, "kg" => value * 1000.0, "oz" => value * 28.349_523_125, _ => return None, }, Dimension::Milligrams => match unit { "mg" => value, "g" => value * 1000.0, "mcg" | "µg" => value / 1000.0, _ => return None, }, Dimension::Micrograms => match unit { "mcg" | "µg" => value, "mg" => value * 1000.0, "g" => value * 1_000_000.0, _ => return None, }, Dimension::Effort => match unit { "kcal/(kg*hr)" | "kcal/hr·kg" | "MET" => value, _ => return None, }, Dimension::Litres => match unit { "L" => value, "mL" | "ml" => value / 1000.0, _ => return None, }, Dimension::LitresPerMinute => match unit { "L/min" => value, "L/s" => value * 60.0, _ => return None, }, Dimension::InternationalUnits => match unit { "IU" => value, _ => return None, }, Dimension::Volume => match unit { "mL" | "ml" => value, "L" | "l" => value * 1000.0, "fl_oz_us" => value * 29.573_529_562_5, "cup_us" => value * 236.588_236_5, _ => return None, }, }; Some(out)}/// A workout's kind, from HealthKit's `HKWorkoutActivityType` raw value./// An unknown number is `other`.pub fn workout_kind_of_raw(raw: i64) -> &'static str { WORKOUT_KINDS.iter().find(|(number, _)| *number == raw).map(|(_, kind)| *kind).unwrap_or("other")}/// A workout's kind from the export's word (`HKWorkoutActivityTypeRunning`)/// or a kind already said (`running`); an unknown word is `other`.pub fn workout_kind_of_word(word: &str) -> &'static str { let name = word.strip_prefix("HKWorkoutActivityType").unwrap_or(word); let snake = snake_case(name); WORKOUT_KINDS.iter().find(|(_, kind)| *kind == snake).map(|(_, kind)| *kind).unwrap_or("other")}fn snake_case(name: &str) -> String { let mut out = String::new(); for (index, ch) in name.chars().enumerate() { if ch.is_ascii_uppercase() { if index > 0 { out.push('_'); } out.push(ch.to_ascii_lowercase()); } else { out.push(ch); } } out}/// `HKWorkoutActivityType`'s raw values and the kind each is kept as.pub const WORKOUT_KINDS: &[(i64, &str)] = &[ (1, "american_football"), (2, "archery"), (3, "australian_football"), (4, "badminton"), (5, "baseball"), (6, "basketball"), (7, "bowling"), (8, "boxing"), (9, "climbing"), (10, "cricket"), (11, "cross_training"), (12, "curling"), (13, "cycling"), (14, "dance"), (16, "elliptical"), (17, "equestrian_sports"), (18, "fencing"), (19, "fishing"), (20, "functional_strength_training"), (21, "golf"), (22, "gymnastics"), (23, "handball"), (24, "hiking"), (25, "hockey"), (26, "hunting"), (27, "lacrosse"), (28, "martial_arts"), (29, "mind_and_body"), (31, "paddle_sports"), (32, "play"), (33, "preparation_and_recovery"), (34, "racquetball"), (35, "rowing"), (36, "rugby"), (37, "running"), (38, "sailing"), (39, "skating_sports"), (40, "snow_sports"), (41, "soccer"), (42, "softball"), (43, "squash"), (44, "stair_climbing"), (45, "surfing_sports"), (46, "swimming"), (47, "table_tennis"), (48, "tennis"), (49, "track_and_field"), (50, "traditional_strength_training"), (51, "volleyball"), (52, "walking"), (53, "water_fitness"), (54, "water_polo"), (55, "water_sports"), (56, "wrestling"), (57, "yoga"), (58, "barre"), (59, "core_training"), (60, "cross_country_skiing"), (61, "downhill_skiing"), (62, "flexibility"), (63, "high_intensity_interval_training"), (64, "jump_rope"), (65, "kickboxing"), (66, "pilates"), (67, "snowboarding"), (68, "stairs"), (69, "step_training"), (70, "wheelchair_walk_pace"), (71, "wheelchair_run_pace"), (72, "tai_chi"), (73, "mixed_cardio"), (74, "hand_cycling"), (75, "disc_sports"), (76, "fitness_gaming"), (77, "cardio_dance"), (78, "social_dance"), (79, "pickleball"), (80, "cooldown"), (82, "swim_bike_run"), (83, "transition"), (84, "underwater_diving"), (3000, "other"),];