dashboard/app/lib/health/body_model.dart
bashynx fb3c01cdd7 dashPi: a self-hosted home dashboard, its sync server and phone app
The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end
encrypted sync mailbox (PHP + SQLite) and the Android companion app
(Flutter), with docs, clean-install checks and screenshots made from
demo data.

Built mostly with an AI coding assistant; not yet reviewed line by line
by a human (see README and SECURITY.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 09:56:19 +02:00

344 lines
15 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Body measurements + vitals — a port of the dashboard's plugins/health calc.py (formulas,
// categories), views.py (latest per field, changes, series) and db.py (what a save does).
// Keep them in step with the web pages.
//
// Synced rows: "health.measure" id "measure:<day>" {day, weight, waist, hip, neck, chest, arm,
// thigh, fat_scale, note, updated}; "health.vital" {t "YYYY-MM-DD HH:MM", sys, dia, spo2, pulse,
// note, source} — imported ones have id "vital:<t>", ones typed here a random id.
import 'dart:math';
import '../sync/store.dart';
import 'cycle_model.dart' show iso, parseDay, daysBetween, today;
import 'summaries.dart';
const female = 'female';
const stale = 90; // days a measurement is still used for "now" / carried forward
/// key: (label, unit, min, max)
const fields = {
'weight': ('Weight', 'kg', 20.0, 400.0),
'waist': ('Waist', 'cm', 30.0, 250.0),
'hip': ('Hips', 'cm', 30.0, 250.0),
'neck': ('Neck', 'cm', 15.0, 80.0),
'chest': ('Chest', 'cm', 40.0, 250.0),
'arm': ('Upper arm', 'cm', 10.0, 80.0),
'thigh': ('Thigh', 'cm', 20.0, 120.0),
'fat_scale': ('Body fat from a scale', '%', 2.0, 75.0),
};
const fatDayFields = {'weight', 'waist', 'hip', 'neck', 'fat_scale'};
/// The values set on the dashboard (Settings ▸ Health), from its person summary (profileOf).
class Profile {
const Profile({this.sex = female, this.birth, this.height});
final String sex;
final DateTime? birth;
final double? height;
int? ageOn(DateTime d) {
final b = birth;
if (b == null) return null;
return d.year - b.year - ((d.month < b.month || (d.month == b.month && d.day < b.day)) ? 1 : 0);
}
}
/// The dashboard's Settings ▸ Health (sex, birth date, height) as its summary brings them; none yet = no age / height.
Profile profileOf(SyncStore store) {
final p = Summaries(store).meta('person') ?? {};
final b = DateTime.tryParse('${p['birth'] ?? ''}');
final h = (p['height'] as num?)?.toDouble();
return Profile(sex: p['sex'] == 'male' ? 'male' : female,
birth: b == null ? null : DateTime.utc(b.year, b.month, b.day), height: h == null || h <= 0 ? null : h);
}
// ---- formulas (calc.py) ---------------------------------------------------------------------
double _log10(double x) => log(x) / ln10;
double? bmi(double? w, double? h) => (w == null || h == null || w == 0 || h == 0) ? null : w / pow(h / 100, 2);
const bmiClasses = [(18.5, 'underweight'), (25.0, 'normal'), (30.0, 'overweight'), (35.0, 'obese (class I)'),
(40.0, 'obese (class II)'), (999.0, 'obese (class III)')];
String? bmiClass(double? b) => b == null ? null : bmiClasses.firstWhere((c) => b < c.$1).$2;
(double, double)? healthyWeight(double? h) => h == null ? null : (18.5 * pow(h / 100, 2), 24.9 * pow(h / 100, 2));
double? whtr(double? waist, double? h) => waist != null && h != null ? waist / h : null;
String? whtrClass(double? r) => r == null ? null : r < 0.4 ? 'low' : r < 0.5 ? 'healthy' : r < 0.6 ? 'raised' : 'high';
double? whr(double? waist, double? hip) => waist != null && hip != null ? waist / hip : null;
String? whrClass(double? r, String sex) => r == null ? null : r >= (sex == female ? 0.85 : 0.90) ? 'raised (WHO)' : 'healthy';
String? waistClass(double? w, String sex) {
if (w == null) return null;
final (a, b) = sex == female ? (80, 88) : (94, 102);
return w < a ? 'healthy' : w < b ? 'raised' : 'high';
}
double? navy(Map<String, double> m, double? h, String sex) {
final w = m['waist'], n = m['neck'], hip = m['hip'];
if (w == null || n == null || h == null) return null;
if (sex == female) {
if (hip == null || w + hip - n <= 0) return null;
return 495 / (1.29579 - 0.35004 * _log10(w + hip - n) + 0.22100 * _log10(h)) - 450;
}
if (w - n <= 0) return null;
return 495 / (1.0324 - 0.19077 * _log10(w - n) + 0.15456 * _log10(h)) - 450;
}
double? rfm(Map<String, double> m, double? h, String sex) {
final w = m['waist'];
return w == null || h == null ? null : (sex == female ? 76 : 64) - 20 * h / w;
}
double? ymca(Map<String, double> m, double? h, String sex) {
final w = m['waist'], kg = m['weight'];
if (w == null || kg == null) return null;
final lb = kg * 2.20462, inch = w / 2.54;
return (4.15 * inch - 0.082 * lb - (sex == female ? 76.76 : 98.42)) / lb * 100;
}
class FatResult {
FatResult(this.key, this.name, this.value, this.missing, this.note);
final String key, name, note;
final double? value;
final List<String> missing;
}
/// (key, name, needs, note) — BMI-based formulas and skinfolds left out on purpose (calc.FAT).
const fatFormulas = [
('navy', 'U.S. Navy', ['waist', 'neck', 'hip?', 'height'], 'tape: waist, neck, hips · about ±3–4 % in studies'),
('rfm', 'Relative fat mass', ['waist', 'height'], 'waist and height · checked against DEXA scans'),
('ymca', 'YMCA', ['waist', 'weight'], 'waist and weight · simple, less tested in women'),
('scale', 'Your scale', ['fat_scale'], 'bioimpedance · shifts with water, time of day'),
];
List<FatResult> fatAll(Map<String, double> m, double? h, String sex) => [
for (final (key, name, needs, note) in fatFormulas)
() {
var v = switch (key) {
'navy' => navy(m, h, sex),
'rfm' => rfm(m, h, sex),
'ymca' => ymca(m, h, sex),
_ => m['fat_scale'],
};
if (v != null && (v < 2 || v > 75)) v = null; // implausible: bad inputs
final missing = <String>[];
if (v == null) {
for (final n in needs) {
if (n == 'hip?') {
if (sex == female && m['hip'] == null) missing.add('hip');
} else if (n == 'height') {
if (h == null) missing.add('height');
} else if (m[n] == null) {
missing.add(n);
}
}
}
return FatResult(key, name, v, missing, note);
}()
];
/// Healthy body-fat ranges (Gallagher et al. 2000): (age from, to, healthy from, high from, very high from).
const fatRanges = {
female: [(20, 39, 21.0, 33.0, 39.0), (40, 59, 23.0, 34.0, 40.0), (60, 79, 24.0, 36.0, 42.0)],
'male': [(20, 39, 8.0, 20.0, 25.0), (40, 59, 11.0, 22.0, 28.0), (60, 79, 13.0, 25.0, 30.0)],
};
const fatNames = ['low', 'healthy', 'high', 'very high'];
(int, int, double, double, double)? fatBand(String sex, int? age) {
if (age == null || age < 20) return null;
final rows = fatRanges[sex == female ? female : 'male']!;
return rows.firstWhere((r) => r.$1 <= age && age <= r.$2, orElse: () => rows.last);
}
String? fatClass(double? v, String sex, int? age) {
final b = fatBand(sex, age);
if (v == null || b == null) return null;
return fatNames[[b.$3, b.$4, b.$5].where((x) => v >= x).length];
}
/// Desirable BMI by age (NRC 1989): (age from, to, lo, hi).
const bmiAge = [(19, 24, 19, 24), (25, 34, 20, 25), (35, 44, 21, 26), (45, 54, 22, 27), (55, 64, 23, 28), (65, 200, 24, 29)];
(int, int, int, int)? bmiAgeBand(int? age) =>
age == null || age < 19 ? null : bmiAge.firstWhere((r) => r.$1 <= age && age <= r.$2);
double? bmrMifflin(double? w, double? h, String sex, int? age) =>
w == null || h == null || age == null ? null : 10 * w + 6.25 * h - 5 * age + (sex == female ? -161 : 5);
double? bmrKatch(double? w, double? fat) => w == null || fat == null ? null : 370 + 21.6 * w * (1 - fat / 100);
double? median(List<double> xs) {
if (xs.isEmpty) return null;
final s = [...xs]..sort();
final n = s.length;
return n.isOdd ? s[n ~/ 2] : (s[n ~/ 2 - 1] + s[n ~/ 2]) / 2;
}
// ---- the page's numbers (views.py) ----------------------------------------------------------
class Measure {
Measure(this.row) : day = parseDay(row['day'] as String);
final Map<String, dynamic> row;
final DateTime day;
double? operator [](String k) => (row[k] as num?)?.toDouble();
String get note => (row['note'] as String?) ?? '';
}
class Latest {
Latest(this.v, this.day, this.stale);
final double v;
final DateTime day;
final bool stale;
}
class BodyView {
BodyView(SyncStore store, this.p, {DateTime? now}) : now = now ?? today() {
rows = [for (final r in store.rows('health.measure')) Measure(r)]..sort((a, b) => a.day.compareTo(b.day));
for (final r in rows) {
for (final k in fields.keys) {
if (r[k] != null) cur[k] = Latest(r[k]!, r.day, daysBetween(r.day, this.now) > stale);
}
}
final m = {for (final e in cur.entries) if (!e.value.stale) e.key: e.value.v};
fresh = m;
age = p.ageOn(this.now);
fat = fatAll(m, p.height, p.sex);
final est = [for (final f in fat) if (f.value != null) f.value!];
fatMid = median(est);
fatRange = est.length > 1 ? (est.reduce(min), est.reduce(max)) : null;
}
final Profile p;
final DateTime now;
late final List<Measure> rows;
final cur = <String, Latest>{};
late final Map<String, double> fresh;
late final int? age;
late final List<FatResult> fat;
late final double? fatMid;
late final (double, double)? fatRange;
double? get weight => fresh['weight'];
double? get waist => fresh['waist'];
double? get hip => fresh['hip'];
double? get bmiNow => bmi(weight, p.height);
/// Change of [key] from the value nearest [days] ago (at least 7 days back) to the latest.
(double, DateTime, int)? change(String key, {int days = 30}) {
final pts = [for (final r in rows) if (r[key] != null) (r.day, r[key]!)];
if (pts.length < 2) return null;
final (lastD, lastV) = pts.last;
final old = pts.where((p) => daysBetween(p.$1, lastD) >= 7).toList();
if (old.isEmpty) return null;
old.sort((a, b) => (daysBetween(a.$1, lastD) - days).abs().compareTo((daysBetween(b.$1, lastD) - days).abs()));
final (d, v) = old.first;
return (lastV - v, d, daysBetween(d, lastD));
}
/// Per measured day: weight, waist, BMI and each fat formula (other inputs carried forward ≤ stale days).
Map<String, List<(DateTime, double)>> series() {
final out = <String, List<(DateTime, double)>>{
'weight': [], 'waist': [], 'bmi': [], for (final f in fatFormulas) f.$1: []};
final last = <String, (double, DateTime)>{};
for (final r in rows) {
for (final k in fields.keys) {
if (r[k] != null) last[k] = (r[k]!, r.day);
}
final m = {for (final e in last.entries) if (daysBetween(e.value.$2, r.day) <= stale) e.key: e.value.$1};
for (final k in ['weight', 'waist']) {
if (r[k] != null) out[k]!.add((r.day, r[k]!));
}
if (r['weight'] != null && p.height != null) out['bmi']!.add((r.day, bmi(r['weight'], p.height)!));
if (fatDayFields.any((k) => r[k] != null)) {
for (final f in fatAll(m, p.height, p.sex)) {
if (f.value != null) out[f.key]!.add((r.day, f.value!));
}
}
}
return out;
}
}
/// db.save: replace the day's row; `was` (another day) moves it; nothing in it → deleted.
String? saveMeasure(SyncStore store, DateTime d, Map<String, double?> vals, String note, {DateTime? was}) {
if (d.isAfter(today())) return "That day hasn't happened yet.";
for (final e in vals.entries) {
final f = fields[e.key]!;
if (e.value != null && (e.value! < f.$3 || e.value! > f.$4)) return '${f.$1}: between ${f.$3.round()} and ${f.$4.round()} ${f.$2}.';
}
final u = 'measure:${iso(d)}';
if (was != null && was != d) {
if (store.row('health.measure', u) != null) return 'That day already has measurements — edit it instead.';
store.delete('health.measure', 'measure:${iso(was)}');
}
if (vals.values.every((v) => v == null) && note.trim().isEmpty) {
if (store.row('health.measure', u) != null) store.delete('health.measure', u);
return null;
}
final old = store.row('health.measure', u) ?? {};
final now = DateTime.now();
store.put('health.measure', u, {
...old, // columns this app doesn't show (old skinfolds) stay
'day': iso(d), 'note': note.trim(), 'updated': '${iso(now)} ${now.toIso8601String().substring(11, 19)}',
for (final k in fields.keys) k: vals[k],
});
return null;
}
// ---- vitals ------------------------------------------------------------------------------
const vitalSources = {'mi_fitness': 'Mi Fitness', 'health_connect': 'Health Connect', 'gadgetbridge': 'Gadgetbridge'};
class Vital {
Vital(this.row) : t = DateTime.parse('${(row['t'] as String).replaceFirst(' ', 'T')}:00Z');
final Map<String, dynamic> row;
final DateTime t; // local wall time (stored as UTC so nothing shifts)
String get u => row['_u'] as String;
int? get sys => (row['sys'] as num?)?.toInt();
int? get dia => (row['dia'] as num?)?.toInt();
double? get spo2 => (row['spo2'] as num?)?.toDouble();
String get note => (row['note'] as String?) ?? '';
String? get source => row['source'] as String?;
bool get isBp => sys != null && dia != null;
}
List<Vital> vitals(SyncStore store) =>
[for (final r in store.rows('health.vital')) Vital(r)]..sort((a, b) => b.t.compareTo(a.t)); // newest first
/// (name, colour key) — ESC 2024 office categories; the higher of the two numbers decides.
(String, String)? bpClass(int? sys, int? dia) {
if (sys == null || dia == null) return null;
const classes = [('non-elevated', 0, 0, 'ok'), ('elevated', 120, 70, 'mid'), ('hypertension', 140, 90, 'high'),
('severe hypertension', 180, 110, 'vhigh')];
var pick = classes.first;
for (final c in classes) {
if (sys >= c.$2 || dia >= c.$3) pick = c;
}
return (pick.$1, pick.$4);
}
(String, String)? spo2Class(double? p) => p == null ? null : p >= 95 ? ('normal', 'ok') : p > 90 ? ('low', 'mid') : ('very low', 'vhigh');
/// db.save_vital: one kind per reading (bp: sys + dia, ox: spo2). Returns an error or null.
String? saveVital(SyncStore store, {String? u, required String kind, required DateTime t, int? sys, int? dia, double? spo2,
String note = ''}) {
if (t.isAfter(DateTime.now().toUtc().add(const Duration(hours: 14)))) return "That time hasn't come yet.";
if (kind == 'bp') {
if (sys == null || dia == null) return 'Blood pressure needs both numbers (e.g. 120 / 80).';
if (sys < 60 || sys > 260) return 'Systolic: between 60 and 260 mmHg.';
if (dia < 30 || dia > 160) return 'Diastolic: between 30 and 160 mmHg.';
if (sys <= dia) return 'The upper number (systolic) is the bigger one.';
} else {
if (spo2 == null) return 'Enter the oxygen %.';
if (spo2 < 50 || spo2 > 100) return 'Blood oxygen: between 50 and 100 %.';
}
final old = u == null ? null : store.row('health.vital', u);
final ts = '${iso(t)} ${t.toIso8601String().substring(11, 16)}';
store.put('health.vital', u ?? SyncStore.randomId(), {
...?old,
't': ts, 'sys': kind == 'bp' ? sys : null, 'dia': kind == 'bp' ? dia : null,
'spo2': kind == 'ox' ? (spo2! * 10).round() / 10 : null, 'pulse': null, 'note': note.trim(),
'source': old?['source'],
});
return null;
}
/// Readings of one kind as chart points (oldest first).
List<(DateTime, double)> vitalSeries(List<Vital> vs, double? Function(Vital) pick) =>
[for (final v in vs.reversed) if (pick(v) != null) (v.t, pick(v)!)];