From 96ba5ce92fbdaead9e1e6585eabb88293fcdb6ad Mon Sep 17 00:00:00 2001 From: chandrashekhar reddy Date: Thu, 28 Mar 2024 16:32:21 +0530 Subject: [PATCH] HomeFragment network change edited --- .../presentation/dashboard/HomeFragment.kt | 39 ++-- .../dashboard/ui/LoginFragment.kt | 219 +++++++++++------- .../presentation/hemocube/HemoCubeFragment.kt | 8 +- .../res/navigation/dashboard_navigation.xml | 2 +- 4 files changed, 160 insertions(+), 108 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt index b8c0ce2..ec62c4f 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/HomeFragment.kt @@ -13,7 +13,6 @@ package com.example.hpostesting.presentation.dashboard -import android.Manifest import android.annotation.SuppressLint import android.app.AlertDialog import android.app.DownloadManager @@ -25,10 +24,6 @@ import android.content.DialogInterface import android.content.Intent import android.content.IntentFilter import android.content.SharedPreferences -import android.content.pm.PackageManager -import android.location.Location -import android.location.LocationListener -import android.location.LocationManager import android.net.Uri import android.os.BatteryManager import android.os.Build @@ -42,20 +37,15 @@ import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.RequiresApi -import androidx.core.app.ActivityCompat import androidx.core.content.FileProvider import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController -import com.example.hpostesting.data.constant.DataHolder -import com.example.hpostesting.util.Result -import com.example.hpostesting.presentation.utils.DeviceCommunicationHandler import com.example.hpostesting.data.constant.Constants +import com.example.hpostesting.data.constant.DataHolder import com.example.hpostesting.data.constant.HemoCubeCommands import com.example.hpostesting.data.model.login.LoginRequest import com.example.hpostesting.data.model.login.LoginResponse -import com.example.hpostesting.data.model.molbioresult.MolbioV2Result -import com.example.hpostesting.data.model.molbioresult.MolbioV2ResultRequest import com.example.hpostesting.data.model.patient.DeviceData import com.example.hpostesting.data.model.patient.HemoCubeTestData import com.example.hpostesting.data.model.patient.UserData @@ -63,12 +53,14 @@ import com.example.hpostesting.data.model.updates.CheckUpdateRequest import com.example.hpostesting.data.model.updates.DeviceUpdateRequest import com.example.hpostesting.encryption.Encryption import com.example.hpostesting.presentation.KitScanActivity -import com.example.hpostesting.presentation.utils.UsbServiceListener import com.example.hpostesting.presentation.adapter.OfflineUserListAdapter import com.example.hpostesting.presentation.adapter.UserListAdapter import com.example.hpostesting.presentation.assurance.AssuranceControlsActivity import com.example.hpostesting.presentation.hemocube.HemoCubeViewModel import com.example.hpostesting.presentation.testRight.TestRightViewModel +import com.example.hpostesting.presentation.utils.DeviceCommunicationHandler +import com.example.hpostesting.presentation.utils.UsbServiceListener +import com.example.hpostesting.util.Result import com.firebase.ui.firestore.FirestoreRecyclerOptions import com.google.firebase.crashlytics.ktx.crashlytics import com.google.firebase.firestore.Query @@ -78,7 +70,6 @@ import com.google.firebase.perf.ktx.performance import dagger.hilt.android.AndroidEntryPoint import `in`.sminnovations.hpostesting.R import `in`.sminnovations.hpostesting.databinding.FragmentHomeBinding -import kotlinx.coroutines.tasks.await import okhttp3.ResponseBody import org.json.JSONObject import java.io.BufferedOutputStream @@ -252,6 +243,7 @@ class HomeFragment : Fragment() { @RequiresApi(Build.VERSION_CODES.P) private fun checkNetworkStatus() { hemoCubeViewModel.networkStatusLiveData.observe(viewLifecycleOwner) { isConnected -> + // Toast.makeText(requireContext(),"connected"+isConnected+wasConnected, Toast.LENGTH_SHORT).show() if (isConnected != wasConnected) { if (isConnected) { binding.internetAvailableCL.visibility = View.VISIBLE @@ -338,6 +330,13 @@ class HomeFragment : Fragment() { setUserId() } wasConnected = isConnected + }else{ + if(!wasConnected){ + binding.internetAvailableCL.visibility = View.GONE + binding.pendingTest.visibility = View.GONE + binding.internetNotAvailableCL.visibility = View.VISIBLE + setUserId() + } } } } @@ -378,11 +377,11 @@ class HomeFragment : Fragment() { val encryptedString = file.readText() val encryptionKey = Settings.Secure.getString(context?.contentResolver, Settings.Secure.ANDROID_ID) - val decryptedMessage: String = Encryption.decrypt(encryptedString, encryptionKey) - val credentials = decryptedMessage.split("\n") - userID = credentials[0] - password = credentials[1] - Toast.makeText(context, "DECRYPTED: $credentials", Toast.LENGTH_SHORT).show() + // val decryptedMessage: String = Encryption.decrypt(encryptedString, encryptionKey) + // val credentials = decryptedMessage.split("\n") + // userID = credentials[0] + // password = credentials[1] + // Toast.makeText(context, "DECRYPTED: $credentials", Toast.LENGTH_SHORT).show() if (!isTokenAvailable) { hemoCubeViewModel.login(createLoginRequestData(userID, password)) } @@ -647,9 +646,9 @@ class HomeFragment : Fragment() { val version = pInfo.versionName var labname = sharedPreference.getString(Constants.LABNAME,"") return LoginRequest( - password = password, serialNumber = userID, username = userID, version = version, lab = labname,latitude = DataHolder.location!!.latitude.toString(), longitude = DataHolder.location!!.longitude.toString(), location = DataHolder.location.toString() + password = password, serialNumber = userID, username = userID, version = version, lab = labname ) - } + }//latitude = DataHolder.location!!.latitude.toString(), longitude = DataHolder.location!!.longitude.toString(), location = DataHolder.location.toString() private fun createCheckUpdateRequestData(): CheckUpdateRequest { val pInfo = requireActivity().packageManager.getPackageInfo( diff --git a/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt index 39081b3..a0dc629 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/dashboard/ui/LoginFragment.kt @@ -13,37 +13,41 @@ package com.example.hpostesting.presentation.dashboard.ui -import android.Manifest import android.annotation.SuppressLint import android.content.Context +import android.content.Context.WIFI_SERVICE import android.content.SharedPreferences -import android.content.pm.PackageManager import android.location.Location import android.location.LocationListener import android.location.LocationManager +import android.net.ConnectivityManager +import android.net.wifi.WifiManager import android.os.Build import android.os.Bundle +import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.RequiresApi -import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat.getSystemService import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.example.hpostesting.data.constant.Constants -import com.example.hpostesting.data.constant.DataHolder -import com.example.hpostesting.data.model.patient.UserData import `in`.sminnovations.hpostesting.R import `in`.sminnovations.hpostesting.databinding.FragmentLoginBinding -import kotlin.properties.Delegates +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import java.net.HttpURLConnection +import java.net.URL +import java.util.Scanner + class LoginFragment : Fragment() { - private lateinit var locationManager: LocationManager - var latitude by Delegates.notNull() - var longitude by Delegates.notNull() - private var locationListener: LocationListener? = null - + var latitude = 0.0 + var longitude = 0.0 + var TAG = "LoginFragmentCheck" private var _binding: FragmentLoginBinding? = null private val binding get() = _binding!! private lateinit var sharedPreference: SharedPreferences @@ -57,44 +61,12 @@ class LoginFragment : Fragment() { return binding.root } + @RequiresApi(Build.VERSION_CODES.M) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - locationManager = - requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager - locationListener = MyLocationListener() init() - // Check for permissions - if (ActivityCompat.checkSelfPermission( - requireContext(), - Manifest.permission.ACCESS_FINE_LOCATION - ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( - requireContext(), - Manifest.permission.ACCESS_COARSE_LOCATION - ) != PackageManager.PERMISSION_GRANTED - ) { - // Request permissions if not granted - ActivityCompat.requestPermissions( - requireActivity(), - arrayOf( - Manifest.permission.ACCESS_FINE_LOCATION, - Manifest.permission.ACCESS_COARSE_LOCATION - ), - 123 - ) - return - } - - // Request location updates using NETWORK_PROVIDER - locationManager.requestLocationUpdates( - LocationManager.NETWORK_PROVIDER, - 0, - 0f, - locationListener as LocationListener - ) - - + checkLocation() } - private fun init() { if (isUserLoggedIn()) { navigateToHomeFragment() @@ -102,6 +74,8 @@ class LoginFragment : Fragment() { } binding.btnLogin.setOnClickListener { + // Toast.makeText(requireContext(), "$latitude/$longitude",Toast.LENGTH_SHORT).show() + val loginId = binding.loginId.text.toString() val password = binding.password.text.toString() @@ -150,48 +124,127 @@ class LoginFragment : Fragment() { override fun onDestroyView() { super.onDestroyView() _binding = null - locationManager.removeUpdates(locationListener as LocationListener) } + + /** Check if we can get our location */ @SuppressLint("MissingPermission") - override fun onRequestPermissionsResult( - requestCode: Int, - permissions: Array, - grantResults: IntArray - ) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults) - if (requestCode == 123) { - if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - // Permission granted, request location updates again - locationManager.requestLocationUpdates( - LocationManager.NETWORK_PROVIDER, - 0, - 0f, - locationListener as LocationListener - ) + fun checkLocation() { + // Get the location manager + val locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager + val locationProviderWifi = LocationManager.NETWORK_PROVIDER + val locationProviderGPS = LocationManager.GPS_PROVIDER + val locationListenerNetwork: LocationListener + val locationListenerGPS: LocationListener + var gps_enabled = false + var network_enabled = false + + //check wifi + val connectivityManager = requireActivity().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + val mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) + if (mWifi!!.isConnected) { + Log.d(TAG, "Wifi connected") + } + + //check gps and wifi availability + try { + gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) + } catch (ex: Exception) { + } + try { + network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) + } catch (ex: Exception) { + } + if (!gps_enabled) { + Log.d(TAG, "GPS: Missing") + }else{ +// getPublicIpAddr { ipAddress -> +// // Do something with the ipAddress +// Log.d(TAG, "GPS: PRESENT"+ipAddress) +// } + } + if (!network_enabled) { + Log.d(TAG, "Network: Missing") + } + + /* Location change listeners */try { + Log.d(TAG, "GPS: PRESENT TRy") + // Define a listener that responds to gps location updates + locationListenerGPS = object : LocationListener { + override fun onLocationChanged(location: Location) { + Log.d(TAG, "GPS: PRESENT loc") + Log.d( + TAG, + "GPS: Latitude: " + location.latitude + ", Longitude = " + location.longitude + ) + } + + override fun onStatusChanged(provider: String, status: Int, extras: Bundle) { + Log.d(TAG, "GP location found 1") + } + + override fun onProviderEnabled(provider: String) { + Log.d(TAG, "GP location found 2") + } + + override fun onProviderDisabled(provider: String) { + Log.d(TAG, "GP location found 3") + } } + locationManager.requestLocationUpdates(locationProviderGPS, 0, 0f, locationListenerGPS) + Log.d(TAG, "GPS: PRESENT Req") + } catch (e: Exception) { + Log.e(TAG, "Location Exception: " + e.message) + } + try { + // Define a listener that responds to wifi location updates + locationListenerNetwork = object : LocationListener { + override fun onLocationChanged(location: Location) { + Log.d( + TAG, + "NW: Latitude: " + location.latitude + ", Longitude = " + location.longitude + ) + } + + override fun onStatusChanged(provider: String, status: Int, extras: Bundle) { + Log.d(TAG, "location found 1") + } + + override fun onProviderEnabled(provider: String) { + Log.d(TAG, "location found 2") + } + + override fun onProviderDisabled(provider: String) { + Log.d(TAG, "location found 3") + } + } + locationManager.requestLocationUpdates( + locationProviderWifi, + 0, + 0f, + locationListenerNetwork + ) + } catch (e: Exception) { + Log.e(TAG, "NW Location Exception: " + e.message) } } +// fun getPublicIpAddr(callback: (String) -> Unit) { +// GlobalScope.launch(Dispatchers.IO) { +// val url = URL("https://api.ipify.org") +// val conn = url.openConnection() as HttpURLConnection +// try { +// conn.connect() +// if (conn.responseCode == HttpURLConnection.HTTP_OK) { +// val scanner = Scanner(conn.inputStream) +// scanner.useDelimiter("\\A") +// if (scanner.hasNext()) { +// val ipAddress = scanner.next() +// callback(ipAddress) +// } +// } +// } finally { +// conn.disconnect() +// } +// } +// } - inner class MyLocationListener : LocationListener { - @RequiresApi(Build.VERSION_CODES.P) - override fun onLocationChanged(location: Location) { - // Handle location change here - latitude = location.latitude - longitude = location.longitude - - DataHolder.location = - UserData.Location(location.latitude, location.longitude) - DataHolder.selectedTest?.location = - UserData.Location(location.latitude, location.longitude) - // Toast.makeText(requireContext(), "location$latitude/$longitude",Toast.LENGTH_SHORT).show() - - // Do something with latitude and longitude - } - - override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {} - - override fun onProviderEnabled(provider: String) {} - - override fun onProviderDisabled(provider: String) {} - } } diff --git a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt index 0544292..17ed921 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/hemocube/HemoCubeFragment.kt @@ -463,20 +463,20 @@ class HemoCubeFragment : Fragment() { fetchResult() } //#EC for v0 and v1 and #RC for v2 - (resultData.contains("#EC") && this.testStatusCode < TestStatus.EPROM_ADC_RETRIEVAL_COMPLETED.code) -> { + (resultData.contains("#RC") && this.testStatusCode < TestStatus.EPROM_ADC_RETRIEVAL_COMPLETED.code) -> { this.testStatusCode = TestStatus.EPROM_ADC_RETRIEVAL_COMPLETED.code - hemoCubeViewModel.messages.postValue("EPROM ADC Loaded") + hemoCubeViewModel.messages.postValue("Ready to test")//EPROM ADC Loaded //checkCuvettePresence() activity?.runOnUiThread { binding.btnPlacebuffer.visibility = View.VISIBLE binding.btnSamplestart.visibility = View.VISIBLE } -// getTemp() + getTemp() } (resultData.contains("#AC") && this.testStatusCode < TestStatus.TEMPERATURE_CHECK.code) -> { this.testStatusCode = TestStatus.TEMPERATURE_CHECK.code temperature = resultData.substringAfter("#AS").substringBefore("#AC") - hemoCubeViewModel.messages.postValue("EPROM ADC Loaded and Temperature fetched \n Temp : $temperature") + hemoCubeViewModel.messages.postValue("Ready to test \n Temperature : $temperature") } resultData.contains("#CIN") && sampleClick && this.testStatusCode < TestStatus.CUVETTE_PRESENTS.code -> { hemoCubeViewModel.messages.postValue(getString(R.string.cuvette_present)) diff --git a/app/src/main/res/navigation/dashboard_navigation.xml b/app/src/main/res/navigation/dashboard_navigation.xml index 5f86269..c840904 100644 --- a/app/src/main/res/navigation/dashboard_navigation.xml +++ b/app/src/main/res/navigation/dashboard_navigation.xml @@ -62,7 +62,7 @@