This commit is contained in:
zyp
2026-09-29 19:41:00 +08:00
parent 5d05a27cfc
commit 4254036fad
47 changed files with 4048 additions and 2789 deletions
+2
View File
@@ -19,6 +19,8 @@ ext {
deps.rx2Java = 'io.reactivex.rxjava2:rxjava:2.2.4' // 目前在CSDK升级模块中使用rxjava2
deps.maplibreTurf = 'org.maplibre.gl:android-sdk-turf:5.9.1'
deps.maplibreSdk = 'org.maplibre.gl:android-sdk:10.3.5'
deps.amapSdk = 'com.amap.api:3dmap:10.0.600'
deps.baiduMapSdk = 'com.baidu.lbsyun:BaiduMapSDK_Map:8.2.0'
deps.lottie = 'com.airbnb.android:lottie:3.3.1'//RTK扫描页中使用,用于实现动画效果
deps.cardview = 'androidx.cardview:cardview:1.0.0'//PopoverView中使用
deps.material = 'com.google.android.material:material:1.0.0'//AvoidanceShortcutWidget使用
+1 -1
View File
@@ -1,6 +1,6 @@
# App 服务部署配置(UTF-8)。换服务器后修改此文件,再重新打包并安装 APK。
# 平台入口,支持 http/https、端口和页面路径;登录接口仍使用 /saas 和 /dji。
CLOUD_BASE_URL=https://c2.zklhjs.com/p
CLOUD_BASE_URL=https://uav.zklhjs.com/p
# 平台域名的备用直连 IP/主机名(不要写协议、端口或路径);留空关闭备用直连。
# HTTP 备用请求保留平台域名作为 Host;MQTT 保留服务端返回地址的协议和端口。
+1 -1
View File
@@ -3,6 +3,6 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://downloads.gradle.org/distributions/gradle-8.9-bin.zip
distributionUrl=file\:///E:/Java/Tools/Gradle/gradle-8.9-bin.zip
networkTimeout=120000
validateDistributionUrl=true
+14
View File
@@ -4,6 +4,15 @@ apply plugin: 'kotlin-kapt'
apply plugin: 'org.jetbrains.kotlin.plugin.compose'
apply from: 'deployment-config.gradle'
// Keep the map access key in local configuration, outside tracked application code.
def localMapProperties = new Properties()
def localMapPropertiesFile = rootProject.file('local.properties')
if (localMapPropertiesFile.isFile()) {
localMapPropertiesFile.withInputStream { localMapProperties.load(it) }
}
def tiandituKey = (project.findProperty('TIANDITU_KEY') ?: System.getenv('TIANDITU_KEY') ?:
localMapProperties.getProperty('TIANDITU_KEY', '')).toString().trim()
android {
namespace "dji.sampleV5.aircraft"
compileSdkVersion Integer.parseInt(project.ANDROID_COMPILE_SDK_VERSION)
@@ -20,6 +29,7 @@ android {
buildConfigField "String", "AIRCRAFT_API_KEY", "\"${project.AIRCRAFT_API_KEY}\""
buildConfigField "String", "GMAP_API_KEY", "\"${project.GMAP_API_KEY}\""
buildConfigField "String", "MAPLIBRE_TOKEN", "\"${project.MAPLIBRE_TOKEN}\""
buildConfigField 'String', 'TIANDITU_KEY', groovy.json.JsonOutput.toJson(tiandituKey)
buildConfigField "boolean", "SAFETY_FLIGHT_COMMANDS_ENABLED", "true"
ndk {
//noinspection ChromeOsAbiSupport
@@ -40,6 +50,7 @@ android {
buildTypes {
release {
minifyEnabled true
proguardFiles 'map-proguard-rules.pro'
shrinkResources false
signingConfig signingConfigs.release
}
@@ -120,6 +131,9 @@ dependencies {
/** <-----------------sample所需--------------------> **/
implementation project(':uxsdk')
implementation deps.maplibreSdk
implementation deps.amapSdk
implementation deps.baiduMapSdk
implementation deps.appcompat
implementation deps.constraintLayout
implementation deps.aacCommon
+8
View File
@@ -0,0 +1,8 @@
# Map SDKs access implementation classes through reflection and JNI.
-keep class com.amap.api.** { *; }
-keep class com.autonavi.** { *; }
-dontwarn com.amap.**
-dontwarn com.autonavi.**
-keep class com.baidu.** { *; }
-keep class vi.com.** { *; }
-dontwarn com.baidu.**
@@ -249,7 +249,7 @@ class CloudLoginClient {
}
private fun normalizeOrigin(rawUrl: String): String {
val withScheme = rawUrl.trim().ifBlank { BuildConfig.CLOUD_BASE_URL }.let {
val withScheme = PlatformHosts.migrate(rawUrl).ifBlank { BuildConfig.CLOUD_BASE_URL }.let {
if (it.startsWith("http://", true) || it.startsWith("https://", true)) it else "http://$it"
}
val uri = URI(withScheme)
@@ -265,7 +265,7 @@ class CloudLoginClient {
}
fun normalizeMqttAddress(rawAddress: String): String {
val value = rawAddress.trim()
val value = PlatformHosts.migrate(rawAddress)
if (value.isBlank()) return ""
return when {
value.startsWith("tcp://", true) ||
@@ -0,0 +1,10 @@
package com.zklh.dronecontroller.core.cloud
/** Migrate the host only; paths, protocols, ports and query parameters stay intact. */
internal object PlatformHosts {
const val Origin = "https://uav.zklhjs.com"
private val legacyHost = Regex("(?i)^(\\w+://)?c2\\.zklhjs\\.com(?=[:/?#]|$)")
fun migrate(address: String): String = legacyHost.replace(address.trim()) { match ->
match.groupValues[1] + "uav.zklhjs.com"
}
}
@@ -5,6 +5,7 @@ import dji.sampleV5.aircraft.BuildConfig
import android.net.Uri
import android.util.Log
import com.zklh.dronecontroller.core.msdk.DjiCommandResult
import com.zklh.dronecontroller.core.cloud.PlatformHosts
import dji.sdk.keyvalue.value.common.ComponentIndexType
import dji.v5.common.callback.CommonCallbacks
import dji.v5.common.error.IDJIError
@@ -300,8 +301,8 @@ class LiveStreamingService {
}
private fun JSONObject.toLiveStartConfig(): LiveStartConfig? {
val url = optObjectString("url", "address")
.ifBlank { optStringAny("rtmp_url", "rtmpUrl", "push_url", "pushUrl", "stream_url", "streamUrl") }
val url = PlatformHosts.migrate(optObjectString("url", "address")
.ifBlank { optStringAny("rtmp_url", "rtmpUrl", "push_url", "pushUrl", "stream_url", "streamUrl") })
val urlType = optIntAny(
defaultValue = if (url.startsWith("rtmp", ignoreCase = true)) UrlTypeRtmp else -1,
"url_type",
@@ -0,0 +1,111 @@
package com.zklh.dronecontroller.core.map
import java.net.URI
import com.zklh.dronecontroller.core.cloud.PlatformHosts
import org.json.JSONArray
import org.json.JSONObject
internal enum class MapProvider(val label: String) {
DEFAULT("默认(平台图层)"), PRIVATE("私有化地图"), TIANDITU("天地图"), AMAP("高德地图"), BAIDU("百度地图")
}
internal enum class MapCoordinateSystem { WGS84, GCJ02, BD09 }
internal enum class TileScheme { XYZ, TMS }
internal data class PrivateMapLayer(
val id: String = "global",
val name: String = "谷歌全球离线底图",
val url: String = "https://uav.zklhjs.com/map/Google/quanqiu/{z}/{x}/{y}.jpg",
val annotationUrl: String = "",
val coordinates: MapCoordinateSystem = MapCoordinateSystem.GCJ02,
val scheme: TileScheme = TileScheme.XYZ,
val minZoom: Int = 0,
val maxZoom: Int = 8
) {
fun validationError(): String? = when {
name.isBlank() -> "请填写图层名称"
minZoom !in 0..22 || maxZoom !in minZoom..22 -> "层级范围应为 0–22,最大层级不能小于最小层级"
!validTemplate(url) -> "瓦片地址必须是 HTTPS,包含 {z}、{x}、{y}"
annotationUrl.isNotBlank() && !validTemplate(annotationUrl) -> "标注地址必须是 HTTPS,包含 {z}、{x}、{y}"
else -> null
}
private fun validTemplate(value: String): Boolean = runCatching {
val uri = URI(value.replace("{z}", "0").replace("{x}", "0").replace("{y}", "0"))
uri.scheme == "https" && !uri.host.isNullOrBlank() && uri.userInfo == null && uri.fragment == null &&
listOf("{z}", "{x}", "{y}").all { value.contains(it) }
}.getOrDefault(false)
}
internal data class MapConfiguration(
val provider: MapProvider = MapProvider.DEFAULT,
val tiandituKey: String = "",
val amapKey: String = "",
val baiduKey: String = "",
val amapConsent: Boolean = false,
val baiduConsent: Boolean = false,
val satellite: Boolean = true,
val privateLayers: List<PrivateMapLayer> = listOf(PrivateMapLayer()),
val activeLayerId: String = "global"
) {
val activeLayer: PrivateMapLayer get() = privateLayers.firstOrNull { it.id == activeLayerId } ?: privateLayers.first()
val key: String get() = when (provider) {
MapProvider.TIANDITU -> tiandituKey
MapProvider.AMAP -> amapKey
MapProvider.BAIDU -> baiduKey
MapProvider.PRIVATE, MapProvider.DEFAULT -> ""
}
val consent: Boolean get() = when (provider) {
MapProvider.AMAP -> amapConsent
MapProvider.BAIDU -> baiduConsent
else -> true
}
val displayName: String get() = if (provider == MapProvider.PRIVATE) activeLayer.name else provider.label
val coordinateSystem: MapCoordinateSystem get() = when (provider) {
MapProvider.PRIVATE -> activeLayer.coordinates
MapProvider.AMAP -> MapCoordinateSystem.GCJ02
MapProvider.BAIDU -> MapCoordinateSystem.BD09
MapProvider.TIANDITU -> MapCoordinateSystem.WGS84
MapProvider.DEFAULT -> MapCoordinateSystem.GCJ02
}
fun validationError(): String? = when {
privateLayers.isEmpty() -> "至少保留一个私有图层"
privateLayers.map { it.id }.distinct().size != privateLayers.size -> "图层标识重复"
privateLayers.none { it.id == activeLayerId } -> "请选择有效的私有图层"
provider == MapProvider.PRIVATE -> activeLayer.validationError()
provider == MapProvider.DEFAULT -> null
key.isBlank() -> "请填写${provider.label} Key"
!consent -> "请阅读并同意地图服务的隐私政策"
else -> null
}
}
/** A single versioned document preserves all providers, even when another provider is selected. */
internal object MapConfigurationCodec {
fun encode(config: MapConfiguration): String = JSONObject()
.put("version", 1).put("provider", config.provider.name)
.put("tiandituKey", config.tiandituKey).put("amapKey", config.amapKey).put("baiduKey", config.baiduKey)
.put("amapConsent", config.amapConsent).put("baiduConsent", config.baiduConsent)
.put("satellite", config.satellite).put("activeLayerId", config.activeLayerId)
.put("layers", JSONArray(config.privateLayers.map { layer -> JSONObject()
.put("id", layer.id).put("name", layer.name).put("url", layer.url)
.put("annotationUrl", layer.annotationUrl).put("coordinates", layer.coordinates.name)
.put("scheme", layer.scheme.name).put("minZoom", layer.minZoom).put("maxZoom", layer.maxZoom)
})).toString()
fun decode(json: String): MapConfiguration {
val doc = JSONObject(json)
require(doc.getInt("version") == 1)
val layers = doc.getJSONArray("layers").let { array -> (0 until array.length()).map { index ->
val layer = array.getJSONObject(index)
PrivateMapLayer(layer.getString("id"), layer.getString("name"), PlatformHosts.migrate(layer.getString("url")),
PlatformHosts.migrate(layer.optString("annotationUrl")), MapCoordinateSystem.valueOf(layer.getString("coordinates")),
TileScheme.valueOf(layer.getString("scheme")), layer.getInt("minZoom"), layer.getInt("maxZoom"))
} }
require(layers.isNotEmpty() && layers.map { it.id }.distinct().size == layers.size)
return MapConfiguration(MapProvider.valueOf(doc.getString("provider")), doc.optString("tiandituKey"),
doc.optString("amapKey"), doc.optString("baiduKey"), doc.optBoolean("amapConsent"),
doc.optBoolean("baiduConsent"), doc.optBoolean("satellite", true), layers, doc.getString("activeLayerId"))
.also { require(layers.any { layer -> layer.id == it.activeLayerId }) }
}
}
@@ -0,0 +1,46 @@
package com.zklh.dronecontroller.core.map
import android.content.Context
import dji.sampleV5.aircraft.BuildConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
internal class MapConfigurationStore private constructor(context: Context) {
private val preferences = context.getSharedPreferences("pilot_map_configuration", Context.MODE_PRIVATE)
private val default = MapConfiguration(tiandituKey = BuildConfig.TIANDITU_KEY)
private val mutableConfiguration = MutableStateFlow(
preferences.getString("configuration", null)?.let { runCatching { MapConfigurationCodec.decode(it) }.getOrNull() } ?: default
)
val configuration = mutableConfiguration.asStateFlow()
private val lock = Mutex()
init {
// Persist host migration while retaining the selected provider and every Key.
preferences.getString("configuration", null)?.let { raw ->
runCatching { MapConfigurationCodec.decode(raw) }.getOrNull()?.let { decoded ->
val migrated = MapConfigurationCodec.encode(decoded)
if (raw != migrated) preferences.edit().putString("configuration", migrated).apply()
}
}
}
/** Publish only after a successful disk commit, so all maps switch together. */
suspend fun save(config: MapConfiguration): Boolean = lock.withLock {
withContext(Dispatchers.IO) {
val saved = preferences.edit().putString("configuration", MapConfigurationCodec.encode(config)).commit()
if (saved) mutableConfiguration.value = config
saved
}
}
companion object {
@Volatile private var instance: MapConfigurationStore? = null
fun get(context: Context): MapConfigurationStore = instance ?: synchronized(this) {
instance ?: MapConfigurationStore(context.applicationContext).also { instance = it }
}
}
}
@@ -0,0 +1,40 @@
package com.zklh.dronecontroller.core.map
import kotlin.math.*
internal data class MapPosition(val latitude: Double, val longitude: Double)
/** Display conversion only. DJI telemetry and uploaded flight coordinates remain WGS84. */
internal object MapCoordinates {
fun display(latitude: Double, longitude: Double, system: MapCoordinateSystem): MapPosition {
val original = MapPosition(latitude, longitude)
if (system == MapCoordinateSystem.WGS84) return original
val gcj = gcj02(original)
if (system == MapCoordinateSystem.GCJ02) return gcj
val x = gcj.longitude
val y = gcj.latitude
val z = sqrt(x * x + y * y) + 0.00002 * sin(y * PI * 3000.0 / 180.0)
val theta = atan2(y, x) + 0.000003 * cos(x * PI * 3000.0 / 180.0)
return MapPosition(z * sin(theta) + 0.006, z * cos(theta) + 0.0065)
}
private fun gcj02(p: MapPosition): MapPosition {
if (p.longitude !in 72.004..137.8347 || p.latitude !in 0.8293..55.8271) return p
val x = p.longitude - 105.0
val y = p.latitude - 35.0
var lat = -100.0 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(abs(x))
lat += (20 * sin(6 * x * PI) + 20 * sin(2 * x * PI)) * 2 / 3
lat += (20 * sin(y * PI) + 40 * sin(y / 3 * PI)) * 2 / 3
lat += (160 * sin(y / 12 * PI) + 320 * sin(y * PI / 30)) * 2 / 3
var lng = 300.0 + x + 2 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(abs(x))
lng += (20 * sin(6 * x * PI) + 20 * sin(2 * x * PI)) * 2 / 3
lng += (20 * sin(x * PI) + 40 * sin(x / 3 * PI)) * 2 / 3
lng += (150 * sin(x / 12 * PI) + 300 * sin(x / 30 * PI)) * 2 / 3
val rad = p.latitude / 180 * PI
val magic = 1 - 0.00669342162296594323 * sin(rad).pow(2)
val root = sqrt(magic)
lat = lat * 180 / ((6378245.0 * (1 - 0.00669342162296594323)) / (magic * root) * PI)
lng = lng * 180 / (6378245.0 / root * cos(rad) * PI)
return MapPosition(p.latitude + lat, p.longitude + lng)
}
}
@@ -0,0 +1,25 @@
package com.zklh.dronecontroller.core.map
import com.zklh.dronecontroller.core.mission.MissionPreview
import com.zklh.dronecontroller.core.telemetry.TelemetrySnapshot
internal data class MapLivePositions(val aircraft: MapPosition?, val remoteController: MapPosition?, val home: MapPosition?) {
companion object {
fun from(connected: Boolean, telemetry: TelemetrySnapshot, coordinates: MapCoordinateSystem): MapLivePositions {
fun position(valid: Boolean, lat: Double, lng: Double): MapPosition? =
if (valid && lat.isFinite() && lng.isFinite() && lat in -90.0..90.0 && lng in -180.0..180.0 &&
(lat != 0.0 || lng != 0.0)) MapCoordinates.display(lat, lng, coordinates) else null
return MapLivePositions(
position(connected && telemetry.locationValid, telemetry.latitude, telemetry.longitude),
// RC system GPS can be available before the aircraft is connected.
position(telemetry.rcLocationValid, telemetry.rcLatitude, telemetry.rcLongitude),
position(connected && telemetry.homeLocationValid, telemetry.homeLatitude, telemetry.homeLongitude)
)
}
}
/** Include live locations alongside the route so initial framing shows them together. */
fun focusPoints(mission: MissionPreview?, coordinates: MapCoordinateSystem): List<MapPosition> =
(mission?.points.orEmpty().map { MapCoordinates.display(it.latitude, it.longitude, coordinates) } +
listOfNotNull(aircraft, remoteController)).distinct()
}
@@ -0,0 +1,22 @@
package com.zklh.dronecontroller.core.map
import java.security.MessageDigest
import org.json.JSONArray
import org.json.JSONObject
internal object PlatformMapCache {
fun key(tenant: String, username: String): String = MessageDigest.getInstance("SHA-256")
.digest((tenant.trim() + "\u0000" + username.trim()).toByteArray(Charsets.UTF_8))
.joinToString("") { "%02x".format(it.toInt() and 255) }
fun encode(rows: JSONArray, fetchedAt: Long): String = JSONObject().put("version", 1)
.put("rows", rows).put("fetchedAt", fetchedAt).toString()
fun decode(json: String): Pair<PlatformMapCatalog, Long> {
val cache = JSONObject(json)
require(cache.optInt("version") == 1)
val timestamp = cache.getLong("fetchedAt")
require(timestamp > 0)
return PlatformMapSource.catalog(cache.getJSONArray("rows")) to timestamp
}
}
@@ -0,0 +1,80 @@
package com.zklh.dronecontroller.core.map
import com.zklh.dronecontroller.core.cloud.CloudLoginRequest
import com.zklh.dronecontroller.core.cloud.PlatformHosts
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import org.json.JSONArray
import org.json.JSONObject
internal data class MapApiRequest(val url: String, val headers: Map<String, String> = emptyMap(), val body: JSONObject? = null)
/** SaaS bearer tokens differ from DJI x-auth-token. Never persist or log them. */
internal class PlatformMapClient(private val transport: (MapApiRequest) -> JSONObject = ::httpRequest) {
fun fetch(request: CloudLoginRequest): JSONArray {
val root = PlatformHosts.Origin + "/saas/admin-api/system"
val tenantName = request.tenantName.trim()
val tenant = if (tenantName.toLongOrNull() != null) tenantName else
checked(transport(MapApiRequest("$root/tenant/get-id-by-name?name=${URLEncoder.encode(tenantName, "UTF-8")}")))
.get("data").toString()
require(tenant != "null" && tenant.isNotBlank()) { "未找到平台租户,请检查云平台登录配置" }
fun login(): String = checked(transport(MapApiRequest("$root/auth/login", mapOf("tenant-id" to tenant),
JSONObject().put("username", request.username).put("password", request.password))))
.getJSONObject("data").getString("accessToken").also { require(it.isNotBlank()) { "平台登录未返回访问令牌" } }
var token = login()
val rows = JSONArray()
val seen = mutableSetOf<String>()
var page = 1
while (true) {
val url = "$root/map-layer/page?pageNo=$page&pageSize=20&current=$page&name=&layerType=&mapType="
fun getPage() = transport(MapApiRequest(url, mapOf("tenant-id" to tenant, "Authorization" to "Bearer $token")))
var response = getPage()
if (response.optInt("code") == 401) { token = login(); response = getPage() }
val data = checked(response).getJSONObject("data")
val list = data.getJSONArray("list")
val total = data.getInt("total")
require(total >= 0) { "平台图层分页数据异常" }
var added = 0
for (index in 0 until list.length()) {
val row = list.getJSONObject(index)
if (seen.add(row.get("id").toString())) { rows.put(row); added++ }
}
if (rows.length() >= total) return rows
require(added > 0 && page < 10000) { "平台图层分页未返回完整列表,请重试" }
page++
}
}
private fun checked(response: JSONObject): JSONObject {
when (response.optInt("code", -1)) {
0 -> return response
401, 403 -> error("平台图层鉴权失败,请检查云平台账号和租户权限")
else -> error("平台图层接口返回错误(${response.optInt("code", -1)})")
}
}
companion object {
private fun httpRequest(request: MapApiRequest): JSONObject {
val connection = (URL(request.url).openConnection() as HttpURLConnection).apply {
connectTimeout = 10000
readTimeout = 15000
instanceFollowRedirects = false
setRequestProperty("Accept", "application/json")
request.headers.forEach { (name, value) -> setRequestProperty(name, value) }
}
try {
request.body?.let { body ->
connection.requestMethod = "POST"
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
connection.outputStream.use { it.write(body.toString().toByteArray(Charsets.UTF_8)) }
}
val status = connection.responseCode
if (status == 401 || status == 403) return JSONObject().put("code", status)
check(status in 200..299) { "平台图层请求失败(HTTP $status)" }
return connection.inputStream.bufferedReader(Charsets.UTF_8).use { JSONObject(it.readText()) }
} finally { connection.disconnect() }
}
}
}
@@ -0,0 +1,94 @@
package com.zklh.dronecontroller.core.map
import android.content.Context
import com.zklh.dronecontroller.core.cloud.CloudLoginRequest
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
internal data class PlatformMapState(
val catalog: PlatformMapCatalog = PlatformMapCatalog(),
val loading: Boolean = false,
val cached: Boolean = false,
val fetchedAt: Long = 0,
val error: String? = null
)
internal class PlatformMapRepository private constructor(context: Context) {
private val prefs = context.getSharedPreferences("pilot_platform_map_cache", Context.MODE_PRIVATE)
private val mutableState = MutableStateFlow(PlatformMapState())
val state = mutableState.asStateFlow()
private val lock = Mutex()
private var credentials: CloudLoginRequest? = null
private var identity = ""
private var generation = 0
private var lastAttemptAt = 0L
/** Partition cached catalogs by tenant and account; never cache authentication tokens. */
fun configure(request: CloudLoginRequest) {
if (credentials == request) return
credentials = request
generation++
lastAttemptAt = 0L
val next = PlatformMapCache.key(request.tenantName, request.username)
if (identity != next) {
identity = next
mutableState.value = prefs.getString(next, null)?.let { json -> runCatching {
val cache = PlatformMapCache.decode(json)
PlatformMapState(cache.first, cached = true, fetchedAt = cache.second)
}.getOrNull() } ?: PlatformMapState()
}
}
fun clearCredentials() {
credentials = null
generation++
mutableState.value = mutableState.value.copy(loading = false, cached = true, error = "请登录云平台后刷新图层")
}
suspend fun refresh(force: Boolean = false) = lock.withLock {
val current = mutableState.value
// Multiple full-screen/PIP maps share one request, including when offline.
if (!force && System.currentTimeMillis() - lastAttemptAt < 30000) return@withLock
if (!force && !current.cached && current.fetchedAt > 0 && System.currentTimeMillis() - current.fetchedAt < 300000) return@withLock
val request = credentials ?: run {
mutableState.value = current.copy(error = "请先填写云平台登录账号,再刷新默认图层")
return@withLock
}
val revision = generation
val cacheKey = identity
lastAttemptAt = System.currentTimeMillis()
mutableState.value = current.copy(loading = true, error = null)
try {
val result = withContext(Dispatchers.IO) {
val rows = PlatformMapClient().fetch(request)
val catalog = PlatformMapSource.catalog(rows)
// A broken response must not replace the last usable catalog.
check(rows.length() == 0 || catalog.layers.isNotEmpty() || catalog.issues.isEmpty()) { "平台未返回可用图层,请检查图层配置" }
Triple(rows, catalog, System.currentTimeMillis())
}
if (generation != revision) return@withLock
val saved = withContext(Dispatchers.IO) { prefs.edit().putString(cacheKey,
PlatformMapCache.encode(result.first, result.third)).commit() }
if (generation == revision) mutableState.value = PlatformMapState(result.second, fetchedAt = result.third,
error = if (saved) null else "图层已加载,本地缓存写入失败")
} catch (cancelled: CancellationException) {
if (generation == revision) mutableState.value = current.copy(loading = false)
throw cancelled
} catch (_: Exception) {
if (generation == revision) mutableState.value = current.copy(loading = false, cached = current.fetchedAt > 0,
error = "图层获取失败,请检查网络、云平台账号和图层权限" + if (current.fetchedAt > 0) ";正在使用上次配置" else "")
}
}
companion object {
@Volatile private var instance: PlatformMapRepository? = null
fun get(context: Context): PlatformMapRepository = instance ?: synchronized(this) {
instance ?: PlatformMapRepository(context.applicationContext).also { instance = it }
}
}
}
@@ -0,0 +1,129 @@
package com.zklh.dronecontroller.core.map
import com.zklh.dronecontroller.core.cloud.PlatformHosts
import org.json.JSONArray
import org.json.JSONObject
internal data class MapLayerBounds(val west: Double, val south: Double, val east: Double, val north: Double) {
fun valid() = listOf(west, south, east, north).all { it.isFinite() } &&
west >= -180 && east <= 180 && south >= -90 && north <= 90 && west < east && south < north
fun json() = JSONArray(listOf(west, south, east, north))
}
internal data class PlatformMapLayer(
val id: String,
val name: String,
val url: String,
val coordinates: MapCoordinateSystem,
val scheme: TileScheme,
val minZoom: Int,
val maxZoom: Int,
val bounds: MapLayerBounds?,
val opacity: Double,
val zIndex: Double,
val sort: Double
)
internal data class PlatformMapCatalog(
val layers: List<PlatformMapLayer> = emptyList(),
val issues: List<String> = emptyList(),
val total: Int = 0
) {
val coordinates: MapCoordinateSystem get() = layers.firstOrNull()?.coordinates ?: MapCoordinateSystem.GCJ02
}
internal object PlatformMapSource {
/** Accept the platform's legacy config strings without evaluating any code. */
fun configJson(text: String): JSONObject {
if (text.isBlank()) return JSONObject()
// Remove trailing commas only outside strings; never alter signed URLs.
var quoted = false
var escaped = false
val normalized = buildString {
text.forEachIndexed { index, char ->
if (quoted) {
append(char)
if (escaped) escaped = false
else if (char == '\\') escaped = true
else if (char == '"') quoted = false
} else {
if (char == '"') quoted = true
val next = if (char == ',') text.drop(index + 1).firstOrNull { !it.isWhitespace() } else null
if (char != ',' || (next != null && next != '}' && next != ']')) append(char)
}
}
}
return JSONObject(normalized)
}
fun catalog(rows: JSONArray): PlatformMapCatalog {
val issues = mutableListOf<String>()
val layers = mutableListOf<PlatformMapLayer>()
for (index in 0 until rows.length()) {
val row = rows.getJSONObject(index)
// The platform uses 0=enabled, 1=disabled. Load every enabled layer,
// including entries which are not individually marked defaultShow.
if (row.optInt("status", 0) != 0 || row.optBoolean("deleted", false)) continue
val name = row.optString("name", "图层 ${index + 1}")
runCatching { parse(row) }.onSuccess { layers += it }.onFailure {
issues += "$name:配置不完整或不支持当前瓦片类型"
}
}
val ordered = layers.sortedWith(compareBy<PlatformMapLayer> { it.zIndex }.thenBy { it.sort }.thenBy { it.id })
val coordinates = ordered.firstOrNull()?.coordinates
val compatible = ordered.filter {
(it.coordinates == coordinates).also { same ->
if (!same) issues += "${it.name}:坐标系与底图不同,暂未叠加"
}
}
return PlatformMapCatalog(compatible, issues, rows.length())
}
private fun parse(row: JSONObject): PlatformMapLayer {
val config = configJson(row.optString("configJson"))
val name = row.optString("name").ifBlank { config.optString("name") }
val url = PlatformHosts.migrate(row.optString("url").ifBlank { config.optString("url") }.replace("&amp;", "&"))
val type = config.optString("type", "xyz").lowercase()
require(type == "xyz" || type == "tms")
val scheme = if (type == "tms" || config.optString("scheme").equals("tms", true)) TileScheme.TMS else TileScheme.XYZ
val crs = row.optString("chinaCrs").ifBlank { row.optString("chinaCRS") }
.ifBlank { config.optString("chinaCRS", "WGS84") }.uppercase().replace("-", "")
val coordinates = MapCoordinateSystem.valueOf(crs)
val min = if (!row.isNull("minZoom")) row.getInt("minZoom") else config.optInt("minimumLevel", 0)
val max = if (!row.isNull("maxZoom")) row.getInt("maxZoom") else config.optInt("maximumLevel", 18)
require(PrivateMapLayer(name = name, url = url, minZoom = min, maxZoom = max).validationError() == null)
val bounds = config.optJSONObject("rectangle")?.let {
MapLayerBounds(it.getDouble("xmin"), it.getDouble("ymin"), it.getDouble("xmax"), it.getDouble("ymax"))
.also { bounds -> require(bounds.valid()) }
}
val opacity = if (!row.isNull("opacity")) row.getDouble("opacity") else config.optDouble("opacity", 1.0)
require(opacity.isFinite() && opacity in 0.0..1.0)
val overlay = row.optString("layerType").equals("overlay", true) ||
listOf("路网", "标注", "注记").any { name.contains(it) }
val z = config.optDouble("zIndex", (if (overlay) 1000 else 100) + max.toDouble())
val sort = if (!row.isNull("tenantSort")) row.getDouble("tenantSort") else row.optDouble("sort", 0.0)
require(z.isFinite() && sort.isFinite())
return PlatformMapLayer(row.get("id").toString(), name, url, coordinates, scheme, min, max, bounds, opacity, z, sort)
}
fun styleJson(catalog: PlatformMapCatalog): String {
val sources = JSONObject()
val layers = JSONArray().put(JSONObject().put("id", "background").put("type", "background")
.put("paint", JSONObject().put("background-color", "#E6EEF5")))
catalog.layers.forEachIndexed { index, layer ->
val id = "platform-$index"
val source = JSONObject().put("type", "raster").put("tiles", JSONArray().put(layer.url))
.put("tileSize", 256).put("scheme", layer.scheme.name.lowercase())
.put("minzoom", layer.minZoom).put("maxzoom", layer.maxZoom)
.put("attribution", "中科联航 · ${layer.name}")
layer.bounds?.let { source.put("bounds", it.json()) }
sources.put(id, source)
// Source maxzoom is the native resolution; the layer continues to
// render at higher zooms by overzooming, instead of disappearing.
layers.put(JSONObject().put("id", id).put("type", "raster").put("source", id)
.put("minzoom", layer.minZoom).put("paint", JSONObject()
.put("raster-opacity", layer.opacity).put("raster-fade-duration", 0)))
}
return JSONObject().put("version", 8).put("sources", sources).put("layers", layers).toString()
}
}
@@ -0,0 +1,51 @@
package com.zklh.dronecontroller.core.map
import java.net.HttpURLConnection
import java.net.URL
import org.json.JSONArray
import org.json.JSONObject
import kotlin.math.*
internal object PrivateMapSource {
fun styleJson(layer: PrivateMapLayer): String {
val sources = JSONObject()
val layers = JSONArray().put(JSONObject().put("id", "background").put("type", "background")
.put("paint", JSONObject().put("background-color", "#E6EEF5")))
listOf(layer.url, layer.annotationUrl).filter { it.isNotBlank() }.forEachIndexed { index, url ->
val id = if (index == 0) "basemap" else "labels"
sources.put(id, JSONObject().put("type", "raster").put("tiles", JSONArray().put(url))
.put("tileSize", 256).put("scheme", layer.scheme.name.lowercase())
.put("minzoom", layer.minZoom).put("maxzoom", layer.maxZoom))
layers.put(JSONObject().put("id", id).put("type", "raster").put("source", id)
.put("paint", JSONObject().put("raster-fade-duration", 0)))
}
return JSONObject().put("version", 8).put("sources", sources).put("layers", layers).toString()
}
fun tileUrl(template: String, zoom: Int, latitude: Double, longitude: Double, scheme: TileScheme): String {
val count = 1 shl zoom
val x = floor((longitude + 180) / 360 * count).toInt().coerceIn(0, count - 1)
val lat = latitude.coerceIn(-85.05112878, 85.05112878) * PI / 180
val y = floor((1 - ln(tan(lat) + 1 / cos(lat)) / PI) / 2 * count).toInt().coerceIn(0, count - 1)
val row = if (scheme == TileScheme.TMS) count - 1 - y else y
return template.replace("{z}", zoom.toString()).replace("{x}", x.toString()).replace("{y}", row.toString())
}
/** A sample at the supplied position is a connectivity check, not a coverage guarantee. */
fun checkAccess(layer: PrivateMapLayer, latitude: Double = 35.0, longitude: Double = 104.0): String {
layer.validationError()?.let { return it }
val display = MapCoordinates.display(latitude, longitude, layer.coordinates)
val z = minOf(8, layer.maxZoom).coerceAtLeast(layer.minZoom)
var connection: HttpURLConnection? = null
return try {
connection = (URL(tileUrl(layer.url, z, display.latitude, display.longitude, layer.scheme)).openConnection() as HttpURLConnection)
.apply { connectTimeout = 5000; readTimeout = 5000 }
val status = connection.responseCode
if (status == 200 && connection.contentType.orEmpty().startsWith("image/") &&
connection.inputStream.use { it.read() } >= 0) "样本瓦片可访问(第 $z 级),请在地图上确认区域覆盖"
else "样本瓦片不可用(HTTP $status),请确认当前位置在图层覆盖范围内"
} catch (_: Exception) {
"连接失败,请检查地址、网络和服务器证书"
} finally { connection?.disconnect() }
}
}
@@ -0,0 +1,81 @@
package com.zklh.dronecontroller.core.map
import java.net.URLEncoder
import java.net.URL
import java.net.HttpURLConnection
import org.json.JSONArray
import org.json.JSONObject
/** Web Mercator tiles. The map renderer and DJI overlays continue using longitude/latitude. */
internal object TiandituMapSource {
const val MinZoom = 1.0
const val MaxZoom = 18.0
fun styleJson(satellite: Boolean, key: String): String {
val sources = JSONObject()
val layers = JSONArray().put(JSONObject()
.put("id", "background")
.put("type", "background")
.put("paint", JSONObject().put("background-color", "#E6EEF5")))
if (key.isNotBlank()) {
val types = if (satellite) listOf("img_w", "cia_w") else listOf("vec_w", "cva_w")
types.forEachIndexed { index, type ->
val id = if (index == 0) "basemap" else "labels"
sources.put(id, JSONObject()
.put("type", "raster")
.put("tiles", JSONArray((0..7).map { tileUrl(type, key, it) }))
.put("tileSize", 256)
.put("scheme", "xyz")
.put("minzoom", MinZoom.toInt())
.put("maxzoom", MaxZoom.toInt())
.put("attribution", "<a href=\"https://www.tianditu.gov.cn/\">天地图</a>"))
layers.put(JSONObject().put("id", id).put("type", "raster").put("source", id)
.put("paint", JSONObject().put("raster-fade-duration", 0)))
}
}
return JSONObject().put("version", 8).put("sources", sources).put("layers", layers).toString()
}
private fun tileUrl(type: String, key: String, server: Int): String =
"https://t$server.tianditu.gov.cn/DataServer?T=$type&x={x}&y={y}&l={z}&tk=${URLEncoder.encode(key.trim(), "UTF-8")}"
/** Run on IO. A valid style does not imply that its authenticated tiles are available. */
fun checkAccess(satellite: Boolean, key: String): String? {
if (key.isBlank()) return "未配置天地图 Key"
val url = tileUrl(if (satellite) "img_w" else "vec_w", key, 0)
.replace("{x}", "13").replace("{y}", "6").replace("{z}", "4")
var connection: HttpURLConnection? = null
return try {
connection = (URL(url).openConnection() as HttpURLConnection).apply {
connectTimeout = 5000
readTimeout = 5000
}
val status = connection.responseCode
if (status == 200 && connection.contentType.orEmpty().startsWith("image/")) null
else {
val stream = if (status >= 400) connection.errorStream else connection.inputStream
val body = stream?.use { input ->
val bytes = ByteArray(4096)
var count = 0
while (count < bytes.size) {
val read = input.read(bytes, count, bytes.size - count)
if (read <= 0) break
count += read
}
String(bytes, 0, count, Charsets.UTF_8)
}.orEmpty()
val code = runCatching { JSONObject(body).optInt("code") }.getOrDefault(0)
when {
code == 301012 -> "天地图 Key 权限类型不匹配,请检查控制台的访问权限"
status == 401 || status == 403 -> "天地图鉴权失败,请检查 Key 配置"
else -> "天地图瓦片加载失败,请检查网络或服务状态"
}
}
} catch (_: Exception) {
// Exceptions can contain the complete tile URL including the access key.
"天地图连接失败,请检查网络"
} finally {
connection?.disconnect()
}
}
}
@@ -0,0 +1,84 @@
package com.zklh.dronecontroller.core.mission
import java.io.File
import java.io.InputStream
import java.util.zip.ZipFile
import javax.xml.parsers.DocumentBuilderFactory
import org.w3c.dom.Element
import kotlin.math.*
data class MissionPreviewPoint(val latitude: Double, val longitude: Double, val height: Double?, val index: Int)
data class MissionPreview(
val name: String, val points: List<MissionPreviewPoint>, val distanceMeters: Double,
val speed: Double?, val finishAction: String, val lostAction: String, val heightMode: String,
val fileSize: Long, val modifiedAt: Long, val waylineCount: Int
)
/** Read-only metadata. Does not rewrite the imported mission or issue aircraft commands. */
object MissionPreviewReader {
private const val MaxXmlBytes = 8 * 1024 * 1024
fun read(file: File): MissionPreview {
require(file.isFile) { "航线文件不存在" }
return if (file.extension.equals("kmz", true) || file.extension.equals("zip", true)) {
ZipFile(file).use { zip ->
val entries = zip.entries().asSequence().filter { !it.isDirectory }.toList()
val entry = entries.firstOrNull { it.name.endsWith("waylines.wpml", true) }
?: entries.firstOrNull { it.name.endsWith(".wpml", true) }
?: entries.firstOrNull { it.name.endsWith("template.kml", true) }
?: error("文件中未找到 WPML / KML 航线")
require(entry.size <= MaxXmlBytes) { "航线 XML 文件过大" }
zip.getInputStream(entry).use { parse(it, file) }
}
} else file.inputStream().use { parse(it, file) }
}
private fun parse(input: InputStream, file: File): MissionPreview {
val bytes = input.readBytesLimited()
val factory = DocumentBuilderFactory.newInstance().apply {
isNamespaceAware = true
setFeature("http://xml.org/sax/features/external-general-entities", false)
setFeature("http://xml.org/sax/features/external-parameter-entities", false)
}
// Reject declarations before parsing on both Android and JVM XML implementations.
require(!bytes.toString(Charsets.UTF_8).contains(Regex("<!\\s*(DOCTYPE|ENTITY)", RegexOption.IGNORE_CASE))) { "航线 XML 不允许包含外部实体" }
val doc = factory.newDocumentBuilder().parse(bytes.inputStream())
val root = doc.documentElement
fun Element.value(tag: String): String = getElementsByTagNameNS("*", tag).item(0)?.textContent?.trim().orEmpty()
val folders = root.getElementsByTagNameNS("*", "Folder")
// A KMZ can contain multiple waylines; never draw a fictitious connection between them.
val primary = (folders.item(0) as? Element) ?: root
val placemarks = primary.getElementsByTagNameNS("*", "Placemark")
val globalHeight = primary.value("globalHeight").toDoubleOrNull()
val points = (0 until placemarks.length).mapNotNull { n ->
val item = placemarks.item(n) as Element
val coords = item.value("coordinates").split(Regex("[,\\s]+"))
val lng = coords.getOrNull(0)?.toDoubleOrNull() ?: return@mapNotNull null
val lat = coords.getOrNull(1)?.toDoubleOrNull() ?: return@mapNotNull null
if (!lat.isFinite() || !lng.isFinite() || lat !in -90.0..90.0 || lng !in -180.0..180.0) return@mapNotNull null
val height = item.value("executeHeight").toDoubleOrNull() ?: item.value("height").toDoubleOrNull() ?: globalHeight
MissionPreviewPoint(lat, lng, height?.takeIf { it.isFinite() }, item.value("index").toIntOrNull() ?: n)
}
require(points.isNotEmpty()) { "未找到有效航点坐标" }
require(points.size <= 10000) { "航点数量超出预览上限" }
val distance = points.zipWithNext().sumOf { (a, b) -> distance(a, b) }
return MissionPreview(file.nameWithoutExtension, points, distance,
primary.value("autoFlightSpeed").toDoubleOrNull()?.takeIf { it.isFinite() && it > 0 },
root.value("finishAction"), root.value("executeRCLostAction"), primary.value("executeHeightMode").ifBlank { primary.value("heightMode") },
file.length(), file.lastModified(), folders.length.coerceAtLeast(1))
}
private fun InputStream.readBytesLimited(): ByteArray {
val output = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) { val n = read(buffer); if (n < 0) break; require(output.size() + n <= MaxXmlBytes) { "航线 XML 文件过大" }; output.write(buffer, 0, n) }
return output.toByteArray()
}
private fun distance(a: MissionPreviewPoint, b: MissionPreviewPoint): Double {
val dLat = Math.toRadians(b.latitude - a.latitude)
val dLng = Math.toRadians(b.longitude - a.longitude)
val h = sin(dLat / 2).pow(2) + cos(Math.toRadians(a.latitude)) * cos(Math.toRadians(b.latitude)) * sin(dLng / 2).pow(2)
return 6371000.0 * 2 * asin(sqrt(h.coerceIn(0.0, 1.0)))
}
}
@@ -0,0 +1,235 @@
package com.zklh.dronecontroller.core.telemetry
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import androidx.core.content.ContextCompat
import dji.sdk.keyvalue.key.DJIKey
import dji.sdk.keyvalue.key.FlightControllerKey
import dji.sdk.keyvalue.key.KeyTools
import dji.sdk.keyvalue.key.RemoteControllerKey
import dji.sdk.keyvalue.value.common.LocationCoordinate2D
import dji.sdk.keyvalue.value.common.LocationCoordinate3D
import dji.sdk.keyvalue.value.remotecontroller.RcGPSInfo
import dji.v5.common.callback.CommonCallbacks
import dji.v5.common.error.IDJIError
import dji.v5.manager.KeyManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
internal data class DevicePositionState(
val aircraft: DevicePositionFix?,
val controller: DevicePositionFix?,
val controllerStatus: String
)
/** Read-only positioning, independent of aircraft telemetry and cloud/MQTT connection. */
internal class DeviceLocationMonitor(context: Context?, private val onUpdate: (DevicePositionState) -> Unit) {
private val context = context?.applicationContext
private val manager = this.context?.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private val owner = Any()
private val fixes = LocationFixTracker()
private val providers = mutableSetOf<String>()
private val inFlight = mutableMapOf<String, Long>()
private val androidListener = LocationListener { location -> acceptAndroid(location) }
private var job: Job? = null
private var sdkRegistered = false
private var aircraftConnected = false
private var listening = false
private var revision = 0
private var rcStatus = "等待定位"
private var lastReadAt = 0L
fun start() {
if (job != null) return
revision++
lastReadAt = 0L
val activeJob = scope.launch(start = CoroutineStart.LAZY) {
while (true) {
syncAndroidProviders()
if (sdkRegistered && !listening) registerSdkListeners()
val now = SystemClock.elapsedRealtime()
if (sdkRegistered && (lastReadAt == 0L || now - lastReadAt >= 5000L)) {
lastReadAt = now
readSdkPositions()
}
publish()
delay(1000L)
}
}
job = activeJob
activeJob.start()
}
fun connection(registered: Boolean, connected: Boolean) {
if (sdkRegistered != registered || aircraftConnected != connected) {
revision++
inFlight.clear()
lastReadAt = 0L
if (aircraftConnected != connected || !registered) fixes.clearAircraft()
if (!registered) fixes.update(PositionSource.RC_SDK, null)
if (listening) runCatching { KeyManager.getInstance().cancelListen(owner) }
listening = false
}
sdkRegistered = registered
aircraftConnected = connected
publish()
}
fun stop() {
revision++
job?.cancel()
job = null
if (listening) runCatching { KeyManager.getInstance().cancelListen(owner) }
listening = false
runCatching { manager?.removeUpdates(androidListener) }
providers.clear()
inFlight.clear()
fixes.clear()
publish()
}
private fun registerSdkListeners() {
listen("Aircraft2D", KeyTools.createKey(FlightControllerKey.KeyAircraftLocation)) { value: LocationCoordinate2D? ->
acceptAircraft(PositionSource.AIRCRAFT_2D, value?.latitude, value?.longitude)
}
listen("Aircraft3D", KeyTools.createKey(FlightControllerKey.KeyAircraftLocation3D)) { value: LocationCoordinate3D? ->
acceptAircraft(PositionSource.AIRCRAFT_3D, value?.latitude, value?.longitude, value?.altitude)
}
listen("RcGPS", KeyTools.createKey(RemoteControllerKey.KeyRcGPSInfo), ::acceptRc)
listening = true
}
private fun <T> listen(name: String, key: DJIKey<T>, accept: (T?) -> Unit) {
val version = revision
runCatching {
KeyManager.getInstance().listen(key, owner, true) { _, value ->
scope.launch { if (job != null && revision == version) accept(value) }
}
}.onFailure { Log.w("ZklhPosition", "listen $name unavailable: ${it.javaClass.simpleName}") }
}
private fun readSdkPositions() {
// The callback overload requests hardware values; the synchronous overload only reads cache.
read("RcGPS", KeyTools.createKey(RemoteControllerKey.KeyRcGPSInfo), ::acceptRc)
if (aircraftConnected) {
read("Aircraft2D", KeyTools.createKey(FlightControllerKey.KeyAircraftLocation)) { value: LocationCoordinate2D? ->
acceptAircraft(PositionSource.AIRCRAFT_2D, value?.latitude, value?.longitude)
}
read("Aircraft3D", KeyTools.createKey(FlightControllerKey.KeyAircraftLocation3D)) { value: LocationCoordinate3D? ->
acceptAircraft(PositionSource.AIRCRAFT_3D, value?.latitude, value?.longitude, value?.altitude)
}
}
}
private fun <T> read(name: String, key: DJIKey<T>, accept: (T?) -> Unit) {
val now = SystemClock.elapsedRealtime()
if (inFlight[name]?.let { now - it < 10000L } == true) return
val version = revision
inFlight[name] = now
runCatching {
KeyManager.getInstance().getValue(key, object : CommonCallbacks.CompletionCallbackWithParam<T> {
override fun onSuccess(value: T?) { scope.launch {
if (revision == version && inFlight[name] == now) {
inFlight.remove(name)
if (job != null) accept(value)
}
} }
override fun onFailure(error: IDJIError) { scope.launch {
if (revision == version && inFlight[name] == now) {
inFlight.remove(name)
Log.d("ZklhPosition", "hardware read $name unavailable: ${error.errorCode()}")
}
} }
})
}.onFailure {
inFlight.remove(name)
Log.w("ZklhPosition", "hardware read $name failed: ${it.javaClass.simpleName}")
}
}
private fun acceptAircraft(source: PositionSource, latitude: Double?, longitude: Double?, altitude: Double? = null) {
if (!aircraftConnected) return
val valid = LocationFixTracker.valid(latitude, longitude)
fixes.update(source, if (valid) DevicePositionFix(latitude!!, longitude!!, SystemClock.elapsedRealtime(), source,
altitude?.takeIf { it.isFinite() }) else null)
Log.d("ZklhPosition", "$source coordinateValid=$valid")
publish()
}
private fun acceptRc(info: RcGPSInfo?) {
val location = info?.location
val valid = LocationFixTracker.valid(location?.latitude, location?.longitude)
// Retain the existing RC Plus compatibility: some firmware reports isValid=false
// alongside a usable coordinate. Android GPS remains a separate, fresh channel.
fixes.update(PositionSource.RC_SDK, if (valid) DevicePositionFix(location!!.latitude, location.longitude,
SystemClock.elapsedRealtime(), PositionSource.RC_SDK, accuracy = info!!.accuracy,
satelliteCount = info.satelliteCount) else null)
Log.d("ZklhPosition", "RcGPS coordinateValid=$valid flag=${info?.isValid} satellites=${info?.satelliteCount}")
publish()
}
@SuppressLint("MissingPermission")
private fun syncAndroidProviders() {
val context = context ?: return
val manager = manager ?: return
val permitted = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
if (!permitted) {
runCatching { manager.removeUpdates(androidListener) }
providers.clear()
fixes.update(PositionSource.ANDROID_GPS, null)
fixes.update(PositionSource.ANDROID_NETWORK, null)
rcStatus = "未授予定位权限"
return
}
val enabled = runCatching { manager.getProviders(true) }.getOrDefault(emptyList())
.filter { it != LocationManager.PASSIVE_PROVIDER }
if (providers.any { it !in enabled }) {
runCatching { manager.removeUpdates(androidListener) }
providers.clear()
fixes.update(PositionSource.ANDROID_GPS, null)
fixes.update(PositionSource.ANDROID_NETWORK, null)
}
enabled.filter { it !in providers }.forEach { provider ->
runCatching {
// elapsedRealtime timestamps reject old fixes, even after wall-clock changes.
manager.getLastKnownLocation(provider)?.let(::acceptAndroid)
manager.requestLocationUpdates(provider, 1000L, 0f, androidListener, Looper.getMainLooper())
providers += provider
}.onFailure { Log.w("ZklhPosition", "Android provider $provider unavailable: ${it.javaClass.simpleName}") }
}
rcStatus = if (providers.isEmpty()) "系统定位未开启" else "等待卫星定位"
}
private fun acceptAndroid(location: Location) {
if (job == null) return
val source = if (location.provider == LocationManager.GPS_PROVIDER) PositionSource.ANDROID_GPS else PositionSource.ANDROID_NETWORK
val now = SystemClock.elapsedRealtime()
val observedAt = location.elapsedRealtimeNanos / 1000000L
if (observedAt <= 0 || now - observedAt !in 0..30000L || !LocationFixTracker.valid(location.latitude, location.longitude)) return
fixes.update(source, DevicePositionFix(location.latitude, location.longitude, observedAt, source,
if (location.hasAltitude()) location.altitude.takeIf { it.isFinite() } else null,
if (location.hasAccuracy()) location.accuracy.toDouble() else 0.0))
publish()
}
private fun publish() {
val now = SystemClock.elapsedRealtime()
onUpdate(DevicePositionState(if (aircraftConnected && job != null) fixes.aircraft(now) else null,
if (job != null) fixes.controller(now) else null, rcStatus))
}
}
@@ -0,0 +1,53 @@
package com.zklh.dronecontroller.core.telemetry
internal enum class PositionSource { AIRCRAFT_2D, AIRCRAFT_3D, RC_SDK, ANDROID_GPS, ANDROID_NETWORK }
internal data class DevicePositionFix(
val latitude: Double,
val longitude: Double,
val observedAt: Long,
val source: PositionSource,
val altitude: Double? = null,
val accuracy: Double = 0.0,
val satelliteCount: Int = 0
)
/** Independent channels prevent an unavailable 3D key from erasing a valid 2D fix. */
internal class LocationFixTracker(private val maxAgeMs: Long = 30000L) {
private val fixes = mutableMapOf<PositionSource, DevicePositionFix>()
@Synchronized fun update(source: PositionSource, fix: DevicePositionFix?) {
if (fix == null || !valid(fix.latitude, fix.longitude)) fixes.remove(source)
else if (fix.observedAt >= (fixes[source]?.observedAt ?: Long.MIN_VALUE)) fixes[source] = fix
}
@Synchronized fun aircraft(now: Long): DevicePositionFix? = choose(now) {
it.source == PositionSource.AIRCRAFT_2D || it.source == PositionSource.AIRCRAFT_3D
}
@Synchronized fun controller(now: Long): DevicePositionFix? = fixes.values
.filter { it.source != PositionSource.AIRCRAFT_2D && it.source != PositionSource.AIRCRAFT_3D && now - it.observedAt in 0..maxAgeMs }
.minWithOrNull(compareBy<DevicePositionFix> {
// A newer coarse network fix should not displace fresh, accurate GPS.
if (it.accuracy.isFinite() && it.accuracy > 0) it.accuracy else 1000.0
}.thenByDescending { it.observedAt })
private fun choose(now: Long, eligible: (DevicePositionFix) -> Boolean): DevicePositionFix? =
fixes.values.filter { eligible(it) && now - it.observedAt in 0..maxAgeMs }
.maxWithOrNull(compareBy<DevicePositionFix> { it.observedAt }.thenBy {
if (it.source == PositionSource.RC_SDK || it.source == PositionSource.AIRCRAFT_3D) 1 else 0
})
@Synchronized fun clearAircraft() {
fixes.remove(PositionSource.AIRCRAFT_2D)
fixes.remove(PositionSource.AIRCRAFT_3D)
}
@Synchronized fun clear() = fixes.clear()
companion object {
fun valid(latitude: Double?, longitude: Double?): Boolean = latitude != null && longitude != null &&
latitude.isFinite() && longitude.isFinite() && latitude in -90.0..90.0 && longitude in -180.0..180.0 &&
(latitude != 0.0 || longitude != 0.0)
}
}
@@ -1,15 +1,7 @@
package com.zklh.dronecontroller.core.telemetry
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Looper
import android.util.Log
import androidx.core.content.ContextCompat
import dji.rtk.CoordinateSystem
import dji.sdk.keyvalue.key.BatteryKey
import dji.sdk.keyvalue.key.CameraKey
@@ -42,7 +34,6 @@ import dji.sdk.keyvalue.value.flightcontroller.WindDirection
import dji.sdk.keyvalue.value.payload.PayloadCameraType
import dji.sdk.keyvalue.value.product.ProductType
import dji.sdk.keyvalue.value.remotecontroller.BatteryInfo
import dji.sdk.keyvalue.value.remotecontroller.RcGPSInfo
import dji.sdk.keyvalue.value.remotecontroller.RemoteControllerType
import dji.sdk.keyvalue.value.rtkbasestation.RTKReferenceStationSource
import dji.sdk.keyvalue.value.rtkbasestation.RTKServiceState
@@ -60,7 +51,6 @@ import dji.v5.manager.aircraft.rtk.network.INetworkServiceInfoListener
import dji.v5.manager.aircraft.rtk.station.ConnectedRTKStationInfoListener
import dji.v5.manager.aircraft.rtk.station.RTKStationConnectStatusListener
import dji.v5.manager.aircraft.rtk.station.SearchRTKStationListener
import dji.v5.utils.common.LocationUtil
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -99,6 +89,7 @@ data class TelemetrySnapshot(
val rcLocationValid: Boolean = false,
val rcGpsSatelliteCount: Int = 0,
val rcGpsAccuracy: Double = 0.0,
val rcLocationStatus: String = "等待定位",
val rtkLatitude: Double = 0.0,
val rtkLongitude: Double = 0.0,
val rtkAltitude: Double = 0.0,
@@ -198,8 +189,6 @@ class TelemetryRepository(
) {
private val listenHolder = Any()
private val appContext = context?.applicationContext
private val locationManager = appContext?.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
private val androidLocationListener = LocationListener { location -> updateRcLocationFromAndroid(location) }
private val rtkCenter = RTKCenter.getInstance()
private val rtkLocationInfoListener = RTKLocationInfoListener { info -> updateRtkLocationInfo(info) }
private val rtkSystemStateListener = RTKSystemStateListener { state -> updateRtkSystemState(state) }
@@ -259,6 +248,27 @@ class TelemetryRepository(
}
private val _state = MutableStateFlow(TelemetrySnapshot())
val state: StateFlow<TelemetrySnapshot> = _state.asStateFlow()
private val deviceLocationMonitor = DeviceLocationMonitor(appContext) { positions ->
_state.update { current ->
current.copy(
latitude = positions.aircraft?.latitude ?: 0.0,
longitude = positions.aircraft?.longitude ?: 0.0,
locationValid = positions.aircraft != null,
rcLatitude = positions.controller?.latitude ?: 0.0,
rcLongitude = positions.controller?.longitude ?: 0.0,
rcAltitude = positions.controller?.altitude ?: current.rcAltitude,
rcLocationValid = positions.controller != null,
rcGpsSatelliteCount = positions.controller?.satelliteCount ?: 0,
rcGpsAccuracy = positions.controller?.accuracy ?: 0.0,
rcLocationStatus = positions.controllerStatus
)
}
}
fun startPositioning() = deviceLocationMonitor.start()
fun stopPositioning() = deviceLocationMonitor.stop()
fun updatePositioningConnection(registered: Boolean, connected: Boolean) = deviceLocationMonitor.connection(registered, connected)
private val cameraStreamCapabilities = CameraStreamCapabilities { sources ->
_state.update { it.copy(cameraStreamSources = sources) }
}
@@ -282,34 +292,6 @@ class TelemetryRepository(
started = true
Log.d(TelemetryLogTag, "start telemetry listeners")
listenConnectionTelemetry()
listenSafely("KeyAircraftLocation", KeyTools.createKey(FlightControllerKey.KeyAircraftLocation)) { location: LocationCoordinate2D? ->
location ?: return@listenSafely
Log.d(
TelemetryLogTag,
"KeyAircraftLocation lat=${location.latitude} lon=${location.longitude}"
)
updateAircraftLocation(location.latitude, location.longitude)
}
listenSafely("KeyAircraftLocation3D", KeyTools.createKey(FlightControllerKey.KeyAircraftLocation3D)) { location: LocationCoordinate3D? ->
location ?: return@listenSafely
val latitude = location.latitude ?: 0.0
val longitude = location.longitude ?: 0.0
val altitude = location.altitude
val valid = isValidCoordinate(latitude, longitude)
Log.d(
TelemetryLogTag,
"KeyAircraftLocation3D lat=$latitude lon=$longitude rawAltitude=$altitude valid=$valid"
)
_state.update {
it.copy(
latitude = latitude,
longitude = longitude,
locationValid = valid,
altitude = altitude ?: it.altitude,
error = null
)
}
}
listenSafely("KeyAltitude", KeyTools.createKey(FlightControllerKey.KeyAltitude)) { altitude: Double? ->
_state.update { it.copy(altitude = altitude ?: 0.0, error = null) }
}
@@ -590,7 +572,6 @@ class TelemetryRepository(
}
}
listenRemoteControllerTelemetry()
startAndroidLocationFallback()
listenCameraTelemetry()
cameraCloudTelemetry.start()
cameraStreamCapabilities.start()
@@ -604,7 +585,6 @@ class TelemetryRepository(
cameraCloudTelemetry.stop()
cameraStreamCapabilities.stop()
runCatching { KeyManager.getInstance().cancelListen(listenHolder) }
runCatching { locationManager?.removeUpdates(androidLocationListener) }
runCatching { rtkCenter.removeRTKLocationInfoListener(rtkLocationInfoListener) }
runCatching { rtkCenter.removeRTKSystemStateListener(rtkSystemStateListener) }
runCatching { rtkCenter.qxrtkManager.removeNetworkRTKServiceInfoListener(rtkNetworkServiceInfoListener) }
@@ -658,24 +638,6 @@ class TelemetryRepository(
Log.d(TelemetryLogTag, "refresh current telemetry values reason=$reason")
cameraStreamCapabilities.refresh()
currentValue("KeyAircraftLocation", KeyTools.createKey(FlightControllerKey.KeyAircraftLocation))
?.let { location: LocationCoordinate2D -> updateAircraftLocation(location.latitude, location.longitude) }
currentValue("KeyAircraftLocation3D", KeyTools.createKey(FlightControllerKey.KeyAircraftLocation3D))
?.let { location: LocationCoordinate3D ->
val latitude = location.latitude ?: 0.0
val longitude = location.longitude ?: 0.0
val altitude = location.altitude
val valid = isValidCoordinate(latitude, longitude)
_state.update {
it.copy(
latitude = latitude,
longitude = longitude,
locationValid = valid,
altitude = altitude ?: it.altitude,
error = null
)
}
}
currentValue("KeyAltitude", KeyTools.createKey(FlightControllerKey.KeyAltitude))
?.let { altitude: Double -> _state.update { it.copy(altitude = altitude, error = null) } }
currentValue("KeyHeightAboveSeaLevel", KeyTools.createKey(FlightControllerKey.KeyHeightAboveSeaLevel))
@@ -818,27 +780,6 @@ class TelemetryRepository(
}
private fun refreshRemoteControllerValues() {
currentValue("KeyRcGPSInfo", KeyTools.createKey(RemoteControllerKey.KeyRcGPSInfo))
?.let { info: RcGPSInfo ->
val location = info.location
val latitude = location?.latitude ?: 0.0
val longitude = location?.longitude ?: 0.0
val coordinateValid = isValidCoordinate(latitude, longitude)
_state.update {
if (coordinateValid) {
it.copy(
rcLatitude = latitude,
rcLongitude = longitude,
rcLocationValid = true,
rcGpsSatelliteCount = info.satelliteCount,
rcGpsAccuracy = info.accuracy,
error = null
)
} else {
it.copy(rcGpsSatelliteCount = info.satelliteCount, rcGpsAccuracy = info.accuracy, error = null)
}
}
}
currentValue("KeyRcBatteryInfo", KeyTools.createKey(RemoteControllerKey.KeyBatteryInfo))
?.batteryPercent
?.takeIf { it in 0..100 }
@@ -980,36 +921,6 @@ class TelemetryRepository(
}
private fun listenRemoteControllerTelemetry() {
listenSafely("KeyRcGPSInfo", KeyTools.createKey(RemoteControllerKey.KeyRcGPSInfo)) { info: RcGPSInfo? ->
val location = info?.location
val latitude = location?.latitude ?: 0.0
val longitude = location?.longitude ?: 0.0
val coordinateValid = isValidCoordinate(latitude, longitude)
val accepted = coordinateValid
Log.d(
TelemetryLogTag,
"KeyRcGPSInfo valid=${info?.isValid} coordinateValid=$coordinateValid accepted=$accepted " +
"lat=$latitude lon=$longitude satellites=${info?.satelliteCount} accuracy=${info?.accuracy}"
)
_state.update {
if (accepted) {
it.copy(
rcLatitude = latitude,
rcLongitude = longitude,
rcLocationValid = true,
rcGpsSatelliteCount = info?.satelliteCount ?: 0,
rcGpsAccuracy = info?.accuracy ?: 0.0,
error = null
)
} else {
it.copy(
rcGpsSatelliteCount = info?.satelliteCount ?: 0,
rcGpsAccuracy = info?.accuracy ?: it.rcGpsAccuracy,
error = null
)
}
}
}
listenSafely("KeyRcBatteryInfo", KeyTools.createKey(RemoteControllerKey.KeyBatteryInfo)) { info: BatteryInfo? ->
val percent = info?.batteryPercent ?: return@listenSafely
if (percent in 0..100) {
@@ -1160,16 +1071,6 @@ class TelemetryRepository(
}
}
private fun updateAircraftLocation(latitude: Double?, longitude: Double?) {
val lat = latitude ?: 0.0
val lon = longitude ?: 0.0
val valid = isValidCoordinate(lat, lon)
_state.update {
it.copy(latitude = lat, longitude = lon, locationValid = valid, error = null)
}
Log.d(TelemetryLogTag, "KeyAircraftLocation raw lat=$lat lon=$lon valid=$valid")
}
private fun updateRtkLocationInfo(info: RTKLocationInfo?) {
val realLocation = info?.real3DLocation
val mobileLocation = info?.rtkLocation?.mobileStationLocation
@@ -1428,87 +1329,6 @@ class TelemetryRepository(
}
}
@SuppressLint("MissingPermission")
private fun startAndroidLocationFallback() {
val manager = locationManager ?: return
val context = appContext ?: return
Log.d(TelemetryLogTag, "start RC Android location fallback")
if (
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
) {
Log.w(TelemetryLogTag, "Android location permission not granted, RC system location disabled")
return
}
runCatching {
LocationUtil.getLastLocation()?.let { location ->
Log.d(
TelemetryLogTag,
"LocationUtilLastLocation provider=${location.provider} lat=${location.latitude} " +
"lon=${location.longitude} accuracy=${location.accuracy}"
)
updateRcLocationFromAndroid(location)
}
}.onFailure { error ->
Log.w(TelemetryLogTag, "read DJI LocationUtil last location failed: ${error.message}")
}
val providers = (
listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER, LocationManager.PASSIVE_PROVIDER) +
manager.allProviders
)
.distinct()
.filter { provider ->
provider == LocationManager.PASSIVE_PROVIDER ||
runCatching { manager.isProviderEnabled(provider) }.getOrDefault(false)
}
Log.d(TelemetryLogTag, "RC Android location providers=$providers all=${manager.allProviders}")
if (providers.isEmpty()) {
Log.w(TelemetryLogTag, "no enabled RC Android location providers")
}
providers.forEach { provider ->
runCatching {
manager.getLastKnownLocation(provider)?.let(::updateRcLocationFromAndroid)
manager.requestLocationUpdates(
provider,
1_000L,
0.5f,
androidLocationListener,
Looper.getMainLooper()
)
Log.d(TelemetryLogTag, "registered RC Android location provider=$provider")
}.onFailure { error ->
Log.w(TelemetryLogTag, "register RC Android location provider=$provider failed: ${error.message}")
}
}
}
private fun updateRcLocationFromAndroid(location: Location) {
val latitude = location.latitude
val longitude = location.longitude
val valid = isValidCoordinate(latitude, longitude)
Log.d(
TelemetryLogTag,
"RcAndroidLocation provider=${location.provider} lat=$latitude lon=$longitude accuracy=${location.accuracy} valid=$valid"
)
if (!valid) return
_state.update {
if (it.rcLocationValid && it.rcGpsSatelliteCount > 0) {
it
} else {
it.copy(
rcLatitude = latitude,
rcLongitude = longitude,
rcAltitude = if (location.hasAltitude()) location.altitude else it.rcAltitude,
rcLocationValid = true,
rcGpsAccuracy = location.accuracy.toDouble(),
error = null
)
}
}
}
private fun updateStorage(total: Int?, remain: Int?) {
_state.update {
it.copy(
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,24 @@
package com.zklh.dronecontroller.ui
import androidx.compose.runtime.*
import com.zklh.dronecontroller.core.mission.MissionPreview
import com.zklh.dronecontroller.core.mission.MissionPreviewReader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
internal data class MissionPreviewState(val preview: MissionPreview? = null, val error: String? = null, val loading: Boolean = false)
@Composable
internal fun rememberMissionPreview(path: String, revision: Int = 0): MissionPreviewState {
val result by produceState(MissionPreviewState(loading = path.isNotBlank()), path, revision) {
value = MissionPreviewState(loading = path.isNotBlank())
value = if (path.isBlank()) MissionPreviewState() else withContext(Dispatchers.IO) {
runCatching { MissionPreviewReader.read(File(path)) }.fold(
onSuccess = { MissionPreviewState(preview = it) },
onFailure = { MissionPreviewState(error = it.message ?: "无法读取航线") }
)
}
}
return result
}
@@ -0,0 +1,141 @@
package com.zklh.dronecontroller.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.zklh.dronecontroller.core.cloud.CloudMqttState
import com.zklh.dronecontroller.core.livestream.LiveStreamingState
import com.zklh.dronecontroller.core.msdk.DroneSdkState
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@Composable
internal fun PilotCloudScreen(sdk: DroneSdkState, cloud: CloudMqttState, live: LiveStreamingState, tenant: String, username: String, onBack: () -> Unit, onLogin: () -> Unit, onLive: () -> Unit, onToast: (String) -> Unit) {
BoxWithConstraints(Modifier.fillMaxSize().background(PilotDesign.PageBrush)) {
val compact = maxHeight < 500.dp
CloudMountains(Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(70.dp))
Column(Modifier.fillMaxSize().padding(20.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
TextButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "返回"); Text("返回", color = PilotDesign.Ink, modifier = Modifier.padding(start = 8.dp)) }
VerticalDivider(Modifier.height(38.dp), color = PilotDesign.Line)
Column(Modifier.padding(start = 18.dp).weight(1f)) {
Text("云服务", color = PilotDesign.Ink, fontSize = 27.sp, lineHeight = 34.sp, fontWeight = FontWeight.Bold)
Text("连接云端,拓展更多能力,让飞行创造更大价值", color = PilotDesign.Muted, fontSize = 12.sp)
}
Column(horizontalAlignment = Alignment.End, modifier = Modifier.padding(end = 22.dp)) {
Text(cloud.session?.tenantName ?: tenant.ifBlank { "未登录" }, color = PilotDesign.Ink, fontSize = 14.sp, fontWeight = FontWeight.Bold)
Text(cloud.session?.username ?: username, color = PilotDesign.Muted, fontSize = 11.sp)
}
PilotPrimaryButton(if (cloud.connected) "管理云服务" else "连接云服务", onLogin, icon = Icons.Default.CloudQueue)
}
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(10.dp)) {
CloudFeature("司空 2 私有云", "一体化的无人机私有化云平台\n支持任务管理、设备接入、数据分析与行业应用", listOf("私有化部署", "数据安全", "行业定制"), Icons.Default.Cloud, true, Modifier.weight(1f), onLogin)
CloudFeature("GB28181", "支持国标视频接入与联网\n实现与第三方视频平台的互联互通", listOf("国标协议", "视频上云", "多平台兼容"), Icons.Default.Videocam, false, Modifier.weight(1f)) { onToast("当前业务仅配置了 RTMP 推流,GB28181 尚未配置") }
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(10.dp)) {
CloudFeature("开放平台", "提供标准化 API 与 SDK\n快速集成,构建专属行业应用", listOf("API 接口", "SDK 开发", "生态扩展"), Icons.Default.Widgets, false, Modifier.weight(1f), onLogin)
CloudFeature("自定义直播", "实时视频推送至云端\n使用平台下发的 RTMP 推流地址", listOf("RTMP 推流", "实时状态", "灵活配置"), Icons.Default.LiveTv, false, Modifier.weight(1f), onLive)
}
Column(Modifier.weight(1f).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
PilotCard(Modifier.fillMaxWidth()) {
CloudStatusTitle("飞行器数据同步", Icons.Default.Flight, cloud.connected)
Text(if (cloud.connected) "通过 MQTT 同步飞行器数据" else "连接云端后同步飞行器数据", color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 14.sp, modifier = Modifier.padding(vertical = 7.dp))
Surface(color = PilotDesign.Background, shape = RoundedCornerShape(7.dp)) {
Column(Modifier.padding(10.dp)) {
CloudStatusRow("设备在线", if (cloud.connected) (if (sdk.productConnected) "飞行器在线" else "飞行器未连接") else "云端离线", Icons.Default.Navigation)
CloudStatusRow("飞行数据同步", if (cloud.connected && cloud.lastOsdAt > 0) "已上报" else "等待上报", Icons.Default.BarChart)
CloudStatusRow("任务指令", if (cloud.connected) "接收中" else "未连接", Icons.Default.Assignment)
CloudStatusRow("同步时间", if (cloud.lastOsdAt > 0) SimpleDateFormat("MM-dd HH:mm:ss", Locale.CHINA).format(Date(cloud.lastOsdAt)) else "—", Icons.Default.Schedule)
}
}
}
PilotCard(Modifier.fillMaxWidth()) {
CloudStatusTitle("视频流状态", Icons.Default.Videocam, live.streaming)
Text(live.message, color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 14.sp, modifier = Modifier.padding(vertical = 7.dp))
Surface(color = PilotDesign.Background, shape = RoundedCornerShape(7.dp)) {
Column(Modifier.padding(10.dp)) {
CloudStatusRow("视频流状态", if (live.streaming) "推流中" else "未开启", Icons.Default.SignalCellularAlt)
CloudStatusRow("推流协议", live.urlType.ifBlank { "—" }, Icons.Default.Code)
CloudStatusRow("码率", if (live.streaming && live.vbps > 0) "${instrumentNumber(live.vbps / 1000000.0)} Mbps" else "—", Icons.Default.Speed)
CloudStatusRow("分辨率 / 帧率", if (live.streaming) "${live.resolution.ifBlank { "—" }} / ${live.fps}fps" else "—", Icons.Default.Monitor)
}
}
}
}
}
if (!compact) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text("— 让天空更安全 让作业更高效", color = PilotDesign.Muted, fontSize = 11.sp)
Text("连接云端 · 释放数据价值 · 赋能行业未来 —", color = PilotDesign.Muted, fontSize = 11.sp)
}
}
}
}
@Composable
private fun CloudFeature(title: String, description: String, tags: List<String>, icon: ImageVector, selected: Boolean, modifier: Modifier, onClick: () -> Unit) {
Surface(onClick = onClick, modifier = modifier.fillMaxWidth(), color = Color.White.copy(alpha = 0.9f), shape = RoundedCornerShape(8.dp), border = BorderStroke(if (selected) 1.2.dp else 1.dp, if (selected) Color(0xFF69AEFF) else PilotDesign.Line)) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Box(Modifier.fillMaxWidth().weight(1f).background(Brush.verticalGradient(listOf(Color(0xFFEAF4FF), Color.White))), contentAlignment = Alignment.Center) {
CloudMountains(Modifier.fillMaxSize())
Icon(icon, null, tint = PilotDesign.Blue, modifier = Modifier.size(62.dp))
}
Row(verticalAlignment = Alignment.CenterVertically) { Text(title, color = PilotDesign.Ink, fontSize = 19.sp, lineHeight = 24.sp, fontWeight = FontWeight.Bold); Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, null, tint = PilotDesign.Ink) }
Text(description, color = PilotDesign.Muted, fontSize = 12.sp, lineHeight = 17.sp)
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { tags.forEach { tag -> Surface(color = Color(0xFFF0F7FF), shape = RoundedCornerShape(20.dp)) { Text(tag, color = PilotDesign.Blue, fontSize = 9.sp, lineHeight = 12.sp, modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)) } } }
}
}
}
@Composable
private fun CloudStatusTitle(title: String, icon: ImageVector, active: Boolean) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(icon, null, tint = PilotDesign.Teal, modifier = Modifier.size(29.dp))
Text(title, color = PilotDesign.Ink, fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f).padding(start = 10.dp))
PilotStatus(if (active) "已连接" else "未连接", active)
}
}
@Composable
private fun CloudStatusRow(label: String, value: String, icon: ImageVector) {
Row(Modifier.fillMaxWidth().padding(vertical = 7.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(icon, null, tint = PilotDesign.Ink, modifier = Modifier.size(17.dp))
Text(label, color = PilotDesign.Ink, fontSize = 12.sp, lineHeight = 16.sp, modifier = Modifier.weight(1f).padding(start = 9.dp))
Text(value, color = PilotDesign.Teal, fontSize = 11.sp, lineHeight = 16.sp)
}
}
@Composable
private fun CloudMountains(modifier: Modifier) {
Canvas(modifier) {
listOf(0.10f, 0.17f).forEachIndexed { n, alpha ->
val path = Path().apply {
moveTo(0f, size.height)
for (i in 0..14) lineTo(size.width * i / 14f, size.height * (0.55f + (i % 3) * 0.15f - n * 0.06f))
lineTo(size.width, size.height); close()
}
drawPath(path, Color(0xFFB4CEE6).copy(alpha = alpha))
}
}
}
@@ -0,0 +1,100 @@
package com.zklh.dronecontroller.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Density
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
internal object PilotDesign {
val Background = Color(0xFFF0F5FA)
val Ink = Color(0xFF0C284F)
val Muted = Color(0xFF7387A7)
val Blue = Color(0xFF327FC4)
val Teal = Color(0xFF189D90)
val Line = Color(0xFFDDE7F1)
val Orange = Color(0xFFE99124)
val Red = Color(0xFFC6474C)
val PageBrush = Brush.linearGradient(listOf(Color(0xFFF7FAFD), Background, Color(0xFFEDF4FA)))
}
/** The supplied landscape designs use a 960-unit grid, independent of RC display DPI. */
@Composable
internal fun PilotDesignViewport(content: @Composable () -> Unit) {
BoxWithConstraints(Modifier.fillMaxSize()) {
val deviceDensity = LocalDensity.current
val widthScale = (maxWidth.value / 960f).coerceAtLeast(0.4f)
CompositionLocalProvider(LocalDensity provides Density(deviceDensity.density * widthScale, deviceDensity.fontScale)) {
Box(Modifier.fillMaxSize()) { content() }
}
}
}
@Composable
internal fun rememberPilotTime(pattern: String = "HH:mm"): String {
var now by remember { mutableStateOf(System.currentTimeMillis()) }
LaunchedEffect(Unit) { while (true) { now = System.currentTimeMillis(); delay(1000) } }
return SimpleDateFormat(pattern, Locale.CHINA).format(Date(now))
}
@Composable
internal fun PilotCard(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
Surface(modifier, color = Color.White.copy(alpha = 0.88f), shape = RoundedCornerShape(10.dp), border = BorderStroke(1.dp, PilotDesign.Line.copy(alpha = 0.65f))) {
Column(Modifier.padding(14.dp), content = content)
}
}
@Composable
internal fun PilotStatus(label: String, active: Boolean, modifier: Modifier = Modifier) {
val color = if (active) PilotDesign.Teal else PilotDesign.Muted
Row(modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Box(Modifier.size(8.dp).background(color, CircleShape))
Text(label, color = color, fontSize = 12.sp, lineHeight = 16.sp, fontWeight = FontWeight.Medium, maxLines = 1)
}
}
@Composable
internal fun PilotMetric(label: String, value: String, modifier: Modifier = Modifier, large: Boolean = false, icon: ImageVector? = null) {
Column(modifier, verticalArrangement = Arrangement.spacedBy(5.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) {
if (icon != null) Icon(icon, null, tint = PilotDesign.Ink, modifier = Modifier.size(15.dp))
Text(label, color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Text(value, color = PilotDesign.Ink, fontSize = if (large) 25.sp else 15.sp, lineHeight = if (large) 30.sp else 18.sp, fontWeight = if (large) FontWeight.Bold else FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
@Composable
internal fun PilotDetail(label: String, value: String, color: Color = PilotDesign.Ink) {
Row(Modifier.fillMaxWidth().padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically) {
Text(label, color = PilotDesign.Muted, fontSize = 12.sp, lineHeight = 16.sp, modifier = Modifier.weight(1f))
Text(value, color = color, fontSize = 12.sp, lineHeight = 16.sp, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1.1f))
}
}
@Composable
internal fun PilotPrimaryButton(label: String, onClick: () -> Unit, modifier: Modifier = Modifier, icon: ImageVector? = null, enabled: Boolean = true, color: Color = PilotDesign.Blue) {
Button(onClick, modifier.height(44.dp), enabled = enabled, shape = RoundedCornerShape(7.dp), colors = ButtonDefaults.buttonColors(containerColor = color), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp)) {
if (icon != null) { Icon(icon, null, modifier = Modifier.size(20.dp)); Spacer(Modifier.width(8.dp)) }
Text(label, fontSize = 14.sp, fontWeight = FontWeight.Bold, maxLines = 1)
}
}
internal fun pilotDuration(seconds: Int): String = "%02d:%02d".format(Locale.US, seconds / 60, seconds % 60)
@@ -0,0 +1,48 @@
package com.zklh.dronecontroller.ui
import androidx.compose.runtime.*
import dji.sdk.keyvalue.key.AirLinkKey
import dji.sdk.keyvalue.key.DJIKey
import dji.sdk.keyvalue.key.FlightControllerKey
import dji.sdk.keyvalue.key.KeyTools
import dji.sdk.keyvalue.key.RtkMobileStationKey
import dji.v5.manager.KeyManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
internal data class PilotDeviceReadings(
val downlinkQuality: Int? = null, val goHomeHeight: Int? = null,
val dataRateMbps: Double? = null, val flightTimeSeconds: Int? = null,
val rtkHorizontalStdMeters: Double? = null, val rtkVerticalStdMeters: Double? = null
)
@Composable
internal fun rememberPilotDeviceReadings(connected: Boolean): PilotDeviceReadings {
val flow = remember(connected) { MutableStateFlow(PilotDeviceReadings()) }
DisposableEffect(connected) {
val owner = Any()
val lock = Any()
var active = true
fun <T> observe(key: DJIKey<T>, change: PilotDeviceReadings.(T?) -> PilotDeviceReadings) {
runCatching { KeyManager.getInstance().listen(key, owner, true) { _, value ->
synchronized(lock) { if (active) flow.update { it.change(value) } }
} }
}
if (connected) {
observe(KeyTools.createKey(AirLinkKey.KeyDownLinkQualityRaw)) { copy(downlinkQuality = it?.takeIf { n -> n in 0..100 }) }
observe(KeyTools.createKey(FlightControllerKey.KeyGoHomeHeight)) { copy(goHomeHeight = it) }
// DJI documents this key in 0.1 s units despite its name.
observe(KeyTools.createKey(FlightControllerKey.KeyFlightTimeInSeconds)) { copy(flightTimeSeconds = it?.takeIf { n -> n >= 0 }?.div(10)) }
observe(KeyTools.createKey(AirLinkKey.KeyDynamicDataRate)) { copy(dataRateMbps = it?.takeIf { n -> n.isFinite() && n >= 0 }) }
observe(KeyTools.createKey(RtkMobileStationKey.KeyRTKLocation)) {
val lat = it?.stdLatitude?.takeIf { n -> n.isFinite() && n >= 0 }
val lng = it?.stdLongitude?.takeIf { n -> n.isFinite() && n >= 0 }
copy(rtkHorizontalStdMeters = if (lat != null && lng != null) kotlin.math.hypot(lat, lng) else null,
rtkVerticalStdMeters = it?.stdAltitude?.takeIf { n -> n.isFinite() && n >= 0 })
}
}
onDispose { synchronized(lock) { active = false }; runCatching { KeyManager.getInstance().cancelListen(owner) } }
}
val value by flow.collectAsState()
return value
}
@@ -0,0 +1,229 @@
package com.zklh.dronecontroller.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.zklh.dronecontroller.core.diagnostics.DroneWarningState
import com.zklh.dronecontroller.core.msdk.DroneSdkState
import com.zklh.dronecontroller.core.telemetry.TelemetrySnapshot
import com.zklh.dronecontroller.core.telemetry.hasReliableRtkPosition
import com.zklh.dronecontroller.core.mission.MissionPreview
import dji.v5.manager.diagnostic.WarningLevel
@Composable
internal fun PilotFlightHeader(sdk: DroneSdkState, telemetry: TelemetrySnapshot, camera: Boolean, status: String, alerts: DroneWarningState, onBack: () -> Unit, onAlerts: () -> Unit, onSettings: () -> Unit) {
val ink = PilotDesign.Ink
val muted = PilotDesign.Muted
val device = rememberPilotDeviceReadings(sdk.productConnected)
val instruments = rememberFlightInstrumentReadings(sdk.productConnected, telemetry.cameraComponent)
fun available(value: String) = if (sdk.productConnected) value else "—"
Row(Modifier.fillMaxWidth().height(42.dp).background(Color(0xFFE5EDF5)).padding(horizontal = 9.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
IconButton(onClick = onBack, modifier = Modifier.size(30.dp)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "返回首页", tint = ink) }
Text("飞行控制", color = ink, fontSize = 16.sp, lineHeight = 20.sp, fontWeight = FontWeight.Bold)
Surface(onClick = onAlerts, color = if (alerts.active) PilotDesign.Orange.copy(alpha = 0.18f) else PilotDesign.Teal.copy(alpha = 0.10f), shape = RoundedCornerShape(20.dp)) {
Text(if (alerts.active) "告警 ${alerts.count.coerceAtLeast(1)}" else status, color = if (alerts.active) PilotDesign.Orange else PilotDesign.Teal, fontSize = 11.sp, lineHeight = 14.sp, maxLines = 1, modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp))
}
Spacer(Modifier.weight(1f))
HeaderValue("GPS", available(if (telemetry.gpsValid) telemetry.gpsSatelliteCount.toString() else "—"), ink, muted)
if (!camera) HeaderValue("RTK", available(if (telemetry.hasReliableRtkPosition()) "固定解" else if (telemetry.rtkEnabled) "定位中" else "未启用"), ink, muted)
else {
HeaderValue("高度", "${instrumentNumber(instruments.relativeAltitude, 0)} m", ink, muted)
HeaderValue("速度", "${instrumentNumber(instruments.horizontalSpeed)} m/s", ink, muted)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Default.BatteryFull, null, tint = PilotDesign.Teal, modifier = Modifier.size(19.dp))
HeaderValue("电量", available(if (telemetry.batteryPercent >= 0) "${telemetry.batteryPercent}%" else "—"), ink, muted)
}
HeaderValue("图传", device.downlinkQuality?.let { "$it%" } ?: "—", ink, muted)
if (!camera) HeaderValue("风速", "${instrumentNumber(instruments.windSpeed)} m/s", ink, muted)
HeaderValue(if (camera) "飞行时间" else "时间", if (camera) device.flightTimeSeconds?.let { pilotDuration(it) } ?: "—" else rememberPilotTime(), ink, muted)
IconButton(onClick = onSettings, modifier = Modifier.size(30.dp)) { Icon(Icons.Default.Settings, "设备设置", tint = ink) }
}
}
@Composable
private fun HeaderValue(label: String, value: String, ink: Color, muted: Color) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Text(label, color = muted, fontSize = 11.sp, lineHeight = 16.sp, maxLines = 1)
Text(value, color = ink, fontSize = 11.sp, lineHeight = 16.sp, fontWeight = FontWeight.Medium, maxLines = 1)
}
}
@Composable
internal fun PilotTool(icon: ImageVector, label: String, active: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
Surface(onClick = onClick, enabled = enabled, color = if (active) PilotDesign.Blue else Color.Transparent, shape = RoundedCornerShape(6.dp), modifier = Modifier.fillMaxWidth().height(50.dp)) {
Column(Modifier.padding(vertical = 6.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) {
val ink = if (!enabled) PilotDesign.Muted.copy(alpha = 0.4f) else if (active) Color.White else PilotDesign.Ink
Icon(icon, null, tint = ink, modifier = Modifier.size(23.dp))
Text(label, color = ink, fontSize = 10.sp, lineHeight = 12.sp, maxLines = 1)
}
}
}
@Composable
internal fun PilotFlightMetrics(connected: Boolean, telemetry: TelemetrySnapshot, camera: Boolean, modifier: Modifier = Modifier) {
val readings = rememberFlightInstrumentReadings(connected, telemetry.cameraComponent)
Row(modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
PilotMetric("高度", "${instrumentNumber(readings.relativeAltitude, 0)} m", Modifier.weight(1f), true, Icons.Default.Height)
VerticalDivider(Modifier.height(53.dp), color = PilotDesign.Line)
PilotMetric(if (camera) "水平速度" else "距离返航点", if (camera) "${instrumentNumber(readings.horizontalSpeed)} m/s" else "${instrumentNumber(pilotHomeDistance(connected, telemetry), 0)} m", Modifier.weight(1.1f), true, if (camera) Icons.Default.Speed else Icons.Default.Route)
VerticalDivider(Modifier.height(53.dp), color = PilotDesign.Line)
PilotMetric(if (camera) "航向" else "垂直速度", if (camera) "${instrumentNumber(readings.heading, 0)}°" else "${instrumentNumber(readings.climbSpeed)} m/s", Modifier.weight(1f), true, if (camera) Icons.Default.Explore else Icons.Default.SwapVert)
if (!camera) {
VerticalDivider(Modifier.height(53.dp), color = PilotDesign.Line)
AttitudeIndicator(telemetry, connected, Modifier.size(76.dp))
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
Text("航向 ${instrumentNumber(readings.heading, 0)}°", color = PilotDesign.Ink, fontSize = 11.sp)
Text("俯仰 ${instrumentNumber(telemetry.attitudePitch.takeIf { connected }, 0)}°", color = PilotDesign.Muted, fontSize = 10.sp)
Text("横滚 ${instrumentNumber(telemetry.attitudeRoll.takeIf { connected }, 0)}°", color = PilotDesign.Muted, fontSize = 10.sp)
}
}
}
}
@Composable
internal fun PilotMissionFlightMetrics(connected: Boolean, telemetry: TelemetrySnapshot, mission: MissionPreview?, modifier: Modifier = Modifier) {
val readings = rememberFlightInstrumentReadings(connected, telemetry.cameraComponent)
val values = listOf(
"高度" to "${instrumentNumber(readings.relativeAltitude, 0)} m",
"水平速度" to "${instrumentNumber(readings.horizontalSpeed)} m/s",
"距离起点" to pilotHomeDistance(connected, telemetry)?.let { "${instrumentNumber(it / 1000.0)} km" }.orEmpty().ifBlank { "—" },
"航向" to "${instrumentNumber(readings.heading, 0)}°",
"航线长度" to (mission?.let { "${instrumentNumber(it.distanceMeters / 1000.0, 2)} km" } ?: "—"),
"预计时长" to (mission?.speed?.let { "${instrumentNumber(mission.distanceMeters / it / 60)} min" } ?: "—")
)
Row(modifier.background(Color(0xFF193543)).padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
values.forEachIndexed { index, (label, value) ->
if (index > 0) VerticalDivider(Modifier.height(32.dp), color = Color(0xFF405565))
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(5.dp)) {
Text(label, color = Color(0xFFB5C8D8), fontSize = 9.sp, lineHeight = 12.sp, maxLines = 1)
Text(value, color = Color.White, fontSize = 14.sp, lineHeight = 19.sp, fontWeight = FontWeight.Medium, maxLines = 1)
}
}
}
}
internal fun pilotHomeDistance(connected: Boolean, telemetry: TelemetrySnapshot): Double? {
if (!connected || !telemetry.locationValid || !telemetry.homeLocationValid) return null
val a = Math.toRadians(telemetry.latitude)
val b = Math.toRadians(telemetry.homeLatitude)
val d = Math.toRadians(telemetry.homeLongitude - telemetry.longitude)
val h = kotlin.math.sin((b-a)/2).let { it*it } + kotlin.math.cos(a)*kotlin.math.cos(b)*kotlin.math.sin(d/2).let { it*it }
return 6371000 * 2 * kotlin.math.asin(kotlin.math.sqrt(h.coerceIn(0.0, 1.0)))
}
@Composable
private fun AttitudeIndicator(telemetry: TelemetrySnapshot, connected: Boolean, modifier: Modifier) {
Canvas(modifier.clip(CircleShape).background(Color(0xFF377DC2))) {
val pitch = if (connected) telemetry.attitudePitch.toFloat() else 0f
val roll = if (connected) telemetry.attitudeRoll.toFloat() else 0f
rotate(-roll) {
val horizon = center.y + pitch.coerceIn(-45f, 45f) / 90f * size.height
drawRect(Color(0xFF328275), topLeft = Offset(0f, horizon), size = androidx.compose.ui.geometry.Size(size.width, (size.height-horizon).coerceAtLeast(0f)))
drawLine(Color(0xFFCEFCCB), Offset(0f, horizon), Offset(size.width, horizon), 2.dp.toPx())
for (i in -2..2) { val y = horizon + i*size.height*0.13f; drawLine(Color.White.copy(alpha = 0.65f), Offset(center.x-size.width*0.15f,y), Offset(center.x+size.width*0.15f,y), 1.dp.toPx()) }
}
drawCircle(Color.White.copy(alpha = 0.5f), size.minDimension/2 - 2.dp.toPx(), style = Stroke(2.dp.toPx()))
drawLine(Color.White, Offset(center.x-12.dp.toPx(),center.y), Offset(center.x+12.dp.toPx(),center.y), 2.dp.toPx())
drawCircle(Color.White, 2.dp.toPx(), center)
}
}
@Composable
internal fun PilotAlertsDialog(state: DroneWarningState, sdk: DroneSdkState, telemetry: TelemetrySnapshot, onClose: () -> Unit) {
var filter by remember { mutableStateOf(0) }
val liveItems = state.items
val warnings = liveItems.count { it.level in listOf(WarningLevel.WARNING, WarningLevel.SERIOUS_WARNING, WarningLevel.CAUTION, WarningLevel.UNKNOWN) }
val notices = liveItems.count { it.level == WarningLevel.NOTICE }
val normal = listOf("卫星信号" to (sdk.productConnected && telemetry.gpsValid), "飞行器链路" to sdk.productConnected, "遥控器链路" to sdk.productLinkConnected)
val healthyCount = normal.count { it.second }
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false)) {
Surface(color = Color(0xFFFBFDFF), shape = RoundedCornerShape(12.dp), modifier = Modifier.fillMaxWidth(0.64f).fillMaxHeight(0.83f)) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Default.Notifications, null, tint = PilotDesign.Ink)
Text("实时告警", color = PilotDesign.Ink, fontSize = 21.sp, lineHeight = 28.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f).padding(start = 12.dp))
Text("正常 $healthyCount 告警 $warnings", color = PilotDesign.Teal, fontSize = 12.sp)
IconButton(onClick = onClose) { Icon(Icons.Default.Close, "关闭告警") }
}
HorizontalDivider(color = PilotDesign.Line)
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(15.dp)) {
Column(Modifier.width(100.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
listOf("全部" to (liveItems.size + healthyCount), "告警" to warnings, "提示" to notices, "正常" to healthyCount).forEachIndexed { index, (label, count) ->
Surface(onClick = { filter = index }, color = if (filter == index) Color(0xFFE4F0FF) else Color.Transparent, shape = RoundedCornerShape(7.dp)) { Row(Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween) { Text(label, color = if (filter == index) PilotDesign.Blue else PilotDesign.Ink, fontSize = 13.sp); Text(count.toString(), color = PilotDesign.Muted, fontSize = 12.sp) } }
}
}
Column(Modifier.weight(1f).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
val selected = liveItems.filter { when (filter) { 1 -> it.level !in listOf(WarningLevel.NORMAL, WarningLevel.NOTICE); 2 -> it.level == WarningLevel.NOTICE; 3 -> false; else -> true } }
selected.forEach { item ->
val severe = item.level in listOf(WarningLevel.WARNING, WarningLevel.SERIOUS_WARNING)
val color = if (severe) PilotDesign.Red else PilotDesign.Orange
Surface(color = Color(0xFFFFFAF1), border = BorderStroke(1.dp, color.copy(alpha = 0.35f)), shape = RoundedCornerShape(8.dp)) {
Column(Modifier.fillMaxWidth().padding(12.dp), verticalArrangement = Arrangement.spacedBy(7.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) { Icon(Icons.Default.Warning, null, tint = color); Text(item.title.ifBlank { item.message }, color = PilotDesign.Ink, fontWeight = FontWeight.Bold, fontSize = 14.sp, modifier = Modifier.padding(start = 10.dp)) }
Text(item.description.ifBlank { item.message }, color = PilotDesign.Muted, fontSize = 12.sp, lineHeight = 18.sp)
if (item.code.isNotBlank()) Text("设备告警代码 ${item.code}", color = PilotDesign.Muted, fontSize = 10.sp)
}
}
}
if (liveItems.isEmpty() && state.active && filter != 3) PilotCard(Modifier.fillMaxWidth()) { Text(state.message, color = PilotDesign.Orange, fontSize = 13.sp) }
if (filter == 0 || filter == 3) normal.filter { it.second }.forEach { (label, _) ->
PilotCard(Modifier.fillMaxWidth()) { Row(verticalAlignment = Alignment.CenterVertically) { Icon(Icons.Default.CheckCircle, null, tint = PilotDesign.Teal); Text("${label}正常", color = PilotDesign.Ink, fontSize = 14.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 10.dp)) } }
}
if (selected.isEmpty() && (filter == 1 || filter == 2 || (filter == 3 && healthyCount == 0))) Text("当前分类暂无状态信息", color = PilotDesign.Muted, fontSize = 13.sp, modifier = Modifier.padding(12.dp))
}
}
HorizontalDivider(color = PilotDesign.Line)
Row(verticalAlignment = Alignment.CenterVertically) { Text("请根据现场情况及时处置,确保飞行安全。", color = PilotDesign.Muted, fontSize = 11.sp, modifier = Modifier.weight(1f)); PilotPrimaryButton("已知晓", onClose) }
}
}
}
}
@Composable
internal fun PilotDeviceDialog(sdk: DroneSdkState, telemetry: TelemetrySnapshot, simulator: Boolean, live: Boolean, liveBusy: Boolean, onSimulator: () -> Unit, onLive: () -> Unit, onMapSettings: () -> Unit, onClose: () -> Unit) {
val device = rememberPilotDeviceReadings(sdk.productConnected)
AlertDialog(onDismissRequest = onClose, title = { Text("设备与作业状态") }, text = {
Column(Modifier.verticalScroll(rememberScrollState())) {
PilotDetail("飞行器", telemetry.productType.replace('_', ' ').ifBlank { "未连接" })
PilotDetail("飞机序列号", sdk.aircraftSerialNumber.ifBlank { "—" })
PilotDetail("固件版本", telemetry.firmwareVersion.ifBlank { "—" })
PilotDetail("返航高度", device.goHomeHeight?.let { "$it m" } ?: "—")
PilotDetail("限高", if (sdk.productConnected) "${telemetry.heightLimit} m" else "—")
PilotDetail("遥控器挡位", if (sdk.productLinkConnected) remoteControllerGearText(telemetry.gear) else "—")
PilotDetail("累计飞行距离", if (sdk.productConnected) "${instrumentNumber(telemetry.totalFlightDistance)} m" else "—")
PilotDetail("累计飞行时间", if (sdk.productConnected) pilotDuration(telemetry.totalFlightTime.toInt()) else "—")
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedButton(onClick = onLive, enabled = sdk.productConnected && !liveBusy) { Text(if (live) "停止直播" else "开启直播") }
OutlinedButton(onClick = onSimulator, enabled = sdk.productConnected && !telemetry.isFlying) { Text(if (simulator) "关闭模拟器" else "开启模拟器") }
}
OutlinedButton(onClick = onMapSettings) {
Icon(Icons.Default.Layers, null, Modifier.size(17.dp))
Text("图层配置", Modifier.padding(start = 6.dp))
}
}
}, confirmButton = { TextButton(onClick = onClose) { Text("关闭") } })
}
@@ -1,6 +1,5 @@
package com.zklh.dronecontroller.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
@@ -15,181 +14,160 @@ import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.zklh.dronecontroller.core.msdk.DroneSdkState
import com.zklh.dronecontroller.core.telemetry.TelemetrySnapshot
private val HomeBackground = Color(0xFF090D12)
private val HomeCardColor = Color(0xE6151C24)
private val HomeSecondary = Color(0xFFA2AFBF)
private val HomeAccent = Color(0xFF3C91FF)
private val HomeOnline = Color(0xFF42D6AC)
import com.zklh.dronecontroller.core.telemetry.hasReliableRtkPosition
import dji.sampleV5.aircraft.R
@Composable
internal fun PilotHomeScreen(
sdkState: DroneSdkState,
telemetry: TelemetrySnapshot,
commandMessage: String,
cloudConnected: Boolean,
cloudTenantName: String,
cloudUsername: String,
onOpenCloud: () -> Unit,
onOpenPreflight: () -> Unit,
onOpenMission: () -> Unit,
onEnterFlight: () -> Unit,
onRetryConnect: () -> Unit
sdkState: DroneSdkState, telemetry: TelemetrySnapshot, commandMessage: String,
cloudConnected: Boolean, cloudTenantName: String, cloudUsername: String,
onOpenCloud: () -> Unit, onOpenPreflight: () -> Unit, onOpenMission: () -> Unit,
onEnterFlight: () -> Unit, onRetryConnect: () -> Unit,
warningState: com.zklh.dronecontroller.core.diagnostics.DroneWarningState = com.zklh.dronecontroller.core.diagnostics.DroneWarningState()
) {
BoxWithConstraints(Modifier.fillMaxSize().background(HomeBackground)) {
val compact = maxHeight < 560.dp
val pad = if (compact) 14.dp else 20.dp
val gap = if (compact) 10.dp else 14.dp
Column(Modifier.fillMaxSize().padding(pad), verticalArrangement = Arrangement.spacedBy(gap)) {
val connected = sdkState.productConnected
val device = rememberPilotDeviceReadings(connected)
fun reading(value: String) = if (connected) value else "—"
BoxWithConstraints(Modifier.fillMaxSize().background(PilotDesign.PageBrush)) {
val compact = maxHeight < 500.dp
val pad = if (compact) 12.dp else 16.dp
Column(Modifier.fillMaxSize().padding(pad), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Row(Modifier.height(35.dp), verticalAlignment = Alignment.CenterVertically) {
Text("飞行工作台", color = PilotDesign.Ink, fontSize = 27.sp, lineHeight = 34.sp, fontWeight = FontWeight.Bold)
Spacer(Modifier.width(16.dp))
VerticalDivider(Modifier.height(22.dp), color = PilotDesign.Line)
Text("安全飞行 高效作业", color = PilotDesign.Muted, fontSize = 12.sp, modifier = Modifier.padding(start = 14.dp))
Spacer(Modifier.weight(1f))
Text(rememberPilotTime("yyyy年M月d日 E HH:mm"), color = PilotDesign.Ink, fontSize = 12.sp)
IconButton(onClick = onOpenPreflight, modifier = Modifier.size(36.dp)) { Icon(Icons.Default.Settings, "设备与飞前检查", tint = PilotDesign.Ink) }
}
Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
PilotCard(Modifier.weight(0.27f).fillMaxHeight()) {
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Filled.Navigation, null, tint = HomeAccent, modifier = Modifier.size(26.dp))
Spacer(Modifier.width(10.dp))
Text("飞行工作台", color = Color.White, fontWeight = FontWeight.Bold, fontSize = if (compact) 20.sp else 24.sp)
Spacer(Modifier.weight(1f))
HomeConnectionBadge(if (sdkState.productLinkConnected) "遥控器已连接" else "等待连接遥控器", sdkState.productLinkConnected)
Text("飞行器连接", color = PilotDesign.Ink, fontSize = 16.sp, lineHeight = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))
PilotStatus(if (connected) "已连接" else "未连接", connected)
}
Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(gap)) {
Surface(color = HomeCardColor, shape = RoundedCornerShape(8.dp), border = BorderStroke(1.dp, Color.White.copy(alpha = 0.08f)), modifier = Modifier.weight(0.62f).fillMaxHeight()) {
Column(Modifier.padding(pad).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(gap)) {
Row(Modifier.padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.size(50.dp).background(PilotDesign.Background, RoundedCornerShape(7.dp)), contentAlignment = Alignment.Center) { Icon(Icons.Default.Flight, null, tint = PilotDesign.Ink, modifier = Modifier.size(32.dp)) }
Column(Modifier.weight(1f).padding(start = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(if (connected) telemetry.productType.replace('_', ' ').ifBlank { "飞行器" } else "等待连接飞行器", color = PilotDesign.Ink, fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.Bold, maxLines = 2)
Text("SN: ${sdkState.aircraftSerialNumber.ifBlank { "—" }}", color = PilotDesign.Muted, fontSize = 10.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
HorizontalDivider(color = PilotDesign.Line)
PilotDetail("固件版本", reading(telemetry.firmwareVersion.ifBlank { "—" }))
PilotDetail("飞控状态", if (!connected) "未连接" else if (warningState.active) "查看告警" else "已连接", if (connected && !warningState.active) PilotDesign.Teal else PilotDesign.Muted)
PilotDetail("传感器状态", if (!connected) "未获取" else if (warningState.active) "需检查" else "未报告异常", if (connected && !warningState.active) PilotDesign.Teal else PilotDesign.Muted)
PilotDetail("机身温度", "—")
if (!connected) TextButton(onClick = onRetryConnect) { Text("重试连接", fontSize = 12.sp) }
Text(commandMessage, color = PilotDesign.Muted, fontSize = 10.sp, maxLines = 3, overflow = TextOverflow.Ellipsis)
}
}
Column(Modifier.weight(0.44f).fillMaxHeight(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
AircraftIllustration(Modifier.fillMaxWidth().weight(1f))
Text("— 向更广阔的天空 开启专业作业 —", color = PilotDesign.Muted, fontSize = 12.sp, modifier = Modifier.padding(bottom = 24.dp))
}
Column(Modifier.weight(0.29f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(9.dp)) {
PilotCard(Modifier.weight(1.35f).fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text("当前设备", color = HomeSecondary, fontSize = 13.sp)
Spacer(Modifier.weight(1f))
HomeConnectionBadge(if (sdkState.productConnected) "已连接" else "未连接", sdkState.productConnected)
Text("电池状态", color = PilotDesign.Ink, fontSize = 16.sp, lineHeight = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))
TextButton(onClick = onOpenPreflight, contentPadding = PaddingValues(0.dp), modifier = Modifier.height(24.dp)) { Text("查看更多 ›", fontSize = 10.sp) }
}
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
AircraftIllustration(Modifier.weight(0.42f).height(if (compact) 96.dp else 142.dp))
Column(Modifier.weight(0.54f).padding(start = 12.dp), verticalArrangement = Arrangement.spacedBy(7.dp)) {
Text(
if (sdkState.productConnected) telemetry.productType.replace('_', ' ').ifBlank { "无人机已连接" } else "等待无人机连接",
color = Color.White, fontSize = if (compact) 20.sp else 26.sp, fontWeight = FontWeight.Bold,
maxLines = 2, overflow = TextOverflow.Ellipsis
)
Text("SN ${sdkState.aircraftSerialNumber.ifBlank { "—" }}", color = HomeSecondary, fontSize = 11.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(telemetry.remoteControllerType.replace('_', ' ').ifBlank { "遥控器" }, color = HomeSecondary, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
Row(Modifier.weight(1f).fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Default.BatteryFull, null, tint = PilotDesign.Teal, modifier = Modifier.size(if (compact) 42.dp else 56.dp))
Column(Modifier.weight(1f)) {
Text(reading(if (telemetry.batteryPercent in 0..100) "${telemetry.batteryPercent}%" else "—"), color = PilotDesign.Ink, fontSize = if (compact) 30.sp else 38.sp, lineHeight = if (compact) 36.sp else 44.sp, fontWeight = FontWeight.Bold)
Text("剩余电量", color = PilotDesign.Muted, fontSize = 11.sp)
}
}
HorizontalDivider(color = Color.White.copy(alpha = 0.07f))
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
HomeMetric(Icons.Filled.BatteryFull, "飞行器电量", if (sdkState.productConnected && telemetry.batteryPercent in 0..100) "${telemetry.batteryPercent}%" else "—")
HomeMetric(Icons.Filled.MyLocation, "卫星数", if (sdkState.productConnected && telemetry.gpsValid) telemetry.gpsSatelliteCount.toString() else "—")
HomeMetric(Icons.Filled.Radio, "遥控链路", if (sdkState.productLinkConnected) "已连接" else "未连接")
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
OutlinedButton(onClick = onOpenPreflight, shape = RoundedCornerShape(8.dp), border = BorderStroke(1.dp, Color(0xFF384659)), colors = ButtonDefaults.outlinedButtonColors(contentColor = Color.White), modifier = Modifier.weight(1f).height(46.dp)) {
Icon(Icons.Filled.Shield, null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(7.dp))
Text("飞前检查", maxLines = 1)
}
Button(onClick = { if (!sdkState.productConnected) onRetryConnect(); onEnterFlight() }, shape = RoundedCornerShape(8.dp), colors = ButtonDefaults.buttonColors(containerColor = HomeAccent), modifier = Modifier.weight(1.35f).height(46.dp)) {
Text("进入飞行", fontWeight = FontWeight.Bold, fontSize = 16.sp)
Spacer(Modifier.width(12.dp))
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, null)
VerticalDivider(Modifier.height(76.dp), color = PilotDesign.Line)
Column(Modifier.weight(1f).padding(start = 12.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
HomeBatteryMetric("电压", reading(if (telemetry.batteryVoltageKnown) "${instrumentNumber(telemetry.batteryVoltageMv / 1000.0)} V" else "—"))
HomeBatteryMetric("电池温度", reading(if (telemetry.batteryTemperatureKnown) "${instrumentNumber(telemetry.batteryTemperature)} °C" else "—"))
HomeBatteryMetric("预计可用时间", reading(if (telemetry.remainingFlightTimeKnown) "${telemetry.remainingFlightTime / 60} min" else "—"))
}
}
}
}
Column(Modifier.weight(0.38f).fillMaxHeight().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(gap)) {
Surface(color = HomeCardColor, shape = RoundedCornerShape(8.dp), border = BorderStroke(1.dp, Color.White.copy(alpha = 0.08f))) {
Column(Modifier.fillMaxWidth().padding(pad), verticalArrangement = Arrangement.spacedBy(if (compact) 12.dp else 20.dp)) {
PilotCard(Modifier.weight(0.92f).fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Filled.Cloud, null, tint = HomeAccent)
Spacer(Modifier.width(9.dp))
Text("云平台", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 18.sp)
Text("卫星与定位", color = PilotDesign.Ink, fontSize = 16.sp, lineHeight = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))
PilotStatus(if (connected && telemetry.hasReliableRtkPosition()) "RTK 固定" else if (connected && telemetry.rtkEnabled) "等待 RTK" else "RTK 未启用", connected && telemetry.hasReliableRtkPosition())
}
Spacer(Modifier.weight(1f))
Text(if (cloudConnected) "已连接" else "未连接", color = if (cloudConnected) HomeOnline else HomeSecondary, fontSize = 12.sp)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
PilotMetric("RTK 卫星数", reading(if (telemetry.rtkEnabled) telemetry.rtkSatelliteCount.toString() else "—"), Modifier.weight(1f))
PilotMetric("GPS 卫星数", reading(if (telemetry.gpsValid) telemetry.gpsSatelliteCount.toString() else "—"), Modifier.weight(1f))
PilotMetric("水平标准差", if (telemetry.hasReliableRtkPosition()) device.rtkHorizontalStdMeters?.let { "${instrumentNumber(it * 100)} cm" } ?: "—" else "—", Modifier.weight(1f))
}
}
PilotCard(Modifier.weight(0.82f).fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text("图传链路", color = PilotDesign.Ink, fontSize = 16.sp, lineHeight = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))
PilotStatus(if (connected && device.downlinkQuality != null) "已接入" else "未获取", connected && device.downlinkQuality != null)
}
HomeDetail("租户", cloudTenantName.ifBlank { "未配置" })
HomeDetail("账号", cloudUsername.ifBlank { "未配置" })
OutlinedButton(onClick = onOpenCloud, shape = RoundedCornerShape(8.dp), border = BorderStroke(1.dp, Color(0xFF384659)), colors = ButtonDefaults.outlinedButtonColors(contentColor = Color.White), modifier = Modifier.fillMaxWidth().height(42.dp)) {
Text("管理云平台")
Spacer(Modifier.weight(1f))
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, null)
}
}
}
Surface(onClick = onOpenMission, color = HomeCardColor, shape = RoundedCornerShape(8.dp), border = BorderStroke(1.dp, Color.White.copy(alpha = 0.08f))) {
Row(Modifier.fillMaxWidth().padding(pad), verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Filled.Route, null, tint = HomeAccent, modifier = Modifier.size(30.dp))
Column(Modifier.weight(1f).padding(horizontal = 12.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
Text("航线任务", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 17.sp)
Text("导入 · 上传 · 执行", color = HomeSecondary, fontSize = 11.sp)
}
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, null, tint = HomeSecondary)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
PilotMetric("信号质量", device.downlinkQuality?.let { "$it%" } ?: "—", Modifier.weight(1f))
PilotMetric("遥控链路", if (sdkState.productLinkConnected) "已连接" else "未连接", Modifier.weight(1f))
PilotMetric("传输速率", device.dataRateMbps?.let { "${instrumentNumber(it)} Mbps" } ?: "—", Modifier.weight(1f))
}
}
}
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(Icons.Filled.Radio, null, tint = HomeSecondary, modifier = Modifier.size(16.dp))
Text(commandMessage.ifBlank { if (sdkState.isRegistered) "设备服务已就绪" else "正在初始化设备服务" }, color = HomeSecondary, fontSize = 11.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
if (!sdkState.productConnected) {
TextButton(onClick = onRetryConnect, contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp), modifier = Modifier.height(32.dp)) { Text("重试连接", color = HomeAccent, fontSize = 12.sp) }
}
Row(Modifier.fillMaxWidth().height(if (compact) 76.dp else 98.dp), horizontalArrangement = Arrangement.spacedBy(9.dp)) {
HomeEntry("飞前检查", "设备自检 安全起飞", Icons.Default.AssignmentTurnedIn, Color(0xFFCCE5FC), false, Modifier.weight(1f), onOpenPreflight)
HomeEntry("进入飞行", "起飞作业 掌控全局", Icons.Default.Send, Color(0xFF4095DC), true, Modifier.weight(1f), onEnterFlight)
HomeEntry("云服务", if (cloudConnected) "数据同步 已连接" else "数据同步 协同管理", Icons.Default.CloudQueue, Color(0xFF42B2A3), true, Modifier.weight(1f), onOpenCloud)
HomeEntry("航线任务", "规划航线 自动作业", Icons.Default.Route, Color(0xFFCCE5FC), false, Modifier.weight(1f), onOpenMission)
}
}
}
}
@Composable
private fun HomeConnectionBadge(text: String, online: Boolean) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Box(Modifier.size(6.dp).background(if (online) HomeOnline else HomeSecondary, CircleShape))
Text(text, color = if (online) HomeOnline else HomeSecondary, fontSize = 12.sp)
private fun HomeEntry(title: String, subtitle: String, icon: ImageVector, color: Color, light: Boolean, modifier: Modifier, onClick: () -> Unit) {
Surface(onClick = onClick, modifier = modifier.fillMaxHeight(), shape = RoundedCornerShape(8.dp), color = color) {
Row(Modifier.background(Brush.linearGradient(listOf(color.copy(alpha = 0.55f), color))).padding(14.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Box(Modifier.size(52.dp).background(if (light) Color.Black.copy(alpha = 0.12f) else PilotDesign.Blue, CircleShape), contentAlignment = Alignment.Center) { Icon(icon, null, tint = Color.White, modifier = Modifier.size(30.dp)) }
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(title, color = if (light) Color.White else PilotDesign.Ink, fontSize = 20.sp, lineHeight = 26.sp, fontWeight = FontWeight.Bold, maxLines = 1)
Text(subtitle, color = if (light) Color.White else Color(0xFF42658B), fontSize = 11.sp, maxLines = 1)
}
}
@Composable
private fun HomeMetric(icon: ImageVector, label: String, value: String) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Icon(icon, null, tint = HomeSecondary, modifier = Modifier.size(14.dp))
Text(label, color = HomeSecondary, fontSize = 11.sp)
Box(Modifier.size(26.dp).background(Color.White.copy(alpha = 0.65f), CircleShape), contentAlignment = Alignment.Center) { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, null, tint = PilotDesign.Ink) }
}
Text(value, color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Medium)
}
}
@Composable
private fun HomeDetail(label: String, value: String) {
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
Text(label, color = HomeSecondary, fontSize = 11.sp)
Text(value, color = Color.White, fontSize = 15.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
@Composable
private fun AircraftIllustration(modifier: Modifier) {
// Render only the aircraft region of the supplied reference; all surrounding UI is native Compose.
val reference = ImageBitmap.imageResource(R.drawable.pilot_aircraft_reference)
Canvas(modifier) {
val c = center
val radius = size.minDimension * 0.43f
drawCircle(HomeAccent.copy(alpha = 0.04f), radius, c)
drawCircle(HomeAccent.copy(alpha = 0.14f), radius, c, style = Stroke(1.dp.toPx()))
listOf(Offset(-0.7f, -0.6f), Offset(0.7f, -0.6f), Offset(-0.7f, 0.6f), Offset(0.7f, 0.6f)).forEach { direction ->
val rotor = c + direction * radius
drawLine(Color(0xFF7C8A9B), c, rotor, radius * 0.12f, StrokeCap.Round)
drawCircle(Color(0xFFACBAC9), radius * 0.14f, rotor)
drawLine(Color(0xFFDAE3ED), rotor - Offset(radius * 0.26f, radius * 0.08f), rotor + Offset(radius * 0.26f, radius * 0.08f), radius * 0.06f, StrokeCap.Round)
}
drawOval(Color(0xFFB6C2D0), topLeft = c - Offset(radius * 0.23f, radius * 0.40f), size = androidx.compose.ui.geometry.Size(radius * 0.46f, radius * 0.8f))
drawCircle(Color(0xFF233449), radius * 0.13f, c + Offset(0f, radius * 0.35f))
drawCircle(HomeAccent, radius * 0.055f, c + Offset(0f, radius * 0.35f))
val src = IntSize((reference.width * 0.423f).toInt(), (reference.height * 0.50f).toInt())
val scale = minOf(size.width / src.width, size.height / src.height)
val dst = IntSize((src.width * scale).toInt(), (src.height * scale).toInt())
drawImage(reference, srcOffset = IntOffset((reference.width * 0.277f).toInt(), (reference.height * 0.123f).toInt()), srcSize = src,
dstOffset = IntOffset(((size.width - dst.width) / 2).toInt(), ((size.height - dst.height) / 2).toInt()), dstSize = dst)
}
}
@Preview(name = "Home · RC landscape", widthDp = 960, heightDp = 540)
@Composable
private fun PilotHomePreview() {
PilotHomeScreen(DroneSdkState(), TelemetrySnapshot(), "等待连接无人机", false, "", "", {}, {}, {}, {}, {})
private fun HomeBatteryMetric(label: String, value: String) {
Column(verticalArrangement = Arrangement.spacedBy(1.dp)) {
Text(value, color = PilotDesign.Ink, fontSize = 12.sp, lineHeight = 15.sp, fontWeight = FontWeight.Medium)
Text(label, color = PilotDesign.Muted, fontSize = 9.sp, lineHeight = 12.sp)
}
}
@@ -0,0 +1,90 @@
package com.zklh.dronecontroller.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.zklh.dronecontroller.core.cloud.CloudMqttState
@Composable
internal fun PilotLoginScreen(url: String, onUrlChange: (String) -> Unit, mqtt: String, onMqttChange: (String) -> Unit, tenant: String, onTenantChange: (String) -> Unit, username: String, onUsernameChange: (String) -> Unit, password: String, onPasswordChange: (String) -> Unit, cloud: CloudMqttState, message: String, isError: Boolean, onBack: () -> Unit, onLogin: () -> Unit, onRefresh: () -> Unit, onLogout: () -> Unit) {
var visible by remember { mutableStateOf(false) }
var config by remember { mutableStateOf(false) }
Column(Modifier.fillMaxSize().background(PilotDesign.PageBrush).imePadding()) {
Box(Modifier.fillMaxWidth().height(52.dp).background(Color.White).padding(horizontal = 16.dp)) {
IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "返回云服务", tint = PilotDesign.Ink) }
Text("Cloud Api Platform", color = PilotDesign.Ink, fontSize = 19.sp, lineHeight = 24.sp, fontWeight = FontWeight.Bold, modifier = Modifier.align(Alignment.Center))
Row(Modifier.align(Alignment.CenterEnd), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = { config = true }) { Icon(Icons.Default.Settings, "云端地址配置", tint = PilotDesign.Ink) }
IconButton(onClick = onRefresh) { Icon(Icons.Default.Refresh, "刷新连接状态", tint = PilotDesign.Ink) }
TextButton(onClick = onLogout, enabled = !cloud.connecting, colors = ButtonDefaults.textButtonColors(containerColor = Color(0xFFE7EFF7)), shape = RoundedCornerShape(7.dp)) { Text("注销", color = PilotDesign.Ink) }
}
}
Box(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(24.dp), contentAlignment = Alignment.Center) {
Surface(color = Color.White.copy(alpha = 0.9f), shape = RoundedCornerShape(10.dp), modifier = Modifier.width(372.dp)) {
Column(Modifier.padding(25.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(13.dp)) {
Text("登录", color = PilotDesign.Ink, fontSize = 23.sp, lineHeight = 30.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(bottom = 4.dp))
LoginInput(tenant, onTenantChange, "租户名称", Icons.Default.Business, !cloud.connecting)
LoginInput(username, onUsernameChange, "账号", Icons.Default.PersonOutline, !cloud.connecting)
LoginInput(password, onPasswordChange, "密码", Icons.Default.Lock, !cloud.connecting,
transformation = if (visible) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
trailing = { IconButton(onClick = { visible = !visible }, modifier = Modifier.size(30.dp)) { Icon(if (visible) Icons.Default.Visibility else Icons.Default.VisibilityOff, if (visible) "隐藏密码" else "显示密码", tint = PilotDesign.Muted, modifier = Modifier.size(21.dp)) } })
Button(onClick = onLogin, enabled = !cloud.connecting && tenant.isNotBlank() && username.isNotBlank() && password.isNotBlank(), colors = ButtonDefaults.buttonColors(containerColor = PilotDesign.Blue), shape = RoundedCornerShape(7.dp), contentPadding = PaddingValues(0.dp), modifier = Modifier.fillMaxWidth().height(42.dp)) {
Text(if (cloud.connecting) "正在连接…" else "登录", fontSize = 16.sp, lineHeight = 22.sp, fontWeight = FontWeight.Bold)
}
PilotStatus(if (cloud.connected) "MQTT 连接已建立" else if (cloud.connecting) "MQTT 正在连接" else "MQTT 连接已断开", cloud.connected, Modifier.padding(top = 5.dp))
val text = if (isError) message else cloud.lastError ?: message.takeIf { it.contains("失败") }.orEmpty()
if (text.isNotBlank()) Text(text, color = PilotDesign.Red, fontSize = 11.sp, textAlign = TextAlign.Center)
}
}
}
}
if (config) {
var draftUrl by remember { mutableStateOf(url) }
var draftMqtt by remember { mutableStateOf(mqtt) }
val valid = runCatching { java.net.URI(draftUrl).let { it.scheme in listOf("http", "https") && !it.host.isNullOrBlank() } }.getOrDefault(false)
AlertDialog(onDismissRequest = { config = false }, title = { Text("云服务配置") }, text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
OutlinedTextField(draftUrl, { draftUrl = it }, label = { Text("HTTP / HTTPS 服务地址") }, singleLine = true, isError = !valid, modifier = Modifier.fillMaxWidth())
OutlinedTextField(draftMqtt, { draftMqtt = it }, label = { Text("MQTT 地址(可选)") }, singleLine = true, modifier = Modifier.fillMaxWidth())
Text("MQTT 留空时使用平台登录接口返回的地址。保存后重新登录生效。", color = PilotDesign.Muted, fontSize = 12.sp)
}
}, confirmButton = { TextButton(onClick = { onUrlChange(draftUrl.trim()); onMqttChange(draftMqtt.trim()); config = false }, enabled = valid && !cloud.connecting) { Text("保存") } }, dismissButton = { TextButton(onClick = { config = false }) { Text("取消") } })
}
}
@Composable
private fun LoginInput(value: String, change: (String) -> Unit, placeholder: String, icon: androidx.compose.ui.graphics.vector.ImageVector, enabled: Boolean, transformation: VisualTransformation = VisualTransformation.None, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, trailing: (@Composable () -> Unit)? = null) {
Surface(color = Color.White.copy(alpha = 0.8f), border = BorderStroke(1.dp, Color(0xFFD4DEEB)), shape = RoundedCornerShape(7.dp), modifier = Modifier.fillMaxWidth().height(42.dp)) {
Row(Modifier.padding(horizontal = 14.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(13.dp)) {
Icon(icon, null, tint = Color(0xFF798699), modifier = Modifier.size(21.dp))
BasicTextField(value = value, onValueChange = change, enabled = enabled, singleLine = true,
textStyle = MaterialTheme.typography.bodyLarge.copy(color = PilotDesign.Ink, fontSize = 14.sp, lineHeight = 20.sp),
visualTransformation = transformation, keyboardOptions = keyboardOptions,
cursorBrush = SolidColor(PilotDesign.Blue), modifier = Modifier.weight(1f),
decorationBox = { field -> Box { if (value.isEmpty()) Text(placeholder, color = Color(0xFF8590A3), fontSize = 14.sp, lineHeight = 20.sp); field() } })
trailing?.invoke()
}
}
}
@@ -0,0 +1,252 @@
package com.zklh.dronecontroller.ui
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.http.HttpLogger
import com.mapbox.mapboxsdk.annotations.*
import com.mapbox.mapboxsdk.annotations.Annotation
import com.mapbox.mapboxsdk.camera.CameraPosition
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.geometry.LatLngBounds
import com.mapbox.mapboxsdk.maps.MapView
import com.mapbox.mapboxsdk.maps.MapboxMapOptions
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.Style
import com.zklh.dronecontroller.core.mission.MissionPreview
import com.zklh.dronecontroller.core.telemetry.TelemetrySnapshot
import com.zklh.dronecontroller.core.map.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/** Every preview observes the same persisted configuration. */
@Composable
internal fun PilotMap(connected: Boolean, telemetry: TelemetrySnapshot, modifier: Modifier = Modifier, mission: MissionPreview? = null, controls: Boolean = true, controlsLeading: Boolean = false, onConfigure: (() -> Unit)? = null) {
val context = LocalContext.current
val store = remember { MapConfigurationStore.get(context) }
val config by store.configuration.collectAsState()
var showSettings by remember { mutableStateOf(false) }
val configure = onConfigure ?: { showSettings = true }
key(config.provider, config.key) {
when (config.provider) {
MapProvider.DEFAULT, MapProvider.PRIVATE, MapProvider.TIANDITU -> PilotRasterMap(connected, telemetry, modifier, mission, controls, controlsLeading, config, configure)
MapProvider.AMAP, MapProvider.BAIDU -> PilotVendorMap(connected, telemetry, modifier, mission, controls, controlsLeading, config, configure)
}
}
if (showSettings) PilotMapSettings({ showSettings = false },
if (telemetry.locationValid) telemetry.latitude else 35.0, if (telemetry.locationValid) telemetry.longitude else 104.0)
}
@Suppress("DEPRECATION")
@Composable
private fun PilotRasterMap(connected: Boolean, telemetry: TelemetrySnapshot, modifier: Modifier, mission: MissionPreview?, controls: Boolean, controlsLeading: Boolean, config: MapConfiguration, onConfigure: () -> Unit) {
val context = LocalContext.current
val lifecycle = LocalLifecycleOwner.current.lifecycle
var map by remember { mutableStateOf<MapboxMap?>(null) }
val satellite = config.satellite
val scope = rememberCoroutineScope()
val store = remember { MapConfigurationStore.get(context) }
val platformMaps = remember { PlatformMapRepository.get(context) }
val platformState by platformMaps.state.collectAsState()
val platformDefault = config.provider == MapProvider.DEFAULT
val coordinates = if (platformDefault) platformState.catalog.coordinates else config.coordinateSystem
LaunchedEffect(platformDefault) { if (platformDefault) platformMaps.refresh() }
fun toggleSatellite() { scope.launch { store.save(config.copy(satellite = !satellite)) } }
fun display(latitude: Double, longitude: Double): LatLng = MapCoordinates.display(latitude, longitude, coordinates).let { LatLng(it.latitude, it.longitude) }
val positions = MapLivePositions.from(connected, telemetry, coordinates)
var styleGeneration by remember { mutableStateOf(0) }
var error by remember { mutableStateOf<String?>(null) }
var annotations by remember { mutableStateOf<List<Annotation>>(emptyList()) }
var aircraftMarker by remember { mutableStateOf<Marker?>(null) }
var homeMarker by remember { mutableStateOf<Marker?>(null) }
var rcMarker by remember { mutableStateOf<Marker?>(null) }
val aircraftIcons = remember { mutableMapOf<Int, Icon>() }
var cameraRevision by remember { mutableStateOf(0) }
val mapKey = config.key
val minZoom = if (platformDefault) 0.0 else if (config.provider == MapProvider.PRIVATE) config.activeLayer.minZoom.toDouble() else TiandituMapSource.MinZoom
val maxZoom = if (platformDefault) 22.0 else if (config.provider == MapProvider.PRIVATE) config.activeLayer.maxZoom.toDouble() else TiandituMapSource.MaxZoom
var reload by remember { mutableStateOf(0) }
val accessError by produceState<String?>(null, config, reload) {
value = null
value = if (platformDefault) null else if (config.provider == MapProvider.TIANDITU) withContext(Dispatchers.IO) { TiandituMapSource.checkAccess(satellite, mapKey) } else config.activeLayer.validationError()
}
val view = remember(context) {
HttpLogger.logRequestUrl = false
Mapbox.getInstance(context)
// TextureView participates in Compose clipping and overlays, unlike a
// separate GL SurfaceView beside the DJI video SurfaceView.
val options = MapboxMapOptions.createFromAttributes(context).textureMode(true)
.camera(CameraPosition.Builder().target(LatLng(35.0, 104.0)).zoom(3.0).build())
MapView(context, options).apply {
onCreate(null)
addOnDidFailLoadingMapListener { error = "地图加载失败,请检查网络" }
addOnCameraDidChangeListener { cameraRevision++ }
}
}
DisposableEffect(view, lifecycle) {
val observer = LifecycleEventObserver { _, event -> when (event) {
Lifecycle.Event.ON_START -> view.onStart()
Lifecycle.Event.ON_RESUME -> view.onResume()
Lifecycle.Event.ON_PAUSE -> view.onPause()
Lifecycle.Event.ON_STOP -> view.onStop()
else -> Unit
} }
lifecycle.addObserver(observer)
if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) view.onStart()
if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) view.onResume()
onDispose { lifecycle.removeObserver(observer); view.onPause(); view.onStop(); view.onDestroy() }
}
LaunchedEffect(view) {
view.getMapAsync { ready ->
map = ready
ready.uiSettings.isCompassEnabled = false
ready.uiSettings.isLogoEnabled = false
ready.uiSettings.isAttributionEnabled = true
ready.uiSettings.attributionGravity = android.view.Gravity.BOTTOM or android.view.Gravity.START
}
}
LaunchedEffect(map, config, reload, if (platformDefault) platformState.catalog else null) {
error = if (config.provider == MapProvider.TIANDITU && mapKey.isBlank()) "未配置天地图 Key" else null
map?.let { ready ->
// Reset the lower bound before switching between disjoint layer ranges.
ready.setMinZoomPreference(0.0)
ready.setMaxZoomPreference(maxZoom)
ready.setMinZoomPreference(minZoom)
val style = if (platformDefault) PlatformMapSource.styleJson(platformState.catalog) else if (config.provider == MapProvider.PRIVATE) PrivateMapSource.styleJson(config.activeLayer) else TiandituMapSource.styleJson(satellite, mapKey)
annotations.forEach { ready.removeAnnotation(it) }
aircraftMarker?.let { ready.removeMarker(it) }; homeMarker?.let { ready.removeMarker(it) }
rcMarker?.let { ready.removeMarker(it) }
annotations = emptyList(); aircraftMarker = null; homeMarker = null; rcMarker = null
styleGeneration = 0
ready.setStyle(Style.Builder().fromJson(style)) { styleGeneration++ }
}
}
fun centerMap() {
val ready = map ?: return
val points = positions.focusPoints(mission, coordinates)
when {
points.size > 1 -> ready.animateCamera(CameraUpdateFactory.newLatLngBounds(LatLngBounds.Builder().includes(points.map { LatLng(it.latitude, it.longitude) }).build(), 65))
points.size == 1 -> ready.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(points[0].latitude, points[0].longitude), minOf(if (positions.aircraft != null || mission != null) 16.0 else 14.0, maxZoom)))
}
}
LaunchedEffect(map, styleGeneration, mission) {
val ready = map ?: return@LaunchedEffect
if (styleGeneration == 0) return@LaunchedEffect
annotations.forEach { ready.removeAnnotation(it) }
val updated = mutableListOf<Annotation>()
val icons = IconFactory.getInstance(context)
mission?.points?.let { points ->
if (points.size > 1) updated += ready.addPolyline(PolylineOptions().addAll(points.map { display(it.latitude, it.longitude) }).color(PilotDesign.Blue.toArgb()).width(3f))
val pointIcon = icons.fromBitmap(pilotMapMarker(PilotDesign.Blue.toArgb(), "", false))
points.forEach { p -> updated += ready.addMarker(MarkerOptions().position(display(p.latitude, p.longitude)).title("WP${p.index + 1}").snippet("高度 ${instrumentNumber(p.height)} m").icon(pointIcon)) }
}
annotations = updated
}
LaunchedEffect(map, styleGeneration, positions, telemetry.heading) {
val ready = map ?: return@LaunchedEffect
if (styleGeneration == 0) return@LaunchedEffect
val icons = IconFactory.getInstance(context)
if (positions.home != null) {
val position = LatLng(positions.home.latitude, positions.home.longitude)
if (homeMarker == null) homeMarker = ready.addMarker(MarkerOptions().position(position).title("返航点").icon(icons.fromBitmap(pilotMapMarker(PilotDesign.Teal.toArgb(), "H", false))))
else homeMarker?.position = position
} else { homeMarker?.let { ready.removeMarker(it) }; homeMarker = null }
if (positions.remoteController != null) {
val position = LatLng(positions.remoteController.latitude, positions.remoteController.longitude)
if (rcMarker == null) rcMarker = ready.addMarker(MarkerOptions().position(position).title("遥控器当前位置").icon(icons.fromBitmap(pilotMapMarker(PilotRcMapColor.toArgb(), "RC", false))))
else rcMarker?.position = position
} else { rcMarker?.let { ready.removeMarker(it) }; rcMarker = null }
if (positions.aircraft != null) {
val direction = (((telemetry.heading % 360 + 360) % 360) / 5).toInt() * 5
val icon = aircraftIcons.getOrPut(direction) { icons.fromBitmap(pilotMapMarker(PilotDesign.Blue.toArgb(), "", true, direction.toFloat())) }
val position = LatLng(positions.aircraft.latitude, positions.aircraft.longitude)
if (aircraftMarker == null) aircraftMarker = ready.addMarker(MarkerOptions().position(position).title("飞行器").icon(icon))
else { aircraftMarker?.position = position; aircraftMarker?.icon = icon }
} else { aircraftMarker?.let { ready.removeMarker(it) }; aircraftMarker = null }
}
LaunchedEffect(map, styleGeneration, mission, positions.aircraft != null, positions.remoteController != null) {
if (styleGeneration > 0) centerMap()
}
Box(modifier.background(Color(0xFF244154))) {
AndroidView(factory = { view }, modifier = Modifier.fillMaxSize())
if (map != null && styleGeneration > 0) {
PilotMapLabels(positions, mission, cameraRevision, controls,
project = { map!!.projection.toScreenLocation(LatLng(it.latitude, it.longitude)) },
missionPosition = { lat, lng -> MapCoordinates.display(lat, lng, coordinates) })
}
if (controls) PilotMapLocationStatus(positions, connected, Modifier.align(Alignment.BottomCenter).padding(bottom = 6.dp), telemetry.rcLocationStatus)
if (controls) Column(Modifier.align(if (controlsLeading) Alignment.TopStart else Alignment.TopEnd).padding(12.dp), verticalArrangement = Arrangement.spacedBy(1.dp)) {
Surface(color = Color.White.copy(alpha = 0.94f), shape = RoundedCornerShape(7.dp)) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
if (controlsLeading) {
Column(Modifier.width(36.dp)) {
PilotTool(Icons.Default.Layers, "图层", onClick = onConfigure)
if (config.provider == MapProvider.TIANDITU) PilotTool(Icons.Default.Map, if (satellite) "影像" else "街道", onClick = { toggleSatellite() })
PilotTool(Icons.Default.MyLocation, "定位", onClick = { centerMap() })
PilotTool(Icons.Default.Navigation, "朝北", onClick = { map?.let { ready -> ready.animateCamera(CameraUpdateFactory.newCameraPosition(CameraPosition.Builder(ready.cameraPosition).bearing(0.0).build())) } })
}
} else {
IconButton(onClick = onConfigure) { Icon(Icons.Default.Layers, "图层配置", tint = PilotDesign.Ink) }
if (config.provider == MapProvider.TIANDITU) IconButton(onClick = { toggleSatellite() }) { Icon(Icons.Default.Map, "切换影像/街道", tint = PilotDesign.Ink) }
IconButton(onClick = { map?.let { ready -> ready.animateCamera(CameraUpdateFactory.newCameraPosition(CameraPosition.Builder(ready.cameraPosition).bearing(0.0).build())) } }) { Icon(Icons.Default.Navigation, "地图朝北", tint = PilotDesign.Ink) }
IconButton(onClick = { centerMap() }) { Icon(Icons.Default.MyLocation, "定位飞机/航线", tint = PilotDesign.Ink) }
}
IconButton(onClick = { map?.animateCamera(CameraUpdateFactory.zoomIn()) }) { Icon(Icons.Default.Add, "放大地图", tint = PilotDesign.Ink) }
IconButton(onClick = { map?.animateCamera(CameraUpdateFactory.zoomOut()) }) { Icon(Icons.Default.Remove, "缩小地图", tint = PilotDesign.Ink) }
}
}
}
val platformMessage = if (!platformDefault) null else platformState.error ?: when {
platformState.loading && platformState.catalog.layers.isEmpty() -> "正在获取平台图层"
platformState.fetchedAt > 0 && platformState.catalog.layers.isEmpty() -> "平台没有启用的图层"
platformState.catalog.issues.isNotEmpty() -> "${platformState.catalog.issues.size} 个图层未能叠加,请查看图层配置"
else -> null
}
val displayError = platformMessage ?: accessError ?: error
if (controls && (displayError != null || (!connected && mission == null))) Surface(onClick = { if (platformDefault) scope.launch { platformMaps.refresh(force = true) } else reload++ }, modifier = Modifier.align(Alignment.TopCenter).padding(top = 12.dp), color = Color(0xDE203A50), shape = RoundedCornerShape(6.dp)) {
Text(displayError?.let { "$it · 点击重试" } ?: "等待飞行器定位,可缩放浏览地图", color = Color.White, fontSize = 10.sp, lineHeight = 14.sp, modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp))
}
if (!controls && displayError != null) Text("底图暂不可用", color = PilotDesign.Ink, fontSize = 9.sp, lineHeight = 13.sp, modifier = Modifier.align(Alignment.Center))
Text(config.displayName + if (platformDefault) " · ${platformState.catalog.layers.size} 个图层${if (platformState.cached) " · 缓存" else ""}" else if (config.provider == MapProvider.PRIVATE) " · ${config.activeLayer.minZoom}–${config.activeLayer.maxZoom}级" else " · ${if (satellite) "卫星影像" else "街道地图"}", color = Color.White, fontSize = 8.sp, lineHeight = 11.sp,
modifier = Modifier.align(Alignment.BottomEnd).background(Color(0xB3193B55), RoundedCornerShape(topStart = 4.dp)).padding(horizontal = 6.dp, vertical = 3.dp))
}
}
internal fun pilotMapMarker(color: Int, label: String, aircraft: Boolean, heading: Float = 0f): Bitmap {
val bitmap = Bitmap.createBitmap(64, 64, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
if (aircraft) {
canvas.rotate(heading, 32f, 32f)
val path = Path().apply { moveTo(32f, 5f); lineTo(51f, 52f); lineTo(32f, 43f); lineTo(13f, 52f); close() }
paint.color = color; canvas.drawPath(path, paint)
paint.style = Paint.Style.STROKE; paint.strokeWidth = 4f; paint.color = android.graphics.Color.WHITE; canvas.drawPath(path, paint)
} else {
paint.color = android.graphics.Color.WHITE; canvas.drawCircle(32f, 32f, if (label.isBlank()) 15f else 26f, paint)
paint.color = color; canvas.drawCircle(32f, 32f, if (label.isBlank()) 11f else 22f, paint)
if (label.isNotBlank()) { paint.color = android.graphics.Color.WHITE; paint.textSize = 30f; paint.textAlign = Paint.Align.CENTER; paint.isFakeBoldText = true; canvas.drawText(label, 32f, 42f, paint) }
}
return bitmap
}
@@ -0,0 +1,85 @@
package com.zklh.dronecontroller.ui
import android.graphics.Paint
import android.graphics.PointF
import android.Manifest
import android.content.Intent
import android.provider.Settings
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Flight
import androidx.compose.material.icons.filled.SettingsRemote
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.zklh.dronecontroller.core.map.MapLivePositions
import com.zklh.dronecontroller.core.map.MapPosition
import com.zklh.dronecontroller.core.mission.MissionPreview
internal val PilotRcMapColor = Color(0xFF8B5CC7)
@Composable
internal fun PilotMapLabels(positions: MapLivePositions, mission: MissionPreview?, revision: Int, detailed: Boolean,
project: (MapPosition) -> PointF, missionPosition: (Double, Double) -> MapPosition) {
Canvas(Modifier.fillMaxSize()) {
@Suppress("UNUSED_VARIABLE") val cameraRevision = revision
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = android.graphics.Color.WHITE
textSize = (if (detailed) 11.dp else 8.dp).toPx()
setShadowLayer(3f, 0f, 1f, android.graphics.Color.BLACK)
}
fun label(position: MapPosition?, text: String, vertical: Float) {
if (position == null) return
val screen = project(position)
if (screen.x in 0f..size.width && screen.y in 0f..size.height) {
val textWidth = paint.measureText(text)
val x = (screen.x + 15.dp.toPx()).coerceIn(0f, (size.width - textWidth).coerceAtLeast(0f))
val y = (screen.y + vertical).coerceIn(paint.textSize, (size.height - 3.dp.toPx()).coerceAtLeast(paint.textSize))
drawContext.canvas.nativeCanvas.drawText(text, x, y, paint)
}
}
// Opposite sides keep both labels readable when the aircraft and RC are together.
label(positions.aircraft, "无人机", -17.dp.toPx())
label(positions.remoteController, "遥控器", 25.dp.toPx())
if (detailed) mission?.points?.take(200)?.forEach { point ->
val position = missionPosition(point.latitude, point.longitude)
label(position, "WP${point.index + 1}", -2.dp.toPx())
label(position, "H: ${instrumentNumber(point.height, 0)} m", 12.dp.toPx())
}
}
}
@Composable
internal fun PilotMapLocationStatus(positions: MapLivePositions, connected: Boolean, modifier: Modifier = Modifier, rcStatus: String = "待定位") {
val context = LocalContext.current
val requestPermission = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { }
val permissionMissing = positions.remoteController == null && rcStatus == "未授予定位权限"
val locationDisabled = positions.remoteController == null && rcStatus == "系统定位未开启"
Row(modifier.background(Color(0xDE203A50), RoundedCornerShape(5.dp)).padding(horizontal = 9.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Icon(Icons.Default.Flight, null, Modifier.size(12.dp), tint = PilotDesign.Blue)
Text("无人机 · ${if (positions.aircraft != null) "已定位" else if (connected) "待定位" else "未连接"}", color = Color.White, fontSize = 9.sp, lineHeight = 12.sp)
}
Row(Modifier.clickable(enabled = permissionMissing || locationDisabled) {
if (permissionMissing) requestPermission.launch(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION))
else runCatching { context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) }
}, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Icon(Icons.Default.SettingsRemote, null, Modifier.size(12.dp), tint = PilotRcMapColor)
Text("遥控器 · ${if (positions.remoteController != null) "已定位" else rcStatus}", color = Color.White, fontSize = 9.sp, lineHeight = 12.sp)
}
}
}
@@ -0,0 +1,239 @@
package com.zklh.dronecontroller.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.zklh.dronecontroller.core.map.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.UUID
import java.security.MessageDigest
@Composable
internal fun PilotMapSettings(onClose: () -> Unit, latitude: Double = 35.0, longitude: Double = 104.0) {
val context = LocalContext.current
val store = remember { MapConfigurationStore.get(context) }
val platformMaps = remember { PlatformMapRepository.get(context) }
val platformState by platformMaps.state.collectAsState()
var draft by remember { mutableStateOf(store.configuration.value) }
var notice by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
var revealKey by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
LaunchedEffect(draft.provider) { if (draft.provider == MapProvider.DEFAULT) platformMaps.refresh() }
val uriHandler = LocalUriHandler.current
val signingSha1 = remember(context) {
@Suppress("DEPRECATION")
runCatching {
val signature = if (android.os.Build.VERSION.SDK_INT >= 28) {
context.packageManager.getPackageInfo(context.packageName, android.content.pm.PackageManager.GET_SIGNING_CERTIFICATES)
.signingInfo?.apkContentsSigners?.firstOrNull()
} else context.packageManager.getPackageInfo(context.packageName, android.content.pm.PackageManager.GET_SIGNATURES).signatures?.firstOrNull()
signature?.let { MessageDigest.getInstance("SHA-1").digest(it.toByteArray()).joinToString(":") { byte -> "%02X".format(byte.toInt() and 0xff) } }
}.getOrNull()
}
fun updateLayer(layer: PrivateMapLayer) {
draft = draft.copy(privateLayers = draft.privateLayers.map { if (it.id == layer.id) layer else it })
notice = null
}
Dialog(onDismissRequest = { if (!busy) onClose() }, properties = DialogProperties(usePlatformDefaultWidth = false)) {
Surface(Modifier.widthIn(max = 720.dp).fillMaxWidth(0.9f).heightIn(max = 470.dp), shape = RoundedCornerShape(16.dp), color = PilotDesign.Background) {
Column {
Row(Modifier.fillMaxWidth().background(Color.White).padding(start = 22.dp, end = 12.dp, top = 8.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Default.Layers, null, tint = PilotDesign.Blue)
Text("图层配置", Modifier.padding(start = 10.dp).weight(1f), color = PilotDesign.Ink, fontSize = 20.sp)
IconButton(onClick = onClose, enabled = !busy) { Icon(Icons.Default.Close, "关闭") }
}
Row(Modifier.weight(1f).fillMaxWidth()) {
Column(Modifier.width(145.dp).fillMaxHeight().background(Color.White).padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
MapProvider.entries.forEach { provider ->
val selected = draft.provider == provider
Surface(onClick = { draft = draft.copy(provider = provider); notice = null; revealKey = false },
enabled = !busy, color = if (selected) PilotDesign.Blue else Color.Transparent,
shape = RoundedCornerShape(7.dp), modifier = Modifier.fillMaxWidth()) {
Text(provider.label, Modifier.padding(horizontal = 8.dp, vertical = 10.dp), color = if (selected) Color.White else PilotDesign.Ink, fontSize = 12.sp)
}
}
Text("保存后自动记住\n重开 App 无需重填", color = PilotDesign.Muted, fontSize = 10.sp, lineHeight = 16.sp, modifier = Modifier.padding(top = 12.dp))
}
Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
if (draft.provider == MapProvider.DEFAULT) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text("平台图层 · ${platformState.catalog.layers.size} 个", Modifier.weight(1f), color = PilotDesign.Ink, fontSize = 14.sp)
OutlinedButton(onClick = { scope.launch { platformMaps.refresh(force = true) } }, enabled = !platformState.loading) {
Icon(Icons.Default.Refresh, null, Modifier.size(17.dp))
Text(if (platformState.loading) "获取中…" else "刷新图层", Modifier.padding(start = 4.dp), fontSize = 12.sp)
}
}
Text("使用云平台登录账号获取全部图层,按覆盖范围和叠放顺序自动显示。无需填写地图 Key。", color = PilotDesign.Muted, fontSize = 12.sp, lineHeight = 18.sp)
Text("服务:uav.zklhjs.com · system/map-layer/page", color = PilotDesign.Muted, fontSize = 10.sp, lineHeight = 15.sp)
if (platformState.fetchedAt > 0) Text("${if (platformState.cached) "使用本地配置缓存" else "图层已同步"} · " +
java.text.SimpleDateFormat("MM-dd HH:mm", java.util.Locale.CHINA).format(java.util.Date(platformState.fetchedAt)), color = PilotDesign.Teal, fontSize = 11.sp)
platformState.error?.let { Text(it, color = PilotDesign.Ink, fontSize = 12.sp, lineHeight = 18.sp) }
platformState.catalog.layers.forEach { layer ->
Surface(color = Color.White, shape = RoundedCornerShape(7.dp), modifier = Modifier.fillMaxWidth()) {
Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Default.CheckCircle, null, tint = PilotDesign.Teal, modifier = Modifier.size(18.dp))
Column(Modifier.padding(start = 10.dp)) {
Text(layer.name, color = PilotDesign.Ink, fontSize = 13.sp)
Text("${layer.coordinates} · ${layer.minZoom}–${layer.maxZoom} 级 · 透明度 ${(layer.opacity * 100).toInt()}%", color = PilotDesign.Muted, fontSize = 10.sp)
}
}
}
}
platformState.catalog.issues.forEach { Text(it, color = PilotDesign.Ink, fontSize = 11.sp, lineHeight = 16.sp) }
Text("成功获取的图层配置会保存在 App 中。瓦片仍需联网请求;网络恢复后可点击刷新同步平台更新。", color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 16.sp)
} else if (draft.provider == MapProvider.PRIVATE) {
val layer = draft.activeLayer
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text("私有图层 · ${draft.privateLayers.size} 个", Modifier.weight(1f), color = PilotDesign.Ink, fontSize = 13.sp)
Button(onClick = {
val newLayer = PrivateMapLayer(id = UUID.randomUUID().toString(), name = "新图层 ${draft.privateLayers.size + 1}", url = "", maxZoom = 18)
draft = draft.copy(privateLayers = draft.privateLayers + newLayer, activeLayerId = newLayer.id); notice = null
}, enabled = !busy, contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp)) {
Icon(Icons.Default.Add, null, Modifier.size(17.dp))
Text("新增图层", Modifier.padding(start = 4.dp), fontSize = 12.sp)
}
OutlinedButton(onClick = {
val remaining = draft.privateLayers.filter { it.id != layer.id }
draft = draft.copy(privateLayers = remaining, activeLayerId = remaining.first().id); notice = null
}, enabled = !busy && draft.privateLayers.size > 1, contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp)) {
Icon(Icons.Default.DeleteOutline, null, Modifier.size(17.dp))
Text("删除", Modifier.padding(start = 4.dp), fontSize = 12.sp)
}
}
MapChoice("当前图层 · 点击切换", layer.id, draft.privateLayers.map { it.id to it.name }, Modifier.fillMaxWidth(), !busy) {
draft = draft.copy(activeLayerId = it); notice = null
}
Text("可以添加多个图层,分别填写地址;完成后点击“保存并应用”,整个列表都会保存。", color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 16.sp)
MapInput("图层名称", layer.name, !busy) { updateLayer(layer.copy(name = it)) }
MapInput("瓦片地址(HTTPS)", layer.url, !busy, singleLine = false) { updateLayer(layer.copy(url = it.trim())) }
Text("地址包含 {z}/{x}/{y};例:https://服务器/map/{z}/{x}/{y}.jpg", color = PilotDesign.Muted, fontSize = 10.sp, lineHeight = 14.sp)
MapInput("标注瓦片地址(可选)", layer.annotationUrl, !busy, singleLine = false) { updateLayer(layer.copy(annotationUrl = it.trim())) }
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
MapChoice("坐标系", layer.coordinates, MapCoordinateSystem.entries.map { it to it.name }, Modifier.weight(1f), !busy) { updateLayer(layer.copy(coordinates = it)) }
MapChoice("瓦片编号", layer.scheme, TileScheme.entries.map { it to it.name }, Modifier.weight(1f), !busy) { updateLayer(layer.copy(scheme = it)) }
}
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
var minimum by remember(layer.id) { mutableStateOf(layer.minZoom.toString()) }
var maximum by remember(layer.id) { mutableStateOf(layer.maxZoom.toString()) }
OutlinedTextField(minimum, { minimum = it; updateLayer(layer.copy(minZoom = it.toIntOrNull() ?: -1)) }, Modifier.weight(1f), label = { Text("最小层级") }, singleLine = true, enabled = !busy, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
OutlinedTextField(maximum, { maximum = it; updateLayer(layer.copy(maxZoom = it.toIntOrNull() ?: -1)) }, Modifier.weight(1f), label = { Text("最大层级") }, singleLine = true, enabled = !busy, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
}
Text("截图中的全球图为 GCJ02 / XYZ,最大 8 级。区域图请按服务器实际配置填写。", color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 16.sp)
} else {
val androidSdk = draft.provider == MapProvider.AMAP || draft.provider == MapProvider.BAIDU
Text(if (androidSdk) "填写你申请的 Android 地图 SDK Key" else "填写有在线瓦片访问权限的天地图 Key", color = PilotDesign.Ink, fontSize = 14.sp)
OutlinedTextField(draft.key, { value ->
val key = value.trim()
draft = when (draft.provider) {
MapProvider.TIANDITU -> draft.copy(tiandituKey = key)
MapProvider.AMAP -> draft.copy(amapKey = key)
MapProvider.BAIDU -> draft.copy(baiduKey = key)
else -> draft
}; notice = null
}, Modifier.fillMaxWidth(), label = { Text("${draft.provider.label} Key") }, enabled = !busy,
singleLine = true, visualTransformation = if (revealKey) VisualTransformation.None else PasswordVisualTransformation(),
trailingIcon = { IconButton(onClick = { revealKey = !revealKey }) { Icon(if (revealKey) Icons.Default.VisibilityOff else Icons.Default.Visibility, "显示或隐藏 Key") } })
if (androidSdk) {
Text("包名:com.zklh.dronecontroller\nKey 需要绑定本 App 的签名 SHA1;浏览器 Key 不能代替 Android Key。", color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 17.sp)
signingSha1?.let { sha1 -> SelectionContainer { Text("签名 SHA1(长按可复制):\n$sha1", color = PilotDesign.Muted, fontSize = 10.sp, lineHeight = 16.sp) } }
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(draft.consent, { agreed -> draft = if (draft.provider == MapProvider.AMAP) draft.copy(amapConsent = agreed) else draft.copy(baiduConsent = agreed) }, enabled = !busy)
Text("我已阅读并同意该地图服务的隐私政策", fontSize = 11.sp, modifier = Modifier.weight(1f), lineHeight = 16.sp)
}
TextButton(onClick = { uriHandler.openUri(if (draft.provider == MapProvider.AMAP) "https://lbs.amap.com/pages/privacy/" else "https://lbsyun.baidu.com/index.php?title=openprivacy") }) { Text("查看${draft.provider.label}隐私政策", fontSize = 11.sp) }
Text("保存后由地图 SDK 鉴权。若地图空白,请检查 Key 和签名绑定;本次运行已使用过该地图时,更换 Key 后需完全退出 App 再打开。", color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 16.sp)
} else {
Text("若提示 Key 权限类型不匹配,请在天地图控制台检查该 Key 是否允许当前客户端访问。", color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 16.sp)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text("默认底图", Modifier.weight(1f), color = PilotDesign.Ink, fontSize = 13.sp)
FilterChip(draft.satellite, { draft = draft.copy(satellite = true) }, { Text("影像") }, enabled = !busy)
Spacer(Modifier.width(8.dp))
FilterChip(!draft.satellite, { draft = draft.copy(satellite = false) }, { Text("街道") }, enabled = !busy)
}
}
notice?.let { Text(it, color = PilotDesign.Ink, fontSize = 12.sp, lineHeight = 18.sp) }
}
}
Row(Modifier.fillMaxWidth().background(Color.White).padding(horizontal = 20.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
if (draft.provider == MapProvider.PRIVATE || draft.provider == MapProvider.TIANDITU) {
OutlinedButton(onClick = {
val candidate = draft
val error = candidate.validationError()
if (error != null) notice = error else {
busy = true
scope.launch {
notice = withContext(Dispatchers.IO) {
if (candidate.provider == MapProvider.PRIVATE) PrivateMapSource.checkAccess(candidate.activeLayer, latitude, longitude)
else TiandituMapSource.checkAccess(candidate.satellite, candidate.key) ?: "天地图样本瓦片可访问"
}
busy = false
}
}
}, enabled = !busy) { Text(if (busy) "处理中…" else "测试连接") }
}
Spacer(Modifier.weight(1f))
TextButton(onClick = onClose, enabled = !busy) { Text("取消") }
Button(onClick = {
val candidate = draft
val error = candidate.validationError()
if (error != null) notice = error else {
busy = true
scope.launch {
val saved = store.save(candidate)
busy = false
if (saved) onClose() else notice = "配置未能写入本地,请重试"
}
}
}, enabled = !busy) { Text("保存并应用") }
}
}
}
}
}
@Composable
private fun MapInput(label: String, value: String, enabled: Boolean, singleLine: Boolean = true, onChange: (String) -> Unit) {
OutlinedTextField(value, onChange, Modifier.fillMaxWidth(), label = { Text(label, fontSize = 12.sp) }, singleLine = singleLine,
maxLines = if (singleLine) 1 else 3, enabled = enabled, textStyle = LocalTextStyle.current.copy(fontSize = 13.sp, lineHeight = 18.sp))
}
@Composable
private fun <T> MapChoice(label: String, value: T, options: List<Pair<T, String>>, modifier: Modifier = Modifier, enabled: Boolean = true, onChange: (T) -> Unit) {
var expanded by remember { mutableStateOf(false) }
Box(modifier) {
OutlinedButton(onClick = { expanded = true }, enabled = enabled, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(6.dp), contentPadding = PaddingValues(10.dp)) {
Column(Modifier.weight(1f)) {
Text(label, fontSize = 9.sp, color = PilotDesign.Muted)
Text(options.firstOrNull { it.first == value }?.second.orEmpty(), fontSize = 12.sp, color = PilotDesign.Ink, maxLines = 1)
}
Icon(Icons.Default.ExpandMore, null, Modifier.size(18.dp))
}
DropdownMenu(expanded, { expanded = false }) {
options.forEach { option -> DropdownMenuItem(text = { Text(option.second, fontSize = 12.sp) }, onClick = { onChange(option.first); expanded = false }) }
}
}
}
@@ -0,0 +1,80 @@
package com.zklh.dronecontroller.ui
import android.graphics.BitmapFactory
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.zklh.dronecontroller.core.telemetry.TelemetrySnapshot
import dji.v5.manager.datacenter.MediaDataCenter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
@Composable
internal fun PilotMediaDialog(connected: Boolean, telemetry: TelemetrySnapshot, onClose: () -> Unit) {
val context = LocalContext.current
var tick by remember { mutableStateOf(0) }
var selected by remember { mutableStateOf<File?>(null) }
val files by produceState(emptyList<File>(), tick) {
value = withContext(Dispatchers.IO) { File(context.cacheDir, "msdk-media").listFiles()?.filter { it.isFile }?.sortedByDescending { it.lastModified() }.orEmpty() }
}
val aircraft = remember(tick, connected) { if (connected) runCatching { MediaDataCenter.getInstance().mediaManager.mediaFileListData.data.toList() }.getOrDefault(emptyList()) else emptyList() }
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false)) {
Surface(shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp), modifier = Modifier.fillMaxWidth(0.65f).fillMaxHeight(0.8f)) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text("媒体相册", color = PilotDesign.Ink, fontSize = 22.sp, lineHeight = 28.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))
IconButton(onClick = { tick++ }) { Icon(Icons.Default.Refresh, "刷新媒体列表") }
IconButton(onClick = onClose) { Icon(Icons.Default.Close, "关闭媒体相册") }
}
Text(if (connected) "剩余照片 ${telemetry.remainPhotoNum} · 存储剩余 ${telemetry.storageRemain} MB" else "飞行器未连接", color = PilotDesign.Muted, fontSize = 12.sp)
LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(7.dp)) {
item { Text("已下载媒体", color = PilotDesign.Ink, fontWeight = FontWeight.Bold, fontSize = 14.sp) }
if (files.isEmpty()) item { Text("暂无已下载的媒体,拍摄并完成云端上传后可在此查看本地照片。", color = PilotDesign.Muted, fontSize = 12.sp) }
items(files, key = { it.absolutePath }) { file ->
Surface(onClick = { if (file.extension.lowercase() in listOf("jpg", "jpeg", "png", "webp")) selected = file }, color = PilotDesign.Background, shape = androidx.compose.foundation.shape.RoundedCornerShape(7.dp)) {
Row(Modifier.fillMaxWidth().padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(if (file.extension.lowercase() in listOf("mp4", "mov")) Icons.Default.Videocam else Icons.Default.Image, null, tint = PilotDesign.Blue)
Text(file.name, color = PilotDesign.Ink, fontSize = 12.sp, modifier = Modifier.weight(1f).padding(start = 10.dp))
Text("${instrumentNumber(file.length() / 1048576.0, 2)} MB", color = PilotDesign.Muted, fontSize = 11.sp)
}
}
}
item { Text("相机最近读取的文件", color = PilotDesign.Ink, fontWeight = FontWeight.Bold, fontSize = 14.sp, modifier = Modifier.padding(top = 12.dp)) }
if (aircraft.isEmpty()) item { Text("暂无相机文件列表", color = PilotDesign.Muted, fontSize = 12.sp) }
items(aircraft.takeLast(30)) { file -> PilotDetail(file.fileName.orEmpty(), "${instrumentNumber(file.fileSize / 1048576.0, 2)} MB") }
}
}
}
}
selected?.let { file ->
val bitmap by produceState<androidx.compose.ui.graphics.ImageBitmap?>(null, file) {
value = withContext(Dispatchers.IO) { runCatching {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(file.absolutePath, bounds)
val options = BitmapFactory.Options().apply { inSampleSize = (maxOf(bounds.outWidth, bounds.outHeight) / 1600).coerceAtLeast(1) }
BitmapFactory.decodeFile(file.absolutePath, options)?.asImageBitmap()
}.getOrNull() }
}
Dialog(onDismissRequest = { selected = null }, properties = DialogProperties(usePlatformDefaultWidth = false)) {
Surface(shape = androidx.compose.foundation.shape.RoundedCornerShape(10.dp), modifier = Modifier.fillMaxWidth(0.85f).fillMaxHeight(0.85f)) {
Box { bitmap?.let { Image(it, file.name, Modifier.fillMaxSize(), contentScale = ContentScale.Fit) }; IconButton(onClick = { selected = null }, modifier = Modifier.align(Alignment.TopEnd)) { Icon(Icons.Default.Close, "关闭照片预览") } }
}
}
}
}
@@ -0,0 +1,60 @@
package com.zklh.dronecontroller.ui
import androidx.compose.runtime.*
import dji.v5.common.error.IDJIError
import dji.v5.manager.aircraft.waypoint3.WaylineExecutingInfoListener
import dji.v5.manager.aircraft.waypoint3.WaypointMissionExecuteStateListener
import dji.v5.manager.aircraft.waypoint3.WaypointMissionManager
import dji.v5.manager.aircraft.waypoint3.model.WaylineExecutingInfo
import dji.v5.manager.aircraft.waypoint3.model.WaypointMissionExecuteState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
internal data class PilotMissionExecution(
val state: WaypointMissionExecuteState? = null, val fileName: String = "",
val waypointIndex: Int? = null, val waylineId: Int? = null, val error: String? = null
) {
val label: String get() = when (state) {
WaypointMissionExecuteState.DISCONNECTED -> "未连接"
WaypointMissionExecuteState.IDLE -> "待机"
WaypointMissionExecuteState.NOT_SUPPORTED -> "机型不支持"
WaypointMissionExecuteState.READY -> "已就绪"
WaypointMissionExecuteState.UPLOADING -> "上传中"
WaypointMissionExecuteState.PREPARING -> "准备中"
WaypointMissionExecuteState.ENTER_WAYLINE -> "进入航线"
WaypointMissionExecuteState.EXECUTING -> "执行中"
WaypointMissionExecuteState.INTERRUPTED -> "已中断"
WaypointMissionExecuteState.RECOVERING -> "恢复中"
WaypointMissionExecuteState.FINISHED -> "已完成"
WaypointMissionExecuteState.RETURN_TO_START_POINT -> "返回起点"
else -> "等待任务状态"
}
}
@Composable
internal fun rememberPilotMissionExecution(connected: Boolean): PilotMissionExecution {
val flow = remember(connected) { MutableStateFlow(PilotMissionExecution()) }
DisposableEffect(connected) {
val lock = Any()
var active = true
val manager = if (connected) runCatching { WaypointMissionManager.getInstance() }.getOrNull() else null
val stateListener = WaypointMissionExecuteStateListener { state -> synchronized(lock) { if (active) flow.update { it.copy(state = state, error = null) } } }
val infoListener = object : WaylineExecutingInfoListener {
override fun onWaylineExecutingInfoUpdate(info: WaylineExecutingInfo) {
synchronized(lock) { if (active) flow.update { it.copy(fileName = info.missionFileName.orEmpty(), waypointIndex = info.currentWaypointIndex.takeIf { n -> n >= 0 }, waylineId = info.waylineID, error = null) } }
}
override fun onWaylineExecutingInterruptReasonUpdate(error: IDJIError?) {
synchronized(lock) { if (active) flow.update { it.copy(error = error?.description()) } }
}
}
runCatching { manager?.addWaypointMissionExecuteStateListener(stateListener) }
runCatching { manager?.addWaylineExecutingInfoListener(infoListener) }
onDispose {
synchronized(lock) { active = false }
runCatching { manager?.removeWaypointMissionExecuteStateListener(stateListener) }
runCatching { manager?.removeWaylineExecutingInfoListener(infoListener) }
}
}
val value by flow.collectAsState()
return value
}
@@ -0,0 +1,188 @@
package com.zklh.dronecontroller.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.zklh.dronecontroller.core.mission.MissionPreview
import com.zklh.dronecontroller.core.mission.MissionUploadUpdate
import com.zklh.dronecontroller.core.telemetry.TelemetrySnapshot
import java.io.File
import java.util.Locale
@Composable
internal fun PilotMissionPanel(connected: Boolean, telemetry: TelemetrySnapshot, missionPath: String, missionId: String, upload: MissionUploadUpdate, state: MissionPreviewState, execution: PilotMissionExecution, onIdChange: (String) -> Unit, onPick: () -> Unit, onGenerate: () -> Unit, onUpload: () -> Unit, onStart: () -> Unit, onPause: () -> Unit, onResume: () -> Unit, onStop: () -> Unit, onClose: () -> Unit, modifier: Modifier = Modifier) {
var tab by remember { mutableStateOf(0) }
val info = state.preview
val file = remember(missionPath) { File(missionPath) }
val hasFile = missionPath.isNotBlank() && file.isFile
CompositionLocalProvider(LocalMinimumInteractiveComponentSize provides 0.dp) {
Surface(modifier, color = Color(0xFFF6FAFE), shape = RoundedCornerShape(topStart = 8.dp)) {
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.height(28.dp), verticalAlignment = Alignment.CenterVertically) {
Text("航线任务", color = PilotDesign.Ink, fontSize = 20.sp, lineHeight = 26.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))
IconButton(onClick = onClose, modifier = Modifier.size(28.dp)) { Icon(Icons.Default.Close, "关闭航线任务", tint = PilotDesign.Ink, modifier = Modifier.size(21.dp)) }
}
Row(Modifier.fillMaxWidth()) {
listOf("文件导入", "任务信息", "航点列表", "任务设置").forEachIndexed { index, title ->
Column(Modifier.weight(1f)) {
TextButton(onClick = { tab = index }, contentPadding = PaddingValues(0.dp), modifier = Modifier.fillMaxWidth().height(28.dp)) {
Text(title, fontSize = 11.sp, lineHeight = 14.sp, color = if (tab == index) PilotDesign.Blue else PilotDesign.Muted, fontWeight = if (tab == index) FontWeight.Bold else FontWeight.Normal)
}
HorizontalDivider(color = if (tab == index) PilotDesign.Blue else PilotDesign.Line, thickness = if (tab == index) 2.dp else 1.dp)
}
}
}
key(tab) {
if (tab == 2) {
LazyColumn(Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(7.dp)) {
if (info == null) item { Text(if (state.loading) "正在解析航线…" else state.error ?: "选择航线文件后显示航点", color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 16.sp) }
items(info?.points.orEmpty()) { point ->
PilotCard(Modifier.fillMaxWidth()) {
Text("WP${point.index + 1} H: ${instrumentNumber(point.height, 0)} m", color = PilotDesign.Ink, fontSize = 12.sp, lineHeight = 16.sp, fontWeight = FontWeight.Bold)
Text("%.6f, %.6f".format(Locale.US, point.latitude, point.longitude), color = PilotDesign.Muted, fontSize = 10.sp, lineHeight = 14.sp, modifier = Modifier.padding(top = 5.dp))
}
}
}
} else {
Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) {
if (tab == 0) {
Row(Modifier.height(26.dp), verticalAlignment = Alignment.CenterVertically) {
Text("KMZ / WPML 文件", color = PilotDesign.Ink, fontSize = 12.sp, lineHeight = 16.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))
MissionOutlineButton("选择", onPick, Modifier.width(60.dp))
}
Spacer(Modifier.height(6.dp))
Surface(color = Color.White.copy(alpha = 0.65f), shape = RoundedCornerShape(6.dp), border = BorderStroke(1.dp, PilotDesign.Line)) {
Row(Modifier.fillMaxWidth().heightIn(min = 44.dp).padding(horizontal = 10.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Default.Description, null, tint = PilotDesign.Blue, modifier = Modifier.size(24.dp))
Column(Modifier.weight(1f).padding(start = 10.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(if (hasFile) file.name else "尚未选择航线文件", color = PilotDesign.Ink, fontSize = 11.sp, lineHeight = 15.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(if (hasFile) "${instrumentNumber(file.length() / 1048576.0, 2)} MB ${info?.points?.size?.let { "$it 个航点" } ?: "解析中"}" else "支持 KMZ / WPML / KML 预览", color = PilotDesign.Muted, fontSize = 9.sp, lineHeight = 12.sp)
}
}
}
Spacer(Modifier.height(8.dp))
Text("上传进度", color = PilotDesign.Ink, fontSize = 11.sp, lineHeight = 14.sp, fontWeight = FontWeight.Medium)
Spacer(Modifier.height(5.dp))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
LinearProgressIndicator(progress = { upload.progress.toFloat().coerceIn(0f, 1f) }, color = PilotDesign.Teal, trackColor = PilotDesign.Line, modifier = Modifier.weight(1f).height(6.dp))
Text("${(upload.progress.coerceIn(0.0, 1.0) * 100).toInt()}%", color = PilotDesign.Ink, fontSize = 11.sp, lineHeight = 14.sp)
}
Spacer(Modifier.height(5.dp))
Text(upload.error ?: upload.message.ifBlank { if (upload.completed) "航线已上传" else "选择文件后上传至飞行器" }, color = if (upload.error == null) PilotDesign.Muted else PilotDesign.Red, fontSize = 10.sp, lineHeight = 14.sp, maxLines = 2, overflow = TextOverflow.Ellipsis)
Spacer(Modifier.height(10.dp))
HorizontalDivider(color = PilotDesign.Line)
Spacer(Modifier.height(10.dp))
}
if (tab != 3) {
Text("任务信息", color = PilotDesign.Ink, fontSize = 12.sp, lineHeight = 16.sp, fontWeight = FontWeight.Bold)
Spacer(Modifier.height(8.dp))
if (state.loading || state.error != null) Text(state.error ?: "正在解析航线…", color = if (state.error == null) PilotDesign.Muted else PilotDesign.Red, fontSize = 10.sp, lineHeight = 14.sp)
MissionSummary(connected, telemetry, missionId, info)
if (info != null) {
Text("预计时长按巡航速度估算${if (info.waylineCount > 1) ";预览第一条航线" else ""}", color = PilotDesign.Muted, fontSize = 9.sp, lineHeight = 12.sp, modifier = Modifier.padding(top = 4.dp))
}
} else {
OutlinedTextField(missionId, onIdChange, label = { Text("任务 ID") }, singleLine = true, modifier = Modifier.fillMaxWidth())
Text("以下设置读取自航线文件,执行时由 DJI 校验。", color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 16.sp, modifier = Modifier.padding(vertical = 10.dp))
PilotDetail("自动飞行速度", info?.speed?.let { "${instrumentNumber(it)} m/s" } ?: "—")
PilotDetail("高度模式", missionSettingLabel(info?.heightMode.orEmpty()))
PilotDetail("完成动作", missionSettingLabel(info?.finishAction.orEmpty()))
PilotDetail("失联动作", missionSettingLabel(info?.lostAction.orEmpty()))
}
}
}
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text("执行状态 ${execution.label}", color = PilotDesign.Teal, fontSize = 10.sp, lineHeight = 14.sp, modifier = Modifier.weight(1f))
val matches = execution.fileName.substringBeforeLast('.') == missionId && execution.waylineId == 0
if (matches && info != null && execution.waypointIndex != null) Text("航点 ${(execution.waypointIndex + 1).coerceAtMost(info.points.size)} / ${info.points.size}", color = PilotDesign.Muted, fontSize = 10.sp, lineHeight = 14.sp)
}
if (execution.error != null) Text(execution.error, color = PilotDesign.Red, fontSize = 10.sp, lineHeight = 14.sp, maxLines = 2)
Surface(color = Color(0xFFFFEBD0), shape = RoundedCornerShape(6.dp), modifier = Modifier.fillMaxWidth()) {
Row(Modifier.padding(horizontal = 10.dp, vertical = 7.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(Icons.Default.Error, null, tint = Color(0xFFAF641D), modifier = Modifier.size(20.dp))
Column {
Text("安全提醒", color = Color(0xFF925117), fontSize = 11.sp, lineHeight = 14.sp, fontWeight = FontWeight.Bold)
Text("请确认空域、天气与现场安全,作业全程保持可控。", color = Color(0xFF986025), fontSize = 9.sp, lineHeight = 12.sp)
}
}
}
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
MissionOutlineButton("选择", onPick, Modifier.weight(1f))
MissionOutlineButton("生成", onGenerate, Modifier.weight(1f), connected)
MissionOutlineButton("上传", onUpload, Modifier.weight(1f), connected && hasFile)
}
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
MissionRunButton("开始", Icons.Default.PlayArrow, PilotDesign.Teal, onStart, Modifier.weight(1f), connected && upload.completed)
MissionRunButton("暂停", Icons.Default.Pause, PilotDesign.Blue, onPause, Modifier.weight(1f), connected)
MissionRunButton("继续", Icons.Default.PlayArrow, PilotDesign.Blue, onResume, Modifier.weight(1f), connected)
MissionRunButton("停止", Icons.Default.Stop, PilotDesign.Red, onStop, Modifier.weight(1f), connected)
}
}
}
}
}
@Composable
private fun MissionSummary(connected: Boolean, telemetry: TelemetrySnapshot, missionId: String, info: MissionPreview?) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Column(Modifier.weight(0.57f)) {
MissionSummaryRow("任务 ID", missionId.ifBlank { "—" })
MissionSummaryRow("任务名称", info?.name ?: "—")
MissionSummaryRow("航点数量", info?.points?.size?.toString() ?: "—")
MissionSummaryRow("航线长度", info?.let { "${instrumentNumber(it.distanceMeters / 1000.0, 2)} km" } ?: "—")
MissionSummaryRow("预计时长", info?.speed?.let { "${instrumentNumber(info.distanceMeters / it / 60)} min" } ?: "—")
MissionSummaryRow("作业高度", info?.points?.mapNotNull { it.height }?.takeIf { it.isNotEmpty() }?.let { "${instrumentNumber(it.min(), 0)}–${instrumentNumber(it.max(), 0)} m" } ?: "—")
}
Surface(color = Color(0xFFE7EEF5), shape = RoundedCornerShape(6.dp), modifier = Modifier.weight(0.43f).height(108.dp)) {
if (info != null) {
Box {
PilotMap(connected, telemetry, Modifier.fillMaxSize(), info, controls = false)
Surface(Modifier.align(Alignment.BottomEnd).padding(5.dp), color = Color(0xAA193B55), shape = RoundedCornerShape(4.dp)) { Text("预览", color = Color.White, fontSize = 9.sp, lineHeight = 12.sp, modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp)) }
}
} else {
Column(Modifier.fillMaxSize().padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
Icon(Icons.Default.Route, null, tint = PilotDesign.Muted, modifier = Modifier.size(26.dp))
Text("选择航线后预览", color = PilotDesign.Muted, fontSize = 9.sp, lineHeight = 13.sp, modifier = Modifier.padding(top = 6.dp))
}
}
}
}
}
@Composable
private fun MissionSummaryRow(label: String, value: String) {
Row(Modifier.fillMaxWidth().height(18.dp), verticalAlignment = Alignment.CenterVertically) {
Text(label, color = PilotDesign.Muted, fontSize = 10.sp, lineHeight = 14.sp, modifier = Modifier.width(57.dp))
Text(value, color = PilotDesign.Ink, fontSize = 10.sp, lineHeight = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
}
}
private fun missionSettingLabel(value: String) = when (value) {
"goHome", "goBack" -> "返航"; "autoLand", "landing" -> "降落"; "hover" -> "悬停"; "noAction" -> "无动作"; "relativeToStartPoint" -> "相对起飞点"; "WGS84" -> "WGS84"; "EGM96" -> "海拔高度"; "realTimeFollowSurface" -> "实时仿地"; "" -> "—"; else -> value
}
@Composable
private fun MissionOutlineButton(label: String, onClick: () -> Unit, modifier: Modifier, enabled: Boolean = true) {
OutlinedButton(onClick, modifier.height(26.dp), enabled = enabled, shape = RoundedCornerShape(5.dp), contentPadding = PaddingValues(0.dp), border = BorderStroke(1.dp, if (enabled) PilotDesign.Blue else PilotDesign.Line)) { Text(label, fontSize = 11.sp, lineHeight = 14.sp, fontWeight = FontWeight.Medium) }
}
@Composable
private fun MissionRunButton(label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, color: Color, onClick: () -> Unit, modifier: Modifier, enabled: Boolean) {
Button(onClick, modifier.height(35.dp), enabled = enabled, shape = RoundedCornerShape(5.dp), colors = ButtonDefaults.buttonColors(containerColor = color), contentPadding = PaddingValues(0.dp)) { Icon(icon, null, modifier = Modifier.size(18.dp)); Spacer(Modifier.width(3.dp)); Text(label, fontSize = 11.sp, lineHeight = 14.sp, fontWeight = FontWeight.Medium) }
}
@@ -3,15 +3,17 @@ package com.zklh.dronecontroller.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@@ -19,56 +21,68 @@ import com.zklh.dronecontroller.core.msdk.DroneSdkState
import com.zklh.dronecontroller.core.telemetry.TelemetrySnapshot
import com.zklh.dronecontroller.core.telemetry.hasReliableRtkPosition
/** Read-only checks. The former placeholder sliders never wrote settings to the aircraft. */
@Composable
internal fun PilotPreflightScreen(sdkState: DroneSdkState, telemetry: TelemetrySnapshot, onClose: () -> Unit) {
internal fun PilotPreflightScreen(sdkState: DroneSdkState, telemetry: TelemetrySnapshot, onClose: () -> Unit, onEnterFlight: () -> Unit = onClose) {
val connected = sdkState.productConnected
val device = rememberPilotDeviceReadings(connected)
val instruments = rememberFlightInstrumentReadings(connected, telemetry.cameraComponent)
var propellersChecked by remember(sdkState.aircraftSerialNumber, connected) { mutableStateOf(false) }
var airspaceChecked by remember(sdkState.aircraftSerialNumber, connected) { mutableStateOf(false) }
fun reading(value: String) = if (connected) value else "—"
Column(Modifier.fillMaxSize().background(Color(0xFF0D1118)).padding(20.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text("飞前检查", color = Color.White, fontSize = 24.sp, fontWeight = FontWeight.Bold)
Text("设备状态", color = Color(0xFF9CABB9), fontSize = 12.sp)
Column(Modifier.fillMaxSize().background(PilotDesign.PageBrush).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Row(Modifier.height(36.dp), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = onClose, modifier = Modifier.size(32.dp)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "返回", tint = PilotDesign.Ink) }
Text("飞前检查", color = PilotDesign.Ink, fontSize = 27.sp, lineHeight = 34.sp, fontWeight = FontWeight.Bold)
Text("检查各项状态,确保满足飞行条件", color = PilotDesign.Muted, fontSize = 12.sp, modifier = Modifier.padding(start = 20.dp))
Spacer(Modifier.weight(1f))
Text("风速 ${instrumentNumber(instruments.windSpeed)} m/s ${rememberPilotTime()} ${reading(if (telemetry.batteryPercent >= 0) "${telemetry.batteryPercent}%" else "—")}", color = PilotDesign.Ink, fontSize = 12.sp)
}
IconButton(onClick = onClose) { Icon(Icons.Filled.Close, "关闭飞前检查", tint = Color.White) }
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(14.dp)) {
Column(Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
CheckCard("飞行器连接", if (connected) "已连接,实时获取设备状态" else "等待连接飞行器", Icons.Default.Flight, connected, listOf(
"链路质量" to (device.downlinkQuality?.let { "$it%" } ?: "—"), "固件版本" to reading(telemetry.firmwareVersion.ifBlank { "—" }), "飞行模式" to reading(telemetry.flightModeString.ifBlank { telemetry.flightMode }), "飞行器状态" to if (connected) "已连接" else "未连接"))
CheckCard("电池", "电量、温度与续航状态", Icons.Default.BatteryFull, connected && telemetry.batteryPercent > 30, listOf(
"当前电量" to reading(if (telemetry.batteryPercent >= 0) "${telemetry.batteryPercent}%" else "—"), "预计续航" to reading(if (telemetry.remainingFlightTimeKnown) "${telemetry.remainingFlightTime / 60} min" else "—"), "电压" to reading(if (telemetry.batteryVoltageKnown) "${instrumentNumber(telemetry.batteryVoltageMv / 1000.0)} V" else "—"), "电池温度" to reading(if (telemetry.batteryTemperatureKnown) "${instrumentNumber(telemetry.batteryTemperature)} °C" else "—"), "循环次数" to reading(if (telemetry.batteryLoopTimesKnown) "${telemetry.batteryLoopTimes} 次" else "—")))
CheckCard("GPS / RTK", if (connected && telemetry.gpsValid) "实时定位状态" else "等待有效定位", Icons.Default.LocationOn, connected && telemetry.gpsValid, listOf(
"GPS 卫星数" to reading(if (telemetry.gpsValid) telemetry.gpsSatelliteCount.toString() else "—"), "RTK 状态" to reading(if (telemetry.hasReliableRtkPosition()) "固定解" else if (telemetry.rtkEnabled) "等待定位" else "未启用"), "水平 / 垂直精度" to if (telemetry.hasReliableRtkPosition()) "${instrumentNumber(device.rtkHorizontalStdMeters?.times(100))} / ${instrumentNumber(device.rtkVerticalStdMeters?.times(100))} cm" else "—"))
CheckCard("遥控器", if (sdkState.productLinkConnected) "已连接" else "等待连接遥控器", Icons.Default.SportsEsports, sdkState.productLinkConnected, listOf(
"连接状态" to if (sdkState.productLinkConnected) "在线" else "离线", "电量" to if (sdkState.productLinkConnected && telemetry.rcBatteryPercent >= 0) "${telemetry.rcBatteryPercent}%" else "—", "设备型号" to telemetry.remoteControllerType.replace('_', ' ').ifBlank { "—" }))
}
Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Column(Modifier.weight(1f).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
CheckCard("桨叶", "请现场确认安装、变形与裂纹情况", Icons.Default.Toys, propellersChecked, listOf("桨叶检查" to if (propellersChecked) "人工已确认" else "需人工确认", "安装状态" to if (propellersChecked) "已检查" else "待检查"), onConfirm = { propellersChecked = !propellersChecked })
CheckCard("返航点", if (connected && telemetry.homeLocationValid) "返航点已记录" else "尚未获取返航点", Icons.Default.Home, connected && telemetry.homeLocationValid, listOf(
"返航点坐标" to reading(if (telemetry.homeLocationValid) "%.5f, %.5f".format(java.util.Locale.US, telemetry.homeLatitude, telemetry.homeLongitude) else "—"), "返航高度" to (device.goHomeHeight?.let { "$it m" } ?: "—")))
CheckCard("空域", "飞行许可与现场环境需人工确认", Icons.Default.Navigation, airspaceChecked, listOf("空域许可" to if (airspaceChecked) "人工已确认" else "请确认", "限高设置" to reading("${telemetry.heightLimit} m")), onConfirm = { airspaceChecked = !airspaceChecked })
PilotCard(Modifier.fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically) { Icon(Icons.Default.Shield, null, tint = PilotDesign.Blue, modifier = Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text("安全提示", color = PilotDesign.Ink, fontSize = 14.sp, fontWeight = FontWeight.Bold) }
Text("• 请确认设备、环境及任务计划满足现场作业要求。\n• 起飞前再次检查周边人员、车辆与障碍物。\n• 如遇异常,及时中止任务并返航。", color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 17.sp, modifier = Modifier.padding(top = 5.dp))
}
}
PilotPrimaryButton("进入飞行", onEnterFlight, Modifier.fillMaxWidth(), Icons.Default.Send)
}
Spacer(Modifier.height(18.dp))
Row(Modifier.weight(1f).verticalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(16.dp)) {
CheckCard("连接与定位", listOf(
"飞机连接" to if (connected) "已连接" else "未连接",
"遥控链路" to if (sdkState.productLinkConnected) "已连接" else "未连接",
"卫星数" to reading(if (telemetry.gpsValid) telemetry.gpsSatelliteCount.toString() else "定位不可用"),
"返航点" to reading(if (telemetry.homeLocationValid) "已记录" else "未取得"),
"RTK" to reading(if (telemetry.hasReliableRtkForCheck()) "定位可用" else if (telemetry.rtkEnabled) "等待定位" else "未启用")
), Modifier.weight(1f))
CheckCard("电池与设备", listOf(
"飞行器电量" to reading(if (telemetry.batteryPercent in 0..100) "${telemetry.batteryPercent}%" else "—"),
"遥控器电量" to if (sdkState.productLinkConnected && telemetry.rcBatteryPercent in 0..100) "${telemetry.rcBatteryPercent}%" else "—",
"电池温度" to reading(if (telemetry.batteryTemperatureKnown) "${instrumentNumber(telemetry.batteryTemperature)} °C" else "—"),
"预计剩余飞行时间" to reading(if (telemetry.remainingFlightTimeKnown) "${telemetry.remainingFlightTime / 60} 分钟" else "—"),
"固件版本" to reading(telemetry.firmwareVersion.ifBlank { "—" })
), Modifier.weight(1f))
}
Spacer(Modifier.height(12.dp))
Text(sdkState.registerError ?: sdkState.aircraftConnectionDetail, color = Color(0xFF9CABB9), fontSize = 12.sp)
Text("起飞前请检查机臂、桨叶及周围环境,并确认返航与避障设置。", color = Color(0xFF9CABB9), fontSize = 12.sp, modifier = Modifier.padding(top = 8.dp))
}
}
private fun TelemetrySnapshot.hasReliableRtkForCheck() =
hasReliableRtkPosition()
@Composable
private fun CheckCard(title: String, rows: List<Pair<String, String>>, modifier: Modifier) {
Surface(color = Color(0xFF171F2A), shape = RoundedCornerShape(16.dp), modifier = modifier) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
Text(title, color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold)
rows.forEach { (label, value) ->
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
Text(label, color = Color(0xFF9CABB9), fontSize = 13.sp, modifier = Modifier.weight(1f))
Text(value, color = Color.White, fontSize = 13.sp, modifier = Modifier.weight(1f))
private fun CheckCard(title: String, subtitle: String, icon: ImageVector, healthy: Boolean, rows: List<Pair<String, String>>, onConfirm: (() -> Unit)? = null) {
Surface(Modifier.fillMaxWidth(), color = Color.White.copy(alpha = 0.9f), shape = androidx.compose.foundation.shape.RoundedCornerShape(10.dp)) {
Column(Modifier.padding(12.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.size(40.dp).background(PilotDesign.Background, CircleShape), contentAlignment = Alignment.Center) { Icon(icon, null, tint = PilotDesign.Ink, modifier = Modifier.size(25.dp)) }
Column(Modifier.weight(1f).padding(start = 14.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(title, color = PilotDesign.Ink, fontSize = 17.sp, lineHeight = 21.sp, fontWeight = FontWeight.Bold)
Text(subtitle, color = PilotDesign.Muted, fontSize = 11.sp, lineHeight = 14.sp)
}
if (onConfirm == null) PilotStatus(if (healthy) "正常" else "待确认", healthy)
else TextButton(onClick = onConfirm, contentPadding = PaddingValues(4.dp)) { Icon(if (healthy) Icons.Default.CheckCircle else Icons.Default.Help, null, tint = if (healthy) PilotDesign.Teal else PilotDesign.Muted, modifier = Modifier.size(19.dp)); Text(if (healthy) "已确认" else "需确认", fontSize = 12.sp) }
}
Spacer(Modifier.height(10.dp))
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { rows.forEachIndexed { index, (label, value) ->
if (index > 0) VerticalDivider(Modifier.height(32.dp), color = PilotDesign.Line)
PilotMetric(label, value, Modifier.weight(1f))
} }
}
}
}
@@ -0,0 +1,284 @@
package com.zklh.dronecontroller.ui
import android.content.Context
import android.graphics.PointF
import android.view.View
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.zklh.dronecontroller.core.map.*
import com.zklh.dronecontroller.core.mission.MissionPreview
import com.zklh.dronecontroller.core.telemetry.TelemetrySnapshot
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
/** SDK initialization is deferred until a user has supplied a key and consented. */
internal object VendorMapRuntime {
val amapError = MutableStateFlow<String?>(null)
val baiduError = MutableStateFlow<String?>(null)
private var amapKey: String? = null
private var baiduKey: String? = null
@Synchronized
fun initialize(context: Context, config: MapConfiguration): String? {
config.validationError()?.let { return it }
val previous = if (config.provider == MapProvider.AMAP) amapKey else baiduKey
if (previous != null) return if (previous == config.key) null else "Key 已保存,请完全退出 App 后重新打开以重新鉴权"
val app = context.applicationContext
return try {
if (config.provider == MapProvider.AMAP) {
com.amap.api.maps.MapsInitializer.updatePrivacyShow(app, true, true)
com.amap.api.maps.MapsInitializer.updatePrivacyAgree(app, config.amapConsent)
com.amap.api.maps.MapsInitializer.setApiKey(config.key)
com.amap.api.maps.MapsInitializer.setProtocol(com.amap.api.maps.MapsInitializer.HTTPS)
com.amap.api.maps.MapsInitializer.setExceptionLogger(object : com.amap.api.maps.ExceptionLogger {
override fun onException(error: Throwable) { amapError.value = "高德地图加载异常,请检查 Android Key、签名绑定和网络" }
override fun onDownloaderException(status: Int, code: Int) { amapError.value = "高德地图下载失败($status / $code),请检查 Key 和网络" }
})
amapError.value = null
amapKey = config.key
} else {
com.baidu.mapapi.SDKInitializer.setAgreePrivacy(app, config.baiduConsent)
com.baidu.mapapi.SDKInitializer.setApiKey(config.key)
com.baidu.mapapi.SDKInitializer.setCoordType(com.baidu.mapapi.CoordType.BD09LL)
com.baidu.mapapi.SDKInitializer.setHttpsEnable(true)
baiduError.value = "百度地图正在鉴权…"
com.baidu.mapapi.SDKInitializer.addAuthResultListener { status, _ ->
baiduError.value = if (status == 0) null else "百度地图鉴权失败($status),请检查 Android Key 与签名绑定"
}
com.baidu.mapapi.SDKInitializer.initialize(app)
baiduKey = config.key
}
null
} catch (_: Exception) { "地图 SDK 初始化失败,请检查配置后重开 App" }
}
}
@Composable
internal fun PilotVendorMap(connected: Boolean, telemetry: TelemetrySnapshot, modifier: Modifier, mission: MissionPreview?, controls: Boolean, controlsLeading: Boolean, config: MapConfiguration, onConfigure: () -> Unit) {
val context = LocalContext.current
val lifecycle = LocalLifecycleOwner.current.lifecycle
val scope = rememberCoroutineScope()
val store = remember { MapConfigurationStore.get(context) }
var ready by remember { mutableStateOf(false) }
var timeout by remember { mutableStateOf(false) }
var revision by remember { mutableStateOf(0) }
val positions = MapLivePositions.from(connected, telemetry, config.coordinateSystem)
val initializationError = remember(config.provider, config.key, config.consent) { VendorMapRuntime.initialize(context, config) }
val sdkError by (if (config.provider == MapProvider.AMAP) VendorMapRuntime.amapError else VendorMapRuntime.baiduError).collectAsState()
val controller: VendorPilotController? = remember(config.provider, config.key, initializationError) {
if (initializationError != null) null else runCatching {
if (config.provider == MapProvider.AMAP) AmapPilotController(context, { ready = true }, { revision++ })
else BaiduPilotController(context, { ready = true }, { revision++ })
}.getOrNull()
}
fun display(lat: Double, lng: Double) = MapCoordinates.display(lat, lng, config.coordinateSystem)
fun center() {
val target = controller ?: return
val points = positions.focusPoints(mission, config.coordinateSystem)
if (points.isNotEmpty()) target.center(points, if (positions.aircraft != null || mission != null) 16f else 14f)
}
DisposableEffect(controller, lifecycle) {
val observer = LifecycleEventObserver { _, event -> when (event) {
Lifecycle.Event.ON_RESUME -> controller?.resume()
Lifecycle.Event.ON_PAUSE -> controller?.pause()
else -> Unit
} }
lifecycle.addObserver(observer)
if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) controller?.resume()
onDispose { lifecycle.removeObserver(observer); controller?.pause(); controller?.destroy() }
}
LaunchedEffect(controller, config.satellite) { controller?.satellite(config.satellite) }
LaunchedEffect(controller, ready) { timeout = false; if (!ready && controller != null) { delay(15000); timeout = !ready } }
LaunchedEffect(controller, mission, ready) {
if (ready) controller?.mission(mission?.points.orEmpty().map { display(it.latitude, it.longitude) })
}
LaunchedEffect(controller, ready, positions, telemetry.heading) {
if (ready) {
controller?.telemetry(positions.aircraft, positions.home, positions.remoteController, telemetry.heading.toFloat())
}
}
LaunchedEffect(controller, ready, mission, positions.aircraft != null, positions.remoteController != null) { if (ready) center() }
Box(modifier.background(PilotDesign.Background)) {
controller?.let { native -> AndroidView(factory = { native.view }, modifier = Modifier.fillMaxSize()) }
if (controller != null && ready) {
PilotMapLabels(positions, mission, revision, controls, project = { controller.project(it) }, missionPosition = { lat, lng -> display(lat, lng) })
}
if (controls) PilotMapLocationStatus(positions, connected, Modifier.align(Alignment.BottomCenter).padding(bottom = 6.dp), telemetry.rcLocationStatus)
if (controls) Surface(Modifier.align(if (controlsLeading) Alignment.TopStart else Alignment.TopEnd).padding(12.dp), color = Color.White.copy(alpha = 0.94f), shape = RoundedCornerShape(7.dp)) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
if (controlsLeading) {
Column(Modifier.width(36.dp)) {
PilotTool(Icons.Default.Layers, "图层", onClick = onConfigure)
PilotTool(Icons.Default.Map, if (config.satellite) "影像" else "街道") { scope.launch { store.save(config.copy(satellite = !config.satellite)) } }
PilotTool(Icons.Default.MyLocation, "定位") { center() }
PilotTool(Icons.Default.Navigation, "朝北") { controller?.north() }
}
} else {
IconButton(onClick = onConfigure) { Icon(Icons.Default.Layers, "图层配置", tint = PilotDesign.Ink) }
IconButton(onClick = { scope.launch { store.save(config.copy(satellite = !config.satellite)) } }) { Icon(Icons.Default.Map, "切换影像/街道", tint = PilotDesign.Ink) }
IconButton(onClick = { controller?.north() }) { Icon(Icons.Default.Navigation, "朝北", tint = PilotDesign.Ink) }
IconButton(onClick = { center() }) { Icon(Icons.Default.MyLocation, "定位", tint = PilotDesign.Ink) }
}
IconButton(onClick = { controller?.zoom(true) }) { Icon(Icons.Default.Add, "放大", tint = PilotDesign.Ink) }
IconButton(onClick = { controller?.zoom(false) }) { Icon(Icons.Default.Remove, "缩小", tint = PilotDesign.Ink) }
}
}
val error = initializationError ?: if (controller == null) "地图创建失败,请检查配置" else sdkError ?: if (timeout) "底图加载较慢,请检查 Android Key、签名绑定和网络" else null
if (error != null) Surface(modifier = Modifier.align(if (controls) Alignment.TopCenter else Alignment.Center).padding(12.dp), color = Color(0xDE203A50), shape = RoundedCornerShape(6.dp)) {
Text(if (controls) error else "底图暂不可用", color = Color.White, fontSize = 10.sp, lineHeight = 14.sp, modifier = Modifier.padding(10.dp))
}
Text("${config.provider.label} · ${if (config.satellite) "卫星影像" else "街道地图"}", color = Color.White, fontSize = 8.sp, lineHeight = 11.sp,
modifier = Modifier.align(Alignment.BottomEnd).background(Color(0xB3193B55), RoundedCornerShape(topStart = 4.dp)).padding(horizontal = 6.dp, vertical = 3.dp))
}
}
private interface VendorPilotController {
val view: View
fun resume()
fun pause()
fun destroy()
fun satellite(value: Boolean)
fun center(points: List<MapPosition>, zoom: Float)
fun zoom(inside: Boolean)
fun north()
fun mission(points: List<MapPosition>)
fun telemetry(aircraft: MapPosition?, home: MapPosition?, remoteController: MapPosition?, heading: Float)
fun project(position: MapPosition): PointF
}
private class AmapPilotController(context: Context, loaded: () -> Unit, changed: () -> Unit) : VendorPilotController {
override val view = com.amap.api.maps.TextureMapView(context).apply { onCreate(null) }
private val map = view.map
private val route = mutableListOf<() -> Unit>()
private var aircraftMarker: com.amap.api.maps.model.Marker? = null
private var homeMarker: com.amap.api.maps.model.Marker? = null
private var rcMarker: com.amap.api.maps.model.Marker? = null
private val aircraftIcons = mutableMapOf<Int, com.amap.api.maps.model.BitmapDescriptor>()
private val homeIcon = com.amap.api.maps.model.BitmapDescriptorFactory.fromBitmap(pilotMapMarker(PilotDesign.Teal.toArgb(), "H", false))
private val rcIcon = com.amap.api.maps.model.BitmapDescriptorFactory.fromBitmap(pilotMapMarker(PilotRcMapColor.toArgb(), "RC", false))
private val pointIcon = com.amap.api.maps.model.BitmapDescriptorFactory.fromBitmap(pilotMapMarker(PilotDesign.Blue.toArgb(), "", false))
private fun latLng(p: MapPosition) = com.amap.api.maps.model.LatLng(p.latitude, p.longitude)
init {
map.uiSettings.isZoomControlsEnabled = false
map.uiSettings.isCompassEnabled = false
map.uiSettings.isMyLocationButtonEnabled = false
map.uiSettings.isTiltGesturesEnabled = false
map.setOnMapLoadedListener { loaded() }
map.setOnCameraChangeListener(object : com.amap.api.maps.AMap.OnCameraChangeListener {
override fun onCameraChange(position: com.amap.api.maps.model.CameraPosition) = changed()
override fun onCameraChangeFinish(position: com.amap.api.maps.model.CameraPosition) = changed()
})
map.moveCamera(com.amap.api.maps.CameraUpdateFactory.newLatLngZoom(latLng(MapCoordinates.display(35.0, 104.0, MapCoordinateSystem.GCJ02)), 3f))
}
override fun resume() = view.onResume()
override fun pause() = view.onPause()
override fun destroy() { view.onDestroy(); (aircraftIcons.values + listOf(homeIcon, rcIcon, pointIcon)).forEach { it.recycle() } }
override fun satellite(value: Boolean) { map.mapType = if (value) com.amap.api.maps.AMap.MAP_TYPE_SATELLITE else com.amap.api.maps.AMap.MAP_TYPE_NORMAL }
override fun center(points: List<MapPosition>, zoom: Float) {
if (points.isEmpty()) return
val update = if (points.size == 1 || points.distinct().size == 1) com.amap.api.maps.CameraUpdateFactory.newLatLngZoom(latLng(points.first()), zoom)
else com.amap.api.maps.CameraUpdateFactory.newLatLngBounds(com.amap.api.maps.model.LatLngBounds.Builder().apply { points.forEach { include(latLng(it)) } }.build(), 65)
map.animateCamera(update)
}
override fun zoom(inside: Boolean) = map.animateCamera(if (inside) com.amap.api.maps.CameraUpdateFactory.zoomIn() else com.amap.api.maps.CameraUpdateFactory.zoomOut())
override fun north() = map.animateCamera(com.amap.api.maps.CameraUpdateFactory.changeBearing(0f))
override fun mission(points: List<MapPosition>) {
route.forEach { it() }; route.clear()
if (points.size > 1) { val line = map.addPolyline(com.amap.api.maps.model.PolylineOptions().addAll(points.map { latLng(it) }).color(PilotDesign.Blue.toArgb()).width(5f)); route += { line.remove() } }
points.forEach { p -> val marker = map.addMarker(com.amap.api.maps.model.MarkerOptions().position(latLng(p)).anchor(0.5f, 0.5f).icon(pointIcon)); route += { marker.remove() } }
}
override fun telemetry(aircraft: MapPosition?, home: MapPosition?, remoteController: MapPosition?, heading: Float) {
if (remoteController == null) { rcMarker?.remove(); rcMarker = null } else {
if (rcMarker == null) rcMarker = map.addMarker(com.amap.api.maps.model.MarkerOptions().position(latLng(remoteController)).anchor(0.5f, 0.5f).title("遥控器当前位置").zIndex(1f).icon(rcIcon))
rcMarker?.position = latLng(remoteController)
}
if (home == null) { homeMarker?.remove(); homeMarker = null } else {
if (homeMarker == null) homeMarker = map.addMarker(com.amap.api.maps.model.MarkerOptions().position(latLng(home)).anchor(0.5f, 0.5f).title("返航点").icon(homeIcon))
homeMarker?.position = latLng(home)
}
if (aircraft == null) { aircraftMarker?.remove(); aircraftMarker = null } else {
val direction = (((heading % 360 + 360) % 360) / 5).toInt() * 5
val icon = aircraftIcons.getOrPut(direction) { com.amap.api.maps.model.BitmapDescriptorFactory.fromBitmap(pilotMapMarker(PilotDesign.Blue.toArgb(), "", true, direction.toFloat())) }
if (aircraftMarker == null) aircraftMarker = map.addMarker(com.amap.api.maps.model.MarkerOptions().position(latLng(aircraft)).anchor(0.5f, 0.5f).title("飞行器").zIndex(2f).icon(icon))
aircraftMarker?.position = latLng(aircraft); aircraftMarker?.setIcon(icon)
}
}
override fun project(position: MapPosition): PointF = map.projection.toScreenLocation(latLng(position)).let { PointF(it.x.toFloat(), it.y.toFloat()) }
}
private class BaiduPilotController(context: Context, loaded: () -> Unit, changed: () -> Unit) : VendorPilotController {
override val view = com.baidu.mapapi.map.TextureMapView(context).apply { showZoomControls(false) }
private val map = view.map
private val route = mutableListOf<com.baidu.mapapi.map.Overlay>()
private var aircraftMarker: com.baidu.mapapi.map.Marker? = null
private var homeMarker: com.baidu.mapapi.map.Marker? = null
private var rcMarker: com.baidu.mapapi.map.Marker? = null
private val aircraftIcons = mutableMapOf<Int, com.baidu.mapapi.map.BitmapDescriptor>()
private val homeIcon = com.baidu.mapapi.map.BitmapDescriptorFactory.fromBitmap(pilotMapMarker(PilotDesign.Teal.toArgb(), "H", false))
private val rcIcon = com.baidu.mapapi.map.BitmapDescriptorFactory.fromBitmap(pilotMapMarker(PilotRcMapColor.toArgb(), "RC", false))
private val pointIcon = com.baidu.mapapi.map.BitmapDescriptorFactory.fromBitmap(pilotMapMarker(PilotDesign.Blue.toArgb(), "", false))
private fun latLng(p: MapPosition) = com.baidu.mapapi.model.LatLng(p.latitude, p.longitude)
init {
map.uiSettings.isCompassEnabled = false
map.uiSettings.isOverlookingGesturesEnabled = false
map.setOnMapLoadedCallback { loaded() }
map.setOnMapStatusChangeListener(object : com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener {
override fun onMapStatusChangeStart(status: com.baidu.mapapi.map.MapStatus) = changed()
override fun onMapStatusChangeStart(status: com.baidu.mapapi.map.MapStatus, reason: Int) = changed()
override fun onMapStatusChange(status: com.baidu.mapapi.map.MapStatus) = changed()
override fun onMapStatusChangeFinish(status: com.baidu.mapapi.map.MapStatus) = changed()
})
map.setMapStatus(com.baidu.mapapi.map.MapStatusUpdateFactory.newLatLngZoom(latLng(MapCoordinates.display(35.0, 104.0, MapCoordinateSystem.BD09)), 3f))
}
override fun resume() = view.onResume()
override fun pause() = view.onPause()
override fun destroy() { view.onDestroy(); (aircraftIcons.values + listOf(homeIcon, rcIcon, pointIcon)).forEach { it.recycle() } }
override fun satellite(value: Boolean) { map.mapType = if (value) com.baidu.mapapi.map.BaiduMap.MAP_TYPE_SATELLITE else com.baidu.mapapi.map.BaiduMap.MAP_TYPE_NORMAL }
override fun center(points: List<MapPosition>, zoom: Float) {
if (points.isEmpty()) return
val update = if (points.size == 1 || points.distinct().size == 1) com.baidu.mapapi.map.MapStatusUpdateFactory.newLatLngZoom(latLng(points.first()), zoom)
else com.baidu.mapapi.map.MapStatusUpdateFactory.newLatLngBounds(com.baidu.mapapi.model.LatLngBounds.Builder().include(points.map { latLng(it) }).build(), 65, 65, 65, 65)
map.animateMapStatus(update)
}
override fun zoom(inside: Boolean) = map.animateMapStatus(if (inside) com.baidu.mapapi.map.MapStatusUpdateFactory.zoomIn() else com.baidu.mapapi.map.MapStatusUpdateFactory.zoomOut())
override fun north() = map.animateMapStatus(com.baidu.mapapi.map.MapStatusUpdateFactory.newMapStatus(com.baidu.mapapi.map.MapStatus.Builder(map.mapStatus).rotate(0f).overlook(0f).build()))
override fun mission(points: List<MapPosition>) {
route.forEach { it.remove() }; route.clear()
if (points.size > 1) route += map.addOverlay(com.baidu.mapapi.map.PolylineOptions().points(points.map { latLng(it) }).color(PilotDesign.Blue.toArgb()).width(5f))
points.forEach { p -> route += map.addOverlay(com.baidu.mapapi.map.MarkerOptions().position(latLng(p)).anchor(0.5f, 0.5f).icon(pointIcon)) }
}
override fun telemetry(aircraft: MapPosition?, home: MapPosition?, remoteController: MapPosition?, heading: Float) {
if (remoteController == null) { rcMarker?.remove(); rcMarker = null } else {
if (rcMarker == null) rcMarker = map.addOverlay(com.baidu.mapapi.map.MarkerOptions().position(latLng(remoteController)).anchor(0.5f, 0.5f).title("遥控器当前位置").zIndex(1).icon(rcIcon)) as com.baidu.mapapi.map.Marker
rcMarker?.position = latLng(remoteController)
}
if (home == null) { homeMarker?.remove(); homeMarker = null } else {
if (homeMarker == null) homeMarker = map.addOverlay(com.baidu.mapapi.map.MarkerOptions().position(latLng(home)).anchor(0.5f, 0.5f).title("返航点").icon(homeIcon)) as com.baidu.mapapi.map.Marker
homeMarker?.position = latLng(home)
}
if (aircraft == null) { aircraftMarker?.remove(); aircraftMarker = null } else {
val direction = (((heading % 360 + 360) % 360) / 5).toInt() * 5
val icon = aircraftIcons.getOrPut(direction) { com.baidu.mapapi.map.BitmapDescriptorFactory.fromBitmap(pilotMapMarker(PilotDesign.Blue.toArgb(), "", true, direction.toFloat())) }
if (aircraftMarker == null) aircraftMarker = map.addOverlay(com.baidu.mapapi.map.MarkerOptions().position(latLng(aircraft)).anchor(0.5f, 0.5f).title("飞行器").zIndex(2).icon(icon)) as com.baidu.mapapi.map.Marker
aircraftMarker?.position = latLng(aircraft); aircraftMarker?.setIcon(icon)
}
}
override fun project(position: MapPosition): PointF = map.projection.toScreenLocation(latLng(position)).let { PointF(it.x.toFloat(), it.y.toFloat()) }
}
@@ -2,26 +2,59 @@ package com.zklh.dronecontroller.ui
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.material3.Typography
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.PlatformTextStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Compact landscape controls need an explicit line height. Changing fontSize on
// Material's 16/24 body style alone leaves a 24sp line even for a 10sp label.
private fun pilotText(size: Int, height: Int, weight: FontWeight = FontWeight.Normal) = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = weight,
fontSize = size.sp,
lineHeight = height.sp,
letterSpacing = 0.sp,
platformStyle = PlatformTextStyle(includeFontPadding = false)
)
private val ControllerTypography = Typography(
bodyLarge = pilotText(14, 18),
bodyMedium = pilotText(12, 16),
bodySmall = pilotText(10, 14),
labelLarge = pilotText(13, 18, FontWeight.Medium),
labelMedium = pilotText(11, 14, FontWeight.Medium),
labelSmall = pilotText(10, 12, FontWeight.Medium),
titleLarge = pilotText(22, 28, FontWeight.Bold),
titleMedium = pilotText(16, 22, FontWeight.Medium),
titleSmall = pilotText(14, 18, FontWeight.Medium)
)
private val ControllerColors = lightColorScheme(
primary = Color(0xFF1D4ED8),
secondary = Color(0xFF047857),
primary = PilotDesign.Blue,
secondary = PilotDesign.Teal,
tertiary = Color(0xFFB45309),
error = Color(0xFFB91C1C),
background = Color(0xFFF7F8FA),
background = PilotDesign.Background,
surface = Color(0xFFFFFFFF),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White
onTertiary = Color.White,
onBackground = PilotDesign.Ink,
onSurface = PilotDesign.Ink,
onSurfaceVariant = PilotDesign.Muted,
outline = PilotDesign.Line
)
@Composable
fun ZklhDroneTheme(content: @Composable () -> Unit) {
MaterialTheme(
colorScheme = ControllerColors,
typography = MaterialTheme.typography,
typography = ControllerTypography,
content = content
)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

@@ -0,0 +1,79 @@
package com.zklh.dronecontroller.core.map
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
class MapConfigurationTest {
@Test fun savedDocumentRestoresKeysAndPrivateCatalogAfterReload() {
val second = PrivateMapLayer(id = "region", name = "区域影像", url = "https://maps.example.com/{z}/{x}/{y}.png?token=test", annotationUrl = "https://maps.example.com/labels/{z}/{x}/{y}.png", coordinates = MapCoordinateSystem.WGS84, scheme = TileScheme.TMS, minZoom = 5, maxZoom = 18)
val original = MapConfiguration(MapProvider.BAIDU, "test-tdt", "test-amap", "test-baidu", true, true, false, listOf(PrivateMapLayer(), second), "region")
val persisted = MapConfigurationCodec.encode(original)
assertEquals(original, MapConfigurationCodec.decode(persisted))
val switched = MapConfigurationCodec.decode(MapConfigurationCodec.encode(original.copy(provider = MapProvider.PRIVATE)))
assertEquals("test-amap", switched.amapKey)
assertEquals("test-baidu", switched.baiduKey)
assertEquals(second, switched.activeLayer)
}
@Test fun removedLayerAndSelectionSurviveReload() {
val regional = PrivateMapLayer(id = "region")
val config = MapConfiguration(privateLayers = listOf(regional), activeLayerId = regional.id)
assertEquals(listOf(regional), MapConfigurationCodec.decode(MapConfigurationCodec.encode(config)).privateLayers)
}
@Test fun missingKeyOrConsentCannotActivateVendorSdk() {
assertNotNull(MapConfiguration(provider = MapProvider.AMAP).validationError())
assertNotNull(MapConfiguration(provider = MapProvider.AMAP, amapKey = "test").validationError())
assertNull(MapConfiguration(provider = MapProvider.AMAP, amapKey = "test", amapConsent = true).validationError())
assertNotNull(MapConfiguration(provider = MapProvider.BAIDU, baiduKey = "test").validationError())
assertNull(MapConfiguration(provider = MapProvider.BAIDU, baiduKey = "test", baiduConsent = true).validationError())
}
@Test fun rejectsUnsupportedTemplatesAndBadZoomRange() {
listOf("http://maps.example.com/{z}/{x}/{y}.png", "https://maps.example.com/{z}/{x}.png", "file:///sdcard/{z}/{x}/{y}.jpg", "https://maps.example.com/{z}/{x}/{y}.png#fragment").forEach {
assertNotNull(PrivateMapLayer(url = it).validationError())
}
assertNotNull(PrivateMapLayer(minZoom = 9, maxZoom = 8).validationError())
assertNotNull(PrivateMapLayer(maxZoom = 23).validationError())
assertNotNull(PrivateMapLayer(annotationUrl = "bad").validationError())
assertNull(PrivateMapLayer().validationError())
}
@Test fun rejectsEmptyCatalogAndMissingSelection() {
assertNotNull(MapConfiguration(privateLayers = emptyList()).validationError())
assertNotNull(MapConfiguration(activeLayerId = "missing").validationError())
assertNotNull(MapConfiguration(privateLayers = listOf(PrivateMapLayer(), PrivateMapLayer())).validationError())
}
@Test fun sourcePreservesProjectionSchemeZoomAndAnnotation() {
val layer = PrivateMapLayer(annotationUrl = "https://maps.example.com/{z}/{x}/{y}.png", scheme = TileScheme.TMS, minZoom = 2, maxZoom = 8)
val doc = JSONObject(PrivateMapSource.styleJson(layer))
val base = doc.getJSONObject("sources").getJSONObject("basemap")
assertEquals("tms", base.getString("scheme"))
assertEquals(2, base.getInt("minzoom")); assertEquals(8, base.getInt("maxzoom"))
assertEquals(layer.url, base.getJSONArray("tiles").getString(0))
assertEquals(layer.annotationUrl, doc.getJSONObject("sources").getJSONObject("labels").getJSONArray("tiles").getString(0))
}
@Test fun xyzAndTmsProbeUseCorrectRow() {
val template = "https://maps.example.com/{z}/{x}/{y}.jpg"
assertEquals("https://maps.example.com/1/1/1.jpg", PrivateMapSource.tileUrl(template, 1, 0.0, 0.0, TileScheme.XYZ))
assertEquals("https://maps.example.com/1/1/0.jpg", PrivateMapSource.tileUrl(template, 1, 0.0, 0.0, TileScheme.TMS))
assertEquals("https://maps.example.com/0/0/0.jpg", PrivateMapSource.tileUrl(template, 0, 90.0, 180.0, TileScheme.XYZ))
}
@Test fun displayCoordinatesMatchKnownBeijingPoint() {
val gcj = MapCoordinates.display(39.908823, 116.397470, MapCoordinateSystem.GCJ02)
assertEquals(39.9102265, gcj.latitude, 0.000001)
assertEquals(116.4037136, gcj.longitude, 0.000001)
val bd = MapCoordinates.display(39.908823, 116.397470, MapCoordinateSystem.BD09)
assertEquals(39.9165658, bd.latitude, 0.000001)
assertEquals(116.4100865, bd.longitude, 0.000001)
}
@Test fun wgsAndOutsideChinaGcjAreUnmodified() {
assertEquals(MapPosition(39.908823, 116.397470), MapCoordinates.display(39.908823, 116.397470, MapCoordinateSystem.WGS84))
assertEquals(MapPosition(51.5, -0.12), MapCoordinates.display(51.5, -0.12, MapCoordinateSystem.GCJ02))
}
}
@@ -0,0 +1,61 @@
package com.zklh.dronecontroller.core.map
import com.zklh.dronecontroller.core.mission.MissionPreview
import com.zklh.dronecontroller.core.mission.MissionPreviewPoint
import com.zklh.dronecontroller.core.telemetry.TelemetrySnapshot
import org.junit.Assert.*
import org.junit.Test
class MapLivePositionsTest {
private val telemetry = TelemetrySnapshot(
latitude = 39.908823, longitude = 116.397470, locationValid = true,
rcLatitude = 39.9, rcLongitude = 116.39, rcLocationValid = true,
homeLatitude = 39.901, homeLongitude = 116.391, homeLocationValid = true
)
@Test fun aircraftAndControllerUseDistinctLiveCoordinates() {
val positions = MapLivePositions.from(true, telemetry, MapCoordinateSystem.WGS84)
assertEquals(MapPosition(telemetry.latitude, telemetry.longitude), positions.aircraft)
assertEquals(MapPosition(telemetry.rcLatitude, telemetry.rcLongitude), positions.remoteController)
assertEquals(MapPosition(telemetry.homeLatitude, telemetry.homeLongitude), positions.home)
}
@Test fun controllerStillAppearsWithoutAircraftConnection() {
val positions = MapLivePositions.from(false, telemetry, MapCoordinateSystem.WGS84)
assertNull(positions.aircraft); assertNull(positions.home)
assertEquals(MapPosition(telemetry.rcLatitude, telemetry.rcLongitude), positions.remoteController)
}
@Test fun missingFixOrInvalidCoordinatesDoNotProduceFakeMarkers() {
val noFix = MapLivePositions.from(true, telemetry.copy(locationValid = false, rcLocationValid = false, homeLocationValid = false), MapCoordinateSystem.WGS84)
assertNull(noFix.aircraft); assertNull(noFix.remoteController); assertNull(noFix.home)
val invalid = MapLivePositions.from(true, telemetry.copy(latitude = Double.NaN, rcLongitude = 181.0, homeLatitude = 0.0, homeLongitude = 0.0), MapCoordinateSystem.GCJ02)
assertNull(invalid.aircraft); assertNull(invalid.remoteController); assertNull(invalid.home)
}
@Test fun everyProviderConvertsAllLocationsWithoutChangingRawTelemetry() {
MapCoordinateSystem.entries.forEach { coordinates ->
val positions = MapLivePositions.from(true, telemetry, coordinates)
assertEquals(MapCoordinates.display(telemetry.latitude, telemetry.longitude, coordinates), positions.aircraft)
assertEquals(MapCoordinates.display(telemetry.rcLatitude, telemetry.rcLongitude, coordinates), positions.remoteController)
assertEquals(MapCoordinates.display(telemetry.homeLatitude, telemetry.homeLongitude, coordinates), positions.home)
}
assertEquals(39.908823, telemetry.latitude, 0.0)
assertEquals(116.39, telemetry.rcLongitude, 0.0)
}
@Test fun focusContainsAircraftControllerAndRouteWithOneConversion() {
val point = MissionPreviewPoint(39.91, 116.41, 80.0, 0)
val route = MissionPreview("test", listOf(point), 0.0, null, "", "", "", 0, 0, 1)
val positions = MapLivePositions.from(true, telemetry, MapCoordinateSystem.GCJ02)
val focus = positions.focusPoints(route, MapCoordinateSystem.GCJ02)
assertEquals(listOf(MapCoordinates.display(point.latitude, point.longitude, MapCoordinateSystem.GCJ02), positions.aircraft, positions.remoteController), focus)
}
@Test fun coincidentLocationsProduceASingleCameraTarget() {
val same = telemetry.copy(rcLatitude = telemetry.latitude, rcLongitude = telemetry.longitude)
val positions = MapLivePositions.from(true, same, MapCoordinateSystem.WGS84)
assertEquals(positions.aircraft, positions.remoteController)
assertEquals(listOf(positions.aircraft), positions.focusPoints(null, MapCoordinateSystem.WGS84))
}
}
@@ -0,0 +1,163 @@
package com.zklh.dronecontroller.core.map
import com.zklh.dronecontroller.core.cloud.CloudLoginRequest
import com.zklh.dronecontroller.core.cloud.PlatformHosts
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
class PlatformMapTest {
private fun row(id: Int, name: String = "区域影像", max: Int = 17, z: Int = 1000): JSONObject = JSONObject()
.put("id", id).put("name", name).put("status", 0).put("defaultShow", 0)
.put("chinaCrs", "GCJ02").put("minZoom", 1).put("maxZoom", max).put("opacity", 0.7)
.put("url", "https://c2.zklhjs.com/map/$id/{z}/{x}/{y}.png")
.put("configJson", """{"type":"xyz","rectangle":{"xmin":118.3,"xmax":119.3,"ymin":31.2,"ymax":32.6,},"zIndex":$z,},""")
@Test fun loadsAllEnabledLayersInServerOrderWithBoundsOpacityAndNativeZoom() {
val rows = JSONArray().put(row(3, "区域路网标注", 18, 1001))
.put(row(2, max = 18)).put(row(1, "全球底图", 8, 900))
val catalog = PlatformMapSource.catalog(rows)
assertTrue(catalog.issues.isEmpty())
assertEquals(listOf("1", "2", "3"), catalog.layers.map { it.id })
val style = JSONObject(PlatformMapSource.styleJson(catalog))
val sources = style.getJSONObject("sources")
assertEquals(3, sources.length())
assertEquals(8, sources.getJSONObject("platform-0").getInt("maxzoom"))
assertEquals(18, sources.getJSONObject("platform-1").getInt("maxzoom"))
assertEquals("https://uav.zklhjs.com/map/2/{z}/{x}/{y}.png", sources.getJSONObject("platform-1").getJSONArray("tiles").getString(0))
assertEquals("[118.3,31.2,119.3,32.6]", sources.getJSONObject("platform-1").getJSONArray("bounds").toString())
val image = style.getJSONArray("layers").getJSONObject(2)
assertEquals(0.7, image.getJSONObject("paint").getDouble("raster-opacity"), 0.0)
assertFalse(image.has("maxzoom")) // Keep global/regional imagery visible by overzooming.
}
@Test fun currentPlatformCatalogLoadsAllNineIncludingLegacyNanjingConfig() {
val text = javaClass.getResourceAsStream("/platform-layers.json")!!.bufferedReader().use { it.readText() }
val catalog = PlatformMapSource.catalog(JSONArray(text))
assertEquals(9, catalog.layers.size)
assertTrue(catalog.issues.toString(), catalog.issues.isEmpty())
assertEquals("谷歌全球离线底图", catalog.layers.first().name)
val nanjing = catalog.layers.first { it.id == "2" }
assertEquals(18, nanjing.maxZoom)
assertEquals(118.358459, nanjing.bounds!!.west, 0.0)
assertTrue(catalog.layers.indexOfFirst { it.id == "2" } < catalog.layers.indexOfFirst { it.id == "3" })
assertEquals(9, JSONObject(PlatformMapSource.styleJson(catalog)).getJSONObject("sources").length())
}
@Test fun reportsUnsupportedOrMisalignedLayersWithoutBreakingGoodLayers() {
val rows = JSONArray().put(row(1, z = 900)).put(row(2).put("status", 1))
.put(row(3).put("configJson", "{\"type\":\"wms\"}"))
.put(row(4).put("chinaCrs", "WGS84"))
.put(row(5).put("minZoom", 20).put("maxZoom", 8))
val result = PlatformMapSource.catalog(rows)
assertEquals(listOf("1"), result.layers.map { it.id })
assertEquals(3, result.issues.size)
assertEquals(MapCoordinateSystem.GCJ02, result.coordinates)
assertEquals(5, result.total)
}
@Test fun rejectsInvalidBoundsInsteadOfRequestingWorldwideRegionalTiles() {
val invalid = row(1).put("configJson", """{"rectangle":{"xmin":180,"xmax":-180,"ymin":0,"ymax":30}}""")
val catalog = PlatformMapSource.catalog(JSONArray().put(invalid))
assertTrue(catalog.layers.isEmpty())
assertEquals(1, catalog.issues.size)
}
@Test fun lenientConfigParsingPreservesStringsAndEscapes() {
val parsed = PlatformMapSource.configJson("""{"name":"quoted \\\" text,}","url":"https://maps.example/?key=a,]",},""")
assertEquals("https://maps.example/?key=a,]", parsed.getString("url"))
assertTrue(parsed.getString("name").endsWith("text,}"))
}
@Test fun cacheRestoresCatalogAndPartitionsAccountsWithoutPersistingLoginData() {
val rows = JSONArray().put(row(1)).put(row(2))
val json = PlatformMapCache.encode(rows, 1000L)
val restored = PlatformMapCache.decode(json)
assertEquals(PlatformMapSource.catalog(rows), restored.first)
assertEquals(1000L, restored.second)
assertFalse(json.contains("accessToken"))
assertFalse(json.contains("password"))
assertNotEquals(PlatformMapCache.key("tenant1", "user"), PlatformMapCache.key("tenant2", "user"))
assertNotEquals(PlatformMapCache.key("tenant1", "user"), PlatformMapCache.key("tenant1", "other"))
assertEquals(PlatformMapCache.key("tenant1", "user"), PlatformMapCache.key(" tenant1 ", " user "))
}
@Test fun defaultRequiresNoKeyAndPreservesOtherProvidersOnReload() {
val config = MapConfiguration(tiandituKey = "tdt", amapKey = "amap", baiduKey = "baidu")
assertEquals(MapProvider.DEFAULT, config.provider)
assertNull(config.validationError())
assertEquals(config, MapConfigurationCodec.decode(MapConfigurationCodec.encode(config)))
val migrated = MapConfigurationCodec.decode(MapConfigurationCodec.encode(config.copy(provider = MapProvider.PRIVATE,
privateLayers = listOf(PrivateMapLayer(url = "https://c2.zklhjs.com/map/{z}/{x}/{y}.jpg")))))
assertEquals(MapProvider.PRIVATE, migrated.provider)
assertEquals("tdt", migrated.tiandituKey)
assertEquals("https://uav.zklhjs.com/map/{z}/{x}/{y}.jpg", migrated.activeLayer.url)
}
@Test fun migratesOnlyLegacyHostPreservingPortsPathsAndKeys() {
assertEquals("rtmp://uav.zklhjs.com:1935/live/drone", PlatformHosts.migrate("rtmp://c2.zklhjs.com:1935/live/drone"))
assertEquals("wss://uav.zklhjs.com:443/mqtt?key=unchanged", PlatformHosts.migrate("wss://C2.zklhjs.com:443/mqtt?key=unchanged"))
assertEquals("uav.zklhjs.com:1883", PlatformHosts.migrate("c2.zklhjs.com:1883"))
assertEquals("https://other.example/c2.zklhjs.com?key=c2.zklhjs.com", PlatformHosts.migrate("https://other.example/c2.zklhjs.com?key=c2.zklhjs.com"))
assertEquals("https://c2.zklhjs.com.evil.example/x", PlatformHosts.migrate("https://c2.zklhjs.com.evil.example/x"))
}
private fun ok(data: Any): JSONObject = JSONObject().put("code", 0).put("data", data)
private val login = CloudLoginRequest("https://uav.zklhjs.com/p", "test-tenant", "test-user", "test-password")
@Test fun fetchesBeyondTwentyAndReauthenticatesWithSaasTokenOn401() {
var logins = 0
var secondPageCalls = 0
val pageNumbers = mutableListOf<Int>()
val client = PlatformMapClient { request ->
when {
request.url.contains("get-id-by-name") -> ok(12)
request.url.endsWith("/auth/login") -> {
logins++
assertEquals("12", request.headers["tenant-id"])
assertEquals("test-user", request.body!!.getString("username"))
ok(JSONObject().put("accessToken", "saas-$logins"))
}
else -> {
assertFalse(request.headers.containsKey("x-auth-token"))
val page = if (request.url.contains("pageNo=1&")) 1 else 2
pageNumbers += page
assertTrue(request.url.contains("current=$page&"))
if (page == 2 && secondPageCalls++ == 0) JSONObject().put("code", 401)
else {
assertEquals("Bearer saas-$logins", request.headers["Authorization"])
val rows = JSONArray()
(if (page == 1) 1..20 else 21..25).forEach { rows.put(row(it)) }
ok(JSONObject().put("list", rows).put("total", 25))
}
}
}
}
assertEquals(25, client.fetch(login).length())
assertEquals(listOf(1, 2, 2), pageNumbers)
assertEquals(2, logins)
}
@Test fun rejectsRepeatedPagesInsteadOfSavingPartialCatalog() {
val client = PlatformMapClient { request -> when {
request.url.contains("get-id-by-name") -> ok(12)
request.url.endsWith("/auth/login") -> ok(JSONObject().put("accessToken", "test"))
else -> ok(JSONObject().put("total", 40).put("list", JSONArray().put(row(1))))
} }
try { client.fetch(login); fail("Expected incomplete pagination to fail") }
catch (expected: IllegalArgumentException) { assertTrue(expected.message!!.contains("完整列表")) }
}
@Test fun unauthorizedSecondAttemptStopsWithoutAnInfiniteLoginLoop() {
var attempts = 0
val client = PlatformMapClient { request -> when {
request.url.contains("get-id-by-name") -> ok(12)
request.url.endsWith("/auth/login") -> { attempts++; ok(JSONObject().put("accessToken", "test")) }
else -> JSONObject().put("code", 401)
} }
try { client.fetch(login); fail("Expected authorization failure") }
catch (expected: IllegalStateException) { assertTrue(expected.message!!.contains("鉴权")) }
assertEquals(2, attempts)
}
}
@@ -0,0 +1,60 @@
package com.zklh.dronecontroller.core.map
import java.net.URLDecoder
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
class TiandituMapSourceTest {
@Test fun imageryIncludesSeparateChineseLabelsAboveBasemap() {
val style = JSONObject(TiandituMapSource.styleJson(true, "test-key"))
assertSource(style, "basemap", "img_w")
assertSource(style, "labels", "cia_w")
val layers = style.getJSONArray("layers")
assertEquals("background", layers.getJSONObject(0).getString("type"))
assertEquals("basemap", layers.getJSONObject(1).getString("source"))
assertEquals("labels", layers.getJSONObject(2).getString("source"))
}
@Test fun streetMapUsesMatchingVectorAnnotationTiles() {
val style = JSONObject(TiandituMapSource.styleJson(false, "test-key"))
assertSource(style, "basemap", "vec_w")
assertSource(style, "labels", "cva_w")
}
@Test fun missingKeyDoesNotIssueUnauthenticatedTileRequests() {
val style = JSONObject(TiandituMapSource.styleJson(true, " "))
assertEquals(0, style.getJSONObject("sources").length())
assertEquals(1, style.getJSONArray("layers").length())
}
@Test fun keyCannotChangeTileCoordinatesOrInjectQueryParameters() {
val key = "key&x=999\"+#"
val style = JSONObject(TiandituMapSource.styleJson(true, key))
val url = style.getJSONObject("sources").getJSONObject("basemap").getJSONArray("tiles").getString(0)
val query = url.substringAfter('?').split('&').associate { part ->
part.substringBefore('=') to part.substringAfter('=')
}
assertEquals(5, query.size)
assertEquals("{x}", query["x"])
assertEquals("{y}", query["y"])
assertEquals("{z}", query["l"])
assertEquals(key, URLDecoder.decode(query.getValue("tk"), "UTF-8"))
}
private fun assertSource(style: JSONObject, id: String, layer: String) {
val source = style.getJSONObject("sources").getJSONObject(id)
assertEquals("raster", source.getString("type"))
assertEquals("xyz", source.getString("scheme"))
assertEquals(256, source.getInt("tileSize"))
assertEquals(1, source.getInt("minzoom"))
assertEquals(18, source.getInt("maxzoom"))
val urls = source.getJSONArray("tiles")
assertEquals(8, urls.length())
for (server in 0..7) {
val url = urls.getString(server)
assertTrue(url.startsWith("https://t$server.tianditu.gov.cn/DataServer?T=$layer&"))
assertTrue(url.contains("&x={x}&y={y}&l={z}&"))
}
}
}
@@ -0,0 +1,69 @@
package com.zklh.dronecontroller.core.mission
import org.junit.Assert.*
import org.junit.Test
import java.nio.file.Files
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
class MissionPreviewReaderTest {
private val xml = """<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:wpml="http://www.dji.com/wpmz/1.0.6"><Document>
<wpml:missionConfig><wpml:finishAction>goHome</wpml:finishAction><wpml:executeRCLostAction>goBack</wpml:executeRCLostAction></wpml:missionConfig>
<Folder><wpml:autoFlightSpeed>5</wpml:autoFlightSpeed><wpml:executeHeightMode>relativeToStartPoint</wpml:executeHeightMode>
<Placemark><Point><coordinates>121.0,31.0</coordinates></Point><wpml:index>0</wpml:index><wpml:executeHeight>100</wpml:executeHeight></Placemark>
<Placemark><Point><coordinates>121.0,31.001</coordinates></Point><wpml:index>1</wpml:index><wpml:executeHeight>120</wpml:executeHeight></Placemark></Folder>
</Document></kml>"""
@Test fun readsWaypointCoordinatesAltitudeAndMetadata() {
val file = Files.createTempFile("mission", ".wpml").toFile()
try {
file.writeText(xml)
val result = MissionPreviewReader.read(file)
assertEquals(2, result.points.size)
assertEquals(31.0, result.points[0].latitude, 0.0)
assertEquals(121.0, result.points[0].longitude, 0.0)
assertEquals(100.0, result.points[0].height!!, 0.0)
assertEquals(111.19, result.distanceMeters, 0.02)
assertEquals(5.0, result.speed!!, 0.0)
assertEquals("goHome", result.finishAction)
} finally { file.delete() }
}
@Test fun prefersExecutableWpmlOverTemplate() {
val file = Files.createTempFile("mission", ".kmz").toFile()
try {
ZipOutputStream(file.outputStream()).use { zip ->
zip.putNextEntry(ZipEntry("wpmz/template.kml")); zip.write(xml.replace("100", "40").toByteArray()); zip.closeEntry()
zip.putNextEntry(ZipEntry("wpmz/waylines.wpml")); zip.write(xml.toByteArray()); zip.closeEntry()
}
assertEquals(100.0, MissionPreviewReader.read(file).points[0].height!!, 0.0)
} finally { file.delete() }
}
@Test fun doesNotConnectSeparateWaylines() {
val file = Files.createTempFile("mission", ".wpml").toFile()
try {
file.writeText(xml.replace("</Document>", "<Folder><Placemark><Point><coordinates>130,40</coordinates></Point></Placemark></Folder></Document>"))
val result = MissionPreviewReader.read(file)
assertEquals(2, result.waylineCount)
assertEquals(2, result.points.size)
assertTrue(result.distanceMeters < 112)
} finally { file.delete() }
}
@Test fun rejectsExternalEntities() {
val file = Files.createTempFile("mission", ".wpml").toFile()
try {
file.writeText("<!DOCTYPE kml [<!ENTITY xxe SYSTEM 'file:///secret'>]>" + xml)
assertThrows(IllegalArgumentException::class.java) { MissionPreviewReader.read(file) }
} finally { file.delete() }
}
@Test fun rejectsInvalidCoordinates() {
val file = Files.createTempFile("mission", ".wpml").toFile()
try {
file.writeText(xml.replace("121.0,31.0", "NaN,NaN").replace("121.0,31.001", "181,91"))
assertThrows(IllegalArgumentException::class.java) { MissionPreviewReader.read(file) }
} finally { file.delete() }
}
}
@@ -0,0 +1,92 @@
package com.zklh.dronecontroller.core.telemetry
import org.junit.Assert.*
import org.junit.Test
class LocationFixTrackerTest {
private fun fix(source: PositionSource, at: Long = 1000L, lat: Double = 39.9, lng: Double = 116.4) =
DevicePositionFix(lat, lng, at, source)
@Test fun unavailable3dChannelCannotEraseValid2dLocation() {
val tracker = LocationFixTracker()
val twoD = fix(PositionSource.AIRCRAFT_2D)
tracker.update(twoD.source, twoD)
tracker.update(PositionSource.AIRCRAFT_3D, fix(PositionSource.AIRCRAFT_3D, lat = 0.0, lng = 0.0))
assertEquals(twoD, tracker.aircraft(2000))
tracker.update(PositionSource.AIRCRAFT_3D, null)
assertEquals(twoD, tracker.aircraft(2000))
}
@Test fun fresh3dCanReplace2dAndFallBackWhen3dBecomesInvalid() {
val tracker = LocationFixTracker()
val twoD = fix(PositionSource.AIRCRAFT_2D)
val threeD = fix(PositionSource.AIRCRAFT_3D, 2000, 40.0, 116.5)
tracker.update(twoD.source, twoD)
tracker.update(threeD.source, threeD)
assertEquals(threeD, tracker.aircraft(2100))
tracker.update(threeD.source, null)
assertEquals(twoD, tracker.aircraft(2100))
}
@Test fun controllerDoesNotDependOnAircraftAndAndroidRefreshIsNotFrozenBySdkSatellites() {
val tracker = LocationFixTracker()
val sdk = fix(PositionSource.RC_SDK).copy(satelliteCount = 30)
val android = fix(PositionSource.ANDROID_GPS, 5000, 39.91, 116.41)
tracker.update(sdk.source, sdk)
tracker.update(android.source, android)
assertNull(tracker.aircraft(5100))
assertEquals(android, tracker.controller(5100))
tracker.update(sdk.source, null)
assertEquals(android, tracker.controller(5100))
}
@Test fun staleOrFutureCoordinatesNeverAppearAsCurrentPositions() {
val tracker = LocationFixTracker()
tracker.update(PositionSource.AIRCRAFT_2D, fix(PositionSource.AIRCRAFT_2D))
tracker.update(PositionSource.ANDROID_GPS, fix(PositionSource.ANDROID_GPS))
assertNull(tracker.aircraft(31001))
assertNull(tracker.controller(31001))
assertNull(tracker.controller(999))
}
@Test fun disconnectedAircraftIsClearedWithoutLosingControllerFix() {
val tracker = LocationFixTracker()
val rc = fix(PositionSource.RC_SDK)
tracker.update(rc.source, rc)
tracker.update(PositionSource.AIRCRAFT_2D, fix(PositionSource.AIRCRAFT_2D))
tracker.clearAircraft()
assertNull(tracker.aircraft(1000))
assertEquals(rc, tracker.controller(1000))
tracker.clear()
assertNull(tracker.controller(1000))
}
@Test fun oldCachedAndroidLocationCannotReplaceNewPosition() {
val tracker = LocationFixTracker()
val current = fix(PositionSource.ANDROID_GPS, 2000)
tracker.update(current.source, current)
tracker.update(current.source, fix(current.source, 1000, 1.0, 1.0))
assertEquals(current, tracker.controller(2100))
}
@Test fun freshPreciseGpsIsPreferredOverCoarseNetworkUntilItExpires() {
val tracker = LocationFixTracker()
val gps = fix(PositionSource.ANDROID_GPS, 1000).copy(accuracy = 5.0)
val coarse = fix(PositionSource.ANDROID_NETWORK, 10000, 40.0, 116.5).copy(accuracy = 2000.0)
tracker.update(gps.source, gps)
tracker.update(coarse.source, coarse)
assertEquals(gps, tracker.controller(11000))
assertEquals(coarse, tracker.controller(31001))
}
@Test fun rejectsNonfiniteCoordinatesAndOriginButAllowsEquatorAndPrimeMeridian() {
assertFalse(LocationFixTracker.valid(Double.NaN, 20.0))
assertFalse(LocationFixTracker.valid(20.0, Double.POSITIVE_INFINITY))
assertFalse(LocationFixTracker.valid(91.0, 20.0))
assertFalse(LocationFixTracker.valid(20.0, 181.0))
assertFalse(LocationFixTracker.valid(0.0, 0.0))
assertFalse(LocationFixTracker.valid(null, 20.0))
assertTrue(LocationFixTracker.valid(0.0, 20.0))
assertTrue(LocationFixTracker.valid(20.0, 0.0))
}
}
@@ -0,0 +1,101 @@
[
{
"id": 9,
"name": "葫芦岛路网图",
"url": "https://uav.zklhjs.com/map/Google/xingcheng-network-cn/{z}/{x}/{y}.png",
"chinaCrs": "GCJ02",
"minZoom": 1,
"maxZoom": 17,
"opacity": 1.0,
"status": 0,
"configJson": " {\n \"id\": 2006,\n \"name\": \"葫芦岛中文路网标注\",\n \"type\": \"xyz\",\n \"url\": \"https://uav.zklhjs.com/map/Google/xingcheng-network-cn/{z}/{x}/{y}.png\",\n \"chinaCRS\": \"GCJ02\",\n \"minimumLevel\": 1,\n \"maximumLevel\": 17,\n \"rectangle\": {\n \"xmin\": 120.03,\n \"xmax\": 121.52,\n \"ymin\": 40.16,\n \"ymax\": 41.12\n },\n \"opacity\": 1,\n \"zIndex\": 1001,\n \"show\": true\n }"
},
{
"id": 8,
"name": "葫芦岛卫星影像",
"url": "https://uav.zklhjs.com/map/Google/xingcheng/{z}/{x}/{y}.jpg",
"chinaCrs": "GCJ02",
"minZoom": 1,
"maxZoom": 17,
"opacity": 1.0,
"status": 0,
"configJson": " {\n \"id\": 2005,\n \"name\": \"葫芦岛卫星影像\",\n \"type\": \"xyz\",\n \"url\": \"https://uav.zklhjs.com/map/Google/xingcheng/{z}/{x}/{y}.jpg\",\n \"chinaCRS\": \"GCJ02\",\n \"minimumLevel\": 1,\n \"maximumLevel\": 17,\n \"rectangle\": {\n \"xmin\": 120.03,\n \"xmax\": 121.52,\n \"ymin\": 40.16,\n \"ymax\": 41.12\n },\n \"opacity\": 1,\n \"zIndex\": 1000,\n \"show\": true\n }"
},
{
"id": 7,
"name": "谷歌沈阳离线底图",
"url": "https://uav.zklhjs.com/map/Google/shenyang/{z}/{x}/{y}.jpg",
"chinaCrs": "GCJ02",
"minZoom": 1,
"maxZoom": 17,
"opacity": 1.0,
"status": 0,
"configJson": " {\n \"id\": 2004,\n \"name\": \"谷歌沈阳离线底图\",\n \"type\": \"xyz\",\n \"url\": \"https://uav.zklhjs.com/map/Google/shenyang/{z}/{x}/{y}.jpg\",\n \"chinaCRS\": \"GCJ02\",\n \"minimumLevel\": 1,\n \"maximumLevel\": 17,\n \"rectangle\": {\n \"xmin\": 122.419167,\n \"xmax\": 123.806667,\n \"ymin\": 41.1975,\n \"ymax\": 43.036944\n },\n \"opacity\": 1,\n \"zIndex\": 1000,\n \"show\": true\n }"
},
{
"id": 6,
"name": "谷歌北京地图",
"url": "https://uav.zklhjs.com/map/Google/beijing/{z}/{x}/{y}.png",
"chinaCrs": "GCJ02",
"minZoom": 1,
"maxZoom": 17,
"opacity": 1.0,
"status": 0,
"configJson": "{\n \"id\": 2000,\n \"name\": \"谷歌北京地图\",\n \"type\": \"xyz\",\n \"url\": \"https://uav.zklhjs.com/map/Google/beijing/{z}/{x}/{y}.png\",\n \"chinaCRS\": \"GCJ02\",\n \"minimumLevel\": 1,\n \"maximumLevel\": 17,\n \"rectangle\": {\n \"xmin\": 115.42,\n \"xmax\": 117.52,\n \"ymin\": 39.44,\n \"ymax\": 41.07\n },\n \"opacity\": 1,\n \"zIndex\": 1003,\n \"show\": true\n}"
},
{
"id": 5,
"name": "张家口谷歌路网图",
"url": "https://uav.zklhjs.com/map/Google/zhangjiakou-network-cn/{z}/{x}/{y}.png",
"chinaCrs": "GCJ02",
"minZoom": 1,
"maxZoom": 17,
"opacity": 1.0,
"status": 0,
"configJson": "{\n \"id\": 3002,\n \"name\": \"谷歌张家口路网标注\",\n \"type\": \"xyz\",\n \"url\": \"https://uav.zklhjs.com/map/Google/zhangjiakou-network-cn/{z}/{x}/{y}.png\",\n \"chinaCRS\": \"GCJ02\",\n \"minimumLevel\": 1,\n \"maximumLevel\": 17,\n \"rectangle\": {\n \"xmin\": 113.819304,\n \"xmax\": 116.465845,\n \"ymin\": 39.555872,\n \"ymax\": 42.149634\n },\n \"opacity\": 1,\n \"zIndex\": 1001,\n \"show\": true\n }"
},
{
"id": 4,
"name": "张家口谷歌影像",
"url": "https://uav.zklhjs.com/map/Google/zhangjiakou/{z}/{x}/{y}.jpg",
"chinaCrs": "GCJ02",
"minZoom": 1,
"maxZoom": 17,
"opacity": 1.0,
"status": 0,
"configJson": "{\n \"id\": 3001,\n \"name\": \"谷歌张家口卫星影像\",\n \"type\": \"xyz\",\n \"url\": \"https://uav.zklhjs.com/map/Google/zhangjiakou/{z}/{x}/{y}.jpg\",\n \"chinaCRS\": \"GCJ02\",\n \"minimumLevel\": 1,\n \"maximumLevel\": 17,\n \"rectangle\": {\n \"xmin\": 113.819304,\n \"xmax\": 116.465845,\n \"ymin\": 39.555872,\n \"ymax\": 42.149634\n },\n \"opacity\": 1,\n \"zIndex\": 1000,\n \"show\": true\n }"
},
{
"id": 3,
"name": "谷歌南京路网标注",
"url": "https://uav.zklhjs.com/map/Google/nanjing-network-cn/{z}/{x}/{y}.png",
"chinaCrs": "GCJ02",
"minZoom": 1,
"maxZoom": 18,
"opacity": 1.0,
"status": 0,
"configJson": "{\n \"id\": 2002,\n \"name\": \"谷歌南京路网标注\",\n \"type\": \"xyz\",\n \"url\": \"https://uav.zklhjs.com/map/Google/nanjing-network-cn/{z}/{x}/{y}.png\",\n \"chinaCRS\": \"GCJ02\",\n \"minimumLevel\": 1,\n \"maximumLevel\": 18,\n \"rectangle\": {\n \"xmin\": 118.358459,\n \"xmax\": 119.242859,\n \"ymin\": 31.226894,\n \"ymax\": 32.611616\n },\n \"opacity\": 1,\n \"zIndex\": 1001,\n \"show\": true\n }"
},
{
"id": 2,
"name": "谷歌南京地图",
"url": "https://uav.zklhjs.com/map/Google/nanjing/{z}/{x}/{y}.jpg",
"chinaCrs": "GCJ02",
"minZoom": 1,
"maxZoom": 18,
"opacity": 1.0,
"status": 0,
"configJson": " {\n \"id\": 2001,\n \"name\": \"谷歌南京地图\",\n \"type\": \"xyz\",\n \"url\": \"https://uav.zklhjs.com/map/Google/nanjing/{z}/{x}/{y}.jpg\",\n \"chinaCRS\": \"GCJ02\",\n \"minimumLevel\": 1,\n \"maximumLevel\": 18,\n \"rectangle\": {\n \"xmin\": 118.358459,\n \"xmax\": 119.242859,\n \"ymin\": 31.226894,\n \"ymax\": 32.611616\n },\n \"opacity\": 1,\n \"zIndex\": 1000,\n \"show\": true\n },"
},
{
"id": 1,
"name": "谷歌全球离线底图",
"url": "https://uav.zklhjs.com/map/Google/quanqiu/{z}/{x}/{y}.jpg",
"chinaCrs": "GCJ02",
"minZoom": 0,
"maxZoom": 8,
"opacity": 1.0,
"status": 0,
"configJson": "{\n \"id\": 2003,\n \"type\": \"xyz\",\n \"model_type\": 2,\n \"chinaCRS\": \"GCJ02\",\n \"minimumLevel\": 0,\n \"maximumLevel\": 8,\n \"rectangle\": {\n \"xmin\": -180,\n \"xmax\": 180,\n \"ymin\": -85.05112878,\n \"ymax\": 85.05112878\n },\n \"opacity\": 1,\n \"zIndex\": 900,\n \"show\": true\n}"
}
]