forked from Blendman974/faceclaw
Connection reliability and thread safety fixes
This commit is contained in:
1 parent
0d0b55c2da
commit
aa0b1d6874
8 files changed
+567
-277
No files matched your search
@@ -50,6 +50,9 @@ type LogLevel = "debug"|"info"|"warn"|"error";
|
||||
const CONTAINER_NAME = "dashboard";
|
||||
const DASHBOARD_INTERVAL_MS = 60_000;
|
||||
const SCREEN_TIMEOUT_CHECK_MS = 1_000;
|
||||
const STOPWATCH_RENDER_INTERVAL_MS = 100;
|
||||
const FOREGROUND_NOTIFICATION_MIN_UPDATE_MS = 30_000;
|
||||
const FRAME_TRANSMIT_BACKPRESSURE_TIMEOUT_MS = 6_000;
|
||||
const EVEN_APP_DETECTED_MESSAGE =
|
||||
"The Even Realities app appears to be running. If Faceclaw has trouble connecting, open its app settings and force stop it.";
|
||||
|
||||
@@ -114,6 +117,7 @@ class DashboardController {
|
||||
private communicator: FaceclawCommunicatorBridge | null = null;
|
||||
private dashboardTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private screenTimeoutTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private stopwatchRenderTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private offState: (() => void) | null = null;
|
||||
private offLog: (() => void) | null = null;
|
||||
private offRing: (() => void) | null = null;
|
||||
@@ -129,6 +133,7 @@ class DashboardController {
|
||||
private renderInProgress = false;
|
||||
private renderQueued = false;
|
||||
private queuedRenderReason: "initial" | "interval" = "interval";
|
||||
private lastForegroundNotificationUpdateAtMs = 0;
|
||||
|
||||
constructor() {
|
||||
setDashboardActions({
|
||||
@@ -139,6 +144,7 @@ class DashboardController {
|
||||
startNightscoutApiTokenEdit: () => this.startNightscoutApiTokenEdit(),
|
||||
endTextSettingEdit: () => this.endTextSettingEdit(),
|
||||
setVoiceControlEnabled: (enabled) => this.setVoiceControlEnabled(enabled),
|
||||
setStopwatchRenderActive: (active) => this.setStopwatchRenderActive(active),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -354,6 +360,7 @@ class DashboardController {
|
||||
this.screenTimeoutTimer = setInterval(() => {
|
||||
if (this.phase !== "connected" || !this.communicator) return;
|
||||
if (!applyDashboardScreenTimeout()) return;
|
||||
this.setStopwatchRenderActive(false);
|
||||
this.endTextSettingEdit();
|
||||
void this.requestRender("interval").catch((error) => {
|
||||
const message = this.formatError(error);
|
||||
@@ -586,14 +593,13 @@ class DashboardController {
|
||||
const forceTiledCommit = consumeDashboardTiledWakePaint();
|
||||
const fingerprint = image.fingerprint();
|
||||
const tiles = image.toEvenHubTiles().map((tile) => tile.bmp);
|
||||
this.setDisplayPreview(grayImageToPreviewSource(image));
|
||||
if (this.communicator) {
|
||||
await this.communicator.submitDashboardImage(tiles, fingerprint, forceTiledCommit, paintMs);
|
||||
await this.communicator.waitForNextFrameMetrics(FRAME_TRANSMIT_BACKPRESSURE_TIMEOUT_MS);
|
||||
}
|
||||
this.setDisplayPreview(grayImageToPreviewSource(image));
|
||||
|
||||
if (this.phase === "connected") {
|
||||
updateForegroundNotification(`Connected`);
|
||||
}
|
||||
this.updateConnectedForegroundNotification();
|
||||
this.appendLog(`${reason === "initial" ? "initial" : "scheduled"} dashboard image queued`);
|
||||
}
|
||||
|
||||
@@ -652,12 +658,26 @@ class DashboardController {
|
||||
private startVoiceControlIfEnabled(): void {
|
||||
if (!this.communicator) return;
|
||||
if (!isDashboardVoiceControlEnabled()) return;
|
||||
if (this.phase === "connected") {
|
||||
updateForegroundNotification("Connected");
|
||||
}
|
||||
this.updateConnectedForegroundNotification();
|
||||
voiceControlBridge.start();
|
||||
}
|
||||
|
||||
private setStopwatchRenderActive(active: boolean): void {
|
||||
if (!active || this.phase !== "connected" || !this.communicator) {
|
||||
if (this.stopwatchRenderTimer) {
|
||||
clearInterval(this.stopwatchRenderTimer);
|
||||
this.stopwatchRenderTimer = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.stopwatchRenderTimer) return;
|
||||
this.stopwatchRenderTimer = setInterval(() => {
|
||||
void this.requestRender("interval").catch((error) => {
|
||||
this.appendLog(`stopwatch render failed: ${this.formatError(error)}`);
|
||||
});
|
||||
}, STOPWATCH_RENDER_INTERVAL_MS);
|
||||
}
|
||||
|
||||
private clearDashboardTimer(): void {
|
||||
if (this.dashboardTimer) {
|
||||
clearInterval(this.dashboardTimer);
|
||||
@@ -667,6 +687,10 @@ class DashboardController {
|
||||
clearInterval(this.screenTimeoutTimer);
|
||||
this.screenTimeoutTimer = null;
|
||||
}
|
||||
if (this.stopwatchRenderTimer) {
|
||||
clearInterval(this.stopwatchRenderTimer);
|
||||
this.stopwatchRenderTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private setPhase(phase: ConnectionPhase): void {
|
||||
@@ -681,6 +705,14 @@ class DashboardController {
|
||||
this.emit();
|
||||
}
|
||||
|
||||
private updateConnectedForegroundNotification(): void {
|
||||
if (this.phase !== "connected") return;
|
||||
const now = Date.now();
|
||||
if (now - this.lastForegroundNotificationUpdateAtMs < FOREGROUND_NOTIFICATION_MIN_UPDATE_MS) return;
|
||||
this.lastForegroundNotificationUpdateAtMs = now;
|
||||
updateForegroundNotification("Connected");
|
||||
}
|
||||
|
||||
private formatFrameMetrics(metrics: FrameMetrics): string {
|
||||
return `paint=${Math.round(metrics.paintMs)}ms, transmit=${Math.round(metrics.transmitMs)}ms, tiles=${Math.round(metrics.tileCount)}`;
|
||||
}
|
||||
|
||||
@@ -65,6 +65,8 @@ function nonNegativeNumber(value: number): number {
|
||||
export class FaceclawCommunicatorBridge {
|
||||
private readonly communicator: any;
|
||||
private readonly listenerProxy: any;
|
||||
private javaCallQueue: Promise<void> = Promise.resolve();
|
||||
private readonly frameMetricWaiters = new Set<(metrics: FrameMetrics) => void>();
|
||||
private readonly logListeners = new Set<(line: string) => void>();
|
||||
private readonly stateListeners = new Set<(state: CommunicatorState) => void>();
|
||||
private readonly ringListeners = new Set<(event: RawInputEvent) => void>();
|
||||
@@ -84,18 +86,14 @@ export class FaceclawCommunicatorBridge {
|
||||
);
|
||||
this.listenerProxy = new com.faceclaw.app.FaceclawBleCommunicatorListener({
|
||||
onLog: (line: string) => {
|
||||
for (const listener of this.logListeners) {
|
||||
listener(String(line));
|
||||
}
|
||||
this.emitAsync(this.logListeners, String(line));
|
||||
},
|
||||
onStateChange: (phase: string, status: string) => {
|
||||
const state = {
|
||||
phase: String(phase) as CommunicatorPhase,
|
||||
status: String(status),
|
||||
};
|
||||
for (const listener of this.stateListeners) {
|
||||
listener(state);
|
||||
}
|
||||
this.emitAsync(this.stateListeners, state);
|
||||
},
|
||||
onRingEvent: (
|
||||
kind: string,
|
||||
@@ -111,23 +109,17 @@ export class FaceclawCommunicatorBridge {
|
||||
eventSource: Number(eventSource),
|
||||
systemExitReasonCode: Number(systemExitReasonCode),
|
||||
};
|
||||
for (const listener of this.ringListeners) {
|
||||
listener(event);
|
||||
}
|
||||
this.emitAsync(this.ringListeners, event);
|
||||
},
|
||||
onBatteryState: (headsetBattery: number, headsetCharging: number) => {
|
||||
const state = {
|
||||
battery: Number(headsetBattery),
|
||||
chargingStatus: Number(headsetCharging),
|
||||
};
|
||||
for (const listener of this.batteryListeners) {
|
||||
listener(state);
|
||||
}
|
||||
this.emitAsync(this.batteryListeners, state);
|
||||
},
|
||||
onEvenAppConflict: (message: string) => {
|
||||
for (const listener of this.evenAppConflictListeners) {
|
||||
listener(String(message));
|
||||
}
|
||||
this.emitAsync(this.evenAppConflictListeners, String(message));
|
||||
},
|
||||
onFrameMetrics: (paintMs: number, transmitMs: number, tileCount: number) => {
|
||||
const metrics = {
|
||||
@@ -135,14 +127,46 @@ export class FaceclawCommunicatorBridge {
|
||||
transmitMs: nonNegativeNumber(transmitMs),
|
||||
tileCount: nonNegativeNumber(tileCount),
|
||||
};
|
||||
for (const listener of this.frameMetricsListeners) {
|
||||
listener(metrics);
|
||||
const waiters = Array.from(this.frameMetricWaiters);
|
||||
this.frameMetricWaiters.clear();
|
||||
for (const waiter of waiters) {
|
||||
setTimeout(() => waiter(metrics), 0);
|
||||
}
|
||||
this.emitAsync(this.frameMetricsListeners, metrics);
|
||||
},
|
||||
});
|
||||
this.communicator.setListener(this.listenerProxy);
|
||||
}
|
||||
|
||||
private emitAsync<T>(listeners: Set<(value: T) => void>, value: T): void {
|
||||
const snapshot = Array.from(listeners);
|
||||
setTimeout(() => {
|
||||
for (const listener of snapshot) {
|
||||
listener(value);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
private enqueueJavaCall<T>(operation: () => T): Promise<T> {
|
||||
const run = () =>
|
||||
new Promise<T>((resolve, reject) => {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
resolve(operation());
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
}, 0);
|
||||
});
|
||||
|
||||
const result = this.javaCallQueue.then(run, run);
|
||||
this.javaCallQueue = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
onLog(listener: (line: string) => void): () => void {
|
||||
this.logListeners.add(listener);
|
||||
return () => this.logListeners.delete(listener);
|
||||
@@ -173,34 +197,57 @@ export class FaceclawCommunicatorBridge {
|
||||
return () => this.frameMetricsListeners.delete(listener);
|
||||
}
|
||||
|
||||
waitForNextFrameMetrics(timeoutMs: number): Promise<FrameMetrics | null> {
|
||||
const delayMs = Math.max(1, Math.round(nonNegativeNumber(timeoutMs)));
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
|
||||
const complete = (metrics: FrameMetrics | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timeoutHandle !== null) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.frameMetricWaiters.delete(onMetrics);
|
||||
resolve(metrics);
|
||||
};
|
||||
const onMetrics = (metrics: FrameMetrics) => complete(metrics);
|
||||
this.frameMetricWaiters.add(onMetrics);
|
||||
timeoutHandle = setTimeout(() => complete(null), delayMs);
|
||||
});
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.communicator.start();
|
||||
await this.enqueueJavaCall(() => this.communicator.start());
|
||||
}
|
||||
|
||||
async submitDashboardImage(tileBmps: Uint8Array[], fingerprint: string, forceTiledCommit = false, paintMs = -1): Promise<void> {
|
||||
if (tileBmps.length !== 4) {
|
||||
throw new Error(`expected 4 dashboard tiles, got ${tileBmps.length}`);
|
||||
}
|
||||
this.communicator.submitDashboardImage4(
|
||||
toJavaByteArray(tileBmps[0]!),
|
||||
toJavaByteArray(tileBmps[1]!),
|
||||
toJavaByteArray(tileBmps[2]!),
|
||||
toJavaByteArray(tileBmps[3]!),
|
||||
fingerprint,
|
||||
forceTiledCommit,
|
||||
Math.round(nonNegativeNumber(paintMs)),
|
||||
);
|
||||
const tileSnapshots = tileBmps.map((tile) => new Uint8Array(tile));
|
||||
await this.enqueueJavaCall(() => {
|
||||
this.communicator.submitDashboardImage4(
|
||||
toJavaByteArray(tileSnapshots[0]!),
|
||||
toJavaByteArray(tileSnapshots[1]!),
|
||||
toJavaByteArray(tileSnapshots[2]!),
|
||||
toJavaByteArray(tileSnapshots[3]!),
|
||||
fingerprint,
|
||||
forceTiledCommit,
|
||||
Math.round(nonNegativeNumber(paintMs)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.communicator.disconnect();
|
||||
await this.enqueueJavaCall(() => this.communicator.disconnect());
|
||||
}
|
||||
|
||||
async sendShutdown(exitMode = 0): Promise<boolean> {
|
||||
return Boolean(this.communicator.sendShutdown(exitMode));
|
||||
return this.enqueueJavaCall(() => Boolean(this.communicator.sendShutdown(exitMode)));
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.communicator.close();
|
||||
await this.enqueueJavaCall(() => this.communicator.close());
|
||||
}
|
||||
}
|
||||
+36
-21
@@ -149,6 +149,7 @@ const PLUGIN_MAP = new Map<DashboardPluginId, DashboardPlugin>(
|
||||
const nightscoutLargeFont = loadEmbeddedTerminus24();
|
||||
const NIGHTSCOUT_STALE_MS = 15 * 60 * 1000;
|
||||
const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
|
||||
const NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS = 60 * 1000;
|
||||
|
||||
export function listDashboardPlugins(): DashboardPlugin[] {
|
||||
return [...DASHBOARD_PLUGINS];
|
||||
@@ -294,8 +295,12 @@ function drawNightscoutGraph(
|
||||
return;
|
||||
}
|
||||
|
||||
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
||||
const visibleHistory = nightscout.history.filter((point) => point.timestampMs >= windowStartMs && point.timestampMs <= nowMs);
|
||||
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;
|
||||
}
|
||||
@@ -308,18 +313,14 @@ function drawNightscoutGraph(
|
||||
const paddedMax = max + range * 0.1;
|
||||
|
||||
image.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 56);
|
||||
drawNightscoutBasalOverlay(image, bounds, nightscout.basal, nowMs);
|
||||
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:
|
||||
bounds.x +
|
||||
Math.round(
|
||||
((point.timestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1),
|
||||
),
|
||||
x: timeToGraphX(bounds, windowStartMs, point.timestampMs),
|
||||
y:
|
||||
bounds.y +
|
||||
bounds.height -
|
||||
@@ -343,8 +344,8 @@ function drawNightscoutGraph(
|
||||
image.fillRect(current.x - 1, current.y - 1, 2, 2, 220);
|
||||
}
|
||||
}
|
||||
drawNightscoutCarbMarkers(image, bounds, font, nightscout.carbs, nowMs);
|
||||
drawNightscoutBolusMarkers(image, bounds, font, nightscout.boluses, nowMs);
|
||||
drawNightscoutCarbMarkers(image, bounds, font, nightscout.carbs, graphNowMs);
|
||||
drawNightscoutBolusMarkers(image, bounds, font, nightscout.boluses, graphNowMs);
|
||||
}
|
||||
|
||||
function drawNightscoutBasalOverlay(
|
||||
@@ -353,9 +354,12 @@ function drawNightscoutBasalOverlay(
|
||||
basalEvents: NightscoutState["basal"],
|
||||
nowMs: number,
|
||||
): void {
|
||||
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
||||
const graphNowMs = minuteBucketTimestampMs(nowMs);
|
||||
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
||||
const visibleEvents = basalEvents.filter(
|
||||
(event) => event.timestampMs + event.durationMinutes * 60_000 >= windowStartMs && event.timestampMs <= nowMs,
|
||||
(event) =>
|
||||
minuteBucketTimestampMs(event.timestampMs + event.durationMinutes * 60_000) >= windowStartMs &&
|
||||
minuteBucketTimestampMs(event.timestampMs) <= graphNowMs,
|
||||
);
|
||||
if (visibleEvents.length === 0) {
|
||||
return;
|
||||
@@ -367,8 +371,8 @@ function drawNightscoutBasalOverlay(
|
||||
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, event.timestampMs);
|
||||
const endMs = Math.min(nowMs, event.timestampMs + event.durationMinutes * 60_000);
|
||||
const startMs = Math.max(windowStartMs, minuteBucketTimestampMs(event.timestampMs));
|
||||
const endMs = Math.min(graphNowMs, minuteBucketTimestampMs(event.timestampMs + event.durationMinutes * 60_000));
|
||||
if (endMs <= startMs) {
|
||||
continue;
|
||||
}
|
||||
@@ -386,13 +390,15 @@ function drawNightscoutCarbMarkers(
|
||||
carbEvents: NightscoutState["carbs"],
|
||||
nowMs: number,
|
||||
): void {
|
||||
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
||||
const graphNowMs = minuteBucketTimestampMs(nowMs);
|
||||
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
||||
const baselineY = bounds.y + bounds.height - 2;
|
||||
for (const event of carbEvents) {
|
||||
if (event.timestampMs < windowStartMs || event.timestampMs > nowMs) {
|
||||
const eventTimestampMs = minuteBucketTimestampMs(event.timestampMs);
|
||||
if (eventTimestampMs < windowStartMs || eventTimestampMs > graphNowMs) {
|
||||
continue;
|
||||
}
|
||||
const x = timeToGraphX(bounds, windowStartMs, event.timestampMs);
|
||||
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);
|
||||
}
|
||||
@@ -405,13 +411,15 @@ function drawNightscoutBolusMarkers(
|
||||
bolusEvents: NightscoutState["boluses"],
|
||||
nowMs: number,
|
||||
): void {
|
||||
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
||||
const graphNowMs = minuteBucketTimestampMs(nowMs);
|
||||
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
||||
const topY = bounds.y + 1;
|
||||
for (const event of bolusEvents) {
|
||||
if (event.timestampMs < windowStartMs || event.timestampMs > nowMs) {
|
||||
const eventTimestampMs = minuteBucketTimestampMs(event.timestampMs);
|
||||
if (eventTimestampMs < windowStartMs || eventTimestampMs > graphNowMs) {
|
||||
continue;
|
||||
}
|
||||
const x = timeToGraphX(bounds, windowStartMs, event.timestampMs);
|
||||
const x = timeToGraphX(bounds, windowStartMs, eventTimestampMs);
|
||||
image.drawLine(x, topY, x, topY + 6, 144);
|
||||
if (event.insulin >= 1) {
|
||||
drawTextCentered(
|
||||
@@ -446,12 +454,19 @@ function timeToGraphX(
|
||||
windowStartMs: number,
|
||||
timestampMs: number,
|
||||
): number {
|
||||
const graphTimestampMs = minuteBucketTimestampMs(timestampMs);
|
||||
return (
|
||||
bounds.x +
|
||||
Math.round(((timestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1))
|
||||
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 },
|
||||
|
||||
+77
-3
@@ -84,6 +84,7 @@ const dashboardActions: LayerActions = {
|
||||
startNightscoutApiTokenEdit: () => {},
|
||||
endTextSettingEdit: () => {},
|
||||
setVoiceControlEnabled: () => {},
|
||||
setStopwatchRenderActive: () => {},
|
||||
};
|
||||
const dashboardFont = loadEmbeddedTerminus12();
|
||||
const dashboardSystemFont = loadEmbeddedTerminus16();
|
||||
@@ -443,12 +444,12 @@ function createRootMenuLayer(): MenuLayer {
|
||||
return new RootMenuLayer(
|
||||
"Menu",
|
||||
[
|
||||
/*{
|
||||
{
|
||||
label: "Apps",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(createAppsMenuLayer());
|
||||
},
|
||||
},*/
|
||||
},
|
||||
{
|
||||
label: "Settings",
|
||||
onSelect: (ctx) => {
|
||||
@@ -476,7 +477,80 @@ function createRootMenuLayer(): MenuLayer {
|
||||
}
|
||||
|
||||
function createAppsMenuLayer(): MenuLayer {
|
||||
return new MenuLayer("Apps", [], TOP_LEFT_MENU_LAYOUT);
|
||||
return new MenuLayer(
|
||||
"Apps",
|
||||
[
|
||||
{
|
||||
label: "Stopwatch",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new StopwatchLayer());
|
||||
void ctx.actions.setStopwatchRenderActive(true);
|
||||
},
|
||||
},
|
||||
],
|
||||
TOP_LEFT_MENU_LAYOUT,
|
||||
);
|
||||
}
|
||||
|
||||
class StopwatchLayer implements Layer {
|
||||
private readonly startedAtMs = Date.now();
|
||||
private pausedAtMs: number | null = null;
|
||||
private pausedDurationMs = 0;
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
|
||||
const elapsedMs = this.elapsedMs();
|
||||
const timeLabel = formatStopwatchElapsed(elapsedMs);
|
||||
const stateLabel = this.pausedAtMs === null ? "Running" : "Paused";
|
||||
|
||||
image.drawRect(12, 12, G2_LENS_WIDTH - 24, G2_LENS_HEIGHT - 24, 52);
|
||||
image.drawText(ctx.font, 24, 24, "Stopwatch", 180);
|
||||
image.drawText(ctx.font, G2_LENS_WIDTH - 114, 24, stateLabel, this.pausedAtMs === null ? 200 : 120);
|
||||
|
||||
const timeX = Math.max(0, ((G2_LENS_WIDTH - dashboardSystemFont.measureText(timeLabel)) / 2) | 0);
|
||||
image.drawText(dashboardSystemFont, timeX, 106, timeLabel, 245);
|
||||
image.drawText(ctx.font, 126, 160, "Click: pause / resume", 150);
|
||||
image.drawText(ctx.font, 126, 178, "Double-click: back", 120);
|
||||
image.drawText(ctx.font, 126, 214, "Renders requested every 100ms", 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
|
||||
if (event.type === "double-click") {
|
||||
void ctx.actions.setStopwatchRenderActive(false);
|
||||
ctx.stack.pop();
|
||||
return;
|
||||
}
|
||||
if (event.type === "click") {
|
||||
if (this.pausedAtMs === null) {
|
||||
this.pausedAtMs = Date.now();
|
||||
void ctx.actions.setStopwatchRenderActive(false);
|
||||
} else {
|
||||
this.pausedDurationMs += Date.now() - this.pausedAtMs;
|
||||
this.pausedAtMs = null;
|
||||
void ctx.actions.setStopwatchRenderActive(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private elapsedMs(): number {
|
||||
const now = this.pausedAtMs ?? Date.now();
|
||||
return Math.max(0, now - this.startedAtMs - this.pausedDurationMs);
|
||||
}
|
||||
}
|
||||
|
||||
function formatStopwatchElapsed(elapsedMs: number): string {
|
||||
const totalTenths = Math.floor(elapsedMs / 100);
|
||||
const tenths = totalTenths % 10;
|
||||
const totalSeconds = Math.floor(totalTenths / 10);
|
||||
const seconds = totalSeconds % 60;
|
||||
const totalMinutes = Math.floor(totalSeconds / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
if (hours > 0) {
|
||||
return `${hours}:${pad2(minutes)}:${pad2(seconds)}.${tenths}`;
|
||||
}
|
||||
return `${pad2(minutes)}:${pad2(seconds)}.${tenths}`;
|
||||
}
|
||||
|
||||
function createSystemMenuLayer(): MenuLayer {
|
||||
|
||||
@@ -16,6 +16,7 @@ export type LayerActions = {
|
||||
startNightscoutApiTokenEdit: () => Promise<void> | void;
|
||||
endTextSettingEdit: () => Promise<void> | void;
|
||||
setVoiceControlEnabled: (enabled: boolean) => Promise<void> | void;
|
||||
setStopwatchRenderActive: (active: boolean) => Promise<void> | void;
|
||||
};
|
||||
|
||||
export type PaintBelow = () => GrayImage;
|
||||
|
||||
Reference in new issue
Block a user