Device provision fetching code is added

This commit is contained in:
Mariya
2024-02-12 13:56:05 +05:30
parent 7f47e1dff8
commit 9314b155cd
4 changed files with 61 additions and 79 deletions

View File

@@ -8,7 +8,7 @@ import com.example.hpostesting.data.model.patient.DeviceData
import com.example.hpostesting.data.model.patient.HemoCubeTestData
import com.example.hpostesting.data.model.patient.UserData
@Database(entities = [UserData::class, HemoCubeTestData::class, DeviceData::class, BufferCheckData::class], version = 24, exportSchema = false)
@Database(entities = [UserData::class, HemoCubeTestData::class, DeviceData::class, BufferCheckData::class], version = 25, exportSchema = false)
@TypeConverters(Converters::class)
abstract class MyDatabase : RoomDatabase() {
abstract fun userDao(): UserDao

View File

@@ -19,9 +19,13 @@ import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.hpostesting.data.Result
import com.example.hpostesting.data.api.DeviceCommunicationHandler
import com.example.hpostesting.data.constant.HemoCubeCommands
import com.example.hpostesting.data.constant.LanguageManager
import com.example.hpostesting.presentation.NatsManager
import com.example.hpostesting.presentation.UsbServiceListener
import com.example.hpostesting.presentation.hemocube.HemoCubeViewModel
import com.example.hpostesting.presentation.testRight.UsbService
import com.google.android.material.navigation.NavigationView
import com.google.firebase.appdistribution.FirebaseAppDistribution
import com.google.firebase.appdistribution.FirebaseAppDistributionException

View File

@@ -1,7 +1,6 @@
package com.example.hpostesting.presentation.dashboard
import android.app.AlertDialog
import android.content.ContentValues.TAG
import android.content.Context
import android.content.Context.BATTERY_SERVICE
import android.content.DialogInterface
@@ -23,7 +22,6 @@ import com.example.hpostesting.data.Result
import com.example.hpostesting.data.api.DeviceCommunicationHandler
import com.example.hpostesting.data.constant.Constants
import com.example.hpostesting.data.constant.HemoCubeCommands
import com.example.hpostesting.data.model.deviceprovision.ProvisionData
import com.example.hpostesting.data.model.login.LoginRequest
import com.example.hpostesting.data.model.login.LoginResponse
import com.example.hpostesting.data.model.molbioresult.MolbioV2Result
@@ -41,18 +39,14 @@ import com.example.hpostesting.presentation.assurance.AssuranceControlsActivity
import com.example.hpostesting.presentation.hemocube.HemoCubeViewModel
import com.example.hpostesting.presentation.testRight.TestRightViewModel
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.common.reflect.TypeToken
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.google.firebase.perf.ktx.performance
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import dagger.hilt.android.AndroidEntryPoint
import `in`.sminnovations.hpostesting.R
import `in`.sminnovations.hpostesting.databinding.FragmentHomeBinding
import org.json.JSONException
import org.json.JSONObject
import java.nio.charset.Charset
import java.text.SimpleDateFormat
@@ -73,8 +67,6 @@ class HomeFragment : Fragment() {
private val homeViewModel: HemoCubeViewModel by activityViewModels()
private var isTokenAvailable = false
private var username: String = ""
private var passworD: String = ""
private var natsToken: String = ""
private var deviceId: String = ""
@@ -105,7 +97,7 @@ class HomeFragment : Fragment() {
binding.labelQuickCapture.visibility = View.VISIBLE
binding.btnQuickCapture.visibility = View.VISIBLE
}
getDeviceId()
checkUnprocessedCSVData()
viewModel.allUserData.observe(viewLifecycleOwner) { userData ->
deleteIncompleteRegistrations(userData)
@@ -140,7 +132,6 @@ class HomeFragment : Fragment() {
loadUserData()
setSearch()
checkForLocalDBData()
getDeviceId()
checkForTokenAndUpdate()
} else {
binding.internetAvailableCL.visibility = View.GONE
@@ -234,11 +225,21 @@ class HomeFragment : Fragment() {
}
}
}else if (deviceId.isNotEmpty()) {
fetchDeviceProvisionResponse()
userID = username
password = passworD
hemoCubeViewModel.login(createLoginRequestData(userID, password))
} else {
fetchDeviceCredentials()
// This code will execute after credentials have been successfully fetched and stored.
userID = sharedPreference.getString("username", "").toString()
password = sharedPreference.getString("password", "").toString()
accessToken = sharedPreference.getString(Constants.ACCESS_TOKEN, "").toString()
if (accessToken.isEmpty()) {
hemoCubeViewModel.login(createLoginRequestData(userID, password))
} else {
// Continue with your existing logic if the token is not empty.
isTokenAvailable = true
hemoCubeViewModel.deviceUpdate(createDeviceUpdateRequestData())
hemoCubeViewModel.uploadLogs()
hemoCubeViewModel.startPeriodicCheckUpdate()
}
} else {
Toast.makeText(
requireContext(),
"Contact Help and get your device provision done",
@@ -400,75 +401,45 @@ class HomeFragment : Fragment() {
}
private fun fetchDeviceProvisionResponse() {
val db = Firebase.firestore
val deviceId = sharedPreference.getString(Constants.DEVICE_ID, "").toString()
val deviceRef = db.collection("devices").document(deviceId)
private fun fetchDeviceCredentials() {
try {
val db = Firebase.firestore
// Ensure deviceId is not null or empty
val deviceId = sharedPreference.getString(Constants.DEVICE_ID, "").takeIf { it!!.isNotBlank() }
?: throw IllegalStateException("Device ID is missing or blank.")
val deviceRef = db.collection("devices").whereEqualTo("deviceId", deviceId)
deviceRef.get()
.addOnSuccessListener { document ->
if (document.exists()) {
val deviceData = document.toObject(DeviceData::class.java)
val deviceProvisionResponse = deviceData?.deviceProvisionResponse
// Parse the deviceProvisionResponse to extract username, password, natsToken
val provisionData = deviceProvisionResponse?.let {
parseDeviceProvisionResponse(
it
)
deviceRef.get()
.addOnSuccessListener { documentSnapshot ->
if (!documentSnapshot.isEmpty) {
val deviceData = documentSnapshot.documents[0].toObject(DeviceData::class.java)
deviceData?.let { data ->
val username = data.username
val password = data.password
// Log for debugging
Log.d("fetchDeviceCredentials", "Username: $username, Password: $password")
// Save credentials in SharedPreferences
with(sharedPreference.edit()) {
putString("username", username)
putString("password", password)
apply()
}
hemoCubeViewModel.login(createLoginRequestData(username, password))
} ?: Log.e("fetchDeviceCredentials", "Failed to parse device data.")
} else {
Log.e("fetchDeviceCredentials", "Document does not exist.")
}
provisionData?.let { data ->
// Assuming 'data' has the fields 'username', 'password', and 'natsToken'
username = data.username.toString()
passworD = data.password.toString()
natsToken = data.natsToken.toString()
// Assuming 'sharedPreference' is correctly initialized SharedPreferences instance
with(sharedPreference.edit()) {
putString(
"username",
username
) // Replace "username_key" with your actual key for username
putString(
"password",
passworD
) // Replace "password_key" with your actual key for password
putString(
"natsToken",
natsToken
) // Replace "natsToken_key" with your actual key for NATS token
apply() // Don't forget to call apply() to save the changes
}
}
} else {
// Handle the case where the device document doesn't exist
}
}
.addOnFailureListener { exception ->
// Handle any errors
Log.e(TAG, "Error fetching device data: $exception")
}
}
private fun parseDeviceProvisionResponse(responseString: String): ProvisionData? {
return try {
val jsonObject = JSONObject(responseString)
val credentials = jsonObject.getJSONObject("credentials")
val username = credentials.getString("username")
val password = credentials.getString("password")
val deviceUser = jsonObject.getJSONObject("device").getJSONObject("deviceUser")
val natsToken = deviceUser.getString("natsToken")
ProvisionData(username, password, natsToken)
} catch (e: JSONException) {
null
.addOnFailureListener { exception ->
Log.e("fetchDeviceCredentials", "Error fetching device data", exception)
}
} catch (e: Exception) {
Log.e("fetchDeviceCredentials", "Error in fetchDeviceCredentials", e)
}
}
private fun loadUserData() {
try {
val dateFormat = SimpleDateFormat("yyyy-MM-dd")

View File

@@ -22,8 +22,11 @@ import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.view.get
import com.example.hpostesting.data.DataHolder
import com.example.hpostesting.data.api.DeviceCommunicationHandler
import com.example.hpostesting.data.constant.Constants
import com.example.hpostesting.data.constant.HemoCubeCommands
import com.example.hpostesting.data.constant.LanguageManager
import com.example.hpostesting.presentation.UsbServiceListener
import com.example.hpostesting.presentation.testRight.UsbService
import com.hoho.android.usbserial.driver.UsbSerialDriver
import com.hoho.android.usbserial.driver.UsbSerialProber
@@ -33,7 +36,7 @@ import `in`.sminnovations.hpostesting.databinding.ActivityDeviceBinding
@Suppress("MemberVisibilityCanBePrivate")
@AndroidEntryPoint
class DeviceActivity : AppCompatActivity() {
class DeviceActivity : AppCompatActivity(), DeviceCommunicationHandler {
private lateinit var binding: ActivityDeviceBinding
private val deviceViewModel by viewModels<DeviceViewModel>()
private var myMenu: Menu? = null
@@ -177,4 +180,8 @@ class DeviceActivity : AppCompatActivity() {
deviceViewModel.isServiceConnected = false
}
}
override fun sendAndListenToDevice(command: HemoCubeCommands, listener: UsbServiceListener) {
mService.sendAndListenToHemoCube(command = HemoCubeCommands.DEVICE_CONFIGURATION_COMMAND, listener)
}
}