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