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

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