diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/API.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/API.kt new file mode 100644 index 00000000..f8cc815e --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/API.kt @@ -0,0 +1,9 @@ +package com.cloud.diplomaticquarterapp + +class API { + companion object{ + private val BASE = "https://uat.hmgwebservices.com" + private val SERVICE = "Services/Patients.svc/REST" + val WIFI_CREDENTIALS = "$BASE/$SERVICE/Hmg_SMS_Get_By_ProjectID_And_PatientID" + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/BaseActivity.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/BaseActivity.kt new file mode 100644 index 00000000..5790abf6 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/BaseActivity.kt @@ -0,0 +1,51 @@ +package com.cloud.diplomaticquarterapp + +import android.content.Intent +import androidx.appcompat.app.AppCompatActivity +import android.os.Bundle +import android.widget.RelativeLayout +import android.widget.TextView +import com.cloud.diplomaticquarterapp.utils.PlatformBridge +import com.wang.avi.AVLoadingIndicatorView +import io.flutter.embedding.android.FlutterView +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.embedding.engine.dart.DartExecutor +import io.flutter.plugin.common.MethodChannel +import io.flutter.view.FlutterMain +import org.jetbrains.anko.find +import java.util.ArrayList + +open class BaseActivity : AppCompatActivity() { + + lateinit var loadingView:RelativeLayout + lateinit var lblLoadingView:TextView + lateinit var avLoadingView:AVLoadingIndicatorView + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + } + + override fun setContentView(layoutResID: Int) { + super.setContentView(layoutResID) + + loadingView = find(R.id.loadingView) + lblLoadingView = find(R.id.lblLoadingView) + avLoadingView = find(R.id.avLoadingView) + } + + override fun onResume() { + super.onResume() + } + + override fun onPause() { + super.onPause() + } + + override fun onStop() { + super.onStop() + } + + override fun onDestroy() { + super.onDestroy() + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/FlutterMainActivity.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/FlutterMainActivity.kt new file mode 100644 index 00000000..387c35a4 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/FlutterMainActivity.kt @@ -0,0 +1,93 @@ +package com.cloud.diplomaticquarterapp + +import android.content.Intent +import androidx.appcompat.app.AppCompatActivity +import android.os.Bundle +import com.cloud.diplomaticquarterapp.utils.PlatformBridge +import io.flutter.embedding.android.FlutterView +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.embedding.engine.dart.DartExecutor +import io.flutter.plugin.common.MethodChannel +import io.flutter.view.FlutterMain +import java.util.ArrayList + +class FlutterMainActivity : BaseActivity() { + + + private var flutterView: FlutterView? = null + companion object { + private var flutterEngine: FlutterEngine? = null + + private lateinit var instance:FlutterMainActivity + fun getInstance() : FlutterMainActivity{ + return instance + } + } + + + // to get and check returned intent + private fun getArgsFromIntent(intent: Intent): Array? { + // Before adding more entries to this list, consider that arbitrary + // Android applications can generate intents with extra data and that + // there are many security-sensitive args in the binary. + val args = ArrayList() + if (intent.getBooleanExtra("trace-startup", false)) { + args.add("--trace-startup") + } + if (intent.getBooleanExtra("start-paused", false)) { + args.add("--start-paused") + } + if (intent.getBooleanExtra("enable-dart-profiling", false)) { + args.add("--enable-dart-profiling") + } + if (!args.isEmpty()) { + return args.toTypedArray() + } + return null + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + val args = getArgsFromIntent(intent) + + // check if flutterEngine is null + if (flutterEngine == null) { + println(args) + flutterEngine = FlutterEngine(this, args) + flutterEngine!!.dartExecutor.executeDartEntrypoint( + // set which of dart methode will be used here + DartExecutor.DartEntrypoint(FlutterMain.findAppBundlePath(), "main") + ) + } + + setContentView(R.layout.activity_flutter_main) + + flutterView = findViewById(R.id.flutterView) + flutterView!!.attachToFlutterEngine(flutterEngine!!) + + PlatformBridge(flutterEngine!!.dartExecutor.binaryMessenger, this).create() + } + + + override fun onResume() { + super.onResume() + flutterEngine!!.lifecycleChannel.appIsResumed() + instance = this + } + + override fun onPause() { + super.onPause() + flutterEngine!!.lifecycleChannel.appIsInactive() + } + + override fun onStop() { + super.onStop() + flutterEngine!!.lifecycleChannel.appIsPaused() + } + + override fun onDestroy() { + flutterView!!.detachFromFlutterEngine() + super.onDestroy() + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/hmgwifi/HMG_Wifi.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/hmgwifi/HMG_Wifi.kt new file mode 100644 index 00000000..e594cc83 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/hmgwifi/HMG_Wifi.kt @@ -0,0 +1,99 @@ +package com.cloud.diplomaticquarterapp.hmgwifi + +import android.annotation.SuppressLint +import android.util.Log +import com.cloud.diplomaticquarterapp.API +import com.cloud.diplomaticquarterapp.FlutterMainActivity +import com.github.kittinunf.fuel.Fuel +import com.github.kittinunf.fuel.core.extensions.jsonBody +import com.github.kittinunf.fuel.httpGet +import com.github.kittinunf.fuel.httpPost +import org.jetbrains.anko.doAsync +import org.json.JSONObject + + +@SuppressLint("MissingPermission") +class HMG_Wifi(flutterMainActivity: FlutterMainActivity) { + private val TAG = "HMG_Wifi" + private val TEST = true + + private var context = flutterMainActivity; + + private lateinit var completionListener: ((status: Boolean, message: String) -> Unit) + + private var SSID = "GUEST-POC" + private var USER_NAME = "" + private var PASSWORD = "" + + fun completionOnUiThread(status: Boolean, message: String){ + context.runOnUiThread { + completionListener(status, message) + } + } + + /* + * Helpful: + * http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically + */ + fun connectToHMGGuestNetwork(patientId: String, completion: (status: Boolean, message: String) -> Unit): HMG_Wifi { + completionListener = completion + getWifiCredentials(patientId) { + WPA(context,SSID).connect(USER_NAME,PASSWORD) { status, message -> + completionOnUiThread(status,message) + } + } + return this + } + + private fun haveInternet(completion: ((status: Boolean) -> Unit)){ + if (TEST) + completion(true) + + "https://captive.apple.com".httpGet().response { request, response, result -> + val have = response.statusCode == 200 && String(response.data).contains("Success", true) + completion(have) + } + } + + private fun getWifiCredentials(patientId:String, completion: (() -> Unit)){ +// if (TEST){ +// SSID = "GUEST-POC" +// USER_NAME = "0696" +// PASSWORD = "0000" +// completion() +// return +// } + + val jsonBody = """{"PatientID":$patientId}""" + API.WIFI_CREDENTIALS. + httpPost() + .jsonBody(jsonBody, Charsets.UTF_8) + .response { request, response, result -> + + result.fold(success = { data -> + val jsonString = String(data) + val jsonObject = JSONObject(jsonString) + if(!jsonObject.getString("ErrorMessage").equals("null")){ + val errorMsg = jsonObject.getString("ErrorMessage") + completionOnUiThread(false, errorMsg) + + }else{ + jsonObject.getJSONArray("Hmg_SMS_Get_By_ProjectID_And_PatientIDList").let { array -> + array.getJSONObject(0).let { object_ -> + if (object_.has("UserName") && object_.has("UserName")){ + USER_NAME = object_.getString("UserName") + PASSWORD = object_.getString("Password") + completion() + }else{ + completionOnUiThread(false, "Failed to get your internet credentials") + } + } + } + } + + },failure = { error -> + completionOnUiThread(false, error.localizedMessage ) + }) + } + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/hmgwifi/WPA.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/hmgwifi/WPA.kt new file mode 100644 index 00000000..18bfc1a7 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/hmgwifi/WPA.kt @@ -0,0 +1,98 @@ +package com.cloud.diplomaticquarterapp.hmgwifi + +import android.content.Context +import android.net.ConnectivityManager +import android.net.wifi.* +import android.util.Log +import com.cloud.diplomaticquarterapp.FlutterMainActivity +import com.cloud.diplomaticquarterapp.utils.HMGUtils + +class WPA(mainActivity: FlutterMainActivity, SSID:String) { + private var TAG = "WPA" + private var SSID = "GUEST-POC" + private var wifiManager_: WifiManager? = null + private var connectivityManager_: ConnectivityManager? = null + + init { + wifiManager_ = mainActivity.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager? + connectivityManager_ = mainActivity.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager? + } + + fun connect(identity:String, password:String, completion: (status: Boolean, message: String) -> Unit) { + if(wifiManager_ == null || connectivityManager_ == null){ + completion(false, "Failed to access system connectivity services") + return + } + + val wifiManager = wifiManager_!! + val connectivityManager = connectivityManager_!! + + // Initialize the WifiConfiguration object + val enterpriseConfig = WifiEnterpriseConfig() + val wifi = WifiConfiguration() + wifi.SSID = """"$SSID"""" + wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP) + wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X) + enterpriseConfig.eapMethod = WifiEnterpriseConfig.Eap.PEAP + enterpriseConfig.identity = identity + enterpriseConfig.password = password + wifi.enterpriseConfig = enterpriseConfig + wifi.networkId = ssidToNetworkId(wifi.SSID) + if (wifi.networkId == -1) { + wifiManager.addNetwork(wifi) + } else { + Log.v(TAG, "WiFi found - updating it.\n") + wifiManager.updateNetwork(wifi) + } + Log.v(TAG, "saving config.\n") + wifiManager.saveConfiguration() + wifi.networkId = ssidToNetworkId(wifi.SSID) + + Log.v(TAG, "wifi ID in device = " + wifi.networkId) + + var supState: SupplicantState + val networkIdToConnect = wifi.networkId + if (networkIdToConnect >= 0) { + Log.v(TAG, "Start connecting...\n") + + // We disable the network before connecting, because if this was the last connection before + // a disconnect(), this will not reconnect. + wifiManager.disableNetwork(networkIdToConnect) + wifiManager.enableNetwork(networkIdToConnect, true) + + val wifiInfo: WifiInfo = wifiManager.connectionInfo + + HMGUtils.timer(5000,false){ + supState = wifiInfo.supplicantState + Log.i(TAG, "WifiWizard: Done connect to network : status = $supState") + if (supState == SupplicantState.COMPLETED) + completion(true,"Connected to Wifi") + else + completion(false,"Failed to connect with HMG network") + } + + } else { + Log.v(TAG, "WifiWizard: cannot connect to network") + completion(false,"Failed to connect to Wifi") + } + } + + /** + * This method takes a given String, searches the current list of configured WiFi + * networks, and returns the networkId for the network if the SSID matches. If not, + * it returns -1. + */ + private fun ssidToNetworkId(ssid: String): Int { + val currentNetworks = wifiManager_!!.configuredNetworks + var networkId = -1 + + // For each network in the list, compare the SSID with the given one + for (test in currentNetworks) { + if (test.SSID == ssid) { + networkId = test.networkId + break + } + } + return networkId + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HMGUtils.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HMGUtils.kt new file mode 100644 index 00000000..71488c1d --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HMGUtils.kt @@ -0,0 +1,51 @@ +package com.cloud.diplomaticquarterapp.utils + +import android.opengl.Visibility +import android.view.View +import android.widget.Toast +import com.cloud.diplomaticquarterapp.BaseActivity +import java.util.* +import kotlin.concurrent.timerTask + +class HMGUtils { + + companion object{ + fun timer(delay:Long, repeat:Boolean, tick:(Timer)->Unit) : Timer{ + val timer = Timer() + if(repeat) + timer.schedule(timerTask { + tick(timer) + },delay,delay) + else + timer.schedule(timerTask { + tick(timer) + },delay) + + return timer + } + + + fun showLoading(context: BaseActivity, show:Boolean = true, message:String = "Please wait"){ + if(show){ + context.loadingView.visibility = View.VISIBLE + context.avLoadingView.smoothToShow() + context.lblLoadingView.text = message + }else{ + context.loadingView.visibility = View.GONE + context.avLoadingView.smoothToHide() + context.lblLoadingView.text = "" + } + + } + + fun showMessage(context:BaseActivity, title:String = "", message:String){ + Toast.makeText(context,message,Toast.LENGTH_LONG).show() + } + + } + +} + +private fun Timer.schedule(timerTask: TimerTask) { + +} diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HMG_Wifi_.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HMG_Wifi_.kt new file mode 100644 index 00000000..9bb6196e --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HMG_Wifi_.kt @@ -0,0 +1,351 @@ +package com.cloud.diplomaticquarterapp.utils + +import android.annotation.SuppressLint +import android.content.Context +import android.net.ConnectivityManager +import android.net.Network +import android.net.NetworkCapabilities +import android.net.NetworkRequest +import android.net.wifi.ScanResult +import android.net.wifi.WifiConfiguration +import android.net.wifi.WifiManager +import android.util.Log +import com.cloud.diplomaticquarterapp.API +import com.cloud.diplomaticquarterapp.FlutterMainActivity +import com.github.kittinunf.fuel.core.extensions.jsonBody +import com.github.kittinunf.fuel.httpGet +import com.github.kittinunf.fuel.httpPost +import org.json.JSONObject +import java.util.* + + +@SuppressLint("MissingPermission") +class HMG_Wifi_(flutterMainActivity: FlutterMainActivity) { + val TAG = "WIFI" + val TEST = true + + var context = flutterMainActivity; + var completionListener: ((status: Boolean, message: String) -> Unit)? = null + + + private var SSID = "HMG-GUEST" + private var USER_NAME = "" + private var PASSWORD = "" + var NETWORK_ID = -1 // HMG-GUEST Assigned Network ID by Android + private lateinit var PATIENT_ID:String + /* + * Helpful: + * http://stackoverflow.com/questions/5452940/how-can-i-get-android-wifi-scan-results-into-a-list + */ + fun triggerWifiScan(context: Context) { + val wifi = context.getSystemService(Context.WIFI_SERVICE) as WifiManager + wifi.startScan() + } + + /* + * Helpful: + * http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically + */ + fun connectToWifiNetworkWith(patientId: String): HMG_Wifi_ { + + val connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + + PATIENT_ID = patientId + + val security = "OPEN" + val networkPass = "" + Log.d(TAG, "Connecting to SSID \"$SSID\" with password \"$networkPass\" and with security \"$security\" ...") + + // You need to create WifiConfiguration instance like this: + val conf = WifiConfiguration() + conf.SSID = "\"" + SSID + "\"" + + if (security == "OPEN") { + conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE) + } else if (security == "WEP") { + conf.wepKeys[0] = "\"" + networkPass + "\"" + conf.wepTxKeyIndex = 0 + conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE) + conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40) + } else { + conf.preSharedKey = "\"" + networkPass + "\"" + } + + // Then, you need to add it to Android wifi manager settings: + val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager + + NETWORK_ID = wifiManager.addNetwork(conf) + Log.d(TAG, "Network ID: $NETWORK_ID") + + //wifiManager.disconnect(); + val result = wifiManager.enableNetwork(NETWORK_ID, true) + //wifiManager.reconnect(); + wifiManager.saveConfiguration() + + if(result == true){ + authNetworkConnection(NETWORK_ID); + }else{ + completionListener?.let { it(false, "Error connecting to HMG network") } + } + return this + } + + private var authTimer:Timer? = null + fun authNetworkConnection(networkId: Int){ + authTimer = Timer() + authTimer?.scheduleAtFixedRate(object : TimerTask() { + override fun run() { + if (connectedNetworkId() == networkId && connectedNetworkIPAddress() > 0) { + authServerCall() + authTimer?.cancel() + } + } + + }, 2000, 1000) + + // If wifi not connected in 5 sec terminate with fail status + Timer().schedule(object : TimerTask() { + override fun run() { + if (null != authTimer) { + authTimer?.cancel() + completionListener?.let { it(false, "Error connecting to HMG network") } + } + } + }, 5000) + + } + + fun authServerCall(){ + + fun call(){ + + forceNetworkCallOverWifi() + + val params = listOf("cmd" to "authenticate", "password" to PASSWORD, "user" to USER_NAME) + val serverUrl = "https://captiveportal-login.hmg.com/cgi-bin/login" +// val serverUrl = "http://192.168.102.223/cgi-bin/login" + serverUrl + .httpPost(params) + .timeout(10000) + .response { request, response, result -> + Log.v(TAG, response.statusCode.toString()) + + haveInternet { have -> + if(have){ + Log.v(TAG, "Connected to internet via $SSID network at HMG") + completionListener?.let { it(true, "Successfully connected to the internet") } + }else{ + Log.e(TAG, "failed to connect to internet via $SSID network at HMG") + completionListener?.let { it(false, "Authentication failed or you are already using your credentials on another device") } + } + } + } + } + + haveInternet { has -> + if (has){ + getAuthCredentials { + call() + } + }else{ + completionListener?.let { it(false, "You must have active internet connection to connect with HMG Network") } + } + } + } + + fun haveInternet(completion: ((status: Boolean) -> Unit)){ + if (TEST) + completion(true) + + "https://captive.apple.com".httpGet().response { request, response, result -> + val have = response.statusCode == 200 && String(response.data).contains("Success", true) + completion(have) + } + } + + fun getAuthCredentials(completion: (() -> Unit)){ + if (TEST){ + USER_NAME = "2300" + PASSWORD = "1820" + completion() + return + } + + val jsonBody = """{"PatientID":$PATIENT_ID}""" + API.WIFI_CREDENTIALS + .httpPost() + .jsonBody(jsonBody, Charsets.UTF_8) + .response { request, response, result -> + val jsonString = String(response.data) + Log.d(TAG, "JSON $jsonString") + + if (response.statusCode == 200){ + + val jsonObject = JSONObject(jsonString) + if(!jsonObject.getString("ErrorMessage").equals("null")){ + val errorMsg = jsonObject.getString("ErrorMessage") + completionListener?.let { it(false, errorMsg) } + + }else{ + jsonObject.getJSONArray("Hmg_SMS_Get_By_ProjectID_And_PatientIDList").let { array -> + array.getJSONObject(0).let { object_ -> + if (object_.has("UserName") && object_.has("UserName")){ + USER_NAME = object_.getString("UserName") + PASSWORD = object_.getString("Password") + completion() + }else{ + completionListener?.let { it(false, "Failed to get your internet credentials") } + } + } + } + } + + }else{ + completionListener?.let { it(false, "Failed to get your internet credentials") } + } + } + } + + fun forceNetworkCallOverWifi(){ + val connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager +// val network = Network +// connectivityManager.activeNetwork + // Exit app if Network disappears. + // Exit app if Network disappears. +// val networkCapabilities: NetworkCapabilities = ConnectivityManager.from(context).getNetworkCapabilities(network) +// val networkCapabilities: NetworkCapabilities = connectivityManager.getNetworkCapabilities(network) + +// if (networkCapabilities == null) { +// return +// } + + val mNetworkCallback = object : ConnectivityManager.NetworkCallback() { + override fun onLost(lostNetwork: Network?) { +// if (network.equals(lostNetwork)){ +// //GlyphLayout.done(false) +// } + } + } + val builder: NetworkRequest.Builder = NetworkRequest.Builder() +// for (transportType in networkCapabilities.getTransportTypes()) { +// builder.addTransportType(transportType) +// } + connectivityManager.registerNetworkCallback(builder.build(), mNetworkCallback) + } + + /* + * Helpful: + * http://stackoverflow.com/questions/6517314/android-wifi-connection-programmatically + */ + fun getScanResultSecurity(result: ScanResult): String? { + val capabilities: String = result.capabilities + val securityModes = arrayOf("WEP", "PSK", "EAP") + for (securityMode in securityModes) { + if (capabilities.contains(securityMode)) { + return securityMode + } + } + return "OPEN" + } + + //connects to the given ssid + fun connectToWPAWiFi(ssid: String, password: String){ + +// WifiUtils.withContext(context) +// .connectWith(ssid, "") +// .setTimeout(40000) +// .onConnectionResult(object : ConnectionSuccessListener { +// override fun success() { +// Log.v(TAG,"Success") +// } +// +// override fun failed(@NonNull errorCode: ConnectionErrorCode) { +// Log.v(TAG,"Failed") +// } +// }) +// .start() +// if(isConnectedTo(ssid)){ //see if we are already connected to the given ssid +// return +// } +// +// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { +// Log.e(TAG, "connection wifi Q") +// +// val wifiNetworkSpecifier: WifiNetworkSpecifier = WifiNetworkSpecifier.Builder() +// .setSsid(ssid) +// .setWpa2Passphrase(password) +// .build() +// +// val networkRequest: NetworkRequest = NetworkRequest.Builder() +// .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) +// .setNetworkSpecifier(wifiNetworkSpecifier) +// .build() +// +// var connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager +// var networkCallback = object : ConnectivityManager.NetworkCallback() { +// override fun onAvailable(network: Network) { +// super.onAvailable(network) +// connectivityManager.bindProcessToNetwork(network) +// Log.e(TAG, "onAvailable") +// } +// +// override fun onLosing(network: Network, maxMsToLive: Int) { +// super.onLosing(network, maxMsToLive) +// Log.e(TAG, "onLosing") +// } +// +// override fun onLost(network: Network) { +// super.onLost(network) +// Log.e(TAG, "onLosing") +// Log.e(TAG, "losing active connection") +// } +// +// override fun onUnavailable() { +// super.onUnavailable() +// Log.e(TAG, "onUnavailable") +// } +// } +// connectivityManager.requestNetwork(networkRequest, networkCallback) +// +// }else{ +// +// try { +// val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager +// +// Log.e(TAG, "connection wifi pre Q") +// +// var netId: Int = wm.addNetwork(getWifiConfig(ssid)) +// if (netId == -1) netId = getExistingNetworkId(ssid); +// wm.saveConfiguration() +// if(wm.enableNetwork(netId, true)){ +// Log.v(TAG,"HMG-GUEST Connected") +// }else{ +// Log.v(TAG,"HMG-GUEST failed to connect") +// } +// } catch (e: Exception) { +// e.printStackTrace() +// Log.v(TAG,"HMG-GUEST failed to connect") +// } +// } + + } + + fun connectedNetworkId():Int{ + val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager + return wm.connectionInfo.networkId + } + + fun connectedNetworkIPAddress():Int{ + val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager + return wm.connectionInfo.ipAddress + } + + fun isConnectedTo(bssid: String):Boolean{ + val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager + if(wm.connectionInfo.bssid == bssid){ + return true + } + return false + } + +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HTTPRequest.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HTTPRequest.kt new file mode 100644 index 00000000..6bc738c8 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/HTTPRequest.kt @@ -0,0 +1,49 @@ +package com.cloud.diplomaticquarterapp.utils + +import android.os.AsyncTask +import android.os.Parcel +import android.os.Parcelable +import android.util.Log +import java.io.BufferedReader +import java.io.InputStreamReader +import java.io.OutputStreamWriter +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder + +class HTTPRequest { + val TAG = "HTTPRequest" + + fun post(serverURL:String, params:Map){ + + var encodedParamsList = params.map { + URLEncoder.encode(it.key, "UTF-8") + "=" + URLEncoder.encode(it.value,"UTF-8") + } + + val postParam = encodedParamsList.joinToString (separator = "&") + + + val url = URL(serverURL) + + with(url.openConnection() as HttpURLConnection) { + requestMethod = "POST" + + val wr = OutputStreamWriter(outputStream) + wr.write(postParam) + wr.flush() + + BufferedReader(InputStreamReader(inputStream)).use { + val response = StringBuffer() + + var inputLIne = it.readLine() + while(inputLIne != null) { + response.append(inputLIne) + inputLIne = it.readLine() + } + + it.close() + Log.v(TAG,response.toString()) + } + } + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/PlatformBridge.kt b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/PlatformBridge.kt new file mode 100644 index 00000000..22852a56 --- /dev/null +++ b/android/app/src/main/kotlin/com/cloud/diplomaticquarterapp/utils/PlatformBridge.kt @@ -0,0 +1,71 @@ +package com.cloud.diplomaticquarterapp.utils + +import android.util.Log +import android.widget.Toast +import com.cloud.diplomaticquarterapp.FlutterMainActivity +import com.cloud.diplomaticquarterapp.hmgwifi.HMG_Wifi +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel + +class PlatformBridge(binaryMessenger: BinaryMessenger, flutterMainActivity: FlutterMainActivity) { + private var binaryMessenger = binaryMessenger + private var mainActivity = flutterMainActivity + + private lateinit var channel: MethodChannel + + companion object { + private const val CHANNEL = "HMG-Platform-Bridge" + private const val METHOD_CONNECT_WIFI = "connectHMGGuestWifi" + private const val METHOD_SHOW_LOADING = "loading" + } + + fun create(){ + channel = MethodChannel(binaryMessenger, CHANNEL) + channel.setMethodCallHandler { methodCall: MethodCall, result: MethodChannel.Result -> + if (methodCall.method == METHOD_CONNECT_WIFI) { + connectHMGGuestWifi(methodCall,result) + + }else if (methodCall.method == METHOD_SHOW_LOADING) { + showLoading(methodCall,result) + + }else { + result.notImplemented() + } + } + } + + private fun connectHMGGuestWifi(methodCall: MethodCall, result: MethodChannel.Result){ + (methodCall.arguments as ArrayList<*>).let { + require(it.size > 0 && (it[0] is String),lazyMessage = { + "Missing or invalid arguments (Must have one argument 'String at 0'" + }) + + val patientId = it[0].toString() +// HMGUtils.showLoading(mainActivity,true,"Connecting...") + HMG_Wifi(mainActivity) + .connectToHMGGuestNetwork(patientId){ status, message -> + HMGUtils.showLoading(mainActivity,false) + if(status){ + HMGUtils.showMessage(mainActivity,"Error", message) + }else{ + HMGUtils.showMessage(mainActivity,"Success",message) + } + Log.v(this.javaClass.simpleName, "$status | $message") + + } + } + } + + private fun showLoading(methodCall: MethodCall, result: MethodChannel.Result){ + (methodCall.arguments as ArrayList<*>).let { + require(it.size > 1 && (it[0] is String) && (it[1] is Boolean),lazyMessage = { + "Missing or invalid arguments (Must have two argument 'String at 1' and 'Boolean at 1'" + }) + + val message = it[0] as String + val show = it[1] as Boolean + HMGUtils.showLoading(mainActivity,show,message) + } + } +} \ No newline at end of file