@ateam-ai-mobile/expo 0.1.5 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/android/build.gradle +16 -0
  2. package/android/src/main/java/expo/modules/adavision/AdaVisionModule.kt +75 -0
  3. package/dist/attachmentCache-DhQTqi2E.d.mts +18 -0
  4. package/dist/attachmentCache-DhQTqi2E.d.ts +18 -0
  5. package/dist/bootstrap.d.mts +95 -0
  6. package/dist/bootstrap.d.ts +95 -0
  7. package/dist/bootstrap.js +2991 -0
  8. package/dist/bootstrap.js.map +1 -0
  9. package/dist/bootstrap.mjs +66 -0
  10. package/dist/bootstrap.mjs.map +1 -0
  11. package/dist/chunk-4BMWVN25.mjs +91 -0
  12. package/dist/chunk-4BMWVN25.mjs.map +1 -0
  13. package/dist/chunk-6LXF3JVX.mjs +96 -0
  14. package/dist/chunk-6LXF3JVX.mjs.map +1 -0
  15. package/dist/chunk-7FWYEHN5.mjs +203 -0
  16. package/dist/chunk-7FWYEHN5.mjs.map +1 -0
  17. package/dist/chunk-C7M5WAHA.mjs +1798 -0
  18. package/dist/chunk-C7M5WAHA.mjs.map +1 -0
  19. package/dist/chunk-FF6ZZZXH.mjs +71 -0
  20. package/dist/chunk-FF6ZZZXH.mjs.map +1 -0
  21. package/dist/chunk-GF2MPTAB.mjs +647 -0
  22. package/dist/chunk-GF2MPTAB.mjs.map +1 -0
  23. package/dist/chunk-J6XRNX7P.mjs +19 -0
  24. package/dist/chunk-J6XRNX7P.mjs.map +1 -0
  25. package/dist/chunk-KOXF2FZM.mjs +92 -0
  26. package/dist/chunk-KOXF2FZM.mjs.map +1 -0
  27. package/dist/chunk-L4V7OCJ3.mjs +71 -0
  28. package/dist/chunk-L4V7OCJ3.mjs.map +1 -0
  29. package/dist/chunk-PCAEUX2N.mjs +67 -0
  30. package/dist/chunk-PCAEUX2N.mjs.map +1 -0
  31. package/dist/chunk-WMJKH4XE.mjs +34 -0
  32. package/dist/chunk-WMJKH4XE.mjs.map +1 -0
  33. package/dist/chunk-XQSY6MHP.mjs +213 -0
  34. package/dist/chunk-XQSY6MHP.mjs.map +1 -0
  35. package/dist/chunk-Z5AI2SXX.mjs +1810 -0
  36. package/dist/chunk-Z5AI2SXX.mjs.map +1 -0
  37. package/dist/createBridge.js +41 -10
  38. package/dist/createBridge.js.map +1 -1
  39. package/dist/createBridge.mjs +7 -1
  40. package/dist/createBridge.mjs.map +1 -1
  41. package/dist/device/createDeviceProvider.d.mts +23 -0
  42. package/dist/device/createDeviceProvider.d.ts +23 -0
  43. package/dist/device/createDeviceProvider.js +1228 -0
  44. package/dist/device/createDeviceProvider.js.map +1 -0
  45. package/dist/device/createDeviceProvider.mjs +19 -0
  46. package/dist/device/createDeviceProvider.mjs.map +1 -0
  47. package/dist/device-bridge/collectors/appEngagement.d.mts +10 -0
  48. package/dist/device-bridge/collectors/appEngagement.d.ts +10 -0
  49. package/dist/device-bridge/collectors/appEngagement.js +128 -0
  50. package/dist/device-bridge/collectors/appEngagement.js.map +1 -0
  51. package/dist/device-bridge/collectors/appEngagement.mjs +12 -0
  52. package/dist/device-bridge/collectors/appEngagement.mjs.map +1 -0
  53. package/dist/device-bridge/collectors/health.d.mts +24 -0
  54. package/dist/device-bridge/collectors/health.d.ts +24 -0
  55. package/dist/device-bridge/collectors/health.js +238 -0
  56. package/dist/device-bridge/collectors/health.js.map +1 -0
  57. package/dist/device-bridge/collectors/health.mjs +18 -0
  58. package/dist/device-bridge/collectors/health.mjs.map +1 -0
  59. package/dist/device-bridge/cookies.d.mts +49 -0
  60. package/dist/device-bridge/cookies.d.ts +49 -0
  61. package/dist/device-bridge/cookies.js +90 -0
  62. package/dist/device-bridge/cookies.js.map +1 -0
  63. package/dist/device-bridge/cookies.mjs +14 -0
  64. package/dist/device-bridge/cookies.mjs.map +1 -0
  65. package/dist/device-bridge/index.d.mts +495 -0
  66. package/dist/device-bridge/index.d.ts +495 -0
  67. package/dist/device-bridge/index.js +2121 -0
  68. package/dist/device-bridge/index.js.map +1 -0
  69. package/dist/device-bridge/index.mjs +34 -0
  70. package/dist/device-bridge/index.mjs.map +1 -0
  71. package/dist/device-bridge/nfc.d.mts +30 -0
  72. package/dist/device-bridge/nfc.d.ts +30 -0
  73. package/dist/device-bridge/nfc.js +109 -0
  74. package/dist/device-bridge/nfc.js.map +1 -0
  75. package/dist/device-bridge/nfc.mjs +14 -0
  76. package/dist/device-bridge/nfc.mjs.map +1 -0
  77. package/dist/index.d.mts +509 -18
  78. package/dist/index.d.ts +509 -18
  79. package/dist/index.js +1706 -6
  80. package/dist/index.js.map +1 -1
  81. package/dist/index.mjs +24 -194
  82. package/dist/index.mjs.map +1 -1
  83. package/dist/maps/index.d.mts +56 -0
  84. package/dist/maps/index.d.ts +56 -0
  85. package/dist/maps/index.js +95 -0
  86. package/dist/maps/index.js.map +1 -0
  87. package/dist/maps/index.mjs +17 -0
  88. package/dist/maps/index.mjs.map +1 -0
  89. package/dist/oauth/expoOAuth.d.mts +18 -0
  90. package/dist/oauth/expoOAuth.d.ts +18 -0
  91. package/dist/oauth/expoOAuth.js +102 -0
  92. package/dist/oauth/expoOAuth.js.map +1 -0
  93. package/dist/oauth/expoOAuth.mjs +8 -0
  94. package/dist/oauth/expoOAuth.mjs.map +1 -0
  95. package/dist/types-BRanJYTn.d.mts +138 -0
  96. package/dist/types-BRanJYTn.d.ts +138 -0
  97. package/dist/vision/index.d.mts +83 -0
  98. package/dist/vision/index.d.ts +83 -0
  99. package/dist/vision/index.js +101 -0
  100. package/dist/vision/index.js.map +1 -0
  101. package/dist/vision/index.mjs +28 -0
  102. package/dist/vision/index.mjs.map +1 -0
  103. package/expo-module.config.json +9 -0
  104. package/ios/AdaMaps/AdaMapsModule.swift +180 -0
  105. package/ios/AdaMaps.podspec +25 -0
  106. package/ios/AdaVision.podspec +32 -0
  107. package/ios/AdaVisionModule.swift +486 -0
  108. package/ios/Resources/yolov8n-oiv7.mlmodelc/analytics/coremldata.bin +0 -0
  109. package/ios/Resources/yolov8n-oiv7.mlmodelc/coremldata.bin +0 -0
  110. package/ios/Resources/yolov8n-oiv7.mlmodelc/metadata.json +773 -0
  111. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/analytics/coremldata.bin +0 -0
  112. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/coremldata.bin +0 -0
  113. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/model.mil +720 -0
  114. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/weights/weight.bin +0 -0
  115. package/ios/Resources/yolov8n-oiv7.mlmodelc/model1/coremldata.bin +0 -0
  116. package/package.json +113 -7
  117. package/src/args.ts +56 -0
  118. package/src/bootstrap.ts +159 -0
  119. package/src/camera/CameraTaskHost.tsx +175 -0
  120. package/src/camera/cameraTasks.ts +129 -0
  121. package/src/createBridge.ts +3 -1
  122. package/src/device/createDeviceProvider.ts +917 -0
  123. package/src/device-bridge/actions/calendar-actions.ts +217 -0
  124. package/src/device-bridge/actions/dnd.ts +74 -0
  125. package/src/device-bridge/actions/health-actions.ts +58 -0
  126. package/src/device-bridge/actions/index.ts +12 -0
  127. package/src/device-bridge/actions/messaging.ts +74 -0
  128. package/src/device-bridge/actions/navigation.ts +88 -0
  129. package/src/device-bridge/actions/queue-poller.ts +151 -0
  130. package/src/device-bridge/background.ts +137 -0
  131. package/src/device-bridge/biometrics.ts +64 -0
  132. package/src/device-bridge/capabilities.ts +218 -0
  133. package/src/device-bridge/collectors/appEngagement.ts +120 -0
  134. package/src/device-bridge/collectors/battery.ts +83 -0
  135. package/src/device-bridge/collectors/calendar.ts +162 -0
  136. package/src/device-bridge/collectors/camera.ts +27 -0
  137. package/src/device-bridge/collectors/connectivity.ts +60 -0
  138. package/src/device-bridge/collectors/contacts.ts +200 -0
  139. package/src/device-bridge/collectors/health.ts +299 -0
  140. package/src/device-bridge/collectors/index.ts +12 -0
  141. package/src/device-bridge/collectors/location.ts +236 -0
  142. package/src/device-bridge/collectors/mood.ts +141 -0
  143. package/src/device-bridge/collectors/notifications.ts +70 -0
  144. package/src/device-bridge/cookies.ts +89 -0
  145. package/src/device-bridge/dynamic-connector.ts +422 -0
  146. package/src/device-bridge/index.ts +467 -0
  147. package/src/device-bridge/nfc.ts +85 -0
  148. package/src/device-bridge/plugin.ts +71 -0
  149. package/src/device-bridge/relay-client.ts +237 -0
  150. package/src/device-bridge/scanner.ts +42 -0
  151. package/src/device-bridge/sharing.ts +35 -0
  152. package/src/device-bridge/types.ts +326 -0
  153. package/src/device-state/activityClassifier.ts +151 -0
  154. package/src/device-state/activityEngine.ts +252 -0
  155. package/src/device-state/collectors.ts +35 -0
  156. package/src/device-state/domains/activity.ts +93 -0
  157. package/src/device-state/domains/capability.ts +60 -0
  158. package/src/device-state/domains/connectivity.ts +60 -0
  159. package/src/device-state/domains/deviceContext.ts +57 -0
  160. package/src/device-state/domains/interaction.ts +60 -0
  161. package/src/device-state/domains/spatial.ts +367 -0
  162. package/src/device-state/domains/visual.ts +121 -0
  163. package/src/device-state/events.ts +49 -0
  164. package/src/device-state/headingSource.ts +119 -0
  165. package/src/device-state/index.ts +78 -0
  166. package/src/device-state/quality.ts +60 -0
  167. package/src/device-state/replay.ts +285 -0
  168. package/src/device-state/spatialEvents.ts +300 -0
  169. package/src/device-state/turnDetector.ts +121 -0
  170. package/src/device-state/visualEngine.ts +341 -0
  171. package/src/geo.ts +23 -0
  172. package/src/haptics.ts +4 -0
  173. package/src/index.ts +37 -0
  174. package/src/maps/index.ts +81 -0
  175. package/src/maps/normalize.ts +225 -0
  176. package/src/oauth/expoOAuth.tsx +113 -0
  177. package/src/vision/analysis.js +80 -0
  178. package/src/vision/index.ts +146 -0
  179. package/src/vision/ring.js +35 -0
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Spatial events, derived from spatial snapshots.
3
+ *
4
+ * ONE MODEL, NOT TWO. An event is what changed between two snapshots — the
5
+ * same snapshots `getSnapshot()` returns — so an event can never say "moving"
6
+ * while a read says "stationary", and no threshold here has a second copy
7
+ * somewhere else. The thresholds a read uses (the stationary speed, the GPS
8
+ * confidence bands, distance along a path) live in this file and the domain
9
+ * imports them, rather than the other way round, so the detector can be tested
10
+ * without an Expo import: the live engine feeds it on every fix, every turn and
11
+ * a one-second tick; replay feeds it recorded samples on a virtual clock.
12
+ *
13
+ * THE HARD PART IS NOT DETECTING CHANGES, IT IS NOT INVENTING THEM (the turn
14
+ * detector's lesson, again). GPS speed wobbles around any threshold, and a fix
15
+ * band flickers when accuracy sits near a boundary. So every state change must
16
+ * HOLD before it is reported, and position changes must beat the fix's own
17
+ * error bar. Holds delay an event on purpose; `since` in the payload carries
18
+ * the real onset.
19
+ *
20
+ * A HOLD IS HELD BY FIXES, NOT BY THE CLOCK ALONE. The one-second tick re-reads
21
+ * the SAME fix, so a hold measured only in time would let one outlier fix
22
+ * followed by a gap — sparse fixes at Balanced accuracy, a wifi jump read as
23
+ * speed — become "you started moving". A state settles only once two distinct
24
+ * fixes have shown it; after that the tick may complete the hold, which is what
25
+ * it is for ("stationary for five seconds" completes while nothing arrives).
26
+ *
27
+ * Type-only imports from plugin-runtime, so `node --test` can load this file.
28
+ */
29
+ import type {
30
+ Confidence,
31
+ SpatialEvent,
32
+ SpatialIntent,
33
+ SpatialPoint,
34
+ SpatialSnapshot,
35
+ SpatialStateEvent,
36
+ } from '@ateam-ai-mobile/plugin-runtime';
37
+ import { stateEvent } from './events';
38
+ import { distanceOf } from '../geo';
39
+
40
+ /**
41
+ * Below this the user is standing still.
42
+ *
43
+ * 0.4 m/s is well under a slow walk (~1.2 m/s) and above the jitter a
44
+ * stationary phone's GPS produces. The point of the band is that a guide
45
+ * must not say "keep going straight" to someone who has stopped.
46
+ */
47
+ export const STATIONARY_MPS = 0.4;
48
+
49
+ /**
50
+ * Only claim stationary/moving when a speed was actually obtained. With no
51
+ * speed the truthful answer is `unknown`, not `stationary` — "you have
52
+ * stopped" is a false statement, not a neutral default.
53
+ */
54
+ export function movementStateOf(speedMps: number | null): 'stationary' | 'moving' | 'unknown' {
55
+ return speedMps === null ? 'unknown' : speedMps < STATIONARY_MPS ? 'stationary' : 'moving';
56
+ }
57
+
58
+ /**
59
+ * The GPS fix's confidence band, from metres of horizontal error. ~10m is a
60
+ * good open-sky fix; beyond ~50m the position is street-level at best and
61
+ * useless for "turn at the next corner".
62
+ */
63
+ export function fixConfidence(accuracyM: number | null): Confidence['level'] {
64
+ return accuracyM === null ? 'unknown' : accuracyM <= 10 ? 'high' : accuracyM <= 50 ? 'medium' : 'low';
65
+ }
66
+
67
+
68
+ export interface SpatialEventProfile {
69
+ /** How long `moving` must hold before `movementStarted`. */
70
+ movingHoldMs: number;
71
+ /** How long `stationary` must hold, after moving, before `movementStopped`. */
72
+ stoppedHoldMs: number;
73
+ /** How long a new GPS confidence band must hold before it is reported. */
74
+ confidenceHoldMs: number;
75
+ /** Floor for `positionChanged`, metres. The real threshold is
76
+ * max(this, moveThresholdM(anchor, fix)) — both fixes' uncertainty — so a
77
+ * loose fix on EITHER end needs a bigger move. */
78
+ minMoveM: number;
79
+ }
80
+
81
+ /**
82
+ * Intent → how eager the events are.
83
+ *
84
+ * These are the engine's judgement, not the freeze's — the architecture doc
85
+ * says only "thresholds are profile-dependent". Recorded here so the reasoning
86
+ * is visible and arguable rather than buried. The intent changes ONLY these
87
+ * holds, not sampling: there is no native strategy layer for it to reach.
88
+ *
89
+ * - `navigation`: a guide needs "you've stopped" soon enough to act on, but a
90
+ * pause at a crossing is not a stop worth announcing — 3 s to start, 5 s to
91
+ * stop. 10 m is about one building frontage.
92
+ * - `fitness`: same movement holds; a slower confidence hold, because a runner
93
+ * under trees dips in and out of a band constantly and nobody needs to hear it.
94
+ * - `preciseLocate`: the caller is deliberately pinning a position, so the
95
+ * holds are shortest and a few metres counts.
96
+ * - `geofence` / `lowPowerTracking`: coarse by nature — tens of metres, and a
97
+ * state must hold for a while before it is worth waking anyone for.
98
+ */
99
+ export const SPATIAL_EVENT_PROFILES: Record<SpatialIntent, SpatialEventProfile> = {
100
+ navigation: { movingHoldMs: 3000, stoppedHoldMs: 5000, confidenceHoldMs: 3000, minMoveM: 10 },
101
+ fitness: { movingHoldMs: 3000, stoppedHoldMs: 5000, confidenceHoldMs: 5000, minMoveM: 10 },
102
+ preciseLocate: { movingHoldMs: 2000, stoppedHoldMs: 3000, confidenceHoldMs: 2000, minMoveM: 3 },
103
+ geofence: { movingHoldMs: 10000, stoppedHoldMs: 30000, confidenceHoldMs: 10000, minMoveM: 25 },
104
+ lowPowerTracking: { movingHoldMs: 10000, stoppedHoldMs: 30000, confidenceHoldMs: 10000, minMoveM: 50 },
105
+ };
106
+
107
+ /** The profile for an intent; an unrecognised one gets `navigation`'s. */
108
+ /**
109
+ * The move two fixes can vouch for. A fix is a circle, not a point, and so is
110
+ * the anchor it is compared with: two fixes of a phone lying still differ by up
111
+ * to BOTH their errors. Combined (root-sum-square, each accuracyM ~ one radius)
112
+ * and doubled, like a single fix's 2× before. No estimate = 0 (the floor rules).
113
+ * Anchor ±100 m → fix ±5 m: a 20 m difference is noise, not a walk.
114
+ */
115
+ export function moveThresholdM(anchor: { accuracyM?: number | null }, fix: { accuracyM?: number | null }): number {
116
+ const a = anchor.accuracyM ?? 0, b = fix.accuracyM ?? 0;
117
+ return 2 * Math.sqrt(a * a + b * b);
118
+ }
119
+
120
+ export function spatialEventProfile(intent: string | null | undefined): SpatialEventProfile {
121
+ return SPATIAL_EVENT_PROFILES[intent as SpatialIntent] ?? SPATIAL_EVENT_PROFILES.navigation;
122
+ }
123
+
124
+ type Band = 'high' | 'medium' | 'low';
125
+ const RANK: Record<Band, number> = { high: 3, medium: 2, low: 1 };
126
+ type PayloadOf<N extends SpatialEvent> = Extract<SpatialStateEvent, { name: N }>['payload'];
127
+
128
+ /** Distinct fixes a state must be seen on before its hold can complete. */
129
+ const MIN_FIXES = 2;
130
+
131
+ /**
132
+ * An unbroken run of one raw state: when it began, and how many distinct fixes
133
+ * (by `position.timestamp`) have shown it. A re-read of the same fix extends
134
+ * the run's time, never its evidence.
135
+ */
136
+ interface Run<S> { state: S; since: number; fixAt: number | null; fixes: number }
137
+
138
+ function extend<S>(run: Run<S> | null, state: S, fixAt: number | null, now: number): Run<S> {
139
+ if (!run || run.state !== state) return { state, since: now, fixAt, fixes: fixAt === null ? 0 : 1 };
140
+ if (fixAt !== null && fixAt !== run.fixAt) { run.fixAt = fixAt; run.fixes++; }
141
+ return run;
142
+ }
143
+
144
+ const settled = (run: Run<unknown>, now: number, holdMs: number): boolean =>
145
+ run.fixes >= MIN_FIXES && now - run.since >= holdMs;
146
+
147
+ /** Which fix a snapshot was built from — its identity when counting evidence. */
148
+ const fixAt = (s: SpatialSnapshot): number | null => s.position?.timestamp ?? null;
149
+
150
+ export class SpatialEventDetector {
151
+ private profile: SpatialEventProfile;
152
+
153
+ /** The movement state last settled on. Only MEASURED states settle. */
154
+ private movement: 'stationary' | 'moving' | 'unknown' = 'unknown';
155
+ private run: Run<'stationary' | 'moving' | 'unknown'> | null = null;
156
+
157
+ /** The completed turn already on record — reported turns, and the one the
158
+ * session opened onto. Only a turn with a new timestamp is news. */
159
+ private lastTurnAt: number | null = null;
160
+
161
+ /** The GPS band last settled on; null until the session's first band. */
162
+ private band: Band | null = null;
163
+ private bandRun: Run<Band> | null = null;
164
+
165
+ /** The last position REPORTED — distance is measured from here, not from
166
+ * the previous fix, so a slow walk still adds up to a change. */
167
+ private anchor: SpatialPoint | null = null;
168
+
169
+ private staleArmed = true;
170
+
171
+ constructor(profile: SpatialEventProfile = SPATIAL_EVENT_PROFILES.navigation) {
172
+ this.profile = profile;
173
+ }
174
+
175
+ /**
176
+ * Forget everything — a new session, or replay seeking backwards. Emits
177
+ * nothing. `turnOnRecordAt` is the timestamp of the turn already completed
178
+ * when the session opens (a visual session shares the compass): history, not
179
+ * news. Seeded from the turn itself rather than compared against a clock, so
180
+ * it holds whichever clock the turn was stamped with — epoch live, the
181
+ * recording's epoch in replay, where `now` is virtual.
182
+ */
183
+ reset(profile?: SpatialEventProfile, turnOnRecordAt: number | null = null): void {
184
+ if (profile) this.profile = profile;
185
+ this.movement = 'unknown';
186
+ this.run = null;
187
+ this.lastTurnAt = turnOnRecordAt;
188
+ this.band = null;
189
+ this.bandRun = null;
190
+ this.anchor = null;
191
+ this.staleArmed = true;
192
+ }
193
+
194
+ /**
195
+ * Feed the newest snapshot. Returns what changed since the last one, in this
196
+ * order: movement, turn, position, confidence, staleness. Fields are read
197
+ * defensively — replay hands over recorded snapshots verbatim, and a recording
198
+ * may lack a block the live engine always fills.
199
+ */
200
+ push(snapshot: SpatialSnapshot, now: number): SpatialStateEvent[] {
201
+ const out: SpatialStateEvent[] = [];
202
+ const emit: Emit = (name, payload) => {
203
+ // The payload is checked against its name by `Emit`; the union cannot
204
+ // follow a generic name through stateEvent's return, hence the assertion.
205
+ out.push(stateEvent('spatial', name, payload as unknown, now) as SpatialStateEvent);
206
+ };
207
+ this.movementFrom(snapshot, now, emit);
208
+ this.turnFrom(snapshot, emit);
209
+ this.positionFrom(snapshot, emit);
210
+ this.confidenceFrom(snapshot, now, emit);
211
+ this.staleFrom(snapshot, emit);
212
+ return out;
213
+ }
214
+
215
+ private movementFrom(s: SpatialSnapshot, now: number, emit: Emit): void {
216
+ const state = s.movement?.state ?? 'unknown';
217
+ this.run = extend(this.run, state, fixAt(s), now);
218
+ if (state === this.movement) return;
219
+
220
+ if (state === 'moving' && settled(this.run, now, this.profile.movingHoldMs)) {
221
+ emit('movementStarted', {
222
+ previous: this.movement === 'stationary' ? 'stationary' : 'unknown',
223
+ speedMps: s.movement?.speedMps ?? null,
224
+ bearingDeg: s.movement?.bearingDeg ?? null,
225
+ since: this.run.since,
226
+ });
227
+ this.movement = 'moving';
228
+ } else if (state === 'stationary' && settled(this.run, now, this.profile.stoppedHoldMs)) {
229
+ if (this.movement === 'moving') emit('movementStopped', { previous: 'moving', since: this.run.since });
230
+ this.movement = 'stationary';
231
+ }
232
+ // `unknown` never settles. Losing the speed is not evidence of stopping, so
233
+ // moving → unknown says nothing, and a later measured `stationary` is still
234
+ // reported as the stop it is.
235
+ }
236
+
237
+ private turnFrom(s: SpatialSnapshot, emit: Emit): void {
238
+ const at = s.changes?.timestamp ?? null;
239
+ const deg = s.changes?.lastMeaningfulTurnDeg ?? null;
240
+ // A compass reset clears the turn to null. That is not a new turn.
241
+ if (at === null || deg === null || at === this.lastTurnAt) return;
242
+ this.lastTurnAt = at;
243
+ emit('lastMeaningfulTurnChanged', { lastMeaningfulTurnDeg: deg, timestamp: at });
244
+ }
245
+
246
+ private positionFrom(s: SpatialSnapshot, emit: Emit): void {
247
+ const p = s.position ?? null;
248
+ if (!p) return;
249
+ if (!this.anchor) {
250
+ emit('positionChanged', { position: { ...p }, previous: null, distanceM: null });
251
+ this.anchor = p;
252
+ return;
253
+ }
254
+ const d = distanceOf([this.anchor, p]);
255
+ if (d < Math.max(this.profile.minMoveM, moveThresholdM(this.anchor, p))) {
256
+ // Not a move — but if this fix is far more precise than the anchor, keep
257
+ // IT as the reference (silently): measuring later moves from a ±100 m
258
+ // anchor would hide real ones behind the old fix's error.
259
+ const aNew = p.accuracyM ?? null, aOld = this.anchor.accuracyM ?? null;
260
+ if (aNew != null && aOld != null && aNew * 2 < aOld) this.anchor = p;
261
+ return;
262
+ }
263
+ emit('positionChanged', { position: { ...p }, previous: { ...this.anchor }, distanceM: d });
264
+ this.anchor = p;
265
+ }
266
+
267
+ private confidenceFrom(s: SpatialSnapshot, now: number, emit: Emit): void {
268
+ const p = s.position ?? null;
269
+ if (!p) return;
270
+ const level = fixConfidence(p.accuracyM ?? null);
271
+ // A fix with no accuracy estimate says nothing about the band — the same
272
+ // way the snapshot's confidence ignores an `unknown` part.
273
+ if (level === 'unknown') return;
274
+ // The first band is where the session starts, not a change.
275
+ if (this.band === null) { this.band = level; return; }
276
+ if (level === this.band) { this.bandRun = null; return; }
277
+ this.bandRun = extend(this.bandRun, level, fixAt(s), now);
278
+ if (!settled(this.bandRun, now, this.profile.confidenceHoldMs)) return;
279
+ emit('positionConfidenceChanged', {
280
+ level,
281
+ previous: this.band,
282
+ accuracyM: p.accuracyM ?? null,
283
+ direction: RANK[level] < RANK[this.band] ? 'dropped' : 'recovered',
284
+ });
285
+ this.band = level;
286
+ this.bandRun = null;
287
+ }
288
+
289
+ private staleFrom(s: SpatialSnapshot, emit: Emit): void {
290
+ const f = s.quality?.freshness;
291
+ if (!f) return;
292
+ // Re-armed only by a FRESH read: `aging` on the way back is not recovery.
293
+ if (f.state === 'fresh') { this.staleArmed = true; return; }
294
+ if (f.state !== 'stale' || !this.staleArmed) return;
295
+ emit('spatialStateStale', { observedAt: f.observedAt, ageMs: f.ageMs });
296
+ this.staleArmed = false;
297
+ }
298
+ }
299
+
300
+ type Emit = <N extends SpatialEvent>(name: N, payload: PayloadOf<N>) => void;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Turning, and which way.
3
+ *
4
+ * "Turn right at the corner" and "you have just turned left" are the two
5
+ * sentences a walking guide says most, and neither can be read off a single
6
+ * heading — they need heading OVER TIME. This is that, as a pure state machine
7
+ * with no Expo import, so it can be tested against a scripted walk instead of
8
+ * against a phone in someone's hand.
9
+ *
10
+ * SIGN IS THE WHOLE POINT. Compass degrees increase clockwise, so a positive
11
+ * delta is a turn to the RIGHT and a negative one to the LEFT. A caller that
12
+ * wants only the magnitude can take the absolute value; a caller handed a
13
+ * magnitude cannot recover the side, and "turn 90°" without the side is worse
14
+ * than saying nothing.
15
+ *
16
+ * THE HARD PART IS NOT DETECTING TURNS, IT IS NOT INVENTING THEM. A phone held
17
+ * by a walking person swings 15–20° with every stride, and a compass drifts.
18
+ * Compare against a fixed origin and the drift eventually crosses any threshold
19
+ * on its own, so the machine re-baselines whenever the heading holds steady:
20
+ * "straight ahead" is wherever you have been pointing for the last couple of
21
+ * seconds, not wherever you were pointing when the session opened.
22
+ */
23
+
24
+ /** A completed turn. `deg` is signed: **positive = clockwise = right**. */
25
+ export interface TurnEvent {
26
+ deg: number;
27
+ /** When the turn was recognised as complete. */
28
+ timestamp: number;
29
+ }
30
+
31
+ export interface TurnDetectorOptions {
32
+ /**
33
+ * How far the heading must swing before it counts as a turn.
34
+ *
35
+ * 35° is a judgement, not a measurement: a street corner is ~90°, a gentle
36
+ * bend in a corridor 30–45°, and hand-sway while walking routinely 15–20°.
37
+ * Lower and the detector narrates the user's arm.
38
+ */
39
+ minTurnDeg?: number;
40
+ /** Within this of the reference counts as "still pointing the same way". */
41
+ stableDeg?: number;
42
+ /** How long it must stay there before the reference moves. */
43
+ stableMs?: number;
44
+ }
45
+
46
+ /** Signed shortest arc from `a` to `b`, in (-180, 180]. */
47
+ export function signedDelta(a: number, b: number): number {
48
+ return ((b - a + 540) % 360) - 180;
49
+ }
50
+
51
+ export class TurnDetector {
52
+ private readonly minTurnDeg: number;
53
+ private readonly stableDeg: number;
54
+ private readonly stableMs: number;
55
+
56
+ /** The heading currently treated as "straight ahead". */
57
+ private refDeg: number | null = null;
58
+ private stableSince = 0;
59
+ private lastTurn: TurnEvent | null = null;
60
+
61
+ constructor(opts: TurnDetectorOptions = {}) {
62
+ this.minTurnDeg = opts.minTurnDeg ?? 35;
63
+ this.stableDeg = opts.stableDeg ?? 12;
64
+ this.stableMs = opts.stableMs ?? 2500;
65
+ }
66
+
67
+ /** Feed one compass reading. `null` degrees means the compass said nothing. */
68
+ push(deg: number | null, now: number): TurnEvent | null {
69
+ if (deg === null) return null;
70
+
71
+ if (this.refDeg === null) {
72
+ this.refDeg = deg;
73
+ this.stableSince = now;
74
+ return null;
75
+ }
76
+
77
+ const delta = signedDelta(this.refDeg, deg);
78
+
79
+ if (Math.abs(delta) >= this.minTurnDeg) {
80
+ // Re-baseline immediately, so a continuous 180° about-face is reported as
81
+ // the turns it is made of. Left as one growing delta it would flip sign
82
+ // at the halfway point and report a right turn for a left one.
83
+ this.lastTurn = { deg: Math.round(delta), timestamp: now };
84
+ this.refDeg = deg;
85
+ this.stableSince = now;
86
+ return this.lastTurn;
87
+ }
88
+
89
+ if (Math.abs(delta) > this.stableDeg) {
90
+ // Moving, but not far enough yet. Hold the reference and keep watching —
91
+ // this is what lets a slow 90° turn accumulate instead of being
92
+ // re-baselined away one degree at a time.
93
+ this.stableSince = now;
94
+ return null;
95
+ }
96
+
97
+ // Steady. After a while, treat here as the new straight-ahead.
98
+ if (now - this.stableSince >= this.stableMs) {
99
+ this.refDeg = deg;
100
+ this.stableSince = now;
101
+ }
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * The most recent completed turn, or null if none this session.
107
+ *
108
+ * It does NOT expire on its own: the age is derivable from `timestamp`, and
109
+ * "recent enough to mention" is a product judgement this layer must not make
110
+ * on the caller's behalf.
111
+ */
112
+ last(): TurnEvent | null {
113
+ return this.lastTurn;
114
+ }
115
+
116
+ reset(): void {
117
+ this.refDeg = null;
118
+ this.stableSince = 0;
119
+ this.lastTurn = null;
120
+ }
121
+ }