@mentra/bluetooth-sdk 3.5.0-dev.1513 → 3.5.0-dev.1515

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 (74) hide show
  1. package/README.md +14 -30
  2. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +28 -3
  3. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +27 -16
  4. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +1 -0
  5. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
  6. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +69 -17
  7. package/android/src/main/java/com/mentra/bluetoothsdk/camera/CameraModels.kt +12 -12
  8. package/android/src/main/java/com/mentra/bluetoothsdk/camera/PhotoCapture.kt +115 -0
  9. package/android/src/main/java/com/mentra/bluetoothsdk/controllers/ControllerManager.kt +1 -1
  10. package/android/src/main/java/com/mentra/bluetoothsdk/controllers/R1.kt +1 -1
  11. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Ar99.java +2 -2
  12. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G1.kt +1 -1
  13. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G2.kt +2 -2
  14. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Mach1.kt +1 -1
  15. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +83 -27
  16. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraNex.kt +2 -2
  17. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +2 -2
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +1 -1
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Simulated.kt +2 -2
  20. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +7 -0
  21. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerSceneHandoffTest.kt +1 -1
  22. package/android/src/test/java/com/mentra/bluetoothsdk/camera/PhotoCaptureTest.kt +53 -0
  23. package/android/src/test/java/com/mentra/bluetoothsdk/camera/PhotoRequestTest.kt +0 -19
  24. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveFileTransferSessionTest.kt +16 -0
  25. package/build/BluetoothSdk.types.d.ts +56 -25
  26. package/build/BluetoothSdk.types.d.ts.map +1 -1
  27. package/build/BluetoothSdk.types.js.map +1 -1
  28. package/build/_private/BluetoothSdkModule.d.ts +5 -3
  29. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  30. package/build/_private/BluetoothSdkModule.js +50 -4
  31. package/build/_private/BluetoothSdkModule.js.map +1 -1
  32. package/build/_private/photoRequestPayload.d.ts +4 -2
  33. package/build/_private/photoRequestPayload.d.ts.map +1 -1
  34. package/build/_private/photoRequestPayload.js +11 -12
  35. package/build/_private/photoRequestPayload.js.map +1 -1
  36. package/build/generated/releaseMetadata.js +5 -5
  37. package/build/generated/releaseMetadata.js.map +1 -1
  38. package/build/index.d.ts +1 -1
  39. package/build/index.d.ts.map +1 -1
  40. package/build/index.js +4 -2
  41. package/build/index.js.map +1 -1
  42. package/ios/BluetoothSdkModule.swift +35 -3
  43. package/ios/Source/BluetoothSdkDefaults.swift +1 -1
  44. package/ios/Source/DeviceManager.swift +15 -3
  45. package/ios/Source/DeviceStore.swift +1 -0
  46. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  47. package/ios/Source/MentraBluetoothSDK.swift +60 -17
  48. package/ios/Source/camera/CameraModels.swift +17 -16
  49. package/ios/Source/camera/PhotoCapture.swift +118 -0
  50. package/ios/Source/controllers/ControllerManager.swift +1 -1
  51. package/ios/Source/controllers/R1.swift +1 -1
  52. package/ios/Source/sgcs/Ar99.swift +2 -2
  53. package/ios/Source/sgcs/Frame.swift +1 -1
  54. package/ios/Source/sgcs/G1.swift +1 -1
  55. package/ios/Source/sgcs/G2.swift +1 -1
  56. package/ios/Source/sgcs/Mach1.swift +1 -1
  57. package/ios/Source/sgcs/MentraLive.swift +84 -34
  58. package/ios/Source/sgcs/MentraLiveFileTransferSession.swift +5 -0
  59. package/ios/Source/sgcs/MentraNex.swift +1 -1
  60. package/ios/Source/sgcs/Nimo.swift +4 -4
  61. package/ios/Source/sgcs/SGCManager.swift +1 -1
  62. package/ios/Source/sgcs/Simulated.swift +2 -2
  63. package/ios/Source/status/DeviceStatus.swift +9 -0
  64. package/ios/Tests/DashboardRenderingTests.swift +1 -1
  65. package/ios/Tests/DeviceManagerReconnectTests.swift +1 -1
  66. package/ios/Tests/PhotoCaptureTests.swift +39 -0
  67. package/ios/Tests/PhotoLocalFileTests.swift +0 -7
  68. package/ios/Tests/PhotoRequestRoutingTests.swift +0 -14
  69. package/package.json +2 -2
  70. package/src/BluetoothSdk.types.ts +50 -25
  71. package/src/_private/BluetoothSdkModule.ts +68 -7
  72. package/src/_private/photoRequestPayload.ts +13 -13
  73. package/src/generated/releaseMetadata.ts +5 -5
  74. package/src/index.ts +9 -3
package/README.md CHANGED
@@ -238,7 +238,7 @@ Each usage occurrence below is one event, sent when it happens:
238
238
  `forget`, `cancel`, `bluetooth_off`, `link_lost`, or `unknown`), and the
239
239
  battery levels seen during the connection. A connection already up when the
240
240
  SDK started is not reported.
241
- - `bluetooth_sdk_photo_taken`: a `requestPhoto` call settled, or a photo taken
241
+ - `bluetooth_sdk_photo_taken`: an `uploadPhoto` call settled, or a photo taken
242
242
  with the glasses button failed (successful button photos never reach the
243
243
  phone). Carries `trigger` (`api` / `button`), `success`, `error_code`,
244
244
  `latency_ms`, the requested size, mode, compression, gallery save and
@@ -380,7 +380,7 @@ each event is sent from. PostHog receives a locally generated anonymous SDK inst
380
380
 
381
381
  React Native apps can import optional lifecycle helpers from the `react`
382
382
  subpath for common lifecycle plumbing. Use the root `BluetoothSdk` object for
383
- commands such as `requestPhoto()`, `startStream()`, and `setMicState()`.
383
+ commands such as `uploadPhoto()`, `startStream()`, and `setMicState()`.
384
384
 
385
385
  ```tsx
386
386
  import {Button, Text, View} from "react-native"
@@ -637,7 +637,7 @@ React Native narrows returned values to success shapes where the raw listener ev
637
637
 
638
638
  | API | Returned Value After `await` | Error Path |
639
639
  | --- | --- | --- |
640
- | `requestPhoto(...)` | Terminal `PhotoSuccessResponseEvent` with `state: "success"` after capture and delivery finish. `uploadUrl` is always present; webhook JSON metadata such as `photoUrl`, `statusUrl`, `contentType`, or `fileSizeBytes` is included when the receiver returns it. | Rejects when raw `photo_response.state === "error"`, the SDK cannot send the command, or the terminal photo response times out. |
640
+ | `uploadPhoto(...)` | Terminal `PhotoSuccessResponseEvent` with `state: "success"` after capture and delivery finish. `uploadUrl` is always present; webhook JSON metadata such as `photoUrl`, `statusUrl`, `contentType`, or `fileSizeBytes` is included when the receiver returns it. | Rejects when raw `photo_response.state === "error"`, the SDK cannot send the command, or the terminal photo response times out. |
641
641
  | `startVideoRecording(...)` | `VideoRecordingStartedStatusEvent` with `success: true` and `status: "recording_started"`. | Rejects on `success: false` statuses such as `already_recording`, send failure, or timeout. |
642
642
  | `stopVideoRecording(...)` | `VideoRecordingStoppedStatusEvent` with `success: true` and `status: "recording_stopped"`. When a webhook URL is supplied, resolves after the video upload succeeds. | Rejects on `success: false` statuses such as `not_recording`, webhook upload failure, send failure, or timeout. |
643
643
  | `queryVideoRecordingStatus(requestId)` | `VideoRecordingStatusEvent` with the current `recording` state and elapsed `duration_ms` when available. | Rejects when disconnected, another video command uses the same request ID, or the response times out. |
@@ -714,7 +714,7 @@ Mentra Live also rejects `ota_start` before acknowledgement when its known batte
714
714
  ## Photo Upload
715
715
 
716
716
  ```ts
717
- const photo = await BluetoothSdk.requestPhoto({
717
+ const photo = await BluetoothSdk.uploadPhoto({
718
718
  size: "medium",
719
719
  webhookUrl: "https://api.example.com/mentra/photo",
720
720
  authToken: "optional-token",
@@ -726,37 +726,21 @@ const photo = await BluetoothSdk.requestPhoto({
726
726
  console.log("photo delivered", photo.photoUrl ?? photo.uploadUrl, photo.fileSizeBytes)
727
727
  ```
728
728
 
729
- `requestPhoto(...)` resolves only after the full photo action reaches terminal success: capture completed and the photo was delivered to the webhook, either directly from the glasses over Wi-Fi or through the phone's Bluetooth fallback relay. If you omit `requestId`, the SDK generates one and the terminal response includes it. It rejects if the ASG reports `state: "error"`, if phone-side fallback upload fails, if the SDK cannot send the command, or if no terminal `photo_response` arrives within 30 seconds (110 seconds when `presend_thumbnail` is enabled). Photo requests use this longer operation-specific deadline because max-quality BLE fallback can legitimately exceed the 15-second deadline used by ordinary commands. Use `photo_status` for intermediate stages such as `accepted`, `configuring`, `capturing`, `captured`, `uploading`, `ble_fallback_compression`, `ready_for_transfer`, and `transferring`; `photo_status` is progress, while `photo_response` is terminal success/error. The raw `photo_response` event stream still includes both success and error events for subscribers. The webhook should accept multipart form data with a `photo` file and `requestId`. If `authToken` is provided, the uploader adds `Authorization: Bearer <token>`. The camera light is always enabled for photo capture.
729
+ `uploadPhoto(...)` resolves only after the full photo action reaches terminal success: capture completed and the photo was delivered to the webhook, either directly from the glasses over Wi-Fi or through the phone's Bluetooth fallback relay. If you omit `requestId`, the SDK generates one and the terminal response includes it. It rejects if the ASG reports `state: "error"`, if phone-side fallback upload fails, if the SDK cannot send the command, or if no terminal `photo_response` arrives within 30 seconds. Photo requests use this longer operation-specific deadline because max-quality BLE fallback can legitimately exceed the 15-second deadline used by ordinary commands. Use `photo_status` for intermediate stages such as `accepted`, `configuring`, `capturing`, `captured`, `uploading`, `ble_fallback_compression`, `ready_for_transfer`, and `transferring`; `photo_status` is progress, while `photo_response` is terminal success/error. The raw `photo_response` event stream still includes both success and error events for subscribers. The webhook should accept multipart form data with a `photo` file and `requestId`. If `authToken` is provided, the uploader adds `Authorization: Bearer <token>`. The camera light is always enabled for photo capture.
730
730
 
731
- To keep the photo on the phone and upload nothing, pass `localFile: true` and no `webhookUrl`:
731
+ To keep the photo on the phone and upload nothing, use `capturePhoto`. It returns at once with the capture's stages:
732
732
 
733
733
  ```ts
734
- const photo = await BluetoothSdk.requestPhoto({size: "medium", webhookUrl: null, authToken: null, sound: true, localFile: true})
735
- console.log("photo saved", photo.photoUrl, photo.fileSizeBytes) // file:///.../photo_<id>.jpg
734
+ const capture = BluetoothSdk.capturePhoto({size: "medium", sound: true})
735
+ await capture.captured // the camera is free for the next photo
736
+ const preview = await capture.preview // {url: "data:image/jpeg;base64,...", width, height}, at most 500 px
737
+ const photo = await capture.photo() // {requestId, fileUri: "file:///.../photo_<id>.jpg", mimeType, size}
738
+ await capture.release() // the full photo isn't needed (any more): the glasses delete it
736
739
  ```
737
740
 
738
- The glasses send the photo over Bluetooth, whatever `transferMethod` says, and the SDK saves it as a JPEG in the app's cache folder. `photoUrl` is that file's `file://` URI and `uploadUrl` is empty. The file is yours to move or delete. It needs no internet connection. A save failure rejects with `PHONE_SAVE_FAILED`.
739
-
740
- Set `presend_thumbnail: true` to receive a JPEG preview over Bluetooth before the
741
- full photo (default: `false`). Listen for `photo_status` with
742
- `status: "thumbnail_received"`; `thumbnailUrl` is a JPEG data URI and
743
- `fileSizeBytes` is the preview size. The preview preserves aspect ratio, is at
744
- most 500 pixels on its longest edge, never upscales, and uses JPEG quality 50.
745
- Preview pixels match the full delivered image's display orientation, including
746
- EXIF rotation/mirroring on direct uploads; no EXIF-aware preview renderer is needed.
747
- It does not resolve `requestPhoto()` or replace the full webhook delivery.
748
- The opted-in end-to-end deadline is 110 seconds: capture (45) + preview
749
- transfer/retries and ACK (30) + full delivery (30) + response transit margin (5).
750
- Both native SDK facades mirror ASG's constants; the glasses job watchdog is 105
751
- seconds. Progress and preview ACK never restart these timers.
752
- An upload target is required; save-only capture does not support previews.
753
- Compatible ASG firmware is required; older firmware may ignore this option.
754
-
755
- On the BLE delivery path, full-image encoding overlaps preview transmission,
756
- but the full image is sent only after the phone acknowledges the preview.
757
- Preview send failure or a missing acknowledgement fails the request rather than
758
- starting a competing transfer. ASG timing logs use `BlePhotoTiming`; thumbnail
759
- transmission and CPU processing overlap, so their durations are not additive.
741
+ `takePhoto(options)` is `capturePhoto(options).photo()` followed by `release()`: the whole photo, and the glasses' copy deleted.
742
+
743
+ Every photo gets its preview first. The full photo waits on the glasses (deferred delivery) until the first `photo()` call asks for it, for 30 minutes at most; later calls return the same photo, and not calling `photo()` is how a photo is skipped. The file is in the app's cache folder and is yours to move or delete. It needs no internet connection. Any number of captures can be in flight: the glasses refuse one (`CAMERA_BUSY`) only while another is being taken, never because photos are being sent. After the glasses restart or reconnect, the SDK asks again for the previews and photos it still waits for. A preview that didn't arrive rejects `preview` with `PREVIEW_FAILED`; the full photo can still be asked for. Glasses without deferred photos (`deferredPhotosVersion` 0 in the glasses status) send the whole photo at once: `photo()` resolves with it, and it is also the preview.
760
744
 
761
745
  For one-shot manual capture tuning, pass `exposureTimeNs` and `iso` together. `exposureTimeNs` is sensor exposure time in nanoseconds; `iso` is sensor ISO. If `exposureTimeNs` is omitted, `null`, invalid, or unsupported by the connected glasses, the camera uses auto exposure and ignores `iso`.
762
746
 
@@ -131,6 +131,8 @@ private inline fun <
131
131
  }
132
132
 
133
133
  class BluetoothSdkModule : Module() {
134
+ private val photoCaptures = java.util.concurrent.ConcurrentHashMap<String, PhotoCapture>()
135
+
134
136
  private var sdk: MentraBluetoothSdk? = null
135
137
  private var deviceManager: DeviceManager? = null
136
138
  private val logForwarding = LogForwardingBudget()
@@ -763,12 +765,12 @@ class BluetoothSdkModule : Module() {
763
765
 
764
766
  SdkCoroutineFunction("queryGalleryStatus") { -> requireSdk().queryGalleryStatus().values }
765
767
 
766
- SdkCoroutineFunction("requestPhoto") { params: Map<String, Any?> ->
768
+ SdkCoroutineFunction("uploadPhoto") { params: Map<String, Any?> ->
767
769
  val req = PhotoRequest.fromMap(params)
768
770
  Bridge.log(
769
- "NATIVE: PHOTO PIPELINE [3/6] BluetoothSdk.requestPhoto requestId=${req.requestId} size=${req.size} mode=${req.mode.value} compress=${req.compress} sound=${req.sound} exposureTimeNs=${req.exposureTimeNs} iso=${req.iso}"
771
+ "NATIVE: PHOTO PIPELINE [3/6] BluetoothSdk.uploadPhoto requestId=${req.requestId} size=${req.size} mode=${req.mode.value} compress=${req.compress} sound=${req.sound} exposureTimeNs=${req.exposureTimeNs} iso=${req.iso}"
770
772
  )
771
- requireSdk().requestPhoto(req).values
773
+ requireSdk().uploadPhoto(req).values
772
774
  }
773
775
 
774
776
  SdkCoroutineFunction("warmUpCamera") { params: Map<String, Any?> ->
@@ -789,6 +791,29 @@ class BluetoothSdkModule : Module() {
789
791
  requireSdk().stopCameraWarmUp(requestId)
790
792
  }
791
793
 
794
+ // A capture's stages, by its request ID: the JS PhotoCapture awaits each one.
795
+ SdkAsyncFunction("capturePhoto") { params: Map<String, Any?> ->
796
+ val capture = requireSdk().capturePhoto(PhotoRequest.fromMap(params))
797
+ val cutoff = System.currentTimeMillis() - 30 * 60_000L
798
+ photoCaptures.values.removeIf { it.createdAtMs < cutoff }
799
+ photoCaptures[capture.requestId] = capture
800
+ capture.requestId
801
+ }
802
+
803
+ SdkCoroutineFunction("photoCaptureStage") { requestId: String, stage: String ->
804
+ val capture = photoCaptures[requestId]
805
+ ?: throw BluetoothSdkException("photo_released", "No photo capture $requestId.")
806
+ when (stage) {
807
+ "captured" -> capture.captured().let { null }
808
+ "preview" -> capture.preview().values
809
+ else -> capture.photo().values
810
+ }
811
+ }
812
+
813
+ SdkAsyncFunction("releasePhotoCapture") { requestId: String ->
814
+ photoCaptures.remove(requestId)?.release()
815
+ }
816
+
792
817
  // MARK: - OTA Commands
793
818
 
794
819
  SdkFunction("setOtaVersionUrl") { otaVersionUrl: String ->
@@ -2186,6 +2186,16 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2186
2186
  live.stopCameraWarmUp(requestId)
2187
2187
  }
2188
2188
 
2189
+ private fun liveForPhotos(): MentraLive =
2190
+ sgc as? MentraLive
2191
+ ?: throw BluetoothSdkException("unsupported_device", "This command requires Mentra Live glasses.")
2192
+
2193
+ fun capturePhoto(request: PhotoRequest, deferred: Boolean) = liveForPhotos().capturePhoto(routedForCapture(request), deferred)
2194
+
2195
+ fun fetchPhoto(request: PhotoRequest, preview: Boolean) = liveForPhotos().fetchPhoto(request, preview)
2196
+
2197
+ fun releasePhotos(requestIds: List<String>?) = liveForPhotos().releasePhotos(requestIds)
2198
+
2189
2199
  /**
2190
2200
  * Read glasses media step volume (0—5) via K900 on Mentra Live only. Blocks until response,
2191
2201
  * error, or timeout (used from JS AsyncFunction on a worker thread).
@@ -2305,22 +2315,10 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2305
2315
  updateMicState()
2306
2316
  }
2307
2317
 
2308
- fun requestPhoto(request: PhotoRequest) {
2309
- val exposureNs: Long? =
2310
- request.exposureTimeNs?.takeIf { it.isFinite() && it > 0 }?.let { v ->
2311
- when {
2312
- v > Long.MAX_VALUE.toDouble() -> Long.MAX_VALUE
2313
- else -> v.toLong()
2314
- }
2315
- }
2316
- val manualIso = if (exposureNs != null) request.iso?.takeIf { it > 0 } else null
2317
- val routed =
2318
- request.copy(
2319
- exposureTimeNs = exposureNs?.toDouble(),
2320
- iso = manualIso,
2321
- )
2318
+ fun uploadPhoto(request: PhotoRequest) {
2319
+ val routed = routedForCapture(request)
2322
2320
  Bridge.log(
2323
- "MAN: PHOTO PIPELINE [4/6] DeviceManager.requestPhoto requestId=${routed.requestId} size=${routed.size.value} mode=${routed.mode.value} compress=${routed.compress.value} save=${routed.save} sound=${routed.sound} exposureTimeNs=$exposureNs iso=${manualIso ?: "auto"} aeDivisor=${routed.aeExposureDivisor} isoCap=${routed.isoCap} sgc=${sgc?.javaClass?.simpleName ?: "null"}"
2321
+ "MAN: PHOTO PIPELINE [4/6] DeviceManager.uploadPhoto requestId=${routed.requestId} size=${routed.size.value} mode=${routed.mode.value} compress=${routed.compress.value} save=${routed.save} sound=${routed.sound} exposureTimeNs=${routed.exposureTimeNs} iso=${routed.iso ?: "auto"} aeDivisor=${routed.aeExposureDivisor} isoCap=${routed.isoCap} sgc=${sgc?.javaClass?.simpleName ?: "null"}"
2324
2322
  )
2325
2323
  val activeSgc = sgc
2326
2324
  if (activeSgc == null) {
@@ -2329,7 +2327,20 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2329
2327
  )
2330
2328
  return
2331
2329
  }
2332
- activeSgc.requestPhoto(routed)
2330
+ activeSgc.uploadPhoto(routed)
2331
+ }
2332
+
2333
+ /** A manual exposure only when it is valid, and its ISO only with it. */
2334
+ private fun routedForCapture(request: PhotoRequest): PhotoRequest {
2335
+ val exposureNs: Long? =
2336
+ request.exposureTimeNs?.takeIf { it.isFinite() && it > 0 }?.let { v ->
2337
+ when {
2338
+ v > Long.MAX_VALUE.toDouble() -> Long.MAX_VALUE
2339
+ else -> v.toLong()
2340
+ }
2341
+ }
2342
+ val manualIso = if (exposureNs != null) request.iso?.takeIf { it > 0 } else null
2343
+ return request.copy(exposureTimeNs = exposureNs?.toDouble(), iso = manualIso)
2333
2344
  }
2334
2345
 
2335
2346
  fun rgbLedControl(
@@ -77,6 +77,7 @@ object DeviceStore {
77
77
  store.set("glasses", "deviceModel", "")
78
78
  store.set("glasses", "firmwareVersion", "")
79
79
  store.set("glasses", "hotspotOtaVersion", 0)
80
+ store.set("glasses", "deferredPhotosVersion", 0)
80
81
  store.set("glasses", "micEnabled", false)
81
82
  store.set("glasses", "voiceActivityDetectionEnabled", BluetoothSdkDefaults.VOICE_ACTIVITY_DETECTION_ENABLED)
82
83
  store.set("glasses", "bluetoothClassicConnected", false)
@@ -3,9 +3,9 @@ package com.mentra.bluetoothsdk
3
3
  /** Generated by release CI. Do not edit in a release checkout. */
4
4
  internal object GeneratedReleaseMetadata {
5
5
  const val FAMILY_BASE_VERSION: String = "3.5.0"
6
- const val RELEASE_IDENTITY: String = "3.5.0-dev.1513"
7
- const val RELEASE_SET_ID: String = "mentra-3.5.0-dev.1513"
8
- const val SOURCE_COMMIT: String = "027fbe5f4c4109d8b48bc3aac3982ec69f99ae90"
9
- const val OTA_MANIFEST_URL: String = "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.5.0/mentra-live-ota-3.5.0-dev.1513.json"
10
- const val OTA_MANIFEST_SHA256: String = "1ffa737ac3a6141e4bda0055188ed608c555100f3e0ab90ecda72f0877e9b45b"
6
+ const val RELEASE_IDENTITY: String = "3.5.0-dev.1515"
7
+ const val RELEASE_SET_ID: String = "mentra-3.5.0-dev.1515"
8
+ const val SOURCE_COMMIT: String = "709922bb8d64421fe5a7e74b44c0a66cd6ef8691"
9
+ const val OTA_MANIFEST_URL: String = "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.5.0/mentra-live-ota-3.5.0-dev.1515.json"
10
+ const val OTA_MANIFEST_SHA256: String = "c5eedb9b905e2dde68a8cdf9a789479c925f9b8c0c19d0b4644e6df86e0a1d6f"
11
11
  }
@@ -136,15 +136,6 @@ class MentraBluetoothSdk private constructor(
136
136
  // A photo response is terminal only after capture, encoding, transport, and upload.
137
137
  // Max-quality BLE fallback can legitimately exceed the generic command deadline.
138
138
  private const val PHOTO_REQUEST_TIMEOUT_MS = 30_000L
139
- // Mirrors AsgConstants.PHOTO_THUMBNAIL_REQUEST_TIMEOUT_MS and the iOS facade.
140
- // Reserve capture, preview ACK/retries, full delivery, then terminal-event transit.
141
- private const val PHOTO_CAPTURE_TIMEOUT_MS = 45_000L
142
- private const val PHOTO_THUMBNAIL_TIMEOUT_SECONDS = 30L
143
- private const val PHOTO_DELIVERY_TIMEOUT_MS = 30_000L
144
- private const val PHOTO_RESPONSE_MARGIN_MS = 5_000L
145
- private const val PHOTO_THUMBNAIL_REQUEST_TIMEOUT_MS =
146
- PHOTO_CAPTURE_TIMEOUT_MS + PHOTO_THUMBNAIL_TIMEOUT_SECONDS * 1000L +
147
- PHOTO_DELIVERY_TIMEOUT_MS + PHOTO_RESPONSE_MARGIN_MS
148
139
  private const val WIFI_SCAN_TIMEOUT_MS = 20_000L
149
140
  private const val VIDEO_UPLOAD_STOP_TIMEOUT_MS = 10 * 60 * 1000L
150
141
  private const val STREAM_START_TIMEOUT_MS = 30_000L
@@ -702,7 +693,7 @@ class MentraBluetoothSdk private constructor(
702
693
  @Deprecated(
703
694
  message =
704
695
  "Sticky action-button photo presets are deprecated. Prefer per-request " +
705
- "requestPhoto(...) options (e.g. mode=TEXT for text sensor size/crop, or explicit per-shot fields). " +
696
+ "uploadPhoto(...) options (e.g. mode=TEXT for text sensor size/crop, or explicit per-shot fields). " +
706
697
  "This method still works but will be removed in a future release.",
707
698
  )
708
699
  suspend fun setPhotoCaptureDefaults(settings: PhotoCaptureDefaults): SettingsAckEvent =
@@ -1137,13 +1128,17 @@ class MentraBluetoothSdk private constructor(
1137
1128
  deviceManager.setSystemTime(timestampMs)
1138
1129
  }
1139
1130
 
1140
- suspend fun requestPhoto(request: PhotoRequest): PhotoResponseEvent {
1131
+ /**
1132
+ * A photo sent to [PhotoRequest.webhookUrl]: uploaded by the glasses over their own Wi-Fi, or
1133
+ * relayed by the phone over Bluetooth. A photo kept on the phone is [takePhoto].
1134
+ */
1135
+ suspend fun uploadPhoto(request: PhotoRequest): PhotoResponseEvent {
1141
1136
  val routedRequest =
1142
1137
  nonBlankRequestId(request.requestId)
1143
1138
  ?.let { if (it == request.requestId) request else request.copy(requestId = it) }
1144
1139
  ?: request.copy(requestId = generatedCameraRequestId("photo"))
1145
1140
  Bridge.log(
1146
- "NATIVE: PHOTO PIPELINE [3b/6] MentraBluetoothSdk.requestPhoto requestId=${routedRequest.requestId}"
1141
+ "NATIVE: PHOTO PIPELINE [3b/6] MentraBluetoothSdk.uploadPhoto requestId=${routedRequest.requestId}"
1147
1142
  )
1148
1143
  val pending = PendingResponse<PhotoResponseEvent>("photo request ${routedRequest.requestId}", "photo request")
1149
1144
  pendingPhotoRequests[routedRequest.requestId] = pending
@@ -1165,10 +1160,8 @@ class MentraBluetoothSdk private constructor(
1165
1160
  }
1166
1161
  },
1167
1162
  ) {
1168
- deviceManager.requestPhoto(routedRequest)
1169
- pending.await(
1170
- if (routedRequest.presendThumbnail) PHOTO_THUMBNAIL_REQUEST_TIMEOUT_MS else PHOTO_REQUEST_TIMEOUT_MS,
1171
- )
1163
+ deviceManager.uploadPhoto(routedRequest)
1164
+ pending.await(PHOTO_REQUEST_TIMEOUT_MS)
1172
1165
  }
1173
1166
  } finally {
1174
1167
  pendingPhotoRequests.remove(routedRequest.requestId, pending)
@@ -1202,6 +1195,52 @@ class MentraBluetoothSdk private constructor(
1202
1195
  }
1203
1196
  }
1204
1197
 
1198
+ private val photoCaptures = ConcurrentHashMap<String, PhotoCapture>()
1199
+
1200
+ private val captureGlasses =
1201
+ object : PhotoCapture.Glasses {
1202
+ override fun fetch(request: PhotoRequest, preview: Boolean) = deviceManager.fetchPhoto(request, preview)
1203
+
1204
+ override fun release(requestId: String) = deviceManager.releasePhotos(listOf(requestId))
1205
+
1206
+ override fun forget(requestId: String) {
1207
+ photoCaptures.remove(requestId)
1208
+ }
1209
+ }
1210
+
1211
+ /** A photo kept on the phone, whole: [capturePhoto], its [PhotoCapture.photo], then its release. */
1212
+ suspend fun takePhoto(request: PhotoRequest): PhotoResponseEvent {
1213
+ val capture = capturePhoto(request)
1214
+ try {
1215
+ return capture.photo()
1216
+ } finally {
1217
+ capture.release()
1218
+ }
1219
+ }
1220
+
1221
+ /**
1222
+ * Take a photo that is kept on the phone, in stages: see [PhotoCapture]. Any number can be in
1223
+ * flight: the glasses refuse a capture only while another one is being taken (`CAMERA_BUSY`).
1224
+ */
1225
+ fun capturePhoto(request: PhotoRequest): PhotoCapture {
1226
+ val routed =
1227
+ nonBlankRequestId(request.requestId)
1228
+ ?.let { if (it == request.requestId) request else request.copy(requestId = it) }
1229
+ ?: request.copy(requestId = generatedCameraRequestId("photo"))
1230
+ // The glasses keep a photo 30 minutes; nothing arrives for an older capture.
1231
+ val cutoff = System.currentTimeMillis() - 30 * 60_000L
1232
+ photoCaptures.values.removeIf { it.done || it.createdAtMs < cutoff }
1233
+ val capture = PhotoCapture(routed, getRawGlassesStatus().deferredPhotosVersion > 0, captureGlasses)
1234
+ photoCaptures[routed.requestId] = capture
1235
+ try {
1236
+ deviceManager.capturePhoto(routed, getRawGlassesStatus().deferredPhotosVersion > 0)
1237
+ } catch (e: Exception) {
1238
+ photoCaptures.remove(routed.requestId)
1239
+ throw e
1240
+ }
1241
+ return capture
1242
+ }
1243
+
1205
1244
  fun stopCameraWarmUp(requestId: String) {
1206
1245
  val effectiveRequestId = nonBlankRequestId(requestId)
1207
1246
  ?: throw BluetoothSdkException("invalid_request", "A warm-up request ID is required.")
@@ -2000,13 +2039,26 @@ class MentraBluetoothSdk private constructor(
2000
2039
  "photo_response" -> {
2001
2040
  val event = PhotoResponseEvent(data)
2002
2041
  handlePhotoResponseForRequests(event)
2042
+ photoCaptures[event.requestId]?.onResponse(event)
2003
2043
  val response = event.response
2004
2044
  if (response is PhotoResponse.Error && event.requestId == BluetoothSdkUsageTracker.LOCAL_PHOTO_REQUEST_ID) {
2005
2045
  analytics.recordUsage { buttonPhotoFailed(response.errorCode) }
2006
2046
  }
2007
2047
  dispatchToListeners { it.onPhotoResponse(event) }
2008
2048
  }
2009
- "photo_status" -> dispatchToListeners { it.onPhotoStatus(PhotoStatusEvent(data)) }
2049
+ "photo_status" -> {
2050
+ val event = PhotoStatusEvent(data)
2051
+ photoCaptures[event.requestId]?.onStatus(event)
2052
+ dispatchToListeners { it.onPhotoStatus(event) }
2053
+ }
2054
+ "photo_preview" -> {
2055
+ val requestId = data["requestId"] as? String ?: ""
2056
+ val url = data["url"] as? String ?: ""
2057
+ photoCaptures[requestId]?.onPreview(
2058
+ PhotoPreview(url, (data["width"] as? Number)?.toInt(), (data["height"] as? Number)?.toInt()),
2059
+ )
2060
+ }
2061
+ "glasses_ready" -> photoCaptures.values.forEach { it.resume() }
2010
2062
  "camera_status" -> {
2011
2063
  val event = CameraStatusEvent(data)
2012
2064
  handleCameraStatusForRequests(event)
@@ -203,7 +203,8 @@ enum class PhotoMode(val value: String) {
203
203
  data class PhotoRequest @JvmOverloads constructor(
204
204
  val requestId: String = generatedCameraRequestId("photo"),
205
205
  val size: PhotoSize,
206
- val webhookUrl: String,
206
+ /** Where the glasses (or the phone, over BLE) upload the photo; ignored by `capturePhoto`. */
207
+ val webhookUrl: String = "",
207
208
  val authToken: String? = null,
208
209
  val compress: PhotoCompression = PhotoCompression.NONE,
209
210
  val save: Boolean = false,
@@ -224,13 +225,6 @@ data class PhotoRequest @JvmOverloads constructor(
224
225
  val mode: PhotoMode = PhotoMode.PHOTO,
225
226
  /** `direct` disables BLE fallback; `ble` skips direct upload; `auto` tries both. */
226
227
  val transferMethod: String = "auto",
227
- val presendThumbnail: Boolean = false,
228
- /**
229
- * Keep the photo on the phone: it comes over BLE, is saved as a JPEG file, and the
230
- * success response carries that file's URI as `photoUrl`. Nothing is uploaded, and
231
- * `webhookUrl` and `transferMethod` are ignored.
232
- */
233
- val localFile: Boolean = false,
234
228
  ) {
235
229
  companion object {
236
230
  private fun transferMethodFromValue(value: Any?): String {
@@ -282,8 +276,6 @@ data class PhotoRequest @JvmOverloads constructor(
282
276
  sound = boolValue(values, "sound") ?: true,
283
277
  mode = PhotoMode.fromValue(stringValue(values, "mode")),
284
278
  transferMethod = transferMethodFromValue(values["transferMethod"]),
285
- presendThumbnail = boolValue(values, "presend_thumbnail") ?: false,
286
- localFile = boolValue(values, "localFile") ?: false,
287
279
  exposureTimeNs = exposureTimeNs,
288
280
  iso = iso,
289
281
  aeExposureDivisor = aeDivisor,
@@ -482,6 +474,16 @@ private fun Map<String, Any>.withOptionalPhotoMetadata(
482
474
  success.fileSizeBytes?.let { this["fileSizeBytes"] = it }
483
475
  }
484
476
 
477
+ /** A photo's preview: the glasses' at most 500 px JPEG, as a `data:image/jpeg;base64,` URL. */
478
+ data class PhotoPreview(val url: String, val width: Int?, val height: Int?) {
479
+ val values: Map<String, Any>
480
+ get() = buildMap {
481
+ put("url", url)
482
+ width?.let { put("width", it) }
483
+ height?.let { put("height", it) }
484
+ }
485
+ }
486
+
485
487
  data class PhotoResponseEvent(
486
488
  val response: PhotoResponse,
487
489
  ) {
@@ -494,8 +496,6 @@ data class PhotoResponseEvent(
494
496
  data class PhotoStatusEvent(
495
497
  val values: Map<String, Any>,
496
498
  ) {
497
- val thumbnailUrl: String? get() = stringValue(values, "thumbnailUrl")
498
- val fileSizeBytes: Long? get() = longValue(values, "fileSizeBytes")
499
499
  val requestId: String get() = stringValue(values, "requestId").orEmpty()
500
500
  val status: String get() = stringValue(values, "status").orEmpty()
501
501
  val timestamp: Long get() = longValue(values, "timestamp") ?: System.currentTimeMillis()
@@ -0,0 +1,115 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ import android.graphics.BitmapFactory
4
+ import android.net.Uri
5
+ import java.util.concurrent.atomic.AtomicBoolean
6
+ import kotlinx.coroutines.CompletableDeferred
7
+ import kotlinx.coroutines.withTimeoutOrNull
8
+
9
+ /**
10
+ * One photo kept on the phone, in stages. [captured]: the camera is done and free for the next
11
+ * one. [preview]: the glasses' at most 500 px preview. [photo]: the full photo as a file; the first
12
+ * call asks the glasses to send it, and until then it waits on the glasses ("deferred delivery").
13
+ * [release]: the full photo isn't needed, and the glasses delete it. Glasses without deferred
14
+ * photos send the whole photo at once; it is then also the preview.
15
+ */
16
+ class PhotoCapture internal constructor(
17
+ val request: PhotoRequest,
18
+ private val deferred: Boolean,
19
+ private val glasses: Glasses,
20
+ ) {
21
+ internal interface Glasses {
22
+ fun fetch(request: PhotoRequest, preview: Boolean)
23
+
24
+ fun release(requestId: String)
25
+
26
+ fun forget(requestId: String)
27
+ }
28
+
29
+ val requestId: String get() = request.requestId
30
+ internal val createdAtMs = System.currentTimeMillis()
31
+ private val capturedStage = CompletableDeferred<Unit>()
32
+ private val previewStage = CompletableDeferred<PhotoPreview>()
33
+ private val photoStage = CompletableDeferred<PhotoResponseEvent>()
34
+ private val photoAsked = AtomicBoolean(!deferred)
35
+
36
+ /** Resolves once the glasses wrote the photo: the camera takes the next request. */
37
+ suspend fun captured() = await(capturedStage, CAPTURED_TIMEOUT_MS, "capture")
38
+
39
+ suspend fun preview(): PhotoPreview = await(previewStage, STAGE_TIMEOUT_MS, "preview")
40
+
41
+ /** The full photo; `photoUrl` is a `file://` URI in the app's cache folder, the caller's to move. */
42
+ suspend fun photo(): PhotoResponseEvent {
43
+ if (photoAsked.compareAndSet(false, true)) glasses.fetch(request, preview = false)
44
+ return await(photoStage, STAGE_TIMEOUT_MS, "photo")
45
+ }
46
+
47
+ /** The full photo isn't needed: the glasses delete it. Stages not reached yet fail. */
48
+ fun release() {
49
+ glasses.forget(requestId)
50
+ // The glasses keep the photo after sending it, so a released one goes even once fetched.
51
+ if (deferred) glasses.release(requestId)
52
+ fail(BluetoothSdkException("photo_released", "The photo was released."))
53
+ }
54
+
55
+ internal val done: Boolean
56
+ get() = capturedStage.isCompleted && previewStage.isCompleted && photoStage.isCompleted
57
+
58
+ internal fun onStatus(event: PhotoStatusEvent) {
59
+ if (event.status == "captured") capturedStage.complete(Unit)
60
+ }
61
+
62
+ internal fun onPreview(preview: PhotoPreview) {
63
+ previewStage.complete(preview)
64
+ }
65
+
66
+ internal fun onResponse(event: PhotoResponseEvent) {
67
+ when (val response = event.response) {
68
+ is PhotoResponse.Success -> {
69
+ capturedStage.complete(Unit)
70
+ if (!deferred) previewStage.complete(previewOf(response))
71
+ photoStage.complete(event)
72
+ }
73
+ is PhotoResponse.Error -> {
74
+ val error = BluetoothSdkException(response.errorCode ?: "photo_request_failed", response.errorMessage)
75
+ when {
76
+ !capturedStage.isCompleted -> fail(error)
77
+ // Only the preview failed: the photo is still on the glasses.
78
+ response.errorCode == "PREVIEW_FAILED" -> previewStage.completeExceptionally(error)
79
+ else -> photoStage.completeExceptionally(error)
80
+ }
81
+ }
82
+ }
83
+ }
84
+
85
+ /** The glasses are back after a reconnect or restart: ask again for what is still awaited. */
86
+ internal fun resume() {
87
+ if (!deferred || !capturedStage.isCompleted) return
88
+ if (!previewStage.isCompleted) glasses.fetch(request, preview = true)
89
+ if (photoAsked.get() && !photoStage.isCompleted) glasses.fetch(request, preview = false)
90
+ }
91
+
92
+ private fun fail(error: Throwable) {
93
+ capturedStage.completeExceptionally(error)
94
+ previewStage.completeExceptionally(error)
95
+ photoStage.completeExceptionally(error)
96
+ }
97
+
98
+ private suspend fun <T> await(stage: CompletableDeferred<T>, timeoutMs: Long, name: String): T =
99
+ withTimeoutOrNull(timeoutMs) { stage.await() }
100
+ ?: throw BluetoothSdkException("request_timeout", "Photo $name timed out waiting for the glasses.")
101
+
102
+ /** Older glasses send no preview: the whole photo stands in, with its pixel size. */
103
+ private fun previewOf(response: PhotoResponse.Success): PhotoPreview {
104
+ val url = response.photoUrl.orEmpty()
105
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
106
+ Uri.parse(url).path?.let { BitmapFactory.decodeFile(it, bounds) }
107
+ return PhotoPreview(url, bounds.outWidth.takeIf { it > 0 }, bounds.outHeight.takeIf { it > 0 })
108
+ }
109
+
110
+ private companion object {
111
+ const val CAPTURED_TIMEOUT_MS = 45_000L
112
+ // Capture, preview ACK and retries, then the send queue's wait behind other photos.
113
+ const val STAGE_TIMEOUT_MS = 110_000L
114
+ }
115
+ }
@@ -16,7 +16,7 @@ abstract class ControllerManager {
16
16
  abstract fun sendJson(jsonOriginal: Map<String, Any>, wakeUp: Boolean, requireAck: Boolean)
17
17
 
18
18
  // Camera & Media
19
- abstract fun requestPhoto(request: PhotoRequest)
19
+ abstract fun uploadPhoto(request: PhotoRequest)
20
20
  abstract fun startStream(message: Map<String, Any>)
21
21
  abstract fun stopStream()
22
22
  abstract fun sendStreamKeepAlive(message: Map<String, Any>)
@@ -862,7 +862,7 @@ class R1 : ControllerManager() {
862
862
  override fun setMicEnabled(enabled: Boolean) {}
863
863
  override fun sortMicRanking(list: MutableList<String>): MutableList<String> = list
864
864
  override fun sendJson(jsonOriginal: Map<String, Any>, wakeUp: Boolean, requireAck: Boolean) {}
865
- override fun requestPhoto(request: PhotoRequest) {}
865
+ override fun uploadPhoto(request: PhotoRequest) {}
866
866
  override fun startVideoRecording(requestId: String, save: Boolean, sound: Boolean) {}
867
867
  override fun stopVideoRecording(requestId: String) {}
868
868
  override fun startStream(message: Map<String, Any>) {}
@@ -434,8 +434,8 @@ public class Ar99 extends SGCManager {
434
434
  }
435
435
 
436
436
  @Override
437
- public void requestPhoto(PhotoRequest request) {
438
- Bridge.log(TAG + ": requestPhoto not implemented for AR99 yet");
437
+ public void uploadPhoto(PhotoRequest request) {
438
+ Bridge.log(TAG + ": uploadPhoto not implemented for AR99 yet");
439
439
  }
440
440
 
441
441
  @Override
@@ -1568,7 +1568,7 @@ class G1 : SGCManager() {
1568
1568
 
1569
1569
  }
1570
1570
 
1571
- override fun requestPhoto(request: PhotoRequest) {
1571
+ override fun uploadPhoto(request: PhotoRequest) {
1572
1572
 
1573
1573
  }
1574
1574
 
@@ -3623,8 +3623,8 @@ class G2 : SGCManager() {
3623
3623
  }
3624
3624
 
3625
3625
  // Camera & Media - G2 has no camera
3626
- override fun requestPhoto(request: PhotoRequest) {
3627
- Bridge.log("G2: requestPhoto - not supported (no camera)")
3626
+ override fun uploadPhoto(request: PhotoRequest) {
3627
+ Bridge.log("G2: uploadPhoto - not supported (no camera)")
3628
3628
  }
3629
3629
 
3630
3630
  override fun startStream(message: MutableMap<String, Any>) {
@@ -167,7 +167,7 @@ class Mach1 : SGCManager() {
167
167
  return list
168
168
  }
169
169
 
170
- override fun requestPhoto(request: PhotoRequest) {
170
+ override fun uploadPhoto(request: PhotoRequest) {
171
171
 
172
172
  }
173
173