@glassly/bluetooth-sdk 0.1.0-dev.100

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 (553) hide show
  1. package/README.md +563 -0
  2. package/android/build.gradle +450 -0
  3. package/android/gradle.properties.example +9 -0
  4. package/android/lc3Lib/CMakeLists.txt +6 -0
  5. package/android/lc3Lib/build.gradle +212 -0
  6. package/android/lc3Lib/proguard-rules.pro +33 -0
  7. package/android/lc3Lib/src/main/AndroidManifest.xml +2 -0
  8. package/android/lc3Lib/src/main/cpp/CMakeLists.txt +8 -0
  9. package/android/lc3Lib/src/main/cpp/google_opus_stuff/CMakeLists.txt +30 -0
  10. package/android/lc3Lib/src/main/cpp/google_opus_stuff/jni/CMakeLists.txt +7 -0
  11. package/android/lc3Lib/src/main/cpp/google_opus_stuff/jni/ogg_opus_encoder.cc +96 -0
  12. package/android/lc3Lib/src/main/cpp/google_opus_stuff/jni/ogg_opus_encoder.h +53 -0
  13. package/android/lc3Lib/src/main/cpp/google_opus_stuff/libogg/Makefile.am +6 -0
  14. package/android/lc3Lib/src/main/cpp/google_opus_stuff/libogg/config_types.h +26 -0
  15. package/android/lc3Lib/src/main/cpp/google_opus_stuff/libogg/config_types.h.in +26 -0
  16. package/android/lc3Lib/src/main/cpp/google_opus_stuff/libogg/ogg.h +209 -0
  17. package/android/lc3Lib/src/main/cpp/google_opus_stuff/libogg/os_types.h +158 -0
  18. package/android/lc3Lib/src/main/cpp/google_opus_stuff/libopus/opus.h +981 -0
  19. package/android/lc3Lib/src/main/cpp/google_opus_stuff/libopus/opus_custom.h +342 -0
  20. package/android/lc3Lib/src/main/cpp/google_opus_stuff/libopus/opus_defines.h +799 -0
  21. package/android/lc3Lib/src/main/cpp/google_opus_stuff/libopus/opus_multistream.h +660 -0
  22. package/android/lc3Lib/src/main/cpp/google_opus_stuff/libopus/opus_projection.h +568 -0
  23. package/android/lc3Lib/src/main/cpp/google_opus_stuff/libopus/opus_types.h +166 -0
  24. package/android/lc3Lib/src/main/cpp/google_opus_stuff/ogg_opus_encoder.cc +268 -0
  25. package/android/lc3Lib/src/main/cpp/google_opus_stuff/ogg_opus_encoder.h +115 -0
  26. package/android/lc3Lib/src/main/cpp/google_opus_stuff/opus_tools/opus_header.h +59 -0
  27. package/android/lc3Lib/src/main/cpp/liblc3/CMakeLists.txt +38 -0
  28. package/android/lc3Lib/src/main/cpp/liblc3/include/lc3.h +309 -0
  29. package/android/lc3Lib/src/main/cpp/liblc3/include/lc3_private.h +162 -0
  30. package/android/lc3Lib/src/main/cpp/liblc3/include/rnnoise.h +114 -0
  31. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/CMakeLists.txt +19 -0
  32. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/attdet.c +92 -0
  33. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/attdet.h +44 -0
  34. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/bits.c +375 -0
  35. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/bits.h +315 -0
  36. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/bwdet.c +129 -0
  37. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/bwdet.h +69 -0
  38. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/common.h +148 -0
  39. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/energy.c +70 -0
  40. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/energy.h +43 -0
  41. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/fastmath.h +158 -0
  42. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/lc3.c +702 -0
  43. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/ltpf.c +893 -0
  44. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/ltpf.h +111 -0
  45. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/ltpf_arm.h +506 -0
  46. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/ltpf_neon.h +281 -0
  47. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/makefile.mk +35 -0
  48. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/mdct.c +452 -0
  49. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/mdct.h +57 -0
  50. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/mdct_neon.h +296 -0
  51. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/meson.build +46 -0
  52. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/plc.c +61 -0
  53. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/plc.h +57 -0
  54. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/sns.c +880 -0
  55. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/sns.h +103 -0
  56. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/spec.c +904 -0
  57. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/spec.h +119 -0
  58. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/tables.c +3457 -0
  59. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/tables.h +94 -0
  60. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/tns.c +457 -0
  61. package/android/lc3Lib/src/main/cpp/liblc3/liblc3/tns.h +99 -0
  62. package/android/lc3Lib/src/main/cpp/liblc3/liblc3.cpp +159 -0
  63. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/_kiss_fft_guts.h +182 -0
  64. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/arch.h +261 -0
  65. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/celt_lpc.c +279 -0
  66. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/celt_lpc.h +59 -0
  67. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/common.h +48 -0
  68. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/compile.sh +3 -0
  69. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/denoise.c +646 -0
  70. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/kiss_fft.c +601 -0
  71. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/kiss_fft.h +203 -0
  72. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/opus_types.h +159 -0
  73. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/pitch.c +526 -0
  74. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/pitch.h +149 -0
  75. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/rnn.c +178 -0
  76. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/rnn.h +69 -0
  77. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/rnn_data.c +11051 -0
  78. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/rnn_data.h +34 -0
  79. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/rnn_reader.c +168 -0
  80. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/rnn_train.py +66 -0
  81. package/android/lc3Lib/src/main/cpp/liblc3/rnnoise/tansig_table.h +45 -0
  82. package/android/lc3Lib/src/main/java/com/glassly/lc3Lib/Lc3Cpp.java +38 -0
  83. package/android/lc3Lib/third_party/CMakeLists.txt +23 -0
  84. package/android/lc3Lib/third_party/CMakeLists_libogg.txt +18 -0
  85. package/android/lc3Lib/third_party/CMakeLists_libopus.txt +18 -0
  86. package/android/lc3Lib/third_party/CMakeLists_opus-tools.txt +23 -0
  87. package/android/lc3Lib/third_party/opus_tools/src/AUTHORS +5 -0
  88. package/android/lc3Lib/third_party/opus_tools/src/CMakeLists.txt +4 -0
  89. package/android/lc3Lib/third_party/opus_tools/src/COPYING +371 -0
  90. package/android/lc3Lib/third_party/opus_tools/src/ChangeLog +3 -0
  91. package/android/lc3Lib/third_party/opus_tools/src/Makefile.am +42 -0
  92. package/android/lc3Lib/third_party/opus_tools/src/Makefile.unix +23 -0
  93. package/android/lc3Lib/third_party/opus_tools/src/NEWS +0 -0
  94. package/android/lc3Lib/third_party/opus_tools/src/README +0 -0
  95. package/android/lc3Lib/third_party/opus_tools/src/autogen.sh +115 -0
  96. package/android/lc3Lib/third_party/opus_tools/src/configure.ac +293 -0
  97. package/android/lc3Lib/third_party/opus_tools/src/src/arch.h +239 -0
  98. package/android/lc3Lib/third_party/opus_tools/src/src/audio-in.c +1046 -0
  99. package/android/lc3Lib/third_party/opus_tools/src/src/diag_range.c +245 -0
  100. package/android/lc3Lib/third_party/opus_tools/src/src/diag_range.h +28 -0
  101. package/android/lc3Lib/third_party/opus_tools/src/src/info_opus.c +320 -0
  102. package/android/lc3Lib/third_party/opus_tools/src/src/info_opus.h +51 -0
  103. package/android/lc3Lib/third_party/opus_tools/src/src/lpc.c +157 -0
  104. package/android/lc3Lib/third_party/opus_tools/src/src/lpc.h +27 -0
  105. package/android/lc3Lib/third_party/opus_tools/src/src/opus_header.c +286 -0
  106. package/android/lc3Lib/third_party/opus_tools/src/src/opus_header.h +59 -0
  107. package/android/lc3Lib/third_party/opus_tools/src/src/opusdec.c +884 -0
  108. package/android/lc3Lib/third_party/opus_tools/src/src/opusenc.c +1021 -0
  109. package/android/lc3Lib/third_party/opus_tools/src/src/opusenc.h +101 -0
  110. package/android/lc3Lib/third_party/opus_tools/src/src/opusinfo.c +639 -0
  111. package/android/lc3Lib/third_party/opus_tools/src/src/opusinfo.h +51 -0
  112. package/android/lc3Lib/third_party/opus_tools/src/src/os_support.h +167 -0
  113. package/android/lc3Lib/third_party/opus_tools/src/src/resample.c +1137 -0
  114. package/android/lc3Lib/third_party/opus_tools/src/src/speex_resampler.h +344 -0
  115. package/android/lc3Lib/third_party/opus_tools/src/src/stack_alloc.h +115 -0
  116. package/android/lc3Lib/third_party/opus_tools/src/src/wav_io.c +125 -0
  117. package/android/lc3Lib/third_party/opus_tools/src/src/wav_io.h +62 -0
  118. package/android/lc3Lib/third_party/opus_tools/src/src/wave_out.c +223 -0
  119. package/android/lc3Lib/third_party/opus_tools/src/src/wave_out.h +60 -0
  120. package/android/settings.gradle +4 -0
  121. package/android/silero/LICENSE.md +17 -0
  122. package/android/silero/build.gradle +50 -0
  123. package/android/silero/proguard-rules.pro +24 -0
  124. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  125. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +79 -0
  126. package/android/silero/src/main/assets/LICENSE +21 -0
  127. package/android/silero/src/main/assets/silero_vad.onnx +0 -0
  128. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +160 -0
  129. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +449 -0
  130. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +15 -0
  131. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +14 -0
  132. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +12 -0
  133. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +47 -0
  134. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +41 -0
  135. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +44 -0
  136. package/android/src/main/AndroidManifest.xml +42 -0
  137. package/android/src/main/assets/G2Firmware/README.md +11 -0
  138. package/android/src/main/assets/G2Firmware/g2-glassly-cfw-2.2.9.22.evenota.bin +0 -0
  139. package/android/src/main/assets/G2Firmware/g2-stock-2.2.9.22.evenota.bin +0 -0
  140. package/android/src/main/java/com/glassly/bluetoothsdk/BluetoothSdk.kt +2321 -0
  141. package/android/src/main/java/com/glassly/bluetoothsdk/BluetoothSdkAnalytics.kt +216 -0
  142. package/android/src/main/java/com/glassly/bluetoothsdk/BluetoothSdkDebug.kt +14 -0
  143. package/android/src/main/java/com/glassly/bluetoothsdk/BluetoothSdkDefaults.kt +7 -0
  144. package/android/src/main/java/com/glassly/bluetoothsdk/BluetoothSdkModule.kt +1087 -0
  145. package/android/src/main/java/com/glassly/bluetoothsdk/Bridge.kt +953 -0
  146. package/android/src/main/java/com/glassly/bluetoothsdk/DeviceManager.kt +2472 -0
  147. package/android/src/main/java/com/glassly/bluetoothsdk/DeviceStore.kt +359 -0
  148. package/android/src/main/java/com/glassly/bluetoothsdk/GeneratedChangelogCatalog.kt +9 -0
  149. package/android/src/main/java/com/glassly/bluetoothsdk/GeneratedReleaseMetadata.kt +11 -0
  150. package/android/src/main/java/com/glassly/bluetoothsdk/LocalNetworkModule.kt +414 -0
  151. package/android/src/main/java/com/glassly/bluetoothsdk/ObservableStore.kt +88 -0
  152. package/android/src/main/java/com/glassly/bluetoothsdk/OtaManifest.kt +191 -0
  153. package/android/src/main/java/com/glassly/bluetoothsdk/ReleaseChangelog.kt +61 -0
  154. package/android/src/main/java/com/glassly/bluetoothsdk/ScopedNetworkReadiness.kt +17 -0
  155. package/android/src/main/java/com/glassly/bluetoothsdk/audio/AudioModels.kt +144 -0
  156. package/android/src/main/java/com/glassly/bluetoothsdk/camera/CameraModels.kt +486 -0
  157. package/android/src/main/java/com/glassly/bluetoothsdk/connection/ConnectionModels.kt +78 -0
  158. package/android/src/main/java/com/glassly/bluetoothsdk/controllers/ControllerManager.kt +158 -0
  159. package/android/src/main/java/com/glassly/bluetoothsdk/controllers/R1.kt +1057 -0
  160. package/android/src/main/java/com/glassly/bluetoothsdk/debug/BleTraceLogger.kt +165 -0
  161. package/android/src/main/java/com/glassly/bluetoothsdk/events/BluetoothEvents.kt +178 -0
  162. package/android/src/main/java/com/glassly/bluetoothsdk/internal/MapParsing.kt +140 -0
  163. package/android/src/main/java/com/glassly/bluetoothsdk/net/LocalIpv4.kt +57 -0
  164. package/android/src/main/java/com/glassly/bluetoothsdk/otaserver/LocalOtaServer.kt +304 -0
  165. package/android/src/main/java/com/glassly/bluetoothsdk/otaserver/OtaServerModule.kt +120 -0
  166. package/android/src/main/java/com/glassly/bluetoothsdk/photoreceiver/LocalPhotoReceiverRegistry.java +108 -0
  167. package/android/src/main/java/com/glassly/bluetoothsdk/photoreceiver/LocalPhotoUploadServer.kt +622 -0
  168. package/android/src/main/java/com/glassly/bluetoothsdk/photoreceiver/PhotoReceiverModule.kt +156 -0
  169. package/android/src/main/java/com/glassly/bluetoothsdk/requests/DisplayRequests.kt +56 -0
  170. package/android/src/main/java/com/glassly/bluetoothsdk/services/Foreground.kt +272 -0
  171. package/android/src/main/java/com/glassly/bluetoothsdk/services/PhoneMic.kt +1195 -0
  172. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/Ar99.java +2653 -0
  173. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/BesOtaHeartbeatGuard.kt +49 -0
  174. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/BesOtaProgressMapper.kt +27 -0
  175. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/G1.kt +3837 -0
  176. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/G1TextSanitizer.kt +38 -0
  177. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/G2.kt +6457 -0
  178. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/G2CfwClassification.kt +49 -0
  179. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/G2CfwRenderer.kt +1253 -0
  180. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/G2CfwTextureCache.kt +270 -0
  181. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/G2FlashProtocol.kt +291 -0
  182. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/G2Flasher.kt +411 -0
  183. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/GlasslyBle.java +43189 -0
  184. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/Mach1.kt +1267 -0
  185. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/MentraLive.kt +10742 -0
  186. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/MentraLiveL2capChannel.kt +274 -0
  187. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +54 -0
  188. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/MentraNex.kt +2008 -0
  189. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/Nimo.kt +2532 -0
  190. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/SGCManager.kt +470 -0
  191. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/Simulated.kt +228 -0
  192. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/ar99/ota/Ar99OtaManager.java +566 -0
  193. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/ar99/ota/OtaByteUtils.java +18 -0
  194. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/ar99/ota/OtaCommandConstants.java +35 -0
  195. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/ar99/ota/OtaCrc32Util.java +13 -0
  196. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/ar99/ota/OtaGattTransport.java +11 -0
  197. package/android/src/main/java/com/glassly/bluetoothsdk/sgcs/ar99/ota/OtaProtocol.java +92 -0
  198. package/android/src/main/java/com/glassly/bluetoothsdk/speakerid/SpeakerIdEngine.kt +525 -0
  199. package/android/src/main/java/com/glassly/bluetoothsdk/status/DeviceStatus.kt +669 -0
  200. package/android/src/main/java/com/glassly/bluetoothsdk/status/RuntimeState.kt +201 -0
  201. package/android/src/main/java/com/glassly/bluetoothsdk/status/WifiHotspotStatus.kt +189 -0
  202. package/android/src/main/java/com/glassly/bluetoothsdk/streaming/StreamModels.kt +518 -0
  203. package/android/src/main/java/com/glassly/bluetoothsdk/stt/STTTools.kt +391 -0
  204. package/android/src/main/java/com/glassly/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +518 -0
  205. package/android/src/main/java/com/glassly/bluetoothsdk/stt/VadGateSpeechPolicy.kt +227 -0
  206. package/android/src/main/java/com/glassly/bluetoothsdk/tts/TTSTools.kt +248 -0
  207. package/android/src/main/java/com/glassly/bluetoothsdk/types/DeviceModels.kt +96 -0
  208. package/android/src/main/java/com/glassly/bluetoothsdk/utils/AES.java +106 -0
  209. package/android/src/main/java/com/glassly/bluetoothsdk/utils/AudioSessionMonitor.kt +189 -0
  210. package/android/src/main/java/com/glassly/bluetoothsdk/utils/AvifExifStripper.java +573 -0
  211. package/android/src/main/java/com/glassly/bluetoothsdk/utils/BitmapJavaUtils.java +169 -0
  212. package/android/src/main/java/com/glassly/bluetoothsdk/utils/BleJsonCompact.java +496 -0
  213. package/android/src/main/java/com/glassly/bluetoothsdk/utils/BlePhotoUploadService.java +677 -0
  214. package/android/src/main/java/com/glassly/bluetoothsdk/utils/BleWireProtocol.java +108 -0
  215. package/android/src/main/java/com/glassly/bluetoothsdk/utils/Constants.kt +46 -0
  216. package/android/src/main/java/com/glassly/bluetoothsdk/utils/G1Text.kt +436 -0
  217. package/android/src/main/java/com/glassly/bluetoothsdk/utils/HeifExifTagReader.java +199 -0
  218. package/android/src/main/java/com/glassly/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +29 -0
  219. package/android/src/main/java/com/glassly/bluetoothsdk/utils/IncidentLogBleUploadService.java +77 -0
  220. package/android/src/main/java/com/glassly/bluetoothsdk/utils/K900LengthCodec.java +115 -0
  221. package/android/src/main/java/com/glassly/bluetoothsdk/utils/K900ProtocolUtils.java +827 -0
  222. package/android/src/main/java/com/glassly/bluetoothsdk/utils/MessageChunkReassembler.java +228 -0
  223. package/android/src/main/java/com/glassly/bluetoothsdk/utils/MessageChunker.java +325 -0
  224. package/android/src/main/java/com/glassly/bluetoothsdk/utils/NexSGCUtils.kt +698 -0
  225. package/android/src/main/java/com/glassly/bluetoothsdk/utils/PhoneAudioMonitor.kt +348 -0
  226. package/android/src/main/java/com/glassly/bluetoothsdk/utils/SmartGlassesConnectionState.java +9 -0
  227. package/android/src/main/java/com/glassly/bluetoothsdk/utils/audio/Ar99OpusPcmDecoder.java +398 -0
  228. package/android/src/main/java/com/glassly/bluetoothsdk/utils/audio/ByteUtilAudioPlayer.java +655 -0
  229. package/android/src/main/java/com/glassly/bluetoothsdk/utils/audio/Lc3Player.java +441 -0
  230. package/android/src/main/java/com/glassly/bluetoothsdk/utils/audio/PCMAudioPlayer.java +431 -0
  231. package/android/src/main/java/com/glassly/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +328 -0
  232. package/android/src/main/res/values/strings.xml +4 -0
  233. package/android/src/test/java/com/glassly/bluetoothsdk/BluetoothSdkExceptionTest.kt +18 -0
  234. package/android/src/test/java/com/glassly/bluetoothsdk/OtaManifestDowngradeTest.kt +86 -0
  235. package/android/src/test/java/com/glassly/bluetoothsdk/OtaStartResponsePolicyTest.kt +30 -0
  236. package/android/src/test/java/com/glassly/bluetoothsdk/ReleaseChangelogTest.kt +13 -0
  237. package/android/src/test/java/com/glassly/bluetoothsdk/ScopedNetworkReadinessTest.kt +39 -0
  238. package/android/src/test/java/com/glassly/bluetoothsdk/StreamStatusEventTest.kt +29 -0
  239. package/android/src/test/java/com/glassly/bluetoothsdk/camera/PhotoRequestTest.kt +141 -0
  240. package/android/src/test/java/com/glassly/bluetoothsdk/otaserver/LocalOtaServerTest.kt +82 -0
  241. package/android/src/test/java/com/glassly/bluetoothsdk/photoreceiver/LocalPhotoReceiverRegistryTest.java +75 -0
  242. package/android/src/test/java/com/glassly/bluetoothsdk/services/ForegroundServiceTypeTest.kt +69 -0
  243. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/Ar99AdvertisementMatcherTest.java +22 -0
  244. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/BesOtaHeartbeatGuardTest.kt +73 -0
  245. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/BesOtaProgressMapperTest.kt +67 -0
  246. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/EvenRleTest.kt +63 -0
  247. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/G1TextSanitizerTest.kt +31 -0
  248. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/G2CfwClassificationTest.kt +89 -0
  249. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/G2CfwRendererTest.kt +344 -0
  250. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/G2CfwTextureCacheTest.kt +200 -0
  251. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/G2FlashProtocolTest.kt +131 -0
  252. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/MentraLiveGattCharacteristicsTest.kt +39 -0
  253. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +133 -0
  254. package/android/src/test/java/com/glassly/bluetoothsdk/sgcs/NimoProtocolTest.kt +333 -0
  255. package/android/src/test/java/com/glassly/bluetoothsdk/utils/AvifExifStripperTest.java +46 -0
  256. package/android/src/test/java/com/glassly/bluetoothsdk/utils/BinaryMessageChunkerTest.java +84 -0
  257. package/android/src/test/java/com/glassly/bluetoothsdk/utils/BleJsonCompactTest.java +319 -0
  258. package/android/src/test/java/com/glassly/bluetoothsdk/utils/BlePhotoUploadServiceTest.java +107 -0
  259. package/android/src/test/java/com/glassly/bluetoothsdk/utils/K900ProtocolUtilsEndiannessTest.java +172 -0
  260. package/android/src/test/java/com/glassly/bluetoothsdk/utils/K900ProtocolUtilsTest.java +24 -0
  261. package/android/src/test/java/com/glassly/bluetoothsdk/utils/PhoneAudioMonitorTest.kt +45 -0
  262. package/android/src/test/resources/avif_with_exif.avif +0 -0
  263. package/app.plugin.js +3 -0
  264. package/build/BluetoothSdk.types.d.ts +1390 -0
  265. package/build/BluetoothSdk.types.d.ts.map +1 -0
  266. package/build/BluetoothSdk.types.js +41 -0
  267. package/build/BluetoothSdk.types.js.map +1 -0
  268. package/build/_internal.d.ts +17 -0
  269. package/build/_internal.d.ts.map +1 -0
  270. package/build/_internal.js +16 -0
  271. package/build/_internal.js.map +1 -0
  272. package/build/_private/BluetoothSdkModule.d.ts +171 -0
  273. package/build/_private/BluetoothSdkModule.d.ts.map +1 -0
  274. package/build/_private/BluetoothSdkModule.js +300 -0
  275. package/build/_private/BluetoothSdkModule.js.map +1 -0
  276. package/build/_private/LocalNetworkModule.d.ts +38 -0
  277. package/build/_private/LocalNetworkModule.d.ts.map +1 -0
  278. package/build/_private/LocalNetworkModule.js +3 -0
  279. package/build/_private/LocalNetworkModule.js.map +1 -0
  280. package/build/_private/cameraRequestPayload.d.ts +4 -0
  281. package/build/_private/cameraRequestPayload.d.ts.map +1 -0
  282. package/build/_private/cameraRequestPayload.js +32 -0
  283. package/build/_private/cameraRequestPayload.js.map +1 -0
  284. package/build/_private/photoRequestPayload.d.ts +6 -0
  285. package/build/_private/photoRequestPayload.d.ts.map +1 -0
  286. package/build/_private/photoRequestPayload.js +86 -0
  287. package/build/_private/photoRequestPayload.js.map +1 -0
  288. package/build/_private/sdkOtaManifest.d.ts +11 -0
  289. package/build/_private/sdkOtaManifest.d.ts.map +1 -0
  290. package/build/_private/sdkOtaManifest.js +15 -0
  291. package/build/_private/sdkOtaManifest.js.map +1 -0
  292. package/build/changelogs.d.ts +7 -0
  293. package/build/changelogs.d.ts.map +1 -0
  294. package/build/changelogs.js +46 -0
  295. package/build/changelogs.js.map +1 -0
  296. package/build/debug.d.ts +3 -0
  297. package/build/debug.d.ts.map +1 -0
  298. package/build/debug.js +8 -0
  299. package/build/debug.js.map +1 -0
  300. package/build/generated/changelogCatalog.d.ts +12 -0
  301. package/build/generated/changelogCatalog.d.ts.map +1 -0
  302. package/build/generated/changelogCatalog.js +16 -0
  303. package/build/generated/changelogCatalog.js.map +1 -0
  304. package/build/generated/releaseMetadata.d.ts +12 -0
  305. package/build/generated/releaseMetadata.d.ts.map +1 -0
  306. package/build/generated/releaseMetadata.js +10 -0
  307. package/build/generated/releaseMetadata.js.map +1 -0
  308. package/build/index.d.ts +6 -0
  309. package/build/index.d.ts.map +1 -0
  310. package/build/index.js +170 -0
  311. package/build/index.js.map +1 -0
  312. package/build/ota-server/OtaServer.types.d.ts +14 -0
  313. package/build/ota-server/OtaServer.types.d.ts.map +1 -0
  314. package/build/ota-server/OtaServer.types.js +2 -0
  315. package/build/ota-server/OtaServer.types.js.map +1 -0
  316. package/build/ota-server/OtaServerModule.d.ts +21 -0
  317. package/build/ota-server/OtaServerModule.d.ts.map +1 -0
  318. package/build/ota-server/OtaServerModule.js +3 -0
  319. package/build/ota-server/OtaServerModule.js.map +1 -0
  320. package/build/ota-server/OtaServerModule.web.d.ts +10 -0
  321. package/build/ota-server/OtaServerModule.web.d.ts.map +1 -0
  322. package/build/ota-server/OtaServerModule.web.js +12 -0
  323. package/build/ota-server/OtaServerModule.web.js.map +1 -0
  324. package/build/ota-server/index.d.ts +3 -0
  325. package/build/ota-server/index.d.ts.map +1 -0
  326. package/build/ota-server/index.js +3 -0
  327. package/build/ota-server/index.js.map +1 -0
  328. package/build/ota-transport/index.d.ts +67 -0
  329. package/build/ota-transport/index.d.ts.map +1 -0
  330. package/build/ota-transport/index.js +58 -0
  331. package/build/ota-transport/index.js.map +1 -0
  332. package/build/photo-receiver/PhotoReceiver.types.d.ts +18 -0
  333. package/build/photo-receiver/PhotoReceiver.types.d.ts.map +1 -0
  334. package/build/photo-receiver/PhotoReceiver.types.js +2 -0
  335. package/build/photo-receiver/PhotoReceiver.types.js.map +1 -0
  336. package/build/photo-receiver/PhotoReceiverModule.d.ts +10 -0
  337. package/build/photo-receiver/PhotoReceiverModule.d.ts.map +1 -0
  338. package/build/photo-receiver/PhotoReceiverModule.js +3 -0
  339. package/build/photo-receiver/PhotoReceiverModule.js.map +1 -0
  340. package/build/photo-receiver/PhotoReceiverModule.web.d.ts +10 -0
  341. package/build/photo-receiver/PhotoReceiverModule.web.d.ts.map +1 -0
  342. package/build/photo-receiver/PhotoReceiverModule.web.js +12 -0
  343. package/build/photo-receiver/PhotoReceiverModule.web.js.map +1 -0
  344. package/build/photo-receiver/index.d.ts +3 -0
  345. package/build/photo-receiver/index.d.ts.map +1 -0
  346. package/build/photo-receiver/index.js +3 -0
  347. package/build/photo-receiver/index.js.map +1 -0
  348. package/build/react/index.d.ts +5 -0
  349. package/build/react/index.d.ts.map +1 -0
  350. package/build/react/index.js +4 -0
  351. package/build/react/index.js.map +1 -0
  352. package/build/react/useBluetooth.d.ts +100 -0
  353. package/build/react/useBluetooth.d.ts.map +1 -0
  354. package/build/react/useBluetooth.js +167 -0
  355. package/build/react/useBluetooth.js.map +1 -0
  356. package/build/react/useBluetoothEvent.d.ts +6 -0
  357. package/build/react/useBluetoothEvent.d.ts.map +1 -0
  358. package/build/react/useBluetoothEvent.js +21 -0
  359. package/build/react/useBluetoothEvent.js.map +1 -0
  360. package/build/react/useBluetoothScan.d.ts +22 -0
  361. package/build/react/useBluetoothScan.d.ts.map +1 -0
  362. package/build/react/useBluetoothScan.js +135 -0
  363. package/build/react/useBluetoothScan.js.map +1 -0
  364. package/build/react/useBluetoothStatus.d.ts +16 -0
  365. package/build/react/useBluetoothStatus.d.ts.map +1 -0
  366. package/build/react/useBluetoothStatus.js +137 -0
  367. package/build/react/useBluetoothStatus.js.map +1 -0
  368. package/build/react/useGlassesConnection.d.ts +29 -0
  369. package/build/react/useGlassesConnection.d.ts.map +1 -0
  370. package/build/react/useGlassesConnection.js +153 -0
  371. package/build/react/useGlassesConnection.js.map +1 -0
  372. package/build/types/index.d.ts +3 -0
  373. package/build/types/index.d.ts.map +1 -0
  374. package/build/types/index.js +2 -0
  375. package/build/types/index.js.map +1 -0
  376. package/expo-module.config.json +14 -0
  377. package/ios/BackgroundOtaArtifactDownloader.swift +125 -0
  378. package/ios/BluetoothSdkModule.swift +1028 -0
  379. package/ios/GlasslyBluetoothSDK.podspec +106 -0
  380. package/ios/LocalIPv4.swift +150 -0
  381. package/ios/LocalOtaServer.swift +309 -0
  382. package/ios/LocalPhotoUploadServer.swift +754 -0
  383. package/ios/OtaServerModule.swift +147 -0
  384. package/ios/Packages/CoreObjC/CoreObjC.xcodeproj/project.pbxproj +213 -0
  385. package/ios/Packages/CoreObjC/PcmConverter.h +22 -0
  386. package/ios/Packages/CoreObjC/PcmConverter.m +266 -0
  387. package/ios/Packages/CoreObjC/attdet.c +92 -0
  388. package/ios/Packages/CoreObjC/attdet.h +44 -0
  389. package/ios/Packages/CoreObjC/bits.c +375 -0
  390. package/ios/Packages/CoreObjC/bits.h +315 -0
  391. package/ios/Packages/CoreObjC/bwdet.c +129 -0
  392. package/ios/Packages/CoreObjC/bwdet.h +69 -0
  393. package/ios/Packages/CoreObjC/common.h +151 -0
  394. package/ios/Packages/CoreObjC/energy.c +70 -0
  395. package/ios/Packages/CoreObjC/energy.h +43 -0
  396. package/ios/Packages/CoreObjC/fastmath.h +158 -0
  397. package/ios/Packages/CoreObjC/include/PcmConverter.h +22 -0
  398. package/ios/Packages/CoreObjC/lc3.c +704 -0
  399. package/ios/Packages/CoreObjC/lc3.h +313 -0
  400. package/ios/Packages/CoreObjC/lc3_cpp.h +283 -0
  401. package/ios/Packages/CoreObjC/lc3_private.h +163 -0
  402. package/ios/Packages/CoreObjC/ltpf.c +905 -0
  403. package/ios/Packages/CoreObjC/ltpf.h +111 -0
  404. package/ios/Packages/CoreObjC/ltpf_arm.h +506 -0
  405. package/ios/Packages/CoreObjC/ltpf_neon.h +281 -0
  406. package/ios/Packages/CoreObjC/makefile.mk +35 -0
  407. package/ios/Packages/CoreObjC/mdct.c +469 -0
  408. package/ios/Packages/CoreObjC/mdct.h +57 -0
  409. package/ios/Packages/CoreObjC/mdct_neon.h +296 -0
  410. package/ios/Packages/CoreObjC/meson.build +61 -0
  411. package/ios/Packages/CoreObjC/plc.c +61 -0
  412. package/ios/Packages/CoreObjC/plc.h +57 -0
  413. package/ios/Packages/CoreObjC/rnnoise.h +114 -0
  414. package/ios/Packages/CoreObjC/sns.c +880 -0
  415. package/ios/Packages/CoreObjC/sns.h +103 -0
  416. package/ios/Packages/CoreObjC/spec.c +907 -0
  417. package/ios/Packages/CoreObjC/spec.h +119 -0
  418. package/ios/Packages/CoreObjC/tables.c +3457 -0
  419. package/ios/Packages/CoreObjC/tables.h +94 -0
  420. package/ios/Packages/CoreObjC/tns.c +457 -0
  421. package/ios/Packages/CoreObjC/tns.h +99 -0
  422. package/ios/Packages/SherpaOnnx/Model/joiner.onnx +0 -0
  423. package/ios/Packages/SherpaOnnx/Model/tokens.txt +502 -0
  424. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +2383 -0
  425. package/ios/Packages/SherpaOnnx/sherpa-onnx.xcframework/Info.plist +48 -0
  426. package/ios/Packages/SherpaOnnx/sherpa-onnx.xcframework/ios-arm64/Headers/sherpa-onnx/c-api/c-api.h +4689 -0
  427. package/ios/Packages/SherpaOnnx/sherpa-onnx.xcframework/ios-arm64/Headers/sherpa-onnx/c-api/cxx-api.h +2036 -0
  428. package/ios/Packages/SherpaOnnx/sherpa-onnx.xcframework/ios-arm64/libsherpa-onnx.a +0 -0
  429. package/ios/Packages/SherpaOnnx/sherpa-onnx.xcframework/ios-arm64_x86_64-simulator/Headers/sherpa-onnx/c-api/c-api.h +4689 -0
  430. package/ios/Packages/SherpaOnnx/sherpa-onnx.xcframework/ios-arm64_x86_64-simulator/Headers/sherpa-onnx/c-api/cxx-api.h +2036 -0
  431. package/ios/Packages/SherpaOnnx/sherpa-onnx.xcframework/ios-arm64_x86_64-simulator/libsherpa-onnx.a +0 -0
  432. package/ios/Packages/libbz2/module.modulemap +5 -0
  433. package/ios/Packages/libbz2/shim.h +1 -0
  434. package/ios/PhotoReceiverModule.swift +129 -0
  435. package/ios/Source/BluetoothSDK.swift +2299 -0
  436. package/ios/Source/BluetoothSDKDebug.swift +12 -0
  437. package/ios/Source/BluetoothSdkDefaults.swift +29 -0
  438. package/ios/Source/Bridge.swift +708 -0
  439. package/ios/Source/Bridging-Header.h +16 -0
  440. package/ios/Source/DeviceManager.swift +2054 -0
  441. package/ios/Source/DeviceStore.swift +350 -0
  442. package/ios/Source/GeneratedChangelogCatalog.swift +8 -0
  443. package/ios/Source/GeneratedReleaseMetadata.swift +11 -0
  444. package/ios/Source/ObservableStore.swift +118 -0
  445. package/ios/Source/OtaManifest.swift +211 -0
  446. package/ios/Source/PrivacyInfo.xcprivacy +23 -0
  447. package/ios/Source/ReleaseChangelog.swift +65 -0
  448. package/ios/Source/Resources/G2Firmware/README.md +10 -0
  449. package/ios/Source/Resources/G2Firmware/g2-glassly-cfw-2.2.9.22.evenota.bin +0 -0
  450. package/ios/Source/Resources/G2Firmware/g2-stock-2.2.9.22.evenota.bin +0 -0
  451. package/ios/Source/audio/AudioModels.swift +178 -0
  452. package/ios/Source/audio/PcmStreamPlayer.swift +410 -0
  453. package/ios/Source/camera/CameraModels.swift +866 -0
  454. package/ios/Source/connection/ScanSession.swift +27 -0
  455. package/ios/Source/controllers/ControllerManager.swift +184 -0
  456. package/ios/Source/controllers/R1.swift +925 -0
  457. package/ios/Source/errors/BluetoothSdkError.swift +19 -0
  458. package/ios/Source/events/BluetoothEvents.swift +342 -0
  459. package/ios/Source/internal/BleTraceLogger.swift +192 -0
  460. package/ios/Source/internal/BluetoothAvailability.swift +78 -0
  461. package/ios/Source/internal/BluetoothSdkAnalytics.swift +199 -0
  462. package/ios/Source/internal/ValueParsing.swift +99 -0
  463. package/ios/Source/requests/DisplayRequests.swift +82 -0
  464. package/ios/Source/services/PhoneMic.swift +662 -0
  465. package/ios/Source/sgcs/Ar99.swift +2451 -0
  466. package/ios/Source/sgcs/G1.swift +2554 -0
  467. package/ios/Source/sgcs/G2.swift +7142 -0
  468. package/ios/Source/sgcs/G2CfwClassification.swift +43 -0
  469. package/ios/Source/sgcs/G2CfwRenderer.swift +1295 -0
  470. package/ios/Source/sgcs/G2CfwTextureCache.swift +233 -0
  471. package/ios/Source/sgcs/G2FlashProtocol.swift +312 -0
  472. package/ios/Source/sgcs/G2Flasher.swift +773 -0
  473. package/ios/Source/sgcs/Mach1.swift +541 -0
  474. package/ios/Source/sgcs/MentraLive.swift +7011 -0
  475. package/ios/Source/sgcs/MentraLiveL2capChannel.swift +183 -0
  476. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +64 -0
  477. package/ios/Source/sgcs/MentraNex.swift +3220 -0
  478. package/ios/Source/sgcs/Nimo.swift +1886 -0
  479. package/ios/Source/sgcs/SGCManager.swift +621 -0
  480. package/ios/Source/sgcs/Simulated.swift +274 -0
  481. package/ios/Source/sgcs/ar99/ota/Ar99OtaManager.swift +637 -0
  482. package/ios/Source/sgcs/glassly_ble.pb.swift +4354 -0
  483. package/ios/Source/speakerid/SpeakerIdEngine.swift +573 -0
  484. package/ios/Source/status/DeviceStatus.swift +981 -0
  485. package/ios/Source/status/RuntimeState.swift +359 -0
  486. package/ios/Source/status/WifiHotspotStatus.swift +345 -0
  487. package/ios/Source/streaming/StreamModels.swift +693 -0
  488. package/ios/Source/stt/STTTools.swift +191 -0
  489. package/ios/Source/stt/SherpaOnnxTranscriber.swift +466 -0
  490. package/ios/Source/tts/TTSTools.swift +167 -0
  491. package/ios/Source/types/DeviceModels.swift +177 -0
  492. package/ios/Source/utils/AudioSessionMonitor.swift +283 -0
  493. package/ios/Source/utils/BinaryCodec.swift +61 -0
  494. package/ios/Source/utils/BleJsonCompact.swift +405 -0
  495. package/ios/Source/utils/BleWireProtocol.swift +92 -0
  496. package/ios/Source/utils/Constants.swift +78 -0
  497. package/ios/Source/utils/Enums.swift +95 -0
  498. package/ios/Source/utils/G1Text.swift +2096 -0
  499. package/ios/Source/utils/G2NotifyFile.swift +116 -0
  500. package/ios/Source/utils/JSCExperiment.swift +241 -0
  501. package/ios/Source/utils/MemoryMonitor.swift +44 -0
  502. package/ios/Source/utils/MessageChunkReassembler.swift +190 -0
  503. package/ios/Source/utils/MessageChunker.swift +294 -0
  504. package/ios/Source/utils/Models.swift +135 -0
  505. package/ios/Source/utils/PhoneAudioMonitor.swift +230 -0
  506. package/ios/Source/utils/TarBz2Extractor.swift +257 -0
  507. package/ios/Tests/BluetoothSDKTests/G2CfwClassificationTests.swift +78 -0
  508. package/ios/Tests/BluetoothSDKTests/G2CfwRendererTests.swift +372 -0
  509. package/ios/Tests/BluetoothSDKTests/G2CfwTextureCacheTests.swift +162 -0
  510. package/ios/Tests/BluetoothSDKTests/G2FlashProtocolTests.swift +182 -0
  511. package/ios/Tests/BluetoothSDKTests/G2NotifyFileTests.swift +91 -0
  512. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +160 -0
  513. package/ios/Tests/ReleaseChangelogTests.swift +13 -0
  514. package/package.json +129 -0
  515. package/plugin/build/index.d.ts +10 -0
  516. package/plugin/build/index.js +12 -0
  517. package/plugin/build/withAndroid.d.ts +3 -0
  518. package/plugin/build/withAndroid.js +190 -0
  519. package/plugin/build/withIos.d.ts +5 -0
  520. package/plugin/build/withIos.js +108 -0
  521. package/scripts/inject-ios-sdk-version.mjs +65 -0
  522. package/scripts/public-ota-api.test.mjs +37 -0
  523. package/scripts/verify-release-package.mjs +46 -0
  524. package/scripts/write-release-metadata.mjs +154 -0
  525. package/scripts/write-release-metadata.test.mjs +37 -0
  526. package/src/BluetoothSdk.types.ts +1659 -0
  527. package/src/_internal.ts +16 -0
  528. package/src/_private/BluetoothSdkModule.ts +683 -0
  529. package/src/_private/LocalNetworkModule.ts +50 -0
  530. package/src/_private/cameraRequestPayload.ts +34 -0
  531. package/src/_private/photoRequestPayload.ts +90 -0
  532. package/src/_private/sdkOtaManifest.ts +18 -0
  533. package/src/changelogs.ts +46 -0
  534. package/src/debug.ts +9 -0
  535. package/src/generated/changelogCatalog.ts +17 -0
  536. package/src/generated/releaseMetadata.ts +20 -0
  537. package/src/index.ts +320 -0
  538. package/src/ota-server/OtaServer.types.ts +10 -0
  539. package/src/ota-server/OtaServerModule.ts +23 -0
  540. package/src/ota-server/OtaServerModule.web.ts +17 -0
  541. package/src/ota-server/index.ts +2 -0
  542. package/src/ota-transport/index.ts +116 -0
  543. package/src/photo-receiver/PhotoReceiver.types.ts +20 -0
  544. package/src/photo-receiver/PhotoReceiverModule.ts +11 -0
  545. package/src/photo-receiver/PhotoReceiverModule.web.ts +17 -0
  546. package/src/photo-receiver/index.ts +2 -0
  547. package/src/react/index.ts +21 -0
  548. package/src/react/useBluetooth.ts +309 -0
  549. package/src/react/useBluetoothEvent.ts +35 -0
  550. package/src/react/useBluetoothScan.ts +173 -0
  551. package/src/react/useBluetoothStatus.ts +180 -0
  552. package/src/react/useGlassesConnection.ts +202 -0
  553. package/src/types/index.ts +12 -0
@@ -0,0 +1,3837 @@
1
+ package com.glassly.bluetoothsdk.sgcs
2
+
3
+
4
+ import android.bluetooth.BluetoothAdapter
5
+ import android.bluetooth.BluetoothDevice
6
+ import android.bluetooth.BluetoothGatt
7
+ import android.bluetooth.BluetoothGattCallback
8
+ import android.bluetooth.BluetoothGattCharacteristic
9
+ import android.bluetooth.BluetoothGattDescriptor
10
+ import android.bluetooth.BluetoothGattService
11
+ import android.bluetooth.BluetoothProfile
12
+ import android.bluetooth.le.BluetoothLeScanner
13
+ import android.bluetooth.le.ScanCallback
14
+ import android.bluetooth.le.ScanFilter
15
+ import android.bluetooth.le.ScanResult
16
+ import android.bluetooth.le.ScanSettings
17
+ import android.content.BroadcastReceiver
18
+ import android.content.Context
19
+ import android.content.Intent
20
+ import android.content.IntentFilter
21
+ import android.graphics.Bitmap
22
+ import android.graphics.BitmapFactory
23
+ import android.os.Handler
24
+ import android.os.Looper
25
+ import android.util.Log
26
+ import android.util.SparseArray
27
+
28
+ import java.io.IOException
29
+ import java.io.InputStream
30
+ import java.util.concurrent.BlockingQueue
31
+ import java.util.concurrent.CountDownLatch
32
+ import java.util.concurrent.TimeUnit
33
+ import java.util.concurrent.ExecutorService
34
+ import java.util.concurrent.Executors
35
+
36
+ //BMP
37
+ import java.util.ArrayList
38
+ import java.util.concurrent.LinkedBlockingQueue
39
+ import java.util.zip.CRC32
40
+ import java.nio.ByteBuffer
41
+
42
+ import com.google.gson.Gson
43
+
44
+ import org.json.JSONArray
45
+ import org.json.JSONException
46
+ import org.json.JSONObject
47
+
48
+ import java.lang.reflect.Method
49
+ import java.nio.charset.StandardCharsets
50
+ import java.util.Arrays
51
+ import java.util.UUID
52
+ import java.util.concurrent.Semaphore
53
+ import java.util.regex.Matcher
54
+ import java.util.regex.Pattern
55
+ import java.util.HashMap
56
+ import java.util.HashSet
57
+
58
+ // Glassly
59
+ import com.glassly.bluetoothsdk.DeviceManager
60
+ import com.glassly.bluetoothsdk.Bridge
61
+ import com.glassly.bluetoothsdk.PhotoRequest
62
+ import com.glassly.bluetoothsdk.utils.DeviceTypes
63
+ import com.glassly.bluetoothsdk.utils.BitmapJavaUtils
64
+
65
+ import com.glassly.bluetoothsdk.utils.BitmapJavaUtils.convertBitmapTo1BitBmpBytes
66
+
67
+ import com.glassly.bluetoothsdk.utils.G1Text
68
+ import com.glassly.bluetoothsdk.utils.SmartGlassesConnectionState
69
+ import com.glassly.lc3Lib.Lc3Cpp
70
+ import com.glassly.bluetoothsdk.DeviceStore
71
+
72
+ class G1 : SGCManager() {
73
+
74
+ companion object {
75
+ private const val TAG = "WearableAi_EvenRealitiesG1SGC"
76
+ const val SHARED_PREFS_NAME = "EvenRealitiesPrefs"
77
+
78
+ const val LEFT_DEVICE_KEY = "SavedG1LeftName"
79
+ const val RIGHT_DEVICE_KEY = "SavedG1RightName"
80
+
81
+ private val UART_SERVICE_UUID: UUID = UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
82
+ private val UART_TX_CHAR_UUID: UUID = UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E")
83
+ private val UART_RX_CHAR_UUID: UUID = UUID.fromString("6E400003-B5A3-F393-E0A9-E50E24DCCA9E")
84
+ private val CLIENT_CHARACTERISTIC_CONFIG_UUID: UUID = UUID
85
+ .fromString("00002902-0000-1000-8000-00805f9b34fb")
86
+ private const val SAVED_G1_ID_KEY = "SAVED_G1_ID_KEY"
87
+
88
+ private const val DELAY_BETWEEN_SENDS_MS = 5L // not using now
89
+ private const val DELAY_BETWEEN_CHUNKS_SEND = 5L // super small just in case
90
+ private const val DELAY_BETWEEN_ACTIONS_SEND = 250L // not using now
91
+ private const val HEARTBEAT_INTERVAL_MS = 15000L
92
+ private const val MICBEAT_INTERVAL_MS = (1000L * 60) * 30 // micbeat every 30 minutes
93
+
94
+ private const val BASE_RECONNECT_DELAY_MS = 3000L // Start with 3 seconds
95
+ private const val MAX_RECONNECT_DELAY_MS = 60000L
96
+
97
+ private const val BOND_RETRY_DELAY_MS = 5000L // 5-second backoff
98
+
99
+ private const val CONNECTION_TIMEOUT_MS = 10000L // 10 seconds
100
+
101
+ private const val DEBOUNCE_DELAY_MS = 270L // Minimum time between chunk sends
102
+
103
+ private const val RIGHT_CONNECTION_RETRY_DELAY = 1000L // 1 second
104
+
105
+ private const val INITIAL_CONNECTION_DELAY_MS = 350L // Adjust this value as needed
106
+
107
+ private const val NOTIFICATION = 0x4B // Notification command
108
+
109
+ // Constants for text wall display
110
+ private const val TEXT_COMMAND = 0x4E // Text command
111
+ private const val DISPLAY_WIDTH = 488
112
+ private const val DISPLAY_USE_WIDTH = 488 // How much of the display to use
113
+ private const val FONT_MULTIPLIER = 1 / 50.0f
114
+ private const val OLD_FONT_SIZE = 21 // Font size
115
+ private const val FONT_DIVIDER = 2.0f
116
+ private const val LINES_PER_SCREEN = 5 // Lines per screen
117
+ private const val MAX_CHUNK_SIZE = 176 // Maximum chunk size for BLE packets
118
+ // private static final int INDENT_SPACES = 32; // Number of spaces to indent
119
+ // text
120
+
121
+ // handle white list stuff
122
+ private const val WHITELIST_CMD = 0x04 // Command ID for whitelist
123
+
124
+ // BMP handling
125
+
126
+ // Add these class variables
127
+ private const val BMP_CHUNK_SIZE = 194
128
+ private val GLASSES_ADDRESS = byteArrayOf(0x00, 0x1c, 0x00, 0x00)
129
+ private val END_COMMAND = byteArrayOf(0x20, 0x0d, 0x0e)
130
+ private const val MAX_BMP_RETRY_ATTEMPTS = 10
131
+ private const val BMP_RETRY_DELAY_MS = 1000L
132
+
133
+ // Platform-specific timing (matching Flutter implementation)
134
+ // private static final long ANDROID_CHUNK_DELAY_MS = 5;
135
+ private const val ANDROID_CHUNK_DELAY_MS = 8L
136
+ private const val IOS_CHUNK_DELAY_MS = 8L
137
+ private const val END_COMMAND_TIMEOUT_MS = 3000L
138
+ private const val CRC_COMMAND_TIMEOUT_MS = 3000L
139
+ private const val CHUNK_SEND_TIMEOUT_MS = 5000L
140
+
141
+ // Optimized bitmap display flags
142
+ private const val USE_OPTIMIZED_BITMAP_DISPLAY = true
143
+ private const val USE_PARALLEL_BITMAP_WRITES = true
144
+
145
+ @JvmStatic
146
+ fun savePreferredG1DeviceId(context: Context?, deviceName: String?) {
147
+ Bridge.saveSetting("deviceName", deviceName!!)
148
+ }
149
+
150
+ @JvmStatic
151
+ fun deleteEvenSharedPreferences(context: Context?) {
152
+ // savePreferredG1DeviceId(context, null);
153
+ // SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFS_NAME,
154
+ // Context.MODE_PRIVATE);
155
+ // prefs.edit().clear().apply();
156
+ // Bridge.log("G1: Nuked EvenRealities SharedPreferences");
157
+ }
158
+
159
+ private fun bytesToHex(bytes: ByteArray): String {
160
+ val sb = StringBuilder()
161
+ for (b in bytes) {
162
+ sb.append(String.format("%02X ", b))
163
+ }
164
+ return sb.toString().trim()
165
+ }
166
+
167
+ private fun bytesToUtf8(bytes: ByteArray): String {
168
+ return String(bytes, StandardCharsets.UTF_8)
169
+ }
170
+
171
+ /**
172
+ * Decodes Even G1 serial number to extract style and color information
173
+ *
174
+ * @param serialNumber The full serial number (e.g., "S110LABD020021")
175
+ * @return Array containing [style, color] or ["Unknown", "Unknown"] if invalid
176
+ */
177
+ @JvmStatic
178
+ fun decodeEvenG1SerialNumber(serialNumber: String?): Array<String> {
179
+ if (serialNumber == null || serialNumber.length < 6) {
180
+ return arrayOf("Unknown", "Unknown")
181
+ }
182
+
183
+ // Style mapping: 3rd character (index 2)
184
+ val style: String
185
+ when (serialNumber[1]) {
186
+ '0' ->
187
+ style = "Round"
188
+ '1' ->
189
+ style = "Rectangular"
190
+ else ->
191
+ style = "Round"
192
+ }
193
+
194
+ // Color mapping: 5th character (index 4)
195
+ val color: String
196
+ when (serialNumber[4]) {
197
+ 'A' ->
198
+ color = "Grey"
199
+ 'B' ->
200
+ color = "Brown"
201
+ 'C' ->
202
+ color = "Green"
203
+ else ->
204
+ color = "Grey"
205
+ }
206
+
207
+ return arrayOf(style, color)
208
+ }
209
+ }
210
+
211
+ private var heartbeatCount = 0
212
+ private var micBeatCount = 0
213
+ private var bluetoothAdapter: BluetoothAdapter? = null
214
+
215
+ private var isKilled = false
216
+
217
+ private var context: Context? = null
218
+ private var leftGlassGatt: BluetoothGatt? = null
219
+ private var rightGlassGatt: BluetoothGatt? = null
220
+ private var leftTxChar: BluetoothGattCharacteristic? = null
221
+ private var rightTxChar: BluetoothGattCharacteristic? = null
222
+ private var leftRxChar: BluetoothGattCharacteristic? = null
223
+ private var rightRxChar: BluetoothGattCharacteristic? = null
224
+ // Not named connectionState: Kotlin can't shadow SGCManager's public val
225
+ // connectionState with a private field of another type.
226
+ private var g1ConnectionState = SmartGlassesConnectionState.DISCONNECTED
227
+ // Declared before init so the constructor body can assign it.
228
+ private var bitmapExecutor: ExecutorService? = null
229
+ private val handler = Handler(Looper.getMainLooper())
230
+ private val queryBatteryStatusHandler = Handler(Looper.getMainLooper())
231
+ private val sendBrightnessCommandHandler = Handler(Looper.getMainLooper())
232
+ private var connectHandler = Handler(Looper.getMainLooper())
233
+ private var reconnectHandler = Handler(Looper.getMainLooper())
234
+ private var characteristicHandler = Handler(Looper.getMainLooper())
235
+ private val sendSemaphore = Semaphore(1)
236
+ private var isLeftConnected = false
237
+ private var isRightConnected = false
238
+ private var currentSeq = 0
239
+ private var stopper = false
240
+ private var debugStopper = false
241
+ private var shouldUseAutoBrightness = false
242
+ private var updatingScreen = false
243
+
244
+
245
+ private var batteryLeft = -1
246
+ private var batteryRight = -1
247
+ private var leftReconnectAttempts = 0
248
+ private var rightReconnectAttempts = 0
249
+ private var reconnectAttempts = 0 // Counts the number of reconnect attempts
250
+
251
+ // heartbeat sender
252
+ private var heartbeatHandler = Handler()
253
+ private var findCompatibleDevicesHandler: Handler? = null
254
+ private var isScanningForCompatibleDevices = false
255
+ private var isScanning = false
256
+
257
+ private var heartbeatRunnable: Runnable? = null
258
+
259
+ // mic heartbeat turn on
260
+ private var micBeatHandler = Handler()
261
+ private var micBeatRunnable: Runnable? = null
262
+
263
+ // white list sender
264
+ private var whiteListHandler = Handler()
265
+ private var whiteListedAlready = false
266
+
267
+ // mic enable Handler
268
+ private var micEnableHandler = Handler()
269
+ private var isMicrophoneEnabled = false // Track current microphone state
270
+
271
+ // notification period sender
272
+ private var notificationHandler = Handler()
273
+ private var notificationRunnable: Runnable? = null
274
+ private var notifysStarted = false
275
+ private var notificationNum = 10
276
+
277
+ // text wall periodic sender
278
+ private var textWallHandler = Handler()
279
+ private var textWallRunnable: Runnable? = null
280
+ private var textWallsStarted = false
281
+ private var textWallNum = 10
282
+
283
+ // pairing logic
284
+ private var isLeftPairing = false
285
+ private var isRightPairing = false
286
+ private var isLeftBonded = false
287
+ private var isRightBonded = false
288
+ private var leftDevice: BluetoothDevice? = null
289
+ private var rightDevice: BluetoothDevice? = null
290
+ private var leftDeviceName: String? = null // Store name separately since BluetoothDevice.getName() can become null
291
+ private var rightDeviceName: String? = null // Store name separately since BluetoothDevice.getName() can become null
292
+ private var preferredG1Id: String? = null
293
+ private var pendingSavedG1LeftName: String? = null
294
+ private var pendingSavedG1RightName: String? = null
295
+ private var savedG1LeftName: String? = null
296
+ private var savedG1RightName: String? = null
297
+ private var preferredG1DeviceId: String? = null
298
+
299
+ // handler to turn off screen
300
+ // Handler goHomeHandler;
301
+ // Runnable goHomeRunnable;
302
+
303
+ // Retry handler
304
+ var retryBondHandler: Handler? = null
305
+
306
+ // remember when we connected
307
+ private var lastConnectionTimestamp = 0L
308
+
309
+ // Handlers for connection timeouts
310
+ private val leftConnectionTimeoutHandler = Handler(Looper.getMainLooper())
311
+ private val rightConnectionTimeoutHandler = Handler(Looper.getMainLooper())
312
+
313
+ // Runnable tasks for handling timeouts
314
+ private var leftConnectionTimeoutRunnable: Runnable? = null
315
+ private var rightConnectionTimeoutRunnable: Runnable? = null
316
+ private var isBondingReceiverRegistered = false
317
+ private var shouldUseGlassesMic = false
318
+ private var lastThingDisplayedWasAnImage = false
319
+
320
+ // serialNumber/style/color come from SGCManager's val properties; do not
321
+ // redeclare them here.
322
+
323
+ // fonts in G1
324
+ private var g1Text: G1Text? = null
325
+
326
+ @Volatile private var lastSendTimestamp = 0L
327
+ private var lc3DecoderPtr = 0L
328
+
329
+ init {
330
+ this.type = DeviceTypes.G1
331
+ this.hasMic = true // G1 has a built-in microphone
332
+ DeviceStore.apply("glasses", "micEnabled", false)
333
+ Bridge.log("G1: G1 constructor")
334
+ this.context = Bridge.getContext()
335
+ loadPairedDeviceNames()
336
+ // goHomeHandler = new Handler();
337
+ // this.smartGlassesDevice = smartGlassesDevice;
338
+ preferredG1DeviceId = DeviceStore.get("bluetooth", "device_name") as String?
339
+ this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
340
+ this.shouldUseGlassesMic = false
341
+
342
+ // Initialize bitmap executor for parallel operations
343
+ if (USE_PARALLEL_BITMAP_WRITES) {
344
+ bitmapExecutor = Executors.newFixedThreadPool(2)
345
+ }
346
+
347
+ // setup LC3 decoder
348
+ if (lc3DecoderPtr == 0L) {
349
+ lc3DecoderPtr = Lc3Cpp.initDecoder()
350
+ }
351
+
352
+ // setup fonts
353
+ g1Text = G1Text()
354
+ DeviceStore.apply("glasses", "caseRemoved", true)
355
+ }
356
+
357
+ private val leftGattCallback: BluetoothGattCallback = createGattCallback("Left")
358
+ private val rightGattCallback: BluetoothGattCallback = createGattCallback("Right")
359
+
360
+ private fun createGattCallback(side: String): BluetoothGattCallback {
361
+ return object : BluetoothGattCallback() {
362
+ override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
363
+ // Bridge.log("G1: ConnectionStateChanged");
364
+ // Cancel the connection timeout
365
+ if ("Left" == side && leftConnectionTimeoutRunnable != null) {
366
+ leftConnectionTimeoutHandler.removeCallbacks(leftConnectionTimeoutRunnable!!)
367
+ leftConnectionTimeoutRunnable = null
368
+ } else if ("Right" == side && rightConnectionTimeoutRunnable != null) {
369
+ rightConnectionTimeoutHandler.removeCallbacks(rightConnectionTimeoutRunnable!!)
370
+ rightConnectionTimeoutRunnable = null
371
+ }
372
+
373
+ if (status == BluetoothGatt.GATT_SUCCESS) {
374
+
375
+ if (newState == BluetoothProfile.STATE_CONNECTED) {
376
+ Bridge.log("G1: " + side + " glass connected, discovering services...")
377
+ if ("Left" == side) {
378
+ isLeftConnected = true
379
+ leftReconnectAttempts = 0
380
+ } else {
381
+ isRightConnected = true
382
+ rightReconnectAttempts = 0
383
+ }
384
+
385
+ if (isLeftConnected && isRightConnected) {
386
+ stopScan()
387
+ Bridge.log("G1: Both glasses connected. Stopping BLE scan.")
388
+ }
389
+
390
+ Bridge.log("G1: Discover services calling...")
391
+ gatt.discoverServices()
392
+ } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
393
+ Bridge.log("G1: Glass disconnected, stopping heartbeats")
394
+ Bridge.log("G1: Entering STATE_DISCONNECTED branch for side: " + side)
395
+
396
+ // Mark both sides as not ready (you could also clear both if one disconnects)
397
+ leftServicesWaiter.setTrue()
398
+ rightServicesWaiter.setTrue()
399
+ Bridge.log("G1: Set leftServicesWaiter and rightServicesWaiter to true.")
400
+
401
+ forceSideDisconnection()
402
+ Bridge.log("G1: Called forceSideDisconnection().")
403
+
404
+ // Stop any periodic transmissions
405
+ stopHeartbeat()
406
+ stopMicBeat()
407
+ sendQueue.clear()
408
+ Bridge.log("G1: Stopped heartbeat and mic beat; cleared sendQueue.")
409
+
410
+ updateConnectionState()
411
+ Bridge.log("G1: Updated connection state after disconnection.")
412
+
413
+ // Compute reconnection delay for both sides (here you could choose the maximum
414
+ // of the two delays or a new delay)
415
+ // long delayLeft = Math.min(BASE_RECONNECT_DELAY_MS * (1L <<
416
+ // leftReconnectAttempts), MAX_RECONNECT_DELAY_MS);
417
+ // long delayRight = Math.min(BASE_RECONNECT_DELAY_MS * (1L <<
418
+ // rightReconnectAttempts), MAX_RECONNECT_DELAY_MS);
419
+ val delay = 2000L // or choose another strategy
420
+ // Bridge.log("G1: Computed delayLeft: " + delayLeft + " ms, delayRight: " +
421
+ // delayRight + " ms. Using delay: " + delay + " ms.");
422
+
423
+ Bridge.log("G1: " +
424
+ side + " glass disconnected. Scheduling reconnection for both glasses in " + delay
425
+ + " ms (Left attempts: " + leftReconnectAttempts + ", Right attempts: "
426
+ + rightReconnectAttempts + ")")
427
+
428
+ // if (gatt.getDevice() != null) {
429
+ // // Close the current gatt connection
430
+ // Bridge.log("G1: Closing GATT connection for device: " +
431
+ // gatt.getDevice().getAddress());
432
+ // gatt.disconnect();
433
+ // gatt.close();
434
+ // Bridge.log("G1: GATT connection closed.");
435
+ // } else {
436
+ // Bridge.log("G1: No GATT device available to disconnect.");
437
+ // }
438
+
439
+ // Schedule a reconnection for both devices after the delay
440
+ reconnectHandler.postDelayed({
441
+ Bridge.log("G1: Reconnect handler triggered after delay.")
442
+ if (gatt.device != null && !isKilled) {
443
+ Bridge.log("G1: Reconnecting to both glasses. isKilled = " + isKilled)
444
+ // Assuming you have stored references to both devices:
445
+ if (leftDevice != null) {
446
+ Bridge.log("G1: Attempting to reconnect to leftDevice: " + leftDevice!!.address)
447
+ reconnectToGatt(leftDevice!!)
448
+ } else {
449
+ Bridge.log("G1: Left device reference is null.")
450
+ }
451
+ if (rightDevice != null) {
452
+ Bridge.log("G1: Attempting to reconnect to rightDevice: " + rightDevice!!.address)
453
+ reconnectToGatt(rightDevice!!)
454
+ } else {
455
+ Bridge.log("G1: Right device reference is null.")
456
+ }
457
+ } else {
458
+ Bridge.log("G1: Reconnect handler aborted: either no GATT device or system is killed.")
459
+ }
460
+ }, delay)
461
+ }
462
+ } else {
463
+ Log.e(TAG, "Unexpected connection state encountered for " + side + " glass: " + newState)
464
+ stopHeartbeat()
465
+ stopMicBeat()
466
+ sendQueue.clear()
467
+
468
+ // Mark both sides as not ready (you could also clear both if one disconnects)
469
+ leftServicesWaiter.setTrue()
470
+ rightServicesWaiter.setTrue()
471
+
472
+ Bridge.log("G1: Stopped heartbeat and mic beat; cleared sendQueue due to connection failure.")
473
+
474
+ Log.e(TAG, side + " glass connection failed with status: " + status)
475
+ if ("Left" == side) {
476
+ isLeftConnected = false
477
+ leftReconnectAttempts++
478
+ if (leftGlassGatt != null) {
479
+ leftGlassGatt!!.disconnect()
480
+ leftGlassGatt!!.close()
481
+ }
482
+ leftGlassGatt = null
483
+ } else {
484
+ isRightConnected = false
485
+ rightReconnectAttempts++
486
+ if (rightGlassGatt != null) {
487
+ rightGlassGatt!!.disconnect()
488
+ rightGlassGatt!!.close()
489
+ }
490
+ rightGlassGatt = null
491
+ }
492
+
493
+ forceSideDisconnection()
494
+ Bridge.log("G1: Called forceSideDisconnection() after connection failure.")
495
+
496
+ // Update connection state and notify frontend of disconnection
497
+ updateConnectionState()
498
+ Bridge.log("G1: Updated connection state after connection failure.")
499
+
500
+ connectHandler.postDelayed({
501
+ Bridge.log("G1: Attempting GATT connection for leftDevice immediately.")
502
+ attemptGattConnection(leftDevice)
503
+ }, 0L)
504
+
505
+ connectHandler.postDelayed({
506
+ Bridge.log("G1: Attempting GATT connection for rightDevice after 2000 ms delay.")
507
+ attemptGattConnection(rightDevice)
508
+ }, 400L)
509
+ }
510
+ }
511
+
512
+ private fun forceSideDisconnection() {
513
+ Bridge.log("G1: forceSideDisconnection() called for side: " + side)
514
+ // Force disconnection from the other side if necessary
515
+ if ("Left" == side) {
516
+ isLeftConnected = false
517
+ leftReconnectAttempts++
518
+ Bridge.log("G1: Left glass: Marked as disconnected and incremented leftReconnectAttempts to "
519
+ + leftReconnectAttempts)
520
+ if (leftGlassGatt != null) {
521
+ Bridge.log("G1: Left glass GATT exists. Disconnecting and closing leftGlassGatt.")
522
+ leftGlassGatt!!.disconnect()
523
+ leftGlassGatt!!.close()
524
+ leftGlassGatt = null
525
+ } else {
526
+ Bridge.log("G1: Left glass GATT is already null.")
527
+ }
528
+ // If right is still connected, disconnect it too
529
+ if (rightGlassGatt != null) {
530
+ Bridge.log("G1: Left glass disconnected - forcing disconnection from right glass.")
531
+ rightGlassGatt!!.disconnect()
532
+ rightGlassGatt!!.close()
533
+ rightGlassGatt = null
534
+ isRightConnected = false
535
+ rightReconnectAttempts++
536
+ Bridge.log("G1: Right glass marked as disconnected and rightReconnectAttempts incremented to "
537
+ + rightReconnectAttempts)
538
+ } else {
539
+ Bridge.log("G1: Right glass GATT already null, no action taken.")
540
+ }
541
+ } else { // side equals "Right"
542
+ isRightConnected = false
543
+ rightReconnectAttempts++
544
+ Bridge.log("G1: Right glass: Marked as disconnected and incremented rightReconnectAttempts to "
545
+ + rightReconnectAttempts)
546
+ if (rightGlassGatt != null) {
547
+ Bridge.log("G1: Right glass GATT exists. Disconnecting and closing rightGlassGatt.")
548
+ rightGlassGatt!!.disconnect()
549
+ rightGlassGatt!!.close()
550
+ rightGlassGatt = null
551
+ } else {
552
+ Bridge.log("G1: Right glass GATT is already null.")
553
+ }
554
+ // If left is still connected, disconnect it too
555
+ if (leftGlassGatt != null) {
556
+ Bridge.log("G1: Right glass disconnected - forcing disconnection from left glass.")
557
+ leftGlassGatt!!.disconnect()
558
+ leftGlassGatt!!.close()
559
+ leftGlassGatt = null
560
+ isLeftConnected = false
561
+ leftReconnectAttempts++
562
+ Bridge.log("G1: Left glass marked as disconnected and leftReconnectAttempts incremented to "
563
+ + leftReconnectAttempts)
564
+ } else {
565
+ Bridge.log("G1: Left glass GATT already null, no action taken.")
566
+ }
567
+ }
568
+ }
569
+
570
+ override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
571
+ if (status == BluetoothGatt.GATT_SUCCESS) {
572
+ Handler(Looper.getMainLooper()).post { initG1s(gatt, side) }
573
+ }
574
+ }
575
+
576
+ override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic,
577
+ status: Int) {
578
+ if (status == BluetoothGatt.GATT_SUCCESS) {
579
+ // Bridge.log("G1: PROC_QUEUE - " + side + " glass write successful");
580
+ } else {
581
+ Bridge.log("G1: " + side + " glass write failed with status: " + status)
582
+
583
+ if (status == 133) {
584
+ Bridge.log("G1: GOT THAT 133 STATUS!")
585
+
586
+ }
587
+ }
588
+
589
+ // clear the waiter
590
+ if ("Left" == side) {
591
+ leftWaiter.setFalse()
592
+ } else {
593
+ rightWaiter.setFalse()
594
+ }
595
+ }
596
+
597
+ override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
598
+ Bridge.log("G1: PROC - GOT DESCRIPTOR WRITE: " + status)
599
+
600
+ // clear the waiter
601
+ if ("Left" == side) {
602
+ leftServicesWaiter.setFalse()
603
+ } else {
604
+ rightServicesWaiter.setFalse()
605
+ }
606
+ }
607
+
608
+ override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
609
+ characteristicHandler.post {
610
+ if (characteristic.uuid == UART_RX_CHAR_UUID) {
611
+ val data = characteristic.value
612
+ val deviceName = gatt.device.name
613
+ if (deviceName == null)
614
+ return@post
615
+
616
+ // Handle MIC audio data
617
+ if (data.isNotEmpty() && (data[0].toInt() and 0xFF) == 0xF1) {
618
+ // Bridge.log("G1: Lc3 Audio data received. Data: " + Arrays.toString(data) + ",
619
+ // from: " + deviceName);
620
+ val seq = data[1].toInt() and 0xFF // Sequence number
621
+ // eg. LC3 to PCM
622
+ val lc3 = Arrays.copyOfRange(data, 2, 202)
623
+ // byte[] pcmData = L3cCpp.decodeLC3(lc3);
624
+ // if (pcmData == null) {
625
+ // throw new IllegalStateException("Failed to decode LC3 data");
626
+ // }
627
+
628
+ if (deviceName.contains("R_")) {
629
+ // Forward raw LC3 to DeviceManager (matches iOS behavior)
630
+ // G1 uses 20-byte LC3 frames (default canonical config)
631
+ if (shouldUseGlassesMic) {
632
+ DeviceManager.getInstance().handleGlassesMicData(lc3, 20)
633
+ }
634
+ } else {
635
+ // Bridge.log("G1: Lc3 Audio data received. Seq: " + seq + ", Data: " +
636
+ // Arrays.toString(lc3) + ", from: " + deviceName);
637
+ }
638
+ }
639
+ // HEAD UP MOVEMENTS
640
+ else if (data.size > 1 && (data[0].toInt() and 0xFF) == 0xF5 && (data[1].toInt() and 0xFF) == 0x02) {
641
+ // Only check head movements from the right sensor
642
+ if (deviceName.contains("R_")) {
643
+ // Check for head down movement - initial F5 02 signal
644
+ Bridge.log("G1: HEAD UP MOVEMENT DETECTED")
645
+ DeviceStore.apply("glasses", "headUp", true)
646
+ }
647
+ }
648
+ // HEAD DOWN MOVEMENTS
649
+ else if (data.size > 1 && (data[0].toInt() and 0xFF) == 0xF5 && (data[1].toInt() and 0xFF) == 0x03) {
650
+ if (deviceName.contains("R_")) {
651
+ Bridge.log("G1: HEAD DOWN MOVEMENT DETECTED")
652
+ // clearBmpDisplay();
653
+ DeviceStore.apply("glasses", "headUp", false)
654
+ }
655
+ }
656
+ // Double tap (0xF5 0x20 / 0x00) is deliberately unhandled: on this
657
+ // firmware it clears the screen. Don't surface the touchpads until
658
+ // that is fixed.
659
+ // BATTERY RESPONSE
660
+ else if (data.size > 2 && data[0] == 0x2C.toByte() && data[1] == 0x66.toByte()) {
661
+ if (deviceName.contains("L_")) {
662
+ // Bridge.log("G1: LEFT Battery response received");
663
+ batteryLeft = data[2].toInt()
664
+ } else if (deviceName.contains("R_")) {
665
+ // Bridge.log("G1: RIGHT Battery response received");
666
+ batteryRight = data[2].toInt()
667
+ }
668
+
669
+ if (batteryLeft != -1 && batteryRight != -1) {
670
+ val minBatt = Math.min(batteryLeft, batteryRight)
671
+ DeviceStore.apply("glasses", "batteryLevel", minBatt)
672
+ }
673
+ }
674
+ // CASE REMOVED
675
+ else if (data.size > 1 && (data[0].toInt() and 0xFF) == 0xF5
676
+ && ((data[1].toInt() and 0xFF) == 0x07 || (data[1].toInt() and 0xFF) == 0x06)) {
677
+ DeviceStore.apply("glasses", "caseRemoved", true)
678
+ Bridge.log("G1: CASE REMOVED")
679
+ }
680
+ // CASE OPEN
681
+ else if (data.size > 1 && (data[0].toInt() and 0xFF) == 0xF5 && (data[1].toInt() and 0xFF) == 0x08) {
682
+ DeviceStore.apply("glasses", "caseOpen", true)
683
+ DeviceStore.apply("glasses", "caseRemoved", false)
684
+ }
685
+ // CASE CLOSED
686
+ else if (data.size > 1 && (data[0].toInt() and 0xFF) == 0xF5 && (data[1].toInt() and 0xFF) == 0x0B) {
687
+ DeviceStore.apply("glasses", "caseOpen", false)
688
+ DeviceStore.apply("glasses", "caseRemoved", false)
689
+ }
690
+ // CASE CHARGING STATUS
691
+ else if (data.size > 3 && (data[0].toInt() and 0xFF) == 0xF5 && (data[1].toInt() and 0xFF) == 0x0E) {
692
+ DeviceStore.apply("glasses", "caseCharging", (data[2].toInt() and 0xFF) == 0x01)// TODO: verify this is correct
693
+ }
694
+ // CASE CHARGING INFO
695
+ else if (data.size > 3 && (data[0].toInt() and 0xFF) == 0xF5 && (data[1].toInt() and 0xFF) == 0x0F) {
696
+ val newCaseBatteryLevel = (data[2].toInt() and 0xFF)// TODO: verify this is correct
697
+ DeviceStore.apply("glasses", "caseBatteryLevel", newCaseBatteryLevel)
698
+ }
699
+ // HEARTBEAT RESPONSE
700
+ else if (data.isNotEmpty() && data[0] == 0x25.toByte()) {
701
+ Bridge.log("G1: Heartbeat response received")
702
+ }
703
+ // TEXT RESPONSE
704
+ else if (data.isNotEmpty() && data[0] == 0x4E.toByte()) {
705
+ // Bridge.log("G1: Text response on side " + (deviceName.contains("L_") ? "Left" : "Right")
706
+ // + " was: " + ((data.length > 1 && (data[1] & 0xFF) == 0xC9) ? "SUCCEED" : "FAIL"));
707
+ }
708
+
709
+ // Handle other non-audio responses
710
+ else {
711
+ // Bridge.log("G1: PROC - Received other Even Realities response: " + bytesToHex(data) + ", from: "
712
+ // + deviceName);
713
+ }
714
+
715
+ // clear the waiter
716
+ // if ((data.length > 1 && (data[1] & 0xFF) == 0xC9)){
717
+ // if (deviceName.contains("L_")) {
718
+ // Bridge.log("G1: PROC - clearing LEFT waiter on success");
719
+ // leftWaiter.setFalse();
720
+ // } else {
721
+ // Bridge.log("G1: PROC - clearing RIGHT waiter on success");
722
+ // rightWaiter.setFalse();
723
+ // }
724
+ // }
725
+ }
726
+ }
727
+ }
728
+
729
+ }
730
+ }
731
+
732
+ private fun initG1s(gatt: BluetoothGatt, side: String) {
733
+ gatt.requestMtu(251) // Request a higher MTU size
734
+ Bridge.log("G1: Requested MTU size: 251")
735
+
736
+ val uartService = gatt.getService(UART_SERVICE_UUID)
737
+
738
+ if (uartService != null) {
739
+ val txChar = uartService.getCharacteristic(UART_TX_CHAR_UUID)
740
+ val rxChar = uartService.getCharacteristic(UART_RX_CHAR_UUID)
741
+
742
+ if (txChar != null) {
743
+ if ("Left" == side)
744
+ leftTxChar = txChar
745
+ else
746
+ rightTxChar = txChar
747
+ // enableNotification(gatt, txChar, side);
748
+ // txChar.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
749
+ Bridge.log("G1: " + side + " glass TX characteristic found")
750
+ }
751
+
752
+ if (rxChar != null) {
753
+ if ("Left" == side)
754
+ leftRxChar = rxChar
755
+ else
756
+ rightRxChar = rxChar
757
+ enableNotification(gatt, rxChar, side)
758
+ // rxChar.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
759
+ Bridge.log("G1: " + side + " glass RX characteristic found")
760
+ }
761
+
762
+ // Mark as connected but wait for setup below to update connection state
763
+ if ("Left" == side) {
764
+ isLeftConnected = true
765
+ Bridge.log("G1: PROC_QUEUE - left side setup complete")
766
+ } else {
767
+ isRightConnected = true
768
+ // Bridge.log("G1: PROC_QUEUE - right side setup complete");
769
+ }
770
+
771
+ // setup the G1s
772
+ if (isLeftConnected && isRightConnected) {
773
+ Bridge.log("G1: Sending firmware request Command")
774
+ sendDataSequentially(byteArrayOf(0x6E.toByte(), 0x74.toByte()))
775
+
776
+ Bridge.log("G1: Sending init 0x4D Command")
777
+ sendDataSequentially(byteArrayOf(0x4D.toByte(), 0xFB.toByte())) // told this is only left
778
+
779
+ Bridge.log("G1: Sending turn off wear detection command")
780
+ sendDataSequentially(byteArrayOf(0x27.toByte(), 0x00.toByte()))
781
+
782
+ Bridge.log("G1: Sending turn off silent mode Command")
783
+ sendDataSequentially(byteArrayOf(0x03.toByte(), 0x0A.toByte()))
784
+
785
+ // debug command
786
+ // Bridge.log("G1: Sending debug 0xF4 Command");
787
+ // sendDataSequentially(new byte[]{(byte) 0xF4, (byte) 0x01});
788
+
789
+ queryBatteryStatusHandler.postDelayed({ queryBatteryStatus() }, 10L)
790
+
791
+ val brightnessValue = (DeviceStore.get("bluetooth", "brightness") as Number).toInt()
792
+ val shouldUseAutoBrightness = DeviceStore.get("bluetooth", "auto_brightness") as Boolean
793
+ sendBrightnessCommandHandler
794
+ .postDelayed({ sendBrightnessCommand(brightnessValue, shouldUseAutoBrightness) }, 10L)
795
+
796
+ // MIC state is handled by DeviceManager.updateMicState() after reconnection
797
+ // Don't hardcode mic state here - let DeviceManager restore the user's preference
798
+
799
+ // enable our AugmentOS notification key
800
+ sendWhiteListCommand(10)
801
+
802
+ // start heartbeat
803
+ startHeartbeat(10000)
804
+
805
+ // start mic beat
806
+ // startMicBeat(30000);
807
+
808
+ showHomeScreen() // turn on the g1 display
809
+
810
+ updateConnectionState()
811
+
812
+ // start sending debug notifications
813
+ // startPeriodicNotifications(302);
814
+ // start sending debug notifications
815
+ // startPeriodicTextWall(302);
816
+ }
817
+ } else {
818
+ Bridge.log("G1: " + side + " glass UART service not found")
819
+ }
820
+ }
821
+
822
+ // working on all phones - must keep the delay
823
+ private fun enableNotification(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, side: String) {
824
+ Bridge.log("G1: PROC_QUEUE - Starting notification setup for " + side)
825
+
826
+ // Simply enable notifications
827
+ Bridge.log("G1: PROC_QUEUE - setting characteristic notification on side: " + side)
828
+ val result = gatt.setCharacteristicNotification(characteristic, true)
829
+ Bridge.log("G1: PROC_QUEUE - setCharacteristicNotification result for " + side + ": " + result)
830
+
831
+ // Set write type for the characteristic
832
+ characteristic.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
833
+ Bridge.log("G1: PROC_QUEUE - write type set for " + side)
834
+
835
+ // wait
836
+ Bridge.log("G1: PROC_QUEUE - waiting to enable it on this side: " + side)
837
+
838
+ try {
839
+ Thread.sleep(500)
840
+ } catch (e: InterruptedException) {
841
+ Bridge.log("G1: Error sending data: " + e.message)
842
+ }
843
+
844
+ Bridge.log("G1: PROC_QUEUE - get descriptor on side: " + side)
845
+ val descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID)
846
+ if (descriptor != null) {
847
+ Bridge.log("G1: PROC_QUEUE - setting descriptor on side: " + side)
848
+ descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
849
+ val r_result = gatt.writeDescriptor(descriptor)
850
+ Bridge.log("G1: PROC_QUEUE - set descriptor on side: " + side + " with result: " + r_result)
851
+ }
852
+ }
853
+
854
+ private fun updateConnectionState() {
855
+ val previousConnectionState = connectionState
856
+ if (isLeftConnected && isRightConnected) {
857
+ g1ConnectionState = SmartGlassesConnectionState.CONNECTED
858
+ Bridge.log("G1: Both glasses connected")
859
+ lastConnectionTimestamp = System.currentTimeMillis()
860
+ DeviceStore.apply("glasses", "fullyBooted", true)
861
+ DeviceStore.apply("glasses", "connected", true)
862
+ } else if (isLeftConnected || isRightConnected) {
863
+ g1ConnectionState = SmartGlassesConnectionState.CONNECTING
864
+ Bridge.log("G1: One glass connected")
865
+ DeviceStore.apply("glasses", "fullyBooted", false)
866
+ DeviceStore.apply("glasses", "connected", false)
867
+ } else {
868
+ g1ConnectionState = SmartGlassesConnectionState.DISCONNECTED
869
+ Bridge.log("G1: No glasses connected")
870
+ DeviceStore.apply("glasses", "fullyBooted", false)
871
+ DeviceStore.apply("glasses", "connected", false)
872
+ }
873
+ }
874
+
875
+ private val bondingReceiver: BroadcastReceiver = object : BroadcastReceiver() {
876
+ override fun onReceive(context: Context, intent: Intent) {
877
+ val action = intent.action
878
+ if (BluetoothDevice.ACTION_BOND_STATE_CHANGED == action) {
879
+ val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
880
+
881
+ // Use device address to match with stored devices instead of relying on getName()
882
+ // which can be null in the bonding broadcast
883
+ val deviceAddress = device!!.address
884
+ var isLeft = false
885
+ var isRight = false
886
+ var deviceName = device.name
887
+
888
+ // Match by address with stored left/right devices from scanning
889
+ if (leftDevice != null && leftDevice!!.address == deviceAddress) {
890
+ isLeft = true
891
+ // Use stored name string (more reliable than BluetoothDevice.getName())
892
+ if (deviceName == null) {
893
+ deviceName = leftDeviceName
894
+ }
895
+ } else if (rightDevice != null && rightDevice!!.address == deviceAddress) {
896
+ isRight = true
897
+ // Use stored name string (more reliable than BluetoothDevice.getName())
898
+ if (deviceName == null) {
899
+ deviceName = rightDeviceName
900
+ }
901
+ }
902
+
903
+ // If we couldn't match this device, it's not one we're pairing with
904
+ if (!isLeft && !isRight) {
905
+ Bridge.log("G1: Bond state changed for unknown device: " + deviceAddress)
906
+ return
907
+ }
908
+
909
+ // If name is still null after checking stored devices, log and return
910
+ if (deviceName == null) {
911
+ Bridge.log("G1: Could not determine device name for address: " + deviceAddress)
912
+ return
913
+ }
914
+
915
+ val bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1)
916
+
917
+ if (bondState == BluetoothDevice.BOND_BONDED) {
918
+ Bridge.log("G1: Bonded with device: " + deviceName + " (address: " + deviceAddress + ")")
919
+ if (isLeft) {
920
+ isLeftBonded = true
921
+ isLeftPairing = false
922
+ pendingSavedG1LeftName = deviceName
923
+ } else if (isRight) {
924
+ isRightBonded = true
925
+ isRightPairing = false
926
+ pendingSavedG1RightName = deviceName
927
+ }
928
+
929
+ // Reset both pairing flags when a device bonds successfully
930
+ // This prevents the other device from being blocked when scan restarts
931
+ isLeftPairing = false
932
+ isRightPairing = false
933
+
934
+ // Restart scan for the next device
935
+ if (!isLeftBonded || !isRightBonded) {
936
+ // if (!(isLeftBonded && !isRightBonded)){// || !doPendingPairingIdsMatch()) {
937
+ Bridge.log("G1: Restarting scan to find remaining device...")
938
+ // Add delay for vendor-specific timing issues (e.g., Motorola devices)
939
+ Handler(Looper.getMainLooper()).postDelayed({
940
+ startScan()
941
+ }, 500L) // 500ms delay
942
+ } else if (isLeftBonded && isRightBonded && !doPendingPairingIdsMatch()) {
943
+ // We've connected to two different G1s...
944
+ // Let's unpair the right, try to pair to a different one
945
+ isRightBonded = false
946
+ isRightConnected = false
947
+ isRightPairing = false
948
+ pendingSavedG1RightName = null
949
+ Bridge.log("G1: Connected to two different G1s - retry right G1 arm")
950
+ } else {
951
+ Bridge.log("G1: Both devices bonded. Proceeding with connections...")
952
+ savedG1LeftName = pendingSavedG1LeftName
953
+ savedG1RightName = pendingSavedG1RightName
954
+ savePairedDeviceNames()
955
+ stopScan()
956
+
957
+ connectHandler.postDelayed({
958
+ connectToGatt(leftDevice!!)
959
+ }, 0L)
960
+
961
+ connectHandler.postDelayed({
962
+ connectToGatt(rightDevice!!)
963
+ }, 2000L)
964
+ }
965
+ } else if (bondState == BluetoothDevice.BOND_NONE) {
966
+ Bridge.log("G1: Bonding failed for device: " + deviceName + " (address: " + deviceAddress + ")")
967
+ if (isLeft)
968
+ isLeftPairing = false
969
+ if (isRight)
970
+ isRightPairing = false
971
+
972
+ // Restart scanning to retry bonding
973
+ if (retryBondHandler == null) {
974
+ retryBondHandler = Handler(Looper.getMainLooper())
975
+ }
976
+
977
+ retryBondHandler!!.postDelayed({
978
+ Bridge.log("G1: Retrying scan after bond failure...")
979
+ startScan()
980
+ }, BOND_RETRY_DELAY_MS)
981
+ }
982
+ }
983
+ }
984
+ }
985
+
986
+ fun doPendingPairingIdsMatch(): Boolean {
987
+ val leftId = parsePairingIdFromDeviceName(pendingSavedG1LeftName)
988
+ val rightId = parsePairingIdFromDeviceName(pendingSavedG1RightName)
989
+ Bridge.log("G1: LeftID: " + leftId)
990
+ Bridge.log("G1: RightID: " + rightId)
991
+
992
+ // ok, HACKY, but if one of them is null, that means that we connected to the
993
+ // other on a previous connect
994
+ // this whole function shouldn't matter anymore anyway as we properly filter for
995
+ // the device name, so it should be fine
996
+ // in the future, the way to actually check this would be to check the final ID
997
+ // string, which is the only one guaranteed to be unique
998
+ if (leftId == null || rightId == null) {
999
+ return true
1000
+ }
1001
+
1002
+ return leftId != null && leftId == rightId
1003
+ }
1004
+
1005
+ fun parsePairingIdFromDeviceName(input: String?): String? {
1006
+ if (input == null || input.isEmpty())
1007
+ return null
1008
+ // Regular expression to match the number after "G1_"
1009
+ val pattern = Pattern.compile("G1_(\\d+)_")
1010
+ val matcher = pattern.matcher(input)
1011
+
1012
+ if (matcher.find()) {
1013
+ return matcher.group(1) // Group 1 contains the number
1014
+ }
1015
+ return null // Return null if no match is found
1016
+ }
1017
+
1018
+ private fun savePairedDeviceNames() {
1019
+ // if (savedG1LeftName != null && savedG1RightName != null) {
1020
+ // context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)
1021
+ // .edit()
1022
+ // .putString(LEFT_DEVICE_KEY, savedG1LeftName)
1023
+ // .putString(RIGHT_DEVICE_KEY, savedG1RightName)
1024
+ // .apply();
1025
+ // Bridge.log("G1: Saved paired device names: Left=" + savedG1LeftName + ", Right="
1026
+ // + savedG1RightName);
1027
+ // }
1028
+ }
1029
+
1030
+ private fun loadPairedDeviceNames() {
1031
+ // SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFS_NAME,
1032
+ // Context.MODE_PRIVATE);
1033
+ // savedG1LeftName = prefs.getString(LEFT_DEVICE_KEY, null);
1034
+ // savedG1RightName = prefs.getString(RIGHT_DEVICE_KEY, null);
1035
+ // Bridge.log("G1: Loaded paired device names: Left=" + savedG1LeftName + ", Right="
1036
+ // + savedG1RightName);
1037
+ }
1038
+
1039
+ private fun connectToGatt(device: BluetoothDevice?) {
1040
+ if (device == null) {
1041
+ Bridge.log("G1: Cannot connect to GATT: device is null")
1042
+ return
1043
+ }
1044
+
1045
+ Bridge.log("G1: connectToGatt called for device: " + device.name + " (" + device.address + ")")
1046
+ val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
1047
+ if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
1048
+ Bridge.log("G1: Bluetooth is disabled or not available. Cannot reconnect to glasses.")
1049
+ return
1050
+ }
1051
+
1052
+ // Reset the services waiter based on device name
1053
+ if (device.name.contains("_L_")) {
1054
+ Bridge.log("G1: Device identified as left side. Resetting leftServicesWaiter.")
1055
+ leftServicesWaiter.setTrue()
1056
+ } else {
1057
+ Bridge.log("G1: Device identified as right side. Resetting rightServicesWaiter.")
1058
+ rightServicesWaiter.setTrue()
1059
+ }
1060
+
1061
+ // Establish GATT connection based on device name and current connection state
1062
+ if (device.name.contains("_L_") && leftGlassGatt == null) {
1063
+ Bridge.log("G1: Connecting GATT to left side.")
1064
+ leftGlassGatt = device.connectGatt(context, false, leftGattCallback)
1065
+ isLeftConnected = false // Reset connection state
1066
+ Bridge.log("G1: Left GATT connection initiated. isLeftConnected set to false.")
1067
+ } else if (device.name.contains("_R_") && rightGlassGatt == null && isLeftConnected) {
1068
+ Bridge.log("G1: Connecting GATT to right side.")
1069
+ rightGlassGatt = device.connectGatt(context, false, rightGattCallback)
1070
+ isRightConnected = false // Reset connection state
1071
+ Bridge.log("G1: Right GATT connection initiated. isRightConnected set to false.")
1072
+ } else {
1073
+ Bridge.log("G1: Tried to connect to incorrect or already connected device: " + device.name)
1074
+ }
1075
+ }
1076
+
1077
+ private fun reconnectToGatt(device: BluetoothDevice) {
1078
+ if (isKilled) {
1079
+ return
1080
+ }
1081
+ connectToGatt(device) // Reuse the connectToGatt method
1082
+ }
1083
+
1084
+ private val seenDevices: MutableSet<String?> = HashSet()
1085
+
1086
+ private val modernScanCallback: ScanCallback = object : ScanCallback() {
1087
+ override fun onScanResult(callbackType: Int, result: ScanResult) {
1088
+ val device = result.device
1089
+ val name = device.name
1090
+
1091
+ // Now you can reference the bluetoothAdapter field if needed:
1092
+ if (!bluetoothAdapter!!.isEnabled()) {
1093
+ Bridge.log("G1: Bluetooth is disabled")
1094
+ return
1095
+ }
1096
+
1097
+ // Check if G1 arm
1098
+ if (name == null || !name.contains("Even G1_")) {
1099
+ return
1100
+ }
1101
+
1102
+ // Log all available device information for debugging
1103
+ // Bridge.log("G1: === Device Information ===");
1104
+ // Bridge.log("G1: Device Name: " + name);
1105
+ // Bridge.log("G1: Device Address: " + device.getAddress());
1106
+ // Bridge.log("G1: Device Type: " + device.getType());
1107
+ // Bridge.log("G1: Device Class: " + device.getBluetoothClass());
1108
+ // Bridge.log("G1: Bond State: " + device.getBondState());
1109
+
1110
+ // Try to get additional device information using reflection
1111
+ try {
1112
+ // Try to get the full device name (might contain serial number)
1113
+ val getAliasMethod = device.javaClass.getMethod("getAlias")
1114
+ val alias = getAliasMethod.invoke(device) as String?
1115
+ // add alias to seen device set:
1116
+ if (!seenDevices.contains(alias)) {
1117
+ seenDevices.add(alias)
1118
+ } else {
1119
+ return
1120
+ }
1121
+ Bridge.log("G1: Device Alias: " + alias)
1122
+ } catch (e: Exception) {
1123
+ Bridge.log("G1: Could not get device alias: " + e.message)
1124
+ }
1125
+
1126
+ // Capture manufacturer data for left device during scanning
1127
+ if (name != null && name.contains("_L_") && result.scanRecord != null) {
1128
+ val allManufacturerData = result.scanRecord!!.manufacturerSpecificData
1129
+ for (i in 0 until allManufacturerData.size()) {
1130
+ val parsedDeviceName = parsePairingIdFromDeviceName(name)
1131
+ if (parsedDeviceName != null) {
1132
+ // Bridge.log("G1: Parsed Device Name: " + parsedDeviceName);
1133
+ }
1134
+
1135
+ val manufacturerId = allManufacturerData.keyAt(i)
1136
+ val data = allManufacturerData.valueAt(i)
1137
+ // Bridge.log("G1: Left Device Manufacturer ID " + manufacturerId + ": " + bytesToHex(data));
1138
+
1139
+ // Try to decode serial number from this manufacturer data
1140
+ val decodedSerial = decodeSerialFromManufacturerData(data)
1141
+ if (decodedSerial != null) {
1142
+ // Bridge.log("G1: LEFT DEVICE DECODED SERIAL NUMBER from ID " + manufacturerId + ": " + decodedSerial);
1143
+ val decoded = decodeEvenG1SerialNumber(decodedSerial)
1144
+ // Bridge.log("G1: LEFT DEVICE Style: " + decoded[0] + ", Color: " + decoded[1]);
1145
+
1146
+ if (preferredG1DeviceId != null && preferredG1DeviceId == parsedDeviceName) {
1147
+ // Store the information (matching iOS implementation)
1148
+ DeviceStore.apply("glasses", "serialNumber", decodedSerial)
1149
+ DeviceStore.apply("glasses", "style", decoded[0])
1150
+ DeviceStore.apply("glasses", "color", decoded[1])
1151
+
1152
+ // Emit the serial number information to React Native
1153
+ emitSerialNumberInfo(decodedSerial, decoded[0], decoded[1])
1154
+ }
1155
+ break
1156
+ }
1157
+ }
1158
+ }
1159
+
1160
+ // Bridge.log("G1: PREFERRED ID: " + preferredG1DeviceId);
1161
+ if (preferredG1DeviceId == null || !name.contains("_" + preferredG1DeviceId + "_")) {
1162
+ // Bridge.log("G1: NOT PAIRED GLASSES");
1163
+ return
1164
+ }
1165
+
1166
+ Bridge.log("G1: FOUND OUR PREFERRED ID: " + preferredG1DeviceId)
1167
+
1168
+ val isLeft = name.contains("_L_")
1169
+
1170
+ // // If we already have saved device names for left/right...
1171
+ // if (savedG1LeftName != null && savedG1RightName != null) {
1172
+ // if (!(name.contains(savedG1LeftName) || name.contains(savedG1RightName))) {
1173
+ // return; // Not a matching device
1174
+ // }
1175
+ // }
1176
+
1177
+ // Identify which side (left/right) and store both device and name
1178
+ if (isLeft) {
1179
+ leftDevice = device
1180
+ leftDeviceName = name // Store name now since getName() can return null later
1181
+ } else {
1182
+ rightDevice = device
1183
+ rightDeviceName = name // Store name now since getName() can return null later
1184
+ }
1185
+
1186
+ val bondState = device.bondState
1187
+ if (bondState != BluetoothDevice.BOND_BONDED) {
1188
+ if (isLeft && !isLeftPairing && !isLeftBonded) {
1189
+ // Stop scan before initiating bond
1190
+ stopScan()
1191
+ // Bridge.log("G1: Bonding with Left Glass...");
1192
+ isLeftPairing = true
1193
+ g1ConnectionState = SmartGlassesConnectionState.BONDING
1194
+ // connectionEvent(g1ConnectionState);
1195
+ bondDevice(device)
1196
+ } else if (!isLeft && !isRightPairing && !isRightBonded) {
1197
+ // Stop scan before initiating bond
1198
+ stopScan()
1199
+ Bridge.log("G1: Attempting to bond with right device. isRightPairing=" + isRightPairing
1200
+ + ", isRightBonded=" + isRightBonded)
1201
+ isRightPairing = true
1202
+ g1ConnectionState = SmartGlassesConnectionState.BONDING
1203
+ // connectionEvent(g1ConnectionState);
1204
+ bondDevice(device)
1205
+ } else {
1206
+ Bridge.log("G1: Not running bonding - isLeft=" + isLeft + ", isLeftPairing=" + isLeftPairing +
1207
+ ", isLeftBonded=" + isLeftBonded + ", isRightPairing=" + isRightPairing +
1208
+ ", isRightBonded=" + isRightBonded + " - continuing scan for other side")
1209
+ }
1210
+ } else {
1211
+ // Already bonded
1212
+ if (isLeft) {
1213
+ isLeftBonded = true
1214
+ } else {
1215
+ isRightBonded = true
1216
+ }
1217
+
1218
+ // Both are bonded => connect to GATT
1219
+ if (leftDevice != null && rightDevice != null && isLeftBonded && isRightBonded) {
1220
+ Bridge.log("G1: Both sides bonded. Ready to connect to GATT.")
1221
+ stopScan()
1222
+
1223
+ connectHandler.postDelayed({
1224
+ attemptGattConnection(leftDevice)
1225
+ }, 0L)
1226
+
1227
+ connectHandler.postDelayed({
1228
+ attemptGattConnection(rightDevice)
1229
+ }, 2000L)
1230
+ } else {
1231
+ Bridge.log("G1: Not running a63dd")
1232
+ Bridge.log("G1: leftBonded=" + isLeftBonded + ", rightBonded=" + isRightBonded)
1233
+ Bridge.log("G1: leftDevice=" + leftDevice + ", rightDevice=" + rightDevice)
1234
+ }
1235
+ }
1236
+ }
1237
+
1238
+ override fun onScanFailed(errorCode: Int) {
1239
+ Bridge.log("G1: Scan failed with error: " + errorCode)
1240
+ }
1241
+ }
1242
+
1243
+ private fun resetAllBondsAndState() {
1244
+ Bridge.log("G1: Resetting ALL bonds and internal state for complete fresh start")
1245
+
1246
+ // Remove both bonds if devices exist
1247
+ if (leftDevice != null) {
1248
+ removeBond(leftDevice!!)
1249
+ }
1250
+
1251
+ if (rightDevice != null) {
1252
+ removeBond(rightDevice!!)
1253
+ }
1254
+
1255
+ // Reset all internal state
1256
+ isLeftBonded = false
1257
+ isRightBonded = false
1258
+ isLeftPairing = false
1259
+ isRightPairing = false
1260
+ isLeftConnected = false
1261
+ isRightConnected = false
1262
+
1263
+ // Clear saved device names
1264
+ pendingSavedG1LeftName = null
1265
+ pendingSavedG1RightName = null
1266
+
1267
+ // Close any existing GATT connections
1268
+ if (leftGlassGatt != null) {
1269
+ leftGlassGatt!!.disconnect()
1270
+ leftGlassGatt!!.close()
1271
+ leftGlassGatt = null
1272
+ }
1273
+
1274
+ if (rightGlassGatt != null) {
1275
+ rightGlassGatt!!.disconnect()
1276
+ rightGlassGatt!!.close()
1277
+ rightGlassGatt = null
1278
+ }
1279
+
1280
+ // Wait briefly for bond removal to complete
1281
+ Handler(Looper.getMainLooper()).postDelayed({
1282
+ Bridge.log("G1: Restarting scan after complete bond/state reset")
1283
+ g1ConnectionState = SmartGlassesConnectionState.SCANNING
1284
+ // connectionEvent(g1ConnectionState);
1285
+ startScan()
1286
+ }, 2000L)
1287
+ }
1288
+
1289
+ /**
1290
+ * Handles a device with a valid bond
1291
+ */
1292
+ private fun handleValidBond(device: BluetoothDevice, isLeft: Boolean) {
1293
+ Bridge.log("G1: Handling valid bond for " + (if (isLeft) "left" else "right") + " glass")
1294
+
1295
+ // Update state
1296
+ if (isLeft) {
1297
+ isLeftBonded = true
1298
+ } else {
1299
+ isRightBonded = true
1300
+ }
1301
+
1302
+ // If both glasses are bonded, connect to GATT
1303
+ if (leftDevice != null && rightDevice != null && isLeftBonded && isRightBonded) {
1304
+ Bridge.log("G1: Both glasses have valid bonds - ready to connect to GATT")
1305
+
1306
+ connectHandler.postDelayed({
1307
+ attemptGattConnection(leftDevice)
1308
+ }, 0L)
1309
+
1310
+ connectHandler.postDelayed({
1311
+ attemptGattConnection(rightDevice)
1312
+ }, 2000L)
1313
+ } else {
1314
+ // Continue scanning for the other glass
1315
+ Bridge.log("Still need to find " + (if (isLeft) "right" else "left") + " glass - resuming scan")
1316
+ startScan()
1317
+ }
1318
+ }
1319
+
1320
+ /**
1321
+ * Removes an existing bond with a Bluetooth device to force fresh pairing
1322
+ */
1323
+ private fun removeBond(device: BluetoothDevice?): Boolean {
1324
+ try {
1325
+ if (device == null) {
1326
+ Bridge.log("G1: Cannot remove bond: device is null")
1327
+ return false
1328
+ }
1329
+
1330
+ val method = device.javaClass.getMethod("removeBond")
1331
+ val result = method.invoke(device) as Boolean
1332
+ Bridge.log("G1: Removing bond for device " + device.name + ", result: " + result)
1333
+ return result
1334
+ } catch (e: Exception) {
1335
+ Bridge.log("G1: Error removing bond: " + e.message)
1336
+ return false
1337
+ }
1338
+ }
1339
+
1340
+ fun connectToSmartGlasses() {
1341
+ // Register bonding receiver
1342
+ val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
1343
+ context!!.registerReceiver(bondingReceiver, filter)
1344
+ isBondingReceiverRegistered = true
1345
+
1346
+ preferredG1DeviceId = DeviceStore.get("bluetooth", "device_name") as String?
1347
+
1348
+ if (!bluetoothAdapter!!.isEnabled()) {
1349
+ return
1350
+ }
1351
+
1352
+ // Start scanning for devices
1353
+ g1ConnectionState = SmartGlassesConnectionState.SCANNING
1354
+ // connectionEvent(g1ConnectionState);
1355
+ startScan()
1356
+ }
1357
+
1358
+ private fun startScan() {
1359
+ val scanner = bluetoothAdapter!!.bluetoothLeScanner
1360
+ if (scanner == null) {
1361
+ Bridge.log("G1: BluetoothLeScanner not available.")
1362
+ return
1363
+ }
1364
+
1365
+ // Optionally, define filters if needed
1366
+ val filters = ArrayList<ScanFilter>()
1367
+ // For example, to filter by device name:
1368
+ // filters.add(new ScanFilter.Builder().setDeviceName("Even G1_").build());
1369
+
1370
+ // Set desired scan settings
1371
+ val settings = ScanSettings.Builder()
1372
+ .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
1373
+ .build()
1374
+
1375
+ // Start scanning
1376
+ isScanning = true
1377
+ try {
1378
+ scanner.startScan(filters, settings, modernScanCallback)
1379
+ } catch (e: SecurityException) {
1380
+ // Auto-reconnect paths may fire before BLUETOOTH_SCAN is granted on Android 12+
1381
+ Bridge.log("G1: startScan SecurityException — bluetooth permission missing: " + e.message)
1382
+ isScanning = false
1383
+ g1ConnectionState = SmartGlassesConnectionState.DISCONNECTED
1384
+ return
1385
+ } catch (e: Exception) {
1386
+ Bridge.log("G1: startScan failed: " + e.message)
1387
+ isScanning = false
1388
+ g1ConnectionState = SmartGlassesConnectionState.DISCONNECTED
1389
+ return
1390
+ }
1391
+ Bridge.log("G1: CALL START SCAN - Started scanning for devices...")
1392
+
1393
+ // Ensure scanning state is immediately communicated to UI
1394
+ g1ConnectionState = SmartGlassesConnectionState.SCANNING
1395
+ // connectionEvent(g1ConnectionState);
1396
+
1397
+ // Stop the scan after some time (e.g., 10-15s instead of 60 to avoid
1398
+ // throttling)
1399
+ // handler.postDelayed(() -> stopScan(), 10000);
1400
+ }
1401
+
1402
+ override fun stopScan() {
1403
+ val scanner = bluetoothAdapter!!.bluetoothLeScanner
1404
+ if (scanner != null) {
1405
+ scanner.stopScan(modernScanCallback)
1406
+ }
1407
+ isScanning = false
1408
+ Bridge.log("G1: Stopped scanning for devices")
1409
+ }
1410
+
1411
+ private fun bondDevice(device: BluetoothDevice) {
1412
+ try {
1413
+ Bridge.log("G1: Attempting to bond with device: " + device.name)
1414
+ val method = device.javaClass.getMethod("createBond")
1415
+ method.invoke(device)
1416
+ } catch (e: Exception) {
1417
+ Bridge.log("G1: Bonding failed: " + e.message)
1418
+ }
1419
+ }
1420
+
1421
+ private var rightConnectionRetryRunnable: Runnable? = null
1422
+
1423
+ private fun attemptGattConnection(device: BluetoothDevice?) {
1424
+ // if (!isKilled)
1425
+
1426
+ if (device == null) {
1427
+ Bridge.log("G1: Cannot connect to GATT: Device is null")
1428
+ return
1429
+ }
1430
+
1431
+ val deviceName = device.name
1432
+ if (deviceName == null) {
1433
+ Bridge.log("G1: Skipping null device name: " + device.address
1434
+ + "... this means something horriffic has occured. Look into this.")
1435
+ return
1436
+ }
1437
+
1438
+ Bridge.log("G1: attemptGattConnection called for device: " + deviceName + " (" + device.address + ")")
1439
+
1440
+ // Check if both devices are bonded before attempting connection
1441
+ if (!isLeftBonded || !isRightBonded) {
1442
+ Bridge.log("G1: Cannot connect to GATT: Both devices are not bonded yet (isLeftBonded: " + isLeftBonded
1443
+ + ", isRightBonded: " + isRightBonded + ")")
1444
+ return
1445
+ }
1446
+
1447
+ g1ConnectionState = SmartGlassesConnectionState.CONNECTING
1448
+ Bridge.log("G1: Setting g1ConnectionState to CONNECTING. Notifying connectionEvent.")
1449
+ // connectionEvent(g1ConnectionState);
1450
+
1451
+ val isLeftDevice = deviceName.contains("_L_")
1452
+ val isRightDevice = deviceName.contains("_R_")
1453
+
1454
+ if (isLeftDevice) {
1455
+ connectLeftDevice(device)
1456
+ } else if (isRightDevice) {
1457
+ connectRightDevice(device)
1458
+ } else {
1459
+ Bridge.log("G1: Unknown device type: " + deviceName)
1460
+ }
1461
+ }
1462
+
1463
+ private fun connectLeftDevice(device: BluetoothDevice) {
1464
+ if (leftGlassGatt == null) {
1465
+ Bridge.log("G1: Attempting GATT connection for Left Glass...")
1466
+ leftGlassGatt = device.connectGatt(context, false, leftGattCallback)
1467
+ isLeftConnected = false
1468
+ Bridge.log("G1: Left GATT connection initiated. isLeftConnected set to false.")
1469
+ } else {
1470
+ Bridge.log("G1: Left Glass GATT already exists")
1471
+ }
1472
+ }
1473
+
1474
+ private fun connectRightDevice(device: BluetoothDevice) {
1475
+ // Only connect right after left is fully connected
1476
+ if (isLeftConnected) {
1477
+ if (rightGlassGatt == null) {
1478
+ Bridge.log("G1: Attempting GATT connection for Right Glass...")
1479
+ rightGlassGatt = device.connectGatt(context, false, rightGattCallback)
1480
+ isRightConnected = false
1481
+ Bridge.log("G1: Right GATT connection initiated. isRightConnected set to false.")
1482
+
1483
+ // Cancel any pending retry attempts since we're now connecting
1484
+ if (rightConnectionRetryRunnable != null) {
1485
+ connectHandler.removeCallbacks(rightConnectionRetryRunnable!!)
1486
+ rightConnectionRetryRunnable = null
1487
+ }
1488
+ } else {
1489
+ Bridge.log("G1: Right Glass GATT already exists")
1490
+ }
1491
+ } else {
1492
+ Bridge.log("G1: Waiting for left glass before connecting right. Scheduling retry in "
1493
+ + RIGHT_CONNECTION_RETRY_DELAY + "ms")
1494
+
1495
+ // Cancel any existing retry attempts to avoid duplicate retries
1496
+ if (rightConnectionRetryRunnable != null) {
1497
+ connectHandler.removeCallbacks(rightConnectionRetryRunnable!!)
1498
+ }
1499
+
1500
+ // Create new retry runnable
1501
+ rightConnectionRetryRunnable = Runnable {
1502
+ if (!isKilled) {
1503
+ Bridge.log("G1: Retrying right glass connection...")
1504
+ attemptGattConnection(device)
1505
+ } else {
1506
+ Bridge.log("G1: Connection cancelled, stopping retry attempts")
1507
+ }
1508
+ }
1509
+
1510
+ // Schedule retry
1511
+ connectHandler.postDelayed(rightConnectionRetryRunnable!!, RIGHT_CONNECTION_RETRY_DELAY)
1512
+ }
1513
+ }
1514
+
1515
+ private fun createTextPackage(text: String, currentPage: Int, totalPages: Int, screenStatus: Int): ByteArray {
1516
+ val textBytes = text.toByteArray()
1517
+ val buffer = ByteBuffer.allocate(9 + textBytes.size)
1518
+ buffer.put(0x4E.toByte())
1519
+ buffer.put((currentSeq++ and 0xFF).toByte())
1520
+ buffer.put(1.toByte())
1521
+ buffer.put(0.toByte())
1522
+ buffer.put(screenStatus.toByte())
1523
+ buffer.put(0.toByte())
1524
+ buffer.put(0.toByte())
1525
+ buffer.put(currentPage.toByte())
1526
+ buffer.put(totalPages.toByte())
1527
+ buffer.put(textBytes)
1528
+
1529
+ return buffer.array()
1530
+ }
1531
+
1532
+ private fun sendDataSequentially(data: ByteArray) {
1533
+ sendDataSequentially(data, false)
1534
+ }
1535
+
1536
+ private fun sendDataSequentially(data: List<ByteArray>) {
1537
+ sendDataSequentially(data, false)
1538
+ }
1539
+
1540
+ fun sendJson(jsonOriginal: Map<String, Any>, wakeUp: Boolean) {
1541
+
1542
+ }
1543
+
1544
+ override fun requestPhoto(request: PhotoRequest) {
1545
+
1546
+ }
1547
+
1548
+ override fun startStream(message: MutableMap<String, Any>) {
1549
+
1550
+ }
1551
+
1552
+ override fun stopStream() {
1553
+
1554
+ }
1555
+
1556
+ override fun sendStreamKeepAlive(message: MutableMap<String, Any>) {
1557
+
1558
+ }
1559
+
1560
+ override fun startVideoRecording(requestId: String, save: Boolean, sound: Boolean) {
1561
+
1562
+ }
1563
+
1564
+ override fun stopVideoRecording(requestId: String) {
1565
+
1566
+ }
1567
+
1568
+ override fun sendButtonPhotoSettings() {
1569
+
1570
+ }
1571
+
1572
+ override fun sendButtonVideoRecordingSettings() {
1573
+
1574
+ }
1575
+
1576
+ override fun sendCameraFovSetting() {
1577
+ }
1578
+
1579
+ override fun sendButtonMaxRecordingTime() {
1580
+
1581
+ }
1582
+
1583
+ override fun setBrightness(level: Int, autoMode: Boolean) {
1584
+ Bridge.log("G1: setBrightness() - level: " + level + "%, autoMode: " + autoMode)
1585
+ sendBrightnessCommand(level, autoMode)
1586
+ }
1587
+
1588
+ override fun clearDisplay() {
1589
+ Bridge.log("G1: clearDisplay() - sending space")
1590
+ // Bypass the throttle (a clear must always land) and drop any pending caption so it can't
1591
+ // overwrite the clear after the fact.
1592
+ cancelPendingThrottledText()
1593
+ displayTextWall(" ")
1594
+ }
1595
+
1596
+ // G1-specific display throttle (300ms, last-wins) — see G1.swift. G1 firmware can't absorb
1597
+ // rapid text-wall updates; coalesce to the latest within a 300ms window. Belongs in the G1 SGC
1598
+ // (G1 hardware quirk); G2 deliberately does NOT throttle (it must show every caption). The
1599
+ // trailing flush always sends the most recent text, so the final caption is never dropped —
1600
+ // only intermediate frames within a window are coalesced.
1601
+ private val textThrottleHandler = Handler(Looper.getMainLooper())
1602
+ private var textThrottlePending: String? = null
1603
+ private var textThrottleLastSent: Long = 0L
1604
+ private var textThrottleScheduled = false
1605
+ private val TEXT_THROTTLE_WINDOW_MS = 300L
1606
+
1607
+ /** Drop any pending throttled text-wall flush so it can't later overwrite a newer, non-text
1608
+ * display write (a clear, double-text-wall, or bitmap). The posted flush no-ops when
1609
+ * `textThrottlePending` is null. Called from every G1 display path that bypasses the throttle. */
1610
+ private fun cancelPendingThrottledText() {
1611
+ textThrottlePending = null
1612
+ }
1613
+
1614
+ private fun throttledTextWall(text: String) {
1615
+ val now = android.os.SystemClock.uptimeMillis()
1616
+ val sinceLast = now - textThrottleLastSent
1617
+ if (sinceLast >= TEXT_THROTTLE_WINDOW_MS) {
1618
+ // Past the window — send now.
1619
+ textThrottleLastSent = now
1620
+ textThrottlePending = null
1621
+ displayTextWall(text)
1622
+ } else {
1623
+ // Inside the window — keep only the latest and schedule one trailing flush.
1624
+ textThrottlePending = text
1625
+ if (!textThrottleScheduled) {
1626
+ textThrottleScheduled = true
1627
+ textThrottleHandler.postDelayed({
1628
+ textThrottleScheduled = false
1629
+ val pending = textThrottlePending ?: return@postDelayed
1630
+ textThrottlePending = null
1631
+ textThrottleLastSent = android.os.SystemClock.uptimeMillis()
1632
+ displayTextWall(pending)
1633
+ }, TEXT_THROTTLE_WINDOW_MS - sinceLast)
1634
+ }
1635
+ }
1636
+ }
1637
+
1638
+ override fun sendText(text: String) {
1639
+ Bridge.log("G1: sendText() - text: " + text)
1640
+ throttledTextWall(text)
1641
+ }
1642
+
1643
+ override fun sendTextWall(text: String) {
1644
+ // Bridge.log("G1: sendTextWall() - text: " + text);
1645
+ throttledTextWall(text)
1646
+ }
1647
+
1648
+ override fun sendDoubleTextWall(top: String, bottom: String) {
1649
+ cancelPendingThrottledText() // a newer layout supersedes any pending caption text
1650
+ Bridge.log("G1: sendDoubleTextWall() - top: " + top + ", bottom: " + bottom)
1651
+ displayDoubleTextWall(top, bottom)
1652
+ }
1653
+
1654
+ override fun displayBitmap(base64ImageData: String, x: Int?, y: Int?, width: Int?, height: Int?): Boolean {
1655
+ cancelPendingThrottledText() // a bitmap supersedes any pending caption text
1656
+ try {
1657
+ // Decode base64 to byte array
1658
+ val bmpData = android.util.Base64.decode(base64ImageData, android.util.Base64.DEFAULT)
1659
+
1660
+ if (bmpData == null || bmpData.isEmpty()) {
1661
+ Log.e(TAG, "Failed to decode base64 image data")
1662
+ return false
1663
+ }
1664
+
1665
+ // Call internal implementation
1666
+ displayBitmapImage(bmpData)
1667
+ return true
1668
+ } catch (e: Exception) {
1669
+ Log.e(TAG, "Error displaying bitmap from base64", e)
1670
+ return false
1671
+ }
1672
+ }
1673
+
1674
+ override fun showDashboard() {
1675
+ exit()
1676
+ }
1677
+
1678
+ override fun ping() {
1679
+ Bridge.log("G1: ping()")
1680
+ }
1681
+
1682
+ override fun dbg1() {
1683
+ }
1684
+
1685
+ override fun dbg2() {
1686
+ }
1687
+
1688
+ override fun setDashboardPosition(height: Int, depth: Int) {
1689
+ Bridge.log("G1: setDashboardPosition() - height: " + height + ", depth: " + depth)
1690
+ sendDashboardPositionCommand(height, depth)
1691
+ }
1692
+
1693
+ override fun setHeadUpAngle(angle: Int) {
1694
+ Bridge.log("G1: setHeadUpAngle() - angle: " + angle)
1695
+ sendHeadUpAngleCommand(angle)
1696
+ }
1697
+
1698
+ override fun getBatteryStatus() {
1699
+ Bridge.log("G1: Requesting battery status")
1700
+ queryBatteryStatus()
1701
+ }
1702
+
1703
+ override fun setSilentMode(enabled: Boolean) {
1704
+
1705
+ }
1706
+
1707
+ override fun exit() {
1708
+ sendExitCommand()
1709
+ }
1710
+
1711
+ override fun sendShutdown() {
1712
+ Bridge.log("sendShutdown - not supported on G1")
1713
+ }
1714
+
1715
+ override fun sendReboot() {
1716
+ Bridge.log("sendReboot - not supported on G1")
1717
+ }
1718
+
1719
+ override fun sendRgbLedControl(requestId: String, packageName: String?, action: String, color: String?, onDurationMs: Int, offDurationMs: Int, count: Int) {
1720
+ Bridge.log("sendRgbLedControl - not supported on G1")
1721
+ Bridge.sendRgbLedControlResponse(requestId, false, "device_not_supported")
1722
+ }
1723
+
1724
+ override fun disconnect() {
1725
+ DeviceStore.apply("glasses", "fullyBooted", false)
1726
+ destroy()
1727
+ }
1728
+
1729
+ override fun forget() {
1730
+ DeviceStore.apply("glasses", "fullyBooted", false)
1731
+ destroy()
1732
+ }
1733
+
1734
+ override fun connectById(id: String) {
1735
+ preferredG1DeviceId = id
1736
+ connectToSmartGlasses()
1737
+ }
1738
+
1739
+ override fun getConnectedBluetoothName(): String {
1740
+ // Return left device name if available, otherwise right device name
1741
+ if (leftDevice != null && leftDevice!!.name != null) {
1742
+ return leftDevice!!.name
1743
+ } else if (rightDevice != null && rightDevice!!.name != null) {
1744
+ return rightDevice!!.name
1745
+ }
1746
+ return ""
1747
+ }
1748
+
1749
+ override fun requestWifiScan(scanId: String?) {
1750
+
1751
+ }
1752
+
1753
+ override fun sendWifiCredentials(ssid: String, password: String) {
1754
+
1755
+ }
1756
+
1757
+ override fun forgetWifiNetwork(ssid: String) {
1758
+ // G1 doesn't support WiFi
1759
+ }
1760
+
1761
+ override fun sendHotspotState(enabled: Boolean) {
1762
+ // G1 doesn't support hotspot
1763
+ }
1764
+
1765
+ override fun sendUserEmailToGlasses(email: String) {
1766
+ // G1 doesn't support user email (no ASG client)
1767
+ }
1768
+
1769
+ override fun sendIncidentId(incidentId: String, apiBaseUrl: String?) {
1770
+ // G1 doesn't support incident reporting (no ASG client)
1771
+ }
1772
+
1773
+ override fun queryGalleryStatus() {
1774
+
1775
+ }
1776
+
1777
+ override fun sendGalleryMode() {
1778
+ // G1 doesn't have a built-in camera/gallery system
1779
+ Bridge.log("G1: sendGalleryModeActive - not supported on G1")
1780
+ }
1781
+
1782
+ override fun requestVersionInfo() {
1783
+ // G1 doesn't support version info requests
1784
+ Bridge.log("G1: requestVersionInfo - not supported on G1")
1785
+ }
1786
+
1787
+ // private void sendDataSequentially(byte[] data, boolean onlyLeft) {
1788
+ // if (stopper) return;
1789
+ // stopper = true;
1790
+ //
1791
+ // new Thread(() -> {
1792
+ // try {
1793
+ // if (leftGlassGatt != null && leftTxChar != null) {
1794
+ // leftTxChar.setValue(data);
1795
+ // leftGlassGatt.writeCharacteristic(leftTxChar);
1796
+ // Thread.sleep(DELAY_BETWEEN_SENDS_MS);
1797
+ // }
1798
+ //
1799
+ // if (!onlyLeft && rightGlassGatt != null && rightTxChar != null) {
1800
+ // rightTxChar.setValue(data);
1801
+ // rightGlassGatt.writeCharacteristic(rightTxChar);
1802
+ // Thread.sleep(DELAY_BETWEEN_SENDS_MS);
1803
+ // }
1804
+ // stopper = false;
1805
+ // } catch (InterruptedException e) {
1806
+ // Bridge.log("G1: Error sending data: " + e.getMessage());
1807
+ // }
1808
+ // }).start();
1809
+ // }
1810
+
1811
+ // Data class to represent a send request
1812
+ private class SendRequest {
1813
+ val data: ByteArray
1814
+ val onlyLeft: Boolean
1815
+ val onlyRight: Boolean
1816
+ var waitTime = -1
1817
+
1818
+ constructor(data: ByteArray, onlyLeft: Boolean, onlyRight: Boolean) {
1819
+ this.data = data
1820
+ this.onlyLeft = onlyLeft
1821
+ this.onlyRight = onlyRight
1822
+ }
1823
+
1824
+ constructor(data: ByteArray, onlyLeft: Boolean, onlyRight: Boolean, waitTime: Int) {
1825
+ this.data = data
1826
+ this.onlyLeft = onlyLeft
1827
+ this.onlyRight = onlyRight
1828
+ this.waitTime = waitTime
1829
+ }
1830
+ }
1831
+
1832
+ // Queue to hold pending requests
1833
+ private val sendQueue: BlockingQueue<Array<SendRequest?>> = LinkedBlockingQueue()
1834
+
1835
+ @Volatile private var isWorkerRunning = false
1836
+
1837
+ // Non-blocking function to add new send request
1838
+ private fun sendDataSequentially(data: ByteArray, onlyLeft: Boolean) {
1839
+ val chunks = arrayOf<SendRequest?>(SendRequest(data, onlyLeft, false))
1840
+ sendQueue.offer(chunks)
1841
+ startWorkerIfNeeded()
1842
+ }
1843
+
1844
+ // Non-blocking function to add new send request
1845
+ private fun sendDataSequentially(data: ByteArray, onlyLeft: Boolean, waitTime: Int) {
1846
+ val chunks = arrayOf<SendRequest?>(SendRequest(data, onlyLeft, false, waitTime))
1847
+ sendQueue.offer(chunks)
1848
+ startWorkerIfNeeded()
1849
+ }
1850
+
1851
+ // Overloaded function to handle multiple chunks (List<byte[]>)
1852
+ private fun sendDataSequentially(data: List<ByteArray>, onlyLeft: Boolean) {
1853
+ sendDataSequentially(data, onlyLeft, false)
1854
+ }
1855
+
1856
+ private fun sendDataSequentially(data: ByteArray, onlyLeft: Boolean, onlyRight: Boolean) {
1857
+ val chunks = arrayOf<SendRequest?>(SendRequest(data, onlyLeft, onlyRight))
1858
+ sendQueue.offer(chunks)
1859
+ startWorkerIfNeeded()
1860
+ }
1861
+
1862
+ private fun sendDataSequentially(data: ByteArray, onlyLeft: Boolean, onlyRight: Boolean, waitTime: Int) {
1863
+ val chunks = arrayOf<SendRequest?>(SendRequest(data, onlyLeft, onlyRight, waitTime))
1864
+ sendQueue.offer(chunks)
1865
+ startWorkerIfNeeded()
1866
+ }
1867
+
1868
+ private fun sendDataSequentially(data: List<ByteArray>, onlyLeft: Boolean, onlyRight: Boolean) {
1869
+ val chunks = arrayOfNulls<SendRequest>(data.size)
1870
+ for (i in 0 until data.size) {
1871
+ chunks[i] = SendRequest(data[i], onlyLeft, onlyRight)
1872
+ }
1873
+ sendQueue.offer(chunks)
1874
+ startWorkerIfNeeded()
1875
+ }
1876
+
1877
+ // Start the worker thread if it's not already running
1878
+ @Synchronized
1879
+ private fun startWorkerIfNeeded() {
1880
+ if (!isWorkerRunning) {
1881
+ isWorkerRunning = true
1882
+ Thread(this::processQueue, "EvenRealitiesG1SGCProcessQueue").start()
1883
+ }
1884
+ }
1885
+
1886
+ // Fast send method for bitmap chunks - doesn't wait for write confirmation
1887
+ private fun sendBitmapChunkNoWait(data: ByteArray?, sendLeft: Boolean, sendRight: Boolean) {
1888
+ if (data == null || data.isEmpty())
1889
+ return
1890
+
1891
+ // IMPORTANT: Set write type to NO_RESPONSE for fire-and-forget behavior
1892
+ // This prevents waiting for BLE acknowledgments
1893
+
1894
+ // Send to right glass without waiting
1895
+ if (sendRight && rightGlassGatt != null && rightTxChar != null && isRightConnected) {
1896
+ rightTxChar!!.value = data
1897
+ rightTxChar!!.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
1898
+ rightGlassGatt!!.writeCharacteristic(rightTxChar)
1899
+ // Restore default write type
1900
+ rightTxChar!!.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
1901
+ }
1902
+
1903
+ // Send to left glass without waiting
1904
+ if (sendLeft && leftGlassGatt != null && leftTxChar != null && isLeftConnected) {
1905
+ leftTxChar!!.value = data
1906
+ leftTxChar!!.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
1907
+ leftGlassGatt!!.writeCharacteristic(leftTxChar)
1908
+ // Restore default write type
1909
+ leftTxChar!!.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
1910
+ }
1911
+ }
1912
+
1913
+ class BooleanWaiter {
1914
+ private var flag = true // initially true
1915
+
1916
+ @Synchronized
1917
+ @Throws(InterruptedException::class)
1918
+ fun waitWhileTrue() {
1919
+ while (flag) {
1920
+ (this as java.lang.Object).wait()
1921
+ }
1922
+ }
1923
+
1924
+ @Synchronized
1925
+ fun setTrue() {
1926
+ flag = true
1927
+ }
1928
+
1929
+ @Synchronized
1930
+ fun setFalse() {
1931
+ flag = false
1932
+ (this as java.lang.Object).notifyAll()
1933
+ }
1934
+ }
1935
+
1936
+ private val leftWaiter = BooleanWaiter()
1937
+ private val rightWaiter = BooleanWaiter()
1938
+ private val leftServicesWaiter = BooleanWaiter()
1939
+ private val rightServicesWaiter = BooleanWaiter()
1940
+
1941
+ private fun processQueue() {
1942
+ // First wait until the services are setup and ready to receive data
1943
+ Bridge.log("G1: PROC_QUEUE - waiting on services waiters")
1944
+ try {
1945
+ leftServicesWaiter.waitWhileTrue()
1946
+ rightServicesWaiter.waitWhileTrue()
1947
+ } catch (e: InterruptedException) {
1948
+ Bridge.log("G1: Interrupted waiting for descriptor writes: " + e.toString())
1949
+ }
1950
+ Bridge.log("G1: PROC_QUEUE - DONE waiting on services waiters")
1951
+
1952
+ while (!isKilled) {
1953
+ try {
1954
+ // Make sure services are ready before processing requests
1955
+ leftServicesWaiter.waitWhileTrue()
1956
+ rightServicesWaiter.waitWhileTrue()
1957
+
1958
+ // This will block until data is available - no CPU spinning!
1959
+ val requests = sendQueue.take()
1960
+
1961
+ for (request in requests) {
1962
+ if (request == null) {
1963
+ isWorkerRunning = false
1964
+ break
1965
+ }
1966
+
1967
+ try {
1968
+ // Force an initial delay so BLE gets all setup
1969
+ val timeSinceConnection = System.currentTimeMillis() - lastConnectionTimestamp
1970
+ if (timeSinceConnection < INITIAL_CONNECTION_DELAY_MS) {
1971
+ Thread.sleep(INITIAL_CONNECTION_DELAY_MS - timeSinceConnection)
1972
+ }
1973
+
1974
+ var leftSuccess = true
1975
+ var rightSuccess = true
1976
+
1977
+ // Start both writes without waiting
1978
+ var leftStarted = false
1979
+ var rightStarted = false
1980
+
1981
+ // Start right glass write (non-blocking)
1982
+ if (!request.onlyLeft && rightGlassGatt != null && rightTxChar != null && isRightConnected) {
1983
+ rightWaiter.setTrue()
1984
+ rightTxChar!!.value = request.data
1985
+ rightSuccess = rightGlassGatt!!.writeCharacteristic(rightTxChar)
1986
+ if (rightSuccess) {
1987
+ rightStarted = true
1988
+ lastSendTimestamp = System.currentTimeMillis()
1989
+ }
1990
+ }
1991
+
1992
+ // Start left glass write immediately (non-blocking)
1993
+ if (!request.onlyRight && leftGlassGatt != null && leftTxChar != null && isLeftConnected) {
1994
+ leftWaiter.setTrue()
1995
+ leftTxChar!!.value = request.data
1996
+ leftSuccess = leftGlassGatt!!.writeCharacteristic(leftTxChar)
1997
+ if (leftSuccess) {
1998
+ leftStarted = true
1999
+ lastSendTimestamp = System.currentTimeMillis()
2000
+ }
2001
+ }
2002
+
2003
+ // Now wait for both to complete
2004
+ if (rightStarted) {
2005
+ rightWaiter.waitWhileTrue()
2006
+ }
2007
+ if (leftStarted) {
2008
+ leftWaiter.waitWhileTrue()
2009
+ }
2010
+
2011
+ Thread.sleep(DELAY_BETWEEN_CHUNKS_SEND)
2012
+
2013
+ // If the packet asked us to do a delay, then do it
2014
+ if (request.waitTime != -1) {
2015
+ Thread.sleep(request.waitTime.toLong())
2016
+ }
2017
+ } catch (e: InterruptedException) {
2018
+ Bridge.log("G1: Error sending data: " + e.message)
2019
+ if (isKilled)
2020
+ break
2021
+ }
2022
+ }
2023
+ } catch (e: InterruptedException) {
2024
+ if (isKilled) {
2025
+ Bridge.log("G1: Process queue thread interrupted - shutting down")
2026
+ break
2027
+ }
2028
+ Bridge.log("G1: Error in queue processing: " + e.message)
2029
+ }
2030
+ }
2031
+
2032
+ Bridge.log("G1: Process queue thread exiting")
2033
+ }
2034
+
2035
+ // @Override
2036
+ // public void displayReferenceCardSimple(String title, String body, int
2037
+ // lingerTimeMs) {
2038
+ // displayReferenceCardSimple(title, body, lingerTimeMs);
2039
+ // }
2040
+
2041
+ private fun createNotificationJson(appIdentifier: String, title: String, subtitle: String, message: String): String {
2042
+ val currentTime = System.currentTimeMillis() / 1000L // Unix timestamp in seconds
2043
+ val currentDate = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(java.util.Date()) // Date
2044
+ // format
2045
+ // for
2046
+ // 'date'
2047
+ // field
2048
+
2049
+ val ncsNotification = NCSNotification(
2050
+ notificationNum++, // Increment sequence ID for uniqueness
2051
+ 1, // type (e.g., 1 = notification type)
2052
+ appIdentifier,
2053
+ title,
2054
+ subtitle,
2055
+ message,
2056
+ currentTime.toInt(), // Cast long to int to match Python
2057
+ currentDate, // Add the current date to the notification
2058
+ "AugmentOS" // display_name
2059
+ )
2060
+
2061
+ val notification = Notification(ncsNotification, "Add")
2062
+
2063
+ val gson = Gson()
2064
+ return gson.toJson(notification)
2065
+ }
2066
+
2067
+ internal class Notification {
2068
+ var ncs_notification: NCSNotification? = null
2069
+ var type: String? = null
2070
+
2071
+ constructor() {
2072
+ // Default constructor
2073
+ }
2074
+
2075
+ constructor(ncs_notification: NCSNotification?, type: String?) {
2076
+ this.ncs_notification = ncs_notification
2077
+ this.type = type
2078
+ }
2079
+ }
2080
+
2081
+ internal class NCSNotification(
2082
+ var msg_id: Int,
2083
+ var type: Int,
2084
+ var app_identifier: String,
2085
+ var title: String,
2086
+ var subtitle: String,
2087
+ var message: String,
2088
+ var time_s: Int, // Changed from long to int for consistency
2089
+ var date: String, // Added to match Python's date field
2090
+ var display_name: String
2091
+ )
2092
+
2093
+ private fun createNotificationChunks(json: String): List<ByteArray> {
2094
+ val MAX_CHUNK_SIZE = 176 // 180 - 4 header bytes
2095
+ val jsonBytes = json.toByteArray(StandardCharsets.UTF_8)
2096
+ val totalChunks = Math.ceil(jsonBytes.size.toDouble() / MAX_CHUNK_SIZE).toInt()
2097
+
2098
+ val chunks = ArrayList<ByteArray>()
2099
+ for (i in 0 until totalChunks) {
2100
+ val start = i * MAX_CHUNK_SIZE
2101
+ val end = Math.min(start + MAX_CHUNK_SIZE, jsonBytes.size)
2102
+ val payloadChunk = Arrays.copyOfRange(jsonBytes, start, end)
2103
+
2104
+ // Create the header
2105
+ val header = byteArrayOf(
2106
+ NOTIFICATION.toByte(),
2107
+ 0x00, // notify_id (can be updated as needed)
2108
+ totalChunks.toByte(),
2109
+ i.toByte()
2110
+ )
2111
+
2112
+ // Combine header and payload
2113
+ val chunk = ByteBuffer.allocate(header.size + payloadChunk.size)
2114
+ chunk.put(header)
2115
+ chunk.put(payloadChunk)
2116
+
2117
+ chunks.add(chunk.array())
2118
+ }
2119
+
2120
+ return chunks
2121
+ }
2122
+
2123
+ fun displayReferenceCardSimple(title: String, body: String) {
2124
+ if (!isConnected()) {
2125
+ Bridge.log("G1: Not connected to glasses")
2126
+ return
2127
+ }
2128
+
2129
+ if (title.trim().isEmpty() && body.trim().isEmpty()) {
2130
+ if (DeviceManager.getInstance().powerSavingMode) {
2131
+ sendExitCommand()
2132
+ return
2133
+ }
2134
+ }
2135
+
2136
+ val chunks = createTextWallChunks(title + "\n\n" + body)
2137
+ for (i in 0 until chunks.size) {
2138
+ val chunk = chunks[i]
2139
+ val isLastChunk = (i == chunks.size - 1)
2140
+
2141
+ if (isLastChunk) {
2142
+ sendDataSequentially(chunk, false)
2143
+ } else {
2144
+ sendDataSequentially(chunk, false, 300)
2145
+ }
2146
+ }
2147
+ Bridge.log("G1: Send simple reference card")
2148
+ }
2149
+
2150
+ fun destroy() {
2151
+ Bridge.log("G1: EvenRealitiesG1SGC ONDESTROY")
2152
+ showHomeScreen()
2153
+ isKilled = true
2154
+ DeviceStore.apply("glasses", "fullyBooted", false)
2155
+
2156
+ // Reset battery levels
2157
+ batteryLeft = -1
2158
+ batteryRight = -1
2159
+ DeviceStore.apply("glasses", "batteryLevel", -1)
2160
+
2161
+ // stop BLE scanning
2162
+ stopScan()
2163
+
2164
+ // Shutdown bitmap executor
2165
+ if (bitmapExecutor != null) {
2166
+ bitmapExecutor!!.shutdown()
2167
+ try {
2168
+ if (!bitmapExecutor!!.awaitTermination(1, TimeUnit.SECONDS)) {
2169
+ bitmapExecutor!!.shutdownNow()
2170
+ }
2171
+ } catch (e: InterruptedException) {
2172
+ bitmapExecutor!!.shutdownNow()
2173
+ }
2174
+ }
2175
+
2176
+ if (bondingReceiver != null && isBondingReceiverRegistered) {
2177
+ context!!.unregisterReceiver(bondingReceiver)
2178
+ isBondingReceiverRegistered = false
2179
+ }
2180
+
2181
+ if (rightConnectionRetryRunnable != null) {
2182
+ connectHandler.removeCallbacks(rightConnectionRetryRunnable!!)
2183
+ rightConnectionRetryRunnable = null
2184
+ }
2185
+
2186
+ // disable the microphone
2187
+ sendSetMicEnabled(false, 0)
2188
+
2189
+ // stop sending heartbeat
2190
+ stopHeartbeat()
2191
+
2192
+ // stop sending micbeat
2193
+ stopMicBeat()
2194
+
2195
+ // Stop periodic notifications
2196
+ stopPeriodicNotifications()
2197
+
2198
+ // Stop periodic text wall
2199
+ // stopPeriodicNotifications();
2200
+
2201
+ if (leftGlassGatt != null) {
2202
+ leftGlassGatt!!.disconnect()
2203
+ leftGlassGatt!!.close()
2204
+ leftGlassGatt = null
2205
+ }
2206
+ if (rightGlassGatt != null) {
2207
+ rightGlassGatt!!.disconnect()
2208
+ rightGlassGatt!!.close()
2209
+ rightGlassGatt = null
2210
+ }
2211
+
2212
+ if (handler != null)
2213
+ handler.removeCallbacksAndMessages(null)
2214
+ if (heartbeatHandler != null && heartbeatRunnable != null)
2215
+ heartbeatHandler.removeCallbacks(heartbeatRunnable!!)
2216
+ if (whiteListHandler != null)
2217
+ whiteListHandler.removeCallbacksAndMessages(null)
2218
+ if (micEnableHandler != null)
2219
+ micEnableHandler.removeCallbacksAndMessages(null)
2220
+ if (notificationHandler != null && notificationRunnable != null)
2221
+ notificationHandler.removeCallbacks(notificationRunnable!!)
2222
+ if (textWallHandler != null && textWallRunnable != null)
2223
+ textWallHandler.removeCallbacks(textWallRunnable!!)
2224
+ // if (goHomeHandler != null)
2225
+ // goHomeHandler.removeCallbacks(goHomeRunnable);
2226
+ if (findCompatibleDevicesHandler != null)
2227
+ findCompatibleDevicesHandler!!.removeCallbacksAndMessages(null)
2228
+ if (connectHandler != null)
2229
+ connectHandler.removeCallbacksAndMessages(null)
2230
+ if (retryBondHandler != null)
2231
+ retryBondHandler!!.removeCallbacksAndMessages(null)
2232
+ if (characteristicHandler != null) {
2233
+ characteristicHandler.removeCallbacksAndMessages(null)
2234
+ }
2235
+ if (reconnectHandler != null) {
2236
+ reconnectHandler.removeCallbacksAndMessages(null)
2237
+ }
2238
+ if (leftConnectionTimeoutHandler != null && leftConnectionTimeoutRunnable != null) {
2239
+ leftConnectionTimeoutHandler.removeCallbacks(leftConnectionTimeoutRunnable!!)
2240
+ }
2241
+ if (rightConnectionTimeoutHandler != null && rightConnectionTimeoutRunnable != null) {
2242
+ rightConnectionTimeoutHandler.removeCallbacks(rightConnectionTimeoutRunnable!!)
2243
+ }
2244
+ if (reconnectHandler != null) {
2245
+ reconnectHandler.removeCallbacksAndMessages(null)
2246
+ }
2247
+ if (queryBatteryStatusHandler != null && queryBatteryStatusHandler != null) {
2248
+ queryBatteryStatusHandler.removeCallbacksAndMessages(null)
2249
+ }
2250
+
2251
+ // free LC3 decoder
2252
+ if (lc3DecoderPtr != 0L) {
2253
+ Lc3Cpp.freeDecoder(lc3DecoderPtr)
2254
+ lc3DecoderPtr = 0
2255
+ }
2256
+
2257
+ sendQueue.clear()
2258
+
2259
+ // Add a dummy element to unblock the take() call if needed
2260
+ sendQueue.offer(arrayOfNulls<SendRequest>(0)) // is this needed?
2261
+
2262
+ isWorkerRunning = false
2263
+
2264
+ isLeftConnected = false
2265
+ isRightConnected = false
2266
+
2267
+ // Clear device references and stored names
2268
+ leftDevice = null
2269
+ rightDevice = null
2270
+ leftDeviceName = null
2271
+ rightDeviceName = null
2272
+
2273
+ Bridge.log("G1: EvenRealitiesG1SGC cleanup complete")
2274
+ }
2275
+
2276
+ fun isConnected(): Boolean {
2277
+ return g1ConnectionState == SmartGlassesConnectionState.CONNECTED
2278
+ }
2279
+
2280
+ // Remaining methods
2281
+ fun showNaturalLanguageCommandScreen(prompt: String, naturalLanguageInput: String) {
2282
+ }
2283
+
2284
+ fun updateNaturalLanguageCommandScreen(naturalLanguageArgs: String) {
2285
+ }
2286
+
2287
+ fun scrollingTextViewIntermediateText(text: String) {
2288
+ }
2289
+
2290
+ fun scrollingTextViewFinalText(text: String) {
2291
+ }
2292
+
2293
+ fun stopScrollingTextViewMode() {
2294
+ }
2295
+
2296
+ fun displayPromptView(title: String, options: Array<String>) {
2297
+ }
2298
+
2299
+ fun displayTextLine(text: String) {
2300
+ }
2301
+
2302
+ fun displayBitmap(bmp: Bitmap) {
2303
+ try {
2304
+ val bmpBytes = convertBitmapTo1BitBmpBytes(bmp, false)
2305
+ displayBitmapImage(bmpBytes)
2306
+ } catch (e: Exception) {
2307
+ Log.e(TAG, e.message!!)
2308
+ }
2309
+ }
2310
+
2311
+ /**
2312
+ * Convert arbitrary image data (PNG/JPEG bytes) to G1-compatible 1-bit BMP format.
2313
+ * Mirrors G2.convertToG2Bmp() for local miniapp bitmap display support.
2314
+ *
2315
+ * @param imageData Raw image bytes (PNG, JPEG, etc.)
2316
+ * @return 1-bit BMP byte array, or null on failure
2317
+ */
2318
+ fun convertToG1Bmp(imageData: ByteArray): ByteArray? {
2319
+ try {
2320
+ val bmp = BitmapFactory.decodeByteArray(imageData, 0, imageData.size)
2321
+ if (bmp == null) {
2322
+ Bridge.log("G1: convertToG1Bmp - could not decode image data")
2323
+ return null
2324
+ }
2325
+ val bmpBytes = convertBitmapTo1BitBmpBytes(bmp, false)
2326
+ bmp.recycle()
2327
+ Bridge.log("G1: convertToG1Bmp - produced " + bmpBytes.size + " byte BMP")
2328
+ return bmpBytes
2329
+ } catch (e: Exception) {
2330
+ Log.e(TAG, "G1: convertToG1Bmp error: " + e.message)
2331
+ return null
2332
+ }
2333
+ }
2334
+
2335
+ fun blankScreen() {
2336
+ }
2337
+
2338
+ /**
2339
+ * Display pre-composed double text wall (two columns) on the glasses.
2340
+ *
2341
+ * NOTE: DisplayProcessor now composes double_text_wall into a single text_wall
2342
+ * with pixel-precise column alignment using ColumnComposer. This method may
2343
+ * not be called anymore for new flows, but is kept for backwards compatibility.
2344
+ *
2345
+ * Column composition is handled by DisplayProcessor in React Native.
2346
+ * This method is a "dumb pipe" - it just combines and sends the text.
2347
+ */
2348
+ fun displayDoubleTextWall(textTop: String, textBottom: String) {
2349
+ // Text is already composed by DisplayProcessor's ColumnComposer
2350
+ // Just combine and send as a text wall - no custom wrapping logic needed
2351
+ val combinedText = textTop + "\n" + textBottom
2352
+ displayTextWall(combinedText)
2353
+ }
2354
+
2355
+ fun showHomeScreen() {
2356
+ displayTextWall(" ")
2357
+
2358
+ // if (lastThingDisplayedWasAnImage) {
2359
+ // // clearG1Screen();
2360
+ // lastThingDisplayedWasAnImage = false;
2361
+ // }
2362
+ }
2363
+
2364
+ fun clearG1Screen() {
2365
+ Bridge.log("G1: Clearing G1 screen")
2366
+ val exitCommand = byteArrayOf(0x18.toByte())
2367
+ // sendDataSequentially(exitCommand, false);
2368
+ val theClearBitmapOrSomething = loadEmptyBmpFromAssets()
2369
+ val bmp = BitmapJavaUtils.bytesToBitmap(theClearBitmapOrSomething)
2370
+ try {
2371
+ val bmpBytes = convertBitmapTo1BitBmpBytes(bmp, false)
2372
+ displayBitmapImage(bmpBytes)
2373
+ } catch (e: Exception) {
2374
+ Log.e(TAG, "Error displaying clear bitmap: " + e.message)
2375
+ }
2376
+ }
2377
+
2378
+
2379
+ fun displayRowsCard(rowStrings: Array<String>) {
2380
+ }
2381
+
2382
+ fun displayBulletList(title: String, bullets: Array<String>) {
2383
+ }
2384
+
2385
+ fun displayReferenceCardImage(title: String, body: String, imgUrl: String) {
2386
+ }
2387
+
2388
+ fun displayTextWall(a: String) {
2389
+ val chunks = createTextWallChunks(a)
2390
+ sendChunks(chunks)
2391
+ }
2392
+
2393
+ fun setUpdatingScreen(updatingScreen: Boolean) {
2394
+ this.updatingScreen = updatingScreen
2395
+ }
2396
+
2397
+ fun setFontSizes() {
2398
+ }
2399
+
2400
+ // Heartbeat methods
2401
+ private fun constructHeartbeat(): ByteArray {
2402
+ val buffer = ByteBuffer.allocate(6)
2403
+ buffer.put(0x25.toByte())
2404
+ buffer.put(6.toByte())
2405
+ buffer.put((currentSeq and 0xFF).toByte())
2406
+ buffer.put(0x00.toByte())
2407
+ buffer.put(0x04.toByte())
2408
+ buffer.put((currentSeq++ and 0xFF).toByte())
2409
+ return buffer.array()
2410
+ }
2411
+
2412
+ private fun constructBatteryLevelQuery(): ByteArray {
2413
+ val buffer = ByteBuffer.allocate(2)
2414
+ buffer.put(0x2C.toByte()) // Command
2415
+ buffer.put(0x01.toByte()) // use 0x02 for iOS
2416
+ return buffer.array()
2417
+ }
2418
+
2419
+ private fun startHeartbeat(delay: Int) {
2420
+ Bridge.log("G1: Starting heartbeat")
2421
+ if (heartbeatCount > 0)
2422
+ stopHeartbeat()
2423
+
2424
+ heartbeatRunnable = object : Runnable {
2425
+ override fun run() {
2426
+ sendHeartbeat()
2427
+ // sendLoremIpsum();
2428
+
2429
+ // quickRestartG1();
2430
+
2431
+ heartbeatHandler.postDelayed(this, HEARTBEAT_INTERVAL_MS)
2432
+ }
2433
+ }
2434
+
2435
+ heartbeatHandler.postDelayed(heartbeatRunnable!!, delay.toLong())
2436
+ }
2437
+
2438
+ // periodically send a mic ON request so it never turns off
2439
+ private fun startMicBeat(delay: Int) {
2440
+ Bridge.log("G1: Starting micbeat")
2441
+ if (micBeatCount > 0)
2442
+ stopMicBeat()
2443
+ sendSetMicEnabled(true, 10)
2444
+
2445
+ micBeatRunnable = object : Runnable {
2446
+ override fun run() {
2447
+ Bridge.log("G1: SENDING MIC BEAT")
2448
+ sendSetMicEnabled(shouldUseGlassesMic, 1)
2449
+ micBeatHandler.postDelayed(this, MICBEAT_INTERVAL_MS)
2450
+ }
2451
+ }
2452
+
2453
+ micBeatHandler.postDelayed(micBeatRunnable!!, delay.toLong())
2454
+ }
2455
+
2456
+ override fun findCompatibleDevices() {
2457
+ Bridge.log("G1: findCompatibleDevices called")
2458
+ if (isScanningForCompatibleDevices) {
2459
+ Bridge.log("G1: Scan already in progress, skipping...")
2460
+ return
2461
+ }
2462
+ isScanningForCompatibleDevices = true
2463
+
2464
+ val scanner = bluetoothAdapter!!.bluetoothLeScanner
2465
+ if (scanner == null) {
2466
+ Log.e(TAG, "BluetoothLeScanner not available")
2467
+ isScanningForCompatibleDevices = false
2468
+ return
2469
+ }
2470
+
2471
+ val foundDeviceNames = ArrayList<String>()
2472
+ if (findCompatibleDevicesHandler == null) {
2473
+ findCompatibleDevicesHandler = Handler(Looper.getMainLooper())
2474
+ }
2475
+
2476
+ // Optional: add filters if you want to narrow the scan
2477
+ val filters = ArrayList<ScanFilter>()
2478
+ val settings = ScanSettings.Builder()
2479
+ .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
2480
+ .build()
2481
+
2482
+ // Create a modern ScanCallback instead of the deprecated LeScanCallback
2483
+ val bleScanCallback = object : ScanCallback() {
2484
+ override fun onScanResult(callbackType: Int, result: ScanResult) {
2485
+ val device = result.device
2486
+ val name = device.name
2487
+ if (name != null && name.contains("Even G1_") && name.contains("_L_")) {
2488
+ synchronized(foundDeviceNames) {
2489
+ if (!foundDeviceNames.contains(name)) {
2490
+ foundDeviceNames.add(name)
2491
+ Bridge.log("Found smart glasses: " + name)
2492
+ var adjustedName = parsePairingIdFromDeviceName(name)
2493
+ // If parsing failed, use the full name as fallback
2494
+ if (adjustedName == null) {
2495
+ adjustedName = name
2496
+ Bridge.log("G1: Failed to parse device ID from name: " + name)
2497
+ }
2498
+ Bridge.sendDiscoveredDevice("Even Realities G1", adjustedName)
2499
+ }
2500
+ }
2501
+ }
2502
+ }
2503
+
2504
+ override fun onBatchScanResults(results: List<ScanResult>) {
2505
+ // If needed, handle batch results here
2506
+ }
2507
+
2508
+ override fun onScanFailed(errorCode: Int) {
2509
+ Log.e(TAG, "BLE scan failed with code: " + errorCode)
2510
+ }
2511
+ }
2512
+
2513
+ // Start scanning
2514
+ try {
2515
+ scanner.startScan(filters, settings, bleScanCallback)
2516
+ } catch (e: SecurityException) {
2517
+ Bridge.log("G1: findCompatibleDevices startScan SecurityException — bluetooth permission missing: " + e.message)
2518
+ isScanningForCompatibleDevices = false
2519
+ return
2520
+ } catch (e: Exception) {
2521
+ Bridge.log("G1: findCompatibleDevices startScan failed: " + e.message)
2522
+ isScanningForCompatibleDevices = false
2523
+ return
2524
+ }
2525
+ Bridge.log("G1: Started scanning for smart glasses with BluetoothLeScanner...")
2526
+
2527
+ // Stop scanning after 10 seconds (adjust as needed)
2528
+ findCompatibleDevicesHandler!!.postDelayed({
2529
+ scanner.stopScan(bleScanCallback)
2530
+ isScanningForCompatibleDevices = false
2531
+ Bridge.log("G1: Stopped scanning for smart glasses.")
2532
+ }, 10000L)
2533
+ }
2534
+
2535
+ private fun sendWhiteListCommand(delay: Int) {
2536
+ if (whiteListedAlready) {
2537
+ return
2538
+ }
2539
+ whiteListedAlready = true
2540
+
2541
+ Bridge.log("G1: Sending whitelist command")
2542
+ whiteListHandler.postDelayed({
2543
+ val chunks = getWhitelistChunks()
2544
+ sendDataSequentially(chunks, false)
2545
+ // for (byte[] chunk : chunks) {
2546
+ // Bridge.log("G1: Sending this chunk for white list:" + bytesToUtf8(chunk));
2547
+ // sendDataSequentially(chunk, false);
2548
+ //
2549
+ //// // Sleep for 100 milliseconds between sending each chunk
2550
+ //// try {
2551
+ //// Thread.sleep(150);
2552
+ //// } catch (InterruptedException e) {
2553
+ //// e.printStackTrace();
2554
+ //// }
2555
+ // }
2556
+ }, delay.toLong())
2557
+ }
2558
+
2559
+ private fun stopHeartbeat() {
2560
+ Bridge.log("G1: stopHeartbeat()")
2561
+ if (heartbeatHandler != null) {
2562
+ heartbeatHandler.removeCallbacksAndMessages(null)
2563
+ heartbeatHandler.removeCallbacksAndMessages(heartbeatRunnable)
2564
+ heartbeatCount = 0
2565
+ }
2566
+ }
2567
+
2568
+ private fun stopMicBeat() {
2569
+ Bridge.log("G1: stopMicBeat()")
2570
+ sendSetMicEnabled(false, 10)
2571
+ if (micBeatHandler != null) {
2572
+ micBeatHandler.removeCallbacksAndMessages(null)
2573
+ micBeatHandler.removeCallbacksAndMessages(micBeatRunnable)
2574
+ micBeatRunnable = null
2575
+ micBeatCount = 0
2576
+ }
2577
+ }
2578
+
2579
+ private fun sendHeartbeat() {
2580
+ val heartbeatPacket = constructHeartbeat()
2581
+ // Bridge.log("G1: Sending heartbeat: " + bytesToHex(heartbeatPacket));
2582
+
2583
+ sendDataSequentially(heartbeatPacket, false, 100)
2584
+
2585
+ if (batteryLeft == -1 || batteryRight == -1 || heartbeatCount % 10 == 0) {
2586
+ queryBatteryStatusHandler.postDelayed(this::queryBatteryStatus, 500L)
2587
+ }
2588
+ // queryBatteryStatusHandler.postDelayed(this::queryBatteryStatus, 500);
2589
+
2590
+ heartbeatCount++
2591
+ }
2592
+
2593
+ private fun queryBatteryStatus() {
2594
+ val batteryQueryPacket = constructBatteryLevelQuery()
2595
+ // Bridge.log("G1: Sending battery status query: " +
2596
+ // bytesToHex(batteryQueryPacket));
2597
+
2598
+ sendDataSequentially(batteryQueryPacket, false, 250)
2599
+ }
2600
+
2601
+ fun sendBrightnessCommand(brightness: Int, autoLight: Boolean) {
2602
+ // Validate brightness range
2603
+
2604
+ val validBrightness: Int
2605
+ if (brightness != -1) {
2606
+ validBrightness = (brightness * 63) / 100
2607
+ } else {
2608
+ validBrightness = (30 * 63) / 100
2609
+ }
2610
+
2611
+ // Construct the command
2612
+ val buffer = ByteBuffer.allocate(3)
2613
+ buffer.put(0x01.toByte()) // Command
2614
+ buffer.put(validBrightness.toByte()) // Brightness level (0~63)
2615
+ buffer.put((if (autoLight) 1 else 0).toByte()) // Auto light (0 = close, 1 = open)
2616
+
2617
+ sendDataSequentially(buffer.array(), false, 100)
2618
+
2619
+ Bridge.log("G1: Sent auto light brightness command => Brightness: " + brightness + ", Auto Light: "
2620
+ + (if (autoLight) "Open" else "Close"))
2621
+ }
2622
+
2623
+ fun sendHeadUpAngleCommand(headUpAngle: Int) {
2624
+ // Validate headUpAngle range (0 ~ 60)
2625
+ var headUpAngleValue = headUpAngle
2626
+ if (headUpAngleValue < 0) {
2627
+ headUpAngleValue = 0
2628
+ } else if (headUpAngleValue > 60) {
2629
+ headUpAngleValue = 60
2630
+ }
2631
+
2632
+ // Construct the command
2633
+ val buffer = ByteBuffer.allocate(3)
2634
+ buffer.put(0x0B.toByte()) // Command for configuring headUp angle
2635
+ buffer.put(headUpAngleValue.toByte()) // Angle value (0~60)
2636
+ buffer.put(0x01.toByte()) // Level (fixed at 0x01)
2637
+
2638
+ sendDataSequentially(buffer.array(), false, 100)
2639
+
2640
+ Bridge.log("G1: Sent headUp angle command => Angle: " + headUpAngleValue)
2641
+ }
2642
+
2643
+ fun sendDashboardPositionCommand(height: Int, depth: Int) {
2644
+ // clamp height and depth to 0-8 and 1-9 respectively:
2645
+ val heightValue = Math.max(0, Math.min(height, 8))
2646
+ val depthValue = Math.max(1, Math.min(depth, 9))
2647
+
2648
+ val globalCounter = 0 // TODO: must be incremented each time this command is sent!
2649
+
2650
+ val buffer = ByteBuffer.allocate(8)
2651
+ buffer.put(0x26.toByte()) // Command for dashboard height
2652
+ buffer.put(0x08.toByte()) // Length
2653
+ buffer.put(0x00.toByte()) // Sequence
2654
+ buffer.put((globalCounter and 0xFF).toByte()) // counter
2655
+ buffer.put(0x02.toByte()) // Fixed value
2656
+ buffer.put(0x01.toByte()) // State ON
2657
+ buffer.put(heightValue.toByte()) // Height value (0-8)
2658
+ buffer.put(depthValue.toByte()) // Depth value (0-9)
2659
+
2660
+ sendDataSequentially(buffer.array(), false, 100)
2661
+
2662
+ Bridge.log("G1: Sent dashboard height/depth command => Height: " + heightValue + ", Depth: " + depthValue)
2663
+ }
2664
+
2665
+ fun updateGlassesBrightness(brightness: Int) {
2666
+ Bridge.log("G1: Updating glasses brightness: " + brightness)
2667
+ sendBrightnessCommand(brightness, false)
2668
+ }
2669
+
2670
+ fun updateGlassesAutoBrightness(autoBrightness: Boolean) {
2671
+ Bridge.log("G1: Updating glasses auto brightness: " + autoBrightness)
2672
+ sendBrightnessCommand(-1, autoBrightness)
2673
+ }
2674
+
2675
+ fun updateGlassesHeadUpAngle(headUpAngle: Int) {
2676
+ sendHeadUpAngleCommand(headUpAngle)
2677
+ }
2678
+
2679
+ fun updateGlassesDepthHeight(depth: Int, height: Int) {
2680
+ sendDashboardPositionCommand(height, depth)
2681
+ }
2682
+
2683
+ fun sendExitCommand() {
2684
+ sendDataSequentially(byteArrayOf(0x18.toByte()), false, 100)
2685
+ }
2686
+
2687
+ // microphone stuff
2688
+ fun sendSetMicEnabled(enable: Boolean, delay: Int) {
2689
+ Bridge.log("G1: sendSetMicEnabled(): " + enable)
2690
+
2691
+ isMicrophoneEnabled = enable // Update the state tracker
2692
+ DeviceStore.apply("glasses", "micEnabled", enable)
2693
+ micEnableHandler.postDelayed({
2694
+ if (!isConnected()) {
2695
+ Bridge.log("G1: Tryna start mic: Not connected to glasses")
2696
+ return@postDelayed
2697
+ }
2698
+
2699
+ val command: Byte = 0x0E // Command for MIC control
2700
+ val enableByte = (if (enable) 1 else 0).toByte() // 1 to enable, 0 to disable
2701
+
2702
+ val buffer = ByteBuffer.allocate(2)
2703
+ buffer.put(command)
2704
+ buffer.put(enableByte)
2705
+
2706
+ sendDataSequentially(buffer.array(), false, true, 300) // wait some time to setup the mic
2707
+ Bridge.log("G1: Sent MIC command: " + bytesToHex(buffer.array()))
2708
+ }, delay.toLong())
2709
+ }
2710
+
2711
+ // notifications
2712
+ private fun startPeriodicNotifications(delay: Int) {
2713
+ if (notifysStarted) {
2714
+ return
2715
+ }
2716
+ notifysStarted = true
2717
+
2718
+ notificationRunnable = object : Runnable {
2719
+ override fun run() {
2720
+ // Send notification
2721
+ sendPeriodicNotification()
2722
+
2723
+ // Schedule the next notification
2724
+ notificationHandler.postDelayed(this, 12000L)
2725
+ }
2726
+ }
2727
+
2728
+ // Start the first notification after 5 seconds
2729
+ notificationHandler.postDelayed(notificationRunnable!!, delay.toLong())
2730
+ }
2731
+
2732
+ private fun sendPeriodicNotification() {
2733
+ if (!isConnected()) {
2734
+ Bridge.log("G1: Cannot send notification: Not connected to glasses")
2735
+ return
2736
+ }
2737
+
2738
+ // Example notification data (replace with your actual data)
2739
+ // String json = createNotificationJson("com.augment.os", "QuestionAnswerer",
2740
+ // "How much caffeine in dark chocolate?", "25 to 50 grams per piece");
2741
+ val json = createNotificationJson("com.augment.os", "QuestionAnswerer",
2742
+ "How much caffeine in dark chocolate?", "25 to 50 grams per piece")
2743
+ Bridge.log("G1: the JSON to send: " + json)
2744
+ val chunks = createNotificationChunks(json)
2745
+ for (chunk in chunks) {
2746
+ Bridge.log("G1: Sent chunk to glasses: " + bytesToUtf8(chunk))
2747
+ }
2748
+
2749
+ // Send each chunk with a short sleep between each send
2750
+ sendDataSequentially(chunks, false)
2751
+
2752
+ Bridge.log("G1: Sent periodic notification")
2753
+ }
2754
+
2755
+ // text wall debug
2756
+ private fun startPeriodicTextWall(delay: Int) {
2757
+ if (textWallsStarted) {
2758
+ return
2759
+ }
2760
+ textWallsStarted = true
2761
+
2762
+ textWallRunnable = object : Runnable {
2763
+ override fun run() {
2764
+ // Send notification
2765
+ sendPeriodicTextWall()
2766
+
2767
+ // Schedule the next notification
2768
+ textWallHandler.postDelayed(this, 12000L)
2769
+ }
2770
+ }
2771
+
2772
+ // Start the first text wall send after 5 seconds
2773
+ textWallHandler.postDelayed(textWallRunnable!!, delay.toLong())
2774
+ }
2775
+
2776
+ private var textSeqNum = 0 // Sequence number for text packets
2777
+
2778
+ /**
2779
+ * Creates BLE chunks for pre-wrapped text.
2780
+ *
2781
+ * IMPORTANT: Text is expected to come pre-wrapped from the DisplayProcessor in React Native.
2782
+ * This function does NOT perform any text wrapping - it only chunks the text for BLE transmission.
2783
+ * The DisplayProcessor handles all pixel-accurate wrapping using @glassly/display-utils.
2784
+ *
2785
+ * @param text Pre-wrapped text with newlines already in place
2786
+ * @return List of BLE chunks ready for transmission
2787
+ */
2788
+ private fun createTextWallChunks(text: String): List<ByteArray> {
2789
+ // Text comes pre-wrapped from DisplayProcessor - just chunk it for transmission
2790
+ return chunkTextForTransmission(text)
2791
+ }
2792
+
2793
+ /**
2794
+ * Chunks text into BLE packets for transmission to glasses.
2795
+ * This is a low-level function that handles BLE protocol framing.
2796
+ *
2797
+ * @param text Text to chunk (should already be formatted/wrapped)
2798
+ * @return List of BLE chunks with headers
2799
+ */
2800
+ private fun chunkTextForTransmission(text: String?): List<ByteArray> {
2801
+ // Handle empty or whitespace-only text by sending at least a space
2802
+ // This ensures the display gets updated/cleared properly
2803
+ val textToSend = if (text == null || text.trim().isEmpty()) " " else sanitizeG1DisplayText(text)
2804
+ val textBytes = textToSend.toByteArray(StandardCharsets.UTF_8)
2805
+ val totalChunks = Math.ceil(textBytes.size.toDouble() / MAX_CHUNK_SIZE).toInt()
2806
+
2807
+ val allChunks = ArrayList<ByteArray>()
2808
+ for (i in 0 until totalChunks) {
2809
+ val start = i * MAX_CHUNK_SIZE
2810
+ val end = Math.min(start + MAX_CHUNK_SIZE, textBytes.size)
2811
+ val payloadChunk = Arrays.copyOfRange(textBytes, start, end)
2812
+
2813
+ // Create header with protocol specifications
2814
+ val screenStatus: Byte = 0x71 // New content (0x01) + Text Show (0x70)
2815
+ val header = byteArrayOf(
2816
+ TEXT_COMMAND.toByte(), // Command type
2817
+ textSeqNum.toByte(), // Sequence number
2818
+ totalChunks.toByte(), // Total packages
2819
+ i.toByte(), // Current package number
2820
+ screenStatus, // Screen status
2821
+ 0x00.toByte(), // new_char_pos0 (high)
2822
+ 0x00.toByte(), // new_char_pos1 (low)
2823
+ 0x00.toByte(), // Current page number (always 0)
2824
+ 0x01.toByte() // Max page number (always 1)
2825
+ )
2826
+
2827
+ // Combine header and payload
2828
+ val chunk = ByteBuffer.allocate(header.size + payloadChunk.size)
2829
+ chunk.put(header)
2830
+ chunk.put(payloadChunk)
2831
+
2832
+ allChunks.add(chunk.array())
2833
+ }
2834
+
2835
+ // Increment sequence number for next transmission
2836
+ textSeqNum = (textSeqNum + 1) % 256
2837
+
2838
+ return allChunks
2839
+ }
2840
+
2841
+ private fun calculateSpacesForAlignment(currentWidth: Int, targetPosition: Int, spaceWidth: Int): Int {
2842
+ // Calculate space needed in pixels
2843
+ val pixelsNeeded = targetPosition - currentWidth
2844
+
2845
+ // Calculate spaces needed (with minimum of 1 space for separation)
2846
+ if (pixelsNeeded <= 0) {
2847
+ return 1 // Ensure at least one space between columns
2848
+ }
2849
+
2850
+ // Calculate the exact number of spaces needed
2851
+ val spaces = Math.ceil(pixelsNeeded.toDouble() / spaceWidth).toInt()
2852
+
2853
+ // Cap at a reasonable maximum
2854
+ return Math.min(spaces, 100)
2855
+ }
2856
+
2857
+ private fun sendPeriodicTextWall() {
2858
+ if (!isConnected()) {
2859
+ Bridge.log("G1: Cannot send text wall: Not connected to glasses")
2860
+ return
2861
+ }
2862
+
2863
+ Bridge.log("G1: ^^^^^^^^^^^^^ SENDING DEBUG TEXT WALL")
2864
+
2865
+ // Example text wall content - replace with your actual text content
2866
+ val sampleText = "This is an example of a text wall that will be displayed on the glasses. " +
2867
+ "It demonstrates how text can be split into multiple pages and displayed sequentially. " +
2868
+ "Each page contains multiple lines, and each line is carefully formatted to fit the display width. " +
2869
+ "The text continues across multiple pages, showing how longer content can be handled effectively."
2870
+
2871
+ val chunks = createTextWallChunks(sampleText)
2872
+
2873
+ // Send each chunk with a delay between sends
2874
+ for (chunk in chunks) {
2875
+ sendDataSequentially(chunk)
2876
+
2877
+ // try {
2878
+ // Thread.sleep(150); // 150ms delay between chunks
2879
+ // } catch (InterruptedException e) {
2880
+ // e.printStackTrace();
2881
+ // }
2882
+ }
2883
+
2884
+ // Bridge.log("G1: Sent text wall");
2885
+ }
2886
+
2887
+ private fun stopPeriodicNotifications() {
2888
+ if (notificationHandler != null && notificationRunnable != null) {
2889
+ notificationHandler.removeCallbacks(notificationRunnable!!)
2890
+ Bridge.log("G1: Stopped periodic notifications")
2891
+ }
2892
+ }
2893
+
2894
+ fun getWhitelistChunks(): List<ByteArray> {
2895
+ // Define the hardcoded whitelist JSON
2896
+ val apps = ArrayList<AppInfo>()
2897
+ apps.add(AppInfo("com.augment.os", "AugmentOS"))
2898
+ val whitelistJson = createWhitelistJson(apps)
2899
+
2900
+ Bridge.log("G1: Creating chunks for hardcoded whitelist: " + whitelistJson)
2901
+
2902
+ // Convert JSON to bytes and split into chunks
2903
+ return createWhitelistChunks(whitelistJson)
2904
+ }
2905
+
2906
+ private fun createWhitelistJson(apps: List<AppInfo>): String {
2907
+ val appList = JSONArray()
2908
+ try {
2909
+ // Add each app to the list
2910
+ for (app in apps) {
2911
+ val appJson = JSONObject()
2912
+ appJson.put("id", app.id)
2913
+ appJson.put("name", app.name)
2914
+ appList.put(appJson)
2915
+ }
2916
+
2917
+ val whitelistJson = JSONObject()
2918
+ whitelistJson.put("calendar_enable", false)
2919
+ whitelistJson.put("call_enable", false)
2920
+ whitelistJson.put("msg_enable", false)
2921
+ whitelistJson.put("ios_mail_enable", false)
2922
+
2923
+ val appObject = JSONObject()
2924
+ appObject.put("list", appList)
2925
+ appObject.put("enable", true)
2926
+
2927
+ whitelistJson.put("app", appObject)
2928
+
2929
+ return whitelistJson.toString()
2930
+ } catch (e: JSONException) {
2931
+ Log.e(TAG, "Error creating whitelist JSON: " + e.message)
2932
+ return "{}"
2933
+ }
2934
+ }
2935
+
2936
+ // Simple class to hold app info
2937
+ internal class AppInfo(val id: String, val name: String)
2938
+
2939
+ // Helper function to split JSON into chunks
2940
+ private fun createWhitelistChunks(json: String): List<ByteArray> {
2941
+ val MAX_CHUNK_SIZE = 180 - 4 // Reserve space for the header
2942
+ val jsonBytes = json.toByteArray(StandardCharsets.UTF_8)
2943
+ val totalChunks = Math.ceil(jsonBytes.size.toDouble() / MAX_CHUNK_SIZE).toInt()
2944
+
2945
+ val chunks = ArrayList<ByteArray>()
2946
+ for (i in 0 until totalChunks) {
2947
+ val start = i * MAX_CHUNK_SIZE
2948
+ val end = Math.min(start + MAX_CHUNK_SIZE, jsonBytes.size)
2949
+ val payloadChunk = Arrays.copyOfRange(jsonBytes, start, end)
2950
+
2951
+ // Create the header: [WHITELIST_CMD, total_chunks, chunk_index]
2952
+ val header = byteArrayOf(
2953
+ WHITELIST_CMD.toByte(), // Command ID
2954
+ totalChunks.toByte(), // Total number of chunks
2955
+ i.toByte() // Current chunk index
2956
+ )
2957
+
2958
+ // Combine header and payload
2959
+ val buffer = ByteBuffer.allocate(header.size + payloadChunk.size)
2960
+ buffer.put(header)
2961
+ buffer.put(payloadChunk)
2962
+
2963
+ chunks.add(buffer.array())
2964
+ }
2965
+
2966
+ return chunks
2967
+ }
2968
+
2969
+ fun displayCustomContent(content: String) {
2970
+ Bridge.log("G1: DISPLAY CUSTOM CONTENT")
2971
+ }
2972
+
2973
+ private fun sendChunks(chunks: List<ByteArray>) {
2974
+ // Send each chunk with a delay between sends
2975
+ for (chunk in chunks) {
2976
+ // Bridge.log("G1: Sending chunk: " + Arrays.toString(chunk));
2977
+ sendDataSequentially(chunk)
2978
+
2979
+ // try {
2980
+ // Thread.sleep(DELAY_BETWEEN_CHUNKS_SEND); // delay between chunks
2981
+ // } catch (InterruptedException e) {
2982
+ // e.printStackTrace();
2983
+ // }
2984
+ }
2985
+ }
2986
+
2987
+ // public int DEFAULT_CARD_SHOW_TIME = 6;
2988
+ // public void homeScreenInNSeconds(int n){
2989
+ // if (n == -1){
2990
+ // return;
2991
+ // }
2992
+ //
2993
+ // if (n == 0){
2994
+ // n = DEFAULT_CARD_SHOW_TIME;
2995
+ // }
2996
+ //
2997
+ // //disconnect after slight delay, so our above text gets a chance to show up
2998
+ // goHomeHandler.removeCallbacksAndMessages(goHomeRunnable);
2999
+ // goHomeHandler.removeCallbacksAndMessages(null);
3000
+ // goHomeRunnable = new Runnable() {
3001
+ // @Override
3002
+ // public void run() {
3003
+ // showHomeScreen();
3004
+ // }};
3005
+ // goHomeHandler.postDelayed(goHomeRunnable, n * 1000);
3006
+ // }
3007
+
3008
+ @Volatile private var isSendingBitmap = false
3009
+
3010
+ // Progress callback interface
3011
+ interface BmpProgressCallback {
3012
+ fun onProgress(side: String, offset: Int, chunkIndex: Int, totalSize: Int)
3013
+
3014
+ fun onSuccess(side: String)
3015
+
3016
+ fun onError(side: String, error: String)
3017
+ }
3018
+
3019
+ /**
3020
+ * Inverts BMP pixel data by flipping all bits after the header.
3021
+ * Matches iOS implementation exactly (G1.swift line 1790-1811)
3022
+ *
3023
+ * @param bmpData The original BMP data
3024
+ * @return Inverted BMP data with pixel bits flipped
3025
+ */
3026
+ private fun invertBmpPixels(bmpData: ByteArray?): ByteArray? {
3027
+ if (bmpData == null || bmpData.size <= 62) {
3028
+ Bridge.log("G1: BMP data too small to contain pixel data")
3029
+ return bmpData
3030
+ }
3031
+
3032
+ // BMP header is 62 bytes (14 byte file header + 40 byte DIB header + 8 byte color table)
3033
+ val headerSize = 62
3034
+ val invertedData = ByteArray(bmpData.size)
3035
+
3036
+ // Copy header unchanged
3037
+ System.arraycopy(bmpData, 0, invertedData, 0, headerSize)
3038
+
3039
+ // Invert the pixel data (everything after the header)
3040
+ for (i in headerSize until bmpData.size) {
3041
+ // Invert each byte (flip all bits)
3042
+ invertedData[i] = bmpData[i].toInt().inv().toByte()
3043
+ }
3044
+
3045
+ Bridge.log("G1: Inverted BMP pixels: " + (bmpData.size - headerSize) + " bytes processed")
3046
+ return invertedData
3047
+ }
3048
+
3049
+ fun displayBitmapImage(bmpData: ByteArray?) {
3050
+ displayBitmapImage(bmpData, null)
3051
+ }
3052
+
3053
+ fun displayBitmapImage(bmpData: ByteArray?, callback: BmpProgressCallback?) {
3054
+ // Invert BMP pixels to match iOS implementation
3055
+ val invertedBmpData = invertBmpPixels(bmpData)
3056
+
3057
+ if (USE_OPTIMIZED_BITMAP_DISPLAY) {
3058
+ displayBitmapImageOptimized(invertedBmpData, callback)
3059
+ } else {
3060
+ displayBitmapImageLegacy(invertedBmpData, callback)
3061
+ }
3062
+ }
3063
+
3064
+ // Optimized bitmap display using iOS-like approach
3065
+ private fun displayBitmapImageOptimized(bmpData: ByteArray?, callback: BmpProgressCallback?) {
3066
+ Bridge.log("G1: Starting OPTIMIZED BMP display process")
3067
+
3068
+ try {
3069
+ if (bmpData == null || bmpData.isEmpty()) {
3070
+ Log.e(TAG, "Invalid BMP data provided")
3071
+ if (callback != null)
3072
+ callback.onError("both", "Invalid BMP data")
3073
+ return
3074
+ }
3075
+
3076
+ isSendingBitmap = true
3077
+ val startTime = System.currentTimeMillis()
3078
+
3079
+ Bridge.log("G1: Processing BMP data, size: " + bmpData.size + " bytes")
3080
+ val chunks = createBmpChunks(bmpData)
3081
+ Bridge.log("G1: Created " + chunks.size + " chunks")
3082
+
3083
+ // Send chunks using optimized method
3084
+ val chunksSuccess = sendBmpChunksOptimized(chunks, callback)
3085
+ if (!chunksSuccess) {
3086
+ Log.e(TAG, "Failed to send BMP chunks")
3087
+ if (callback != null)
3088
+ callback.onError("both", "Failed to send chunks")
3089
+ return
3090
+ }
3091
+
3092
+ // Send end command - this needs confirmation
3093
+ val endSuccess = sendBmpEndCommandOptimized()
3094
+ if (!endSuccess) {
3095
+ Log.e(TAG, "Failed to send BMP end command")
3096
+ if (callback != null)
3097
+ callback.onError("both", "Failed to send end command")
3098
+ return
3099
+ }
3100
+
3101
+ // Send CRC - this needs confirmation
3102
+ val crcSuccess = sendBmpCrcOptimized(bmpData)
3103
+ if (!crcSuccess) {
3104
+ Log.e(TAG, "Failed to send BMP CRC")
3105
+ if (callback != null)
3106
+ callback.onError("both", "CRC check failed")
3107
+ return
3108
+ }
3109
+
3110
+ lastThingDisplayedWasAnImage = true
3111
+
3112
+ val totalTime = System.currentTimeMillis() - startTime
3113
+ Bridge.log("G1: BMP display completed in " + totalTime + "ms")
3114
+
3115
+ if (callback != null) {
3116
+ callback.onSuccess("both")
3117
+ }
3118
+
3119
+ } catch (e: Exception) {
3120
+ Log.e(TAG, "Error in displayBitmapImageOptimized: " + e.message)
3121
+ if (callback != null)
3122
+ callback.onError("both", "Exception: " + e.message)
3123
+ } finally {
3124
+ isSendingBitmap = false
3125
+ }
3126
+ }
3127
+
3128
+ // Legacy method for fallback
3129
+ private fun displayBitmapImageLegacy(bmpData: ByteArray?, callback: BmpProgressCallback?) {
3130
+ Bridge.log("G1: Starting LEGACY BMP display process")
3131
+
3132
+ try {
3133
+ if (bmpData == null || bmpData.isEmpty()) {
3134
+ Log.e(TAG, "Invalid BMP data provided")
3135
+ if (callback != null)
3136
+ callback.onError("both", "Invalid BMP data")
3137
+ return
3138
+ }
3139
+ Bridge.log("G1: Processing BMP data, size: " + bmpData.size + " bytes")
3140
+ // Split into chunks and send
3141
+ val chunks = createBmpChunks(bmpData)
3142
+ Bridge.log("G1: Created " + chunks.size + " chunks")
3143
+
3144
+ // Send all chunks
3145
+ sendBmpChunks(chunks)
3146
+ // Send all chunks with progress
3147
+ val chunksSuccess = sendBmpChunksWithProgress(chunks, callback)
3148
+ if (!chunksSuccess) {
3149
+ Log.e(TAG, "Failed to send BMP chunks")
3150
+ if (callback != null)
3151
+ callback.onError("both", "Failed to send chunks")
3152
+ return
3153
+ }
3154
+
3155
+ // Send end command with retry
3156
+ val endSuccess = sendBmpEndCommandWithRetry()
3157
+ if (!endSuccess) {
3158
+ Log.e(TAG, "Failed to send BMP end command")
3159
+ if (callback != null)
3160
+ callback.onError("both", "Failed to send end command")
3161
+ return
3162
+ }
3163
+
3164
+ // Calculate and send CRC with proper algorithm
3165
+ val crcSuccess = sendBmpCrcWithRetry(bmpData)
3166
+ if (!crcSuccess) {
3167
+ Log.e(TAG, "Failed to send BMP CRC")
3168
+ if (callback != null)
3169
+ callback.onError("both", "CRC check failed")
3170
+ return
3171
+ }
3172
+
3173
+ lastThingDisplayedWasAnImage = true
3174
+
3175
+ if (callback != null) {
3176
+ callback.onSuccess("both")
3177
+ }
3178
+
3179
+ Bridge.log("G1: BMP display process completed successfully")
3180
+
3181
+ } catch (e: Exception) {
3182
+ Log.e(TAG, "Error in displayBitmapImage: " + e.message)
3183
+ if (callback != null)
3184
+ callback.onError("both", "Exception: " + e.message)
3185
+ }
3186
+ }
3187
+
3188
+ private fun createBmpChunks(bmpData: ByteArray): List<ByteArray> {
3189
+ val chunks = ArrayList<ByteArray>()
3190
+ val totalChunks = Math.ceil(bmpData.size.toDouble() / BMP_CHUNK_SIZE).toInt()
3191
+ Bridge.log("G1: Creating " + totalChunks + " chunks from " + bmpData.size + " bytes")
3192
+
3193
+ for (i in 0 until totalChunks) {
3194
+ val start = i * BMP_CHUNK_SIZE
3195
+ val end = Math.min(start + BMP_CHUNK_SIZE, bmpData.size)
3196
+ val chunk = Arrays.copyOfRange(bmpData, start, end)
3197
+
3198
+ // First chunk needs address bytes
3199
+ if (i == 0) {
3200
+ val headerWithAddress = ByteArray(2 + GLASSES_ADDRESS.size + chunk.size)
3201
+ headerWithAddress[0] = 0x15 // Command
3202
+ headerWithAddress[1] = (i and 0xFF).toByte() // Sequence
3203
+ System.arraycopy(GLASSES_ADDRESS, 0, headerWithAddress, 2, GLASSES_ADDRESS.size)
3204
+ System.arraycopy(chunk, 0, headerWithAddress, 6, chunk.size)
3205
+ chunks.add(headerWithAddress)
3206
+ } else {
3207
+ val header = ByteArray(2 + chunk.size)
3208
+ header[0] = 0x15 // Command
3209
+ header[1] = (i and 0xFF).toByte() // Sequence
3210
+ System.arraycopy(chunk, 0, header, 2, chunk.size)
3211
+ chunks.add(header)
3212
+ }
3213
+ }
3214
+ return chunks
3215
+ }
3216
+
3217
+ private fun sendBmpChunksWithProgress(chunks: List<ByteArray>, callback: BmpProgressCallback?): Boolean {
3218
+ if (updatingScreen)
3219
+ return false
3220
+
3221
+ for (i in 0 until chunks.size) {
3222
+ val chunk = chunks[i]
3223
+ Bridge.log("G1: Sending chunk " + i + " of " + chunks.size + ", size: " + chunk.size)
3224
+
3225
+ val success = sendDataSequentiallyWithTimeout(chunk, CHUNK_SEND_TIMEOUT_MS)
3226
+ if (!success) {
3227
+ Log.e(TAG, "Failed to send chunk " + i)
3228
+ return false
3229
+ }
3230
+
3231
+ // Report progress
3232
+ if (callback != null) {
3233
+ val offset = i * BMP_CHUNK_SIZE
3234
+ callback.onProgress("both", offset, i, chunks.size * BMP_CHUNK_SIZE)
3235
+ }
3236
+
3237
+ // Platform-specific delay between chunks (matching Flutter implementation)
3238
+ try {
3239
+ Thread.sleep(ANDROID_CHUNK_DELAY_MS)
3240
+ } catch (e: InterruptedException) {
3241
+ Log.e(TAG, "Sleep interrupted: " + e.message)
3242
+ return false
3243
+ }
3244
+ }
3245
+ return true
3246
+ }
3247
+
3248
+ // Optimized chunk sending - mimics iOS approach
3249
+ private fun sendBmpChunksOptimized(chunks: List<ByteArray>, callback: BmpProgressCallback?): Boolean {
3250
+ if (updatingScreen)
3251
+ return false
3252
+
3253
+ Bridge.log("G1: Sending " + chunks.size + " chunks using OPTIMIZED method")
3254
+
3255
+ // Send all chunks except last without waiting for response
3256
+ for (i in 0 until chunks.size - 1) {
3257
+ val chunk = chunks[i]
3258
+ val chunkIndex = i
3259
+
3260
+ if (USE_PARALLEL_BITMAP_WRITES && bitmapExecutor != null) {
3261
+ // Send to both glasses in parallel using executor
3262
+ val latch = CountDownLatch(2)
3263
+
3264
+ // Send to left glass
3265
+ bitmapExecutor!!.execute {
3266
+ try {
3267
+ if (leftGlassGatt != null && leftTxChar != null && isLeftConnected) {
3268
+ synchronized(leftTxChar!!) {
3269
+ leftTxChar!!.value = chunk
3270
+ leftTxChar!!.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
3271
+ leftGlassGatt!!.writeCharacteristic(leftTxChar)
3272
+ leftTxChar!!.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
3273
+ }
3274
+ }
3275
+ } finally {
3276
+ latch.countDown()
3277
+ }
3278
+ }
3279
+
3280
+ // Send to right glass
3281
+ bitmapExecutor!!.execute {
3282
+ try {
3283
+ if (rightGlassGatt != null && rightTxChar != null && isRightConnected) {
3284
+ synchronized(rightTxChar!!) {
3285
+ rightTxChar!!.value = chunk
3286
+ rightTxChar!!.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
3287
+ rightGlassGatt!!.writeCharacteristic(rightTxChar)
3288
+ rightTxChar!!.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
3289
+ }
3290
+ }
3291
+ } finally {
3292
+ latch.countDown()
3293
+ }
3294
+ }
3295
+
3296
+ // Wait for both to complete (but don't wait for BLE response)
3297
+ try {
3298
+ latch.await(50, TimeUnit.MILLISECONDS) // Short timeout
3299
+ } catch (e: InterruptedException) {
3300
+ // Continue anyway
3301
+ }
3302
+ } else {
3303
+ // Fall back to sequential but still no wait
3304
+ sendBitmapChunkNoWait(chunk, true, true)
3305
+ }
3306
+
3307
+ // Report progress
3308
+ if (callback != null) {
3309
+ val offset = chunkIndex * BMP_CHUNK_SIZE
3310
+ callback.onProgress("both", offset, chunkIndex, chunks.size * BMP_CHUNK_SIZE)
3311
+ }
3312
+
3313
+ // Small delay between chunks (iOS uses 8ms)
3314
+ try {
3315
+ Thread.sleep(ANDROID_CHUNK_DELAY_MS)
3316
+ } catch (e: InterruptedException) {
3317
+ Log.e(TAG, "Sleep interrupted: " + e.message)
3318
+ return false
3319
+ }
3320
+ }
3321
+
3322
+ // Last chunk - wait for confirmation (like iOS)
3323
+ if (!chunks.isEmpty()) {
3324
+ val lastChunk = chunks[chunks.size - 1]
3325
+ Bridge.log("G1: Sending last chunk with confirmation")
3326
+
3327
+ val success = sendDataSequentiallyWithTimeout(lastChunk, 2000) // Shorter timeout for last chunk
3328
+ if (!success) {
3329
+ Log.e(TAG, "Failed to send last chunk")
3330
+ return false
3331
+ }
3332
+
3333
+ if (callback != null) {
3334
+ val offset = (chunks.size - 1) * BMP_CHUNK_SIZE
3335
+ callback.onProgress("both", offset, chunks.size - 1, chunks.size * BMP_CHUNK_SIZE)
3336
+ }
3337
+ }
3338
+
3339
+ return true
3340
+ }
3341
+
3342
+ // Optimized end command sending
3343
+ private fun sendBmpEndCommandOptimized(): Boolean {
3344
+ Bridge.log("G1: Sending BMP end command (optimized)")
3345
+
3346
+ // End command needs confirmation, but with shorter timeout
3347
+ val success = sendDataSequentiallyWithTimeout(END_COMMAND, 1000)
3348
+ if (success) {
3349
+ Bridge.log("G1: BMP end command sent successfully")
3350
+
3351
+ // Small delay after end command
3352
+ try {
3353
+ Thread.sleep(10)
3354
+ } catch (e: InterruptedException) {
3355
+ // Ignore
3356
+ }
3357
+ }
3358
+ return success
3359
+ }
3360
+
3361
+ // Optimized CRC sending
3362
+ private fun sendBmpCrcOptimized(bmpData: ByteArray): Boolean {
3363
+ // Create data with address for CRC calculation
3364
+ val dataWithAddress = ByteArray(GLASSES_ADDRESS.size + bmpData.size)
3365
+ System.arraycopy(GLASSES_ADDRESS, 0, dataWithAddress, 0, GLASSES_ADDRESS.size)
3366
+ System.arraycopy(bmpData, 0, dataWithAddress, GLASSES_ADDRESS.size, bmpData.size)
3367
+
3368
+ // Calculate CRC32
3369
+ val crc = CRC32()
3370
+ crc.update(dataWithAddress)
3371
+ val crcValue = crc.value
3372
+
3373
+ // Create CRC command packet
3374
+ val crcCommand = ByteArray(5)
3375
+ crcCommand[0] = 0x16 // CRC command
3376
+ crcCommand[1] = ((crcValue shr 24) and 0xFF).toByte()
3377
+ crcCommand[2] = ((crcValue shr 16) and 0xFF).toByte()
3378
+ crcCommand[3] = ((crcValue shr 8) and 0xFF).toByte()
3379
+ crcCommand[4] = (crcValue and 0xFF).toByte()
3380
+
3381
+ Bridge.log("G1: Sending CRC command (optimized), CRC value: " + java.lang.Long.toHexString(crcValue))
3382
+
3383
+ // CRC needs confirmation, but with shorter timeout
3384
+ val success = sendDataSequentiallyWithTimeout(crcCommand, 1000)
3385
+ if (success) {
3386
+ Bridge.log("G1: CRC command sent successfully")
3387
+ }
3388
+ return success
3389
+ }
3390
+
3391
+ private fun sendDataSequentiallyWithTimeout(data: ByteArray, timeoutMs: Long): Boolean {
3392
+ // Create a future to track the send operation
3393
+ val success = booleanArrayOf(false)
3394
+ val latch = CountDownLatch(1)
3395
+
3396
+ // Send the data asynchronously
3397
+ Thread {
3398
+ try {
3399
+ sendDataSequentially(data)
3400
+ success[0] = true
3401
+ } catch (e: Exception) {
3402
+ Log.e(TAG, "Error sending data: " + e.message)
3403
+ success[0] = false
3404
+ } finally {
3405
+ latch.countDown()
3406
+ }
3407
+ }.start()
3408
+
3409
+ // Wait for completion or timeout
3410
+ try {
3411
+ val completed = latch.await(timeoutMs, TimeUnit.MILLISECONDS)
3412
+ return completed && success[0]
3413
+ } catch (e: InterruptedException) {
3414
+ Log.e(TAG, "Timeout waiting for data send")
3415
+ return false
3416
+ }
3417
+ }
3418
+
3419
+ private fun sendBmpEndCommandWithRetry(): Boolean {
3420
+ if (updatingScreen)
3421
+ return false
3422
+
3423
+ for (attempt in 0 until MAX_BMP_RETRY_ATTEMPTS) {
3424
+ Bridge.log("G1: Sending BMP end command, attempt " + (attempt + 1))
3425
+
3426
+ val success = sendDataSequentiallyWithTimeout(END_COMMAND, END_COMMAND_TIMEOUT_MS)
3427
+ if (success) {
3428
+ Bridge.log("G1: BMP end command sent successfully")
3429
+ return true
3430
+ }
3431
+
3432
+ Log.w(TAG, "BMP end command failed, attempt " + (attempt + 1))
3433
+
3434
+ // Wait before retry
3435
+ try {
3436
+ Thread.sleep(BMP_RETRY_DELAY_MS)
3437
+ } catch (e: InterruptedException) {
3438
+ Log.e(TAG, "Sleep interrupted during retry")
3439
+ return false
3440
+ }
3441
+ }
3442
+
3443
+ Log.e(TAG, "Failed to send BMP end command after " + MAX_BMP_RETRY_ATTEMPTS + " attempts")
3444
+ return false
3445
+ }
3446
+
3447
+ private fun sendBmpCrcWithRetry(bmpData: ByteArray): Boolean {
3448
+ // Create data with address for CRC calculation
3449
+ val dataWithAddress = ByteArray(GLASSES_ADDRESS.size + bmpData.size)
3450
+ System.arraycopy(GLASSES_ADDRESS, 0, dataWithAddress, 0, GLASSES_ADDRESS.size)
3451
+ System.arraycopy(bmpData, 0, dataWithAddress, GLASSES_ADDRESS.size, bmpData.size)
3452
+
3453
+ // Calculate CRC32-XZ (using standard CRC32 for now, but should be Crc32Xz)
3454
+ val crc = CRC32()
3455
+ crc.update(dataWithAddress)
3456
+ val crcValue = crc.value
3457
+
3458
+ // Create CRC command packet
3459
+ val crcCommand = ByteArray(5)
3460
+ crcCommand[0] = 0x16 // CRC command
3461
+ crcCommand[1] = ((crcValue shr 24) and 0xFF).toByte()
3462
+ crcCommand[2] = ((crcValue shr 16) and 0xFF).toByte()
3463
+ crcCommand[3] = ((crcValue shr 8) and 0xFF).toByte()
3464
+ crcCommand[4] = (crcValue and 0xFF).toByte()
3465
+
3466
+ Bridge.log("G1: Sending CRC command, CRC value: " + java.lang.Long.toHexString(crcValue))
3467
+
3468
+ // Send CRC with retry
3469
+ for (attempt in 0 until MAX_BMP_RETRY_ATTEMPTS) {
3470
+ val success = sendDataSequentiallyWithTimeout(crcCommand, CRC_COMMAND_TIMEOUT_MS)
3471
+ if (success) {
3472
+ Bridge.log("G1: CRC command sent successfully")
3473
+ return true
3474
+ }
3475
+
3476
+ Log.w(TAG, "CRC command failed, attempt " + (attempt + 1))
3477
+
3478
+ try {
3479
+ Thread.sleep(BMP_RETRY_DELAY_MS)
3480
+ } catch (e: InterruptedException) {
3481
+ Log.e(TAG, "Sleep interrupted during CRC retry")
3482
+ return false
3483
+ }
3484
+ }
3485
+
3486
+ Log.e(TAG, "Failed to send CRC command after " + MAX_BMP_RETRY_ATTEMPTS + " attempts")
3487
+ return false
3488
+ }
3489
+
3490
+ // Legacy methods for backward compatibility
3491
+ private fun sendBmpChunks(chunks: List<ByteArray>) {
3492
+ sendBmpChunksWithProgress(chunks, null)
3493
+ }
3494
+
3495
+ private fun sendBmpEndCommand() {
3496
+ sendBmpEndCommandWithRetry()
3497
+ }
3498
+
3499
+ private fun sendBmpCRC(bmpData: ByteArray) {
3500
+ sendBmpCrcWithRetry(bmpData)
3501
+ }
3502
+
3503
+ private fun sendBmpToSide(bmpData: ByteArray, side: String) {
3504
+ // For now, send to both sides but could be modified for side-specific sending
3505
+ displayBitmapImage(bmpData, object : BmpProgressCallback {
3506
+ override fun onProgress(side: String, offset: Int, chunkIndex: Int, totalSize: Int) {
3507
+ Bridge.log("G1: BMP progress for " + side + ": " + offset + "/" + totalSize)
3508
+ }
3509
+
3510
+ override fun onSuccess(side: String) {
3511
+ Bridge.log("G1: BMP sent successfully to " + side)
3512
+ }
3513
+
3514
+ override fun onError(side: String, error: String) {
3515
+ Log.e(TAG, "BMP error for " + side + ": " + error)
3516
+ }
3517
+ })
3518
+ }
3519
+
3520
+ private fun loadBmpFromFile(filePath: String): ByteArray? {
3521
+ try {
3522
+ val file = java.io.File(filePath)
3523
+ if (!file.exists()) {
3524
+ Log.e(TAG, "BMP file does not exist: " + filePath)
3525
+ return null
3526
+ }
3527
+
3528
+ // Read file into byte array
3529
+ val fileData = ByteArray(file.length().toInt())
3530
+ java.io.FileInputStream(file).use { fis ->
3531
+ fis.read(fileData)
3532
+ }
3533
+
3534
+ // Convert to 1-bit BMP format if needed
3535
+ return convertTo1BitBmp(fileData)
3536
+
3537
+ } catch (e: Exception) {
3538
+ Log.e(TAG, "Error loading BMP file: " + e.message)
3539
+ return null
3540
+ }
3541
+ }
3542
+
3543
+ private fun convertTo1BitBmp(originalBmp: ByteArray): ByteArray {
3544
+ // This is a placeholder - in a real implementation, you'd convert the BMP to
3545
+ // 1-bit format
3546
+ // For now, we'll assume the input is already in the correct format
3547
+ return originalBmp
3548
+ }
3549
+
3550
+ private fun loadEmptyBmpFromAssets(): ByteArray? {
3551
+ try {
3552
+ context!!.assets.open("empty_bmp.bmp").use { iss ->
3553
+ return iss.readAllBytes()
3554
+ }
3555
+ } catch (e: IOException) {
3556
+ Log.e(TAG, "Failed to load BMP from assets: " + e.message)
3557
+ return null
3558
+ }
3559
+ }
3560
+
3561
+ fun clearBmpDisplay() {
3562
+ if (updatingScreen)
3563
+ return
3564
+ Bridge.log("G1: Clearing BMP display with EXIT command")
3565
+ val exitCommand = byteArrayOf(0x18)
3566
+ sendDataSequentially(exitCommand)
3567
+ }
3568
+
3569
+ fun exitBmp() {
3570
+ clearBmpDisplay()
3571
+ }
3572
+
3573
+ // Enhanced error handling and validation
3574
+ fun validateBmpFormat(bmpData: ByteArray?): Boolean {
3575
+ if (bmpData == null || bmpData.size < 54) { // Minimum BMP header size
3576
+ Log.e(TAG, "Invalid BMP data: null or too short")
3577
+ return false
3578
+ }
3579
+
3580
+ // Check BMP signature
3581
+ if (bmpData[0] != 'B'.code.toByte() || bmpData[1] != 'M'.code.toByte()) {
3582
+ Log.e(TAG, "Invalid BMP signature")
3583
+ return false
3584
+ }
3585
+
3586
+ // Check if it's 1-bit format (simplified check)
3587
+ val bitsPerPixel = bmpData[28].toInt() and 0xFF
3588
+ if (bitsPerPixel != 1) {
3589
+ Log.w(TAG, "BMP is not 1-bit format (bits per pixel: " + bitsPerPixel + ")")
3590
+ }
3591
+
3592
+ return true
3593
+ }
3594
+
3595
+ // Batch processing with progress
3596
+ fun sendBmpBatch(bmpPaths: List<String>, callback: BmpProgressCallback?) {
3597
+ for (i in 0 until bmpPaths.size) {
3598
+ val path = bmpPaths[i]
3599
+
3600
+ if (callback != null) {
3601
+ callback.onProgress("batch", i, i, bmpPaths.size)
3602
+ }
3603
+
3604
+ try {
3605
+ val bmpData = loadBmpFromFile(path)
3606
+ if (bmpData != null && validateBmpFormat(bmpData)) {
3607
+ displayBitmapImage(bmpData, object : BmpProgressCallback {
3608
+ override fun onProgress(side: String, offset: Int, chunkIndex: Int, totalSize: Int) {
3609
+ // Individual image progress
3610
+ }
3611
+
3612
+ override fun onSuccess(side: String) {
3613
+ Bridge.log("G1: Successfully sent BMP: " + path)
3614
+ }
3615
+
3616
+ override fun onError(side: String, error: String) {
3617
+ Log.e(TAG, "Failed to send BMP " + path + ": " + error)
3618
+ if (callback != null) {
3619
+ callback.onError("batch", "Failed to send " + path + ": " + error)
3620
+ }
3621
+ }
3622
+ })
3623
+
3624
+ // Delay between images
3625
+ Thread.sleep(2000)
3626
+ } else {
3627
+ Log.e(TAG, "Invalid BMP format: " + path)
3628
+ if (callback != null) {
3629
+ callback.onError("batch", "Invalid BMP format: " + path)
3630
+ }
3631
+ }
3632
+ } catch (e: Exception) {
3633
+ Log.e(TAG, "Error processing BMP " + path + ": " + e.message)
3634
+ if (callback != null) {
3635
+ callback.onError("batch", "Error processing " + path + ": " + e.message)
3636
+ }
3637
+ }
3638
+ }
3639
+
3640
+ if (callback != null) {
3641
+ callback.onSuccess("batch")
3642
+ }
3643
+ }
3644
+
3645
+ private fun sendLoremIpsum() {
3646
+ if (updatingScreen)
3647
+ return
3648
+ val text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. "
3649
+ sendDataSequentially(createTextWallChunks(text))
3650
+ }
3651
+
3652
+ // Enhanced clearing with state management
3653
+ fun clearBmpDisplayWithState() {
3654
+ if (updatingScreen) {
3655
+ Bridge.log("G1: Screen update in progress, queuing clear command")
3656
+ // Queue the clear command for later
3657
+ handler.postDelayed(this::clearBmpDisplay, 1000L)
3658
+ return
3659
+ }
3660
+
3661
+ Bridge.log("G1: Clearing BMP display with EXIT command")
3662
+ updatingScreen = true
3663
+
3664
+ try {
3665
+ val exitCommand = byteArrayOf(0x18)
3666
+ val success = sendDataSequentiallyWithTimeout(exitCommand, 2000)
3667
+ if (success) {
3668
+ lastThingDisplayedWasAnImage = false
3669
+ Bridge.log("G1: BMP display cleared successfully")
3670
+ } else {
3671
+ Log.e(TAG, "Failed to clear BMP display")
3672
+ }
3673
+ } finally {
3674
+ updatingScreen = false
3675
+ }
3676
+ }
3677
+
3678
+ // Optimized batch clearing
3679
+ fun clearAndDisplayBmp(bmpData: ByteArray?, callback: BmpProgressCallback?) {
3680
+ if (updatingScreen) {
3681
+ Bridge.log("G1: Screen update in progress, cannot clear and display")
3682
+ if (callback != null)
3683
+ callback.onError("both", "Screen update in progress")
3684
+ return
3685
+ }
3686
+
3687
+ // Clear first, then display
3688
+ clearBmpDisplayWithState()
3689
+
3690
+ // Small delay to ensure clear completes
3691
+ handler.postDelayed({
3692
+ displayBitmapImage(bmpData, callback)
3693
+ }, 500L)
3694
+ }
3695
+
3696
+ // Efficient multiple image display with clearing
3697
+ fun displayBmpSequence(bmpDataList: List<ByteArray>?, callback: BmpProgressCallback?) {
3698
+ if (bmpDataList == null || bmpDataList.isEmpty()) {
3699
+ Log.e(TAG, "No BMP data provided for sequence")
3700
+ if (callback != null)
3701
+ callback.onError("sequence", "No BMP data provided")
3702
+ return
3703
+ }
3704
+
3705
+ displayBmpSequenceInternal(bmpDataList, 0, callback)
3706
+ }
3707
+
3708
+ private fun displayBmpSequenceInternal(bmpDataList: List<ByteArray>, index: Int, callback: BmpProgressCallback?) {
3709
+ if (index >= bmpDataList.size) {
3710
+ Bridge.log("G1: BMP sequence completed")
3711
+ if (callback != null)
3712
+ callback.onSuccess("sequence")
3713
+ return
3714
+ }
3715
+
3716
+ val bmpData = bmpDataList[index]
3717
+ displayBitmapImage(bmpData, object : BmpProgressCallback {
3718
+ override fun onProgress(side: String, offset: Int, chunkIndex: Int, totalSize: Int) {
3719
+ if (callback != null) {
3720
+ // Calculate overall progress including sequence position
3721
+ val overallProgress = (index * 100) / bmpDataList.size
3722
+ callback.onProgress("sequence", overallProgress, index, bmpDataList.size)
3723
+ }
3724
+ }
3725
+
3726
+ override fun onSuccess(side: String) {
3727
+ Bridge.log("G1: BMP " + (index + 1) + " of " + bmpDataList.size + " displayed successfully")
3728
+
3729
+ // Schedule next image with delay
3730
+ handler.postDelayed({
3731
+ displayBmpSequenceInternal(bmpDataList, index + 1, callback)
3732
+ }, 2000L) // 2 second delay between images
3733
+ }
3734
+
3735
+ override fun onError(side: String, error: String) {
3736
+ Log.e(TAG, "Failed to display BMP " + (index + 1) + ": " + error)
3737
+ if (callback != null) {
3738
+ callback.onError("sequence", "Failed to display BMP " + (index + 1) + ": " + error)
3739
+ }
3740
+ }
3741
+ })
3742
+ }
3743
+
3744
+ private fun quickRestartG1() {
3745
+ Bridge.log("G1: Sending restart 0x23 0x72 Command")
3746
+ sendDataSequentially(byteArrayOf(0x23.toByte(), 0x72.toByte())) // quick restart comand
3747
+ }
3748
+
3749
+ override fun setMicEnabled(enabled: Boolean) {
3750
+ Bridge.log("G1: setMicEnabled(): " + enabled)
3751
+
3752
+ // Update the shouldUseGlassesMic flag to reflect the current state
3753
+ this.shouldUseGlassesMic = enabled
3754
+ Bridge.log("G1: Updated shouldUseGlassesMic to: " + shouldUseGlassesMic)
3755
+
3756
+ if (enabled) {
3757
+ Bridge.log("G1: Microphone enabled, starting audio input handling")
3758
+ sendSetMicEnabled(true, 10)
3759
+ startMicBeat(MICBEAT_INTERVAL_MS.toInt())
3760
+ } else {
3761
+ Bridge.log("G1: Microphone disabled, stopping audio input handling")
3762
+ sendSetMicEnabled(false, 10)
3763
+ stopMicBeat()
3764
+ }
3765
+ }
3766
+
3767
+ override fun sortMicRanking(list: MutableList<String>): MutableList<String> {
3768
+ return list
3769
+ }
3770
+
3771
+ /**
3772
+ * Emits serial number information to React Native (matching iOS implementation)
3773
+ */
3774
+ private fun emitSerialNumberInfo(serialNumber: String, style: String, color: String) {
3775
+ try {
3776
+ val eventBody = JSONObject()
3777
+ eventBody.put("serialNumber", serialNumber)
3778
+ eventBody.put("style", style)
3779
+ eventBody.put("color", color)
3780
+
3781
+ // Bridge.sendTypedMessage("glasses_serial_number", eventBody);
3782
+ Bridge.log("G1: 📱 Emitted serial number info: " + serialNumber + ", Style: " + style + ", Color: " + color)
3783
+ DeviceStore.apply("glasses", "serialNumber", serialNumber)
3784
+ DeviceStore.apply("glasses", "style", style)
3785
+ DeviceStore.apply("glasses", "color", color)
3786
+
3787
+ } catch (e: Exception) {
3788
+ Bridge.log("G1: Error emitting serial number info: " + e.message)
3789
+ }
3790
+ }
3791
+
3792
+ /**
3793
+ * Decodes serial number from manufacturer data bytes
3794
+ *
3795
+ * @param manufacturerData The manufacturer data bytes
3796
+ * @return Decoded serial number string or null if not found
3797
+ */
3798
+ private fun decodeSerialFromManufacturerData(manufacturerData: ByteArray?): String? {
3799
+ if (manufacturerData == null || manufacturerData.size < 10) {
3800
+ return null
3801
+ }
3802
+
3803
+ try {
3804
+ // Convert hex bytes to ASCII string
3805
+ val serialBuilder = StringBuilder()
3806
+ for (i in 0 until manufacturerData.size) {
3807
+ val b = manufacturerData[i]
3808
+ if (b.toInt() == 0x00) {
3809
+ // Stop at null terminator
3810
+ break
3811
+ }
3812
+ if (b.toInt() >= 0x20 && b.toInt() <= 0x7E) {
3813
+ // Only include printable ASCII characters
3814
+ serialBuilder.append(b.toInt().toChar())
3815
+ }
3816
+ }
3817
+
3818
+ val decodedString = serialBuilder.toString().trim()
3819
+
3820
+ // Check if it looks like a valid Even G1 serial number
3821
+ if (decodedString.length >= 12 &&
3822
+ (decodedString.startsWith("S1") || decodedString.startsWith("100")
3823
+ || decodedString.startsWith("110"))) {
3824
+ return decodedString
3825
+ }
3826
+
3827
+ return null
3828
+ } catch (e: Exception) {
3829
+ Log.e(TAG, "Error decoding manufacturer data: " + e.message)
3830
+ return null
3831
+ }
3832
+ }
3833
+
3834
+ override fun cleanup() {
3835
+ // TODO:
3836
+ }
3837
+ }