91 lines
2.8 KiB
Kotlin
91 lines
2.8 KiB
Kotlin
package org.pupes.mhdrunpathfinder
|
|
|
|
import android.app.Activity
|
|
import android.os.Handler
|
|
import android.os.Looper
|
|
import android.widget.Toast
|
|
import kotlinx.serialization.Serializable
|
|
import kotlinx.serialization.json.Json
|
|
import okhttp3.OkHttpClient
|
|
import ovh.plrapps.mapcompose.api.moveMarker
|
|
import java.net.URL
|
|
|
|
@Serializable
|
|
data class HaukResponse(
|
|
val type: Int,
|
|
val expire: Long,
|
|
val serverTime: Double,
|
|
val interval: Int,
|
|
val points: List<List<Double?>>,
|
|
val encrypted: Boolean,
|
|
val salt: String? = null
|
|
)
|
|
|
|
|
|
// OkHttpClient for making HTTP requests
|
|
val haukhttpClient = OkHttpClient.Builder()
|
|
.build()
|
|
|
|
private val HaukMainHandler = Handler(Looper.getMainLooper())
|
|
private var HaukTrackingThread: Thread? = null
|
|
private var HaukIsTracking = false
|
|
|
|
private fun fetchHaukPosition(haukUrl: String, callee: Activity) {
|
|
try {
|
|
val url = URL(haukUrl)
|
|
val targetId = url.toString().substringAfter("?")
|
|
|
|
val request = okhttp3.Request.Builder()
|
|
.url("${url.protocol}://${url.host}/api/fetch.php?id=$targetId")
|
|
.header("User-Agent", "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME} (Android)")
|
|
.build()
|
|
|
|
haukhttpClient.newCall(request).execute().use { response ->
|
|
var message = if (response.isSuccessful) {
|
|
response.body?.string() ?: "Empty response"
|
|
} else {
|
|
"Error: ${response.code} ${response.message}"
|
|
}
|
|
|
|
message = "{" + message.substringAfter("{");
|
|
val hauk_response = json.decodeFromString<HaukResponse>(message)
|
|
|
|
val lat = hauk_response.points.last()?.getOrNull(0)
|
|
val lon = hauk_response.points.last()?.getOrNull(1)
|
|
if (lat != null && lon != null) {
|
|
HaukMainHandler.post {
|
|
mapState.moveMarker("target_position", x = longitudeToXNormalized(lon), y = latitudeToYNormalized(lat))
|
|
}
|
|
} else {
|
|
Toast.makeText(callee, "TARGET LOCATION NOT AVAILABLE", Toast.LENGTH_SHORT).show()
|
|
}}
|
|
} catch (e: Exception) {
|
|
// Post UI update to main thread
|
|
HaukMainHandler.post {
|
|
Toast.makeText(callee, e.message ?: "Unknown error", Toast.LENGTH_SHORT).show()
|
|
}
|
|
}
|
|
}
|
|
|
|
// Start the timer with a URL:
|
|
fun startHaukTracking(url: String, callee: Activity) {
|
|
if (HaukIsTracking) return
|
|
|
|
HaukIsTracking = true
|
|
HaukTrackingThread = Thread {
|
|
while (HaukIsTracking) {
|
|
fetchHaukPosition(url, callee)
|
|
try {
|
|
Thread.sleep(1000) // Wait 1 second between requests
|
|
} catch (e: InterruptedException) {
|
|
break
|
|
}
|
|
}
|
|
}.apply { start() }
|
|
}
|
|
|
|
fun stopHaukTracking() {
|
|
HaukIsTracking = false
|
|
HaukTrackingThread?.interrupt()
|
|
HaukTrackingThread = null
|
|
} |