First public version

pull/1/head 1.0.0
Tindy X 2021-03-04 01:28:39 +08:00
parent 567333f836
commit 23438b3f1d
No known key found for this signature in database
GPG Key ID: C6AD413169968D58
43 changed files with 1976 additions and 1 deletions

3
.idea/.gitignore vendored 100644
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

1
.idea/.name 100644
View File

@ -0,0 +1 @@
Brokenithm

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="1.8" />
</component>
</project>

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="BintrayJCenter" />
<option name="name" value="BintrayJCenter" />
<option name="url" value="https://jcenter.bintray.com/" />
</remote-repository>
<remote-repository>
<option name="id" value="Google" />
<option name="name" value="Google" />
<option name="url" value="https://dl.google.com/dl/android/maven2/" />
</remote-repository>
</component>
</project>

9
.idea/misc.xml 100644
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>

View File

@ -1 +1,6 @@
# Brokenithm-Android
## Brokenithm-Android
A version of Brokenithm, inspired by the [Brokenithm-iOS](https://github.com/esterTion/Brokenithm-iOS) project.
Supports UDP and TCP connection to host, UDP for Wireless connection and TCP for `adb reverse` port forward (over USB for lower latency?).
The Windows server is in [another repository](https://github.com/tindy2013/Brokenithm-Android-Server).

1
app/.gitignore vendored 100644
View File

@ -0,0 +1 @@
/build

48
app/build.gradle 100644
View File

@ -0,0 +1,48 @@
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.github.brokenithm"
minSdkVersion 23
targetSdkVersion 30
versionCode 10000
versionName "1.0.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2'
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'net.cachapa.expandablelayout:expandablelayout:2.9.2'
}

21
app/proguard-rules.pro vendored 100644
View File

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@ -0,0 +1,24 @@
package com.github.brokenithm
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.github.brokenithm", appContext.packageName)
}
}

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.github.brokenithm">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:name=".BrokenithmApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Brokenithm">
<activity android:name=".activity.MainActivity"
android:screenOrientation="landscape"
android:configChanges="uiMode|orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@ -0,0 +1,59 @@
package com.github.brokenithm
import android.app.Application
class BrokenithmApplication : Application() {
var lastServer: String
get() {
val config = getSharedPreferences(settings_preference, MODE_PRIVATE)
return config.getString("server", "") ?: ""
}
set(value) {
val config = getSharedPreferences(settings_preference, MODE_PRIVATE)
config.edit().putString("server", value).apply()
}
var simpleAir: Boolean
get() {
val config = getSharedPreferences(settings_preference, MODE_PRIVATE)
return config.getBoolean("simple_air", false)
}
set(value) {
val config = getSharedPreferences(settings_preference, MODE_PRIVATE)
config.edit().putBoolean("simple_air", value).apply()
}
var showDelay: Boolean
get() {
val config = getSharedPreferences(settings_preference, MODE_PRIVATE)
return config.getBoolean("show_delay", false)
}
set(value) {
val config = getSharedPreferences(settings_preference, MODE_PRIVATE)
config.edit().putBoolean("show_delay", value).apply()
}
var enableVibrate: Boolean
get() {
val config = getSharedPreferences(settings_preference, MODE_PRIVATE)
return config.getBoolean("enable_vibrate", true)
}
set(value) {
val config = getSharedPreferences(settings_preference, MODE_PRIVATE)
config.edit().putBoolean("enable_vibrate", value).apply()
}
var tcpMode: Boolean
get() {
val config = getSharedPreferences(settings_preference, MODE_PRIVATE)
return config.getBoolean("tcp_mode", false)
}
set(value) {
val config = getSharedPreferences(settings_preference, MODE_PRIVATE)
config.edit().putBoolean("tcp_mode", value).apply()
}
companion object {
private const val settings_preference = "settings"
}
}

View File

@ -0,0 +1,724 @@
package com.github.brokenithm.activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.BitmapDrawable
import android.os.*
import android.util.DisplayMetrics
import android.view.*
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.github.brokenithm.BrokenithmApplication
import com.github.brokenithm.R
import com.github.brokenithm.util.AsyncTaskUtil
import net.cachapa.expandablelayout.ExpandableLayout
import java.net.*
import java.nio.ByteBuffer
import java.util.*
import kotlin.concurrent.thread
class MainActivity : AppCompatActivity() {
private lateinit var senderTask: AsyncTaskUtil.AsyncTask<InetSocketAddress?, Unit, Unit>
private lateinit var receiverTask: AsyncTaskUtil.AsyncTask<InetSocketAddress?, Unit, Unit>
private lateinit var pingPongTask: AsyncTaskUtil.AsyncTask<Unit, Unit, Unit>
private var mExitFlag = true
private lateinit var app: BrokenithmApplication
private val serverPort = 52468
private val mAirIdx = listOf(4, 5, 2, 3, 0, 1)
// TCP
private var mTCPMode = false
private var mTCPSocket = Socket()
// state
private val numOfButtons = 16
private val numOfGaps = 16
private val buttonWidthToGap = 7.428571f
private val numOfAirBlock = 6
private var mCurrentDelay = 0f
// Buttons
private var mCurrentAirHeight = 6
private var mLastButtons = mutableSetOf<Int>()
private var mTestButton = false
private var mServiceButton = false
private data class InputEvent(val keys: MutableSet<Int>? = null, val airHeight : Int = 6, val testButton: Boolean = false, val serviceButton: Boolean = false)
private var mInputQueue = ArrayDeque<InputEvent>()
// LEDs
private lateinit var mLEDBitmap: Bitmap
private lateinit var mLEDCanvas: Canvas
private var buttonWidth = 0f
private var gapWidth = 0f
private lateinit var mButtonRenderer: View
// vibrator
private lateinit var vibrator: Vibrator
private lateinit var vibratorTask: AsyncTaskUtil.AsyncTask<Unit, Unit, Unit>
private lateinit var vibrateMethod: (Long) -> Unit
private val vibrateLength = 50L
private val mVibrationQueue = ArrayDeque<Long>()
// view
private var mEnableAir = true
private var mSimpleAir = false
private var mDebugInfo = false
private var mShowDelay = false
private var mEnableVibrate = true
private lateinit var mDelayText: TextView
private var windowWidth = 0
private var windowHeight = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_FULLSCREEN)
setImmersive()
app = application as BrokenithmApplication
vibrator = applicationContext.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vibrateMethod = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
{
vibrator.vibrate(VibrationEffect.createOneShot(it, 255))
}
} else {
{
vibrator.vibrate(it)
}
}
mDelayText = findViewById(R.id.text_delay)
val textInfo = findViewById<TextView>(R.id.text_info)
findViewById<CheckBox>(R.id.check_debug).setOnCheckedChangeListener { _, isChecked ->
mDebugInfo = isChecked
textInfo.visibility = if (isChecked) {
View.VISIBLE
} else {
View.GONE
}
}
findViewById<CheckBox>(R.id.check_vibrate).apply {
setOnCheckedChangeListener { _, isChecked ->
mEnableVibrate = isChecked
app.enableVibrate = isChecked
}
isChecked = app.enableVibrate
}
val expandControl = findViewById<ExpandableLayout>(R.id.expand_control)
val textExpand = findViewById<TextView>(R.id.text_expand)
textExpand.setOnClickListener {
if (expandControl.isExpanded) {
(it as TextView).setText(R.string.expand)
expandControl.collapse()
} else {
(it as TextView).setText(R.string.collapse)
expandControl.expand()
}
}
val dm = DisplayMetrics()
(applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.getMetrics(dm)
windowWidth = dm.widthPixels
windowHeight = dm.heightPixels
gapWidth = windowWidth.toFloat() / (numOfButtons * buttonWidthToGap + numOfGaps)
buttonWidth = gapWidth * buttonWidthToGap
//val buttonWidth = windowWidth / numOfButtons
val buttonBlockWidth = buttonWidth + gapWidth
val buttonAreaHeight = windowHeight * 0.5f
val airAreaHeight = windowHeight * 0.35f
val airBlockHeight = (buttonAreaHeight - airAreaHeight) / numOfAirBlock
mLEDBitmap = Bitmap.createBitmap(windowWidth, buttonAreaHeight.toInt(), Bitmap.Config.RGB_565)
mLEDCanvas = Canvas(mLEDBitmap)
mButtonRenderer = findViewById(R.id.button_render_area)
mButtonRenderer.background = BitmapDrawable(resources, mLEDBitmap)
findViewById<View>(R.id.touch_area).setOnTouchListener { view, event ->
if (expandControl.isExpanded)
textExpand.callOnClick()
view ?: return@setOnTouchListener view.performClick()
event ?: return@setOnTouchListener view.performClick()
val totalTouches = event.pointerCount
val touchedButtons = mutableSetOf<Int>()
var thisAirHeight = 6
if (event.action != KeyEvent.ACTION_UP && event.action != MotionEvent.ACTION_CANCEL) {
var ignoredIndex = -1
if (event.actionMasked == MotionEvent.ACTION_POINTER_UP)
ignoredIndex = event.actionIndex
for (i in 0 until totalTouches) {
if (i == ignoredIndex)
continue
val x = event.getX(i) + view.left
val y = event.getY(i) + view.top
when(y) {
in 0f..airAreaHeight -> {
thisAirHeight = 0
}
in airAreaHeight..buttonAreaHeight -> {
val curAir = ((y - airAreaHeight) / airBlockHeight).toInt()
thisAirHeight = if(mSimpleAir) 0 else thisAirHeight.coerceAtMost(curAir)
}
in buttonAreaHeight..windowHeight.toFloat() -> {
//val centerButton = (x / buttonBlockWidth).toInt() + 1
//val leftButton = (centerButton - 1).coerceAtLeast(1)
//val rightButton = (centerButton + 1).coerceAtMost(32)
//touchedButtons.addAll(listOf(leftButton, centerButton, rightButton))
//touchedButtons.addAll(listOf((centerButton * 2 - 1), centerButton * 2))
val pointPos = x / buttonBlockWidth
var index = pointPos.toInt()
if (index > numOfButtons) index = numOfButtons
var realIndex = index * 2
if (touchedButtons.contains(realIndex)) realIndex++
touchedButtons.add(realIndex)
if (index > 0) {
if ((pointPos - index) * 4 < 1) {
realIndex = (index - 1) * 2
if (touchedButtons.contains(realIndex)) realIndex++
touchedButtons.add(realIndex)
}
} else if (index < 31) {
if ((pointPos - index) * 4 > 3) {
realIndex = (index + 1) * 2
if (touchedButtons.contains(realIndex)) realIndex++
touchedButtons.add(realIndex)
}
}
}
}
}
}
else
thisAirHeight = 6
if (mEnableVibrate) {
if (hasNewKeys(mLastButtons, touchedButtons))
mVibrationQueue.add(vibrateLength)
else if (touchedButtons.isEmpty())
mVibrationQueue.clear()
}
mLastButtons = touchedButtons
mCurrentAirHeight = thisAirHeight
//mInputQueue.add(InputEvent(touchedButtons, mCurrentAirHeight))
if (mDebugInfo)
textInfo.text = getString(R.string.debug_info, mCurrentAirHeight, touchedButtons.toString(), event.toString())
view.performClick()
}
val editServer = findViewById<EditText>(R.id.edit_server).apply {
setText(app.lastServer)
}
findViewById<Button>(R.id.button_start).setOnClickListener {
val server = editServer.text.toString()
if (server.isBlank())
return@setOnClickListener
if (mExitFlag) {
if (senderTask.isActive || receiverTask.isActive)
return@setOnClickListener
mExitFlag = false
(it as Button).setText(R.string.stop)
editServer.isEnabled = false
app.lastServer = server
val address = parseAddress(server)
if (!mTCPMode)
sendConnect(address)
senderTask.execute(lifecycleScope, address)
receiverTask.execute(lifecycleScope, address)
pingPongTask.execute(lifecycleScope)
} else {
sendDisconnect(parseAddress(server))
mExitFlag = true
(it as Button).setText(R.string.start)
editServer.isEnabled = true
senderTask.cancel()
receiverTask.cancel()
pingPongTask.cancel()
}
}
findViewById<Button>(R.id.button_coin).setOnClickListener {
if(!mExitFlag)
sendFunctionKey(parseAddress(editServer.text.toString()), FUNCTION_BUTTON.FUNCTION_COIN)
}
findViewById<Button>(R.id.button_card).setOnClickListener {
if(!mExitFlag)
sendFunctionKey(parseAddress(editServer.text.toString()), FUNCTION_BUTTON.FUNCTION_CARD)
}
findViewById<CheckBox>(R.id.check_simple_air).apply {
setOnCheckedChangeListener { _, isChecked ->
mSimpleAir = isChecked
app.simpleAir = isChecked
}
isChecked = app.simpleAir
}
findViewById<View>(R.id.button_test).setOnTouchListener { view, event ->
mTestButton = when(event.actionMasked) {
MotionEvent.ACTION_MOVE, MotionEvent.ACTION_DOWN -> true
else -> false
}
mInputQueue.add(InputEvent(serviceButton = mServiceButton, testButton = mTestButton))
view.performClick()
}
findViewById<View>(R.id.button_service).setOnTouchListener { view, event ->
mServiceButton = when(event.actionMasked) {
MotionEvent.ACTION_MOVE, MotionEvent.ACTION_DOWN -> true
else -> false
}
mInputQueue.add(InputEvent(serviceButton = mServiceButton, testButton = mTestButton))
view.performClick()
}
findViewById<CheckBox>(R.id.check_show_delay).apply {
setOnCheckedChangeListener { _, isChecked ->
mShowDelay = isChecked
mDelayText.visibility = if (isChecked) View.VISIBLE else View.GONE
app.showDelay = isChecked
}
isChecked = app.showDelay
}
mTCPMode = app.tcpMode
findViewById<TextView>(R.id.text_mode).apply {
text = getString(if (mTCPMode) R.string.tcp else R.string.udp)
setOnClickListener {
if (!mExitFlag)
return@setOnClickListener
text = getString(if (mTCPMode) {
mTCPMode = false
R.string.udp
} else {
mTCPMode = true
R.string.tcp
})
app.tcpMode = mTCPMode
}
}
initTasks()
//for (id in mButtonIds)
//mButtons.add(findViewById(id))
vibratorTask.execute(lifecycleScope)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus)
setImmersive()
}
private var exitTime: Long = 0
override fun onBackPressed() {
val currentTime = System.currentTimeMillis()
if (currentTime - exitTime > 1500) {
Toast.makeText(this, R.string.press_again_to_exit, Toast.LENGTH_SHORT).show()
exitTime = currentTime
} else {
finish()
}
}
private fun setImmersive() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.apply {
hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
} else {
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
}
}
private fun hasNewKeys(oldKeys: MutableSet<Int>, newKeys: MutableSet<Int>): Boolean {
for (i in newKeys)
if (!oldKeys.contains(i)) return true
return false
}
private fun parseAddress(address: String): InetSocketAddress? {
val parts = address.split(":")
return when(parts.size) {
1 -> InetSocketAddress(parts[0], serverPort)
2 -> InetSocketAddress(parts[0], parts[1].toInt())
else -> null
}
}
private fun initTasks() {
receiverTask = AsyncTaskUtil.AsyncTask.make(
doInBackground = {
val address = it[0] ?: return@make
if (mTCPMode) {
val buffer = ByteArray(256)
while (!mExitFlag) {
if (!mTCPSocket.isConnected || mTCPSocket.isClosed) {
Thread.sleep(50)
continue
}
try {
val dataSize = mTCPSocket.getInputStream().read(buffer, 0, 256)
if (dataSize >= 3) {
if (dataSize >= 100 && buffer[1] == 'L'.toByte() && buffer[2] == 'E'.toByte() && buffer[3] == 'D'.toByte()) {
setLED(buffer)
}
if (dataSize >= 4 && buffer[1] == 'P'.toByte() && buffer[2] == 'O'.toByte() && buffer[3] == 'N'.toByte()) {
val delay = calculateDelay(buffer)
if (delay > 0f)
mCurrentDelay = delay
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
} else {
val socket = try {
DatagramSocket(52468).apply {
reuseAddress = true
soTimeout = 1000
}
} catch (e: BindException) {
e.printStackTrace()
return@make
}
val buffer = ByteArray(256)
val packet = DatagramPacket(buffer, buffer.size)
while (!mExitFlag) {
try {
socket.receive(packet)
if (packet.address.hostAddress == address.hostString && packet.port == address.port) {
val data = packet.data
if (data.size >= 3) {
if (data.size >= 100 && data[1] == 'L'.toByte() && data[2] == 'E'.toByte() && data[3] == 'D'.toByte()) {
setLED(data)
}
if (data.size >= 4 && data[1] == 'P'.toByte() && data[2] == 'O'.toByte() && data[3] == 'N'.toByte()) {
val delay = calculateDelay(data)
if (delay > 0f)
mCurrentDelay = delay
}
}
}
} catch (e: SocketTimeoutException) {
// ignore, try again
}
}
socket.close()
}
}
)
senderTask = AsyncTaskUtil.AsyncTask.make(
doInBackground = {
val address = it[0] ?: return@make
if (mTCPMode) {
if (mTCPSocket.isClosed)
mTCPSocket = Socket()
if (!mTCPSocket.isConnected)
mTCPSocket.connect(address)
while (!mExitFlag) {
if (mShowDelay)
sendTCPPing()
val buttons = InputEvent(mLastButtons, mCurrentAirHeight, mTestButton, mServiceButton)
val buffer = applyKeys(buttons, IoBuffer())
try {
mTCPSocket.getOutputStream().apply {
write(constructBuffer(buffer))
flush()
}
} catch (e: Exception) {
e.printStackTrace()
continue
}
Thread.sleep(1)
}
} else {
val socket = DatagramSocket()
socket.connect(address)
while (!mExitFlag) {
if (mShowDelay)
sendPing(address)
//while (!mInputQueue.isEmpty() && mInputQueue.peek() == null)
//mInputQueue.pop()
//val buttons = mInputQueue.poll()
val buttons = InputEvent(mLastButtons, mCurrentAirHeight, mTestButton, mServiceButton)
if (buttons != null/* || mLastAirHeight != mCurrentAirHeight*/) {
val buffer = applyKeys(buttons/* ?: InputEvent()*/, IoBuffer())
val packet = constructPacket(buffer)
try {
socket.send(packet)
} catch (e: Exception) {
e.printStackTrace()
Thread.sleep(100)
continue
}
}
Thread.sleep(1)
}
socket.close()
}
}
)
pingPongTask = AsyncTaskUtil.AsyncTask.make(
doInBackground = {
while (!mExitFlag) {
if (!mShowDelay) {
Thread.sleep(250)
continue
}
if (mCurrentDelay >= 0f) {
runOnUiThread { mDelayText.text = getString(R.string.current_latency, mCurrentDelay) }
}
Thread.sleep(200)
}
}
)
vibratorTask = AsyncTaskUtil.AsyncTask.make(
doInBackground = {
while (true) {
if (!mEnableVibrate) {
Thread.sleep(250)
continue
}
val next = mVibrationQueue.poll()
if (next != null)
vibrateMethod(next)
Thread.sleep(10)
}
}
)
}
enum class FUNCTION_BUTTON {
UNDEFINED, FUNCTION_COIN, FUNCTION_CARD
}
class IoBuffer {
var length: Int = 0
var header = ByteArray(3)
var air = ByteArray(6)
var slider = ByteArray(32)
var testBtn = false
var serviceBtn = false
}
private fun sendAir(server: String, port: Int) {
val address = InetSocketAddress(server, port)
val socket = DatagramSocket()
val buffer = byteArrayOf(0x04, 'A'.toByte(), 'I'.toByte(), 'R'.toByte(), if (mEnableAir) 0x01 else 0x00)
val packet = DatagramPacket(buffer, buffer.size)
socket.apply {
connect(address)
send(packet)
close()
}
}
private fun getLocalIPAddress(useIPv4: Boolean): String {
try {
val interfaces: List<NetworkInterface> = Collections.list(NetworkInterface.getNetworkInterfaces())
for (intf in interfaces) {
val addrs: List<InetAddress> = Collections.list(intf.inetAddresses)
for (addr in addrs) {
if (!addr.isLoopbackAddress) {
val sAddr = addr.hostAddress
val isIPv4 = sAddr.indexOf(':') < 0
if (useIPv4) {
if (isIPv4) return sAddr
} else {
if (!isIPv4) {
val delim = sAddr.indexOf('%') // drop ip6 zone suffix
return if (delim < 0) sAddr.toUpperCase(Locale.ROOT) else sAddr.substring(0, delim).toUpperCase(Locale.ROOT)
}
}
}
}
}
} catch (e: Exception) {
}
return ""
}
private fun sendConnect(address: InetSocketAddress?) {
address ?: return
thread {
val selfAddress = getLocalIPAddress(true)
val buffer = ByteArray(24)
byteArrayOf(23, 'C'.toByte(), 'O'.toByte(), 'N'.toByte()).copyInto(buffer)
selfAddress.toByteArray().copyInto(buffer, 4)
serverPort.toString().toByteArray().copyInto(buffer, 4 + 15)
val socket = DatagramSocket()
val packet = DatagramPacket(buffer, buffer.size)
socket.apply {
connect(address)
send(packet)
close()
}
}
}
private fun sendDisconnect(address: InetSocketAddress?) {
address ?: return
thread {
val buffer = byteArrayOf(3, 'D'.toByte(), 'I'.toByte(), 'S'.toByte())
if (mTCPMode) {
try {
mTCPSocket.getOutputStream().write(buffer)
} catch (e: Exception) {
e.printStackTrace()
}
mTCPSocket.close()
} else {
val socket = DatagramSocket()
val packet = DatagramPacket(buffer, buffer.size)
socket.apply {
connect(address)
send(packet)
close()
}
}
}
}
private fun sendFunctionKey(address: InetSocketAddress?, function: FUNCTION_BUTTON) {
address ?: return
thread {
val buffer = byteArrayOf(4, 'F'.toByte(), 'N'.toByte(), 'C'.toByte(), function.ordinal.toByte())
if (mTCPMode) {
try {
mTCPSocket.getOutputStream().write(buffer)
} catch (e: Exception) {
e.printStackTrace()
}
} else {
val socket = DatagramSocket()
val packet = DatagramPacket(buffer, buffer.size)
socket.apply {
connect(address)
send(packet)
close()
}
}
}
}
private val pingInterval = 100L
private var lastPingTime = 0L
private fun sendPing(address: InetSocketAddress?) {
address ?: return
if (System.currentTimeMillis() - lastPingTime < pingInterval) return
lastPingTime = System.currentTimeMillis()
val buffer = ByteArray(12)
byteArrayOf(11, 'P'.toByte(), 'I'.toByte(), 'N'.toByte()).copyInto(buffer)
ByteBuffer.wrap(buffer, 4, 8).putLong(SystemClock.elapsedRealtimeNanos())
val socket = DatagramSocket()
val packet = DatagramPacket(buffer, buffer.size)
socket.apply {
connect(address)
send(packet)
close()
}
}
private fun sendTCPPing() {
if (System.currentTimeMillis() - lastPingTime < pingInterval) return
lastPingTime = System.currentTimeMillis()
val buffer = ByteArray(12)
byteArrayOf(11, 'P'.toByte(), 'I'.toByte(), 'N'.toByte()).copyInto(buffer)
ByteBuffer.wrap(buffer, 4, 8).putLong(SystemClock.elapsedRealtimeNanos())
try {
mTCPSocket.getOutputStream().write(buffer)
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun calculateDelay(data: ByteArray): Float {
val currentTime = SystemClock.elapsedRealtimeNanos()
val lastPingTime = ByteBuffer.wrap(data).getLong(4)
return (currentTime - lastPingTime) / 2000000.0f
}
private fun constructBuffer(buffer: IoBuffer): ByteArray {
val realBuf = ByteArray(44)
realBuf[0] = buffer.length.toByte()
buffer.header.copyInto(realBuf, 1)
buffer.air.copyInto(realBuf, 4)
buffer.slider.copyInto(realBuf, 10)
realBuf[42] = if (buffer.testBtn) 0x01 else 0x00
realBuf[43] = if (buffer.serviceBtn) 0x01 else 0x00
return realBuf
}
private fun constructPacket(buffer: IoBuffer): DatagramPacket {
val realBuf = constructBuffer(buffer)
return DatagramPacket(realBuf, buffer.length + 1)
}
private val airUpdateInterval = 10L
private var mLastAirHeight = 6
private var mLastAirUpdateTime = 0L
private fun applyKeys(event: InputEvent, buffer: IoBuffer): IoBuffer {
return buffer.apply {
buffer.length = 43
buffer.header = byteArrayOf('I'.toByte(), 'N'.toByte(), 'P'.toByte())
if (event.keys != null && event.keys.isNotEmpty()) {
for (i in 0 until 32) {
buffer.slider[31 - i] = if (event.keys.contains(i)) 0x80.toByte() else 0x0
}
}
val currentTime = System.currentTimeMillis()
if (currentTime - mLastAirUpdateTime > airUpdateInterval) {
mLastAirHeight += if (mLastAirHeight < mCurrentAirHeight) 1 else if (mLastAirHeight > mCurrentAirHeight) -1 else 0
mLastAirUpdateTime = currentTime
}
if (mLastAirHeight != 6) {
for (i in mLastAirHeight..5) {
buffer.air[mAirIdx[i]] = 1
}
}
buffer.serviceBtn = event.serviceButton
buffer.testBtn = event.testButton
}
}
private fun setLED(status: ByteArray) {
val blockCount = numOfButtons + numOfGaps
val steps = 32 / blockCount
val offset = 4
var drawXOffset = 0f
val drawHeight = mLEDBitmap.height
for (i in (blockCount - 1).downTo(0)) {
val index = offset + (i * steps * 3)
val blue = status[index].toInt() and 0xff
val red = status[index + 1].toInt() and 0xff
val green = status[index + 2].toInt() and 0xff
val color = 0xff000000 or (red.toLong() shl 16) or (green.toLong() shl 8) or blue.toLong()
val left = drawXOffset
val width = when(i.rem(2)) {
0 -> buttonWidth
1 -> gapWidth
else -> continue
}
val right = left + width
mLEDCanvas.drawRect(left, 0f, right, drawHeight.toFloat(), makePaint(color.toInt()))
drawXOffset += width
}
mButtonRenderer.postInvalidate()
}
private fun makePaint(color: Int): Paint {
return Paint().apply { this.color = color }
}
}

View File

@ -0,0 +1,138 @@
package com.github.brokenithm.util
import kotlinx.coroutines.*
@Suppress("unused")
object AsyncTaskUtil {
fun <R> CoroutineScope.executeAsyncTask(
onPreExecute: () -> Unit = {},
doInBackground: () -> R,
onPostExecute: (R) -> Unit = {},
onCancelled: () -> Unit = {}
) = launch {
try {
onPreExecute() // runs in Main Thread
val result = withContext(Dispatchers.IO) {
doInBackground() // runs in background thread without blocking the Main Thread
}
onPostExecute(result) // runs in Main Thread
} catch (e: CancellationException) {
onCancelled()
}
}
fun <P, R> CoroutineScope.executeAsyncTask(
onPreExecute: () -> Unit = {},
doInBackground: suspend (suspend (P) -> Unit) -> R,
onPostExecute: (R) -> Unit = {},
onProgressUpdate: (P) -> Unit,
onCancelled: () -> Unit = {}
) = launch {
try {
onPreExecute()
val result = withContext(Dispatchers.IO) {
doInBackground {
withContext(Dispatchers.Main) { onProgressUpdate(it) }
}
}
onPostExecute(result)
} catch (e: CancellationException) {
onCancelled()
}
}
fun CoroutineScope.executeDelayedTask(
task: () -> Unit,
delayMillis: Long,
onCancelled: () -> Unit = {}
) = launch {
try {
delay(delayMillis)
withContext(Dispatchers.Main) { task() }
} catch (e: CancellationException) {
onCancelled()
}
}
fun <A, P, R> CoroutineScope.executeAsyncTask(task: AsyncTask<A, P, R>, vararg arguments: A) = launch {
try {
task.onPreExecute()
val result = withContext(Dispatchers.IO) {
task.doInBackground(*arguments)
}
task.onPostExecute(result)
} catch (e: CancellationException) {
task.onCancelled()
}
}
abstract class AsyncTask<A, P, R> private constructor() {
open fun onPreExecute() {}
abstract suspend fun doInBackground(vararg argument: A): R
open fun onPostExecute(result: R) {}
open fun onCancelled() {}
open fun onProgressUpdate(progress: P) {}
protected fun publishProgress(progress: P) { onProgressUpdate(progress) }
private var mJob: Job? = null
val isCompleted: Boolean
get() = mJob?.isCompleted ?: false
val isActive: Boolean
get() = mJob?.isActive ?: false
val isCancelled: Boolean
get() = mJob?.isCancelled ?: false
fun execute(scope: CoroutineScope, vararg argument: A) {
if (mJob != null && (!mJob!!.isCompleted || mJob!!.isActive)) {
mJob!!.cancel()
mJob = null
}
mJob = scope.executeAsyncTask(this, *argument)
}
fun cancel(exception: CancellationException? = null) {
if (mJob != null && !mJob!!.isCancelled) {
mJob!!.cancel(exception)
}
}
fun cancel(message: String, cause: Throwable? = null) {
if (mJob != null && !mJob!!.isCancelled) {
mJob!!.cancel(message, cause)
}
}
companion object {
fun <A, R> make(
onPreExecute: () -> Unit = {},
doInBackground: (Array<out A>) -> R,
onPostExecute: (R) -> Unit = {},
onCancelled: () -> Unit = {}
): AsyncTask<A, Unit, R> {
return object : AsyncTask<A, Unit, R>() {
override fun onPreExecute() { onPreExecute() }
override suspend fun doInBackground(vararg argument: A): R { return doInBackground(argument) }
override fun onPostExecute(result: R) { onPostExecute(result) }
override fun onCancelled() { onCancelled() }
}
}
fun <A, P, R> make(
onPreExecute: () -> Unit = {},
doInBackground: (Array<out A>) -> R,
onPostExecute: (R) -> Unit = {},
onProgressUpdate: (P) -> Unit = {},
onCancelled: () -> Unit = {}
): AsyncTask<A, P, R> {
return object : AsyncTask<A, P, R>() {
override fun onPreExecute() { onPreExecute() }
override suspend fun doInBackground(vararg argument: A): R { return doInBackground(argument) }
override fun onPostExecute(result: R) { onPostExecute(result) }
override fun onProgressUpdate(progress: P) { onProgressUpdate(progress) }
override fun onCancelled() { onCancelled() }
}
}
}
}
}

View File

@ -0,0 +1,30 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<stroke android:color="@color/white" android:width="1dp" />
<corners android:radius="5dp" />
<padding android:left="14dp" android:top="14dp" android:right="14dp" android:bottom="14dp" />
</shape>
</item>
</selector>

View File

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<padding android:left="8dp" android:top="8dp" android:right="8dp" android:bottom="8dp" />
<solid android:color="#444444" />
<corners android:radius="8dp" />
</shape>
</item>
</selector>

View File

@ -0,0 +1,260 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/button_area_upper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5" />
<View
android:id="@+id/button_render_area"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/button_area_upper" />
<View
android:id="@+id/button_area_delim"
android:layout_width="0dp"
android:layout_height="1dp"
android:background="@color/white"
app:layout_constraintBottom_toTopOf="@+id/button_area_upper"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/touch_area_upper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.2" />
<View
android:id="@+id/touch_area"
android:layout_width="0dp"
android:layout_height="0dp"
android:clickable="true"
android:focusable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/touch_area_upper"
app:layout_constraintVertical_bias="1.0" />
<TextView
android:id="@+id/text_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:textColor="@color/white"
android:visibility="visible"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/touch_area_upper"
tools:text="TextView" />
<TextView
android:id="@+id/text_delay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="12dp"
android:textColor="@color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/expand_control" />
<net.cachapa.expandablelayout.ExpandableLayout
android:id="@+id/expand_control"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:el_duration="500"
app:el_expanded="true"
app:el_parallax="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#222222"
android:clickable="true"
android:focusable="true"
android:paddingBottom="8dp">
<Button
android:id="@+id/button_coin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/coin"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button_card"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/card"
app:layout_constraintStart_toEndOf="@+id/button_coin"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="@+id/check_simple_air"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/simple_air"
android:textColor="@color/white"
app:layout_constraintStart_toEndOf="@+id/button_card"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.textfield.TextInputLayout
android:layout_width="195dp"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginEnd="16dp"
android:textColorHint="@color/white"
app:boxBackgroundColor="#7f7f7f"
app:layout_constraintEnd_toStartOf="@+id/button_start"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/edit_server"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/address"
android:importantForAutofill="no"
android:inputType="textUri"
android:textColor="@color/white" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="@+id/button_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="@string/start"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="@+id/check_debug"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/show_debug_info"
android:textColor="@color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button_coin" />
<TextView
android:id="@+id/button_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:background="@drawable/highlight_border_1dp"
android:text="@string/test"
android:textColor="@color/white"
android:clickable="true"
android:focusable="true"
app:layout_constraintStart_toEndOf="@id/check_debug"
app:layout_constraintTop_toTopOf="@+id/check_debug" />
<TextView
android:id="@+id/button_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:background="@drawable/highlight_border_1dp"
android:text="@string/service"
android:textColor="@color/white"
android:clickable="true"
android:focusable="true"
app:layout_constraintStart_toEndOf="@id/button_test"
app:layout_constraintTop_toTopOf="@id/button_test" />
<CheckBox
android:id="@+id/check_show_delay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="@string/show_delay"
android:textColor="@color/white"
app:layout_constraintStart_toEndOf="@+id/button_service"
app:layout_constraintTop_toTopOf="@+id/button_service" />
<CheckBox
android:id="@+id/check_vibrate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="@string/enable_vibration"
android:textColor="@color/white"
app:layout_constraintStart_toEndOf="@+id/check_show_delay"
app:layout_constraintTop_toTopOf="@+id/check_show_delay" />
<TextView
android:id="@+id/text_mode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:background="#444444"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
android:padding="8dp"
android:text="UDP"
android:textColor="@color/white"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@+id/check_vibrate"
app:layout_constraintStart_toEndOf="@+id/check_vibrate"
app:layout_constraintTop_toTopOf="@+id/check_vibrate" />
</androidx.constraintlayout.widget.ConstraintLayout>
</net.cachapa.expandablelayout.ExpandableLayout>
<TextView
android:id="@+id/text_expand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="@drawable/round_gray_button"
android:clickable="true"
android:focusable="true"
android:text="@string/collapse"
android:textColor="@color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/expand_control" />
<TextView
android:id="@+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:background="@color/black"
android:text="@string/title"
android:textColor="@color/white"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/expand_control" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@ -0,0 +1,16 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Brokenithm" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_200</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/black</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_200</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>

View File

@ -0,0 +1,24 @@
<resources>
<string name="app_name">Brokenithm</string>
<string name="title">Brokenithm-Evolved</string>
<string name="start">Start</string>
<string name="stop">Stop</string>
<string name="coin">coin</string>
<string name="card">card</string>
<string name="simple_air">Simple Air</string>
<string name="expand"> Control ↓ </string>
<string name="collapse"> Control ↑ </string>
<string name="test">Test</string>
<string name="service">Service</string>
<string name="show_debug_info">Show Debug Info</string>
<string name="debug_info">touched: air:%d %s\n%s</string>
<string name="current_latency">Current Latency: %f ms</string>
<string name="press_again_to_exit">Press again to exit</string>
<string name="show_delay">Show Delay</string>
<string name="address">Address</string>
<string name="enable_vibration">Enable Vibration</string>
<string name="tcp">TCP</string>
<string name="udp">UDP</string>
</resources>

View File

@ -0,0 +1,16 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Brokenithm" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>

View File

@ -0,0 +1,17 @@
package com.github.brokenithm
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}

26
build.gradle 100644
View File

@ -0,0 +1,26 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.30"
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.2"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

21
gradle.properties 100644
View File

@ -0,0 +1,21 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official

BIN
gradle/wrapper/gradle-wrapper.jar vendored 100644

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Fri Feb 26 15:00:15 CST 2021
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip

172
gradlew vendored 100644
View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
gradlew.bat vendored 100644
View File

@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

2
settings.gradle 100644
View File

@ -0,0 +1,2 @@
include ':app'
rootProject.name = "Brokenithm"