@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
@@ -1785,6 +1785,18 @@ struct ViewState {
1785
1785
  try liveSgc().stopCameraWarmUp(requestId: requestId)
1786
1786
  }
1787
1787
 
1788
+ func capturePhoto(_ request: PhotoRequest, deferred: Bool) throws {
1789
+ try liveSgc().capturePhoto(request.routedForCapture(), deferred: deferred)
1790
+ }
1791
+
1792
+ func fetchPhoto(_ request: PhotoRequest, preview: Bool) throws {
1793
+ try liveSgc().fetchPhoto(request, preview: preview)
1794
+ }
1795
+
1796
+ func releasePhotos(requestIds: [String]?) throws {
1797
+ try liveSgc().releasePhotos(requestIds: requestIds)
1798
+ }
1799
+
1788
1800
  /// Request version info from glasses.
1789
1801
  /// Glasses will respond with version_info message containing build number, firmware version, etc.
1790
1802
  func requestVersionInfo(requestId: String? = nil) {
@@ -1899,10 +1911,10 @@ struct ViewState {
1899
1911
  }
1900
1912
  }
1901
1913
 
1902
- func requestPhoto(_ request: PhotoRequest) {
1914
+ func uploadPhoto(_ request: PhotoRequest) {
1903
1915
  let routed = request.routedForCapture()
1904
1916
  Bridge.log(
1905
- "MAN: PHOTO PIPELINE [4/6] DeviceManager.requestPhoto requestId=\(routed.requestId) webhookUrl=\(routed.webhookUrl ?? "nil") size=\(routed.size.rawValue) compress=\(routed.compress.rawValue) save=\(routed.save) sound=\(routed.sound) exposureTimeNs=\(routed.exposureTimeNs.map { String($0) } ?? "nil") iso=\(routed.iso.map { String($0) } ?? "auto") aeDivisor=\(routed.aeExposureDivisor.map { String($0) } ?? "nil") isoCap=\(routed.isoCap.map { String($0) } ?? "nil") sgc=\(sgc != nil ? String(describing: type(of: sgc!)) : "null")"
1917
+ "MAN: PHOTO PIPELINE [4/6] DeviceManager.uploadPhoto requestId=\(routed.requestId) webhookUrl=\(routed.webhookUrl ?? "nil") size=\(routed.size.rawValue) compress=\(routed.compress.rawValue) save=\(routed.save) sound=\(routed.sound) exposureTimeNs=\(routed.exposureTimeNs.map { String($0) } ?? "nil") iso=\(routed.iso.map { String($0) } ?? "auto") aeDivisor=\(routed.aeExposureDivisor.map { String($0) } ?? "nil") isoCap=\(routed.isoCap.map { String($0) } ?? "nil") sgc=\(sgc != nil ? String(describing: type(of: sgc!)) : "null")"
1906
1918
  )
1907
1919
  guard let sgc else {
1908
1920
  Bridge.log(
@@ -1910,7 +1922,7 @@ struct ViewState {
1910
1922
  )
1911
1923
  return
1912
1924
  }
1913
- sgc.requestPhoto(routed)
1925
+ sgc.uploadPhoto(routed)
1914
1926
  }
1915
1927
 
1916
1928
  func connectDefault(requiresAncs: Bool = true) {
@@ -28,6 +28,7 @@ class DeviceStore {
28
28
  store.set("glasses", "deviceModel", "")
29
29
  store.set("glasses", "firmwareVersion", "")
30
30
  store.set("glasses", "hotspotOtaVersion", 0)
31
+ store.set("glasses", "deferredPhotosVersion", 0)
31
32
  store.set("glasses", "micEnabled", false)
32
33
  store.set("glasses", "voiceActivityDetectionEnabled", BluetoothSdkDefaults.voiceActivityDetectionEnabled)
33
34
  store.set("glasses", "bluetoothClassicConnected", false)
@@ -3,9 +3,9 @@ import Foundation
3
3
  /// Generated by release CI. Do not edit in a release checkout.
4
4
  enum GeneratedReleaseMetadata {
5
5
  static let familyBaseVersion = "3.5.0"
6
- static let releaseIdentity = "3.5.0-dev.1513"
7
- static let releaseSetId = "mentra-3.5.0-dev.1513"
8
- static let sourceCommit = "027fbe5f4c4109d8b48bc3aac3982ec69f99ae90"
9
- static let otaManifestUrl = "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.5.0/mentra-live-ota-3.5.0-dev.1513.json"
10
- static let otaManifestSha256 = "1ffa737ac3a6141e4bda0055188ed608c555100f3e0ab90ecda72f0877e9b45b"
6
+ static let releaseIdentity = "3.5.0-dev.1515"
7
+ static let releaseSetId = "mentra-3.5.0-dev.1515"
8
+ static let sourceCommit = "709922bb8d64421fe5a7e74b44c0a66cd6ef8691"
9
+ static let otaManifestUrl = "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.5.0/mentra-live-ota-3.5.0-dev.1515.json"
10
+ static let otaManifestSha256 = "c5eedb9b905e2dde68a8cdf9a789479c925f9b8c0c19d0b4644e6df86e0a1d6f"
11
11
  }
@@ -180,6 +180,8 @@ final class PendingResponse<T> {
180
180
  self.onTimeout = onTimeout
181
181
  }
182
182
 
183
+ var isCompleted: Bool { completed }
184
+
183
185
  func resolve(_ value: T) {
184
186
  guard !completed else { return }
185
187
  completed = true
@@ -252,15 +254,6 @@ public final class MentraBluetoothSDK {
252
254
  /// A photo response is terminal only after capture, encoding, transport, and upload.
253
255
  /// Max-quality BLE fallback can legitimately exceed the generic command deadline.
254
256
  private static let photoRequestTimeoutMs = 30000
255
- // Mirrors AsgConstants.PHOTO_THUMBNAIL_REQUEST_TIMEOUT_MS and the Android facade.
256
- // Reserve capture, preview ACK/retries, full delivery, then terminal-event transit.
257
- private static let photoCaptureTimeoutMs = 45000
258
- private static let photoThumbnailTimeoutSeconds = 30
259
- private static let photoDeliveryTimeoutMs = 30000
260
- private static let photoResponseMarginMs = 5000
261
- private static let photoThumbnailRequestTimeoutMs =
262
- photoCaptureTimeoutMs + photoThumbnailTimeoutSeconds * 1000
263
- + photoDeliveryTimeoutMs + photoResponseMarginMs
264
257
  private static let otaBesVersionWaitMs = 5000
265
258
  private static let otaMtkVersionWaitMs = 2000
266
259
  private static let otaVersionPollMs = 100
@@ -771,7 +764,7 @@ public final class MentraBluetoothSDK {
771
764
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "auto_power_off_enabled", enabled)
772
765
  }
773
766
 
774
- @available(*, deprecated, message: "Sticky action-button photo presets are deprecated. Prefer per-request requestPhoto(...) options (e.g. mode .text for text sensor size/crop, or explicit per-shot fields). This method still works but will be removed in a future release.")
767
+ @available(*, deprecated, message: "Sticky action-button photo presets are deprecated. Prefer per-request uploadPhoto(...) options (e.g. mode .text for text sensor size/crop, or explicit per-shot fields). This method still works but will be removed in a future release.")
775
768
  public func setPhotoCaptureDefaults(_ settings: PhotoCaptureDefaults) async throws -> SettingsAckEvent {
776
769
  try await performSettingsCommand(
777
770
  setting: "button_photo",
@@ -1211,11 +1204,13 @@ public final class MentraBluetoothSDK {
1211
1204
  DeviceManager.shared.setSystemTime(timestampMs)
1212
1205
  }
1213
1206
 
1214
- public func requestPhoto(_ request: PhotoRequest) async throws -> PhotoResponseEvent {
1207
+ /// A photo sent to `webhookUrl`: uploaded by the glasses over their own Wi-Fi, or relayed by the
1208
+ /// phone over Bluetooth. A photo kept on the phone is `takePhoto`.
1209
+ public func uploadPhoto(_ request: PhotoRequest) async throws -> PhotoResponseEvent {
1215
1210
  let routedRequest = nonBlankRequestId(request.requestId).map { request.withRequestId($0) }
1216
1211
  ?? request.withRequestId(generatedCameraRequestId("photo"))
1217
1212
  Bridge.log(
1218
- "NATIVE: PHOTO PIPELINE [3b/6] MentraBluetoothSdk.requestPhoto requestId=\(routedRequest.requestId)"
1213
+ "NATIVE: PHOTO PIPELINE [3b/6] MentraBluetoothSdk.uploadPhoto requestId=\(routedRequest.requestId)"
1219
1214
  )
1220
1215
  let pending = PendingResponse<PhotoResponseEvent>(operation: "photo request \(routedRequest.requestId)", telemetryOperation: "photo request", onTimeout: requestTimeoutReporter)
1221
1216
  pendingPhotoRequests[routedRequest.requestId] = pending
@@ -1236,10 +1231,8 @@ public final class MentraBluetoothSDK {
1236
1231
  )
1237
1232
  }
1238
1233
  }) {
1239
- DeviceManager.shared.requestPhoto(routedRequest)
1240
- return try await pending.wait(timeoutMs: routedRequest.presendThumbnail
1241
- ? MentraBluetoothSDK.photoThumbnailRequestTimeoutMs
1242
- : MentraBluetoothSDK.photoRequestTimeoutMs)
1234
+ DeviceManager.shared.uploadPhoto(routedRequest)
1235
+ return try await pending.wait(timeoutMs: MentraBluetoothSDK.photoRequestTimeoutMs)
1243
1236
  }
1244
1237
  pendingPhotoRequests.removeValue(forKey: routedRequest.requestId)
1245
1238
  return event
@@ -1249,6 +1242,43 @@ public final class MentraBluetoothSDK {
1249
1242
  }
1250
1243
  }
1251
1244
 
1245
+ private var photoCaptures: [String: PhotoCapture] = [:]
1246
+
1247
+ /// A photo kept on the phone, whole: `capturePhoto`, its `photo()`, then its release.
1248
+ public func takePhoto(_ request: PhotoRequest) async throws -> PhotoResponseEvent {
1249
+ let capture = try capturePhoto(request)
1250
+ defer { capture.release() }
1251
+ return try await capture.photo()
1252
+ }
1253
+
1254
+ /// Take a photo that is kept on the phone, in stages: see `PhotoCapture`. Any number can be in
1255
+ /// flight: the glasses refuse a capture only while another one is being taken (`CAMERA_BUSY`).
1256
+ public func capturePhoto(_ request: PhotoRequest) throws -> PhotoCapture {
1257
+ let routed = nonBlankRequestId(request.requestId).map { request.withRequestId($0) }
1258
+ ?? request.withRequestId(generatedCameraRequestId("photo"))
1259
+ // The glasses keep a photo 30 minutes; nothing arrives for an older capture.
1260
+ let cutoff = Date().addingTimeInterval(-30 * 60)
1261
+ photoCaptures = photoCaptures.filter { !$0.value.done && $0.value.createdAt > cutoff }
1262
+ let deferred = glassesStatus.deferredPhotosVersion > 0
1263
+ let capture = PhotoCapture(
1264
+ request: routed,
1265
+ deferred: deferred,
1266
+ glasses: PhotoCapture.Glasses(
1267
+ fetch: { request, preview in try? DeviceManager.shared.fetchPhoto(request, preview: preview) },
1268
+ release: { requestId in try? DeviceManager.shared.releasePhotos(requestIds: [requestId]) },
1269
+ forget: { [weak self] requestId in self?.photoCaptures.removeValue(forKey: requestId) }
1270
+ )
1271
+ )
1272
+ photoCaptures[routed.requestId] = capture
1273
+ do {
1274
+ try DeviceManager.shared.capturePhoto(routed, deferred: deferred)
1275
+ } catch {
1276
+ photoCaptures.removeValue(forKey: routed.requestId)
1277
+ throw error
1278
+ }
1279
+ return capture
1280
+ }
1281
+
1252
1282
  public func warmUpCamera(
1253
1283
  requestId: String? = nil,
1254
1284
  size: PhotoSize,
@@ -2749,6 +2779,7 @@ public final class MentraBluetoothSDK {
2749
2779
  case "photo_response":
2750
2780
  let event = PhotoResponseEvent(values: data)
2751
2781
  handlePhotoResponseForRequests(event)
2782
+ photoCaptures[event.requestId]?.onResponse(event)
2752
2783
  if case let .error(requestId, errorCode, _, _) = event.response,
2753
2784
  requestId == BluetoothSdkUsageTracker.localPhotoRequestId
2754
2785
  {
@@ -2756,7 +2787,19 @@ public final class MentraBluetoothSDK {
2756
2787
  }
2757
2788
  delegate?.mentraBluetoothSDK(self, didReceive: .photoResponse(event))
2758
2789
  case "photo_status":
2759
- delegate?.mentraBluetoothSDK(self, didReceive: .photoStatus(PhotoStatusEvent(values: data)))
2790
+ let event = PhotoStatusEvent(values: data)
2791
+ photoCaptures[event.requestId]?.onStatus(event)
2792
+ delegate?.mentraBluetoothSDK(self, didReceive: .photoStatus(event))
2793
+ case "photo_preview":
2794
+ photoCaptures[data["requestId"] as? String ?? ""]?.onPreview(
2795
+ PhotoPreview(
2796
+ url: data["url"] as? String ?? "",
2797
+ width: (data["width"] as? NSNumber)?.intValue,
2798
+ height: (data["height"] as? NSNumber)?.intValue
2799
+ )
2800
+ )
2801
+ case "glasses_ready":
2802
+ photoCaptures.values.forEach { $0.resume() }
2760
2803
  case "camera_status":
2761
2804
  let event = CameraStatusEvent(values: data)
2762
2805
  handleCameraStatusForRequests(event)
@@ -251,8 +251,21 @@ public struct CameraFovResult: CustomStringConvertible {
251
251
  }
252
252
  }
253
253
 
254
+ /// A photo's preview: the glasses' at most 500 px JPEG, as a `data:image/jpeg;base64,` URL.
255
+ public struct PhotoPreview {
256
+ public let url: String
257
+ public let width: Int?
258
+ public let height: Int?
259
+
260
+ public var values: [String: Any] {
261
+ var values: [String: Any] = ["url": url]
262
+ if let width { values["width"] = width }
263
+ if let height { values["height"] = height }
264
+ return values
265
+ }
266
+ }
267
+
254
268
  public struct PhotoRequest {
255
- public let presendThumbnail: Bool
256
269
  public let requestId: String
257
270
  public let size: PhotoSize
258
271
  public let mode: PhotoMode
@@ -274,10 +287,6 @@ public struct PhotoRequest {
274
287
  public let zsl: Bool?
275
288
  public let ispDigitalGain: Int?
276
289
  public let ispAnalogGain: String?
277
- /// Keep the photo on the phone: it comes over BLE, is saved as a JPEG file, and the
278
- /// success response carries that file's URL as `photoUrl`. Nothing is uploaded, and
279
- /// `webhookUrl` and `transferMethod` are ignored.
280
- public let localFile: Bool
281
290
 
282
291
  public init(
283
292
  requestId: String? = nil,
@@ -298,9 +307,7 @@ public struct PhotoRequest {
298
307
  ispDigitalGain: Int? = nil,
299
308
  ispAnalogGain: String? = nil,
300
309
  mode: PhotoMode = .photo,
301
- transferMethod: String = "auto",
302
- presendThumbnail: Bool = false,
303
- localFile: Bool = false
310
+ transferMethod: String = "auto"
304
311
  ) {
305
312
  self.requestId = nonBlankRequestId(requestId) ?? generatedCameraRequestId("photo")
306
313
  self.size = size
@@ -321,8 +328,6 @@ public struct PhotoRequest {
321
328
  self.ispAnalogGain = ispAnalogGain
322
329
  self.mode = mode
323
330
  self.transferMethod = transferMethod
324
- self.presendThumbnail = presendThumbnail
325
- self.localFile = localFile
326
331
  }
327
332
 
328
333
  public static func from(params: [String: Any]) throws -> PhotoRequest {
@@ -405,9 +410,7 @@ public struct PhotoRequest {
405
410
  ispDigitalGain: optionalInt("ispDigitalGain"),
406
411
  ispAnalogGain: params["ispAnalogGain"] as? String,
407
412
  mode: PhotoMode(normalizedRawValue: params["mode"] as? String),
408
- transferMethod: transferMethod,
409
- presendThumbnail: params["presend_thumbnail"] as? Bool ?? false,
410
- localFile: params["localFile"] as? Bool ?? false
413
+ transferMethod: transferMethod
411
414
  )
412
415
  }
413
416
 
@@ -471,9 +474,7 @@ public struct PhotoRequest {
471
474
  ispDigitalGain: ispDigitalGain,
472
475
  ispAnalogGain: ispAnalogGain,
473
476
  mode: mode,
474
- transferMethod: transferMethod,
475
- presendThumbnail: presendThumbnail,
476
- localFile: localFile
477
+ transferMethod: transferMethod
477
478
  )
478
479
  }
479
480
  }
@@ -0,0 +1,118 @@
1
+ import Foundation
2
+ import ImageIO
3
+
4
+ /// One photo kept on the phone, in stages. `captured()`: the camera is done and free for the next
5
+ /// one. `preview()`: the glasses' at most 500 px preview. `photo()`: the full photo as a file; the
6
+ /// first call asks the glasses to send it, and until then it waits on the glasses ("deferred
7
+ /// delivery"). `release()`: the full photo isn't needed, and the glasses delete it. Glasses without
8
+ /// deferred photos send the whole photo at once; it is then also the preview.
9
+ @MainActor
10
+ public final class PhotoCapture {
11
+ struct Glasses {
12
+ let fetch: (PhotoRequest, _ preview: Bool) -> Void
13
+ let release: (String) -> Void
14
+ let forget: (String) -> Void
15
+ }
16
+
17
+ public let request: PhotoRequest
18
+ public var requestId: String { request.requestId }
19
+ let createdAt = Date()
20
+ private let deferred: Bool
21
+ private let glasses: Glasses
22
+ private let capturedStage = PendingResponse<Void>(operation: "photo capture")
23
+ private let previewStage = PendingResponse<PhotoPreview>(operation: "photo preview")
24
+ private let photoStage = PendingResponse<PhotoResponseEvent>(operation: "photo")
25
+ private var photoAsked: Bool
26
+
27
+ private static let capturedTimeoutMs = 45000
28
+ // Capture, preview ACK and retries, then the send queue's wait behind other photos.
29
+ private static let stageTimeoutMs = 110_000
30
+
31
+ init(request: PhotoRequest, deferred: Bool, glasses: Glasses) {
32
+ self.request = request
33
+ self.deferred = deferred
34
+ self.glasses = glasses
35
+ photoAsked = !deferred
36
+ }
37
+
38
+ /// Returns once the glasses wrote the photo: the camera takes the next request.
39
+ public func captured() async throws {
40
+ try await capturedStage.wait(timeoutMs: Self.capturedTimeoutMs)
41
+ }
42
+
43
+ public func preview() async throws -> PhotoPreview {
44
+ try await previewStage.wait(timeoutMs: Self.stageTimeoutMs)
45
+ }
46
+
47
+ /// The full photo; `photoUrl` is a `file://` URL in the app's cache folder, the caller's to move.
48
+ public func photo() async throws -> PhotoResponseEvent {
49
+ if !photoAsked {
50
+ photoAsked = true
51
+ glasses.fetch(request, false)
52
+ }
53
+ return try await photoStage.wait(timeoutMs: Self.stageTimeoutMs)
54
+ }
55
+
56
+ /// The full photo isn't needed: the glasses delete it. Stages not reached yet fail.
57
+ public func release() {
58
+ glasses.forget(requestId)
59
+ // The glasses keep the photo after sending it, so a released one goes even once fetched.
60
+ if deferred { glasses.release(requestId) }
61
+ fail(BluetoothSdkError(code: "photo_released", message: "The photo was released."))
62
+ }
63
+
64
+ var done: Bool { capturedStage.isCompleted && previewStage.isCompleted && photoStage.isCompleted }
65
+
66
+ func onStatus(_ event: PhotoStatusEvent) {
67
+ if event.status == "captured" { capturedStage.resolve(()) }
68
+ }
69
+
70
+ func onPreview(_ preview: PhotoPreview) {
71
+ previewStage.resolve(preview)
72
+ }
73
+
74
+ func onResponse(_ event: PhotoResponseEvent) {
75
+ switch event.response {
76
+ case let .success(_, _, photoUrl, _, _, _, _):
77
+ capturedStage.resolve(())
78
+ if !deferred { previewStage.resolve(Self.previewOf(photoUrl ?? "")) }
79
+ photoStage.resolve(event)
80
+ case let .error(_, errorCode, errorMessage, _):
81
+ let error = BluetoothSdkError(code: errorCode ?? "photo_request_failed", message: errorMessage)
82
+ if !capturedStage.isCompleted {
83
+ fail(error)
84
+ } else if errorCode == "PREVIEW_FAILED" {
85
+ // Only the preview failed: the photo is still on the glasses.
86
+ previewStage.reject(error)
87
+ } else {
88
+ photoStage.reject(error)
89
+ }
90
+ }
91
+ }
92
+
93
+ /// The glasses are back after a reconnect or restart: ask again for what is still awaited.
94
+ func resume() {
95
+ guard deferred, capturedStage.isCompleted else { return }
96
+ if !previewStage.isCompleted { glasses.fetch(request, true) }
97
+ if photoAsked, !photoStage.isCompleted { glasses.fetch(request, false) }
98
+ }
99
+
100
+ private func fail(_ error: Error) {
101
+ capturedStage.reject(error)
102
+ previewStage.reject(error)
103
+ photoStage.reject(error)
104
+ }
105
+
106
+ /// Older glasses send no preview: the whole photo stands in, with its pixel size.
107
+ private static func previewOf(_ url: String) -> PhotoPreview {
108
+ guard let fileUrl = URL(string: url),
109
+ let source = CGImageSourceCreateWithURL(fileUrl as CFURL, nil),
110
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]
111
+ else { return PhotoPreview(url: url, width: nil, height: nil) }
112
+ return PhotoPreview(
113
+ url: url,
114
+ width: (properties[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue,
115
+ height: (properties[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue
116
+ )
117
+ }
118
+ }
@@ -18,7 +18,7 @@ protocol ControllerManager {
18
18
 
19
19
  // MARK: - Camera & Media
20
20
 
21
- func requestPhoto(_ request: PhotoRequest)
21
+ func uploadPhoto(_ request: PhotoRequest)
22
22
  func startStream(_ message: [String: Any])
23
23
  func stopStream()
24
24
  func sendStreamKeepAlive(_ message: [String: Any])
@@ -504,7 +504,7 @@ class R1: NSObject, ControllerManager {
504
504
  }
505
505
 
506
506
  func sendJson(_: [String: Any], wakeUp _: Bool, requireAck _: Bool) {}
507
- func requestPhoto(_: PhotoRequest) {}
507
+ func uploadPhoto(_: PhotoRequest) {}
508
508
  func startVideoRecording(requestId _: String, save _: Bool, sound _: Bool) {}
509
509
  func stopVideoRecording(requestId _: String) {}
510
510
  func startStream(_: [String: Any]) {}
@@ -599,8 +599,8 @@ final class Ar99: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate, SGCM
599
599
 
600
600
  // MARK: - Camera & Media
601
601
 
602
- func requestPhoto(_: PhotoRequest) {
603
- Bridge.log("AR99: requestPhoto not implemented")
602
+ func uploadPhoto(_: PhotoRequest) {
603
+ Bridge.log("AR99: uploadPhoto not implemented")
604
604
  }
605
605
 
606
606
  func startStream(_: [String: Any]) {}
@@ -111,7 +111,7 @@ func sendRgbLedControl(requestId: String, packageName _: String?, action _: Stri
111
111
 
112
112
  // func sendJson(_: [String: Any], wakeUp _: Bool) {}
113
113
 
114
- // func requestPhoto(_: String, appId _: String, size _: String?, webhookUrl _: String?) {}
114
+ // func uploadPhoto(_: String, appId _: String, size _: String?, webhookUrl _: String?) {}
115
115
 
116
116
  // func forget() {}
117
117
 
@@ -280,7 +280,7 @@ class G1: NSObject, SGCManager {
280
280
 
281
281
  func sendButtonMaxRecordingTime(_: Int) {}
282
282
 
283
- func requestPhoto(_: PhotoRequest) {}
283
+ func uploadPhoto(_: PhotoRequest) {}
284
284
 
285
285
  func startStream(_: [String: Any]) {}
286
286
 
@@ -4214,7 +4214,7 @@ class G2: NSObject, SGCManager {
4214
4214
 
4215
4215
  // MARK: - SGCManager: Camera & Media (not supported on G2)
4216
4216
 
4217
- func requestPhoto(_: PhotoRequest) {}
4217
+ func uploadPhoto(_: PhotoRequest) {}
4218
4218
  func startVideoRecording(requestId _: String, save _: Bool, sound _: Bool) {}
4219
4219
  func startStream(_: [String: Any]) {}
4220
4220
  func stopStream() {}
@@ -15,7 +15,7 @@ import UltraliteSDK
15
15
  class Mach1: UltraliteBaseViewController, SGCManager {
16
16
  func sendIncidentId(_: String, apiBaseUrl _: String?) {}
17
17
 
18
- func requestPhoto(_: PhotoRequest) {}
18
+ func uploadPhoto(_: PhotoRequest) {}
19
19
 
20
20
  func sendGalleryMode() {}
21
21