import {createScanSession} from "./scanSession" import {NativeModule, requireNativeModule} from "expo" import {Platform} from "react-native" import {installNativeLogConsole, installSdkUpdateNotice} from "./nativeLogConsole" import { BluetoothSettingsUpdate, BluetoothSdkModuleEvents, BluetoothStatus, PhotoCaptureDefaults, CalendarEvent, CAMERA_FOV_DEFAULT, CAMERA_FOV_MAX, CAMERA_FOV_MIN, CameraFovPreset, CameraFovRequest, CameraFovOverrideRequest, CameraFovResult, CameraFovSetting, CameraRoiPosition, CameraStatusEvent, ConnectOptions, DashboardMenuItem, Device, DeviceModel, GlassesMediaVolumeGetResult, GlassesMediaVolumeSetResult, GlassesStatus, GalleryStatusEvent, HotspotStatusChangeEvent, MicPreference, NativePhoneNotification, NativeNotificationConfig, NativeNotificationStatus, MicTuning, ObservableStoreCategory, OtaQueryResult, OtaStartAckEvent, PhotoRequestParams, PhotoSuccessResponseEvent, PublicBluetoothStatus, RgbLedAction, RgbLedColor, RgbLedControlSuccessResponseEvent, ScanDiagnostic, ScanModelOptions, ScanOptions, SettingsAckSuccessEvent, StreamStartRequest, StreamStatusEvent, TouchGesture, VideoRecordingStartedStatusEvent, VideoRecordingSettings, VideoRecordingStoppedStatusEvent, VideoRecordingStatusEvent, VersionInfoResult, WarmUpCameraParams, SavedWifiNetworksResult, WifiForgetResult, WifiSearchResult, WifiStatusChangeEvent, } from "../BluetoothSdk.types" import {warmUpCameraParamsForNative} from "./cameraRequestPayload" import {photoRequestParamsForNative} from "./photoRequestPayload" import {streamRequestParamsForNative} from "./streamRequestPayload" /** * Private React Native native-module facade. * * This file intentionally lives under `_private` so the package root can expose * a small SDK surface while MentraOS uses its monorepo-only internal alias * during migration. Raw status getters/listeners stay here so React hooks can * shape native store snapshots before app code sees them. */ type GlassesListener = (changed: Partial) => void type BluetoothStatusListener = (changed: Partial) => void type MaybePromise = T | Promise declare class BluetoothSdkNativeModule extends NativeModule { // Observable Store Functions (native) getGlassesStatus(): Promise getBluetoothStatus(): Promise getDefaultDevice(): Promise update(category: ObservableStoreCategory, values: object): Promise // Display Commands displayEvent(params: Record): Promise displayText(text: string, x?: number, y?: number, size?: number): Promise clearDisplay(): Promise setDashboardContent(content: string): Promise // Connection Commands requestStatus(): Promise connectDefault(options?: ConnectOptions): Promise connectDefaultWithOptions(options: Required): Promise setDefaultDevice(device: Device | null): Promise clearDefaultDevice(): Promise /** Android only: iOS cannot read its Bluetooth bonds. */ getBondedGlasses?: () => Promise<{name: string; address: string} | null> getScanDiagnostic?: (model: DeviceModel) => Promise startScan(model: DeviceModel): Promise stopScan(): Promise scan(options: ScanOptions): Promise scan(model: DeviceModel, options?: ScanModelOptions): Promise connect(device: Device, options?: ConnectOptions): Promise connectWithOptions(device: Device, options: Required): Promise cancelConnectionAttempt(): Promise connectDefaultController(): Promise disconnectController(): Promise connectSimulated(): Promise disconnect(): Promise forget(): Promise /** Explicit Unpair also resets connected NIMO glasses before forgetting. */ unpair(): Promise forgetController(): Promise showDashboard(): Promise setBrightness(level: number, autoMode?: boolean | null): Promise setAutoBrightness(enabled: boolean): Promise setDashboardPosition(height: number, depth: number): Promise setDashboardMenu(items: DashboardMenuItem[]): Promise setCalendarEvents(events: CalendarEvent[]): Promise setHeadUpAngle(angleDegrees: number): Promise setImuEnabled(enabled: boolean): Promise setScreenDisabled(disabled: boolean): Promise ping(): Promise dbg1(): Promise dbg2(): Promise // Incident Reporting sendIncidentId(incidentId: string, apiBaseUrl?: string | null): Promise /** * Tell Mentra Live that Cloud recorded `reportId` for the BES crash incident * `incidentKey`. Resolves only on the glasses' matching `ok:true` ack; rejects * on `ok:false`, disconnect, or after 10 s. Call `sendIncidentId` only after it resolves. */ sendBesCrashReported(incidentKey: string, reportId: string): Promise // WiFi Commands requestWifiScan(): Promise getSavedWifiNetworks(): Promise sendWifiCredentials(ssid: string, password: string): Promise forgetWifiNetwork(ssid: string): Promise setHotspotState(enabled: boolean): Promise /** Enable or disable Wi-Fi ADB on Mentra Live (no-op on other devices). */ setWifiAdbState(enabled: boolean, expectedBluetoothMac?: string): Promise /** Set the glasses system clock when phone detects clock skew (Mentra Live and G2). */ setSystemTime(timestampMs: number): Promise /** Logs current WiFi frequency (MHz) and 5 GHz band to Android logcat. */ logCurrentWifiFrequency(): Promise // Gallery Commands setGalleryServerEnabled(enabled: boolean): Promise setTouchGestureDefaultBehaviorEnabled(gesture: TouchGesture, enabled: boolean): Promise setGalleryModeEnabled(enabled: boolean): Promise setVoiceActivityDetectionEnabled(enabled: boolean): Promise /** Mentra Live center-mic loudness / Barrier gate (cs_swit type 10). */ setLoudnessGateEnabled(enabled: boolean): Promise /** Mentra Live power-off after ~20 min unworn (cs_swit type 11). */ setAutoPowerOffEnabled(enabled: boolean): Promise /** * Mentra Live mic tuning. `null` clears every override and returns the * glasses to firmware defaults. * * Deliberately absent from the public SDK surface: it is a super-mode * calibration aid whose values only make sense next to a live RMS readout. */ setMicTuning(tuning: MicTuning | null): Promise /** * Ask the glasses to report the tuning they are actually running. The answer * arrives as a `mic_tuning_state` event, which is also emitted unprompted * after every set, so a screen that subscribes on mount and calls this on * focus never has to guess. */ requestMicTuningState(): Promise /** Enable or disable the `mic_rms` readout. Auto-disabled on disconnect. */ setMicRmsTelemetry(enabled: boolean): Promise /** * Mentra Live wear detection. Internal / Super Mode only. * * Reporting is RAM-only on the glasses and must not go through `cs_swit` * type 1 (that bit is NV-backed). `resetWearTuning` both restores the * firmware vote defaults and turns reporting off. */ queryWearState(): Promise setWearReporting(enabled: boolean): Promise /** Negative values leave that field unchanged. */ setWearTuning(intervalMs: number, count: number, majority: number): Promise requestWearTuning(): Promise resetWearTuning(): Promise /** * @deprecated Sticky action-button photo presets are deprecated. Prefer per-request * `requestPhoto(...)` options (e.g. `mode: "text"` for text sensor size/crop). */ setPhotoCaptureDefaults(settings: PhotoCaptureDefaults): Promise setVideoRecordingDefaults(width: number, height: number, fps: number): Promise setMaxVideoRecordingDuration(minutes: number): Promise setCameraFov(request: CameraFovRequest): Promise setLegacyCameraFov(request: CameraFovRequest): Promise restoreLegacyCameraFov(): Promise setCameraFovOverride(request: CameraFovOverrideRequest): Promise releaseCameraFovOverride(leaseId: string): Promise /** * Configure camera HAL tuning (ANR / gain) on Mentra Live glasses. * Sends a {@code camera_tuning_config} BLE message; the ASG client relays it as a * {@code camconfig} broadcast so the HAL picks up new parameters without a reboot. * * Scan-mode convention: pass `{anr: false, gain: false}` when activating scan mode * (disables ANR and pixsmart gain) and `{anr: true, gain: true}` to restore defaults. */ setCameraTuningConfig(anrOn: boolean, gainOn: boolean): Promise queryGalleryStatus(): Promise requestPhoto(params: PhotoRequestParams): Promise warmUpCamera(params: WarmUpCameraParams): Promise stopCameraWarmUp(requestId: string): Promise // OTA Commands setOtaVersionUrl(otaVersionUrl: string): void getOtaVersionUrl(): string checkForOtaUpdate(): Promise startOtaUpdate(otaVersionUrl?: string | null): Promise sendOtaQueryStatus(): Promise startAr99OtaFromFile(path: string): Promise cancelAr99Ota(): Promise sendAr99FactoryReset(): Promise buildAr99OtaSignature( secret: string, appName: string, currentVersion: string, serialNumber: string, nonce: string, ): string // Version Info Commands requestVersionInfo(): Promise // Video Recording Commands startVideoRecording( requestId: string, save: boolean, sound: boolean, settings?: VideoRecordingSettings, ): Promise stopVideoRecording( requestId: string, webhookUrl?: string, authToken?: string, ): Promise queryVideoRecordingStatus(requestId: string): Promise // Stream Commands startStream(params: StreamStartRequest): Promise stopStream(): Promise // Microphone Commands setMicState(enabled: boolean, useGlassesMic?: boolean, sendTranscript?: boolean, sendLc3Data?: boolean): Promise setPreferredMic(preferredMic: MicPreference): Promise /** * Lock microphone selection to one source (`"glasses"`) until released with `null`. * * Stronger than [setPreferredMic]: a preference is a ranking the SDK falls through when a source * is unavailable, while a pin has no fallback and reports `mic_health` with * `reason: "pinned-source-unavailable"` instead. Android only; the iOS implementation is a no-op, * so a caller that depends on the guarantee must gate on platform. */ setMicSourcePin(source: string | null): Promise /** See the public `setWakeWordDetection`. `modelDir` is required when enabling. */ setWakeWordDetection(enabled: boolean, modelDir?: string | null): Promise /** Whether the active recognizer has `path` loaded. Never blocks on a model load. */ isSttModelLoaded(path: string): Promise /** See the public `finishTranscription`. */ finishTranscription(): Promise /** See the public `restartTranscriber`. */ restartTranscriber(): Promise /** See the public `setSpeechActivityDetection`. */ setSpeechActivityDetection(enabled: boolean, options?: {minSilenceMs?: number}): Promise // Audio Playback Monitoring // Notify native side when our app starts/stops playing audio // Used to suspend LC3 mic during audio playback to avoid MCU overload setOwnAppAudioPlaying(playing: boolean): Promise // Live PCM output stream (miniapp speaker.createStream). MentraOS-internal // ? 16-bit LE PCM chunks into a streaming AudioTrack (USAGE_MEDIA, so it // follows the phone's media route, e.g. A2DP to glasses). Implemented with // AudioTrack on Android and AVAudioEngine on iOS. /** * Open a PCM stream session. One AudioTrack per id; caller manages ids. * * `jitterMs` (default 500) is how much audio is queued before playback starts, and the playout * cushion after that. Omit it for one-way media, where the default cushion is inaudible; pass a * small value for conversational audio, where the same cushion is delay before the far end is * heard. Both platforms honor it: playback starts once `jitterMs` is queued or the stream is * closed, so a sound shorter than `jitterMs` still plays. * * A stream that has not received audio yet is aborted when the audio route changes (Bluetooth * or glasses connect/disconnect, a call starting or ending, an audio-session interruption), so * its next write rejects with "stream not open" instead of playing on a stale route. */ pcmStreamOpen( streamId: string, sampleRate: number, channels: number, volume: number, jitterMs?: number, ): Promise /** * Append base64 PCM. Resolves with the queued-but-unplayed backlog in ms; * blocks (on a background dispatcher) while the backlog is above the * backpressure ceiling, so awaited writes self-throttle to realtime. */ pcmStreamWrite(streamId: string, base64: string): Promise<{bufferedMs: number}> /** Drain the backlog, then stop. Resolves with the total played duration. */ pcmStreamClose(streamId: string): Promise<{durationMs: number}> /** Stop immediately, dropping any backlog. Idempotent. */ pcmStreamAbort(streamId: string): Promise /** * Fetch `url` (HTTP GET) and play its body as raw 16-bit little-endian mono PCM at `sampleRate` * while it downloads, through the same stream player as `pcmStreamOpen`. Native code reads the * body; audio never crosses into JavaScript. Resolves with the played duration after the whole * body has played. Rejects on a non-2xx response or a network error (whatever already played * stays played), and with "aborted" after `pcmStreamAbort(streamId)`. Must not block the shared * module queue while it runs. */ pcmStreamPlayUrl( streamId: string, url: string, sampleRate: number, volume: number, jitterMs?: number, ): Promise<{durationMs: number}> /** Mentra Live only: K900 `cs_getvol` / `sr_getvol`. */ getGlassesMediaVolume(): Promise /** Mentra Live only: K900 `cs_vol` / `sr_vol`; level clamped 0??5 on native. */ setGlassesMediaVolume(level: number): Promise // RGB LED Control rgbLedControl( requestId: string, packageName: string | null, action: RgbLedAction, color: RgbLedColor | null, onDurationMs: number, offDurationMs: number, count: number, ): Promise // STT Commands setSttModelDetails(path: string, languageCode: string): Promise getSttModelPath(): Promise checkSttModelAvailable(): Promise validateSttModel(path: string): Promise extractTarBz2(sourcePath: string, destinationPath: string): Promise // TTS Commands setTtsModelDetails(path: string, languageCode: string): Promise getTtsModelPath(): Promise getTtsModelLanguage(): Promise checkTtsModelAvailable(): Promise validateTtsModel(path: string): Promise generateTtsAudio( text: string, modelPath: string, outputPath: string, speakerId: number, speed: number, ): Promise /** Android G2 content upload. iOS receives ANCS directly and rejects uploads. */ sendPhoneNotification(notification: NativePhoneNotification): Promise configureNativeNotifications(config: NativeNotificationConfig): Promise getNativeNotificationStatus(): Promise // Helper methods for type-safe observable store access updateGlasses(values: Partial): Promise updateBluetoothSettings(values: BluetoothSettingsUpdate): Promise onGlassesStatus(callback: GlassesListener): () => void onBluetoothStatus(callback: BluetoothStatusListener): () => void // Process resident-set-size in MB. iOS-only; Android stub returns 0. getMemoryMB(): number } export type BluetoothSdkInternalModule = BluetoothSdkNativeModule // This call loads the native module object from the JSI. // NativeModule already extends EventEmitter const NativeBluetoothSdkModule = requireNativeModule("BluetoothSdk") installNativeLogConsole(NativeBluetoothSdkModule, Platform.OS) installSdkUpdateNotice(NativeBluetoothSdkModule) const DEFAULT_CONNECT_OPTIONS: Required = { saveAsDefault: true, cancelExistingConnectionAttempt: true, requiresAncs: true, enableTransportBridging: true, } const DEFAULT_SCAN_TIMEOUT_MS = 15_000 function bindNativeMethod unknown>(module: Record, name: string): T { const method = module[name] if (typeof method !== "function") { console.warn(`[BluetoothSdk] Native method "${name}" is unavailable ??rebuild the app (bun android / bun ios)`) return (async () => { throw new Error(`BluetoothSdk.${name} is not available in this native build. Rebuild the app.`) }) as T } return method.bind(module) as T } const CAMERA_ROI_MIN = 0 const CAMERA_ROI_MAX = 2 const CAMERA_ROI_POSITION_VALUES: Record = { center: 0, bottom: 1, top: 2, } // Named presets are a convenience layer over the numeric {fov, roiPosition} API. // The default is the full sensor; "standard" preserves the historical 102° crop. const CAMERA_FOV_PRESETS: Record = { narrow: {fov: 82, roiPosition: 0}, standard: {fov: 102, roiPosition: 0}, wide: {fov: CAMERA_FOV_MAX, roiPosition: 0}, } function clampInteger(value: number, min: number, max: number): number { return Math.max(min, Math.min(max, Math.round(value))) } function normalizeCameraFov(request: CameraFovRequest): CameraFovSetting { if ("preset" in request) { return CAMERA_FOV_PRESETS[request.preset] ?? CAMERA_FOV_PRESETS.standard } const roiPosition = request.roiPosition ?? "center" return { fov: clampInteger(Number.isFinite(request.fov) ? request.fov : CAMERA_FOV_DEFAULT, CAMERA_FOV_MIN, CAMERA_FOV_MAX), roiPosition: clampInteger(CAMERA_ROI_POSITION_VALUES[roiPosition] ?? 0, CAMERA_ROI_MIN, CAMERA_ROI_MAX) as | 0 | 1 | 2, } } function searchResultsForModel(status: Partial, model: DeviceModel): Device[] { return status.searchResults?.filter((device) => device.model === model) ?? [] } function normalizeScanArgs(modelOrOptions: DeviceModel | ScanOptions, options?: ScanModelOptions): ScanOptions { if (typeof modelOrOptions === "string") { return {model: modelOrOptions, ...options} } return modelOrOptions } function normalizeTimeoutMs(timeoutMs: number | undefined, defaultTimeoutMs: number): number { return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : defaultTimeoutMs } function dashboardMenuItemToNative(item: DashboardMenuItem): Record { return { ...(item.values ?? {}), title: item.title, packageName: item.packageName, } } function adaptConnectionStatusToNative(connection: GlassesStatus["connection"]): Record { switch (connection.state) { case "connected": return {connectionState: "CONNECTED", connected: true, fullyBooted: connection.fullyBooted} case "scanning": return {connectionState: "SCANNING", connected: false, fullyBooted: false} case "connecting": return {connectionState: "CONNECTING", connected: false, fullyBooted: false} case "bonding": return {connectionState: "BONDING", connected: false, fullyBooted: false} case "disconnected": return {connectionState: "DISCONNECTED", connected: false, fullyBooted: false} } } function adaptGlassesUpdateToNative(values: Partial): Record { const {wifi, hotspot, connection, ...rest} = values let update: Record = {...rest} if (connection) { update = { ...update, ...adaptConnectionStatusToNative(connection), } } if (wifi?.state === "connected") { update = { ...update, wifiConnected: true, wifiSsid: wifi.ssid, wifiLocalIp: wifi.localIp ?? "", } } else if (wifi?.state === "disconnected") { update = { ...update, wifiConnected: false, wifiSsid: "", wifiLocalIp: "", } } if (hotspot?.state === "enabled") { update = { ...update, hotspotEnabled: true, hotspotSsid: hotspot.ssid, hotspotPassword: hotspot.password, hotspotGatewayIp: hotspot.localIp, } } else if (hotspot?.state === "disabled") { update = { ...update, hotspotEnabled: false, hotspotSsid: "", hotspotPassword: "", hotspotGatewayIp: "", } } return update } // Add helper methods to the module const nativeGetGlassesStatus = NativeBluetoothSdkModule.getGlassesStatus.bind( NativeBluetoothSdkModule, ) as () => MaybePromise NativeBluetoothSdkModule.getGlassesStatus = function () { return Promise.resolve(nativeGetGlassesStatus()) } const nativeGetBluetoothStatus = NativeBluetoothSdkModule.getBluetoothStatus.bind( NativeBluetoothSdkModule, ) as () => MaybePromise NativeBluetoothSdkModule.getBluetoothStatus = function () { return Promise.resolve(nativeGetBluetoothStatus()) } const nativeGetDefaultDevice = NativeBluetoothSdkModule.getDefaultDevice.bind( NativeBluetoothSdkModule, ) as () => MaybePromise NativeBluetoothSdkModule.getDefaultDevice = function () { return Promise.resolve(nativeGetDefaultDevice()) } const nativeSetMicState = NativeBluetoothSdkModule.setMicState.bind(NativeBluetoothSdkModule) as ( enabled: boolean, useGlassesMic: boolean, sendTranscript: boolean, sendLc3Data: boolean, ) => MaybePromise const nativeDisplayText = NativeBluetoothSdkModule.displayText.bind(NativeBluetoothSdkModule) as ( text: string, x: number, y: number, size: number, ) => MaybePromise NativeBluetoothSdkModule.updateGlasses = function (values: Partial) { return this.update("glasses", adaptGlassesUpdateToNative(values)) } NativeBluetoothSdkModule.updateBluetoothSettings = function (values: BluetoothSettingsUpdate) { return this.update("bluetooth", values) } NativeBluetoothSdkModule.displayText = function (text: string, x?: number, y?: number, size?: number) { return Promise.resolve(nativeDisplayText(text, x ?? 0, y ?? 0, size ?? 24)) } NativeBluetoothSdkModule.setBrightness = function (level: number, autoMode?: boolean | null) { return this.updateBluetoothSettings({ ...(autoMode == null ? {} : {auto_brightness: autoMode}), brightness: level, }) } NativeBluetoothSdkModule.setAutoBrightness = function (enabled: boolean) { return this.updateBluetoothSettings({auto_brightness: enabled}) } NativeBluetoothSdkModule.setDashboardPosition = function (height: number, depth: number) { return this.updateBluetoothSettings({ dashboard_height: height, dashboard_depth: depth, }) } NativeBluetoothSdkModule.setDashboardMenu = function (items: DashboardMenuItem[]) { return this.updateBluetoothSettings({menu_apps: items.map(dashboardMenuItemToNative)}) } NativeBluetoothSdkModule.setCalendarEvents = function (events: CalendarEvent[]) { return this.updateBluetoothSettings({calendar_events: events}) } NativeBluetoothSdkModule.setHeadUpAngle = function (angleDegrees: number) { return this.updateBluetoothSettings({head_up_angle: angleDegrees}) } NativeBluetoothSdkModule.setImuEnabled = function (enabled: boolean) { return this.updateBluetoothSettings({imu_enabled: enabled}) } NativeBluetoothSdkModule.setScreenDisabled = function (disabled: boolean) { return this.updateBluetoothSettings({screen_disabled: disabled}) } NativeBluetoothSdkModule.setVoiceActivityDetectionEnabled = function (enabled: boolean) { return this.updateBluetoothSettings({voice_activity_detection_enabled: enabled}) } NativeBluetoothSdkModule.setLoudnessGateEnabled = function (enabled: boolean) { return this.updateBluetoothSettings({loudness_gate_enabled: enabled}) } NativeBluetoothSdkModule.setAutoPowerOffEnabled = function (enabled: boolean) { return this.updateBluetoothSettings({auto_power_off_enabled: enabled}) } NativeBluetoothSdkModule.setMicTuning = function (tuning: MicTuning | null) { // `{}` rather than null: the store drops null writes, and the native side // reads an empty object as "no overrides" and sends an explicit reset. return this.updateBluetoothSettings({mic_tuning: tuning ?? {}}) } const nativeMicModule = NativeBluetoothSdkModule as unknown as Record NativeBluetoothSdkModule.requestMicTuningState = bindNativeMethod<() => Promise>( nativeMicModule, "requestMicTuningState", ) NativeBluetoothSdkModule.setMicRmsTelemetry = bindNativeMethod<(enabled: boolean) => Promise>( nativeMicModule, "setMicRmsTelemetry", ) const nativeSetCameraFov = bindNativeMethod<(fov: CameraFovSetting) => MaybePromise>( NativeBluetoothSdkModule as unknown as Record, "setCameraFov", ) NativeBluetoothSdkModule.setCameraFov = function (request: CameraFovRequest) { const setting = normalizeCameraFov(request) return Promise.resolve(nativeSetCameraFov(setting)) } const nativeSetLegacyCameraFov = bindNativeMethod<(fov: CameraFovSetting) => MaybePromise>( NativeBluetoothSdkModule as unknown as Record, "setLegacyCameraFov", ) NativeBluetoothSdkModule.setLegacyCameraFov = function (request: CameraFovRequest) { return Promise.resolve(nativeSetLegacyCameraFov(normalizeCameraFov(request))) } const nativeRestoreLegacyCameraFov = bindNativeMethod<() => MaybePromise>( NativeBluetoothSdkModule as unknown as Record, "restoreLegacyCameraFov", ) NativeBluetoothSdkModule.restoreLegacyCameraFov = function () { return Promise.resolve(nativeRestoreLegacyCameraFov()) } const nativeSetCameraFovOverride = bindNativeMethod< (request: CameraFovSetting & {leaseId: string; ttlMs: number}) => MaybePromise >(NativeBluetoothSdkModule as unknown as Record, "setCameraFovOverride") NativeBluetoothSdkModule.setCameraFovOverride = function (request: CameraFovOverrideRequest) { const setting = normalizeCameraFov(request) const requestedTtl = typeof request.ttlMs === "number" && Number.isFinite(request.ttlMs) && request.ttlMs > 0 ? Math.round(request.ttlMs) : 300_000 return Promise.resolve( nativeSetCameraFovOverride({ ...setting, leaseId: request.leaseId, ttlMs: Math.min(requestedTtl, 600_000), }), ) } NativeBluetoothSdkModule.setMicState = function ( enabled: boolean, useGlassesMic?: boolean, sendTranscript?: boolean, sendLc3Data?: boolean, ) { return Promise.resolve( nativeSetMicState(enabled, useGlassesMic ?? true, sendTranscript ?? false, sendLc3Data ?? false), ) } NativeBluetoothSdkModule.setPreferredMic = function (preferredMic: MicPreference) { return this.updateBluetoothSettings({preferred_mic: preferredMic}) } NativeBluetoothSdkModule.onGlassesStatus = function (callback: GlassesListener) { const subscription = this.addListener("glasses_status", callback) return () => subscription.remove() } NativeBluetoothSdkModule.onBluetoothStatus = function (callback: BluetoothStatusListener) { const subscription = this.addListener("bluetooth_status", callback) return () => subscription.remove() } const nativeConnectDefault = NativeBluetoothSdkModule.connectDefault.bind(NativeBluetoothSdkModule) NativeBluetoothSdkModule.connectDefault = function (options?: ConnectOptions) { if (!options) { return nativeConnectDefault() } return this.connectDefaultWithOptions({...DEFAULT_CONNECT_OPTIONS, ...options}) } NativeBluetoothSdkModule.connect = function (device: Device, options?: ConnectOptions) { return this.connectWithOptions(device, {...DEFAULT_CONNECT_OPTIONS, ...options}) } const nativeStopScan = NativeBluetoothSdkModule.stopScan.bind(NativeBluetoothSdkModule) const activeScanCancellations = new Set<() => Promise>() NativeBluetoothSdkModule.stopScan = async function () { if (activeScanCancellations.size === 0) return nativeStopScan() await Promise.all([...activeScanCancellations].map((cancel) => cancel())) } NativeBluetoothSdkModule.scan = async function (modelOrOptions: DeviceModel | ScanOptions, options?: ScanModelOptions) { if (activeScanCancellations.size > 0) await this.stopScan() const scanOptions = normalizeScanArgs(modelOrOptions, options) const timeoutMs = normalizeTimeoutMs(scanOptions.timeoutMs ?? scanOptions.timeout, DEFAULT_SCAN_TIMEOUT_MS) const session = createScanSession( { start: (model) => this.startScan(model), stop: nativeStopScan, subscribe: (onResults) => this.onBluetoothStatus((status) => { if (Array.isArray(status.searchResults)) onResults(searchResultsForModel(status, scanOptions.model)) }), getResults: async () => searchResultsForModel(await this.getBluetoothStatus(), scanOptions.model), // Older native binaries simply omit diagnostics until the host is rebuilt. getDiagnostic: typeof this.getScanDiagnostic === "function" ? () => this.getScanDiagnostic!(scanOptions.model) : undefined, }, {...scanOptions, timeoutMs}, ) activeScanCancellations.add(session.cancel) try { return await session.result } finally { activeScanCancellations.delete(session.cancel) } } const nativeRequestPhoto = NativeBluetoothSdkModule.requestPhoto.bind(NativeBluetoothSdkModule) NativeBluetoothSdkModule.requestPhoto = function (params: PhotoRequestParams) { return nativeRequestPhoto(photoRequestParamsForNative(params) as unknown as PhotoRequestParams) } const nativeWarmUpCamera = NativeBluetoothSdkModule.warmUpCamera.bind(NativeBluetoothSdkModule) NativeBluetoothSdkModule.warmUpCamera = function (params: WarmUpCameraParams) { return nativeWarmUpCamera(warmUpCameraParamsForNative(params) as unknown as WarmUpCameraParams) } const nativeStartStream = bindNativeMethod<(params: StreamStartRequest) => Promise>( NativeBluetoothSdkModule as unknown as Record, "startStream", ) NativeBluetoothSdkModule.startStream = function (params: StreamStartRequest) { return nativeStartStream(streamRequestParamsForNative(params) as unknown as StreamStartRequest) } const nativeWearModule = NativeBluetoothSdkModule as unknown as Record NativeBluetoothSdkModule.queryWearState = bindNativeMethod<() => Promise>(nativeWearModule, "queryWearState") NativeBluetoothSdkModule.setWearReporting = bindNativeMethod<(enabled: boolean) => Promise>( nativeWearModule, "setWearReporting", ) NativeBluetoothSdkModule.setWearTuning = bindNativeMethod< (intervalMs: number, count: number, majority: number) => Promise >(nativeWearModule, "setWearTuning") NativeBluetoothSdkModule.requestWearTuning = bindNativeMethod<() => Promise>( nativeWearModule, "requestWearTuning", ) NativeBluetoothSdkModule.resetWearTuning = bindNativeMethod<() => Promise>(nativeWearModule, "resetWearTuning") NativeBluetoothSdkModule.sendBesCrashReported = bindNativeMethod< (incidentKey: string, reportId: string) => Promise >(NativeBluetoothSdkModule as unknown as Record, "sendBesCrashReported") export default NativeBluetoothSdkModule export const BluetoothSdk = NativeBluetoothSdkModule as BluetoothSdkInternalModule