Advertisement
androidgeek18

MainActivity.kt

Nov 30th, 2024
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.49 KB | Source Code | 0 0
  1. package com.milesmarine.reeflightcontroller
  2.  
  3. import android.content.Intent
  4. import android.os.Bundle
  5. import android.widget.Button
  6. import android.widget.RadioButton
  7. import android.widget.SeekBar
  8. import android.widget.TextView
  9. import android.widget.Toast
  10. import androidx.activity.result.contract.ActivityResultContracts
  11. import androidx.appcompat.app.AppCompatActivity
  12. import okhttp3.*
  13. import okhttp3.MediaType.Companion.toMediaType
  14. import okhttp3.RequestBody.Companion.toRequestBody
  15. import java.io.IOException
  16. import java.util.Locale
  17.  
  18. class MainActivity : AppCompatActivity() {
  19.  
  20. private lateinit var selectedDeviceTextView: TextView // To show the selected device IP
  21. private val client = OkHttpClient() // Shared OkHttpClient instance
  22.  
  23. // Define an ActivityResultLauncher for handling the result from SecondActivity
  24. private val resultLauncher =
  25. registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
  26. if (result.resultCode == RESULT_OK) {
  27. val selectedIP =
  28. result.data?.getStringExtra("selectedDeviceIP") // Get the selected IP from Intent
  29. selectedIP?.let {
  30. selectedDeviceTextView.text = it // Display IP in TextView
  31. }
  32. }
  33. }
  34.  
  35. override fun onCreate(savedInstanceState: Bundle?) {
  36. super.onCreate(savedInstanceState)
  37. setContentView(R.layout.activity_main)
  38.  
  39. // Find views
  40. val buttonOn = findViewById<Button>(R.id.power_on)
  41. val buttonOff = findViewById<Button>(R.id.power_off)
  42. val radioManual = findViewById<RadioButton>(R.id.manualBtn)
  43. val scanBtn = findViewById<Button>(R.id.scanBtn)
  44. selectedDeviceTextView = findViewById(R.id.selectedDevice) // Initialize the TextView
  45. val whitesSeekBar = findViewById<SeekBar>(R.id.whites)
  46. // Find the TextView that will display the SeekBar value
  47. val whitesValueText = findViewById<TextView>(R.id.whitesValueText)
  48.  
  49. // Load saved device IP from shared preferences
  50. val sharedPreferences = getSharedPreferences("DevicePrefs", MODE_PRIVATE)
  51. val savedDeviceIP = sharedPreferences.getString("selectedDeviceIP", null)
  52. selectedDeviceTextView.text = savedDeviceIP ?: getString(R.string.no_device_selected)
  53.  
  54.  
  55. whitesSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
  56. override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
  57. // Manually format the text using String.format
  58. whitesValueText.text = String.format(Locale.getDefault(), "%d%%", progress)
  59. }
  60.  
  61. override fun onStartTrackingTouch(seekBar: SeekBar?) {
  62. // Optionally handle the start of tracking (user begins sliding)
  63. }
  64.  
  65. override fun onStopTrackingTouch(seekBar: SeekBar?) {
  66. // Once the user stops sliding, send the dimmer command with the current progress
  67. val ip = getSelectedDeviceIP()
  68. if (ip != null) {
  69. val brightness = seekBar?.progress ?: 0
  70. sendDimmerCommand(ip, brightness) // Send the dimmer command
  71. } else {
  72. showNoDeviceSelectedToast()
  73. }
  74. }
  75. })
  76.  
  77.  
  78. buttonOn.setOnClickListener {
  79. val ip = getSelectedDeviceIP()
  80. if (ip != null) {
  81. radioManual.isChecked = true // Select Manual mode immediately
  82. sendHttpPostCommand("http://$ip/api/cmnd", "On") { success ->
  83. runOnUiThread {
  84. if (success) {
  85. buttonOn.setBackgroundResource(R.drawable.button_green)
  86. buttonOff.setBackgroundResource(R.drawable.button_gray)
  87. Toast.makeText(this, "LED Turned On Successfully", Toast.LENGTH_SHORT)
  88. .show()
  89. } else {
  90. Toast.makeText(
  91. this,
  92. "Failed to send Power On command",
  93. Toast.LENGTH_SHORT
  94. ).show()
  95. }
  96. }
  97. }
  98. } else {
  99. showNoDeviceSelectedToast()
  100. }
  101. }
  102.  
  103. buttonOff.setOnClickListener {
  104. val ip = getSelectedDeviceIP()
  105. if (ip != null) {
  106. radioManual.isChecked = true // Select Manual mode immediately
  107. sendHttpPostCommand("http://$ip/api/cmnd", "Off") { success ->
  108. runOnUiThread {
  109. if (success) {
  110. buttonOn.setBackgroundResource(R.drawable.button_gray)
  111. buttonOff.setBackgroundResource(R.drawable.button_red)
  112. Toast.makeText(this, "LED Turned Off Successfully", Toast.LENGTH_SHORT)
  113. .show()
  114. } else {
  115. Toast.makeText(
  116. this,
  117. "Failed to send Power Off command",
  118. Toast.LENGTH_SHORT
  119. ).show()
  120. }
  121. }
  122. }
  123. } else {
  124. showNoDeviceSelectedToast()
  125. }
  126. }
  127.  
  128. scanBtn.setOnClickListener {
  129. val intent = Intent(this, SecondActivity::class.java)
  130. resultLauncher.launch(intent) // Launch the SecondActivity using ActivityResultLauncher
  131. }
  132. }
  133.  
  134. // Function to send dimmer command (brightness control) to OpenBeken device
  135. private fun sendDimmerCommand(ip: String, brightness: Int) {
  136. val url = "http://$ip/api/cmnd"
  137. val command = "dimmer $brightness" // Format the command to adjust brightness
  138.  
  139. val requestBody = command.toRequestBody("text/plain".toMediaType())
  140.  
  141. val request = Request.Builder()
  142. .url(url)
  143. .post(requestBody)
  144. .build()
  145.  
  146. client.newCall(request).enqueue(object : Callback {
  147. override fun onFailure(call: Call, e: IOException) {
  148. e.printStackTrace()
  149. runOnUiThread {
  150. Toast.makeText(
  151. applicationContext,
  152. "Failed to send dimmer command",
  153. Toast.LENGTH_SHORT
  154. ).show()
  155. }
  156. }
  157.  
  158. override fun onResponse(call: Call, response: Response) {
  159. runOnUiThread {
  160. if (response.isSuccessful) {
  161. Toast.makeText(
  162. applicationContext,
  163. "Dimmer command sent successfully",
  164. Toast.LENGTH_SHORT
  165. ).show()
  166. } else {
  167. Toast.makeText(
  168. applicationContext,
  169. "Failed to send dimmer command",
  170. Toast.LENGTH_SHORT
  171. ).show()
  172. }
  173. }
  174. }
  175. })
  176. }
  177.  
  178. private fun sendHttpPostCommand(url: String, args: String, callback: (Boolean) -> Unit) {
  179. val command = "Power"
  180. val formattedCommand = "$command $args"
  181. val requestBody = formattedCommand.toRequestBody("text/plain".toMediaType())
  182.  
  183. val request = Request.Builder()
  184. .url(url)
  185. .post(requestBody)
  186. .build()
  187.  
  188. client.newCall(request).enqueue(object : Callback {
  189. override fun onFailure(call: Call, e: IOException) {
  190. e.printStackTrace()
  191. callback(false)
  192. }
  193.  
  194. override fun onResponse(call: Call, response: Response) {
  195. callback(response.isSuccessful)
  196. }
  197. })
  198. }
  199.  
  200. private fun getSelectedDeviceIP(): String? {
  201. val ip = selectedDeviceTextView.text.toString().trim()
  202. return if (ip.isEmpty() || ip == getString(R.string.no_device_selected)) {
  203. null
  204. } else {
  205. ip
  206. }
  207. }
  208.  
  209. private fun showNoDeviceSelectedToast() {
  210. Toast.makeText(this, "Please click scan devices first", Toast.LENGTH_SHORT).show()
  211. }
  212. }
  213.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement