File size: 12,909 Bytes
8a29801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * Device-event router — engine-owned. Subscribes to the inbound native BLE/device

 * events and routes them into the engine runtime: device stores, the process event

 * bus, the photo/stream coordinators, and local miniapps (via forwardEvent).

 *

 * Why this exists: engine owns the stores, coordinators, miniapp runtime, and facades,

 * but it never *subscribed to the device* for most events — the host MantleManager was

 * still the event router the whole runtime secretly depended on. So a bare OEM that

 * imported engine + called engine.start() got a connected runtime with almost no device

 * data flowing in (no miniapp input, dead gallery sync, starved coordinators). This

 * service moves those inbound bridges into engine so ANY host gets them.

 *

 * Scope: the engine legs only. The Cloud V1 relays that used to live beside them in

 * MantleManager (touch→cloud, the cloud-SDK stream/photo legs, etc.) were deleted with

 * Cloud V1 app end-of-life.

 *

 * Started by `engine.start()`. Idempotent.

 */
import BluetoothSdk from "@mentra/bluetooth-sdk/internal"
import {shallow} from "zustand/shallow"

import audioPlaybackService from "./AudioPlaybackService"
import {wakeWordService} from "./WakeWordService"
import localMiniappRuntime from "./LocalMiniappRuntime"
import localSttFallbackCoordinator from "./LocalSttFallbackCoordinator"
import {phonePhotoCoordinator} from "./PhonePhotoCoordinator"
import {phoneStreamCoordinator} from "./PhoneStreamCoordinator"
import {isGlassesConnected} from "./GlassesReadiness"
import {useGlassesStore} from "../stores/glasses"
import {useSettingsStore} from "../stores/settings"
import {useAppStatusStore} from "../stores/apps"
import {retirePendingSelectionOnPromotion} from "./PairingIdentity"
import GlobalEventEmitter from "../utils/GlobalEventEmitter"
import {asgCameraApi} from "./asg/asgCameraApi"

let subs: Array<{remove: () => void}> = []

export function startDeviceEventRouter(): void {
  if (subs.length) return

  // --- device state → engine stores ---

  // Standalone WiFi status → glasses store.
  subs.push(
    BluetoothSdk.addListener("wifi_status_change", (event) => {
      const {type: _type, ...wifi} = event
      useGlassesStore.getState().setGlassesInfo({wifi})
    }),
  )

  // Forward glasses Wi-Fi to miniapps (session.glasses.onWifi) from the STORE — the
  // single source of truth — so every path converges here: wifi_status_change,
  // onGlassesStatus, and BLE disconnect. Effective connectivity requires the glasses
  // to be connected AND on Wi-Fi, so a disconnect correctly flips `connected` false.
  // `linkConnected` carries the BLE leg on its own so a miniapp can tell "glasses
  // out of Bluetooth range" from "glasses on Bluetooth but off Wi-Fi" — the two
  // need opposite recoveries (wait vs. open Wi-Fi setup).
  subs.push({
    remove: useGlassesStore.subscribe(
      (s) => {
        const linkConnected = isGlassesConnected(s.connection)
        const connected = linkConnected && s.wifi.state === "connected"
        // ssid/localIp describe how to reach the glasses over Wi-Fi, so they are
        // only meaningful under effective connectivity. Gate them on `connected`
        // (not raw wifi.state) so a BLE drop with a stale "connected" Wi-Fi leg
        // never hands miniapps an unreachable address.
        return {
          connected,
          linkConnected,
          ssid: linkConnected && s.wifi.state === "connected" ? s.wifi.ssid : undefined,
          localIp: linkConnected && s.wifi.state === "connected" ? s.wifi.localIp : undefined,
        }
      },
      (wifi) => localMiniappRuntime.forwardEvent("glasses_wifi", wifi),
      {equalityFn: shallow},
    ),
  })

  // Incremental battery status → glasses store + local miniapps.
  subs.push(
    BluetoothSdk.addListener("battery_status", (event) => {
      const state = useGlassesStore.getState()
      state.setBatteryInfo(event.level, event.charging, state.caseBatteryLevel, state.caseCharging)
      localMiniappRuntime.forwardEvent("glasses_battery_update", {
        type: "glasses_battery_update",
        level: event.level,
        charging: event.charging,
        timestamp: event.timestamp ?? Date.now(),
      })
    }),
  )

  // Hotspot status → glasses store + event bus. engine's own gallerySyncService listens
  // on the bus for these, so without this bridge engine's gallery sync is dead.
  subs.push(
    BluetoothSdk.addListener("hotspot_status_change", (event) => {
      const enabled = event.state === "enabled"
      const ssid = enabled ? event.ssid : ""
      const password = enabled ? event.password : ""
      const localIp = enabled ? event.localIp : ""
      useGlassesStore.getState().setHotspotInfo(enabled, ssid, password, localIp)
      // Always retarget the ASG camera client: on disable (or an event with no
      // IP) fall back to the localhost default so later calls fail fast instead
      // of hitting the previous network's stale glasses IP.
      asgCameraApi.setServer(localIp || "localhost", 8089)
      GlobalEventEmitter.emit("hotspot_status_change", {enabled, ssid, password, local_ip: localIp})
    }),
  )
  subs.push(
    BluetoothSdk.addListener("hotspot_error", (event) => {
      GlobalEventEmitter.emit("hotspot_error", {error_message: event.errorMessage, timestamp: event.timestamp})
    }),
  )

  // Glasses gallery content counts → event bus (consumed by gallerySyncService).
  subs.push(
    BluetoothSdk.addListener("gallery_status", (event) => {
      GlobalEventEmitter.emit("gallery_status", {
        photos: event.photos,
        videos: event.videos,
        total: event.total,
        has_content: event.hasContent,
        camera_busy: event.cameraBusy,
      })
    }),
  )

  // Hardware-originated setting changes (user changes a setting ON the glasses) → store.
  // The inbound complement to GlassesSettingsSync (which only pushes store→device).
  subs.push(
    BluetoothSdk.addListener("save_setting", async (event) => {
      const settings = useSettingsStore.getState()
      // Damp the relay: native re-echoes some settings unconditionally (e.g.
      // the identity block at every handleDeviceReady) — a same-value echo
      // must not become a store write (persistence churn + change-push noise).
      if (settings.getSetting(event.key) !== event.value) {
        await settings.setSetting(event.key, event.value)
      }
      // Two-phase identity: a promoted default retires the pending selection
      // marker. The rule lives with PairingIdentity (a no-op for other keys).
      await retirePendingSelectionOnPromotion(event.key, event.value)
    }),
  )

  // Mentra Live pairing state is owned by the Bluetooth SDK (`normal`, `pairing_mode`,
  // `pairing_rejected`). The engine only mirrors it into the glasses store so the app renders
  // from one source: the pairing-mode popup, and the Pair Again card.
  subs.push(
    BluetoothSdk.addListener("pairing_state_changed", (event) => {
      useGlassesStore.getState().setGlassesInfo({pairingState: event.state})
    }),
  )

  // Whether the user has to do anything for glasses audio is decided by the Bluetooth SDK. The
  // engine mirrors it; the pairing flow and Home render Pair Audio from it.
  subs.push(
    BluetoothSdk.addListener("audio_setup_changed", (event) => {
      useGlassesStore.getState().setGlassesInfo({audioSetup: event.state})
    }),
  )

  // --- coordinators (owns()-gated) ---

  // Phone-owned photo errors settle the in-flight long-poll fast (vs. timeout).
  // Non-owned photo responses used to forward to the Cloud V1 photo pipeline via
  // restComms; that relay was removed with Cloud V1 app end-of-life, so they drop.
  // Wire v2 sends a short 4-hex BLE requestId; the coordinator maps it back to
  // the cloud requestId (resolveCloudRequestId) before ownership checks.
  subs.push(
    BluetoothSdk.addListener("photo_response", (event) => {
      const cloudRequestId = event.requestId ? phonePhotoCoordinator.resolveCloudRequestId(event.requestId) : ""
      if (cloudRequestId && phonePhotoCoordinator.owns(cloudRequestId)) {
        if (event.state === "error") {
          phonePhotoCoordinator.handlePhotoError(
            event.requestId ?? cloudRequestId,
            event.errorCode ?? "GLASSES_ERROR",
            event.errorMessage ?? "Glasses reported an error",
          )
        }
      }
    }),
  )

  // Phone-owned stream status → the stream coordinator. The Cloud V1 relay
  // for non-owned streams was removed with Cloud V1 app end-of-life.
  subs.push(
    BluetoothSdk.addListener("stream_status", (event) => {
      if (
        (event.streamId && phoneStreamCoordinator.owns(event.streamId)) ||
        (!event.streamId && event.kind === "snapshot" && event.terminal === true)
      ) {
        phoneStreamCoordinator.handleGlassesStatus(event)
      }
    }),
  )

  // --- device input → local miniapps (forwardEvent is subscriber-gated; a no-op when
  // no miniapp listens). The v1 SocketComms cloud legs for these were removed with
  // the Cloud V1 ripout. ---

  subs.push(
    BluetoothSdk.addListener("button_press", (event) => {
      localMiniappRuntime.forwardEvent("button_press", event)
    }),
  )
  subs.push(
    BluetoothSdk.addListener("touch_event", (event) => {
      localMiniappRuntime.forwardEvent("touch_event", event)
    }),
  )
  // G2 IMU accelerometer — payload already matches the miniapp AccelData shape.
  subs.push(
    BluetoothSdk.addListener("accel_event", (event) => {
      localMiniappRuntime.forwardEvent("accel_event", {
        x: event.x,
        y: event.y,
        z: event.z,
        timestamp: typeof event.timestamp === "number" ? event.timestamp : Date.now(),
      })
    }),
  )
  // Head position — translate native {up:boolean} → SDK {position:"up"|"down"}.
  subs.push(
    BluetoothSdk.addListener("head_up", (event) => {
      localMiniappRuntime.forwardEvent("head_up", {position: event.up ? "up" : "down", timestamp: Date.now()})
    }),
  )
  // On-device "Hey Mentra" → every miniapp subscribed to the wake word. Warm
  // up the audio player on each detection so the next sound starts quickly.
  subs.push(
    BluetoothSdk.addListener("wake_word", (event) => {
      if (event.kind === "detected" && localMiniappRuntime.hasStreamSubscribers("wake_word")) {
        void audioPlaybackService.prepareForPlayback().catch((error) => {
          console.warn("Audio playback preparation after wake word failed", error)
        })
      }
      const forwarded = wakeWordService.onNativeEvent(event)
      if (forwarded) localMiniappRuntime.forwardEvent("wake_word", forwarded)
    }),
  )
  // Phone-side voice activity (native Silero) → `vad`, one event per start or
  // stop. Native counts a gap in microphone audio as silence.
  subs.push(
    BluetoothSdk.addListener("speech_activity", (event) => {
      localMiniappRuntime.forwardEvent("vad", {
        status: event.speaking,
        silentForMs: event.silentForMs,
        timestamp: event.timestamp,
      })
    }),
  )
  // On-device STT transcripts → local miniapps only while the local engine is
  // active (a localOnly or preferLocal listener, or the cloud fallback). The
  // runtime routes each listener to one source, so nothing arrives twice.
  // forwardEvent is subscriber-gated — a no-op when no miniapp listens.
  // (Was MantleManager.handle_local_transcription; its offline-captions display branch
  // went away with the pseudo captions renderer.)
  subs.push(
    BluetoothSdk.addListener("local_transcription", (event) => {
      if (!localSttFallbackCoordinator.isActive()) return
      const lang = event.transcribeLanguage ?? localSttFallbackCoordinator.getActiveLanguage() ?? "en-US"
      localMiniappRuntime.forwardEvent(`transcription:${lang}`, event, "local")
    }),
  )

  // --- glasses swipe-menu app launcher (G2) ---
  subs.push(
    BluetoothSdk.addListener("miniapp_selected", (event) => {
      const packageName = event.packageName as string
      if (!packageName) return
      const app = useAppStatusStore.getState().apps.find((a) => a.packageName === packageName)
      if (!app) return
      // Toggle: stop if running, else start.
      if (app.running) {
        useAppStatusStore.getState().stop(packageName)
      } else {
        // Picked from the glasses' own menu: a person's choice.
        useAppStatusStore.getState().start(app, {skipNavigation: true, trigger: "user"})
      }
    }),
  )
}

export function stopDeviceEventRouter(): void {
  for (const sub of subs) sub.remove()
  subs = []
}