react-native-mytatva-rn-sdk 1.2.24 → 1.2.25

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.
@@ -61,893 +61,929 @@ import kotlin.coroutines.suspendCoroutine
61
61
 
62
62
  @ReactModule(name = "CgmTrackyLib")
63
63
  class CgmTrackyLibModule(reactContext: ReactApplicationContext) :
64
- ReactContextBaseJavaModule(reactContext) {
65
- private val mModel: MainActivityModel
66
- var authenticateSDKService: AuthenticateSDKService
67
- private val job = Job()
68
- private val scope = CoroutineScope(Dispatchers.IO + job)
69
- var prefsHelper: SharedPreferencesLibraryUtil
70
- private val apiScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
71
- private var debounceJob: Job? = null
72
- private var lastDeviceStatus: PocDevice? = null
73
-
74
- private var glucoseObserver: Observer<PocGlucose?>? = null
75
- private var isObserving = false
76
-
77
- init {
78
- mReactContext = reactContext
79
- prefsHelper = SharedPreferencesLibraryUtil(mReactContext)
80
- val viewModelStore = ViewModelStore()
81
- val factory =
82
- ViewModelProvider.AndroidViewModelFactory.getInstance(reactContext.applicationContext as Application)
83
- mModel = ViewModelProvider(viewModelStore, factory)[MainActivityModel::class.java]
84
- authenticateSDKService = AuthenticateSDKService(scope = scope)
85
- }
86
-
87
-
88
- companion object {
89
- var mReactContext: ReactApplicationContext? = null
90
- var userToken: String = ""
91
- }
92
-
93
- override fun getName(): String {
94
- return "CgmTrackyLib"
95
- }
96
-
97
- @ReactMethod
98
- fun observeDeviceStatus(token: String) {
99
- try {
100
- userToken = token
101
- Handler(Looper.getMainLooper()).post {
102
- mModel.device.observeForever { device ->
103
- if (device != lastDeviceStatus) {
104
- lastDeviceStatus = device
105
- postEventDataToAPI(device, "")
106
- resetDebounceTimer()
107
- }
108
-
109
- if (device != null) {
110
- Log.d("observeDeviceStatus: ", device.toString())
111
- }
112
- }
113
- }
114
- } catch (e: Exception) {
115
- Log.e("observeDeviceStatus", "observeDeviceStatus: ${e.message}")
64
+ ReactContextBaseJavaModule(reactContext) {
65
+ private val mModel: MainActivityModel
66
+ var authenticateSDKService: AuthenticateSDKService
67
+ private val job = Job()
68
+ private val scope = CoroutineScope(Dispatchers.IO + job)
69
+ var prefsHelper: SharedPreferencesLibraryUtil
70
+ private val apiScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
71
+ private var debounceJob: Job? = null
72
+ private var lastDeviceStatus: PocDevice? = null
73
+
74
+ private var glucoseObserver: Observer<PocGlucose?>? = null
75
+ private var isObserving = false
76
+
77
+ init {
78
+ mReactContext = reactContext
79
+ prefsHelper = SharedPreferencesLibraryUtil(mReactContext)
80
+ val viewModelStore = ViewModelStore()
81
+ val factory =
82
+ ViewModelProvider.AndroidViewModelFactory.getInstance(reactContext.applicationContext as Application)
83
+ mModel = ViewModelProvider(viewModelStore, factory)[MainActivityModel::class.java]
84
+ authenticateSDKService = AuthenticateSDKService(scope = scope)
116
85
  }
117
- }
118
86
 
119
- @ReactMethod
120
- fun observeTransmitterUnbindStatus(token: String) {
121
- try {
122
- userToken = token
123
87
 
124
- authenticateSDKService.getCGMData(
125
- environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
126
- token = userToken,
127
- responseListener = object : AuthenticateSDKService.ResponseListener {
128
- override fun onResponseSuccess(response: String) {
88
+ companion object {
89
+ var mReactContext: ReactApplicationContext? = null
90
+ var userToken: String = ""
91
+ }
129
92
 
130
- val response = Gson().fromJson(response, CgmSensorResponse::class.java)
131
- val sensor = response.data?.firstOrNull()
93
+ override fun getName(): String {
94
+ return "CgmTrackyLib"
95
+ }
132
96
 
133
- if (sensor != null && !sensor.startDate.isNullOrEmpty() && !sensor.endDate.isNullOrEmpty()) {
134
- val startDate = sensor.startDate
135
- val endDate = sensor.endDate
97
+ @ReactMethod
98
+ fun observeDeviceStatus(token: String) {
99
+ try {
100
+ userToken = token
101
+ Handler(Looper.getMainLooper()).post {
102
+ mModel.device.observeForever { device ->
103
+ if (device != lastDeviceStatus) {
104
+ lastDeviceStatus = device
105
+ postEventDataToAPI(device, "", lastDeviceStatus?.qrMessage ?: "")
106
+ resetDebounceTimer()
107
+ }
136
108
 
137
- println("Start Date: $startDate")
138
- println("End Date: $endDate")
109
+ if (device != null) {
110
+ Log.d("observeDeviceStatus: ", device.toString())
111
+ }
112
+ }
113
+ }
114
+ } catch (e: Exception) {
115
+ Log.e("observeDeviceStatus", "observeDeviceStatus: ${e.message}")
116
+ }
117
+ }
139
118
 
140
- if (isCurrentDateInRange(startDate, endDate)) {
119
+ @ReactMethod
120
+ fun observeTransmitterUnbindStatus(token: String) {
121
+ try {
122
+ userToken = token
123
+
124
+ val sharedPreferencesLibraryUtil =
125
+ SharedPreferencesLibraryUtil(BApplication.getContext())
126
+ val information = sharedPreferencesLibraryUtil.qrInformation
127
+ if (information != null) {
128
+ Log.e("observeTransmitterUnbindStatus", Gson().toJson(information).toString())
129
+
130
+ authenticateSDKService.getCGMData(
131
+ environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
132
+ token = userToken,
133
+ responseListener = object : AuthenticateSDKService.ResponseListener {
134
+ override fun onResponseSuccess(response: String) {
135
+
136
+ val response = Gson().fromJson(response, CgmSensorResponse::class.java)
137
+ val sensor = response.data?.firstOrNull()
138
+
139
+ if (sensor != null && !sensor.startDate.isNullOrEmpty() && !sensor.endDate.isNullOrEmpty()) {
140
+ val startDate = sensor.startDate
141
+ val endDate = sensor.endDate
142
+ val sensorId = sensor.sensorId
143
+
144
+ println("Start Date: $startDate")
145
+ println("End Date: $endDate")
146
+
147
+ if (isCurrentDateInRange(startDate, endDate)) {
148
+
149
+ println("Current date is in range")
150
+
151
+ val pocDevice =
152
+ RepositoryDevice.getInstance(BApplication.getContext()).latestDeviceIoThread
153
+ if (pocDevice != null) {
154
+ if (pocDevice.isUnBind) {
155
+ postEventDataToAPI(
156
+ pocDevice,
157
+ DeviceStatus.TRANSMITTER_DISCONNECT.id,
158
+ pocDevice.qrMessage
159
+ )
160
+ } else {
161
+ postEventDataToAPI(
162
+ pocDevice,
163
+ DeviceStatus.TRANSMITTER_DISCONNECT.id,
164
+ sensorId
165
+ )
166
+ }
167
+ }
168
+
169
+ } else {
170
+ println("Current date is out of range")
171
+ }
172
+ } else {
173
+ println("Start or End date not available")
174
+ }
175
+ }
176
+
177
+ override fun onResponseFail() {
178
+ }
179
+ }
180
+ )
181
+ }
182
+ } catch (e: Exception) {
183
+ Log.e("observeTransmitterUnbindStatus", "observeTransmitterUnbindStatus: ${e.message}")
184
+ }
185
+ }
141
186
 
142
- println("Current date is in range")
187
+ private fun postEventDataToAPI(device: PocDevice?, mStatus: String, sensorId: String?) {
188
+ apiScope.launch {
189
+ try {
190
+ val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
191
+ val bleStatus = bluetoothAdapter?.isEnabled == true
192
+ var status = ""
193
+
194
+ Log.d("ble Status", bleStatus.toString())
195
+ Log.d("device.isBoundAndConnect Status", device?.isBoundAndConnect.toString())
196
+ Log.d("device.isUnBind Status", device?.isUnBind.toString())
197
+ Log.d("device.isBoundButDisConnect Status", device?.isBoundButDisConnect.toString())
198
+
199
+ status = if (mStatus.isEmpty()) {
200
+ when {
201
+ device?.isBoundAndConnect == true -> DeviceStatus.CONNECTED.id
202
+ !bleStatus -> DeviceStatus.BLUETOOTH_OFF.id
203
+ device?.isUnBind == true -> DeviceStatus.TRANSMITTER_DISCONNECT.id
204
+ device?.isBoundButDisConnect == true -> DeviceStatus.DISCONNECTED.id
205
+ else -> "" // fallback if no status matches
206
+ }
207
+ } else {
208
+ mStatus
209
+ }
143
210
 
144
- val pocDevice =
145
- RepositoryDevice.getInstance(BApplication.getContext()).latestDeviceIoThread
146
- if (pocDevice != null) {
147
- if (pocDevice.isUnBind) {
148
- postEventDataToAPI(pocDevice, DeviceStatus.TRANSMITTER_DISCONNECT.id)
211
+ if (status.isNotEmpty()) {
212
+ val rawData = JSONObject().apply {
213
+ put("transmitterName", device?.name ?: "")
214
+ put("SensorId", sensorId ?: "")
215
+ put("Sensor", sensorId ?: "")
216
+ put("timeInMillis", Date().time)
149
217
  }
150
- }
151
218
 
152
- } else {
153
- println("Current date is out of range")
219
+ val obj = JSONObject().apply {
220
+ put("sensorId", sensorId ?: "")
221
+ put("status", status)
222
+ put("rawData", rawData)
223
+ }
224
+
225
+ authenticateSDKService.postDeviceData(
226
+ environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
227
+ data = obj.toString(),
228
+ token = userToken,
229
+ loaderListener = object : LoaderListener {
230
+ override fun onShowLoader() {}
231
+ override fun onHideLoader() {}
232
+ }
233
+ )
154
234
  }
155
- } else {
156
- println("Start or End date not available")
157
- }
158
- }
159
235
 
160
- override fun onResponseFail() {
236
+ } catch (e: Exception) {
237
+ e.printStackTrace()
161
238
  }
162
- }
163
- )
164
-
165
- } catch (e: Exception) {
166
- Log.e("observeTransmitterUnbindStatus", "observeTransmitterUnbindStatus: ${e.message}")
239
+ }
167
240
  }
168
- }
169
241
 
170
- private fun postEventDataToAPI(device: PocDevice, mStatus: String) {
171
- apiScope.launch {
172
- try {
173
- val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
174
- var bleStatus = bluetoothAdapter?.isEnabled == true
175
- var status = ""
176
- Log.d("ble Status", bleStatus.toString())
177
- Log.d("device.isBoundAndConnect Status", device.isBoundAndConnect.toString())
178
- Log.d("device.isUnBind Status", device.isUnBind.toString())
179
- Log.d("device.isBoundButDisConnect Status", device.isBoundButDisConnect.toString())
180
- if (mStatus.isEmpty()) {
181
- if (device.isBoundAndConnect) {
182
- status = DeviceStatus.CONNECTED.id
183
- } else if (!bleStatus) {
184
- status = DeviceStatus.BLUETOOTH_OFF.id
185
- } else if (device.isUnBind) {
186
- status = DeviceStatus.TRANSMITTER_DISCONNECT.id
187
- } else if (device.isBoundButDisConnect) {
188
- status = DeviceStatus.DISCONNECTED.id
189
- }
190
- } else {
191
- status = mStatus
242
+ private fun resetDebounceTimer() {
243
+ debounceJob?.cancel() // Cancel any existing timer
244
+ debounceJob = apiScope.launch {
245
+ delay(60 * 60 * 1000L) // 60 minutes in ms
246
+ lastDeviceStatus = null // Reset status after timeout
247
+ println("60 min window expired, status reset.")
192
248
  }
193
-
194
- if (status.isNotEmpty()) {
195
- val rawData = JSONObject()
196
- rawData.put("transmitterName", device.name)
197
- rawData.put("SensorId", device.qrMessage)
198
- rawData.put("Sensor", device.qrMessage)
199
- rawData.put("timeInMillis", Date().time)
200
-
201
- val obj = JSONObject()
202
- obj.put("sensorId", device.qrMessage)
203
- obj.put("status", status)
204
- obj.put("rawData", rawData)
205
-
206
- authenticateSDKService.postDeviceData(
207
- environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
208
- data = obj.toString(),
209
- token = userToken,
210
- loaderListener = object : LoaderListener {
211
- override fun onShowLoader() {
212
- }
213
-
214
- override fun onHideLoader() {
215
- }
216
- }
217
- )
218
- }
219
-
220
- } catch (e: Exception) {
221
- e.printStackTrace()
222
- }
223
- }
224
- }
225
-
226
- private fun resetDebounceTimer() {
227
- debounceJob?.cancel() // Cancel any existing timer
228
- debounceJob = apiScope.launch {
229
- delay(60 * 60 * 1000L) // 60 minutes in ms
230
- lastDeviceStatus = null // Reset status after timeout
231
- println("60 min window expired, status reset.")
232
249
  }
233
- }
234
250
 
235
- @ReactMethod
236
- fun startCgmTracky(token: String) {
237
- try {
238
- userToken = token
239
- val intent = Intent(currentActivity, StartCGMActivity::class.java)
240
- currentActivity?.startActivity(intent)
241
- } catch (e: Exception) {
242
- Log.e("startCgmTracky", "startCgmTracky: ${e.message}")
251
+ @ReactMethod
252
+ fun startCgmTracky(token: String) {
253
+ try {
254
+ userToken = token
255
+ val intent = Intent(currentActivity, StartCGMActivity::class.java)
256
+ currentActivity?.startActivity(intent)
257
+ } catch (e: Exception) {
258
+ Log.e("startCgmTracky", "startCgmTracky: ${e.message}")
259
+ }
243
260
  }
244
- }
245
-
246
- fun isCurrentDateInRange(startDateStr: String, endDateStr: String): Boolean {
247
- val format = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
248
261
 
249
- val startDate = format.parse(startDateStr)
250
- val endDate = format.parse(endDateStr)
251
- val currentDate = Date()
262
+ fun isCurrentDateInRange(startDateStr: String, endDateStr: String): Boolean {
263
+ val format = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
252
264
 
253
- return startDate != null && endDate != null &&
254
- !currentDate.before(startDate) && !currentDate.after(endDate)
255
- }
265
+ val startDate = format.parse(startDateStr)
266
+ val endDate = format.parse(endDateStr)
267
+ val currentDate = Date()
256
268
 
257
- @ReactMethod
258
- fun reconnectCgmTracky(token: String) {
259
- try {
260
- userToken = token
261
- val intent = if (areAllPermissionsGranted()) {
262
- Intent(currentActivity, SearchTransmitterActivity::class.java).putExtra(
263
- "IsForReconnect",
264
- true
265
- )
266
- } else {
267
- Intent(currentActivity, PermissionActivity::class.java).putExtra("IsForReconnect", true)
268
- }
269
- currentActivity?.startActivity(intent)
270
- } catch (e: Exception) {
271
- Log.e("reconnectCgmTracky", "reconnectCgmTracky: ${e.message}")
269
+ return startDate != null && endDate != null &&
270
+ !currentDate.before(startDate) && !currentDate.after(endDate)
272
271
  }
273
- }
274
-
275
- @ReactMethod
276
- fun openHelpSupport() {
277
- try {
278
- val intent = Intent(currentActivity, HelpActivity::class.java)
279
- currentActivity?.startActivity(intent)
280
- } catch (e: Exception) {
281
- Log.e("openHelpSupport", "openHelpSupport: ${e.message}")
282
- }
283
- }
284
-
285
- private fun areAllPermissionsGranted(): Boolean {
286
- val requiredPermissions = mutableListOf<String>()
287
272
 
288
- // Add Bluetooth permissions
289
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
290
- requiredPermissions.addAll(PermissionUtils.BLUETOOTH_S)
273
+ @ReactMethod
274
+ fun reconnectCgmTracky(token: String) {
275
+ try {
276
+ userToken = token
277
+ val intent = if (areAllPermissionsGranted()) {
278
+ Intent(currentActivity, SearchTransmitterActivity::class.java).putExtra(
279
+ "IsForReconnect",
280
+ true
281
+ )
282
+ } else {
283
+ Intent(currentActivity, PermissionActivity::class.java).putExtra(
284
+ "IsForReconnect",
285
+ true
286
+ )
287
+ }
288
+ currentActivity?.startActivity(intent)
289
+ } catch (e: Exception) {
290
+ Log.e("reconnectCgmTracky", "reconnectCgmTracky: ${e.message}")
291
+ }
291
292
  }
292
293
 
293
- // Add location permissions
294
- requiredPermissions.addAll(PermissionUtils.LOCAL_PERMISSION)
295
-
296
- // Add camera permission
297
- requiredPermissions.addAll(PermissionUtils.CAMERA_PERMISSION)
298
-
299
- return requiredPermissions.all {
300
- ContextCompat.checkSelfPermission(mReactContext!!, it) == PackageManager.PERMISSION_GRANTED
294
+ @ReactMethod
295
+ fun openHelpSupport() {
296
+ try {
297
+ val intent = Intent(currentActivity, HelpActivity::class.java)
298
+ currentActivity?.startActivity(intent)
299
+ } catch (e: Exception) {
300
+ Log.e("openHelpSupport", "openHelpSupport: ${e.message}")
301
+ }
301
302
  }
302
- }
303
303
 
304
+ private fun areAllPermissionsGranted(): Boolean {
305
+ val requiredPermissions = mutableListOf<String>()
304
306
 
305
- /*@ReactMethod
306
- fun observeGlucoseData(token: String) {
307
- try {
308
- userToken = token
309
- Handler(Looper.getMainLooper()).post {
310
- //Observe latest glucose data
311
- mModel.latestGlucose.observeForever { pocGlucose ->
312
- if (pocGlucose != null) {
307
+ // Add Bluetooth permissions
308
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
309
+ requiredPermissions.addAll(PermissionUtils.BLUETOOTH_S)
310
+ }
313
311
 
314
- if (pocGlucose.errorCode == enumError.NONE) {
315
- if (pocGlucose.showGlucoseMG > 0) {
316
- val dto: GlucoseLog = mapToDto(pocGlucose)
317
- val logs: ArrayList<GlucoseLog> = ArrayList()
318
- logs.add(dto)
312
+ // Add location permissions
313
+ requiredPermissions.addAll(PermissionUtils.LOCAL_PERMISSION)
319
314
 
320
- val request: GlucoseLogRequest =
321
- GlucoseLogRequest(vendor = "GoodFlip", logs = logs)
322
- val gson: Gson = GsonBuilder().create()
323
- val json = gson.toJson(request)
315
+ // Add camera permission
316
+ requiredPermissions.addAll(PermissionUtils.CAMERA_PERMISSION)
324
317
 
325
- Log.d("Glucose data 3 min==> ", "Glucose data 3 min==> final Json: $json")
318
+ return requiredPermissions.all {
319
+ ContextCompat.checkSelfPermission(
320
+ mReactContext!!,
321
+ it
322
+ ) == PackageManager.PERMISSION_GRANTED
323
+ }
324
+ }
326
325
 
327
- authenticateSDKService.postCGMData(
328
- environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
329
- data = json.toString(),
330
- token = userToken,
331
- responseListener = object :
332
- AuthenticateSDKService.ResponseListener {
333
- override fun onResponseSuccess() {
334
- }
335
326
 
336
- override fun onResponseFail() {
327
+ /*@ReactMethod
328
+ fun observeGlucoseData(token: String) {
329
+ try {
330
+ userToken = token
331
+ Handler(Looper.getMainLooper()).post {
332
+ //Observe latest glucose data
333
+ mModel.latestGlucose.observeForever { pocGlucose ->
334
+ if (pocGlucose != null) {
335
+
336
+ if (pocGlucose.errorCode == enumError.NONE) {
337
+ if (pocGlucose.showGlucoseMG > 0) {
338
+ val dto: GlucoseLog = mapToDto(pocGlucose)
339
+ val logs: ArrayList<GlucoseLog> = ArrayList()
340
+ logs.add(dto)
341
+
342
+ val request: GlucoseLogRequest =
343
+ GlucoseLogRequest(vendor = "GoodFlip", logs = logs)
344
+ val gson: Gson = GsonBuilder().create()
345
+ val json = gson.toJson(request)
346
+
347
+ Log.d("Glucose data 3 min==> ", "Glucose data 3 min==> final Json: $json")
348
+
349
+ authenticateSDKService.postCGMData(
350
+ environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
351
+ data = json.toString(),
352
+ token = userToken,
353
+ responseListener = object :
354
+ AuthenticateSDKService.ResponseListener {
355
+ override fun onResponseSuccess() {
356
+ }
357
+
358
+ override fun onResponseFail() {
359
+ }
337
360
  }
338
- }
339
- )
340
- }
341
- } else {
342
- if (pocGlucose.errorCode == enumError.ERROR_FLOODING_WATER) {
343
- lastDeviceStatus =
344
- pocGlucose.deviceId.toInt().let { mModel.getDeviceInfo(it) }
345
- lastDeviceStatus?.let {
346
- postEventDataToAPI(
347
- it,
348
- DeviceStatus.MOISTURE_DETECT.id
349
- )
350
- }
351
- resetDebounceTimer()
352
- } else if (pocGlucose.errorCode == enumError.ERROR_CURRENT_SMALL || pocGlucose.errorCode == enumError.ERROR_NOISE || pocGlucose.errorCode == enumError.ERROR_SENSITIVITY_ATTENUATION) {
353
- lastDeviceStatus =
354
- pocGlucose.deviceId.toInt().let { mModel.getDeviceInfo(it) }
355
- lastDeviceStatus?.let {
356
- postEventDataToAPI(
357
- it,
358
- DeviceStatus.WEAK_SIGNAL.id
359
361
  )
360
362
  }
361
- resetDebounceTimer()
362
363
  } else {
363
- lastDeviceStatus =
364
- pocGlucose.deviceId.toInt().let { mModel.getDeviceInfo(it) }
365
- lastDeviceStatus?.let {
366
- postEventDataToAPI(
367
- it,
368
- DeviceStatus.ERROR_COMMON.id
369
- )
364
+ if (pocGlucose.errorCode == enumError.ERROR_FLOODING_WATER) {
365
+ lastDeviceStatus =
366
+ pocGlucose.deviceId.toInt().let { mModel.getDeviceInfo(it) }
367
+ lastDeviceStatus?.let {
368
+ postEventDataToAPI(
369
+ it,
370
+ DeviceStatus.MOISTURE_DETECT.id
371
+ )
372
+ }
373
+ resetDebounceTimer()
374
+ } else if (pocGlucose.errorCode == enumError.ERROR_CURRENT_SMALL || pocGlucose.errorCode == enumError.ERROR_NOISE || pocGlucose.errorCode == enumError.ERROR_SENSITIVITY_ATTENUATION) {
375
+ lastDeviceStatus =
376
+ pocGlucose.deviceId.toInt().let { mModel.getDeviceInfo(it) }
377
+ lastDeviceStatus?.let {
378
+ postEventDataToAPI(
379
+ it,
380
+ DeviceStatus.WEAK_SIGNAL.id
381
+ )
382
+ }
383
+ resetDebounceTimer()
384
+ } else {
385
+ lastDeviceStatus =
386
+ pocGlucose.deviceId.toInt().let { mModel.getDeviceInfo(it) }
387
+ lastDeviceStatus?.let {
388
+ postEventDataToAPI(
389
+ it,
390
+ DeviceStatus.ERROR_COMMON.id
391
+ )
392
+ }
393
+ resetDebounceTimer()
370
394
  }
371
- resetDebounceTimer()
372
395
  }
373
396
  }
374
397
  }
375
398
  }
399
+ } catch (e: Exception) {
400
+ Log.e("observeGlucoseData", "observeGlucoseData: ${e.message}")
376
401
  }
377
- } catch (e: Exception) {
378
- Log.e("observeGlucoseData", "observeGlucoseData: ${e.message}")
379
- }
380
- }*/
402
+ }*/
381
403
 
382
- @ReactMethod
383
- fun observeGlucoseData(token: String) {
384
- try {
385
- userToken = token
404
+ @ReactMethod
405
+ fun observeGlucoseData(token: String) {
406
+ try {
407
+ userToken = token
386
408
 
387
- // Remove existing observer if any to prevent memory leaks
388
- stopObservingGlucoseData()
409
+ // Remove existing observer if any to prevent memory leaks
410
+ stopObservingGlucoseData()
389
411
 
390
- // Create new observer with explicit nullable parameter type
391
- glucoseObserver = Observer<PocGlucose?> { pocGlucose ->
392
- // Critical fix: Explicitly handle nullable parameter
393
- if (pocGlucose != null) {
394
- handleGlucoseData(pocGlucose)
395
- } else {
396
- Log.w("observeGlucoseData", "Received null glucose data - skipping processing")
397
- }
398
- }
412
+ // Create new observer with explicit nullable parameter type
413
+ glucoseObserver = Observer<PocGlucose?> { pocGlucose ->
414
+ // Critical fix: Explicitly handle nullable parameter
415
+ if (pocGlucose != null) {
416
+ handleGlucoseData(pocGlucose)
417
+ } else {
418
+ Log.w("observeGlucoseData", "Received null glucose data - skipping processing")
419
+ }
420
+ }
399
421
 
400
- // Add observer on main thread
401
- Handler(Looper.getMainLooper()).post {
402
- glucoseObserver?.let { observer ->
403
- try {
404
- mModel.latestGlucose.observeForever(observer)
405
- isObserving = true
406
- Log.d("observeGlucoseData", "Observer added successfully")
407
- } catch (e: Exception) {
408
- Log.e("observeGlucoseData", "Error adding observer: ${e.message}")
409
- glucoseObserver = null
410
- }
422
+ // Add observer on main thread
423
+ Handler(Looper.getMainLooper()).post {
424
+ glucoseObserver?.let { observer ->
425
+ try {
426
+ mModel.latestGlucose.observeForever(observer)
427
+ isObserving = true
428
+ Log.d("observeGlucoseData", "Observer added successfully")
429
+ } catch (e: Exception) {
430
+ Log.e("observeGlucoseData", "Error adding observer: ${e.message}")
431
+ glucoseObserver = null
432
+ }
433
+ }
434
+ }
435
+ } catch (e: Exception) {
436
+ Log.e("observeGlucoseData", "observeGlucoseData: ${e.message}")
437
+ e.printStackTrace()
411
438
  }
412
- }
413
- } catch (e: Exception) {
414
- Log.e("observeGlucoseData", "observeGlucoseData: ${e.message}")
415
- e.printStackTrace()
416
439
  }
417
- }
418
-
419
440
 
420
- private fun handleGlucoseData(pocGlucose: PocGlucose) {
421
- try {
422
- // Additional safety check
423
- if (pocGlucose.glucoseId == null) {
424
- Log.w("handleGlucoseData", "Glucose ID is null, skipping processing")
425
- return
426
- }
427
-
428
- Log.d("handleGlucoseData", "Processing glucose data: ${pocGlucose.glucoseId}")
429
-
430
- if (pocGlucose.errorCode == enumError.NONE) {
431
- if (pocGlucose.showGlucoseMG > 0) {
432
- val dto: GlucoseLog = mapToDto(pocGlucose)
433
- val logs: ArrayList<GlucoseLog> = ArrayList()
434
- logs.add(dto)
435
441
 
436
- val request: GlucoseLogRequest = GlucoseLogRequest(vendor = "GoodFlip", logs = logs)
437
- val gson: Gson = GsonBuilder().create()
438
- val json = gson.toJson(request)
439
-
440
- Log.d("Glucose data 3 min==> ", "Glucose data 3 min==> final Json: $json")
442
+ private fun handleGlucoseData(pocGlucose: PocGlucose) {
443
+ try {
444
+ // Additional safety check
445
+ if (pocGlucose.glucoseId == null) {
446
+ Log.w("handleGlucoseData", "Glucose ID is null, skipping processing")
447
+ return
448
+ }
441
449
 
442
- authenticateSDKService.postCGMData(
443
- environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
444
- data = json,
445
- token = userToken,
446
- responseListener = object : AuthenticateSDKService.ResponseListener {
447
- override fun onResponseSuccess(response: String) {
448
- Log.d("CGM Data", "Single glucose data uploaded successfully")
449
- }
450
+ Log.d("handleGlucoseData", "Processing glucose data: ${pocGlucose.glucoseId}")
450
451
 
451
- override fun onResponseFail() {
452
- Log.e("CGM Data", "Failed to upload single glucose data")
453
- }
452
+ if (pocGlucose.errorCode == enumError.NONE) {
453
+ if (pocGlucose.showGlucoseMG > 0) {
454
+ val dto: GlucoseLog = mapToDto(pocGlucose)
455
+ val logs: ArrayList<GlucoseLog> = ArrayList()
456
+ logs.add(dto)
457
+
458
+ val request: GlucoseLogRequest =
459
+ GlucoseLogRequest(vendor = "GoodFlip", logs = logs)
460
+ val gson: Gson = GsonBuilder().create()
461
+ val json = gson.toJson(request)
462
+
463
+ Log.d("Glucose data 3 min==> ", "Glucose data 3 min==> final Json: $json")
464
+
465
+ authenticateSDKService.postCGMData(
466
+ environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
467
+ data = json,
468
+ token = userToken,
469
+ responseListener = object : AuthenticateSDKService.ResponseListener {
470
+ override fun onResponseSuccess(response: String) {
471
+ Log.d("CGM Data", "Single glucose data uploaded successfully")
472
+ }
473
+
474
+ override fun onResponseFail() {
475
+ Log.e("CGM Data", "Failed to upload single glucose data")
476
+ }
477
+ }
478
+ )
479
+ } else {
480
+ Log.d(
481
+ "handleGlucoseData",
482
+ "Glucose value is 0 or negative: ${pocGlucose.showGlucoseMG}"
483
+ )
484
+ }
485
+ } else {
486
+ Log.d("handleGlucoseData", "Glucose data has error: ${pocGlucose.errorCode}")
487
+ handleGlucoseError(pocGlucose)
454
488
  }
455
- )
456
- } else {
457
- Log.d("handleGlucoseData", "Glucose value is 0 or negative: ${pocGlucose.showGlucoseMG}")
489
+ } catch (e: Exception) {
490
+ Log.e("handleGlucoseData", "Error handling glucose data: ${e.message}")
491
+ e.printStackTrace()
458
492
  }
459
- } else {
460
- Log.d("handleGlucoseData", "Glucose data has error: ${pocGlucose.errorCode}")
461
- handleGlucoseError(pocGlucose)
462
- }
463
- } catch (e: Exception) {
464
- Log.e("handleGlucoseData", "Error handling glucose data: ${e.message}")
465
- e.printStackTrace()
466
493
  }
467
- }
468
-
469
- // Extract error handling logic
470
- private fun handleGlucoseError(pocGlucose: PocGlucose) {
471
- try {
472
- // Additional safety check for deviceId
473
- if (pocGlucose.deviceId == null) {
474
- Log.e("handleGlucoseError", "Device ID is null, cannot process error")
475
- return
476
- }
477
494
 
478
- val deviceInfo = mModel.getDeviceInfo(pocGlucose.deviceId.toInt())
479
- deviceInfo?.let {
480
- val statusId = when (pocGlucose.errorCode) {
481
- enumError.ERROR_FLOODING_WATER -> {
482
- Log.d("handleGlucoseError", "Moisture detected")
483
- DeviceStatus.MOISTURE_DETECT.id
484
- }
495
+ // Extract error handling logic
496
+ private fun handleGlucoseError(pocGlucose: PocGlucose) {
497
+ try {
498
+ // Additional safety check for deviceId
499
+ if (pocGlucose.deviceId == null) {
500
+ Log.e("handleGlucoseError", "Device ID is null, cannot process error")
501
+ return
502
+ }
485
503
 
486
- enumError.ERROR_CURRENT_SMALL,
487
- enumError.ERROR_NOISE,
488
- enumError.ERROR_SENSITIVITY_ATTENUATION -> {
489
- Log.d("handleGlucoseError", "Weak signal detected")
490
- DeviceStatus.WEAK_SIGNAL.id
491
- }
504
+ val deviceInfo = mModel.getDeviceInfo(pocGlucose.deviceId.toInt())
505
+ deviceInfo?.let {
506
+ val statusId = when (pocGlucose.errorCode) {
507
+ enumError.ERROR_FLOODING_WATER -> {
508
+ Log.d("handleGlucoseError", "Moisture detected")
509
+ DeviceStatus.MOISTURE_DETECT.id
510
+ }
492
511
 
493
- else -> {
494
- Log.d("handleGlucoseError", "Common error detected: ${pocGlucose.errorCode}")
495
- DeviceStatus.ERROR_COMMON.id
496
- }
497
- }
512
+ enumError.ERROR_CURRENT_SMALL,
513
+ enumError.ERROR_NOISE,
514
+ enumError.ERROR_SENSITIVITY_ATTENUATION -> {
515
+ Log.d("handleGlucoseError", "Weak signal detected")
516
+ DeviceStatus.WEAK_SIGNAL.id
517
+ }
498
518
 
499
- postEventDataToAPI(it, statusId)
500
- resetDebounceTimer()
501
- } ?: run {
502
- Log.e("handleGlucoseError", "Device info not found for deviceId: ${pocGlucose.deviceId}")
503
- }
504
- } catch (e: Exception) {
505
- Log.e("handleGlucoseError", "Error handling glucose error: ${e.message}")
506
- e.printStackTrace()
507
- }
508
- }
519
+ else -> {
520
+ Log.d(
521
+ "handleGlucoseError",
522
+ "Common error detected: ${pocGlucose.errorCode}"
523
+ )
524
+ DeviceStatus.ERROR_COMMON.id
525
+ }
526
+ }
509
527
 
510
- /*@ReactMethod
511
- fun observeAllGlucoseData(token: String) {
512
- userToken = token
513
- Log.e("userToken", "userToken: ${userToken}")
514
- try {
515
- val lastSyncData = prefsHelper.lastSyncData
516
- Log.d("lastSyncData: ", Gson().toJson(lastSyncData).toString())
528
+ postEventDataToAPI(it, statusId, it.qrMessage)
529
+ resetDebounceTimer()
530
+ } ?: run {
531
+ Log.e(
532
+ "handleGlucoseError",
533
+ "Device info not found for deviceId: ${pocGlucose.deviceId}"
534
+ )
535
+ }
536
+ } catch (e: Exception) {
537
+ Log.e("handleGlucoseError", "Error handling glucose error: ${e.message}")
538
+ e.printStackTrace()
539
+ }
540
+ }
517
541
 
518
- if (lastSyncData != null) {
519
- CoroutineScope(Dispatchers.IO).launch {
520
- getGlucoseDataAndUploadInBatch(
521
- mModel.getGlucoseBetweenTime(
522
- lastSyncData.lastSyncTime
542
+ /*@ReactMethod
543
+ fun observeAllGlucoseData(token: String) {
544
+ userToken = token
545
+ Log.e("userToken", "userToken: ${userToken}")
546
+ try {
547
+ val lastSyncData = prefsHelper.lastSyncData
548
+ Log.d("lastSyncData: ", Gson().toJson(lastSyncData).toString())
549
+
550
+ if (lastSyncData != null) {
551
+ CoroutineScope(Dispatchers.IO).launch {
552
+ getGlucoseDataAndUploadInBatch(
553
+ mModel.getGlucoseBetweenTime(
554
+ lastSyncData.lastSyncTime
555
+ )
523
556
  )
524
- )
557
+ }
558
+ } else {
559
+ observeGlucoseData(userToken)
525
560
  }
526
- } else {
527
- observeGlucoseData(userToken)
528
- }
529
-
530
- } catch (e: Exception) {
531
- Log.e("observeAllGlucoseData", "observeAllGlucoseData Error: ${e.message}")
532
- }
533
- }*/
534
561
 
562
+ } catch (e: Exception) {
563
+ Log.e("observeAllGlucoseData", "observeAllGlucoseData Error: ${e.message}")
564
+ }
565
+ }*/
535
566
 
536
- @ReactMethod
537
- fun observeAllGlucoseData(token: String) {
538
- userToken = token
539
- Log.e("userToken", "userToken: $token")
540
567
 
541
- // Stop current observation to prevent duplicates
542
- stopObservingGlucoseData()
568
+ @ReactMethod
569
+ fun observeAllGlucoseData(token: String) {
570
+ userToken = token
571
+ Log.e("userToken", "userToken: $token")
543
572
 
544
- try {
545
- val lastSyncData = prefsHelper.lastSyncData
546
- Log.d("lastSyncData: ", Gson().toJson(lastSyncData).toString())
573
+ // Stop current observation to prevent duplicates
574
+ stopObservingGlucoseData()
547
575
 
548
- if (lastSyncData != null) {
549
- CoroutineScope(Dispatchers.IO).launch {
550
- val glucoseData = mModel.getGlucoseBetweenTime(lastSyncData.lastSyncTime)
551
- if (glucoseData != null) {
552
- getGlucoseDataAndUploadInBatch(glucoseData)
553
- } else {
554
- Log.d("observeAllGlucoseData", "No glucose data found, starting live observation")
555
- observeGlucoseData(userToken)
556
- }
576
+ try {
577
+ val lastSyncData = prefsHelper.lastSyncData
578
+ Log.d("lastSyncData: ", Gson().toJson(lastSyncData).toString())
579
+
580
+ if (lastSyncData != null) {
581
+ CoroutineScope(Dispatchers.IO).launch {
582
+ val glucoseData = mModel.getGlucoseBetweenTime(lastSyncData.lastSyncTime)
583
+ if (glucoseData != null) {
584
+ getGlucoseDataAndUploadInBatch(glucoseData)
585
+ } else {
586
+ Log.d(
587
+ "observeAllGlucoseData",
588
+ "No glucose data found, starting live observation"
589
+ )
590
+ observeGlucoseData(userToken)
591
+ }
592
+ }
593
+ } else {
594
+ observeGlucoseData(userToken)
595
+ }
596
+ } catch (e: Exception) {
597
+ Log.e("observeAllGlucoseData", "observeAllGlucoseData Error: ${e.message}")
557
598
  }
558
- } else {
559
- observeGlucoseData(userToken)
560
- }
561
- } catch (e: Exception) {
562
- Log.e("observeAllGlucoseData", "observeAllGlucoseData Error: ${e.message}")
563
599
  }
564
- }
565
600
 
566
- @ReactMethod
567
- fun stopObservingGlucoseData() {
568
- try {
569
- glucoseObserver?.let { observer ->
570
- Handler(Looper.getMainLooper()).post {
571
- try {
572
- mModel.latestGlucose.removeObserver(observer)
573
- isObserving = false
574
- Log.d("stopObservingGlucoseData", "Observer removed successfully")
575
- } catch (e: Exception) {
576
- Log.e("stopObservingGlucoseData", "Error removing observer: ${e.message}")
577
- }
601
+ @ReactMethod
602
+ fun stopObservingGlucoseData() {
603
+ try {
604
+ glucoseObserver?.let { observer ->
605
+ Handler(Looper.getMainLooper()).post {
606
+ try {
607
+ mModel.latestGlucose.removeObserver(observer)
608
+ isObserving = false
609
+ Log.d("stopObservingGlucoseData", "Observer removed successfully")
610
+ } catch (e: Exception) {
611
+ Log.e("stopObservingGlucoseData", "Error removing observer: ${e.message}")
612
+ }
613
+ }
614
+ }
615
+ glucoseObserver = null
616
+ } catch (e: Exception) {
617
+ Log.e("stopObservingGlucoseData", "Error stopping observer: ${e.message}")
578
618
  }
579
- }
580
- glucoseObserver = null
581
- } catch (e: Exception) {
582
- Log.e("stopObservingGlucoseData", "Error stopping observer: ${e.message}")
583
- }
584
- }
585
-
586
- fun getGlucoseDataAndUploadInBatch(dataList: List<PocGlucose>) {
587
- if (dataList.isEmpty()) {
588
- Log.d("getGlucoseDataAndUploadInBatch", "No data to upload, starting live observation")
589
- if (!isObserving) {
590
- observeGlucoseData(userToken)
591
- }
592
- return
593
619
  }
594
620
 
595
- val batchSize = 40
596
- val chunks = dataList.chunked(batchSize)
621
+ fun getGlucoseDataAndUploadInBatch(dataList: List<PocGlucose>) {
622
+ if (dataList.isEmpty()) {
623
+ Log.d("getGlucoseDataAndUploadInBatch", "No data to upload, starting live observation")
624
+ if (!isObserving) {
625
+ observeGlucoseData(userToken)
626
+ }
627
+ return
628
+ }
597
629
 
598
- Log.d("getGlucoseDataAndUploadInBatch", "Starting batch upload with ${chunks.size} batches")
630
+ val batchSize = 40
631
+ val chunks = dataList.chunked(batchSize)
599
632
 
600
- CoroutineScope(Dispatchers.IO).launch {
601
- var lastSyncedRecord: PocGlucose? = null
602
- var allBatchesSuccessful = true
633
+ Log.d("getGlucoseDataAndUploadInBatch", "Starting batch upload with ${chunks.size} batches")
603
634
 
604
- for ((index, batch) in chunks.withIndex()) {
605
- try {
606
- val transformedLogs = batch.filter { it.showGlucoseMG > 0 }.map { pocGlucose ->
607
- CgmLog(
608
- timeInMillis = pocGlucose.timeInMillis,
609
- countdownMinutes = pocGlucose.countdownMinutes,
610
- countdownDays = pocGlucose.countdownDays,
611
- hypoglycemiaEarlyWarnMinutes = pocGlucose.hypoglycemiaEarlyWarnMinutes,
612
- showGlucoseMG = pocGlucose.showGlucoseMG,
613
- glucoseId = pocGlucose.glucoseId,
614
- name = pocGlucose.name,
615
- bytes = pocGlucose.bytes,
616
- showGlucose = pocGlucose.showGlucose,
617
- Ib = pocGlucose.ib,
618
- Iw = pocGlucose.iw,
619
- countdownHours = pocGlucose.countdownHours,
620
- T = pocGlucose.t,
621
- year = pocGlucose.year,
622
- month = pocGlucose.month,
623
- day = pocGlucose.day,
624
- hour = pocGlucose.hour,
625
- minute = pocGlucose.minute,
626
- trendObject = com.mytatvarnsdk.model.TrendObject(
627
- trendId = pocGlucose.trend.trendId,
628
- drawableId = pocGlucose.trend.drawableId,
629
- widgetImg = pocGlucose.trend.widgetImg,
630
- apsChangeRate = pocGlucose.trend.apsChangeRate
631
- ),
632
- glucoseStatusObject = com.mytatvarnsdk.model.GlucoseStatusObject(
633
- statusId = pocGlucose.glucoseStatus.statusId
634
- ),
635
- errorObject = com.mytatvarnsdk.model.ErrorObject(
636
- errorId = pocGlucose.errorCode.errorId,
637
- sound = pocGlucose.errorCode.sound
638
- )
639
- )
640
- }
635
+ CoroutineScope(Dispatchers.IO).launch {
636
+ var lastSyncedRecord: PocGlucose? = null
637
+ var allBatchesSuccessful = true
638
+
639
+ for ((index, batch) in chunks.withIndex()) {
640
+ try {
641
+ val transformedLogs = batch.filter { it.showGlucoseMG > 0 }.map { pocGlucose ->
642
+ CgmLog(
643
+ timeInMillis = pocGlucose.timeInMillis,
644
+ countdownMinutes = pocGlucose.countdownMinutes,
645
+ countdownDays = pocGlucose.countdownDays,
646
+ hypoglycemiaEarlyWarnMinutes = pocGlucose.hypoglycemiaEarlyWarnMinutes,
647
+ showGlucoseMG = pocGlucose.showGlucoseMG,
648
+ glucoseId = pocGlucose.glucoseId,
649
+ name = pocGlucose.name,
650
+ bytes = pocGlucose.bytes,
651
+ showGlucose = pocGlucose.showGlucose,
652
+ Ib = pocGlucose.ib,
653
+ Iw = pocGlucose.iw,
654
+ countdownHours = pocGlucose.countdownHours,
655
+ T = pocGlucose.t,
656
+ year = pocGlucose.year,
657
+ month = pocGlucose.month,
658
+ day = pocGlucose.day,
659
+ hour = pocGlucose.hour,
660
+ minute = pocGlucose.minute,
661
+ trendObject = com.mytatvarnsdk.model.TrendObject(
662
+ trendId = pocGlucose.trend.trendId,
663
+ drawableId = pocGlucose.trend.drawableId,
664
+ widgetImg = pocGlucose.trend.widgetImg,
665
+ apsChangeRate = pocGlucose.trend.apsChangeRate
666
+ ),
667
+ glucoseStatusObject = com.mytatvarnsdk.model.GlucoseStatusObject(
668
+ statusId = pocGlucose.glucoseStatus.statusId
669
+ ),
670
+ errorObject = com.mytatvarnsdk.model.ErrorObject(
671
+ errorId = pocGlucose.errorCode.errorId,
672
+ sound = pocGlucose.errorCode.sound
673
+ )
674
+ )
675
+ }
641
676
 
642
- if (transformedLogs.isEmpty()) {
643
- Log.d("Batch Upload", "Batch $index skipped - no valid glucose readings")
644
- continue
645
- }
677
+ if (transformedLogs.isEmpty()) {
678
+ Log.d("Batch Upload", "Batch $index skipped - no valid glucose readings")
679
+ continue
680
+ }
646
681
 
647
- val allResult = AllCGMLogRequest(vendor = "GoodFlip", logs = transformedLogs)
648
- val json = Gson().toJson(allResult)
682
+ val allResult = AllCGMLogRequest(vendor = "GoodFlip", logs = transformedLogs)
683
+ val json = Gson().toJson(allResult)
649
684
 
650
- Log.d("Batch Upload JSON", "Batch $index with ${transformedLogs.size} records")
651
- logLongJson("Batch $index JSON=>>> ", json)
685
+ Log.d("Batch Upload JSON", "Batch $index with ${transformedLogs.size} records")
686
+ logLongJson("Batch $index JSON=>>> ", json)
652
687
 
653
- val uploadSuccessful = uploadBatchSynchronously(json, index)
688
+ val uploadSuccessful = uploadBatchSynchronously(json, index)
654
689
 
655
- if (uploadSuccessful) {
656
- lastSyncedRecord = batch.lastOrNull()
657
- updateSyncMetadata(lastSyncedRecord)
658
- Log.d("Batch Upload", "✅ Batch $index uploaded successfully")
659
- } else {
660
- allBatchesSuccessful = false
661
- Log.e("Batch Upload", "❌ Batch $index failed, stopping further uploads")
662
- break
663
- }
690
+ if (uploadSuccessful) {
691
+ lastSyncedRecord = batch.lastOrNull()
692
+ updateSyncMetadata(lastSyncedRecord)
693
+ Log.d("Batch Upload", "✅ Batch $index uploaded successfully")
694
+ } else {
695
+ allBatchesSuccessful = false
696
+ Log.e("Batch Upload", "❌ Batch $index failed, stopping further uploads")
697
+ break
698
+ }
664
699
 
665
- delay(500L) // Rate limiting between batches
700
+ delay(500L) // Rate limiting between batches
666
701
 
667
- } catch (e: Exception) {
668
- Log.e("Batch Upload", "❌ Batch $index exception: ${e.message}")
669
- allBatchesSuccessful = false
670
- break
671
- }
672
- }
702
+ } catch (e: Exception) {
703
+ Log.e("Batch Upload", "❌ Batch $index exception: ${e.message}")
704
+ allBatchesSuccessful = false
705
+ break
706
+ }
707
+ }
673
708
 
674
- // Handle last synced record error status
675
- lastSyncedRecord?.let { record ->
676
- if (record.errorCode != enumError.NONE) {
677
- handleGlucoseError(record)
678
- }
679
- }
709
+ // Handle last synced record error status
710
+ lastSyncedRecord?.let { record ->
711
+ if (record.errorCode != enumError.NONE) {
712
+ handleGlucoseError(record)
713
+ }
714
+ }
680
715
 
681
- Log.d("Batch Upload", "Batch upload completed. Success: $allBatchesSuccessful")
716
+ Log.d("Batch Upload", "Batch upload completed. Success: $allBatchesSuccessful")
682
717
 
683
- // Only start observing new data if we're not already doing so
684
- if (!isObserving) {
685
- observeGlucoseData(userToken)
686
- }
718
+ // Only start observing new data if we're not already doing so
719
+ if (!isObserving) {
720
+ observeGlucoseData(userToken)
721
+ }
722
+ }
687
723
  }
688
- }
689
724
 
690
- // Helper method for synchronous batch upload
691
- private suspend fun uploadBatchSynchronously(json: String, batchIndex: Int): Boolean {
692
- return suspendCoroutine { continuation ->
693
- try {
694
- authenticateSDKService.postCGMData(
695
- environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
696
- data = json,
697
- token = userToken,
698
- responseListener = object : AuthenticateSDKService.ResponseListener {
699
- override fun onResponseSuccess(response: String) {
700
- continuation.resume(true)
725
+ // Helper method for synchronous batch upload
726
+ private suspend fun uploadBatchSynchronously(json: String, batchIndex: Int): Boolean {
727
+ return suspendCoroutine { continuation ->
728
+ try {
729
+ authenticateSDKService.postCGMData(
730
+ environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
731
+ data = json,
732
+ token = userToken,
733
+ responseListener = object : AuthenticateSDKService.ResponseListener {
734
+ override fun onResponseSuccess(response: String) {
735
+ continuation.resume(true)
736
+ }
737
+
738
+ override fun onResponseFail() {
739
+ continuation.resume(false)
740
+ }
741
+ }
742
+ )
743
+ } catch (e: Exception) {
744
+ Log.e("uploadBatchSynchronously", "Exception in batch $batchIndex: ${e.message}")
745
+ continuation.resume(false)
701
746
  }
747
+ }
748
+ }
702
749
 
703
- override fun onResponseFail() {
704
- continuation.resume(false)
750
+ private fun updateSyncMetadata(lastRecord: PocGlucose?) {
751
+ lastRecord?.let {
752
+ try {
753
+ val syncData = SyncMeta(
754
+ Date().time,
755
+ it.timeInMillis,
756
+ it.deviceId,
757
+ it.glucoseId
758
+ )
759
+ prefsHelper.lastSyncData = syncData
760
+ Log.d("Sync Metadata", "Last sync data stored: ${Gson().toJson(syncData)}")
761
+ } catch (e: Exception) {
762
+ Log.e("updateSyncMetadata", "Error updating sync metadata: ${e.message}")
705
763
  }
706
- }
707
- )
708
- } catch (e: Exception) {
709
- Log.e("uploadBatchSynchronously", "Exception in batch $batchIndex: ${e.message}")
710
- continuation.resume(false)
711
- }
764
+ }
712
765
  }
713
- }
714
766
 
715
- private fun updateSyncMetadata(lastRecord: PocGlucose?) {
716
- lastRecord?.let {
717
- try {
718
- val syncData = SyncMeta(
719
- Date().time,
720
- it.timeInMillis,
721
- it.deviceId,
722
- it.glucoseId
723
- )
724
- prefsHelper.lastSyncData = syncData
725
- Log.d("Sync Metadata", "Last sync data stored: ${Gson().toJson(syncData)}")
726
- } catch (e: Exception) {
727
- Log.e("updateSyncMetadata", "Error updating sync metadata: ${e.message}")
728
- }
729
- }
730
- }
731
-
732
- /*fun getGlucoseDataAndUploadInBatch(dataList: List<PocGlucose>) {
733
- if (dataList.isNotEmpty()) {
734
- val batchSize = 40
735
-
736
- val chunks = dataList.chunked(batchSize)
737
-
738
- CoroutineScope(Dispatchers.IO).launch {
739
-
740
- var lastSyncedRecord: PocGlucose? = null
741
-
742
- for ((index, batch) in chunks.withIndex()) {
743
- try {
744
- val transformedLogs = batch.filter { it.showGlucoseMG > 0 }.map {
745
- CgmLog(
746
- timeInMillis = it.timeInMillis,
747
- countdownMinutes = it.countdownMinutes,
748
- countdownDays = it.countdownDays,
749
- hypoglycemiaEarlyWarnMinutes = it.hypoglycemiaEarlyWarnMinutes,
750
- showGlucoseMG = it.showGlucoseMG,
751
- glucoseId = it.glucoseId,
752
- name = it.name,
753
- bytes = it.bytes,
754
- showGlucose = it.showGlucose,
755
- Ib = it.ib,
756
- Iw = it.iw,
757
- countdownHours = it.countdownHours,
758
- T = it.t,
759
- year = it.year,
760
- month = it.month,
761
- day = it.day,
762
- hour = it.hour,
763
- minute = it.minute,
764
- trendObject = com.mytatvarnsdk.model.TrendObject(
765
- trendId = it.trend.trendId,
766
- drawableId = it.trend.drawableId,
767
- widgetImg = it.trend.widgetImg,
768
- apsChangeRate = it.trend.apsChangeRate
769
- ),
770
- glucoseStatusObject = com.mytatvarnsdk.model.GlucoseStatusObject(
771
- statusId = it.glucoseStatus.statusId
772
- ),
773
- errorObject = com.mytatvarnsdk.model.ErrorObject(
774
- errorId = it.errorCode.errorId,
775
- sound = it.errorCode.sound
767
+ /*fun getGlucoseDataAndUploadInBatch(dataList: List<PocGlucose>) {
768
+ if (dataList.isNotEmpty()) {
769
+ val batchSize = 40
770
+
771
+ val chunks = dataList.chunked(batchSize)
772
+
773
+ CoroutineScope(Dispatchers.IO).launch {
774
+
775
+ var lastSyncedRecord: PocGlucose? = null
776
+
777
+ for ((index, batch) in chunks.withIndex()) {
778
+ try {
779
+ val transformedLogs = batch.filter { it.showGlucoseMG > 0 }.map {
780
+ CgmLog(
781
+ timeInMillis = it.timeInMillis,
782
+ countdownMinutes = it.countdownMinutes,
783
+ countdownDays = it.countdownDays,
784
+ hypoglycemiaEarlyWarnMinutes = it.hypoglycemiaEarlyWarnMinutes,
785
+ showGlucoseMG = it.showGlucoseMG,
786
+ glucoseId = it.glucoseId,
787
+ name = it.name,
788
+ bytes = it.bytes,
789
+ showGlucose = it.showGlucose,
790
+ Ib = it.ib,
791
+ Iw = it.iw,
792
+ countdownHours = it.countdownHours,
793
+ T = it.t,
794
+ year = it.year,
795
+ month = it.month,
796
+ day = it.day,
797
+ hour = it.hour,
798
+ minute = it.minute,
799
+ trendObject = com.mytatvarnsdk.model.TrendObject(
800
+ trendId = it.trend.trendId,
801
+ drawableId = it.trend.drawableId,
802
+ widgetImg = it.trend.widgetImg,
803
+ apsChangeRate = it.trend.apsChangeRate
804
+ ),
805
+ glucoseStatusObject = com.mytatvarnsdk.model.GlucoseStatusObject(
806
+ statusId = it.glucoseStatus.statusId
807
+ ),
808
+ errorObject = com.mytatvarnsdk.model.ErrorObject(
809
+ errorId = it.errorCode.errorId,
810
+ sound = it.errorCode.sound
811
+ )
776
812
  )
777
- )
778
- }
813
+ }
779
814
 
780
- val allResult = AllCGMLogRequest(
781
- vendor = "GoodFlip",
782
- logs = transformedLogs
783
- )
815
+ val allResult = AllCGMLogRequest(
816
+ vendor = "GoodFlip",
817
+ logs = transformedLogs
818
+ )
784
819
 
785
- val json = Gson().toJson(allResult)
786
- logLongJson("Final JSON=>>> ", json)
787
-
788
- // sendDataToReact(Gson().toJson(batch).toString(), "DATA_FETCH", "CGMData")
789
-
790
- authenticateSDKService.postCGMData(
791
- environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
792
- data = json.toString(),
793
- token = userToken,
794
- responseListener = object : AuthenticateSDKService.ResponseListener {
795
- override fun onResponseSuccess() {
796
- lastSyncedRecord = batch.lastOrNull()
797
-
798
- lastSyncedRecord?.let {
799
- val syncData =
800
- SyncMeta(
801
- Date().time,
802
- it.timeInMillis,
803
- it.deviceId,
804
- it.glucoseId
820
+ val json = Gson().toJson(allResult)
821
+ logLongJson("Final JSON=>>> ", json)
822
+
823
+ // sendDataToReact(Gson().toJson(batch).toString(), "DATA_FETCH", "CGMData")
824
+
825
+ authenticateSDKService.postCGMData(
826
+ environment = if ("uat".uppercase() == "PROD") TATVA_ENVIRONMENT.PROD else TATVA_ENVIRONMENT.STAGE,
827
+ data = json.toString(),
828
+ token = userToken,
829
+ responseListener = object : AuthenticateSDKService.ResponseListener {
830
+ override fun onResponseSuccess() {
831
+ lastSyncedRecord = batch.lastOrNull()
832
+
833
+ lastSyncedRecord?.let {
834
+ val syncData =
835
+ SyncMeta(
836
+ Date().time,
837
+ it.timeInMillis,
838
+ it.deviceId,
839
+ it.glucoseId
840
+ )
841
+ prefsHelper.lastSyncData = syncData
842
+ Log.d(
843
+ "lastSyncedRecord stored:--- ",
844
+ Gson().toJson(syncData).toString()
805
845
  )
806
- prefsHelper.lastSyncData = syncData
807
- Log.d(
808
- "lastSyncedRecord stored:--- ",
809
- Gson().toJson(syncData).toString()
810
- )
846
+ }
811
847
  }
812
- }
813
848
 
814
- override fun onResponseFail() {
815
- Log.e("Batch Upload", "❌ Batch $index failed")
849
+ override fun onResponseFail() {
850
+ Log.e("Batch Upload", "❌ Batch $index failed")
851
+ }
816
852
  }
817
- }
818
- )
853
+ )
819
854
 
820
- delay(500L)
821
- } catch (e: Exception) {
822
- Log.e("Batch Upload", "❌ Batch $index exception: ${e.message}")
823
- break // Optional: stop further processing if exception occurs
855
+ delay(500L)
856
+ } catch (e: Exception) {
857
+ Log.e("Batch Upload", "❌ Batch $index exception: ${e.message}")
858
+ break // Optional: stop further processing if exception occurs
859
+ }
824
860
  }
825
- }
826
861
 
827
862
 
828
- if (lastSyncedRecord != null) {
829
- if (lastSyncedRecord?.errorCode != enumError.NONE) {
830
- if (lastSyncedRecord?.errorCode == enumError.ERROR_FLOODING_WATER) {
831
- lastDeviceStatus =
832
- lastSyncedRecord?.deviceId!!.toInt().let { mModel.getDeviceInfo(it) }
833
- lastDeviceStatus?.let {
834
- postEventDataToAPI(
835
- it,
836
- DeviceStatus.MOISTURE_DETECT.id
837
- )
838
- }
839
- resetDebounceTimer()
840
- } else if (lastSyncedRecord?.errorCode == enumError.ERROR_CURRENT_SMALL || lastSyncedRecord?.errorCode == enumError.ERROR_NOISE || lastSyncedRecord?.errorCode == enumError.ERROR_SENSITIVITY_ATTENUATION) {
841
- lastDeviceStatus =
842
- lastSyncedRecord?.deviceId!!.toInt().let { mModel.getDeviceInfo(it) }
843
- lastDeviceStatus?.let {
844
- postEventDataToAPI(
845
- it,
846
- DeviceStatus.WEAK_SIGNAL.id
847
- )
848
- }
849
- resetDebounceTimer()
850
- } else {
851
- lastDeviceStatus =
852
- lastSyncedRecord?.deviceId!!.toInt().let { mModel.getDeviceInfo(it) }
853
- lastDeviceStatus?.let {
854
- postEventDataToAPI(
855
- it,
856
- DeviceStatus.ERROR_COMMON.id
857
- )
863
+ if (lastSyncedRecord != null) {
864
+ if (lastSyncedRecord?.errorCode != enumError.NONE) {
865
+ if (lastSyncedRecord?.errorCode == enumError.ERROR_FLOODING_WATER) {
866
+ lastDeviceStatus =
867
+ lastSyncedRecord?.deviceId!!.toInt().let { mModel.getDeviceInfo(it) }
868
+ lastDeviceStatus?.let {
869
+ postEventDataToAPI(
870
+ it,
871
+ DeviceStatus.MOISTURE_DETECT.id
872
+ )
873
+ }
874
+ resetDebounceTimer()
875
+ } else if (lastSyncedRecord?.errorCode == enumError.ERROR_CURRENT_SMALL || lastSyncedRecord?.errorCode == enumError.ERROR_NOISE || lastSyncedRecord?.errorCode == enumError.ERROR_SENSITIVITY_ATTENUATION) {
876
+ lastDeviceStatus =
877
+ lastSyncedRecord?.deviceId!!.toInt().let { mModel.getDeviceInfo(it) }
878
+ lastDeviceStatus?.let {
879
+ postEventDataToAPI(
880
+ it,
881
+ DeviceStatus.WEAK_SIGNAL.id
882
+ )
883
+ }
884
+ resetDebounceTimer()
885
+ } else {
886
+ lastDeviceStatus =
887
+ lastSyncedRecord?.deviceId!!.toInt().let { mModel.getDeviceInfo(it) }
888
+ lastDeviceStatus?.let {
889
+ postEventDataToAPI(
890
+ it,
891
+ DeviceStatus.ERROR_COMMON.id
892
+ )
893
+ }
894
+ resetDebounceTimer()
858
895
  }
859
- resetDebounceTimer()
860
896
  }
861
897
  }
862
- }
863
898
 
864
- Log.e("Batch Upload", "All data uploaded")
899
+ Log.e("Batch Upload", "All data uploaded")
865
900
 
901
+ observeGlucoseData(userToken)
902
+ }
903
+ } else {
866
904
  observeGlucoseData(userToken)
867
905
  }
868
- } else {
869
- observeGlucoseData(userToken)
870
- }
871
- }*/
872
-
873
- fun logLongJson(tag: String, message: String) {
874
- val maxLogSize = 4000
875
- for (i in 0..message.length / maxLogSize) {
876
- val start = i * maxLogSize
877
- val end = (i + 1) * maxLogSize
878
- if (start < message.length) {
879
- Log.d(tag, message.substring(start, minOf(end, message.length)))
880
- }
906
+ }*/
907
+
908
+ fun logLongJson(tag: String, message: String) {
909
+ val maxLogSize = 4000
910
+ for (i in 0..message.length / maxLogSize) {
911
+ val start = i * maxLogSize
912
+ val end = (i + 1) * maxLogSize
913
+ if (start < message.length) {
914
+ Log.d(tag, message.substring(start, minOf(end, message.length)))
915
+ }
916
+ }
881
917
  }
882
- }
883
-
884
- fun mapToDto(glucose: PocGlucose): GlucoseLog {
885
- val dto: GlucoseLog = GlucoseLog()
886
- dto.timeInMillis = glucose.getTimeInMillis()
887
- dto.countdownMinutes = glucose.getCountdownMinutes()
888
- dto.countdownHours = glucose.getCountdownHours()
889
- dto.countdownDays = glucose.getCountdownDays()
890
- dto.hypoglycemiaEarlyWarnMinutes = glucose.getHypoglycemiaEarlyWarnMinutes()
891
- dto.showGlucoseMG = glucose.getShowGlucoseMG()
892
- dto.glucoseId = glucose.getGlucoseId()
893
- dto.name = glucose.getName()
894
- dto.showGlucose = glucose.getShowGlucose()
895
- dto.Ib = glucose.getIb()
896
- dto.Iw = glucose.getIw()
897
- dto.T = glucose.getT()
898
- dto.year = glucose.getYear()
899
- dto.month = glucose.getMonth()
900
- dto.day = glucose.getDay()
901
- dto.hour = glucose.getHour()
902
- dto.minute = glucose.getMinute()
903
-
904
- // Convert byte[] to List<Integer>
905
- dto.bytes = ArrayList()
906
- for (b in glucose.getBytes()) {
907
- dto.bytes?.add(b.toInt() and 0xFF) // Prevent negative values
918
+
919
+ fun mapToDto(glucose: PocGlucose): GlucoseLog {
920
+ val dto: GlucoseLog = GlucoseLog()
921
+ dto.timeInMillis = glucose.getTimeInMillis()
922
+ dto.countdownMinutes = glucose.getCountdownMinutes()
923
+ dto.countdownHours = glucose.getCountdownHours()
924
+ dto.countdownDays = glucose.getCountdownDays()
925
+ dto.hypoglycemiaEarlyWarnMinutes = glucose.getHypoglycemiaEarlyWarnMinutes()
926
+ dto.showGlucoseMG = glucose.getShowGlucoseMG()
927
+ dto.glucoseId = glucose.getGlucoseId()
928
+ dto.name = glucose.getName()
929
+ dto.showGlucose = glucose.getShowGlucose()
930
+ dto.Ib = glucose.getIb()
931
+ dto.Iw = glucose.getIw()
932
+ dto.T = glucose.getT()
933
+ dto.year = glucose.getYear()
934
+ dto.month = glucose.getMonth()
935
+ dto.day = glucose.getDay()
936
+ dto.hour = glucose.getHour()
937
+ dto.minute = glucose.getMinute()
938
+
939
+ // Convert byte[] to List<Integer>
940
+ dto.bytes = ArrayList()
941
+ for (b in glucose.getBytes()) {
942
+ dto.bytes?.add(b.toInt() and 0xFF) // Prevent negative values
943
+ }
944
+
945
+ // Trend
946
+ val trendObj: TrendObject = TrendObject()
947
+ trendObj.trendId = glucose.getTrend().getTrendId()
948
+ trendObj.drawableId = glucose.getTrend().getDrawableId()
949
+ trendObj.widgetImg = glucose.getTrend().getWidgetImg()
950
+ trendObj.apsChangeRate = glucose.getTrend().getApsChangeRate()
951
+ dto.trendObject = trendObj
952
+
953
+ // Status
954
+ val statusObj: GlucoseStatusObject = GlucoseStatusObject()
955
+ statusObj.statusId = glucose.getGlucoseStatus().getStatusId()
956
+ dto.glucoseStatusObject = statusObj
957
+
958
+ // Error
959
+ val errorObj: ErrorObject = ErrorObject()
960
+ errorObj.errorId = glucose.getErrorCode().getErrorId()
961
+ errorObj.sound = glucose.getErrorCode().getSound().toString()
962
+ dto.errorObject = errorObj
963
+
964
+ return dto
908
965
  }
909
966
 
910
- // Trend
911
- val trendObj: TrendObject = TrendObject()
912
- trendObj.trendId = glucose.getTrend().getTrendId()
913
- trendObj.drawableId = glucose.getTrend().getDrawableId()
914
- trendObj.widgetImg = glucose.getTrend().getWidgetImg()
915
- trendObj.apsChangeRate = glucose.getTrend().getApsChangeRate()
916
- dto.trendObject = trendObj
917
-
918
- // Status
919
- val statusObj: GlucoseStatusObject = GlucoseStatusObject()
920
- statusObj.statusId = glucose.getGlucoseStatus().getStatusId()
921
- dto.glucoseStatusObject = statusObj
922
-
923
- // Error
924
- val errorObj: ErrorObject = ErrorObject()
925
- errorObj.errorId = glucose.getErrorCode().getErrorId()
926
- errorObj.sound = glucose.getErrorCode().getSound().toString()
927
- dto.errorObject = errorObj
928
-
929
- return dto
930
- }
931
-
932
-
933
- @ReactMethod
934
- fun sendDataToReact(data: String, status: String, eventName: String) {
935
- Log.d("sendDataToReact: data ", data)
936
-
937
- try {
938
- val map: WritableMap = Arguments.createMap().apply {
939
- putString("data", data)
940
- putString("status", status)
941
- }
942
967
 
943
- Log.d("sendDataToReact: ", map.toString())
968
+ @ReactMethod
969
+ fun sendDataToReact(data: String, status: String, eventName: String) {
970
+ Log.d("sendDataToReact: data ", data)
971
+
972
+ try {
973
+ val map: WritableMap = Arguments.createMap().apply {
974
+ putString("data", data)
975
+ putString("status", status)
976
+ }
944
977
 
945
- mReactContext?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
946
- ?.emit(eventName, map)
947
- } catch (e: Exception) {
948
- Log.e("Error sendDataToReact: ", e.message.toString())
949
- e.printStackTrace()
978
+ Log.d("sendDataToReact: ", map.toString())
979
+
980
+ mReactContext?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
981
+ ?.emit(eventName, map)
982
+ } catch (e: Exception) {
983
+ Log.e("Error sendDataToReact: ", e.message.toString())
984
+ e.printStackTrace()
985
+ }
950
986
  }
951
- }
952
987
 
953
988
  }
989
+