package com.example.motordcesp8266volley
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import android.widget.ToggleButton
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
class MainActivity : AppCompatActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val motorDCSeekBar: SeekBar = findViewById(R.id.motorDCSeekBar)
val motorDCToggleButton: ToggleButton = findViewById(R.id.motorDCToggleButton)
val helixImageView: ImageView = findViewById(R.id.helixImageView)
val percentTextView: TextView = findViewById(R.id.percentTextView)
motorDCSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
val percent: Int = (progress / 0.548).toInt()
animationMotorDC(helixImageView, (percent‐125)*‐2)
senData(progress)
motorDCToggleButton.isChecked = progress != 0
percentTextView.text = "$percent%"
}
override fun onStartTrackingTouch(seekBar: SeekBar?) { }
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
motorDCToggleButton.setOnCheckedChangeListener { _, isChecked ‐>
if (isChecked) {
if(motorDCSeekBar.progress == 0) {
motorDCSeekBar.progress = 55
}
animationMotorDC(helixImageView, 50)
percentTextView.text = "100%"
senData(55)
} else {
animationMotorDC(helixImageView, 0)
motorDCSeekBar.progress = 0
percentTextView.text = "0%"
senData(0)
}
}
}
private fun animationMotorDC(image: ImageView, duration: Int) {
val rotation = AnimationUtils.loadAnimation(this, R.anim.rotate)
rotation.fillAfter = true
rotation.startTime = 0
if(duration!=250){
rotation.duration = duration.toLong()
}
image.startAnimation(rotation)
}
private fun senData(speed: Int) {
val queue = Volley.newRequestQueue(this)
val url = "http://192.168.151.50/motorDC"
val stringRequest = object : StringRequest(Method.POST, url,
{ response ‐> Log.i("Request success", response) },
{ error ‐> Log.e("Request error", error.toString()) }
){
override fun getParams(): Map<String, String> {
val params: MutableMap<String, String> = HashMap()
when(speed) {
0 ‐> params["speed"] = "0"
else ‐> params["speed"] = (speed + 200).toString()
}
return params
}
}
queue.add(stringRequest)
}
}