Compass has higher sample rate, and distinguishes map north from true north

This commit is contained in:
James Babcock committed 2026-09-01 14:37:09 -07:00
1 parent eb8a863222
commit a72e29a04f
13 files changed
+429 -55

No files matched your search

+31 -17
View File
@@ -1,7 +1,11 @@
/**
* The compass calibration screen: a crosshair the wearer aims at a landmark
* of known heading, plus raw/offset/calibrated readouts. Swipe adjusts the
* offset by 1°, double-tap returns to the compass.
* of known heading, plus raw/offset/declination/calibrated readouts. Swipe
* adjusts the offset by 1°, double-tap returns to the compass.
*
* The landmark's heading must be in the frame the compass is showing: aiming
* at a true heading in true mode leaves the wearer-fit offset free of
* declination, which is what lets the calibration survive travel.
*/
import { GrayImage } from "../../graphics/image";
import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
@@ -10,18 +14,16 @@ import { type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext } from "../../ui/layers";
import { lineStep } from "../../ui/metrics";
import { screenCenterInViewportX } from "../../ui/shell/geometry";
import {
formatOffset,
getCompassOffset,
markCompassCalibrated,
normalizeHeading,
setCompassOffset,
} from "./calibration";
import { formatOffset, getCompassOffset, markCompassCalibrated, setCompassOffset } from "./calibration";
import { resolveHeading, type NorthReference } from "./heading";
const INSTRUCTIONS =
const INSTRUCTIONS_PREAMBLE =
"This compass uses the magnetometer in the right arm of the glasses; depending how it rests on your head, "
+ "it may be slightly off. To calibrate, look at a distant object or down a street where you know the true "
+ "compass heading, then adjust the calibration offset below";
+ "it may be slightly off. To calibrate, look at a distant object or down a street where you know the ";
const INSTRUCTIONS_BY_FRAME: Record<NorthReference, string> = {
true: "true compass heading (as shown on a map), then adjust the calibration offset below",
magnetic: "magnetic compass heading (as read by another compass), then adjust the calibration offset below",
};
/** Margins around the instruction paragraph. */
const TEXT_PADDING_X = 16;
@@ -40,7 +42,12 @@ export class CompassCalibrationLayer implements Layer {
const medium = getDefaultMediumFont();
const smallStep = lineStep(small);
const lines = wrapText(small, INSTRUCTIONS, width - TEXT_PADDING_X * 2);
const raw = this.getRawHeading();
const resolved = raw === null ? null : resolveHeading(raw);
// Before the first reading there is no frame to name yet; the true-mode
// wording is the default and the readout will correct it once data arrives.
const frame = resolved?.frame ?? "true";
const lines = wrapText(small, INSTRUCTIONS_PREAMBLE + INSTRUCTIONS_BY_FRAME[frame], width - TEXT_PADDING_X * 2);
for (let i = 0; i < lines.length; i++) {
image.drawText(small, TEXT_PADDING_X, TEXT_PADDING_TOP + i * smallStep, lines[i]!, 190);
}
@@ -49,13 +56,20 @@ export class CompassCalibrationLayer implements Layer {
// Readouts along the bottom: dim label over a bright value, in thirds.
const valueTop = height - medium.lineHeight;
const labelTop = valueTop - small.lineHeight;
const raw = this.getRawHeading();
const offset = getCompassOffset();
const columns: Array<[string, string]> = [
["Raw", raw === null ? "--°" : `${Math.round(raw)}°`],
["Offset", formatOffset(offset)],
["Calibrated", raw === null ? "--°" : `${Math.round(normalizeHeading(raw + offset))}°`],
["Offset", formatOffset(getCompassOffset())],
];
// Declination is only part of the sum in true mode, so only show it then;
// in magnetic mode it would be a number that changes nothing on screen.
if (frame === "true") {
const declination = resolved?.declinationDegrees ?? null;
columns.push(["Declination", declination === null ? "--°" : formatOffset(Math.round(declination))]);
}
columns.push([
frame === "true" ? "True" : "Magnetic",
resolved === null ? "--°" : `${Math.round(resolved.displayDegrees)}°`,
]);
const columnWidth = width / columns.length;
for (let i = 0; i < columns.length; i++) {
const [label, value] = columns[i]!;
+71 -4
View File
@@ -20,8 +20,11 @@ import {
type InProcessWindow,
} from "../../ui/shell/in-process-window";
import { shell } from "../../ui/shell/shell";
import { calibrateHeading, isCompassCalibrated, normalizeHeading } from "./calibration";
import { ensureLocationPermission, hasLocationPermission } from "../../g2/android-permissions";
import { isCompassCalibrated, normalizeHeading } from "./calibration";
import { CompassCalibrationLayer } from "./calibration-layer";
import { getDeclinationAvailability, onDeclinationChanged, refreshDeclination } from "./declination";
import { getNorthReference, resolveHeading, setNorthReference, type NorthReference } from "./heading";
export const COMPASS_WINDOW_ID = "compass";
export const COMPASS_SURFACE_ID = "window:compass";
@@ -98,13 +101,43 @@ class CompassLayer implements Layer {
private removed = false;
private timer: ReturnType<typeof setInterval> | null = null;
private unsubscribe: (() => void) | null = null;
private unsubscribeDeclination: (() => void) | null = null;
private requestingPermission = false;
constructor(private readonly requestRender: () => void) {}
start(): void {
this.unsubscribe = addCompassListener((event) => this.onCompassEvent(event));
this.unsubscribeDeclination = onDeclinationChanged(() => this.requestRender());
this.timer = setInterval(() => this.reconcile(), RECONCILE_INTERVAL_MS);
this.reconcile();
this.ensureDeclination();
}
/**
* True north needs the phone's location. Ask for it the way Weather does,
* on opening, but only while the wearer actually wants true north: a
* magnetic-mode compass has no business raising a permission prompt.
*/
private ensureDeclination(): void {
if (getNorthReference() !== "true") return;
if (hasLocationPermission()) {
refreshDeclination();
return;
}
if (this.requestingPermission) return;
this.requestingPermission = true;
void ensureLocationPermission().then((granted) => {
this.requestingPermission = false;
if (granted) refreshDeclination();
this.requestRender();
});
}
toggleNorthReference(): void {
setNorthReference(getNorthReference() === "true" ? "magnetic" : "true");
this.ensureDeclination();
this.requestRender();
}
stop(): void {
@@ -114,6 +147,8 @@ class CompassLayer implements Layer {
this.timer = null;
this.unsubscribe?.();
this.unsubscribe = null;
this.unsubscribeDeclination?.();
this.unsubscribeDeclination = null;
if (this.enabled) setCompassEnabled(false);
this.enabled = false;
}
@@ -134,6 +169,8 @@ class CompassLayer implements Layer {
this.enabled = visible;
setCompassEnabled(visible);
this.firmwareStatus = null;
// The stored fix may have aged out while the compass was hidden.
if (visible && hasLocationPermission()) refreshDeclination();
this.requestRender();
}
@@ -154,7 +191,8 @@ class CompassLayer implements Layer {
if (this.firmwareStatus !== null) return this.firmwareStatus;
if (!this.enabled) return "Compass paused";
if (this.rawHeading === null) return "Waiting for compass data…";
return isCompassCalibrated() ? "Magnetic heading" : "Uncalibrated - Tap to calibrate";
if (!isCompassCalibrated()) return "Uncalibrated - Tap to calibrate";
return frameStatusText();
}
paint(ctx: LayerContext): GrayImage {
@@ -162,7 +200,7 @@ class CompassLayer implements Layer {
const image = new GrayImage(width, height, 0);
const small = getDefaultSmallFont();
const large = getDefaultLargeFont();
const heading = this.rawHeading === null ? null : calibrateHeading(this.rawHeading);
const heading = this.rawHeading === null ? null : resolveHeading(this.rawHeading).displayDegrees;
const headingText = heading === null ? "--°" : `${Math.round(heading)}° ${cardinalDirection(heading)}`;
const statusLines = wrapText(small, this.statusText(), width - STACK_GAP * 2);
const smallStep = lineStep(small);
@@ -231,6 +269,14 @@ export function createCompassAppWindow(options: InProcessAppOptions): InProcessW
layer.openCalibration(ctx);
},
},
{
label: `North: ${northReferenceName(getNorthReference())}`,
description: "True north is what maps use. Magnetic north matches a handheld compass; it needs no location.",
onSelect: (ctx) => {
ctx.stack.pop();
layer.toggleNorthReference();
},
},
],
baseLayer: new YieldAtRootLayer(layer),
submitFrame: options.submitFrame,
@@ -246,6 +292,27 @@ export function createCompassAppWindow(options: InProcessAppOptions): InProcessW
return app;
}
export function northReferenceName(reference: NorthReference): string {
return reference === "true" ? "True" : "Magnetic";
}
/**
* Name the frame the readout is in. When the wearer wants true north but the
* phone can't supply declination, say that the reading is magnetic and why,
* rather than quietly showing a magnetic heading under a "true" label.
*/
function frameStatusText(): string {
if (getNorthReference() === "magnetic") return "Magnetic heading";
switch (getDeclinationAvailability()) {
case "available":
return "True heading";
case "no-permission":
return "Magnetic heading - location permission needed for true north";
case "no-fix":
return "Magnetic heading - waiting for location";
}
}
function cardinalDirection(heading: number): string {
const names = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
return names[Math.round(normalizeHeading(heading) / 45) % names.length]!;
@@ -272,7 +339,7 @@ function projectRose(cx: number, cy: number, scale: number, radius: number, angl
};
}
/** Draw the tilted rose, with its brightest point aimed at magnetic north. */
/** Draw the tilted rose, with its brightest point aimed at north. */
function drawCompassRose(image: GrayImage, cx: number, cy: number, radius: number, heading: number | null): void {
// Without a reading there is nothing to aim, so show the rose in its resting
// orientation, dimmed, rather than an empty ring.
+97
View File
@@ -0,0 +1,97 @@
/**
* Local magnetic declination for the compass, so the app can show true north.
*
* Declination only varies over tens of kilometres, so the location it needs is
* whatever the phone can cheaply produce: the same one-shot coarse lookup the
* Weather app uses, refreshed no more than daily. The last fix is persisted so
* a fresh start has a usable declination before location comes back, and the
* model is re-evaluated at the current time when it does.
*/
import { hasLocationPermission } from "../../g2/android-permissions";
import { magneticDeclinationDegrees } from "../../native/geomagnetic";
import { getCurrentLocation } from "../../native/location";
import { getStringSetting, setStringSetting } from "../../native/settings-store";
const LATITUDE_KEY = "compass.declination.latitude";
const LONGITUDE_KEY = "compass.declination.longitude";
const LOCATED_AT_KEY = "compass.declination.locatedAtMs";
/** A stored fix older than this is refreshed when the compass next runs. */
const FIX_MAX_AGE_MS = 24 * 60 * 60 * 1000;
/** Back-off between failed location attempts, so a denied or dark phone isn't polled. */
const RETRY_INTERVAL_MS = 10 * 60 * 1000;
export type DeclinationAvailability = "available" | "no-permission" | "no-fix";
type StoredFix = { latitude: number; longitude: number; locatedAtMs: number };
let declination: number | null = null;
let fix: StoredFix | null = null;
let loaded = false;
let refreshing = false;
let lastAttemptMs = 0;
const listeners = new Set<() => void>();
function loadStoredFix(): void {
if (loaded) return;
loaded = true;
const latitude = parseFloat(getStringSetting(LATITUDE_KEY, ""));
const longitude = parseFloat(getStringSetting(LONGITUDE_KEY, ""));
const locatedAtMs = parseInt(getStringSetting(LOCATED_AT_KEY, ""), 10);
if (Number.isFinite(latitude) && Number.isFinite(longitude) && Number.isFinite(locatedAtMs)) {
fix = { latitude, longitude, locatedAtMs };
declination = magneticDeclinationDegrees(latitude, longitude);
}
}
/** Declination in degrees (east positive), or null when no location is known. */
export function getDeclinationDegrees(): number | null {
loadStoredFix();
return declination;
}
/** Why declination is or isn't available, for the compass status line. */
export function getDeclinationAvailability(): DeclinationAvailability {
if (getDeclinationDegrees() !== null) return "available";
return hasLocationPermission() ? "no-fix" : "no-permission";
}
export function onDeclinationChanged(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
/**
* Fetch a location and recompute declination if the stored fix is stale or
* missing. Safe to call on every compass start; it is a no-op while a lookup
* is in flight, while the fix is fresh, or shortly after a failed attempt.
* Never prompts for permission: callers that want to ask do that themselves.
*/
export function refreshDeclination(): void {
loadStoredFix();
if (refreshing || !hasLocationPermission()) return;
const now = Date.now();
if (fix !== null && now - fix.locatedAtMs < FIX_MAX_AGE_MS) return;
if (now - lastAttemptMs < RETRY_INTERVAL_MS) return;
lastAttemptMs = now;
refreshing = true;
getCurrentLocation()
.then((location) => {
const value = magneticDeclinationDegrees(location.latitude, location.longitude);
if (value === null) return;
fix = { latitude: location.latitude, longitude: location.longitude, locatedAtMs: now };
declination = value;
setStringSetting(LATITUDE_KEY, String(location.latitude));
setStringSetting(LONGITUDE_KEY, String(location.longitude));
setStringSetting(LOCATED_AT_KEY, String(now));
for (const listener of listeners) listener();
})
.catch((error) => {
console.warn(`Compass declination location lookup failed: ${error}`);
})
.finally(() => {
refreshing = false;
});
}
+54
View File
@@ -0,0 +1,54 @@
/**
* The compass heading model: raw magnetometer reading → wearer-calibrated
* magnetic heading → true heading, and which of the last two the wearer has
* asked to see.
*
* The wearer-fit offset and declination are kept as separate terms on purpose.
* The offset changes when the glasses are re-seated but not when the wearer
* travels; declination is the reverse. One combined hand-tuned number would go
* quietly wrong after a long trip.
*/
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import { calibrateHeading, normalizeHeading } from "./calibration";
import { getDeclinationDegrees } from "./declination";
const NORTH_REFERENCE_KEY = "compass.northReference";
/** Which north the compass reads relative to. True is the default: it is what maps use. */
export type NorthReference = "true" | "magnetic";
export type ResolvedHeading = {
/** Raw reading corrected by the wearer-fit offset. */
magneticDegrees: number;
/** Local declination (east positive), or null when no location is known. */
declinationDegrees: number | null;
/** Magnetic heading plus declination, or null when declination is unknown. */
trueDegrees: number | null;
/** The heading to show, in whichever frame `frame` names. */
displayDegrees: number;
/** The frame actually shown: true if requested and available, else magnetic. */
frame: NorthReference;
};
export function getNorthReference(): NorthReference {
return getStringSetting(NORTH_REFERENCE_KEY, "true") === "magnetic" ? "magnetic" : "true";
}
export function setNorthReference(reference: NorthReference): void {
setStringSetting(NORTH_REFERENCE_KEY, reference);
}
export function resolveHeading(rawDegrees: number): ResolvedHeading {
const magneticDegrees = calibrateHeading(rawDegrees);
const declinationDegrees = getDeclinationDegrees();
const trueDegrees = declinationDegrees === null ? null : normalizeHeading(magneticDegrees + declinationDegrees);
const wantTrue = getNorthReference() === "true";
const frame: NorthReference = wantTrue && trueDegrees !== null ? "true" : "magnetic";
return {
magneticDegrees,
declinationDegrees,
trueDegrees,
displayDegrees: frame === "true" ? trueDegrees! : magneticDegrees,
frame,
};
}
+36 -5
View File
@@ -3,18 +3,46 @@
* running EvenHub apps, mirroring the IMU router. Only the foreground app
* receives headings, so a backgrounded app can't keep the sensor running.
*
* The compass is NOT pre-calibrated — the magnetometer is in the right arm,
* which rests on the head with a wearer-dependent curl (see compass-app memory);
* headings are relative, not true north.
* The raw reading is NOT pre-calibrated — the magnetometer is in the right
* arm, which rests on the head with a wearer-dependent curl (see compass-app
* memory). Each delivery also carries the Compass app's wearer-calibrated
* magnetic heading and, when the phone has a location, declination and the
* true heading, so apps needn't redo that work.
*/
import { addCompassListener, setCompassEnabled, COMPASS_CHANGED, type CompassEvent } from "../../native/compass";
import { isCompassCalibrated } from "../compass/calibration";
import { refreshDeclination } from "../compass/declination";
import { resolveHeading } from "../compass/heading";
/** Wire shape of the `compass` extension event (faceclaw-extensions `CompassReading`). */
export type EvenHubCompassReading = {
headingDegrees: number;
magneticHeadingDegrees: number;
wearerCalibrated: boolean;
declinationDegrees?: number;
trueHeadingDegrees?: number;
};
export type EvenHubCompassClient = {
readonly windowId: string;
isForeground(): boolean;
deliverCompass(headingDegrees: number): void;
deliverCompass(reading: EvenHubCompassReading): void;
};
export function buildCompassReading(rawDegrees: number): EvenHubCompassReading {
const resolved = resolveHeading(rawDegrees);
const reading: EvenHubCompassReading = {
headingDegrees: rawDegrees,
magneticHeadingDegrees: resolved.magneticDegrees,
wearerCalibrated: isCompassCalibrated(),
};
if (resolved.declinationDegrees !== null && resolved.trueDegrees !== null) {
reading.declinationDegrees = resolved.declinationDegrees;
reading.trueHeadingDegrees = resolved.trueDegrees;
}
return reading;
}
class EvenHubCompassRouter {
private readonly requesting = new Set<EvenHubCompassClient>();
private active: EvenHubCompassClient | null = null;
@@ -47,13 +75,16 @@ class EvenHubCompassRouter {
this.unsubscribe = addCompassListener((event: CompassEvent) => {
// Only heading updates carry a real heading; calibration events use -1.
if (event.command === COMPASS_CHANGED && event.headingDegrees >= 0) {
this.active?.deliverCompass(event.headingDegrees);
this.active?.deliverCompass(buildCompassReading(event.headingDegrees));
}
});
}
if (!this.enabled) {
setCompassEnabled(true);
this.enabled = true;
// Uses location only if the wearer already granted it; an app turning
// on the compass is not a reason to raise a system permission prompt.
refreshDeclination();
}
} else {
if (this.enabled) {
+3 -3
View File
@@ -56,7 +56,7 @@ import { type EvenHubManifest } from "./ehpk";
import { permissionsIncludeMicrophone, permissionsInclude } from "./permissions";
import { evenHubMicRouter, type EvenHubMicClient } from "./mic-router";
import { evenHubImuRouter, type EvenHubImuClient } from "./imu-router";
import { evenHubCompassRouter, type EvenHubCompassClient } from "./compass-router";
import { evenHubCompassRouter, type EvenHubCompassClient, type EvenHubCompassReading } from "./compass-router";
import { type ImuReading } from "../../native/imu";
import { toolRegistry, type ToolResult, type ToolSpec } from "../../assistant/tool-registry";
import { getCurrentLocation } from "../../native/location";
@@ -1010,8 +1010,8 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
// ----- compass (EvenHubCompassClient) -----
deliverCompass(headingDegrees: number): void {
this.pushExtEvent("compass", { headingDegrees });
deliverCompass(reading: EvenHubCompassReading): void {
this.pushExtEvent("compass", reading);
}
private setCompass(enable: boolean): void {