Repository navigation
Expand file tree
/
Copy pathnightscout.ts
More file actions
404 lines (371 loc) · 14.1 KB
/
Copy pathnightscout.ts
File metadata and controls
404 lines (371 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import { BdfFont, getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage, imageFromAsciiArt } from "../../graphics/image";
import { DashboardInputEvent, Layer, LayerContext } from "../layers";
import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge";
import {
isNightscoutSettingsConfigured,
nightscoutApiTokenSetting,
nightscoutSiteUrlSetting,
textSettingMenuItem,
} from "../dashboard-settings";
import { formatAgeShortFromTimestamp, formatTimestamp } from "~/util/date-util";
import { MenuLayer } from "../menu";
import { openSettingsSubMenu } from "../dashboard/settings-panel";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK } from "../gestures";
const nightscoutLargeFont = getDefaultLargeFont();
const NIGHTSCOUT_STALE_MS = 15 * 60 * 1000;
const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
const NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS = 60 * 1000;
function drawDirectionIndicator(
image: GrayImage,
font: BdfFont,
x: number,
y: number,
direction: string,
shade: number,
): void {
const label = directionGlyphLabel(font, direction);
if (label) {
image.drawText(font, x, y, label, shade);
return;
}
const art = directionAsciiArt(direction);
if (art) {
image.bitBlt(imageFromAsciiArt(art, shade), x, y + 1);
return;
}
if (direction) {
image.drawText(font, x, y, truncateLine(direction, 10), shade);
}
}
function directionGlyphLabel(font: BdfFont, direction: string): string {
switch (direction) {
case "DoubleUp":
return font.hasGlyph("↑".codePointAt(0)!) ? "↑↑" : "";
case "SingleUp":
return font.hasGlyph("↑".codePointAt(0)!) ? "↑" : "";
case "FortyFiveUp":
return font.hasGlyph("↗".codePointAt(0)!) ? "↗" : "";
case "Flat":
return font.hasGlyph("→".codePointAt(0)!) ? "→" : "";
case "FortyFiveDown":
return font.hasGlyph("↘".codePointAt(0)!) ? "↘" : "";
case "SingleDown":
return font.hasGlyph("↓".codePointAt(0)!) ? "↓" : "";
case "DoubleDown":
return font.hasGlyph("↓".codePointAt(0)!) ? "↓↓" : "";
default:
return "";
}
}
function directionAsciiArt(direction: string): readonly string[] | undefined {
switch (direction) {
case "FortyFiveUp":
return [" ##", " ###", " # ##", "# ##", " ##"];
case "FortyFiveDown":
return [" ##", "# ##", " # ##", " ###", " ##"];
default:
return undefined;
}
}
function truncateLine(text: string, maxChars: number): string {
if (text.length <= maxChars) return text;
return `${text.slice(0, Math.max(0, maxChars - 3))}...`;
}
function formatDelta(delta: number | null): string {
if (delta === null) return "--";
return `${delta >= 0 ? "+" : ""}${Math.round(delta)}`;
}
function formatWholeNumber(value: number): string {
return `${Math.round(value)}`;
}
function formatBolusLabel(value: number): string {
return Number.isInteger(value) ? `${value}` : value.toFixed(1);
}
function drawNightscoutGraph(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
nightscout: NightscoutState,
nowMs: number,
font: BdfFont,
): void {
if (bounds.width <= 2 || bounds.height <= 2) {
return;
}
const graphNowMs = minuteBucketTimestampMs(nowMs);
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const visibleHistory = nightscout.history.filter((point) => {
const pointTimestampMs = minuteBucketTimestampMs(point.timestampMs);
return pointTimestampMs >= windowStartMs && pointTimestampMs <= graphNowMs;
});
if (visibleHistory.length === 0) {
return;
}
const values = visibleHistory.map((point) => point.sgv);
const min = Math.min(...values, 60);
const max = Math.max(...values, 200);
const range = Math.max(20, max - min);
const paddedMin = min - range * 0.1;
const paddedMax = max + range * 0.1;
image.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 56);
drawNightscoutBasalOverlay(image, bounds, nightscout.basal, graphNowMs);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 60, 40);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 100, 40);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 180, 40);
const plotted = visibleHistory.map((point) => ({
point,
x: timeToGraphX(bounds, windowStartMs, point.timestampMs),
y:
bounds.y +
bounds.height -
1 -
Math.round(((point.sgv - paddedMin) / Math.max(1, paddedMax - paddedMin)) * Math.max(1, bounds.height - 1)),
}));
for (let i = 0; i < plotted.length; i++) {
const current = plotted[i]!;
const previous = i > 0 ? plotted[i - 1]! : null;
const next = i + 1 < plotted.length ? plotted[i + 1]! : null;
const connectedToPrevious =
previous !== null && current.point.timestampMs - previous.point.timestampMs <= NIGHTSCOUT_STALE_MS;
const connectedToNext =
next !== null && next.point.timestampMs - current.point.timestampMs <= NIGHTSCOUT_STALE_MS;
if (connectedToPrevious && previous) {
image.drawLine(previous.x, previous.y, current.x, current.y, 220);
}
if (!connectedToPrevious && !connectedToNext) {
image.fillRect(current.x - 1, current.y - 1, 2, 2, 220);
}
}
drawNightscoutCarbMarkers(image, bounds, font, nightscout.carbs, graphNowMs);
drawNightscoutBolusMarkers(image, bounds, font, nightscout.boluses, graphNowMs);
}
function drawNightscoutBasalOverlay(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
basalEvents: NightscoutState["basal"],
nowMs: number,
): void {
const graphNowMs = minuteBucketTimestampMs(nowMs);
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const visibleEvents = basalEvents.filter(
(event) =>
minuteBucketTimestampMs(event.timestampMs + even
10BC8
t.durationMinutes * 60_000) >= windowStartMs &&
minuteBucketTimestampMs(event.timestampMs) <= graphNowMs,
);
if (visibleEvents.length === 0) {
return;
}
const maxRate = Math.max(...visibleEvents.map((event) => event.rate), 0);
if (maxRate <= 0) {
return;
}
const overlayHeight = Math.max(8, Math.min(18, Math.floor(bounds.height * 0.22)));
const bottomY = bounds.y + bounds.height - 2;
for (const event of visibleEvents) {
const startMs = Math.max(windowStartMs, minuteBucketTimestampMs(event.timestampMs));
const endMs = Math.min(graphNowMs, minuteBucketTimestampMs(event.timestampMs + event.durationMinutes * 60_000));
if (endMs <= startMs) {
continue;
}
const leftX = timeToGraphX(bounds, windowStartMs, startMs);
const rightX = timeToGraphX(bounds, windowStartMs, endMs);
const height = Math.max(1, Math.round((event.rate / maxRate) * overlayHeight));
image.fillRect(leftX, bottomY - height + 1, Math.max(1, rightX - leftX + 1), height, 15);
}
}
function drawNightscoutCarbMarkers(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
font: BdfFont,
carbEvents: NightscoutState["carbs"],
nowMs: number,
): void {
const graphNowMs = minuteBucketTimestampMs(nowMs);
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const baselineY = bounds.y + bounds.height - 2;
for (const event of carbEvents) {
const eventTimestampMs = minuteBucketTimestampMs(event.timestampMs);
if (eventTimestampMs < windowStartMs || eventTimestampMs > graphNowMs) {
continue;
}
const x = timeToGraphX(bounds, windowStartMs, eventTimestampMs);
image.drawLine(x, baselineY, x, baselineY - 6, 150);
drawTextCentered(image, font, x, Math.max(bounds.y + 2, baselineY - 18), `${Math.round(event.carbs)}`, 150, bounds);
}
}
function drawNightscoutBolusMarkers(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
font: BdfFont,
bolusEvents: NightscoutState["boluses"],
nowMs: number,
): void {
const graphNowMs = minuteBucketTimestampMs(nowMs);
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const topY = bounds.y + 1;
for (const event of bolusEvents) {
const eventTimestampMs = minuteBucketTimestampMs(event.timestampMs);
if (eventTimestampMs < windowStartMs || eventTimestampMs > graphNowMs) {
continue;
}
const x = timeToGraphX(bounds, windowStartMs, eventTimestampMs);
image.drawLine(x, topY, x, topY + 6, 144);
if (event.insulin >= 1) {
drawTextCentered(
image,
font,
x,
Math.min(bounds.y + bounds.height - font.lineHeight - 1, topY + 8),
formatBolusLabel(event.insulin),
144,
bounds,
);
}
}
}
function drawTextCentered(
image: GrayImage,
font: BdfFont,
centerX: number,
y: number,
text: string,
shade: number,
bounds: { x: number; y: number; width: number; height: number },
): void {
const textWidth = font.measureText(text);
const x = Math.max(bounds.x + 1, Math.min(bounds.x + bounds.width - textWidth - 1, centerX - Math.round(textWidth / 2)));
image.drawText(font, x, y, text, shade);
}
function timeToGraphX(
bounds: { x: number; y: number; width: number; height: number },
windowStartMs: number,
timestampMs: number,
): number {
const graphTimestampMs = minuteBucketTimestampMs(timestampMs);
return (
bounds.x +
Math.round(
((graphTimestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1),
)
);
}
function minuteBucketTimestampMs(timestampMs: number): number {
return Math.floor(timestampMs / NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS) * NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS;
}
function drawNightscoutReferenceLine(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
minValue: number,
maxValue: number,
value: number,
shade: number,
): void {
const y =
bounds.y +
bounds.height -
1 -
Math.round(((value - minValue) / Math.max(1, maxValue - minValue)) * Math.max(1, bounds.height - 1));
image.drawLine(bounds.x + 1, y, bounds.x + bounds.width - 2, y, shade);
}
export class NightscoutLayer implements Layer {
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
// Sized to the hosting stack (the Nightscout app viewport).
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const nightscout = nightscoutBridge.snapshot();
const nowMs = Date.now();
const footerY = height - 26;
image.drawText(font, 22, 16, "Nightscout", 220);
if (!isNightscoutSettingsConfigured() || nightscout.configurationMissing) {
image.drawText(font, 22, 44, "Nightscout needs configuration.", 180);
image.drawText(font, 22, 62, `Set the site URL and API token in ${GESTURE_CLICK} menu > Settings.`, 140);
image.drawText(font, 22, footerY, `${GESTURE_CLICK} menu ${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
if (!nightscout.available || !nightscout.latest) {
image.drawText(font, 22, 44, "No Nightscout data available.", 180);
image.drawText(font, 22, 58, truncateLine(nightscout.status, 60), 140);
image.drawText(font, 22, footerY, `${GESTURE_CLICK} menu ${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
const latest = nightscout.latest;
const glucoseText = `${latest.sgv}`;
const glucoseX = 22;
const glucoseWidth = nightscoutLargeFont.measureText(glucoseText);
image.drawText(nightscoutLargeFont, glucoseX, 28, glucoseText, 230);
if (isNightscoutPointStale(latest, nowMs)) {
drawNightscoutValueStrikeThrough(image, glucoseX, 40, glucoseWidth);
}
image.drawText(font, glucoseX + glucoseWidth + 8, 36, nightscout.units, 140);
const trendText = `Delta ${formatDelta(nightscout.delta)} Trend `;
image.drawText(font, 22, 62, trendText, 180);
drawDirectionIndicator(image, font, 22 + font.measureText(trendText), 62, nightscout.direction, 180);
image.drawText(
font,
22,
78,
`IOB ${nightscout.iob === null ? "--" : nightscout.iob.toFixed(2)} COB ${nightscout.cob === null ? "--" : formatWholeNumber(nightscout.cob)} Updated ${formatTimestamp(latest.timestampMs)}`,
160,
);
image.drawText(
font,
22,
94,
`CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)} Loop ${nightscout.openapsStatusShort}`,
160,
);
image.drawText(font, 22, 110, `Pump ${truncateLine(nightscout.pumpStatus || "--", 56)}`, 150);
const graphHeight = Math.max(40, height - 128 - 48);
drawNightscoutGraph(image, { x: 22, y: 128, width: width - 44, height: graphHeight }, nightscout, nowMs, font);
image.drawText(font, 22, height - 42, "2-hour glucose history with basal / carbs / boluses", 130);
image.drawText(font, 22, footerY, `${GESTURE_CLICK} menu ${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
switch (event.type) {
case "click":
ctx.stack.push(createNightscoutMenu());
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
}
/** The app menu (opened with a click); MenuLayer self-closes on double-click. */
function createNightscoutMenu(): MenuLayer {
return new MenuLayer(
"Nightscout",
[
{
label: "Refresh",
onSelect: async (ctx) => {
ctx.stack.pop();
await nightscoutBridge.refreshNow();
},
},
{
label: "Settings",
onSelect: (ctx) => {
// Pop the menu first so closing the settings modal lands back on
// the glucose view, not this menu.
ctx.stack.pop();
openSettingsSubMenu(ctx, "Nightscout settings", [
textSettingMenuItem(nightscoutSiteUrlSetting),
textSettingMenuItem(nightscoutApiTokenSetting),
]);
},
},
],
{ x: 8, y: 8, width: 200, minHeight: 0 },
);
}
function isNightscoutPointStale(point: NightscoutState["latest"], nowMs: number): boolean {
return point !== null && nowMs - point.timestampMs > NIGHTSCOUT_STALE_MS;
}
function drawNightscoutValueStrikeThrough(image: GrayImage, x: number, y: number, width: number): void {
image.drawLine(x, y, x + width, y, 180);
}