194 lines · 10.4 KB · RustRaw
//! Body, decided: the owner's Apple Health days by section, and for anyone//! the vitals their reports printed (weight, BMI, height, blood pressure)//! on the same history. PURE.use serde_json::{json, Value};use super::labs::{act, PersonEntry, ResultEntry};use super::shapes::*;use super::{day_said, number_said, say, sayf};use crate::health::catalog;use crate::health::rows::DayRow;/// Body's sections, in order, and the metrics each holds.pub const SECTIONS: &[(&str, &[&str])] = &[ ("activity", &["steps", "distance", "active_energy", "basal_energy", "exercise_minutes", "stand_hours", "stand_minutes", "move_minutes", "flights", "distance_cycling", "distance_swimming", "distance_wheelchair", "distance_snow_sports", "push_count", "swimming_strokes", "time_in_daylight", "uv_exposure", "falls"]), ("heart", &["heart_rate", "resting_heart_rate", "walking_heart_rate", "heart_rate_variability", "vo2_max", "oxygen_saturation", "respiratory_rate", "blood_pressure_systolic", "blood_pressure_diastolic"]), ("sleep", &["sleep_asleep", "sleep_in_bed", "sleep_core", "sleep_deep", "sleep_rem", "sleep_awake", "wrist_temperature", "breathing_disturbances"]), ("body", &["weight", "body_fat", "body_mass_index", "lean_body_mass", "height", "waist", "glucose"]), ("mobility", &["walking_speed", "walking_step_length", "walking_asymmetry", "walking_double_support", "walking_steadiness", "stair_ascent_speed", "stair_descent_speed", "six_minute_walk", "running_speed", "running_power", "running_stride_length", "running_vertical_oscillation", "running_ground_contact", "cycling_speed", "cycling_power", "cycling_cadence"]), ("nutrition", &["dietary_energy", "protein", "carbohydrates", "fat", "saturated_fat", "sugar", "fibre", "sodium", "dietary_cholesterol", "potassium", "calcium", "iron", "vitamin_c", "vitamin_d", "caffeine", "water"]), ("hearing", &["environmental_audio", "headphone_audio"]), ("cycle", &["menstrual_flow", "intermenstrual_bleeding", "sexual_activity"]), ("more", &["mindful_minutes", "toothbrushing", "handwashing"]), ("events", &["high_heart_rate_events", "low_heart_rate_events", "irregular_rhythm_events", "low_cardio_fitness_events", "walking_steadiness_events", "loud_environment_events", "loud_headphone_events", "sleep_apnea_events"]),];/// The day's numbers on the owner's Today.pub const TODAY: &[&str] = &["steps", "distance", "active_energy", "exercise_minutes", "sleep_asleep", "resting_heart_rate"];/// A report's vital and the Apple Health metric it is one history with:/// (parameter, metric, factor from the parameter's unit to the metric's).pub const ONE_HISTORY: &[(&str, &str, f64)] = &[ ("body_weight", "weight", 1.0), ("bmi", "body_mass_index", 1.0), ("body_height", "height", 0.01), ("bp_systolic", "blood_pressure_systolic", 1.0), ("bp_diastolic", "blood_pressure_diastolic", 1.0),];/// A metric's label, as the `health_day` table names it.pub fn label(metric: &str) -> String { static LABELS: std::sync::OnceLock<serde_json::Map<String, Value>> = std::sync::OnceLock::new(); let labels = LABELS.get_or_init(|| { let table: Value = serde_json::from_str(include_str!("../../../kits/personal/tables/health_day.json")).expect("health_day reads"); table["columns"].as_array().and_then(|columns| columns.iter().find(|c| c["key"] == "metric")).and_then(|c| c["labels"].as_object()).cloned().unwrap_or_default() }); labels.get(metric).and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| metric.to_string())}/// A metric's value as drawn.pub fn value_said(metric: &str, value: f64, state: Option<&str>) -> Said { let unit = catalog::metric_of(metric).map(|m| m.unit).unwrap_or_default(); let said = |text: String, unit: &str| Said { text, unit: unit.to_string(), mono: true }; match unit { "" => Said { text: state.unwrap_or_default().to_string(), unit: String::new(), mono: false }, "steps" | "flights" | "pushes" | "strokes" | "falls" | "times" | "count" | "h" | "kcal" => said(crate::rules::shell_lines::number(value.round() as i64), unit), "m" if matches!(metric, "height" | "waist" | "walking_step_length" | "running_stride_length" | "running_vertical_oscillation") => said(number_said((value * 100.0).round()), "cm"), "m" if value >= 1000.0 => said(format!("{:.2}", value / 1000.0), "km"), "m" => said(number_said(value.round()), "m"), "min" if value >= 60.0 => { let minutes = value.round() as i64; said(format!("{} h {} min", minutes / 60, minutes % 60), "") } "min" => said(number_said(value.round()), "min"), "%" | "kg" | "BMI" | "ml/kg/min" | "UV index" => said(format!("{:.1}", value), unit), "°C" | "m/s" => said(format!("{:.2}", value), unit), _ if value.abs() < 10.0 => said(format!("{:.1}", value), unit), _ => said(number_said(value.round()), unit), }}/// One history point of a metric: Apple Health's day, or a report's vital.#[derive(Debug, Clone, PartialEq)]struct Reading { day: String, value: f64, min: Option<f64>, max: Option<f64>, state: Option<String>, source: &'static str,}fn readings(metric: &str, days: &[DayRow], results: &[ResultEntry], person: &PersonEntry) -> Vec<Reading> { let mut out: Vec<Reading> = Vec::new(); if person.owner { for row in days.iter().filter(|row| row.metric == metric) { if let Some(value) = row.value.or(if row.state.is_some() { Some(0.0) } else { None }) { out.push(Reading { day: row.day.clone(), value, min: row.min, max: row.max, state: row.state.clone(), source: "apple_health" }); } } } if let Some((parameter, _, factor)) = ONE_HISTORY.iter().find(|(_, m, _)| *m == metric) { for result in results.iter().filter(|r| r.person == person.id && r.parameter.as_deref() == Some(*parameter)) { if let Some(value) = result.canonical_value { out.push(Reading { day: result.day.clone(), value: value * factor, min: None, max: None, state: None, source: "lab" }); } } } out.sort_by(|a, b| a.day.cmp(&b.day)); out}fn point(reading: &Reading) -> Point { Point { day: reading.day.clone(), value: reading.value, min: reading.min, max: reading.max, source: Some(reading.source.to_string()), tone: None }}fn row(metric: &str, all: &[Reading], person: &PersonEntry) -> Option<MetricRow> { let latest = all.last()?; let mut trend: Vec<Point> = all.iter().map(point).collect(); if trend.len() > TREND_POINTS { trend.drain(..trend.len() - TREND_POINTS); } Some(MetricRow { metric: metric.to_string(), label: label(metric), latest: value_said(metric, latest.value, latest.state.as_deref()), day: day_said(&latest.day), trend, act: act("open", say("labs.open"), "health.metric", json!({ "person": person.id, "metric": metric })), })}/// `apple`: the phone reads Apple Health (an iPhone); elsewhere (Android) nothing asks to connect it, and the/// owner's empty Body says their reports' measures stand here. Days already kept (from an iPhone) draw either way.pub fn body(person: &PersonEntry, days: &[DayRow], results: &[ResultEntry], today: &str, apple: bool) -> BodyAnswer { let mut sections = Vec::new(); if person.owner { let rows: Vec<MetricRow> = TODAY .iter() .filter_map(|metric| { let today_only: Vec<Reading> = readings(metric, days, &[], person).into_iter().filter(|r| r.day == today).collect(); row(metric, &today_only, person) }) .collect(); if !rows.is_empty() { sections.push(BodySection { id: "today".into(), title: say("body.today"), rows }); } for (id, metrics) in SECTIONS { let rows: Vec<MetricRow> = metrics.iter().filter_map(|metric| row(metric, &readings(metric, days, results, person), person)).collect(); if !rows.is_empty() { sections.push(BodySection { id: (*id).into(), title: say(&format!("body.{id}")), rows }); } } } else { // Someone else's Body: only what their reports printed. let rows: Vec<MetricRow> = ONE_HISTORY.iter().filter_map(|(_, metric, _)| row(metric, &readings(metric, days, results, person), person)).collect(); if !rows.is_empty() { sections.push(BodySection { id: "from_reports".into(), title: say("body.from_reports"), rows }); } } let empty = sections.is_empty().then(|| { if person.owner && apple { Empty { title: say("body.empty_title"), body: say("body.empty_owner"), act: Some(act("connect", say("body.connect"), "health.act", json!({ "act": "connect_apple_health" }))) } } else if person.owner { Empty { title: say("body.empty_title"), body: say("body.empty_reports"), act: None } } else { Empty { title: say("body.empty_title"), body: sayf("body.empty_other", &[("name", &person.name)]), act: None } } }); BodyAnswer { person: person.id.clone(), owner: person.owner, title: say("body.title"), sections, connect: (person.owner && apple).then(|| act("connect", say("body.connect"), "health.act", json!({ "act": "connect_apple_health" }))), empty, }}pub fn metric(person: &PersonEntry, metric: &str, days: &[DayRow], results: &[ResultEntry]) -> MetricAnswer { let all = readings(metric, days, results, person); let unit = catalog::metric_of(metric).map(|m| m.unit.to_string()).unwrap_or_default(); MetricAnswer { person: person.id.clone(), metric: metric.to_string(), title: label(metric), unit, points: all.iter().map(point).collect(), readings: all .iter() .rev() .map(|reading| ReadingRow { day: day_said(&reading.day), said: value_said(metric, reading.value, reading.state.as_deref()), original: None, interval: String::new(), mark: Mark { id: reading.source.into(), label: say(if reading.source == "lab" { "body.from_report" } else { "body.from_apple" }), tone: Tone::Neutral }, lab: None, method: None, act: act("open", say("body.readings"), "health.metric", json!({ "person": person.id, "metric": metric })), }) .collect(), }}