mirror of
https://git.undefined-dev.fr/Blendman974/faceclaw.git
synced 2026-11-19 21:03:09 +00:00
Add health metrics widget to Glanceboard
This commit is contained in:
1 parent
27a5fe47ef
commit
3a61ad3842
9 files changed
+161
-3
No files matched your search
@@ -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<GlanceSlotChoice, string> = {
|
||||
none: "Empty",
|
||||
@@ -15,6 +15,7 @@ const SLOT_CHOICE_LABELS: Record<GlanceSlotChoice, string> = {
|
||||
nightscout: "Nightscout",
|
||||
compass: "Compass",
|
||||
music: "Music",
|
||||
health: "Health",
|
||||
};
|
||||
|
||||
export function glanceSlotChoiceLabel(choice: GlanceSlotChoice): string {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<typeof setInterval> | 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());
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user