Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.milesmarine.reeflightcontroller
- import android.content.Intent
- import android.os.Bundle
- import android.widget.Button
- import android.widget.RadioButton
- import android.widget.SeekBar
- import android.widget.TextView
- import android.widget.Toast
- import androidx.activity.result.contract.ActivityResultContracts
- import androidx.appcompat.app.AppCompatActivity
- import okhttp3.*
- import okhttp3.MediaType.Companion.toMediaType
- import okhttp3.RequestBody.Companion.toRequestBody
- import java.io.IOException
- import java.util.Locale
- class MainActivity : AppCompatActivity() {
- private lateinit var selectedDeviceTextView: TextView // To show the selected device IP
- private val client = OkHttpClient() // Shared OkHttpClient instance
- // Define an ActivityResultLauncher for handling the result from SecondActivity
- private val resultLauncher =
- registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
- if (result.resultCode == RESULT_OK) {
- val selectedIP =
- result.data?.getStringExtra("selectedDeviceIP") // Get the selected IP from Intent
- selectedIP?.let {
- selectedDeviceTextView.text = it // Display IP in TextView
- }
- }
- }
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
- // Find views
- val buttonOn = findViewById<Button>(R.id.power_on)
- val buttonOff = findViewById<Button>(R.id.power_off)
- val radioManual = findViewById<RadioButton>(R.id.manualBtn)
- val scanBtn = findViewById<Button>(R.id.scanBtn)
- selectedDeviceTextView = findViewById(R.id.selectedDevice) // Initialize the TextView
- val whitesSeekBar = findViewById<SeekBar>(R.id.whites)
- // Find the TextView that will display the SeekBar value
- val whitesValueText = findViewById<TextView>(R.id.whitesValueText)
- // Load saved device IP from shared preferences
- val sharedPreferences = getSharedPreferences("DevicePrefs", MODE_PRIVATE)
- val savedDeviceIP = sharedPreferences.getString("selectedDeviceIP", null)
- selectedDeviceTextView.text = savedDeviceIP ?: getString(R.string.no_device_selected)
- whitesSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
- override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
- // Manually format the text using String.format
- whitesValueText.text = String.format(Locale.getDefault(), "%d%%", progress)
- }
- override fun onStartTrackingTouch(seekBar: SeekBar?) {
- // Optionally handle the start of tracking (user begins sliding)
- }
- override fun onStopTrackingTouch(seekBar: SeekBar?) {
- // Once the user stops sliding, send the dimmer command with the current progress
- val ip = getSelectedDeviceIP()
- if (ip != null) {
- val brightness = seekBar?.progress ?: 0
- sendDimmerCommand(ip, brightness) // Send the dimmer command
- } else {
- showNoDeviceSelectedToast()
- }
- }
- })
- buttonOn.setOnClickListener {
- val ip = getSelectedDeviceIP()
- if (ip != null) {
- radioManual.isChecked = true // Select Manual mode immediately
- sendHttpPostCommand("http://$ip/api/cmnd", "On") { success ->
- runOnUiThread {
- if (success) {
- buttonOn.setBackgroundResource(R.drawable.button_green)
- buttonOff.setBackgroundResource(R.drawable.button_gray)
- Toast.makeText(this, "LED Turned On Successfully", Toast.LENGTH_SHORT)
- .show()
- } else {
- Toast.makeText(
- this,
- "Failed to send Power On command",
- Toast.LENGTH_SHORT
- ).show()
- }
- }
- }
- } else {
- showNoDeviceSelectedToast()
- }
- }
- buttonOff.setOnClickListener {
- val ip = getSelectedDeviceIP()
- if (ip != null) {
- radioManual.isChecked = true // Select Manual mode immediately
- sendHttpPostCommand("http://$ip/api/cmnd", "Off") { success ->
- runOnUiThread {
- if (success) {
- buttonOn.setBackgroundResource(R.drawable.button_gray)
- buttonOff.setBackgroundResource(R.drawable.button_red)
- Toast.makeText(this, "LED Turned Off Successfully", Toast.LENGTH_SHORT)
- .show()
- } else {
- Toast.makeText(
- this,
- "Failed to send Power Off command",
- Toast.LENGTH_SHORT
- ).show()
- }
- }
- }
- } else {
- showNoDeviceSelectedToast()
- }
- }
- scanBtn.setOnClickListener {
- val intent = Intent(this, SecondActivity::class.java)
- resultLauncher.launch(intent) // Launch the SecondActivity using ActivityResultLauncher
- }
- }
- // Function to send dimmer command (brightness control) to OpenBeken device
- private fun sendDimmerCommand(ip: String, brightness: Int) {
- val url = "http://$ip/api/cmnd"
- val command = "dimmer $brightness" // Format the command to adjust brightness
- val requestBody = command.toRequestBody("text/plain".toMediaType())
- val request = Request.Builder()
- .url(url)
- .post(requestBody)
- .build()
- client.newCall(request).enqueue(object : Callback {
- override fun onFailure(call: Call, e: IOException) {
- e.printStackTrace()
- runOnUiThread {
- Toast.makeText(
- applicationContext,
- "Failed to send dimmer command",
- Toast.LENGTH_SHORT
- ).show()
- }
- }
- override fun onResponse(call: Call, response: Response) {
- runOnUiThread {
- if (response.isSuccessful) {
- Toast.makeText(
- applicationContext,
- "Dimmer command sent successfully",
- Toast.LENGTH_SHORT
- ).show()
- } else {
- Toast.makeText(
- applicationContext,
- "Failed to send dimmer command",
- Toast.LENGTH_SHORT
- ).show()
- }
- }
- }
- })
- }
- private fun sendHttpPostCommand(url: String, args: String, callback: (Boolean) -> Unit) {
- val command = "Power"
- val formattedCommand = "$command $args"
- val requestBody = formattedCommand.toRequestBody("text/plain".toMediaType())
- val request = Request.Builder()
- .url(url)
- .post(requestBody)
- .build()
- client.newCall(request).enqueue(object : Callback {
- override fun onFailure(call: Call, e: IOException) {
- e.printStackTrace()
- callback(false)
- }
- override fun onResponse(call: Call, response: Response) {
- callback(response.isSuccessful)
- }
- })
- }
- private fun getSelectedDeviceIP(): String? {
- val ip = selectedDeviceTextView.text.toString().trim()
- return if (ip.isEmpty() || ip == getString(R.string.no_device_selected)) {
- null
- } else {
- ip
- }
- }
- private fun showNoDeviceSelectedToast() {
- Toast.makeText(this, "Please click scan devices first", Toast.LENGTH_SHORT).show()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement