diff --git a/app/apps/glanceboard/glanceboard-settings.ts b/app/apps/glanceboard/glanceboard-settings.ts index 6036219c..7cecf5e9 100644 --- a/app/apps/glanceboard/glanceboard-settings.ts +++ b/app/apps/glanceboard/glanceboard-settings.ts @@ -5,7 +5,7 @@ import { glanceWidgetSpans } from "./widgets"; export type GlanceSlotChoice = GlanceWidgetId | "none"; -const SLOT_CHOICES: readonly GlanceSlotChoice[] = ["none", "system-card", "calendar", "terminal", "nightscout", "compass", "music"]; +const SLOT_CHOICES: readonly GlanceSlotChoice[] = ["none", "system-card", "calendar", "terminal", "nightscout", "compass", "music", "health"]; const SLOT_CHOICE_LABELS: Record = { none: "Empty", @@ -15,6 +15,7 @@ const SLOT_CHOICE_LABELS: Record = { nightscout: "Nightscout", compass: "Compass", music: "Music", + health: "Health", }; export function glanceSlotChoiceLabel(choice: GlanceSlotChoice): string { diff --git a/app/apps/glanceboard/widget.ts b/app/apps/glanceboard/widget.ts index 0f5c2d78..d6e965b7 100644 --- a/app/apps/glanceboard/widget.ts +++ b/app/apps/glanceboard/widget.ts @@ -27,7 +27,7 @@ export interface GlanceWidget { paint(image: GrayImage): void; } -export type GlanceWidgetId = "system-card" | "nightscout" | "compass" | "music" | "calendar" | "terminal"; +export type GlanceWidgetId = "system-card" | "nightscout" | "compass" | "music" | "calendar" | "terminal" | "health"; export type GlanceWidgetDefinition = { id: GlanceWidgetId; diff --git a/app/apps/glanceboard/widgets/health-widget.ts b/app/apps/glanceboard/widgets/health-widget.ts new file mode 100644 index 00000000..5a6b3ac3 --- /dev/null +++ b/app/apps/glanceboard/widgets/health-widget.ts @@ -0,0 +1,56 @@ +import { type GrayImage } from "../../../graphics/image"; +import { getDefaultMediumFont, getDefaultSmallFont } from "../../../graphics/ui-fonts"; +import { dailySummary, nextBucketStart } from "../../../health/health-derive"; +import { drawHealthCard, type HealthCardData } from "../../../health/health-card"; +import { syncLiveRecords } from "../../../health/health-live"; +import { isFixtureData } from "../../../health/health-seed"; +import { healthStore } from "../../../health/health-store-files"; +import { startOfLocalDay } from "../../../health/health-types"; +import { type GlanceWidget } from "../widget"; + +/** Saved daily metrics, refreshed while visible without extra BLE polling. */ +export class HealthWidget implements GlanceWidget { + private data: HealthCardData = { kind: "empty" }; + private timer: ReturnType | null = null; + + start(requestRender: () => void): void { + this.stop(); + const refresh = (): void => { + this.refresh(); + requestRender(); + }; + refresh(); + this.timer = setInterval(refresh, 60_000); + } + + stop(): void { + if (this.timer !== null) clearInterval(this.timer); + this.timer = null; + } + + private refresh(): void { + try { + syncLiveRecords(); + if (isFixtureData()) { + this.data = { kind: "fixture" }; + return; + } + const today = startOfLocalDay(Date.now()); + const store = healthStore(); + const samples = store.samplesInRange(today, nextBucketStart(today, "day")); + const summary = dailySummary(samples, store.sleepSessions(), today); + this.data = samples.length || summary.sleep + ? { kind: "live", summary, + hasSteps: samples.some((sample) => sample.metric === "steps"), + hasCalories: samples.some((sample) => sample.metric === "calories") } + : { kind: "empty" }; + } catch (error) { + console.warn("health widget refresh failed", error); + this.data = { kind: "error" }; + } + } + + paint(image: GrayImage): void { + drawHealthCard(image, this.data, getDefaultSmallFont(), getDefaultMediumFont()); + } +} diff --git a/app/apps/glanceboard/widgets/index.ts b/app/apps/glanceboard/widgets/index.ts index 2efd48ab..0ebf4c52 100644 --- a/app/apps/glanceboard/widgets/index.ts +++ b/app/apps/glanceboard/widgets/index.ts @@ -5,6 +5,7 @@ import { MusicWidget } from "./music-widget"; import { NightscoutWidget } from "./nightscout-widget"; import { SystemCardWidget } from "./system-card"; import { TerminalWidget } from "./terminal-widget"; +import { HealthWidget } from "./health-widget"; /** Every widget a board slot can hold. */ export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [ @@ -14,6 +15,7 @@ export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [ { id: "nightscout", label: "Nightscout", create: () => new NightscoutWidget() }, { id: "compass", label: "Compass", create: () => new CompassWidget() }, { id: "music", label: "Music", create: () => new MusicWidget() }, + { id: "health", label: "Health", create: () => new HealthWidget() }, ]; export function findGlanceWidget(id: GlanceWidgetId | string): GlanceWidgetDefinition | null { diff --git a/app/health/health-card.ts b/app/health/health-card.ts new file mode 100644 index 00000000..bd0a9435 --- /dev/null +++ b/app/health/health-card.ts @@ -0,0 +1,55 @@ +import { type GrayImage, type UiFont } from "../graphics/image"; +import { truncateText } from "../graphics/textwrap"; +import { formatDuration, type DailySummary, type MetricSummary } from "./health-derive"; + +export type HealthCardData = + | { kind: "live"; summary: DailySummary; hasSteps: boolean; hasCalories: boolean } + | { kind: "fixture" | "empty" | "error" }; + +const PAD = 8; + +/** Three columns keep all six metrics legible in a 288 x 144 board slot. */ +export function drawHealthCard(image: GrayImage, data: HealthCardData, small: UiFont, medium: UiFont): void { + image.drawText(small, PAD, PAD, "Health", 180); + const today = "Today"; + image.drawText(small, image.width - PAD - small.measureText(today), PAD, today, 130); + + const top = PAD + small.lineHeight + 6; + if (data.kind !== "live") { + const title = data.kind === "fixture" ? "Sample data" + : data.kind === "error" ? "Health unavailable" : "No health data today"; + const subtitle = data.kind === "fixture" ? "Open Health for details" + : data.kind === "error" ? "Open Health to retry" : "Open Health to sync"; + const font = medium.measureText(title) <= image.width - PAD * 2 ? medium : small; + const y = Math.round(top + (image.height - PAD - top - font.lineHeight - small.lineHeight - 6) / 2); + const text = truncateText(font, title, image.width - PAD * 2); + image.drawText(font, Math.round((image.width - font.measureText(text)) / 2), y, text, 240); + const hint = truncateText(small, subtitle, image.width - PAD * 2); + image.drawText(small, Math.round((image.width - small.measureText(hint)) / 2), y + font.lineHeight + 6, hint, 150); + return; + } + + const average = (metric: MetricSummary, units: string): string => + metric.hasData ? `${Math.round(metric.avg)}${units}` : "--"; + const { summary } = data; + const cells: [string, string][] = [ + ["HR avg", average(summary.heartRate, " bpm")], + ["HRV avg", average(summary.hrv, " ms")], + ["SpO2 avg", average(summary.spo2, "%")], + ["Steps", data.hasSteps ? String(summary.steps) : "--"], + ["Cal (kcal)", data.hasCalories ? String(summary.calories) : "--"], + ["Sleep", summary.sleep ? formatDuration(summary.sleep.totalSec) : "--"], + ]; + const columnWidth = (image.width - PAD * 2) / 3; + const rowHeight = (image.height - PAD - top) / 2; + cells.forEach(([label, value], index) => { + const left = PAD + Math.floor((index % 3) * columnWidth); + const y = top + Math.floor(Math.floor(index / 3) * rowHeight); + const width = Math.floor(columnWidth) - 6; + const font = medium.measureText(value) <= width + && small.lineHeight + 2 + medium.lineHeight <= rowHeight - 2 ? medium : small; + const fittedLabel = label === "Cal (kcal)" && small.measureText(label) > width ? "kcal" : label; + image.drawText(small, left, y, truncateText(small, fittedLabel, width), 140); + image.drawText(font, left, y + small.lineHeight + 2, truncateText(font, value, width), 235); + }); +} diff --git a/app/health/health-derive.ts b/app/health/health-derive.ts index 7c4a1bcd..ad6feaf6 100644 --- a/app/health/health-derive.ts +++ b/app/health/health-derive.ts @@ -95,7 +95,7 @@ export function rollupSeries( return points; } -function nextBucketStart(startMs: number, granularity: Granularity): number { +export function nextBucketStart(startMs: number, granularity: Granularity): number { const date = new Date(startMs); if (granularity === "hour") date.setHours(date.getHours() + 1, 0, 0, 0); else date.setDate(date.getDate() + 1); diff --git a/tests/health-card.test.cjs b/tests/health-card.test.cjs new file mode 100644 index 00000000..b1cf0992 --- /dev/null +++ b/tests/health-card.test.cjs @@ -0,0 +1,30 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { drawHealthCard } = require("../.test-build/app/health/health-card.js"); +const { dailySummary } = require("../.test-build/app/health/health-derive.js"); + +function render(data) { + const draws = []; + const font = { lineHeight: 21, measureText: (text) => text.length * 10 }; + const image = { width: 288, height: 144, drawText(font, x, y, text) { + assert.ok(x >= 0 && x + font.measureText(text) <= 288, `horizontal overflow: ${text}`); + assert.ok(y >= 0 && y + font.lineHeight <= 144, `vertical overflow: ${text}`); + draws.push(text); + } }; + drawHealthCard(image, data, font, font); + return draws; +} + +test("health card distinguishes an observed zero from missing metrics", () => { + const summary = dailySummary([], [], 0); + const text = render({ kind: "live", summary, hasSteps: true, hasCalories: false }); + assert.equal(text.filter((value) => value === "0").length, 1); + assert.equal(text.filter((value) => value === "--").length, 5); +}); + +test("health card prominently labels fixtures without displaying sample measurements", () => { + const text = render({ kind: "fixture" }); + assert.ok(text.includes("Sample data")); + assert.ok(!text.includes("HR avg")); + for (const kind of ["empty", "error"]) render({ kind }); +}); diff --git a/tests/tsconfig.json b/tests/tsconfig.json index f221361f..ae11cc28 100644 --- a/tests/tsconfig.json +++ b/tests/tsconfig.json @@ -39,6 +39,7 @@ "../app/health/sleep-stages.ts", "../app/health/health-chart.ts", "../app/health/health-glance.ts", + "../app/health/health-card.ts", "../app/health/health-phone-chart.ts" ] } diff --git a/tools/health-preview.cjs b/tools/health-preview.cjs index 40157c5f..37c9aad2 100644 --- a/tools/health-preview.cjs +++ b/tools/health-preview.cjs @@ -103,6 +103,7 @@ const { formatDuration, } = require(path.join(BUILD, "health/health-derive.js")); const { drawGlancePage, GLANCE_PAGES } = require(path.join(BUILD, "health/health-glance.js")); +const { drawHealthCard } = require(path.join(BUILD, "health/health-card.js")); const { convertRecords } = require(path.join(BUILD, "health/health-ingest.js")); const { HealthStore } = require(path.join(BUILD, "health/health-store.js")); const { renderPhoneChart } = require(path.join(BUILD, "health/health-phone-chart.js")); @@ -369,6 +370,18 @@ for (const layout of PHONE_LAYOUTS) { } // --- report ---------------------------------------------------------------- +for (const [name, data] of [ + ["live", { kind: "live", summary: dailySummary(fixtures.samples, fixtures.sleep, TODAY), hasSteps: true, hasCalories: true }], + ["partial", { kind: "live", summary: dailySummary([], [], TODAY), hasSteps: true, hasCalories: false }], + ["sample", { kind: "fixture" }], + ["empty", { kind: "empty" }], + ["error", { kind: "error" }], +]) { + const card = new GrayImage(288, 144, 0); + drawHealthCard(card, data, small, getFont(big ? "terminus24" : "terminus16")); + writePng(`glanceboard-health-${name}`, card); +} + console.log(`font: small lineHeight ${small.lineHeight}, large lineHeight ${large.lineHeight}`); console.log(`wrote ${written.length} PNGs to ${OUT}\n`); for (const entry of written) {