Merge branch 'nightscout-missed-bolus-detector'

This commit is contained in:
James Babcock committed 2026-10-16 18:25:20 -07:00
commit fedc7fed67
14 files changed
+1012 -68

No files matched your search

+8 -4
View File
@@ -1,14 +1,18 @@
import { inProcessTrayWidget, type AppDefinition } from "../app-definition";
import { createNightscoutAppWindow, startNightscoutTrayIcon, NIGHTSCOUT_SURFACE_ID, NIGHTSCOUT_WINDOW_ID } from "./nightscout-app";
import { startMissedBolusMonitor } from "./missed-bolus-monitor";
const nightscoutApp: AppDefinition = {
appId: "nightscout",
title: "Nightscout",
icon: "nightscout",
// Selected in the switcher, the tray readout shows the app's window.
boot: (ctx) => startNightscoutTrayIcon(
inProcessTrayWidget(ctx, NIGHTSCOUT_WINDOW_ID, NIGHTSCOUT_SURFACE_ID, createNightscoutAppWindow),
),
boot: (ctx) => {
// Selected in the switcher, the tray readout shows the app's window.
startNightscoutTrayIcon(
inProcessTrayWidget(ctx, NIGHTSCOUT_WINDOW_ID, NIGHTSCOUT_SURFACE_ID, createNightscoutAppWindow),
);
startMissedBolusMonitor(ctx);
},
launch: (ctx) => ctx.launchInProcessApp(NIGHTSCOUT_WINDOW_ID, NIGHTSCOUT_SURFACE_ID, createNightscoutAppWindow),
};
@@ -0,0 +1,336 @@
/**
* Missed-bolus detector: given a recent window of CGM readings and
* treatments, decide whether glucose is rising the way an unannounced meal
* does, with no meal bolus, manual bolus or carb entry to account for it.
*
* Deliberately self-contained (no imports; plain data in, plain data out) so
* it can move to the server side of Nightscout unchanged, and so it can be
* iterated on against recorded history with
* scripts/nightscout-missed-bolus-replay.cjs. The Faceclaw side (when to run
* it, cooldown, the glasses notification) is in missed-bolus-monitor.ts.
*
* Glucose is mg/dL throughout: Nightscout stores sgv in mg/dL whatever the
* site's display units.
*/
export type GlucoseReading = { timeMs: number; mgdl: number };
/**
* - meal: a meal/snack/wizard bolus, or any bolus entered together with carbs.
* - manual: a bolus explicitly marked user-initiated (e.g. Loop's `automatic: false`).
* - automatic: a bolus the loop issued (SMB, automatic bolus).
* - ambiguous: not marked either way. OpenAPS on a Medtronic pump uploads its
* SMBs as plain "Correction Bolus" records, indistinguishable from a manual
* correction except by size; `ambiguousBolusMinUnits` decides.
*/
export type BolusKind = "meal" | "manual" | "automatic" | "ambiguous";
export type BolusEvent = { timeMs: number; units: number; kind: BolusKind };
export type CarbEntry = { timeMs: number; grams: number };
export type MissedBolusInput = {
/** The time to classify as of. Readings and treatments after it are ignored. */
nowMs: number;
glucose: readonly GlucoseReading[];
boluses: readonly BolusEvent[];
carbs: readonly CarbEntry[];
};
export type MissedBolusOptions = {
/** The latest reading must be at most this old, or there is nothing current to judge. */
maxReadingAgeMs: number;
/** How far back from the latest reading to look for where the rise started. */
lookbackMs: number;
/** A gap between readings longer than this ends the window (the CGM dropped out). */
maxGapMs: number;
/** Recent span the rate of rise is fitted over (least squares). */
slopeWindowMs: number;
/** Fewest readings the rate fit needs. */
minSlopeReadings: number;
/** Rise from the window's lowest reading to the latest. */
minRiseMgdl: number;
/** The latest reading must be at least this high. */
minGlucoseMgdl: number;
/** Rises from below this are taken as recovering from a low (rescue carbs go unbolused). */
hypoNadirMgdl: number;
/** The rise must have lasted at least this long, to rule out sensor noise. */
minRiseDurationMs: number;
/** Rate of rise over the slope window, mg/dL per minute. */
minRateMgdlPerMin: number;
/** A bolus or carb entry this long before the rise began still accounts for it (pre-bolusing). */
preBolusWindowMs: number;
/** Smallest meal or manual bolus that accounts for a rise. */
minManualBolusUnits: number;
/** Smallest unmarked bolus taken as manual rather than an SMB. */
ambiguousBolusMinUnits: number;
/** Whether a carb entry with no bolus accounts for a rise (the user evidently knows they ate). */
carbsCountAsAnnouncement: boolean;
};
export const DEFAULT_MISSED_BOLUS_OPTIONS: Readonly<MissedBolusOptions> = {
maxReadingAgeMs: 12 * 60_000,
lookbackMs: 90 * 60_000,
maxGapMs: 16 * 60_000,
slopeWindowMs: 20 * 60_000,
minSlopeReadings: 3,
minRiseMgdl: 40,
minGlucoseMgdl: 140,
hypoNadirMgdl: 70,
minRiseDurationMs: 20 * 60_000,
minRateMgdlPerMin: 1.5,
preBolusWindowMs: 60 * 60_000,
minManualBolusUnits: 0.5,
ambiguousBolusMinUnits: 1.5,
carbsCountAsAnnouncement: true,
};
export type GlucoseRise = {
/** When the rise started: the lowest reading in the window (the latest, if tied). */
onsetMs: number;
nadirMgdl: number;
latestMs: number;
latestMgdl: number;
riseMgdl: number;
/** Least-squares rate over the slope window, mg/dL per minute. */
rateMgdlPerMin: number;
};
export type MissedBolusClassification = "missed-bolus" | "no-alert" | "insufficient-data";
export type MissedBolusResult = {
classification: MissedBolusClassification;
/** One-line explanation, for logs and the replay tool. */
reason: string;
/** The rise that was judged, when there was enough data to measure one. */
rise: GlucoseRise | null;
};
export function detectMissedBolus(
input: MissedBolusInput,
overrides: Partial<MissedBolusOptions> = {},
): MissedBolusResult {
const options: MissedBolusOptions = { ...DEFAULT_MISSED_BOLUS_OPTIONS, ...overrides };
const { nowMs } = input;
const readings = usableReadings(input.glucose, nowMs);
const latest = readings[readings.length - 1];
if (!latest) return insufficient("no glucose readings");
if (nowMs - latest.timeMs > options.maxReadingAgeMs) {
return insufficient(`latest reading is ${formatMinutes(nowMs - latest.timeMs)} old`);
}
// The contiguous run of readings ending at the latest, within the lookback.
const windowStartMs = latest.timeMs - options.lookbackMs;
let first = readings.length - 1;
while (first > 0) {
const previous = readings[first - 1]!;
if (previous.timeMs < windowStartMs || readings[first]!.timeMs - previous.timeMs > options.maxGapMs) break;
first--;
}
const window = readings.slice(first);
let nadir = window[0]!;
for (const reading of window) {
if (reading.mgdl <= nadir.mgdl) nadir = reading;
}
const slopeStartMs = Math.max(nadir.timeMs, latest.timeMs - options.slopeWindowMs);
const slopeReadings = window.filter((reading) => reading.timeMs >= slopeStartMs);
const rise: GlucoseRise = {
onsetMs: nadir.timeMs,
nadirMgdl: nadir.mgdl,
latestMs: latest.timeMs,
latestMgdl: latest.mgdl,
riseMgdl: latest.mgdl - nadir.mgdl,
rateMgdlPerMin: slopeReadings.length >= 2 ? slopePerMinute(slopeReadings) : 0,
};
const noAlert = (reason: string): MissedBolusResult => ({ classification: "no-alert", reason, rise });
if (rise.riseMgdl < options.minRiseMgdl) {
return noAlert(`rise of ${rise.riseMgdl} mg/dL is under ${options.minRiseMgdl}`);
}
if (latest.mgdl < options.minGlucoseMgdl) {
return noAlert(`glucose ${latest.mgdl} mg/dL is under ${options.minGlucoseMgdl}`);
}
if (nadir.mgdl < options.hypoNadirMgdl) {
return noAlert(`rising from a low of ${nadir.mgdl} mg/dL`);
}
if (latest.timeMs - nadir.timeMs < options.minRiseDurationMs) {
return noAlert(`rise has lasted only ${formatMinutes(latest.timeMs - nadir.timeMs)}`);
}
if (slopeReadings.length < options.minSlopeReadings) {
return { classification: "insufficient-data", reason: `only ${slopeReadings.length} readings to fit a rate`, rise };
}
if (rise.rateMgdlPerMin < options.minRateMgdlPerMin) {
return noAlert(`rising ${formatRate(rise.rateMgdlPerMin)}, under ${formatRate(options.minRateMgdlPerMin)}`);
}
const coverStartMs = nadir.timeMs - options.preBolusWindowMs;
const inCoverWindow = (timeMs: number) => timeMs >= coverStartMs && timeMs <= nowMs;
const bolus = latestMatching(input.boluses, (event) => inCoverWindow(event.timeMs) && accountsForRise(event, options));
if (bolus) {
return noAlert(`${formatUnits(bolus.units)} U ${bolus.kind} bolus ${formatMinutes(nowMs - bolus.timeMs)} ago`);
}
if (options.carbsCountAsAnnouncement) {
const carbs = latestMatching(input.carbs, (entry) => inCoverWindow(entry.timeMs) && entry.grams > 0);
if (carbs) return noAlert(`${carbs.grams} g carbs entered ${formatMinutes(nowMs - carbs.timeMs)} ago`);
}
return {
classification: "missed-bolus",
reason: `up ${rise.riseMgdl} mg/dL in ${formatMinutes(latest.timeMs - nadir.timeMs)}, rising ${formatRate(rise.rateMgdlPerMin)}, no bolus`,
rise,
};
}
function insufficient(reason: string): MissedBolusResult {
return { classification: "insufficient-data", reason, rise: null };
}
function accountsForRise(bolus: BolusEvent, options: MissedBolusOptions): boolean {
switch (bolus.kind) {
case "meal":
case "manual":
return bolus.units >= options.minManualBolusUnits;
case "ambiguous":
return bolus.units >= Math.max(options.minManualBolusUnits, options.ambiguousBolusMinUnits);
case "automatic":
return false;
}
}
/**
* Finite, in-range readings at or before now, oldest first, one per
* timestamp. Dexcom reports 39 for "LOW" and smaller values as error codes.
*/
function usableReadings(glucose: readonly GlucoseReading[], nowMs: number): GlucoseReading[] {
const sorted = glucose
.filter((reading) => Number.isFinite(reading.timeMs) && Number.isFinite(reading.mgdl)
&& reading.mgdl >= 39 && reading.mgdl <= 600 && reading.timeMs <= nowMs)
.slice()
.sort((a, b) => a.timeMs - b.timeMs);
return sorted.filter((reading, index) => index === 0 || reading.timeMs !== sorted[index - 1]!.timeMs);
}
/** Least-squares slope through the readings, in mg/dL per minute. */
function slopePerMinute(readings: readonly GlucoseReading[]): number {
const t0 = readings[0]!.timeMs;
const n = readings.length;
let sumX = 0, sumY = 0, sumXY = 0, sumXX = 0;
for (const reading of readings) {
const x = (reading.timeMs - t0) / 60_000;
sumX += x;
sumY += reading.mgdl;
sumXY += x * reading.mgdl;
sumXX += x * x;
}
const denominator = n * sumXX - sumX * sumX;
return denominator > 0 ? (n * sumXY - sumX * sumY) / denominator : 0;
}
function latestMatching<T extends { timeMs: number }>(events: readonly T[], predicate: (event: T) => boolean): T | null {
let found: T | null = null;
for (const event of events) {
if (predicate(event) && (!found || event.timeMs > found.timeMs)) found = event;
}
return found;
}
function formatMinutes(ms: number): string {
return `${Math.round(ms / 60_000)} min`;
}
function formatRate(mgdlPerMin: number): string {
return `${mgdlPerMin.toFixed(1)} mg/dL/min`;
}
function formatUnits(units: number): string {
return `${Math.round(units * 100) / 100}`;
}
// ---------------------------------------------------------------------------
// Nightscout record normalization, shared by the Faceclaw bridge and a
// server-side port.
/** The fields of a Nightscout treatment record the detector reads. */
export type NightscoutTreatmentRecord = {
eventType?: unknown;
created_at?: unknown;
timestamp?: unknown;
insulin?: unknown;
carbs?: unknown;
automatic?: unknown;
isSMB?: unknown;
type?: unknown;
wizard?: unknown;
};
/** The fields of a Nightscout entry record the detector reads. */
export type NightscoutEntryRecord = { date?: unknown; sgv?: unknown };
const MEAL_BOLUS_EVENT_TYPES = new Set(["Meal Bolus", "Snack Bolus", "Bolus Wizard", "Combo Bolus"]);
/**
* How a treatment's insulin was given. Uploaders mark automatic boluses
* differently: Loop sets `automatic`, AndroidAPS `isSMB`, Trio/OpenAPS
* `type: "SMB"` or eventType "SMB". Meal boluses carry carbs or a wizard
* record, or a meal-type eventType.
*/
export function bolusKindFromTreatment(treatment: NightscoutTreatmentRecord): BolusKind {
const eventType = typeof treatment.eventType === "string" ? treatment.eventType : "";
if (treatment.automatic === true || treatment.isSMB === true || treatment.type === "SMB" || eventType === "SMB") {
return "automatic";
}
if (MEAL_BOLUS_EVENT_TYPES.has(eventType) || positiveNumber(treatment.carbs) !== null
|| (typeof treatment.wizard === "object" && treatment.wizard !== null)) {
return "meal";
}
if (treatment.automatic === false || treatment.isSMB === false) return "manual";
return "ambiguous";
}
/** Boluses and carb entries from raw Nightscout treatment records, oldest first. */
export function normalizeNightscoutTreatments(treatments: readonly NightscoutTreatmentRecord[]): {
boluses: BolusEvent[];
carbs: CarbEntry[];
} {
const boluses: BolusEvent[] = [];
const carbs: CarbEntry[] = [];
for (const treatment of treatments) {
const timeMs = treatmentTimeMs(treatment);
if (timeMs === null) continue;
const units = positiveNumber(treatment.insulin);
if (units !== null) boluses.push({ timeMs, units, kind: bolusKindFromTreatment(treatment) });
const grams = positiveNumber(treatment.carbs);
if (grams !== null) carbs.push({ timeMs, grams });
}
boluses.sort((a, b) => a.timeMs - b.timeMs);
carbs.sort((a, b) => a.timeMs - b.timeMs);
return { boluses, carbs };
}
/** Glucose readings from raw Nightscout sgv entries, oldest first. */
export function normalizeNightscoutEntries(entries: readonly NightscoutEntryRecord[]): GlucoseReading[] {
const readings: GlucoseReading[] = [];
for (const entry of entries) {
const timeMs = Number(entry.date);
const mgdl = Number(entry.sgv);
if (Number.isFinite(timeMs) && timeMs > 0 && Number.isFinite(mgdl)) readings.push({ timeMs, mgdl });
}
return readings.sort((a, b) => a.timeMs - b.timeMs);
}
function treatmentTimeMs(treatment: NightscoutTreatmentRecord): number | null {
for (const value of [treatment.created_at, treatment.timestamp]) {
if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
if (typeof value === "string" && value.trim()) {
const numeric = Number(value);
const parsed = Number.isFinite(numeric) ? numeric : Date.parse(value);
if (Number.isFinite(parsed) && parsed > 0) return parsed;
}
}
return null;
}
function positiveNumber(value: unknown): number | null {
if (typeof value !== "number" && typeof value !== "string") return null;
if (typeof value === "string" && !value.trim()) return null;
const numeric = Number(value);
return Number.isFinite(numeric) && numeric > 0 ? numeric : null;
}
@@ -0,0 +1,73 @@
import { type AppContext } from "../app-definition";
import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge";
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import { nightscoutMissedBolusAlertsSetting, nightscoutMissedBolusCooldownSetting } from "../../ui/dashboard-settings";
import { shell } from "../../ui/shell/shell";
import { detectMissedBolus, type MissedBolusInput } from "./missed-bolus-detector";
import { MissedBolusNotificationLayer } from "./missed-bolus-notification";
/** When the last alert was shown, persisted so a restart doesn't reset the cooldown. */
const LAST_ALERT_STORAGE_KEY = "integrations.nightscout.missedBolusLastAlertMs";
let started = false;
let lastInputKey = "";
let lastSummary = "";
/**
* Runs the missed-bolus detector each time a Nightscout sync brings new
* readings or treatments, and shows a glasses notification when it fires
* outside the cooldown. Shell-lifetime, started from the app's boot hook.
*/
export function startMissedBolusMonitor(ctx: AppContext): void {
if (started) return;
started = true;
nightscoutBridge.onStateChange((state) => checkForMissedBolus(state, ctx));
}
function checkForMissedBolus(state: NightscoutState, ctx: AppContext): void {
if (!nightscoutMissedBolusAlertsSetting.get() || !state.available) return;
const key = inputKey(state);
if (key === lastInputKey) return;
lastInputKey = key;
const nowMs = Date.now();
const result = detectMissedBolus(detectorInput(state, nowMs));
const summary = `${result.classification}: ${result.reason}`;
if (summary !== lastSummary) {
lastSummary = summary;
console.log(`missed-bolus detector: ${summary}`);
}
if (result.classification !== "missed-bolus" || !result.rise) return;
const lastAlertMs = Number(getStringSetting(LAST_ALERT_STORAGE_KEY, "0")) || 0;
const cooldownMs = Number(nightscoutMissedBolusCooldownSetting.get()) * 60_000;
// A last-alert time in the future means the clock moved back; don't let it block alerts.
if (lastAlertMs <= nowMs && nowMs - lastAlertMs < cooldownMs) return;
setStringSetting(LAST_ALERT_STORAGE_KEY, String(nowMs));
ctx.appendLog(`missed-bolus alert: ${result.reason}`);
const rise = result.rise;
shell.postAppNotification({
key: `nightscout-missed-bolus:${nowMs}`,
createLayer: (close) => new MissedBolusNotificationLayer(rise, nowMs, close, () => {
void ctx.launchApp("nightscout");
}),
});
}
/** Changes whenever a sync brings a new reading or a treatment the detector reads. */
function inputKey(state: NightscoutState): string {
return [
state.latest?.timestampMs ?? 0,
state.boluses.map((bolus) => bolus.timestampMs).join(","),
state.carbs.map((entry) => entry.timestampMs).join(","),
].join("|");
}
function detectorInput(state: NightscoutState, nowMs: number): MissedBolusInput {
return {
nowMs,
glucose: state.history.map((point) => ({ timeMs: point.timestampMs, mgdl: point.sgv })),
boluses: state.boluses.map((bolus) => ({ timeMs: bolus.timestampMs, units: bolus.insulin, kind: bolus.kind })),
carbs: state.carbs.map((entry) => ({ timeMs: entry.timestampMs, grams: entry.carbs })),
};
}
@@ -0,0 +1,111 @@
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GrayImage } from "../../graphics/image";
import { renderIcon } from "../../graphics/icons";
import { wrapText } from "../../graphics/textwrap";
import { formatRelativeTime } from "../../util/date-util";
import { nightscoutBridge } from "../../native/nightscout-bridge";
import { type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext } from "../../ui/layers";
import { lineStep } from "../../ui/metrics";
import {
NOTIFICATION_CONTENT_X,
createNotificationActionMenu,
drawNotificationHeader,
notificationActionMenuBox,
notificationContentWidth,
} from "../../ui/notifications";
import { type GlucoseRise } from "./missed-bolus-detector";
import {
drawDirectionIndicator,
drawNightscoutGraph,
drawNightscoutValueStrikeThrough,
formatDelta,
isNightscoutPointStale,
} from "./nightscout";
const ICON_SIZE = 24;
const GRAPH_GAP = 6;
const GRAPH_BOTTOM_MARGIN = 12;
const MIN_GRAPH_HEIGHT = 32;
type ActionItem = { label: string; run: () => void };
/**
* The missed-bolus alert, laid out like an Android notification's detail view
* (header, text, right-hand action column), with the live glucose readout and
* 2-hour graph below the text.
*/
export class MissedBolusNotificationLayer implements Layer {
private readonly menu = createNotificationActionMenu<ActionItem>();
constructor(
private readonly rise: GlucoseRise,
private readonly postedAtMs: number,
private readonly close: () => void,
openNightscout: () => void,
) {
this.menu.setItems([
{ label: "Dismiss", run: close },
{ label: "Open Nightscout", run: () => {
close();
openNightscout();
} },
]);
}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const step = lineStep(font);
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const contentX = NOTIFICATION_CONTENT_X;
const contentWidth = notificationContentWidth(width);
const nowMs = Date.now();
let y = drawNotificationHeader(image, font, renderIcon("nightscout", ICON_SIZE), `Nightscout ${formatRelativeTime(this.postedAtMs)}`);
image.drawText(font, contentX, y, "Missed bolus?", 230);
y += step;
const minutes = Math.round((this.rise.latestMs - this.rise.onsetMs) / 60_000);
const body = `Glucose rose ${this.rise.riseMgdl} mg/dL in ${minutes} min with no bolus or carbs entered.`;
for (const line of wrapText(font, body, contentWidth)) {
image.drawText(font, contentX, y, line, 190);
y += step;
}
// Live readout and graph: the modal repaints with each shell render, so
// these follow new readings (and a bolus, once entered) while it is up.
const nightscout = nightscoutBridge.snapshot();
const latest = nightscout.latest;
if (latest) {
const value = `${latest.sgv}`;
image.drawText(font, contentX, y, value, 230);
if (isNightscoutPointStale(latest, nowMs)) {
drawNightscoutValueStrikeThrough(image, contentX, y + (font.lineHeight >> 1), font.measureText(value));
}
let x = contentX + font.measureText(`${value} `);
x += drawDirectionIndicator(image, font, x, y, nightscout.direction, 200);
x += font.measureText(" ");
const iob = nightscout.iob === null ? "" : ` IOB ${nightscout.iob.toFixed(2)}`;
image.drawText(font, x, y, `${formatDelta(nightscout.delta)}${iob}`, 180);
y += step;
}
const graphTop = y + GRAPH_GAP;
const graphHeight = height - GRAPH_BOTTOM_MARGIN - graphTop;
if (graphHeight >= MIN_GRAPH_HEIGHT) {
drawNightscoutGraph(image, { x: contentX, y: graphTop, width: contentWidth, height: graphHeight }, nightscout, nowMs, font);
}
this.menu.paint(image, notificationActionMenuBox(width, height), ctx.stack.isFocused());
return image;
}
async handleInput(event: InputEvent): Promise<void> {
if (event.type === "double-click") {
this.close();
} else if (event.type === "click") {
this.menu.selectedItem?.run();
} else if (event.type === "scroll-up" || event.type === "scroll-down") {
await this.menu.handleInput(event);
}
}
}
+9 -10
View File
@@ -13,6 +13,8 @@ import {
nightscoutBatteryLowSetting,
nightscoutMaxLoopAgeSetting,
nightscoutAlwaysShowInTopBarSetting,
nightscoutMissedBolusAlertsSetting,
nightscoutMissedBolusCooldownSetting,
toggleSettingMenuItem,
nightscoutApiTokenSetting,
nightscoutSiteUrlSetting,
@@ -28,6 +30,7 @@ export const NIGHTSCOUT_STALE_MS = 15 * 60 * 1000;
const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
const NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS = 60 * 1000;
/** Draws the trend indicator; returns its width. */
export function drawDirectionIndicator(
image: GrayImage,
font: UiFont,
@@ -35,16 +38,10 @@ export function drawDirectionIndicator(
y: number,
direction: string,
shade: number,
): void {
const label = directionGlyphLabel(font, direction);
if (label) {
image.drawText(font, x, y, label, shade);
return;
}
if (direction) {
image.drawText(font, x, y, truncateLine(direction, 10), shade);
}
): number {
const label = directionGlyphLabel(font, direction) || (direction ? truncateLine(direction, 10) : "");
if (label) image.drawText(font, x, y, label, shade);
return font.measureText(label);
}
/**
@@ -425,6 +422,8 @@ export function nightscoutMenuItems(): MenuItem[] {
textSettingMenuItem(nightscoutCartridgeLowSetting),
textSettingMenuItem(nightscoutBatteryLowSetting),
textSettingMenuItem(nightscoutMaxLoopAgeSetting),
toggleSettingMenuItem(nightscoutMissedBolusAlertsSetting),
textSettingMenuItem(nightscoutMissedBolusCooldownSetting),
]);
},
},
+18 -4
View File
@@ -1,5 +1,6 @@
import { nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings";
import { fetchTextWithUserAgent } from "../util/http";
import { bolusKindFromTreatment, type BolusKind } from "../apps/nightscout/missed-bolus-detector";
export type NightscoutPoint = {
timestampMs: number;
@@ -14,6 +15,8 @@ export type NightscoutCarbEvent = {
export type NightscoutBolusEvent = {
timestampMs: number;
insulin: number;
/** Meal, manual, loop-automatic, or unmarked (see BolusKind). */
kind: BolusKind;
};
export type NightscoutBasalEvent = {
@@ -102,10 +105,17 @@ type NightscoutTreatmentResponse = {
absolute?: unknown;
rate?: unknown;
duration?: unknown;
automatic?: unknown;
isSMB?: unknown;
type?: unknown;
wizard?: unknown;
};
const NIGHTSCOUT_REFRESH_MS = 60_000;
const NIGHTSCOUT_HISTORY_COUNT = 30;
// Glucose history by time rather than count, so a 1-minute CGM still covers
// the graphs' 2 hours and the missed-bolus detector's 90-minute lookback.
const NIGHTSCOUT_HISTORY_WINDOW_MS = 3 * 60 * 60 * 1000;
const NIGHTSCOUT_HISTORY_MAX_COUNT = 200;
const NIGHTSCOUT_TREATMENT_LOOKBACK_MS = 3 * 60 * 60 * 1000;
// The v1 treatments API silently adds `created_at >= now - 4 days` to any
// query without an explicit date filter (lib/server/query.js enforceDateFilter),
@@ -208,13 +218,17 @@ export class NightscoutBridge {
this.emit();
return;
}
const historyStartMs = nowMs - NIGHTSCOUT_HISTORY_WINDOW_MS;
const treatmentStartIso = new Date(nowMs - NIGHTSCOUT_TREATMENT_LOOKBACK_MS).toISOString();
const siteChangeStartIso = new Date(nowMs - NIGHTSCOUT_SITE_CHANGE_LOOKBACK_MS).toISOString();
const tokenQuery = `token=${encodeURIComponent(apiToken)}`;
const [entries, deviceStatus, status, treatments, siteChanges] = await Promise.all([
fetchJson<NightscoutEntryResponse[]>(
`${siteUrl}/api/v1/entries.json?count=${NIGHTSCOUT_HISTORY_COUNT}&${tokenQuery}`,
),
`${siteUrl}/api/v1/entries.json?find%5Bdate%5D%5B%24gte%5D=${historyStartMs}&count=${NIGHTSCOUT_HISTORY_MAX_COUNT}&${tokenQuery}`,
).then(async (recent) => recent?.length
? recent
// Nothing in the window: still show the last reading, as stale.
: await fetchJson<NightscoutEntryResponse[]>(`${siteUrl}/api/v1/entries.json?count=1&${tokenQuery}`)),
fetchJson<NightscoutDeviceStatusResponse[]>(
`${siteUrl}/api/v1/devicestatus.json?count=1&${tokenQuery}`,
),
@@ -334,7 +348,7 @@ function parseTreatments(treatments: NightscoutTreatmentResponse[], nowMs: numbe
const insulinValue = firstFiniteNumber(treatment.insulin);
if (insulinValue !== null && insulinValue > 0) {
boluses.push({ timestampMs, insulin: insulinValue });
boluses.push({ timestampMs, insulin: insulinValue, kind: bolusKindFromTreatment(treatment) });
}
const eventType = typeof treatment.eventType === "string" ? treatment.eventType : "";
+17
View File
@@ -1176,6 +1176,23 @@ export const nightscoutAlwaysShowInTopBarSetting = new ConfigSettingBoolean({
defaultValue: false,
description: "Keep the Nightscout glucose graph and warnings in the top bar even when all Nightscout windows are closed.",
});
export const nightscoutMissedBolusAlertsSetting = new ConfigSettingBoolean({
id: "nightscout-missed-bolus-alerts",
label: "Missed-bolus alerts",
storageKey: "integrations.nightscout.missedBolusAlerts",
defaultValue: false,
description: "Show a notification on the glasses when glucose rises like an unannounced meal with no bolus or carbs entered. Experimental.",
});
export const nightscoutMissedBolusCooldownSetting = new ConfigSettingString({
id: "nightscout-missed-bolus-cooldown-minutes",
label: "Missed-bolus alert cooldown",
storageKey: "integrations.nightscout.missedBolusCooldownMinutes",
defaultValue: "120",
editorTitle: "Missed-bolus alert cooldown (min)",
normalize: normalizeNightscoutThreshold,
formatValue: (value) => `${value} min`,
description: "After a missed-bolus alert, wait at least this many minutes before showing another.",
});
export function loadNightscoutThresholds(): NightscoutThresholds {
return {
+61 -39
View File
@@ -190,22 +190,7 @@ export class NotificationsListLayer implements Layer {
*/
export class SingleNotificationLayer implements Layer {
/** The action column; its items are rebuilt from the live notification on every paint and input. */
private readonly detailMenu = new Menu<DetailMenuItem>({
wrap: false,
rowGap: DETAIL_MENU_ROW_GAP,
highlight: { radius: 6 },
getHeight: (item, width) => {
const font = getDefaultSmallFont();
return detailMenuRowLines(font, item, width).length * lineStep(font) + 8;
},
draw: ({ image, item, x, y, width, selected }) => {
const font = getDefaultSmallFont();
const lines = detailMenuRowLines(font, item, width);
for (let line = 0; line < lines.length; line++) {
image.drawText(font, x + DETAIL_MENU_TEXT_X, y + DETAIL_MENU_TEXT_Y + line * lineStep(font), lines[line]!, selected ? 255 : 185);
}
},
});
private readonly detailMenu = createNotificationActionMenu<DetailMenuItem>((item) => item.kind === "disable-source");
private confirmation: { source: AndroidNotification; menu: Menu<ConfirmationItem> } | null = null;
// The last paint, which a tray-hosted layer repeats once its notification
// is gone, until the tray swaps in a neighbour's (see closeUnavailableNotification).
@@ -234,7 +219,7 @@ export class SingleNotificationLayer implements Layer {
this.detailMenu.setItems(buildDetailMenu(notification, this.options.origin));
drawDetailContent(image, font, notification, iconForNotification(notification.key), width, height);
this.detailMenu.paint(image, detailMenuBox(width, height), ctx.stack.isFocused());
this.detailMenu.paint(image, notificationActionMenuBox(width, height), ctx.stack.isFocused());
this.lastImage = image;
return image;
}
@@ -432,20 +417,9 @@ function drawDetailContent(
width: number,
height: number,
): void {
const contentX = DETAIL_CONTENT_X;
const menuX = width - DETAIL_MENU_WIDTH - 24;
const contentWidth = menuX - contentX - 20;
image.drawText(font, contentX, DETAIL_TITLE_Y, "Notification", 220);
// The header row (icon + app name) and the body stack below the title's
// line box, so a large UI font pushes them down instead of overlapping.
const headerTop = DETAIL_TITLE_Y + font.lineHeight + DETAIL_HEADER_GAP;
const headerHeight = Math.max(ICON_SIZE, font.lineHeight);
let appLineX = contentX;
if (icon) {
image.bitBlt(icon, contentX, headerTop + ((headerHeight - ICON_SIZE) >> 1), { transparentZero: true });
appLineX = contentX + ICON_SIZE + ICON_TEXT_GAP;
}
image.drawText(font, appLineX, centeredTextY(font, headerTop, headerHeight), `${notification.appName || notification.packageName} ${formatRelativeTime(notification.postTime)}`, 150);
const contentX = NOTIFICATION_CONTENT_X;
const contentWidth = notificationContentWidth(width);
const bodyTop = drawNotificationHeader(image, font, icon, `${notification.appName || notification.packageName} ${formatRelativeTime(notification.postTime)}`);
const lines: string[] = [];
lines.push(...wrapText(font, notification.title || "(untitled)", contentWidth));
@@ -461,7 +435,6 @@ function drawDetailContent(
}
const step = lineStep(font);
const bodyTop = headerTop + headerHeight + DETAIL_BODY_GAP;
const maxLines = Math.max(1, ((height - bodyTop - step) / step) | 0);
for (let index = 0; index < Math.min(lines.length, maxLines); index++) {
const line = lines[index]!;
@@ -472,8 +445,63 @@ function drawDetailContent(
}
}
/** Left edge of a notification detail view's content column. */
export const NOTIFICATION_CONTENT_X = DETAIL_CONTENT_X;
/** Width of a notification detail view's content column, left of the action column. */
export function notificationContentWidth(width: number): number {
return width - DETAIL_MENU_WIDTH - 24 - NOTIFICATION_CONTENT_X - 20;
}
/**
* The top of a notification detail view: the "Notification" title, then the
* source's icon and label. Returns the y where the body starts.
*/
export function drawNotificationHeader(image: GrayImage, font: UiFont, icon: GrayImage | null, sourceLabel: string): number {
const contentX = NOTIFICATION_CONTENT_X;
image.drawText(font, contentX, DETAIL_TITLE_Y, "Notification", 220);
// The header row (icon + app name) and the body stack below the title's
// line box, so a large UI font pushes them down instead of overlapping.
const headerTop = DETAIL_TITLE_Y + font.lineHeight + DETAIL_HEADER_GAP;
const headerHeight = Math.max(ICON_SIZE, font.lineHeight);
let sourceX = contentX;
if (icon) {
image.bitBlt(icon, contentX, headerTop + ((headerHeight - ICON_SIZE) >> 1), { transparentZero: true });
sourceX = contentX + ICON_SIZE + ICON_TEXT_GAP;
}
image.drawText(font, sourceX, centeredTextY(font, headerTop, headerHeight), sourceLabel, 150);
return headerTop + headerHeight + DETAIL_BODY_GAP;
}
/**
* A notification detail view's right-hand action column. Rows truncate their
* label to one line, except those `wraps` picks, which wrap it.
*/
export function createNotificationActionMenu<T extends { label: string }>(wraps: (item: T) => boolean = () => false): Menu<T> {
const rowLines = (font: UiFont, item: T, rowWidth: number): string[] => {
const textWidth = rowWidth - 2 * DETAIL_MENU_TEXT_X;
return wraps(item) ? wrapText(font, item.label, textWidth) : [truncateText(font, item.label, textWidth)];
};
return new Menu<T>({
wrap: false,
rowGap: DETAIL_MENU_ROW_GAP,
highlight: { radius: 6 },
getHeight: (item, width) => {
const font = getDefaultSmallFont();
return rowLines(font, item, width).length * lineStep(font) + 8;
},
draw: ({ image, item, x, y, width, selected }) => {
const font = getDefaultSmallFont();
const lines = rowLines(font, item, width);
for (let line = 0; line < lines.length; line++) {
image.drawText(font, x + DETAIL_MENU_TEXT_X, y + DETAIL_MENU_TEXT_Y + line * lineStep(font), lines[line]!, selected ? 255 : 185);
}
},
});
}
/** The action column's row boxes: right of the content, from DETAIL_MENU_TOP to the bottom margin. */
function detailMenuBox(width: number, height: number): MenuBox {
export function notificationActionMenuBox(width: number, height: number): MenuBox {
return {
x: width - DETAIL_MENU_WIDTH - 32,
y: DETAIL_MENU_TOP,
@@ -482,12 +510,6 @@ function detailMenuBox(width: number, height: number): MenuBox {
};
}
/** An action row's text lines: the disable-source row wraps, the rest truncate to one line. */
function detailMenuRowLines(font: UiFont, item: DetailMenuItem, rowWidth: number): string[] {
const textWidth = rowWidth - 2 * DETAIL_MENU_TEXT_X;
return item.kind === "disable-source" ? wrapText(font, item.label, textWidth) : [truncateText(font, item.label, textWidth)];
}
function buildDetailMenu(notification: AndroidNotification, origin: SingleNotificationLayerOrigin): DetailMenuItem[] {
return [
{ kind: "back", label: "Back" },
+47 -10
View File
@@ -239,8 +239,11 @@ export type TrayWidget = {
openWindow: () => { window: ShellWindow; opened: boolean } | null;
};
/** A new-notification popup: the shell modal, and the notification view inside it. */
type NotificationPopup = { modal: ShellModalLayer; content: SingleNotificationLayer };
/**
* A new-notification popup: the shell modal, and the notification view inside
* it (null for an app notification, which brings its own layer).
*/
type NotificationPopup = { modal: ShellModalLayer; content: SingleNotificationLayer | null };
/**
* The app switcher's selection while it is on a status bar item rather than
@@ -282,6 +285,18 @@ export type AssistantActivityEvent = {
export type FocusKind = "sidebar" | "window";
/**
* A notification an app posts itself, rather than one Android posted. It
* opens in the same modal (and waits in the same queue) as Android
* notifications, but is not listed in the Notifications app.
*/
export type AppNotification = {
/** Unique per notification; must not collide with Android notification keys. */
key: string;
/** The modal's content; `close` takes the modal down. */
createLayer: (close: () => void) => Layer;
};
const noopActions: LayerActions = noopLayerActions;
/**
@@ -437,9 +452,12 @@ class Shell {
private readonly trayIcons = new Map<string, { icon: GrayImage; widget?: TrayWidget }>();
private activeVoiceLayer: VoiceInputLayer | null = null;
private activeKeyboardLayer: KeyboardInputLayer | null = null;
// App-posted notifications that are open or queued, by key.
private readonly appNotifications = new Map<string, AppNotification>();
private readonly notificationModals = new NotificationModalQueue<NotificationPopup>({
open: (notificationKey) => this.pushNotificationModal(notificationKey),
isAvailable: (notificationKey) => {
if (this.appNotifications.has(notificationKey)) return true;
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey);
return !!notification && shouldShowNotificationOnGlasses(notification.packageName);
},
@@ -866,25 +884,44 @@ class Shell {
*/
notificationRemoved(notificationKey: string): void {
const popup = this.notificationModals.withdrawn(notificationKey);
if (popup && !popup.content.outlivesNotification()) {
this.closeNotificationModal(popup);
if (popup && !popup.content?.outlivesNotification()) {
this.closeNotificationModal(popup, notificationKey);
}
}
/**
* Show an app's own notification the way new Android notifications are
* shown: in the notification modal, waking the screen for it if it was off.
*/
postAppNotification(notification: AppNotification): void {
this.appNotifications.set(notification.key, notification);
const wokeScreen = this.screenOn ? false : this.wake("sidebar");
this.openNotificationModal(notification.key, wokeScreen);
}
private pushNotificationModal(notificationKey: string): NotificationPopup {
const content = new SingleNotificationLayer(notificationKey, {
origin: "new-notification-modal",
onClose: () => this.closeNotificationModal(popup),
});
const appNotification = this.appNotifications.get(notificationKey);
const close = () => this.closeNotificationModal(popup, notificationKey);
const content = appNotification
? null
: new SingleNotificationLayer(notificationKey, { origin: "new-notification-modal", onClose: close });
const popup: NotificationPopup = {
content,
modal: new ShellModalLayer(content, this.config.actions, () => this.notificationModals.removed(popup, this.screenOn)),
modal: new ShellModalLayer(
appNotification ? appNotification.createLayer(close) : content!,
this.config.actions,
() => {
this.appNotifications.delete(notificationKey);
this.notificationModals.removed(popup, this.screenOn);
},
),
};
this.stack.push(popup.modal);
return popup;
}
private closeNotificationModal(popup: NotificationPopup): void {
private closeNotificationModal(popup: NotificationPopup, notificationKey: string): void {
this.appNotifications.delete(notificationKey);
// The queue first: it opens the next notification or puts the screen back
// to sleep, and then ignores the removal below. remove() rather than a
// pop, so a menu opened over the modal doesn't leave it stuck.