diff --git a/build/Si-Connect - v2_9_3.apk b/build/Si-Connect - v2_9_3.apk new file mode 100644 index 00000000..170f29b6 --- /dev/null +++ b/build/Si-Connect - v2_9_3.apk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4da8c0e7b06a1bdd9be68791798f36d66dd4411315823a0bd0c9f97b1946c847 +size 53222080 diff --git a/build/Si-Connect-v2_9_2.apk b/build/Si-Connect-v2_9_2.apk deleted file mode 100644 index 94657958..00000000 --- a/build/Si-Connect-v2_9_2.apk +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:516b06f650d8ee8a7fa6de91aa074cde3f7e6c9207d349aeebc53d47332dec56 -size 53187272 diff --git a/mobile/build.gradle.kts b/mobile/build.gradle.kts index 519b5737..8fd4bf76 100644 --- a/mobile/build.gradle.kts +++ b/mobile/build.gradle.kts @@ -60,8 +60,8 @@ android { create("Si-Connect") { dimension = versionDim applicationId = "com.siliconlabs.bledemo" - versionCode = 54 - versionName = "2.9.2" + versionCode = 55 + versionName = "2.9.3" } } @@ -167,5 +167,5 @@ dependencies { implementation("com.squareup.retrofit2:retrofit:2.9.0") implementation("com.squareup.retrofit2:converter-gson:2.9.0") implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.4.0") - + implementation ("com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2") } diff --git a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/APIClient.kt b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/APIClient.kt deleted file mode 100644 index 914da777..00000000 --- a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/APIClient.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.siliconlabs.bledemo.features.demo.devkitsensor917 - -import retrofit2.Retrofit -import retrofit2.converter.gson.GsonConverterFactory - - -object APIClient { - val baseURL = "http://192.168.10.10" - - fun getInstance(): Retrofit { - return Retrofit.Builder().baseUrl(baseURL) - .addConverterFactory(GsonConverterFactory.create()) - .build() - } -} \ No newline at end of file diff --git a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/activities/DevKitSensor917Activity.kt b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/activities/DevKitSensor917Activity.kt index ae628d0e..2b07a9af 100644 --- a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/activities/DevKitSensor917Activity.kt +++ b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/activities/DevKitSensor917Activity.kt @@ -1,7 +1,11 @@ package com.siliconlabs.bledemo.features.demo.devkitsensor917.activities +import android.annotation.SuppressLint +import android.graphics.Color +import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.MenuItem +import android.widget.Toast import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.appcompat.app.AppCompatActivity @@ -9,8 +13,20 @@ import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import com.siliconlabs.bledemo.R import com.siliconlabs.bledemo.databinding.Activity917DevKitSensorLayoutBinding +import com.siliconlabs.bledemo.features.demo.devkitsensor917.APIInterface +import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.ScanResponse +import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.SensorsResponse import com.siliconlabs.bledemo.features.demo.devkitsensor917.utils.DevKitSensorChecker import com.siliconlabs.bledemo.features.demo.devkitsensor917.utils.DevKitSensorControl +import com.siliconlabs.bledemo.features.demo.matter_demo.utils.CustomProgressDialog +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import timber.log.Timber +import retrofit2.Retrofit +import retrofit2.converter.gson.GsonConverterFactory class DevKitSensor917Activity : AppCompatActivity() { @@ -19,7 +35,9 @@ class DevKitSensor917Activity : AppCompatActivity() { private val devKitSensorChecker = DevKitSensorChecker() private val controls = mutableMapOf() - + private lateinit var devkitSensorCntl: DevKitSensorControl + private lateinit var listener: ResponseListener + private var customProgressDialog: CustomProgressDialog? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -30,42 +48,86 @@ class DevKitSensor917Activity : AppCompatActivity() { val actionBar = supportActionBar actionBar!!.setHomeAsUpIndicator(R.drawable.matter_back) actionBar.setDisplayHomeAsUpEnabled(true) - initGrid() + val ipAddress = intent.getStringExtra(IP_ADDRESS) + if (ipAddress != null) { + showProgressDialog(this.getString(R.string.dev_kit_progress_bar_message)) + println("IP ADDRESS Imported: $ipAddress") + initGrid(ipAddress) + GlobalScope.launch { + doInSensorBackground(ipAddress) + } + } } -// -// override fun onBackPressed() { -// if (getFragmentManager().getBackStackEntryCount() > 0) -// getFragmentManager().popBackStack(); -// else -// super.onBackPressed(); -// } + @SuppressLint("SetTextI18n") + private suspend fun doInSensorBackground(ipAddress: String) { + withContext(Dispatchers.IO) { + delay(3000L) + try { + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val response = retro.create(APIInterface::class.java).getAllSensor() + + println("Response: $response") + if (response.isSuccessful) { + val data = response.body() + println("data: $data") + withContext(Dispatchers.Main) { + if (data != null) { + listener.fetchData(data) + removeProgress() + } + } + } else { + removeProgress() + runOnUiThread { + Toast.makeText( + baseContext, + "API All Sensors Response failed", + Toast.LENGTH_SHORT + ).show() + } + + Timber.tag(TAG).e("API All Sensors Response failed:${response.message()}") + } + } catch (e: Exception) { + removeProgress() + Timber.tag(TAG).e("API All Sensors Exception occurred ${e.message}") + } + } + } + override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { this.finish() true } + else -> super.onOptionsItemSelected(item) } } - private fun initGrid() { + private fun initGrid(ipAddress: String) { binding.envGrid.apply { devKitSensorChecker.devKitSensors.filter { it.value == DevKitSensorChecker.DevkitSensorState.WORKING }.forEach { - controls[it.key] = DevKitSensorControl( + devkitSensorCntl = DevKitSensorControl( this.context, getString(getTileDescription(it.key)), ContextCompat.getDrawable(this.context, getTileIcon(it.key)) ).also { addView(it) - it.setListener(it.tag) + it.setListener(it.tag, ipAddress) + } + listener = devkitSensorCntl + controls[it.key] = devkitSensorCntl } } } @@ -99,6 +161,31 @@ class DevKitSensor917Activity : AppCompatActivity() { } } + private fun removeProgress() { + runOnUiThread { + if (customProgressDialog?.isShowing() == true) { + customProgressDialog?.dismiss() + } + } + } + + private fun showProgressDialog(message: String) { + runOnUiThread { + customProgressDialog = CustomProgressDialog(this) + customProgressDialog!!.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) + customProgressDialog!!.setMessage(message) + customProgressDialog!!.show() + } + } + + interface ResponseListener { + fun fetchData(response: SensorsResponse?) + } + + companion object { + const val IP_ADDRESS = "ip_address" + val TAG = "" + } } diff --git a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/interface/APIInterface.kt b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/interface/APIInterface.kt index d4982169..08c4e42a 100644 --- a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/interface/APIInterface.kt +++ b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/interface/APIInterface.kt @@ -9,6 +9,7 @@ import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.LEDStatusResp import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.MicrophoneResponse import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.ProvisionResponse import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.ScanResponse +import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.SensorsResponse import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.StatusResponse import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.TempResponse import retrofit2.Response @@ -66,5 +67,7 @@ interface APIInterface { @POST("/status_led") fun setLEDStatusOff(@Body body: Map): Call + @GET("/all_sensors") + suspend fun getAllSensor():Response } \ No newline at end of file diff --git a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/model/sensorsResponse.kt b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/model/sensorsResponse.kt new file mode 100644 index 00000000..6be5cf5f --- /dev/null +++ b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/model/sensorsResponse.kt @@ -0,0 +1,11 @@ +package com.siliconlabs.bledemo.features.demo.devkitsensor917.model + +data class SensorsResponse( + val led: LEDResponse, + val light: AmbientLightResponse, + val temperature: TempResponse, + val accelerometer: AccelerometerGyroScopeResponse, + val gyroscope: AccelerometerGyroScopeResponse, + val humidity: HumidityResponse, + val microphone: MicrophoneResponse +) diff --git a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/utils/DevKitSensorControl.kt b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/utils/DevKitSensorControl.kt index bf7d2faf..575d4f49 100644 --- a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/utils/DevKitSensorControl.kt +++ b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/utils/DevKitSensorControl.kt @@ -14,16 +14,19 @@ import android.widget.Toast import androidx.core.content.ContextCompat import androidx.gridlayout.widget.GridLayout import com.siliconlabs.bledemo.R -import com.siliconlabs.bledemo.features.demo.devkitsensor917.APIClient import com.siliconlabs.bledemo.features.demo.devkitsensor917.APIInterface +import com.siliconlabs.bledemo.features.demo.devkitsensor917.activities.DevKitSensor917Activity +import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.AccelerometerGyroScopeResponse +import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.AmbientLightResponse +import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.HumidityResponse import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.LEDResponse import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.LEDStatusResponse -import com.siliconlabs.bledemo.features.demo.thunderboard_demos.demos.environment.model.TemperatureScale +import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.SensorsResponse +import com.siliconlabs.bledemo.features.demo.devkitsensor917.model.TempResponse import kotlinx.android.synthetic.main.environmentdemo_tile.view.env_description import kotlinx.android.synthetic.main.environmentdemo_tile.view.env_icon -import kotlinx.android.synthetic.main.environmentdemo_tile.view.env_value +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch @@ -31,67 +34,53 @@ import kotlinx.coroutines.withContext import retrofit2.Call import retrofit2.Callback import retrofit2.Response +import retrofit2.Retrofit +import retrofit2.converter.gson.GsonConverterFactory import timber.log.Timber + open class DevKitSensorControl( context: Context, description: String?, icon: Drawable? -) : LinearLayout(context, null, 0) { +) : LinearLayout(context, null, 0), DevKitSensor917Activity.ResponseListener { private var btnRedStatus = false private var btnGreenStatus = false private var btnBlueStatus = false private lateinit var ledImageStatus: ImageView - private lateinit var onLEDBtn : Button - private lateinit var offLEDBtn : Button - private lateinit var redLEDBtn : Button - private lateinit var greenLEDBtn : Button - private lateinit var blueLEDBtn : Button + private lateinit var onLEDBtn: Button + private lateinit var offLEDBtn: Button + private lateinit var redLEDBtn: Button + private lateinit var greenLEDBtn: Button + private lateinit var blueLEDBtn: Button + + private var tempResponse: String? = null + private var ambiResponse: String? = null + private var humiResponse: String? = null + private var acceloResponse: AccelerometerGyroScopeResponse? = null + private var gyroResponse: AccelerometerGyroScopeResponse? = null + constructor(context: Context) : this(context, null, null) - private val tileView: View = inflate(context, R.layout.sensor_demo_grid_item,this) + private val tileView: View = inflate(context, R.layout.sensor_demo_grid_item, this) - fun setListener(tag: Any) { + fun setListener(tag: Any, ipAddress: String) { val code = tag.toString() tileView.setOnClickListener { when (code) { - temperature -> showTemperatureDialog(code) - humidity -> showHumidityDialog(code) - ambientLight -> showAmbientLightDialog(code) - microphone -> showMicrophoneDialog(code) - LED -> showLEDControlDialog(code) - motion -> showMotionDialog(code) + temperature -> showTemperatureDialog(code, ipAddress) + humidity -> showHumidityDialog(code, ipAddress) + ambientLight -> showAmbientLightDialog(code, ipAddress) + microphone -> showMicrophoneDialog(code, ipAddress) + LED -> showLEDControlDialog(code, ipAddress) + motion -> showMotionDialog(code, ipAddress) } - - } } - fun setTemperature(temperature: Float, temperatureType: Int) { - tileView.env_value.text = String.format( - if (temperatureType == TemperatureScale.FAHRENHEIT) context.getString(R.string.environment_temp_f) else context.getString( - R.string.environment_temp_c - ), - if (temperatureType == TemperatureScale.FAHRENHEIT) temperature * 1.8f + 32f else temperature - ) - } - - fun setHumidity(humidity: Int) { - tileView.env_value.text = - String.format(context.getString(R.string.environment_humidity_measure), humidity) - } - - fun setAmbientLight(ambientLight: Float) { - tileView.env_value.text = - String.format(context.getString(R.string.devkit_ambient_lx), ambientLight) - } - - fun setMicrophone(microphone: Float) { - tileView.env_value.text = - String.format(context.getString(R.string.devkit_ambient_lx), microphone) - } - private fun showMotionDialog(title: String) { + @SuppressLint("SetTextI18n") + private fun showMotionDialog(title: String, ipAddress: String) { var apiJob: Job? = null val devkitSensorDialog = Dialog(context, R.style.Style_Dialog_Rounded_Corner) devkitSensorDialog.setContentView(R.layout.dev_kit_sesnor_917_motion_control_dialog_layout) @@ -106,22 +95,54 @@ open class DevKitSensorControl( val orientationY = devkitSensorDialog.findViewById(R.id.orientation_y) as TextView val orientationZ = devkitSensorDialog.findViewById(R.id.orientation_z) as TextView val degreeString = context.getString(R.string.motion_orientation_degree) + if (gyroResponse != null && gyroResponse!!.x.isNotEmpty()) { + orientationX.text = String.format(degreeString, gyroResponse!!.x.toFloat()) + } else { + orientationX.text = String.format(degreeString, 00f) + } + if (gyroResponse != null && gyroResponse!!.y.isNotEmpty()) { + orientationX.text = String.format(degreeString, gyroResponse!!.y.toFloat()) + } else { + orientationY.text = String.format(degreeString, 00f) + } + if (gyroResponse != null && gyroResponse!!.z.isNotEmpty()) { + orientationX.text = String.format(degreeString, gyroResponse!!.z.toFloat()) + } else { + orientationZ.text = String.format(degreeString, 00f) + } + + val accelerationString = context.getString(R.string.motion_acceleration_g) val acceloX = devkitSensorDialog.findViewById(R.id.accelo_x) as TextView val acceloY = devkitSensorDialog.findViewById(R.id.accelo_y) as TextView val acceloZ = devkitSensorDialog.findViewById(R.id.accelo_z) as TextView - orientationX.text = String.format(degreeString, 00f) - orientationY.text = String.format(degreeString, 00f) - orientationZ.text = String.format(degreeString, 00f) - - val accelerationString = context.getString(R.string.motion_acceleration_g) - acceloX.text = String.format(accelerationString, 00F) - acceloY.text = String.format(accelerationString, 00F) - acceloZ.text = String.format(accelerationString, 00F) + if (acceloResponse != null && acceloResponse!!.x.isNotEmpty()) { + acceloX.text = String.format(accelerationString, acceloResponse!!.x.toFloat()) + } else { + acceloX.text = String.format(accelerationString, 00F) + } + if (acceloResponse != null && acceloResponse!!.y.isNotEmpty()) { + acceloY.text = String.format(accelerationString, acceloResponse!!.y.toFloat()) + } else { + acceloY.text = String.format(accelerationString, 00F) + } + if (acceloResponse != null && acceloResponse!!.z.isNotEmpty()) { + acceloZ.text = String.format(accelerationString, acceloResponse!!.z.toFloat()) + } else { + acceloZ.text = String.format(accelerationString, 00F) + } yesBtn.setOnClickListener { - GlobalScope.launch(Dispatchers.IO) { - doInMotionOrientationBackground(orientationX, orientationY, orientationZ) - doInMotionAccelometerBackground(acceloX, acceloY, acceloZ) + yesBtn.isClickable = false + yesBtn.isEnabled = false + CoroutineScope(Dispatchers.IO).launch { + doInMotionOrientationBackground( + orientationX, + orientationY, + orientationZ, + yesBtn, + ipAddress + ) + doInMotionAccelerometerBackground(acceloX, acceloY, acceloZ, ipAddress) } } noBtn.setOnClickListener { @@ -132,41 +153,53 @@ open class DevKitSensorControl( } header.text = title + space + context.getString(R.string.title_sensor) devkitSensorDialog.show() - apiJob = GlobalScope.launch { + apiJob = CoroutineScope(Dispatchers.IO).launch { while (true) { - doInMotionOrientationBackground(orientationX, orientationY, orientationZ) - doInMotionAccelometerBackground(acceloX, acceloY, acceloZ) + doInMotionOrientationBackground( + orientationX, + orientationY, + orientationZ, + yesBtn, + ipAddress + ) + doInMotionAccelerometerBackground(acceloX, acceloY, acceloZ, ipAddress) delay(TIME_OUT) } } } - private suspend fun doInMotionAccelometerBackground( + + private suspend fun doInMotionAccelerometerBackground( viewX: TextView, viewY: TextView, - viewZ: TextView + viewZ: TextView, ipAddress: String ) { withContext(Dispatchers.Default) { try { - val apiService = APIClient.getInstance().create(APIInterface::class.java) - val response = apiService.getAccelerometerStatus() + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val response = retro.create(APIInterface::class.java).getAccelerometerStatus() println("Response: $response") if (response.isSuccessful) { val data = response.body() println("data: $data") - if (data != null) { - val accelerationString = context.getString(R.string.motion_acceleration_g) - viewX.text = String.format(accelerationString, data.x.toFloat()) - viewY.text = String.format(accelerationString, data.y.toFloat()) - viewZ.text = String.format(accelerationString, data.z.toFloat()) + withContext(Dispatchers.Main) { + if (data != null) { + val accelerationString = + context.getString(R.string.motion_acceleration_g) + viewX.text = String.format(accelerationString, data.x.toFloat()) + viewY.text = String.format(accelerationString, data.y.toFloat()) + viewZ.text = String.format(accelerationString, data.z.toFloat()) + } } } else { //df - Timber.tag(TAG).e("Response failed:") + Timber.tag(TAG).e("Response failed: ") } } catch (e: Exception) { // Handle the exception - Timber.tag(TAG).e("Exception occurred" + e.message) + Timber.tag(TAG).e("Exception occurred ${e.message}") } } } @@ -175,34 +208,49 @@ open class DevKitSensorControl( private suspend fun doInMotionOrientationBackground( viewX: TextView, viewY: TextView, - viewZ: TextView + viewZ: TextView, btn: TextView, ipAddress: String ) { - withContext(Dispatchers.Default) { + withContext(Dispatchers.IO) { try { - val apiService = APIClient.getInstance().create(APIInterface::class.java) - val response = apiService.getGyroscopeStatus() + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val response = retro.create(APIInterface::class.java).getGyroscopeStatus() println("Response: $response") if (response.isSuccessful) { val data = response.body() println("data: $data") - if (data != null) { - val degreeString = context.getString(R.string.motion_orientation_degree) - viewX.text = String.format(degreeString, data.x.toFloat()) - viewY.text = String.format(degreeString, data.y.toFloat()) - viewZ.text = String.format(degreeString, data.z.toFloat()) + withContext(Dispatchers.Main) { + if (data != null) { + val degreeString = context.getString(R.string.motion_orientation_degree) + viewX.text = String.format(degreeString, data.x.toFloat()) + viewY.text = String.format(degreeString, data.y.toFloat()) + viewZ.text = String.format(degreeString, data.z.toFloat()) + } + btn.isClickable = true + btn.isEnabled = true } } else { //df - Timber.tag(TAG).e("Response failed:") + Timber.tag(TAG) + .e("MotionOrientation API Response failed: ${response.message()}") + btn.isClickable = true + btn.isEnabled = true } } catch (e: Exception) { // Handle the exception - Timber.tag(TAG).e("Exception occurred" + e.message) + Timber.tag(TAG).e("MotionOrientation API Exception occurred ${e.message}") + btn.isClickable = true + btn.isEnabled = true + } finally { + btn.isClickable = true + btn.isEnabled = true } } } - private fun showTemperatureDialog(title: String) { + @SuppressLint("SetTextI18n") + private fun showTemperatureDialog(title: String, ipAddress: String) { var apiJob: Job? = null val devKitSensorDialog = Dialog(context, R.style.Style_Dialog_Rounded_Corner) devKitSensorDialog.setContentView(R.layout.dev_kit_sensor_917_dialog_layout) @@ -210,7 +258,7 @@ open class DevKitSensorControl( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) - //devKitSensorDialog.window?.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT)) + val header = devKitSensorDialog.findViewById(R.id.header) as TextView val subTitle = devKitSensorDialog.findViewById(R.id.subTitle) as TextView val yesBtn = devKitSensorDialog.findViewById(R.id.yes_opt) as TextView @@ -218,12 +266,18 @@ open class DevKitSensorControl( val image = devKitSensorDialog.findViewById(R.id.image) as ImageView val dataHolder = devKitSensorDialog.findViewById(R.id.txt_value) as TextView dataHolder.text = context.getString(R.string.matter_init_value) + // println("tempResponse :${tempResponse!!.temperature_celcius}") + if (tempResponse != null && tempResponse!!.isNotEmpty()) { + dataHolder.text = tempResponse + " ℃" + } image.setImageResource(R.drawable.icon_temp) header.text = title + space + context.getString(R.string.title_sensor) subTitle.text = title yesBtn.setOnClickListener { - GlobalScope.launch(Dispatchers.IO) { - doInTempBackground(dataHolder) + yesBtn.isEnabled = false + yesBtn.isClickable = false + CoroutineScope(Dispatchers.IO).launch { + doInTempBackground(dataHolder, yesBtn, ipAddress) } } noBtn.setOnClickListener { @@ -234,107 +288,149 @@ open class DevKitSensorControl( } devKitSensorDialog.show() - apiJob = GlobalScope.launch { + apiJob = CoroutineScope(Dispatchers.IO).launch { while (true) { - doInTempBackground(dataHolder) + doInTempBackground(dataHolder, yesBtn, ipAddress) delay(TIME_OUT) } } } - private suspend fun doInAmbientBackground(view: TextView) { - withContext(Dispatchers.Default) { + @SuppressLint("SetTextI18n") + private suspend fun doInAmbientBackground(view: TextView, btn: TextView, ipAddress: String) { + withContext(Dispatchers.IO) { try { - val apiService = APIClient.getInstance().create(APIInterface::class.java) - val response = apiService.getAmbitStatus() + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val response = retro.create(APIInterface::class.java).getAmbitStatus() println("Response: $response") if (response.isSuccessful) { val data = response.body() println("data: $data") - if (data != null) { - view.text = data.ambient_light_lux + " lx" + withContext(Dispatchers.Main) { + if (data != null) { + view.text = data.ambient_light_lux + " lx" + } + btn.isClickable = true + btn.isEnabled = true } } else { //df - Timber.tag(TAG).e("Response failed:") + Timber.tag(TAG).e("API Ambient Response failed: ${response.message()}") + btn.isClickable = true + btn.isEnabled = true } } catch (e: Exception) { // Handle the exception - Timber.tag(TAG).e("Exception occurred") + Timber.tag(TAG).e("API Ambient Exception occurred :${e.message}") + btn.isClickable = true + btn.isEnabled = true + } finally { + btn.isClickable = true + btn.isEnabled = true } } } @SuppressLint("SetTextI18n") - private suspend fun doInMicroPhoneBackground(view: TextView) { - withContext(Dispatchers.Default) { + private suspend fun doInMicroPhoneBackground(view: TextView, ipAddress: String) { + withContext(Dispatchers.IO) { try { - val apiService = APIClient.getInstance().create(APIInterface::class.java) - val response = apiService.getMicrophoneStatus() + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val response = retro.create(APIInterface::class.java).getMicrophoneStatus() println("Response: $response") if (response.isSuccessful) { val data = response.body() println("data: $data") - if (data != null) { - view.text = data.microphone_decibel + " dB" + withContext(Dispatchers.Main) { + if (data != null) { + view.text = data.microphone_decibel + " dB" + } } } else { - //df - Timber.tag(TAG).e("Response failed:") + Timber.tag(TAG).e("API Microphone Response failed:${response.message()}") } } catch (e: Exception) { // Handle the exception - Timber.tag(TAG).e("Exception occurred") + Timber.tag(TAG).e("API Microphone Exception occurred ${e.message}") } } } @SuppressLint("SetTextI18n") - private suspend fun doInHumidityBackground(view: TextView) { - withContext(Dispatchers.Default) { + private suspend fun doInHumidityBackground(view: TextView, btn: TextView, ipAddress: String) { + withContext(Dispatchers.IO) { try { - val apiService = APIClient.getInstance().create(APIInterface::class.java) - val response = apiService.getHumidityStatus() + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val response = retro.create(APIInterface::class.java).getHumidityStatus() println("Response: $response") if (response.isSuccessful) { val data = response.body() println("data: $data") - if (data != null) { - view.text = data.humidity_percentage + " %" + withContext(Dispatchers.Main) { + if (data != null) { + view.text = data.humidity_percentage + " %" + } + btn.isEnabled = true + btn.isClickable = true } } else { + btn.isEnabled = true + btn.isClickable = true //df - Timber.tag(TAG).e("Response failed:") + Timber.tag(TAG).e("API Humidity Response failed:${response.message()}") } } catch (e: Exception) { + btn.isEnabled = true + btn.isClickable = true // Handle the exception - Timber.tag(TAG).e("Exception occurred") + Timber.tag(TAG).e("API Humidity Exception occurred ${e.message} ") + } finally { + btn.isEnabled = true + btn.isClickable = true } } } @SuppressLint("SetTextI18n") - private suspend fun doInTempBackground(view: TextView) { - withContext(Dispatchers.Default) { + private suspend fun doInTempBackground(view: TextView, btn: TextView, ipAddress: String) { + withContext(Dispatchers.IO) { try { - val apiService = APIClient.getInstance().create(APIInterface::class.java) - val response = apiService.getTempStatus() + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val response = retro.create(APIInterface::class.java).getTempStatus() + println("Response: $response") if (response.isSuccessful) { val data = response.body() println("data: $data") - if (data != null) { - view.text = data.temperature_celcius + " ℃" + withContext(Dispatchers.Main) { + if (data != null) { + view.text = data.temperature_celcius + " ℃" + } + btn.isClickable = true + btn.isEnabled = true } } else { - //df - Timber.tag(TAG).e("Response failed:") + btn.isClickable = true + btn.isEnabled = true + Timber.tag(TAG).e("API Temperature Response failed:${response.message()}") } } catch (e: Exception) { - // Handle the exception - Timber.tag(TAG).e("Exception occurred") + btn.isClickable = true + btn.isEnabled = true + Timber.tag(TAG).e("API Temperature Exception occurred ${e.message}") + } finally { + btn.isClickable = true + btn.isEnabled = true } } } @@ -343,9 +439,7 @@ open class DevKitSensorControl( tileView.setTag(description) tileView.apply { env_description.text = description -// env_value.text = context.getString(R.string.environment_not_initialized) env_icon.setImageDrawable(icon) -// env_value.visibility = View.INVISIBLE } layoutParams = GridLayout.LayoutParams( GridLayout.spec(GridLayout.UNDEFINED, 1f), @@ -355,7 +449,8 @@ open class DevKitSensorControl( } } - private fun showMicrophoneDialog(title: String) { + @SuppressLint("SetTextI18n") + private fun showMicrophoneDialog(title: String, ipAddress: String) { var apiJob: Job? = null val devKitSensorDialog = Dialog(context, R.style.Style_Dialog_Rounded_Corner) devKitSensorDialog.setContentView(R.layout.dev_kit_sensor_917_dialog_layout) @@ -374,8 +469,8 @@ open class DevKitSensorControl( header.text = title + space + context.getString(R.string.title_sensor) subTitle.text = title yesBtn.setOnClickListener { - GlobalScope.launch(Dispatchers.IO) { - doInMicroPhoneBackground(microphoneHolder) + CoroutineScope(Dispatchers.IO).launch { + doInMicroPhoneBackground(microphoneHolder, ipAddress) } } noBtn.setOnClickListener { @@ -386,16 +481,17 @@ open class DevKitSensorControl( } devKitSensorDialog.show() - apiJob = GlobalScope.launch { + apiJob = CoroutineScope(Dispatchers.IO).launch { while (true) { - doInMicroPhoneBackground(microphoneHolder) + doInMicroPhoneBackground(microphoneHolder, ipAddress) delay(TIME_OUT) } } } - private fun showAmbientLightDialog(title: String) { + @SuppressLint("SetTextI18n") + private fun showAmbientLightDialog(title: String, ipAddress: String) { var apiJob: Job? = null val devKitSensorDialog = Dialog(context, R.style.Style_Dialog_Rounded_Corner) devKitSensorDialog.setContentView(R.layout.dev_kit_sensor_917_dialog_layout) @@ -411,14 +507,19 @@ open class DevKitSensorControl( val abiHolder = devKitSensorDialog.findViewById(R.id.txt_value) as TextView abiHolder.text = context.getString(R.string.dev_kit_sensor_ambient_init_value) + if (ambiResponse != null && ambiResponse!!.isNotEmpty()) { + abiHolder.text = ambiResponse + " lx" + } abiHolder.textSize = 50F image.setImageResource(R.drawable.icon_light) header.text = title + space + context.getString(R.string.title_sensor) subTitle.text = title yesBtn.setOnClickListener { - GlobalScope.launch(Dispatchers.IO) { - doInAmbientBackground(abiHolder) + yesBtn.isEnabled = false + yesBtn.isClickable = false + CoroutineScope(Dispatchers.IO).launch { + doInAmbientBackground(abiHolder, yesBtn, ipAddress) } } noBtn.setOnClickListener { @@ -429,9 +530,9 @@ open class DevKitSensorControl( } devKitSensorDialog.show() - apiJob = GlobalScope.launch { + apiJob = CoroutineScope(Dispatchers.IO).launch { while (true) { - doInAmbientBackground(abiHolder) + doInAmbientBackground(abiHolder, yesBtn, ipAddress) delay(TIME_OUT) } } @@ -467,7 +568,8 @@ open class DevKitSensorControl( ) } - private fun showLEDControlDialog(title: String) { + @SuppressLint("SetTextI18n") + private fun showLEDControlDialog(title: String, ipAddress: String) { val apiJob: Job? = null val devKitSensorDialog = Dialog(context, R.style.Style_Dialog_Rounded_Corner) devKitSensorDialog.setContentView( @@ -494,13 +596,13 @@ open class DevKitSensorControl( //LED Switch Off condition imageForLightOn(view = ledImageStatus, red = false, blue = false, green = false) -// switchOffLEDStatusOff() - GlobalScope.launch { - getLedSwitchStatus() + + CoroutineScope(Dispatchers.IO).launch { + getLedSwitchStatus(ipAddress) } yesBtn.setOnClickListener { - refreshLEDStatus() + refreshLEDStatus(ipAddress) } noBtn.setOnClickListener { devKitSensorDialog.dismiss() @@ -509,38 +611,38 @@ open class DevKitSensorControl( } } onLEDBtn.setOnClickListener { - GlobalScope.launch { - setAllLEDOn(ledImageStatus) + CoroutineScope(Dispatchers.IO).launch { + setAllLEDOn(ledImageStatus, ipAddress) } } offLEDBtn.setOnClickListener { - GlobalScope.launch { - setAllLEDOff(ledImageStatus) + CoroutineScope(Dispatchers.IO).launch { + setAllLEDOff(ledImageStatus, ipAddress) } } redLEDBtn.setOnClickListener { btnRedStatus = !btnRedStatus - setLEDControl() + setLEDControl(ipAddress) } greenLEDBtn.setOnClickListener { btnGreenStatus = !btnGreenStatus - setLEDControl() + setLEDControl(ipAddress) } blueLEDBtn.setOnClickListener { btnBlueStatus = !btnBlueStatus - setLEDControl() + setLEDControl(ipAddress) } devKitSensorDialog.setCanceledOnTouchOutside(false) devKitSensorDialog.show() } - private fun switchOffLEDStatusOff() { - GlobalScope.launch { - setLEDStatusOff(ledImageStatus) + private fun switchOffLEDStatusOff(ipAddress: String) { + CoroutineScope(Dispatchers.IO).launch { + setLEDStatusOff(ledImageStatus, ipAddress) } } @@ -552,6 +654,7 @@ open class DevKitSensorControl( blueLEDBtn.setBackgroundResource(R.drawable.button_background_blue_box) } + private fun setOffBtnBackground() { onLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) offLEDBtn.setBackgroundResource(R.drawable.button_background_soft_black_box) @@ -560,52 +663,83 @@ open class DevKitSensorControl( blueLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) } - private fun refreshLEDStatus() { - GlobalScope.launch(Dispatchers.IO) { - getAllLEDStatus(ledImageStatus) + private fun refreshLEDStatus(ipAddress: String) { + CoroutineScope(Dispatchers.IO).launch { + getAllLEDStatus(ledImageStatus, ipAddress) } } private fun setBtnColorBackground() { - if(btnRedStatus) + if (btnRedStatus) { + onLEDBtn.setBackgroundResource(R.drawable.button_background_soft_black_box) redLEDBtn.setBackgroundResource(R.drawable.button_background_red_box) - else + } else { + offLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) redLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) - - if(btnGreenStatus) + } + if (btnGreenStatus) { + onLEDBtn.setBackgroundResource(R.drawable.button_background_soft_black_box) greenLEDBtn.setBackgroundResource(R.drawable.button_background_green_box) - else + } else { + offLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) greenLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) - - if(btnBlueStatus) + } + if (btnBlueStatus) { + onLEDBtn.setBackgroundResource(R.drawable.button_background_soft_black_box) blueLEDBtn.setBackgroundResource(R.drawable.button_background_blue_box) - else + } else { + offLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) blueLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) - - if(btnRedStatus && btnGreenStatus && btnBlueStatus) { + } + if (btnRedStatus && btnGreenStatus && btnBlueStatus) { onLEDBtn.setBackgroundResource(R.drawable.button_background_soft_black_box) offLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) - } else { + } else if (btnRedStatus && btnGreenStatus) { + offLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) + onLEDBtn.setBackgroundResource(R.drawable.button_background_soft_black_box) + redLEDBtn.setBackgroundResource(R.drawable.button_background_red_box) + greenLEDBtn.setBackgroundResource(R.drawable.button_background_green_box) + } else if (btnRedStatus && btnBlueStatus) { + offLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) + onLEDBtn.setBackgroundResource(R.drawable.button_background_soft_black_box) + redLEDBtn.setBackgroundResource(R.drawable.button_background_red_box) + blueLEDBtn.setBackgroundResource(R.drawable.button_background_blue_box) + } else if (btnGreenStatus && btnBlueStatus) { + offLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) + onLEDBtn.setBackgroundResource(R.drawable.button_background_soft_black_box) + blueLEDBtn.setBackgroundResource(R.drawable.button_background_blue_box) + greenLEDBtn.setBackgroundResource(R.drawable.button_background_green_box) + } else if (!btnRedStatus && !btnGreenStatus && !btnBlueStatus) { onLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) offLEDBtn.setBackgroundResource(R.drawable.button_background_soft_black_box) + } else { + offLEDBtn.setBackgroundResource(R.drawable.button_background_grey_box) + onLEDBtn.setBackgroundResource(R.drawable.button_background_soft_black_box) } } - private fun setLEDControl(){ - GlobalScope.launch { + private fun setLEDControl(ipAddress: String) { + CoroutineScope(Dispatchers.IO).launch { setLEDCtrl( ledImageStatus, btnRedStatus, btnGreenStatus, - btnBlueStatus + btnBlueStatus, ipAddress ) } } - private suspend fun setLEDCtrl(view: ImageView, red: Boolean, green: Boolean, blue: Boolean) { + private suspend fun setLEDCtrl( + view: ImageView, red: Boolean, green: Boolean, blue: Boolean, + ipAddress: String + ) { withContext(Dispatchers.Default) { - val ledStatus = APIClient.getInstance().create(APIInterface::class.java) + + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val ledStatus = retro.create(APIInterface::class.java) val params: MutableMap = HashMap() var statusRed: String = OFF if (red) { @@ -629,6 +763,7 @@ open class DevKitSensorControl( if (response.isSuccessful) { val data = response.body() println("data: $data") + if (data != null) { if (data.red.equals(OFF) && data.green.equals(OFF) && data.blue.equals(OFF) @@ -639,6 +774,8 @@ open class DevKitSensorControl( } setBtnColorBackground() } + } else { + } } @@ -659,15 +796,19 @@ open class DevKitSensorControl( } } - private suspend fun setAllLEDOff(view: ImageView) { - withContext(Dispatchers.Default) { - val ledStatus = APIClient.getInstance().create(APIInterface::class.java) + private suspend fun setAllLEDOff(view: ImageView, ipAddress: String) { + withContext(Dispatchers.IO) { + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val ledStatus = retro.create(APIInterface::class.java) val body = mapOf( RED to OFF, GREEN to OFF, BLUE to OFF ) ledStatus.setAllLEdsOnOff(body).enqueue(object : Callback { + override fun onResponse(call: Call, response: Response) { println("Response: $response") if (response.isSuccessful) { @@ -680,6 +821,7 @@ open class DevKitSensorControl( btnRedStatus = false btnBlueStatus = false btnGreenStatus = false + setOffBtnBackground() imageForLightOn(view, btnRedStatus, btnBlueStatus, btnGreenStatus) } else { @@ -708,9 +850,12 @@ open class DevKitSensorControl( } } - private suspend fun setAllLEDOn(view: ImageView) { - withContext(Dispatchers.Default) { - val ledStatus = APIClient.getInstance().create(APIInterface::class.java) + private suspend fun setAllLEDOn(view: ImageView, ipAddress: String) { + withContext(Dispatchers.IO) { + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val ledStatus = retro.create(APIInterface::class.java) val body = mapOf( RED to ON, GREEN to ON, @@ -730,13 +875,23 @@ open class DevKitSensorControl( btnBlueStatus = false btnGreenStatus = false setOffBtnBackground() - imageForLightOn(view, btnRedStatus, btnBlueStatus, btnGreenStatus) + imageForLightOn( + view, + btnRedStatus, + btnBlueStatus, + btnGreenStatus + ) } else { btnRedStatus = true btnBlueStatus = true btnGreenStatus = true setOnBtnBackground() - imageForLightOn(view, btnRedStatus, btnBlueStatus, btnGreenStatus) + imageForLightOn( + view, + btnRedStatus, + btnBlueStatus, + btnGreenStatus + ) } } } @@ -759,45 +914,54 @@ open class DevKitSensorControl( } } - private suspend fun getLedSwitchStatus() { - withContext(Dispatchers.Default) { + private suspend fun getLedSwitchStatus(ipAddress: String) { + withContext(Dispatchers.IO) { try { - val apiService = APIClient.getInstance().create(APIInterface::class.java) - val response = apiService.getLedSwitchStatus() + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val response = retro.create(APIInterface::class.java).getLedSwitchStatus() println("Response: $response") if (response.isSuccessful) { val data = response.body() println("data: $data") if (data != null) { - if(data.status_led == ON) - switchOffLEDStatusOff() + if (data.status_led == ON) + switchOffLEDStatusOff(ipAddress) else - refreshLEDStatus() + refreshLEDStatus(ipAddress) } } else { - Timber.tag(TAG).e("Response failed:") + Timber.tag(TAG).e("getLedSwitch Response failed: ${response.message()}") } } catch (e: Exception) { // Handle the exception - Timber.tag(TAG).e("Exception occurred") + Timber.tag(TAG).e("getLedSwitch Exception occurred ${e.message}") } } } - private suspend fun setLEDStatusOff(view: ImageView) { + + private suspend fun setLEDStatusOff(view: ImageView, ipAddress: String) { withContext(Dispatchers.Default) { - val ledStatus = APIClient.getInstance().create(APIInterface::class.java) + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val ledStatus = retro.create(APIInterface::class.java) val body = mapOf( STATUS_LED to OFF ) ledStatus.setLEDStatusOff(body).enqueue(object : Callback { - override fun onResponse(call: Call, response: Response) { + override fun onResponse( + call: Call, + response: Response + ) { println("Response: $response") if (response.isSuccessful) { val data = response.body() println("data: $data") if (data != null) { //refresh the current LED status - refreshLEDStatus() + refreshLEDStatus(ipAddress) } } } @@ -818,34 +982,39 @@ open class DevKitSensorControl( }) } } - private suspend fun getAllLEDStatus(view: ImageView) { + + private suspend fun getAllLEDStatus(view: ImageView, ipAddress: String) { withContext(Dispatchers.Default) { try { - val apiService = APIClient.getInstance().create(APIInterface::class.java) - val response = apiService.getLedStatus() + val url = "http://$ipAddress" + val retro = Retrofit.Builder().baseUrl(url) + .addConverterFactory(GsonConverterFactory.create()).build() + val response = retro.create(APIInterface::class.java).getLedStatus() println("Response: $response") if (response.isSuccessful) { val data = response.body() println("data: $data") if (data != null) { - btnRedStatus = data.red == ON - btnGreenStatus = data.green == ON - btnBlueStatus = data.blue == ON - imageForLightOn(view, btnRedStatus, btnBlueStatus, btnGreenStatus) - setBtnColorBackground() + withContext(Dispatchers.Main) { + btnRedStatus = data.red == ON + btnGreenStatus = data.green == ON + btnBlueStatus = data.blue == ON + imageForLightOn(view, btnRedStatus, btnBlueStatus, btnGreenStatus) + setBtnColorBackground() + } } } else { - //df - Timber.tag(TAG).e("Response failed:") + Timber.tag(TAG).e("getAllLEDStatus Response failed: ${response.message()}") } } catch (e: Exception) { // Handle the exception - Timber.tag(TAG).e("Exception occurred") + Timber.tag(TAG).e("getAllLEDStatus Exception occurred: ${e.message}") } } } - private fun showHumidityDialog(title: String) { + @SuppressLint("SetTextI18n") + private fun showHumidityDialog(title: String, ipAddress: String) { var apiJob: Job? = null val devKitSensorDialog = Dialog(context, R.style.Style_Dialog_Rounded_Corner) devKitSensorDialog.setContentView( @@ -862,12 +1031,17 @@ open class DevKitSensorControl( val image = devKitSensorDialog.findViewById(R.id.image) as ImageView val humidityHolder = devKitSensorDialog.findViewById(R.id.txt_value) as TextView humidityHolder.text = context.getString(R.string.dev_kit_sensor_humidity_init_value) + if (humiResponse != null && humiResponse!!.isNotEmpty()) { + humidityHolder.text = humiResponse + " %" + } image.setImageResource(R.drawable.icon_environment) header.text = title + space + context.getString(R.string.title_sensor) subTitle.text = title yesBtn.setOnClickListener { - GlobalScope.launch(Dispatchers.IO) { - doInHumidityBackground(humidityHolder) + yesBtn.isEnabled = false + yesBtn.isClickable = false + CoroutineScope(Dispatchers.IO).launch { + doInHumidityBackground(humidityHolder, yesBtn, ipAddress) } } noBtn.setOnClickListener { @@ -878,9 +1052,9 @@ open class DevKitSensorControl( } devKitSensorDialog.show() - apiJob = GlobalScope.launch { + apiJob = CoroutineScope(Dispatchers.IO).launch { while (true) { - doInHumidityBackground(humidityHolder) + doInHumidityBackground(humidityHolder, yesBtn, ipAddress) delay(TIME_OUT) } } @@ -888,6 +1062,29 @@ open class DevKitSensorControl( } + override fun fetchData(response: SensorsResponse?) { + //temperatureResponse = tempResponse + println("----------------${response!!.led.blue}") + if (response != null) { + //Temp + if (response.temperature != null && response.temperature.temperature_celcius.isNotEmpty()) { + println("----------------${response.temperature.temperature_celcius}") + tempResponse = response.temperature.temperature_celcius + } + //Humi + if (response.humidity != null && response.humidity.humidity_percentage.isNotEmpty()) { + println("----------------${response.humidity.humidity_percentage}") + humiResponse = response.temperature.temperature_celcius + } + //Ambi + if (response.light != null && response.light.ambient_light_lux.isNotEmpty()) { + println("----------------${response.light.ambient_light_lux}") + ambiResponse = response.light.ambient_light_lux + } + } + + } + companion object { const val space = " " const val temperature = "Temperature" @@ -896,13 +1093,15 @@ open class DevKitSensorControl( const val microphone = "Microphone" const val LED = "LED" const val motion = "Motion" - const val TIME_OUT = 3000L + const val TIME_OUT = 2000L const val OFF = "off" const val ON = "on" const val RED = "red" const val GREEN = "green" const val BLUE = "blue" const val STATUS_LED = "status_led" - private val TAG = DevKitSensorControl.javaClass.simpleName.toString() + private val TAG = Companion::class.java.simpleName.toString() } + + } \ No newline at end of file diff --git a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/utils/DevKitSesnorControl.kt b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/utils/DevKitSesnorControl.kt deleted file mode 100644 index 8b93f622..00000000 --- a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/devkitsensor917/utils/DevKitSesnorControl.kt +++ /dev/null @@ -1,4 +0,0 @@ -package com.siliconlabs.bledemo.features.demo.devkitsensor917.utils - -class DevKitSesnorControl { -} \ No newline at end of file diff --git a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/wifi_commissioning/activities/WifiCommissioningActivity.kt b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/wifi_commissioning/activities/WifiCommissioningActivity.kt index d4a0e67e..0dafd412 100644 --- a/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/wifi_commissioning/activities/WifiCommissioningActivity.kt +++ b/mobile/src/main/java/com/siliconlabs/bledemo/features/demo/wifi_commissioning/activities/WifiCommissioningActivity.kt @@ -5,6 +5,9 @@ import android.app.AlertDialog import android.app.ProgressDialog import android.bluetooth.* import android.content.* +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.os.Build import android.os.Bundle import android.util.Log import android.view.View @@ -15,7 +18,10 @@ import com.siliconlabs.bledemo.bluetooth.ble.GattService import com.siliconlabs.bledemo.bluetooth.ble.TimeoutGattCallback import com.siliconlabs.bledemo.R import com.siliconlabs.bledemo.base.activities.BaseDemoActivity +import com.siliconlabs.bledemo.bluetooth.services.BluetoothService import com.siliconlabs.bledemo.databinding.ActivityWifiCommissioningBinding +import com.siliconlabs.bledemo.features.demo.devkitsensor917.activities.DevKitSensor917Activity +import com.siliconlabs.bledemo.features.demo.devkitsensor917.activities.DevKitSensor917Activity.Companion.IP_ADDRESS import com.siliconlabs.bledemo.utils.Converters import com.siliconlabs.bledemo.features.demo.wifi_commissioning.adapters.AccessPointsAdapter import com.siliconlabs.bledemo.features.demo.wifi_commissioning.models.AccessPoint @@ -52,13 +58,17 @@ class WifiCommissioningActivity : BaseDemoActivity() { private val sleepForWrite: Long = 500 private val sleepForRead: Long = 500 + private lateinit var sharedPref: SharedPreferences + var connectType = BluetoothService.GattConnectType.WIFI_COMMISSIONING; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + sharedPref = this.getSharedPreferences("WIFI_Comm_Pref", Context.MODE_PRIVATE) _binding = ActivityWifiCommissioningBinding.inflate(layoutInflater) setContentView(_binding.root) - + connectType = + ((intent?.getSerializableExtra("connectType") as? BluetoothService.GattConnectType)!!) setupRecyclerView() setupUiListeners() } @@ -119,11 +129,34 @@ class WifiCommissioningActivity : BaseDemoActivity() { fun onAccessPointConnection(isSuccessful: Boolean) { dismissProgressDialog() if (isSuccessful) { - showToastOnUi(getString(R.string.ap_connect)) - connectedAccessPoint = clickedAccessPoint - connectedAccessPoint?.status = true + when (connectType) { + BluetoothService.GattConnectType.WIFI_COMMISSIONING -> { + showToastOnUi(getString(R.string.ap_connect)) + connectedAccessPoint = clickedAccessPoint + connectedAccessPoint?.status = true + + runOnUiThread { accessPointsAdapter?.notifyDataSetChanged() } + } + + BluetoothService.GattConnectType.DEV_KIT_SENSOR -> { + showToastOnUi(getString(R.string.ap_connect)) + connectedAccessPoint = clickedAccessPoint + connectedAccessPoint?.status = true + val devKitIntent = Intent( + this, + DevKitSensor917Activity::class.java + ).apply { + putExtra(IP_ADDRESS, clickedAccessPoint?.ipAddress) + } + storeInfo(clickedAccessPoint!!.ipAddress!!) + println("BLE_PROV ipAddress:${clickedAccessPoint!!.ipAddress}") + startActivity(devKitIntent) + this.finish() - runOnUiThread { accessPointsAdapter?.notifyDataSetChanged() } + } + + else -> null + } } else { showToastOnUi(getString(R.string.ap_connect_fail)) } @@ -132,10 +165,23 @@ class WifiCommissioningActivity : BaseDemoActivity() { fun onAccessPointDisconnection(isSuccessful: Boolean) { dismissProgressDialog() if (isSuccessful) { - connectedAccessPoint = null showToastOnUi(getString(R.string.ap_disconnect_success)) - scanForAccessPoints() - toggleMainView(isAccessPointConnected = false) + when (connectType) { + BluetoothService.GattConnectType.WIFI_COMMISSIONING -> { + connectedAccessPoint = null + scanForAccessPoints() + toggleMainView(isAccessPointConnected = false) + } + + BluetoothService.GattConnectType.DEV_KIT_SENSOR -> { + connectedAccessPoint = null + scanForAccessPoints() + toggleMainView(isAccessPointConnected = false) + showToastOnUi(getString(R.string.ap_disconnect_success)) + } + + else -> null + } } else { showToastOnUi(getString(R.string.ap_disconnect_fail)) } @@ -144,10 +190,28 @@ class WifiCommissioningActivity : BaseDemoActivity() { fun isAccessPointConnected(isConnected: Boolean) { dismissProgressDialog() if (isConnected) { - if (isItemClicked) { /* Board already connected when clicking on item */ - showDisconnectionDialog() - } else { /* Board connected when entering the app */ - toggleMainView(isAccessPointConnected = true) + when (connectType) { + BluetoothService.GattConnectType.WIFI_COMMISSIONING -> { + if (isItemClicked) { /* Board already connected when clicking on item */ + showDisconnectionDialog() + } else { /* Board connected when entering the app */ + toggleMainView(isAccessPointConnected = true) + } + } + + BluetoothService.GattConnectType.DEV_KIT_SENSOR -> { + val devKitIntent = Intent( + this, + DevKitSensor917Activity::class.java + ).apply { + putExtra(IP_ADDRESS, getInfo()) + } + println("BLE_PROV ipAddress:${getInfo()}") + startActivity(devKitIntent) + this.finish() + } + + else -> null } } else { clickedAccessPoint?.let { /* No board connected when clicking on item */ @@ -484,7 +548,45 @@ class WifiCommissioningActivity : BaseDemoActivity() { } }.toString() } - + + private fun isNetworkAvailable(context: Context?): Boolean { + if (context == null) return false + val connectivityManager = + context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val capabilities = + connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) + if (capabilities != null) { + when { + capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> { + return true + } + } + } + } else { + val activeNetworkInfo = connectivityManager.activeNetworkInfo + if (activeNetworkInfo != null && activeNetworkInfo.isConnected) { + return true + } + } + return false + } + + override fun onDestroy() { + super.onDestroy() + progressDialog?.dismiss() + } + + private fun storeInfo(info: String) { + val ipInfo = sharedPref.edit() + ipInfo.putString("ipaddress", info) + ipInfo.apply() + } + + private fun getInfo(): String? { + return sharedPref.getString("ipaddress", "") + } + companion object { private const val RADIX_HEX = 16 private const val PADDING_LENGTH = 2 diff --git a/mobile/src/main/java/com/siliconlabs/bledemo/home_screen/dialogs/SelectDeviceDialog.kt b/mobile/src/main/java/com/siliconlabs/bledemo/home_screen/dialogs/SelectDeviceDialog.kt index 4f523ece..ef80f0fc 100644 --- a/mobile/src/main/java/com/siliconlabs/bledemo/home_screen/dialogs/SelectDeviceDialog.kt +++ b/mobile/src/main/java/com/siliconlabs/bledemo/home_screen/dialogs/SelectDeviceDialog.kt @@ -297,6 +297,7 @@ class SelectDeviceDialog( } } + @SuppressLint("StringFormatInvalid") private fun initDemoDescription() { binding.dialogTextInfo.apply { text = when (connectType) { @@ -340,6 +341,11 @@ class SelectDeviceDialog( getString(R.string.demo_firmware_name_esl) ) + GattConnectType.DEV_KIT_SENSOR -> getString( + R.string.demo_firmware_name_wifi_commission, + getString(R.string.demo_firmware_name_esl) + ) + else -> getString(R.string.empty_description) } @@ -465,6 +471,10 @@ class SelectDeviceDialog( add(buildFilter(GattService.EslDemoService)) } + GattConnectType.DEV_KIT_SENSOR -> { + add(buildFilter(BuildFilterName.DEV_KIT_SENSOR)) + } + else -> Unit } } @@ -517,12 +527,16 @@ class SelectDeviceDialog( GattConnectType.MOTION -> MotionActivity::class.java GattConnectType.ENVIRONMENT -> EnvironmentActivity::class.java GattConnectType.ESL_DEMO -> EslDemoActivity::class.java + GattConnectType.DEV_KIT_SENSOR -> WifiCommissioningActivity::class.java + else -> null } - return clazz?.let { - Intent(activity, clazz) + val intent = clazz?.let { Intent(activity, it) } + if (connectType == GattConnectType.WIFI_COMMISSIONING || connectType == GattConnectType.DEV_KIT_SENSOR) { + intent?.putExtra("connectType", connectType) } + return intent } interface RangeTestCallback { @@ -535,7 +549,7 @@ class SelectDeviceDialog( } override fun handleScanResult(scanResult: ScanResultCompat) { - viewModel.handleScanResult(scanResult,connectType,context) + viewModel.handleScanResult(scanResult, connectType, context) } override fun onDiscoveryFailed() { @@ -575,5 +589,7 @@ class SelectDeviceDialog( IOP_TEST_UPDATE("IOP Test Update"), IOP_TEST_NO_1("IOP_Test_1"), IOP_TEST_NO_2("IOP_Test_2"), + DEV_KIT_SENSOR("WIFI_SENSOR") + } } \ No newline at end of file diff --git a/mobile/src/main/java/com/siliconlabs/bledemo/home_screen/fragments/DemoFragment.kt b/mobile/src/main/java/com/siliconlabs/bledemo/home_screen/fragments/DemoFragment.kt index 9828a242..143245be 100644 --- a/mobile/src/main/java/com/siliconlabs/bledemo/home_screen/fragments/DemoFragment.kt +++ b/mobile/src/main/java/com/siliconlabs/bledemo/home_screen/fragments/DemoFragment.kt @@ -239,22 +239,23 @@ class DemoFragment : BaseServiceDependentMainMenuFragment(), DemoAdapter.OnDemoI } override fun onDemoItemClicked(demoItem: DemoMenuItem) { - if (demoItem.connectType == BluetoothService.GattConnectType.DEV_KIT_SENSOR) { - if (isNetworkAvailable(context)) { - requireContext().startActivity( - Intent( - requireContext(), - DevKitSensor917Activity::class.java - ) - ) - }else{ - Toast.makeText( - requireContext(), - getString(R.string.turn_on_wifi), - Toast.LENGTH_SHORT - ).show() - } - } else if (demoItem.connectType == BluetoothService.GattConnectType.MATTER_DEMO) { + /* if (demoItem.connectType == BluetoothService.GattConnectType.DEV_KIT_SENSOR) { + if (isNetworkAvailable(context)) { + requireContext().startActivity( + Intent( + requireContext(), + DevKitSensor917Activity::class.java + ) + ) + }else{ + Toast.makeText( + requireContext(), + getString(R.string.turn_on_wifi), + Toast.LENGTH_SHORT + ).show() + } + } else */ + if (demoItem.connectType == BluetoothService.GattConnectType.MATTER_DEMO) { requireContext().startActivity(Intent(requireContext(), MatterDemoActivity::class.java)) } else if (demoItem.connectType == BluetoothService.GattConnectType.RANGE_TEST) { startActivity(Intent(requireContext(), RangeTestActivity::class.java)) @@ -279,6 +280,7 @@ class DemoFragment : BaseServiceDependentMainMenuFragment(), DemoAdapter.OnDemoI ).show() } } else { + println("BLE_PROV demoItem:${demoItem.connectType}") selectDeviceDialog = SelectDeviceDialog.newDialog(demoItem.connectType) selectDeviceDialog?.show(childFragmentManager, "select_device_dialog") } diff --git a/mobile/src/main/res/values/strings.xml b/mobile/src/main/res/values/strings.xml index 68168e67..bed9bba5 100644 --- a/mobile/src/main/res/values/strings.xml +++ b/mobile/src/main/res/values/strings.xml @@ -843,6 +843,7 @@ RAIL Bluetooth DMP - SoC Range Test Bluetooth - SoC Throughput Bluetooth - NCP ESL Access Point + 1. The SoC and evaluation board (EVK) must be connected and running the correct firmware \n2. The Wi-Fi network on your mobile device should match the Wi-Fi network used for the sensor device\'s commissioning.\n3. Enable your phone\'s local network to access sensor data. A circuit board (SoC) and the evaluation board (EVK) must be connected and running proper firmwares. See here, here and @@ -1208,4 +1209,7 @@ 00 % 00.00 lx 00 dB + Please turn on Wi-Fi in the mobile + Waiting for Response +