HC05AC-CTRL/src/main/java/io/gitlab/jfronny/hc05ac/InputActivity.kt

66 lines
2.2 KiB
Kotlin
Raw Normal View History

2023-01-25 16:05:03 +01:00
package io.gitlab.jfronny.hc05ac
import android.os.Bundle
import android.view.MotionEvent
2023-01-26 15:03:11 +01:00
import android.widget.TextView
2023-01-25 16:05:03 +01:00
import androidx.appcompat.widget.LinearLayoutCompat
2023-01-26 14:52:20 +01:00
import io.gitlab.jfronny.hc05ac.util.Action
import io.gitlab.jfronny.hc05ac.util.BaseActivity
import io.gitlab.jfronny.hc05ac.util.clamp
import io.gitlab.jfronny.hc05ac.util.jAction
2023-01-25 16:05:03 +01:00
2023-01-25 17:04:39 +01:00
/**
* Activity that divides the screen into two halves, each serving as an input controller.
* Implementations define a send function which is called for every update.
*/
abstract class InputActivity : BaseActivity() {
2023-01-25 16:05:03 +01:00
private var root: LinearLayoutCompat? = null
2023-01-26 15:03:11 +01:00
private var leftView: TextView? = null
private var rightView: TextView? = null
2023-01-25 16:05:03 +01:00
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
root = findViewById(R.id.root)
2023-01-26 15:03:11 +01:00
leftView = findViewById(R.id.left)
rightView = findViewById(R.id.right)
2023-01-25 16:05:03 +01:00
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
if (event != null) {
if (event.x > root!!.width / 2) right(event.y, root!!.height.toFloat(), event.jAction)
else left(event.y, root!!.height.toFloat(), event.jAction)
}
return false
}
private var left: Byte = 0
private var right: Byte = 0
private fun left(y: Float, height: Float, action: Action): Boolean {
left = when (action) {
Action.DOWN, Action.MOVE -> (127 - (y * 256 / height).clamp(0f, 256f)).toInt().toByte()
Action.UP -> 0
Action.OTHER -> return false
}
2023-01-26 15:03:11 +01:00
update()
2023-01-25 16:05:03 +01:00
return false
}
private fun right(y: Float, height: Float, action: Action): Boolean {
right = when (action) {
Action.DOWN, Action.MOVE -> (127 - (y * 256 / height).clamp(0f, 256f)).toInt().toByte()
Action.UP -> 0
Action.OTHER -> return false
}
2023-01-26 15:03:11 +01:00
update()
2023-01-25 16:05:03 +01:00
return false
}
2023-01-26 15:03:11 +01:00
private fun update() {
leftView!!.text = left.toString()
rightView!!.text = right.toString()
send(left, right)
}
2023-01-25 16:05:03 +01:00
protected abstract fun send(left: Byte, right: Byte)
}