diff --git a/dependencies.gradle b/dependencies.gradle index 5e3eb1c..01a561d 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -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使用 diff --git a/deployment.properties b/deployment.properties index 318bb62..31b1f4f 100644 --- a/deployment.properties +++ b/deployment.properties @@ -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 保留服务端返回地址的协议和端口。 @@ -24,4 +24,4 @@ RTMP_DEFAULT_APP=live # 打包命令 # .\gradlew.bat :sample:assembleDebug --no-daemon --console=plain -# 安装包目录: D:\Java\Project\zklh\drone-controller-v5\sample\build\outputs\apk\debug\ \ No newline at end of file +# 安装包目录: D:\Java\Project\zklh\drone-controller-v5\sample\build\outputs\apk\debug\ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 3b90a76..5d453cc 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/sample/build.gradle b/sample/build.gradle index ee7326f..e725b26 100644 --- a/sample/build.gradle +++ b/sample/build.gradle @@ -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 diff --git a/sample/map-proguard-rules.pro b/sample/map-proguard-rules.pro new file mode 100644 index 0000000..ca9c5c9 --- /dev/null +++ b/sample/map-proguard-rules.pro @@ -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.** diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/cloud/CloudLoginClient.kt b/sample/src/main/java/com/zklh/dronecontroller/core/cloud/CloudLoginClient.kt index 4cea4e7..932dadd 100644 --- a/sample/src/main/java/com/zklh/dronecontroller/core/cloud/CloudLoginClient.kt +++ b/sample/src/main/java/com/zklh/dronecontroller/core/cloud/CloudLoginClient.kt @@ -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) || diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/cloud/PlatformHosts.kt b/sample/src/main/java/com/zklh/dronecontroller/core/cloud/PlatformHosts.kt new file mode 100644 index 0000000..582f35c --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/cloud/PlatformHosts.kt @@ -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" + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/livestream/LiveStreamingService.kt b/sample/src/main/java/com/zklh/dronecontroller/core/livestream/LiveStreamingService.kt index 90aef6f..fa6df4c 100644 --- a/sample/src/main/java/com/zklh/dronecontroller/core/livestream/LiveStreamingService.kt +++ b/sample/src/main/java/com/zklh/dronecontroller/core/livestream/LiveStreamingService.kt @@ -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", diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/map/MapConfiguration.kt b/sample/src/main/java/com/zklh/dronecontroller/core/map/MapConfiguration.kt new file mode 100644 index 0000000..cfcf513 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/map/MapConfiguration.kt @@ -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 = 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 }) } + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/map/MapConfigurationStore.kt b/sample/src/main/java/com/zklh/dronecontroller/core/map/MapConfigurationStore.kt new file mode 100644 index 0000000..cc46e18 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/map/MapConfigurationStore.kt @@ -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 } + } + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/map/MapCoordinates.kt b/sample/src/main/java/com/zklh/dronecontroller/core/map/MapCoordinates.kt new file mode 100644 index 0000000..555da15 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/map/MapCoordinates.kt @@ -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) + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/map/MapLivePositions.kt b/sample/src/main/java/com/zklh/dronecontroller/core/map/MapLivePositions.kt new file mode 100644 index 0000000..bfd38ee --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/map/MapLivePositions.kt @@ -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 = + (mission?.points.orEmpty().map { MapCoordinates.display(it.latitude, it.longitude, coordinates) } + + listOfNotNull(aircraft, remoteController)).distinct() +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapCache.kt b/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapCache.kt new file mode 100644 index 0000000..93607de --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapCache.kt @@ -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 { + 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 + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapClient.kt b/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapClient.kt new file mode 100644 index 0000000..5f77f66 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapClient.kt @@ -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 = 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() + var page = 1 + while (true) { + val url = "$root/map-layer/page?pageNo=$page&pageSize=20¤t=$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() } + } + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapRepository.kt b/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapRepository.kt new file mode 100644 index 0000000..ec77a0c --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapRepository.kt @@ -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 } + } + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapSource.kt b/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapSource.kt new file mode 100644 index 0000000..9294788 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/map/PlatformMapSource.kt @@ -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 = emptyList(), + val issues: List = 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() + val layers = mutableListOf() + 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 { 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("&", "&")) + 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() + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/map/PrivateMapSource.kt b/sample/src/main/java/com/zklh/dronecontroller/core/map/PrivateMapSource.kt new file mode 100644 index 0000000..f8602e8 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/map/PrivateMapSource.kt @@ -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() } + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/map/TiandituMapSource.kt b/sample/src/main/java/com/zklh/dronecontroller/core/map/TiandituMapSource.kt new file mode 100644 index 0000000..7e71c32 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/map/TiandituMapSource.kt @@ -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", "天地图")) + 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() + } + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/mission/MissionPreviewReader.kt b/sample/src/main/java/com/zklh/dronecontroller/core/mission/MissionPreviewReader.kt new file mode 100644 index 0000000..35e82d6 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/mission/MissionPreviewReader.kt @@ -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, 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(" + 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))) + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/telemetry/DeviceLocationMonitor.kt b/sample/src/main/java/com/zklh/dronecontroller/core/telemetry/DeviceLocationMonitor.kt new file mode 100644 index 0000000..4a86107 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/telemetry/DeviceLocationMonitor.kt @@ -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() + private val inFlight = mutableMapOf() + 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 listen(name: String, key: DJIKey, 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 read(name: String, key: DJIKey, 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 { + 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)) + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/telemetry/LocationFixTracker.kt b/sample/src/main/java/com/zklh/dronecontroller/core/telemetry/LocationFixTracker.kt new file mode 100644 index 0000000..5a13bd1 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/core/telemetry/LocationFixTracker.kt @@ -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() + + @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 { + // 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 { 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) + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/core/telemetry/TelemetryRepository.kt b/sample/src/main/java/com/zklh/dronecontroller/core/telemetry/TelemetryRepository.kt index 482f7b7..6338373 100644 --- a/sample/src/main/java/com/zklh/dronecontroller/core/telemetry/TelemetryRepository.kt +++ b/sample/src/main/java/com/zklh/dronecontroller/core/telemetry/TelemetryRepository.kt @@ -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 = _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( diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/DroneControllerScreen.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/DroneControllerScreen.kt index c28f241..a9d9911 100644 --- a/sample/src/main/java/com/zklh/dronecontroller/ui/DroneControllerScreen.kt +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/DroneControllerScreen.kt @@ -2,32 +2,20 @@ package com.zklh.dronecontroller.ui import dji.sampleV5.aircraft.BuildConfig -import android.annotation.SuppressLint import android.content.Context import android.graphics.Paint -import android.graphics.Typeface import android.util.Log import android.webkit.CookieManager -import android.webkit.JavascriptInterface -import android.webkit.ConsoleMessage -import android.webkit.WebResourceError -import android.webkit.WebResourceRequest -import android.webkit.WebResourceResponse -import android.webkit.WebChromeClient -import android.webkit.WebSettings import android.webkit.WebStorage -import android.webkit.WebView -import android.webkit.WebViewClient import android.widget.Toast +import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Canvas -import androidx.compose.foundation.ExperimentalFoundationApi import android.view.SurfaceHolder import android.view.SurfaceView import androidx.compose.foundation.background -import androidx.compose.foundation.basicMarquee import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectDragGestures @@ -36,106 +24,58 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.aspectRatio -import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width -import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape -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.automirrored.filled.KeyboardArrowRight -import androidx.compose.material.icons.filled.AccountTree import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.BatteryFull import androidx.compose.material.icons.filled.CameraAlt -import androidx.compose.material.icons.filled.CheckCircle -import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Fullscreen import androidx.compose.material.icons.filled.Cloud -import androidx.compose.material.icons.filled.Delete -import androidx.compose.material.icons.filled.ExpandMore -import androidx.compose.material.icons.filled.FolderOpen import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Image -import androidx.compose.material.icons.filled.Layers -import androidx.compose.material.icons.filled.Lock -import androidx.compose.material.icons.filled.LocationOn import androidx.compose.material.icons.filled.Map -import androidx.compose.material.icons.filled.MoreHoriz +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.filled.Description +import androidx.compose.material.icons.filled.Lightbulb +import androidx.compose.material.icons.filled.Layers +import androidx.compose.material.icons.filled.Panorama import androidx.compose.material.icons.filled.MyLocation -import androidx.compose.material.icons.filled.Navigation -import androidx.compose.material.icons.filled.Pause -import androidx.compose.material.icons.filled.Person -import androidx.compose.material.icons.filled.PlayArrow -import androidx.compose.material.icons.filled.PowerSettingsNew -import androidx.compose.material.icons.filled.Radio -import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Remove -import androidx.compose.material.icons.filled.Route -import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Shield -import androidx.compose.material.icons.filled.Speed -import androidx.compose.material.icons.filled.Stop -import androidx.compose.material.icons.filled.Sync -import androidx.compose.material.icons.filled.UploadFile import androidx.compose.material.icons.filled.Videocam -import androidx.compose.material.icons.filled.Warning -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton -import androidx.compose.material3.LinearProgressIndicator -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Slider import androidx.compose.material3.Surface -import androidx.compose.material3.Switch import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.foundation.layout.requiredSize import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.window.Popup -import androidx.compose.ui.window.PopupProperties -import androidx.compose.ui.unit.IntOffset -import androidx.compose.ui.tooling.preview.Preview -import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.drawIntoCanvas @@ -147,21 +87,20 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.TextStyle -import androidx.compose.ui.text.input.PasswordVisualTransformation -import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView -import androidx.compose.ui.zIndex import com.zklh.dronecontroller.core.cloud.CloudCommandExecutor import com.zklh.dronecontroller.core.cloud.CloudLoginClient import com.zklh.dronecontroller.core.cloud.CloudLoginRequest import com.zklh.dronecontroller.core.cloud.CloudMediaUploadService import com.zklh.dronecontroller.core.cloud.CloudMqttService import com.zklh.dronecontroller.core.cloud.CloudMqttState +import com.zklh.dronecontroller.core.cloud.PlatformHosts +import com.zklh.dronecontroller.core.map.PlatformMapRepository +import com.zklh.dronecontroller.core.map.MapConfigurationStore +import com.zklh.dronecontroller.core.map.MapProvider import com.zklh.dronecontroller.core.flight.FlightControlService import com.zklh.dronecontroller.core.flight.FlyToService import com.zklh.dronecontroller.core.diagnostics.DroneWarningRepository @@ -182,7 +121,6 @@ import com.zklh.dronecontroller.core.safety.SafetyInterlock import com.zklh.dronecontroller.core.simulator.SimulatorService import com.zklh.dronecontroller.core.telemetry.TelemetryRepository import com.zklh.dronecontroller.core.telemetry.TelemetrySnapshot -import com.zklh.dronecontroller.core.telemetry.hasReliableRtkPosition import com.zklh.dronecontroller.core.video.DjiVideoPreviewService import com.zklh.dronecontroller.core.virtualstick.StickPosition import com.zklh.dronecontroller.core.virtualstick.VirtualStickService @@ -190,29 +128,21 @@ import dji.v5.manager.diagnostic.WarningLevel import dji.v5.manager.aircraft.virtualstick.Stick import java.io.File import java.util.Locale -import kotlin.math.PI -import kotlin.math.cos import kotlin.math.roundToInt -import kotlin.math.sin import kotlin.math.sqrt import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -private val PilotOrange = Color(0xFFFF9800) -private val PilotGreen = Color(0xFF00E59B) -private val PilotBlue = Color(0xFF1683F7) -private val PilotBlack = Color(0xFF050505) -private val PilotPanel = Color(0xFFEFF1F3) -private val PilotLine = Color(0xFFE0E3E6) -private val PilotText = Color(0xFF111111) -private val PilotMuted = Color(0xFF73777D) -private val PilotDanger = Color(0xFFFF3344) -private val HudTextShadow = Shadow(color = Color.Black, offset = Offset(1.2f, 1.2f), blurRadius = 1.6f) +private val PilotOrange = PilotDesign.Orange +private val PilotGreen = PilotDesign.Teal +private val PilotBlue = PilotDesign.Blue +private val PilotText = PilotDesign.Ink +private val PilotMuted = PilotDesign.Muted +private val PilotDanger = PilotDesign.Red private const val DefaultVirtualStickSpeedLevel = 1.0 private const val CameraLogTag = "ZklhCamera" -private const val CloudLogTag = "ZklhCloud" private const val FlightControlLogTag = "ZklhFlightControl" private const val DefaultThirdCloudUrl = BuildConfig.CLOUD_BASE_URL private const val DefaultThirdCloudTenantName = "中科联航" @@ -259,13 +189,16 @@ private data class SavedCloudLoginConfig( private fun Context.readSavedCloudLoginConfig(): SavedCloudLoginConfig { val prefs = getSharedPreferences(CloudPrefsName, Context.MODE_PRIVATE) + val migratedUrl = PlatformHosts.migrate(prefs.getString(CloudPrefsUrl, DefaultThirdCloudUrl).orEmpty()).ifBlank { DefaultThirdCloudUrl } + val migratedMqtt = PlatformHosts.migrate(prefs.getString(CloudPrefsMqttAddress, "").orEmpty()) + prefs.edit().putString(CloudPrefsUrl, migratedUrl).putString(CloudPrefsMqttAddress, migratedMqtt).apply() return SavedCloudLoginConfig( - url = prefs.getString(CloudPrefsUrl, DefaultThirdCloudUrl).orEmpty().ifBlank { DefaultThirdCloudUrl }, + url = migratedUrl, tenantName = prefs.getString(CloudPrefsTenantName, DefaultThirdCloudTenantName).orEmpty() .ifBlank { DefaultThirdCloudTenantName }, username = prefs.getString(CloudPrefsUsername, DefaultThirdCloudUsername).orEmpty().ifBlank { DefaultThirdCloudUsername }, password = prefs.getString(CloudPrefsPassword, DefaultThirdCloudPassword).orEmpty().ifBlank { DefaultThirdCloudPassword }, - mqttAddress = prefs.getString(CloudPrefsMqttAddress, "").orEmpty(), + mqttAddress = migratedMqtt, autoConnect = prefs.getBoolean(CloudPrefsAutoConnect, true) ) } @@ -316,10 +249,24 @@ private fun isUsableCoordinate(latitude: Double, longitude: Double): Boolean = @Composable fun DroneControllerScreen() { + PilotDesignViewport { DroneControllerContent() } +} + +@Composable +private fun DroneControllerContent() { val context = LocalContext.current val scope = rememberCoroutineScope() val appContext = context.applicationContext val savedCloudLoginConfig = remember(appContext) { appContext.readSavedCloudLoginConfig() } + val platformMaps = remember(appContext) { + PlatformMapRepository.get(appContext).also { repository -> + repository.configure(CloudLoginRequest(savedCloudLoginConfig.url, savedCloudLoginConfig.tenantName, + savedCloudLoginConfig.username, savedCloudLoginConfig.password)) + } + } + LaunchedEffect(platformMaps) { + if (MapConfigurationStore.get(appContext).configuration.value.provider == MapProvider.DEFAULT) platformMaps.refresh() + } val sdkState by DroneSdkManager.state.collectAsState() val telemetryRepository = remember(context) { TelemetryRepository(context.applicationContext) } val telemetry by telemetryRepository.state.collectAsState() @@ -360,17 +307,17 @@ fun DroneControllerScreen() { val liveState by liveStreaming.state.collectAsState() var page by remember { mutableStateOf(PilotPage.Home) } - var flightMode by remember { mutableStateOf(FlightMode.Map) } + var preflightReturnPage by remember { mutableStateOf(PilotPage.Home) } + BackHandler(enabled = page != PilotPage.Home) { page = when (page) { PilotPage.ThirdPartyCloud -> PilotPage.Cloud; PilotPage.Preflight -> preflightReturnPage; else -> PilotPage.Home } } + var flightMode by remember { mutableStateOf(FlightMode.Camera) } var commandMessage by remember { mutableStateOf("待机,等待设备连接") } var flightActionStatus by remember { mutableStateOf("") } var missionPath by remember { mutableStateOf("") } + var missionRevision by remember { mutableStateOf(0) } var missionId by remember { mutableStateOf("") } var uploadUpdate by remember { mutableStateOf(MissionUploadUpdate()) } var showMissionPanel by remember { mutableStateOf(false) } var stickPower by remember { mutableStateOf(Stick.MAX_STICK_POSITION_ABS) } - var returnAltitude by remember { mutableStateOf(100) } - var maxAltitude by remember { mutableStateOf(500) } - var farLimitEnabled by remember { mutableStateOf(false) } var thirdCloudUrl by remember { mutableStateOf(savedCloudLoginConfig.url) } var thirdCloudTenantName by remember { mutableStateOf(savedCloudLoginConfig.tenantName) } var thirdCloudUsername by remember { mutableStateOf(savedCloudLoginConfig.username) } @@ -381,6 +328,7 @@ fun DroneControllerScreen() { var thirdCloudStatusMessage by remember { mutableStateOf("") } var thirdCloudStatusIsError by remember { mutableStateOf(false) } var thirdCloudReloadTick by remember { mutableStateOf(0) } + var cloudLoginBusy by remember { mutableStateOf(false) } var thirdCloudAutoLoginStarted by remember { mutableStateOf(false) } var cameraRecording by remember { mutableStateOf(false) } var laserFillLightEnabled by remember { mutableStateOf(false) } @@ -401,6 +349,8 @@ fun DroneControllerScreen() { withContext(Dispatchers.Main) { result.onSuccess { file -> missionPath = file.absolutePath + missionRevision++ + uploadUpdate = MissionUploadUpdate() missionId = waypointMission.missionIdFromPath(file.absolutePath) commandMessage = "航线文件已载入" showMissionPanel = true @@ -414,7 +364,9 @@ fun DroneControllerScreen() { } DisposableEffect(Unit) { + telemetryRepository.startPositioning() onDispose { + telemetryRepository.stopPositioning() telemetryRepository.stop() virtualStick.clear() simulator.clear() @@ -425,6 +377,7 @@ fun DroneControllerScreen() { } DisposableEffect(sdkState.isRegistered, sdkState.productConnected) { + telemetryRepository.updatePositioningConnection(sdkState.isRegistered, sdkState.productConnected) if (sdkState.isRegistered && sdkState.productConnected) { telemetryRepository.start() } else { @@ -453,8 +406,8 @@ fun DroneControllerScreen() { cloudMqttService.updateDeviceState(sdkState) } - LaunchedEffect(cloudState.connected, sdkState.productConnected) { - if (cloudState.connected && sdkState.productConnected) { + LaunchedEffect(sdkState.isRegistered, sdkState.productConnected) { + if (sdkState.isRegistered && sdkState.productConnected) { while (true) { telemetryRepository.refreshForCloud() delay(5000) @@ -595,8 +548,10 @@ fun DroneControllerScreen() { toast(commandMessage) pickMission() } else { + val uploadRevision = missionRevision waypointMission.uploadKmzFile(missionPath) { update -> scope.launch { + if (uploadRevision != missionRevision) return@launch uploadUpdate = update commandMessage = update.error ?: update.message toast(commandMessage) @@ -678,6 +633,7 @@ fun DroneControllerScreen() { withContext(Dispatchers.Main) { result.onSuccess { file -> missionPath = file.absolutePath + missionRevision++ missionId = waypointMission.missionIdFromPath(file.absolutePath) uploadUpdate = MissionUploadUpdate() showMissionPanel = true @@ -815,38 +771,44 @@ fun DroneControllerScreen() { } } fun loginThirdCloud(showToast: Boolean = true) { + if (cloudLoginBusy || cloudState.connecting) return + cloudLoginBusy = true scope.launch { - val request = CloudLoginRequest( - baseUrl = thirdCloudUrl, - tenantName = thirdCloudTenantName, - username = thirdCloudUsername, - password = thirdCloudPassword, - flag = 2, - mqttAddressOverride = thirdCloudMqttAddress - ) - commandMessage = "正在登录第三方云" - thirdCloudStatusMessage = commandMessage - thirdCloudStatusIsError = false - if (showToast) toast(commandMessage) - cloudLoginClient.login(request) - .onSuccess { session -> - thirdCloudUrl = session.baseUrl - if (thirdCloudMqttAddress.isBlank()) { - thirdCloudMqttAddress = session.mqttAddress + try { + val request = CloudLoginRequest( + baseUrl = thirdCloudUrl, + tenantName = thirdCloudTenantName, + username = thirdCloudUsername, + password = thirdCloudPassword, + flag = 2, + mqttAddressOverride = thirdCloudMqttAddress + ) + commandMessage = "正在登录第三方云" + thirdCloudStatusMessage = commandMessage + thirdCloudStatusIsError = false + if (showToast) toast(commandMessage) + cloudLoginClient.login(request) + .onSuccess { session -> + platformMaps.configure(request) + scope.launch { platformMaps.refresh(force = true) } + thirdCloudUrl = session.baseUrl + if (thirdCloudMqttAddress.isBlank()) { + thirdCloudMqttAddress = session.mqttAddress + } + appContext.saveCloudLoginConfig(request.copy(baseUrl = session.baseUrl), session.mqttAddress) + commandMessage = "第三方云登录成功,正在连接 MQTT" + thirdCloudStatusMessage = commandMessage + thirdCloudStatusIsError = false + if (showToast) toast(commandMessage) + cloudMqttService.connect(session, cloudCommandExecutor) } - appContext.saveCloudLoginConfig(request.copy(baseUrl = session.baseUrl), session.mqttAddress) - commandMessage = "第三方云登录成功,正在连接 MQTT" - thirdCloudStatusMessage = commandMessage - thirdCloudStatusIsError = false - if (showToast) toast(commandMessage) - cloudMqttService.connect(session, cloudCommandExecutor) - } - .onFailure { error -> - commandMessage = "第三方云登录失败:${error.message ?: error.javaClass.simpleName}" - thirdCloudStatusMessage = commandMessage - thirdCloudStatusIsError = true - if (showToast) toast(commandMessage) - } + .onFailure { error -> + commandMessage = "第三方云登录失败:${error.message ?: error.javaClass.simpleName}" + thirdCloudStatusMessage = commandMessage + thirdCloudStatusIsError = true + if (showToast) toast(commandMessage) + } + } finally { cloudLoginBusy = false } } } @@ -872,16 +834,18 @@ fun DroneControllerScreen() { cloudConnected = thirdCloudConnected || cloudState.connected, cloudTenantName = thirdCloudTenantName, cloudUsername = thirdCloudUsername, - onOpenCloud = { page = PilotPage.ThirdPartyCloud }, - onOpenPreflight = { page = PilotPage.Preflight }, + warningState = warningState, + onOpenCloud = { page = PilotPage.Cloud }, + onOpenPreflight = { preflightReturnPage = page; page = PilotPage.Preflight }, onOpenMission = { page = PilotPage.Flight flightMode = FlightMode.Map showMissionPanel = true }, onEnterFlight = { - page = PilotPage.Flight + showMissionPanel = false flightMode = FlightMode.Camera + page = PilotPage.Flight }, onRetryConnect = { if (sdkState.productConnected) { @@ -894,11 +858,14 @@ fun DroneControllerScreen() { } } ) - PilotPage.Cloud -> CloudScreen( + PilotPage.Cloud -> PilotCloudScreen( + sdk = sdkState, cloud = cloudState, live = liveState, + tenant = thirdCloudTenantName, username = thirdCloudUsername, onBack = { page = PilotPage.Home }, - onOpenThirdParty = { page = PilotPage.ThirdPartyCloud }, - onToast = ::toast + onLogin = { page = PilotPage.ThirdPartyCloud }, + onLive = toggleLiveStream, onToast = ::toast ) + PilotPage.ThirdPartyCloud -> ThirdPartyCloudScreen( sdkState = sdkState, url = thirdCloudUrl, @@ -911,7 +878,7 @@ fun DroneControllerScreen() { onPasswordChange = { thirdCloudPassword = it }, mqttAddress = thirdCloudMqttAddress, onMqttAddressChange = { thirdCloudMqttAddress = it }, - cloudState = cloudState, + cloudState = cloudState.copy(connecting = cloudState.connecting || cloudLoginBusy), connected = thirdCloudConnected || cloudState.connected, loginVisible = thirdCloudLoginVisible, reloadTick = thirdCloudReloadTick, @@ -919,7 +886,7 @@ fun DroneControllerScreen() { statusIsError = thirdCloudStatusIsError, onBack = { thirdCloudLoginVisible = false - page = PilotPage.Home + page = PilotPage.Cloud }, onConnect = { thirdCloudLoginVisible = true @@ -948,6 +915,7 @@ fun DroneControllerScreen() { }, onLogout = { cloudMqttService.disconnect() + platformMaps.clearCredentials() appContext.disableCloudAutoConnect() CookieManager.getInstance().removeAllCookies(null) CookieManager.getInstance().flush() @@ -959,18 +927,16 @@ fun DroneControllerScreen() { toast("第三方云已断开") } ) - PilotPage.Preflight -> PreflightScreen( - sdkState = sdkState, - telemetry = telemetry, - returnAltitude = returnAltitude, - maxAltitude = maxAltitude, - farLimitEnabled = farLimitEnabled, - onClose = { page = PilotPage.Flight }, - onReturnAltitudeChange = { returnAltitude = it.coerceIn(20, 1500) }, - onMaxAltitudeChange = { maxAltitude = it.coerceIn(20, 1500) }, - onFarLimitChange = { farLimitEnabled = it }, - onToast = ::toast + PilotPage.Preflight -> PilotPreflightScreen( + sdkState = sdkState, telemetry = telemetry, + onClose = { page = preflightReturnPage }, + onEnterFlight = { + showMissionPanel = false + flightMode = FlightMode.Camera + page = PilotPage.Flight + } ) + PilotPage.Flight -> FlightScreen( sdkState = sdkState, telemetry = telemetry, @@ -978,6 +944,7 @@ fun DroneControllerScreen() { alertState = alertState, flightMode = flightMode, missionPath = missionPath, + missionRevision = missionRevision, missionId = missionId, uploadUpdate = uploadUpdate, stickEnabled = stickStatus.enabled, @@ -989,11 +956,11 @@ fun DroneControllerScreen() { laserFillLightEnabled = laserFillLightEnabled, showMissionPanel = showMissionPanel, onBack = { page = PilotPage.Home }, - onOpenPreflight = { page = PilotPage.Preflight }, + onOpenPreflight = { preflightReturnPage = page; page = PilotPage.Preflight }, onToggleFlightMode = { flightMode = if (flightMode == FlightMode.Map) FlightMode.Camera else FlightMode.Map }, - onToggleMissionPanel = { showMissionPanel = !showMissionPanel }, + onCloseMissionPanel = { showMissionPanel = false }, onMissionPathChange = { missionPath = it }, onMissionIdChange = { missionId = it }, onPickMission = pickMission, @@ -1013,6 +980,13 @@ fun DroneControllerScreen() { onSendStick = { position -> virtualStick.sendStickPosition(position) }, + onZoomChange = { ratio -> + scope.launch { + val result = com.zklh.dronecontroller.core.media.CameraControlService(cameraMedia.currentCameraIndex()).setVisibleZoomRatio(ratio) + commandMessage = result.message + if (!result.success) toast(commandMessage) + } + }, onTakePhoto = takePhoto, onToggleRecord = toggleRecord, onToggleLaserFillLight = toggleLaserFillLight, @@ -1022,162 +996,6 @@ fun DroneControllerScreen() { } } -@Composable -private fun ConnectionDiagnosticCard( - sdkState: DroneSdkState, - message: String, - compact: Boolean, - onRetryConnect: () -> Unit -) { - val title = when { - sdkState.productConnected -> "无人机已连接" - sdkState.isRegistered -> "无人机未连接" - sdkState.isInitialized -> "SDK 已初始化,等待注册" - else -> "SDK 初始化中" - } - val activeColor = if (sdkState.productConnected) Color(0xFF039855) else PilotOrange - - Surface( - color = if (sdkState.productConnected) Color(0xFFE7F7EF) else Color(0xFFFFF4E5), - border = BorderStroke(1.dp, activeColor.copy(alpha = 0.45f)), - shape = RoundedCornerShape(8.dp), - modifier = Modifier.fillMaxWidth() - ) { - Column( - modifier = Modifier.padding(if (compact) 8.dp else 10.dp), - verticalArrangement = Arrangement.spacedBy(if (compact) 1.dp else 3.dp) - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - modifier = Modifier.fillMaxWidth() - ) { - Text( - title, - color = if (sdkState.productConnected) Color(0xFF027A48) else PilotOrange, - fontSize = if (compact) 14.sp else 17.sp, - fontWeight = FontWeight.Black - ) - Text( - "重试", - color = Color(0xFF1D4ED8), - fontSize = 12.sp, - fontWeight = FontWeight.Bold, - modifier = Modifier - .clip(RoundedCornerShape(6.dp)) - .clickable(onClick = onRetryConnect) - .padding(horizontal = 8.dp, vertical = 4.dp) - ) - } - DiagnosticLine( - "初始化", - if (sdkState.productConnected) "${sdkInitDisplayText(sdkState)} ${sdkState.initProgress}%" else sdkInitDisplayText(sdkState) - ) - DiagnosticLine("App Key", if (sdkState.isRegistered) "注册成功" else "未注册") - DiagnosticLine("遥控器/SDK", if (sdkState.productLinkConnected) "在线" else "未在线/待检测") - DiagnosticLine("无人机", if (sdkState.productConnected) "已连接" else "未连接") - DiagnosticLine("检测依据", sdkState.aircraftConnectionDetail) - val error = sdkState.registerError ?: message - if (error.isNotBlank() && !sdkState.productConnected) { - Text( - error, - color = Color(0xFF8A5A00), - fontSize = 10.sp, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - } - } - } -} - -@Composable -private fun DiagnosticLine(label: String, value: String) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(18.dp), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text(label, color = PilotMuted, fontSize = 10.sp) - Text( - value, - color = PilotText, - fontSize = 10.sp, - fontWeight = FontWeight.Bold, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.padding(start = 10.dp) - ) - } -} - -@Composable -private fun CloudScreen( - onBack: () -> Unit, - onOpenThirdParty: () -> Unit, - onToast: (String) -> Unit -) { - Column(Modifier.fillMaxSize().background(PilotPanel)) { - SimpleTitleBar("云服务", onBack = onBack) - Row( - modifier = Modifier - .fillMaxSize() - .padding(14.dp), - horizontalArrangement = Arrangement.spacedBy(14.dp) - ) { - CloudLargeCard(onOpenThirdParty, Modifier.weight(1.08f).fillMaxHeight()) - Column(Modifier.weight(0.92f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(14.dp)) { - Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(14.dp)) { - CloudTile("司空2 私有云", Icons.Filled.Cloud, Modifier.weight(1f), onOpenThirdParty) - CloudTile("开放平台", Icons.Filled.Cloud, Modifier.weight(1f)) { onToast("开放平台后续接入") } - } - Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(14.dp)) { - CloudTile("GB28181", Icons.Filled.Radio, Modifier.weight(1f)) { onToast("GB28181 后续接入") } - CloudTile("自定义直播", Icons.Filled.Videocam, Modifier.weight(1f)) { onToast("自定义直播后续接入") } - } - } - } - } -} - -@Composable -private fun CloudLargeCard(onClick: () -> Unit, modifier: Modifier = Modifier) { - Surface(color = Color.White, shape = RoundedCornerShape(8.dp), modifier = modifier.clickable(onClick = onClick)) { - Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { - RoundCloudIcon(Icons.Filled.Cloud, PilotBlue, 104.dp) - Spacer(Modifier.height(24.dp)) - Text("司空 2", fontSize = 31.sp, fontWeight = FontWeight.Black) - Spacer(Modifier.height(54.dp)) - Row(horizontalArrangement = Arrangement.spacedBy(90.dp)) { - Text("功能特性", color = PilotBlue, fontWeight = FontWeight.Bold) - Text("数据隐私说明", color = PilotBlue, fontWeight = FontWeight.Bold) - } - } - } -} - -@Composable -private fun CloudTile(title: String, icon: ImageVector, modifier: Modifier, onClick: () -> Unit) { - Surface(color = Color.White, shape = RoundedCornerShape(8.dp), modifier = modifier.fillMaxHeight().clickable(onClick = onClick)) { - Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { - RoundCloudIcon(icon, Color(0xFF42484C), 72.dp) - Spacer(Modifier.height(18.dp)) - Text(title, fontSize = 21.sp, fontWeight = FontWeight.Black) - } - } -} - -@Composable -private fun RoundCloudIcon(icon: ImageVector, tint: Color, size: Dp) { - Surface(shape = CircleShape, color = Color(0xFFF3F4F5), modifier = Modifier.size(size)) { - Box(contentAlignment = Alignment.Center) { - Icon(icon, null, tint = tint, modifier = Modifier.size(size * 0.46f)) - } - } -} - @Composable private fun ThirdPartyCloudScreen( sdkState: DroneSdkState, @@ -1205,718 +1023,11 @@ private fun ThirdPartyCloudScreen( onRefresh: () -> Unit, onLogout: () -> Unit ) { - Column(Modifier.fillMaxSize().background(Color(0xFF858992))) { - ThirdPartyCloudTitleBar( - onBack = onBack, - onRefresh = onRefresh, - onLogout = onLogout - ) - Box( - modifier = Modifier.fillMaxSize(), - contentAlignment = Alignment.Center - ) { - ThirdPartyCloudLoginCard( - tenantName = tenantName, - onTenantNameChange = onTenantNameChange, - username = username, - onUsernameChange = onUsernameChange, - password = password, - onPasswordChange = onPasswordChange, - cloudState = cloudState, - statusMessage = statusMessage, - statusIsError = statusIsError, - onLogin = onLogin - ) - } - } -} - -@Composable -private fun ThirdPartyCloudTitleBar( - onBack: () -> Unit, - onRefresh: () -> Unit, - onLogout: () -> Unit -) { - Box( - modifier = Modifier - .fillMaxWidth() - .height(48.dp) - .background(Color.White) - .padding(horizontal = 8.dp) - ) { - IconButton( - onClick = onBack, - modifier = Modifier - .align(Alignment.CenterStart) - .size(32.dp) - ) { - Icon( - Icons.AutoMirrored.Filled.ArrowBack, - contentDescription = null, - tint = Color(0xFF111111), - modifier = Modifier.size(20.dp) - ) - } - Text( - "Cloud Api Platform", - modifier = Modifier.align(Alignment.Center), - color = Color(0xFF101010), - fontSize = 16.sp, - fontWeight = FontWeight.Black, - textAlign = TextAlign.Center - ) - Row( - modifier = Modifier.align(Alignment.CenterEnd), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(14.dp) - ) { - IconButton(onClick = onRefresh, modifier = Modifier.size(38.dp)) { - Icon( - Icons.Filled.Refresh, - contentDescription = null, - tint = Color(0xFF252525), - modifier = Modifier.size(28.dp) - ) - } - Button( - onClick = onLogout, - colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF3E3E3E)), - shape = RoundedCornerShape(4.dp), - contentPadding = PaddingValues(0.dp), - modifier = Modifier - .defaultMinSize(minWidth = 1.dp, minHeight = 1.dp) - .height(31.dp) - .width(48.dp) - ) { - Text("注销", fontSize = 17.sp, fontWeight = FontWeight.Black) - } - } - } -} - -@Composable -private fun ThirdPartyCloudLoginCard( - tenantName: String, - onTenantNameChange: (String) -> Unit, - username: String, - onUsernameChange: (String) -> Unit, - password: String, - onPasswordChange: (String) -> Unit, - cloudState: CloudMqttState, - statusMessage: String, - statusIsError: Boolean, - onLogin: () -> Unit -) { - Surface( - color = Color(0xFFE0E2E6), - shape = RoundedCornerShape(30.dp), - shadowElevation = 12.dp, - modifier = Modifier - .fillMaxWidth(0.552f) - .widthIn(max = 430.dp) - .height(345.dp) - ) { - Column( - modifier = Modifier - .fillMaxSize() - .padding(horizontal = 21.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.Top - ) { - Spacer(Modifier.height(35.dp)) - Text("登录", color = Color.Black, fontSize = 20.sp, fontWeight = FontWeight.Normal) - Spacer(Modifier.height(19.dp)) - ThirdPartyLoginInput( - value = tenantName, - onValueChange = onTenantNameChange, - placeholder = "租户名称", - icon = Icons.Filled.AccountTree - ) - Spacer(Modifier.height(25.dp)) - ThirdPartyLoginInput( - value = username, - onValueChange = onUsernameChange, - placeholder = "账号", - icon = Icons.Filled.Person - ) - Spacer(Modifier.height(25.dp)) - ThirdPartyLoginInput( - value = password, - onValueChange = onPasswordChange, - placeholder = "密码", - icon = Icons.Filled.Lock, - password = true - ) - Spacer(Modifier.height(25.dp)) - Button( - onClick = onLogin, - enabled = !cloudState.connecting, - colors = ButtonDefaults.buttonColors( - containerColor = Color.Black, - disabledContainerColor = Color(0xFF222222) - ), - shape = RoundedCornerShape(16.dp), - contentPadding = PaddingValues(0.dp), - modifier = Modifier - .defaultMinSize(minWidth = 1.dp, minHeight = 1.dp) - .width(80.dp) - .height(32.dp) - ) { - Text( - when { - cloudState.connecting -> "登录中" - cloudState.connected -> "已登录" - else -> "登录" - }, - color = Color.White, - fontSize = 17.sp, - fontWeight = FontWeight.Normal - ) - } - Spacer(Modifier.height(10.dp)) - Box( - modifier = Modifier - .fillMaxWidth() - .height(28.dp), - contentAlignment = Alignment.Center - ) { - val message = statusMessage.ifBlank { - cloudState.lastError ?: when { - cloudState.connected -> "MQTT 在线,正在上报无人机数据" - cloudState.connecting -> "正在连接第三方云" - cloudState.message != "未连接" -> cloudState.message - else -> "" - } - } - val isError = statusIsError || (statusMessage.isBlank() && cloudState.lastError != null) - if (message.isNotBlank()) { - Text( - message, - color = if (isError) PilotDanger else Color(0xFF555B66), - fontSize = 9.sp, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - textAlign = TextAlign.Center - ) - } - } - } - } -} - -@Composable -private fun ThirdPartyLoginInput( - value: String, - onValueChange: (String) -> Unit, - placeholder: String, - icon: ImageVector, - password: Boolean = false -) { - Surface( - color = Color.White, - shape = RoundedCornerShape(20.dp), - modifier = Modifier - .fillMaxWidth() - .height(39.dp) - ) { - Row( - modifier = Modifier - .fillMaxSize() - .padding(horizontal = 12.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Icon(icon, contentDescription = null, tint = Color(0xFFBDBFC3), modifier = Modifier.size(17.dp)) - Spacer(Modifier.width(16.dp)) - BasicTextField( - value = value, - onValueChange = onValueChange, - singleLine = true, - textStyle = TextStyle(color = Color(0xFF262626), fontSize = 16.sp), - visualTransformation = if (password) PasswordVisualTransformation() else androidx.compose.ui.text.input.VisualTransformation.None, - modifier = Modifier.weight(1f), - decorationBox = { innerTextField -> - Box(contentAlignment = Alignment.CenterStart) { - if (value.isBlank()) { - Text(placeholder, color = Color(0xFFB8B8B8), fontSize = 16.sp) - } - innerTextField() - } - } - ) - } - } -} - -@Composable -private fun ThirdPartyUrlContent( - url: String, - onUrlChange: (String) -> Unit, - onClearHistory: () -> Unit -) { - Column(Modifier.fillMaxSize().background(PilotPanel)) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(92.dp) - .background(Color.White) - .padding(horizontal = 24.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Text("URL 链接", fontSize = 23.sp, color = PilotText, modifier = Modifier.width(150.dp)) - BasicTextField( - value = url, - onValueChange = onUrlChange, - singleLine = true, - textStyle = TextStyle( - color = Color(0xFF777777), - fontSize = 24.sp, - textAlign = TextAlign.End - ), - modifier = Modifier.weight(1f) - ) - } - HorizontalDivider(color = PilotLine, thickness = 1.dp) - Box( - modifier = Modifier - .fillMaxSize() - .padding(24.dp) - ) { - Column { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - Text("历史记录", fontSize = 23.sp, color = Color(0xFF777777)) - Spacer(Modifier.weight(1f)) - IconButton(onClick = onClearHistory) { - Icon(Icons.Filled.Delete, null, tint = Color.White, modifier = Modifier.size(30.dp)) - } - } - Spacer(Modifier.height(20.dp)) - Surface( - color = Color.White, - shape = RoundedCornerShape(4.dp), - modifier = Modifier - .fillMaxWidth() - .height(58.dp) - ) { - Box(contentAlignment = Alignment.CenterStart, modifier = Modifier.padding(horizontal = 20.dp)) { - Text(url, fontSize = 20.sp, color = Color(0xFF555555)) - } - } - } - } - } -} - -@SuppressLint("SetJavaScriptEnabled") -@Composable -private fun ThirdPartyLoginWebContent( - sdkState: DroneSdkState, - url: String, - reloadTick: Int, - onConnected: () -> Unit -) { - val context = LocalContext.current - val openUrl = remember(url) { normalizeCloudUrl(url) } - val currentOnConnected by rememberUpdatedState(onConnected) - val bridge = remember( - openUrl, - sdkState.remoteControllerSerialNumber, - sdkState.aircraftSerialNumber, - sdkState.productConnected - ) { - CloudApiWebBridge( - host = cloudHostFromUrl(openUrl), - remoteControllerSn = sdkState.remoteControllerSerialNumber.ifBlank { "--" }, - aircraftSn = sdkState.aircraftSerialNumber.ifBlank { "--" }, - connected = sdkState.productConnected - ) - } - val webView = remember(openUrl, bridge) { - WebView.setWebContentsDebuggingEnabled(true) - WebView(context).apply { - settings.javaScriptEnabled = true - settings.domStorageEnabled = true - settings.loadWithOverviewMode = false - settings.useWideViewPort = true - settings.textZoom = 100 - settings.cacheMode = WebSettings.LOAD_NO_CACHE - settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW - settings.builtInZoomControls = false - settings.displayZoomControls = false - CookieManager.getInstance().setAcceptCookie(true) - CookieManager.getInstance().setAcceptThirdPartyCookies(this, true) - webChromeClient = object : WebChromeClient() { - override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean { - Log.d( - CloudLogTag, - "${consoleMessage.messageLevel()}: ${consoleMessage.message()} (${consoleMessage.sourceId()}:${consoleMessage.lineNumber()})" - ) - return true - } - } - webViewClient = object : WebViewClient() { - override fun onPageStarted(view: WebView, loadedUrl: String?, favicon: android.graphics.Bitmap?) { - Log.d(CloudLogTag, "page started: $loadedUrl") - super.onPageStarted(view, loadedUrl, favicon) - } - - override fun onPageFinished(view: WebView, loadedUrl: String) { - Log.d(CloudLogTag, "page finished: $loadedUrl") - if (loadedUrl.contains("#/pilot-home", ignoreCase = true)) { - view.post { currentOnConnected() } - } - super.onPageFinished(view, loadedUrl) - } - - override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) { - Log.e( - CloudLogTag, - "resource error main=${request.isForMainFrame} url=${request.url} code=${error.errorCode} desc=${error.description}" - ) - super.onReceivedError(view, request, error) - } - - override fun onReceivedHttpError( - view: WebView, - request: WebResourceRequest, - errorResponse: WebResourceResponse - ) { - Log.e( - CloudLogTag, - "http error main=${request.isForMainFrame} url=${request.url} status=${errorResponse.statusCode}" - ) - super.onReceivedHttpError(view, request, errorResponse) - } - } - addJavascriptInterface(bridge, "djiBridge") - loadUrl(openUrl) - tag = reloadTick - } - } - - DisposableEffect(webView) { - onDispose { - webView.stopLoading() - webView.destroy() - } - } - - Box(Modifier.fillMaxSize().background(Color.White)) { - AndroidView( - factory = { webView }, - update = { view -> - if (view.url == null) { - view.loadUrl(openUrl) - view.tag = reloadTick - } else if (view.tag != reloadTick) { - view.loadUrl(openUrl) - view.tag = reloadTick - } - }, - modifier = Modifier.fillMaxSize() - ) - } -} - -@Composable -private fun ThirdPartyConnectedContent( - sdkState: DroneSdkState, - onLogout: () -> Unit -) { - Row( - modifier = Modifier - .fillMaxSize() - .background(PilotPanel) - .padding(horizontal = 22.dp, vertical = 26.dp), - horizontalArrangement = Arrangement.spacedBy(28.dp) - ) { - Surface( - color = Color.White, - shape = RoundedCornerShape(8.dp), - modifier = Modifier - .weight(0.42f) - .fillMaxHeight() - ) { - Column( - modifier = Modifier - .fillMaxSize() - .padding(horizontal = 42.dp, vertical = 22.dp) - ) { - Row(verticalAlignment = Alignment.CenterVertically) { - CloudApiLogo(58.dp) - Spacer(Modifier.width(28.dp)) - Column { - Text( - "中科联航(江苏)信息技术有限公司", - color = PilotText, - fontSize = 16.sp, - fontWeight = FontWeight.Black, - lineHeight = 21.sp, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - Text("已连接", color = Color(0xFF777777), fontSize = 16.sp, fontWeight = FontWeight.Bold) - } - } - Spacer(Modifier.height(24.dp)) - HorizontalDivider(color = PilotLine, thickness = 1.dp) - Spacer(Modifier.weight(1f)) - Button( - onClick = onLogout, - colors = ButtonDefaults.buttonColors( - containerColor = Color(0xFFE7E7E7), - contentColor = PilotDanger - ), - shape = RoundedCornerShape(8.dp), - modifier = Modifier - .align(Alignment.CenterHorizontally) - .width(96.dp) - .height(44.dp) - ) { - Text("退 出", fontSize = 16.sp, fontWeight = FontWeight.Normal) - } - Spacer(Modifier.height(30.dp)) - } - } - Column( - modifier = Modifier - .weight(0.58f) - .fillMaxHeight(), - verticalArrangement = Arrangement.spacedBy(12.dp) - ) { - Text("序列号", color = Color(0xFF8A8A8A), fontSize = 17.sp, modifier = Modifier.padding(start = 6.dp)) - Surface(color = Color.White, shape = RoundedCornerShape(6.dp), modifier = Modifier.fillMaxWidth()) { - Column { - ThirdPartyInfoRow("遥控器Sn码", sdkState.remoteControllerSerialNumber.ifBlank { "--" }) - HorizontalDivider(color = PilotLine, thickness = 1.dp) - ThirdPartyInfoRow("飞机sn码", sdkState.aircraftSerialNumber.ifBlank { "--" }) - } - } - Text("设置", color = Color(0xFF8A8A8A), fontSize = 17.sp, modifier = Modifier.padding(start = 6.dp, top = 4.dp)) - Surface(color = Color.White, shape = RoundedCornerShape(6.dp), modifier = Modifier.fillMaxWidth()) { - Column { - ThirdPartyInfoRow("设备绑定", if (sdkState.productConnected) "绑定的飞机" else "未绑定飞机") - HorizontalDivider(color = PilotLine, thickness = 1.dp) - ThirdPartyActionRow("媒体文件上传") - HorizontalDivider(color = PilotLine, thickness = 1.dp) - ThirdPartyActionRow("手动转播画面") - } - } - } - } -} - -@Composable -private fun CloudApiLogo(size: Dp) { - Surface(shape = CircleShape, color = Color(0xFF15191D), modifier = Modifier.size(size)) { - Box(contentAlignment = Alignment.Center) { - Column(horizontalAlignment = Alignment.CenterHorizontally) { - Text("Cloud", color = Color.White, fontSize = 14.sp, lineHeight = 14.sp) - Text("API", color = Color.White, fontSize = 25.sp, lineHeight = 25.sp) - } - } - } -} - -@Composable -private fun ThirdPartyInfoRow(label: String, value: String) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(74.dp) - .padding(horizontal = 26.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Text(label, color = PilotText, fontSize = 23.sp) - Spacer(Modifier.weight(1f)) - Text(value, color = Color(0xFF777777), fontSize = 22.sp, maxLines = 1, overflow = TextOverflow.Ellipsis) - } -} - -@Composable -private fun ThirdPartyActionRow(label: String) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(74.dp) - .padding(horizontal = 26.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Text(label, color = PilotText, fontSize = 23.sp) - } -} - -private fun normalizeCloudUrl(rawUrl: String): String { - val trimmed = rawUrl.trim() - if (trimmed.isBlank()) return BuildConfig.CLOUD_BASE_URL - return when { - trimmed.startsWith("http://", ignoreCase = true) -> trimmed - trimmed.startsWith("https://", ignoreCase = true) -> trimmed - else -> "http://$trimmed" - } -} - -private fun cloudHostFromUrl(rawUrl: String): String { - val url = normalizeCloudUrl(rawUrl) - val parsed = android.net.Uri.parse(url) - val scheme = parsed.scheme ?: "http" - val host = parsed.host ?: BuildConfig.CLOUD_PLATFORM_HOST - val port = parsed.port.takeIf { it > 0 }?.let { ":$it" }.orEmpty() - return "$scheme://$host$port" -} - -private class CloudApiWebBridge( - private val host: String, - private val remoteControllerSn: String, - private val aircraftSn: String, - private val connected: Boolean -) { - @JavascriptInterface - fun platformLoadComponent(component: String, params: String): String = bridgeString(component) - - @JavascriptInterface - fun platformUnloadComponent(component: String): String = bridgeString(component) - - @JavascriptInterface - fun platformIsComponentLoaded(component: String): String = bridgeRaw("true") - - @JavascriptInterface - fun platformSetWorkspaceId(workspaceId: String): String = bridgeString(workspaceId) - - @JavascriptInterface - fun platformSetInformation(key: String, value: String, type: String): String = bridgeRaw("true") - - @JavascriptInterface - fun platformGetRemoteControllerSN(): String = bridgeString(remoteControllerSn) - - @JavascriptInterface - fun platformGetAircraftSN(): String = bridgeString(aircraftSn) - - @JavascriptInterface - fun platformStopSelf(): String = bridgeString("") - - @JavascriptInterface - fun platformSetLogEncryptKey(key: String): String = bridgeString("") - - @JavascriptInterface - fun platformClearLogEncryptKey(): String = bridgeString("") - - @JavascriptInterface - fun platformGetLogPath(): String = bridgeString("") - - @JavascriptInterface - fun platformVerifyLicense(appId: String, appKey: String, license: String): String = bridgeRaw("true") - - @JavascriptInterface - fun platformIsVerified(): String = bridgeRaw("true") - - @JavascriptInterface - fun platformIsAppInstalled(packageName: String): String = bridgeRaw("false") - - @JavascriptInterface - fun platformGetVersion(): String = "1.0.0" - - @JavascriptInterface - fun thingGetConnectState(): String = bridgeRaw(if (connected) "true" else "false") - - @JavascriptInterface - fun thingGetConfigs(): String = bridgeString("{}") - - @JavascriptInterface - fun apiGetToken(): String = bridgeString("") - - @JavascriptInterface - fun apiSetToken(token: String): String = bridgeString(token) - - @JavascriptInterface - fun apiGetHost(): String = bridgeString(host) - - @JavascriptInterface - fun liveshareSetVideoPublishType(type: String): String = bridgeString(type) - - @JavascriptInterface - fun liveshareGetConfig(): String = bridgeString("") - - @JavascriptInterface - fun liveshareSetConfig(key: String, value: String): String = bridgeString("") - - @JavascriptInterface - fun liveshareSetStatusCallback(callback: String): String = bridgeString(callback) - - @JavascriptInterface - fun liveshareGetStatus(): String = bridgeString("""{"status":0}""") - - @JavascriptInterface - fun liveshareStartLive(): String = bridgeRaw("false") - - @JavascriptInterface - fun liveshareStopLive(): String = bridgeRaw("true") - - @JavascriptInterface - fun wsGetConnectState(): String = bridgeRaw("false") - - @JavascriptInterface - fun wsConnect(host: String, token: String, callback: String): String = bridgeString("") - - @JavascriptInterface - fun wsConnect(): String = bridgeString("") - - @JavascriptInterface - fun wsSend(message: String): String = bridgeString("") - - @JavascriptInterface - fun mediaSetAutoUploadPhoto(enabled: Boolean): String = bridgeString("") - - @JavascriptInterface - fun mediaGetAutoUploadPhoto(): String = bridgeRaw("true") - - @JavascriptInterface - fun mediaSetUploadPhotoType(type: Int): String = bridgeString("") - - @JavascriptInterface - fun mediaGetUploadPhotoType(): String = bridgeRaw("0") - - @JavascriptInterface - fun mediaSetAutoUploadVideo(enabled: Boolean): String = bridgeString("") - - @JavascriptInterface - fun mediaGetAutoUploadVideo(): String = bridgeRaw("true") - - @JavascriptInterface - fun mediaSetDownloadOwner(owner: Int): String = bridgeString("") - - @JavascriptInterface - fun mediaGetDownloadOwner(): String = bridgeRaw("0") - - private fun bridgeString(data: String): String = - """{"code":0,"message":"","data":"${data.escapeBridgeJson()}"}""" - - private fun bridgeRaw(data: String): String = - """{"code":0,"message":"","data":$data}""" - - private fun String.escapeBridgeJson(): String = - replace("\\", "\\\\") - .replace("\"", "\\\"") - .replace("\n", "\\n") - .replace("\r", "\\r") -} - -@Composable -private fun PreflightScreen( - sdkState: DroneSdkState, - telemetry: TelemetrySnapshot, - returnAltitude: Int, - maxAltitude: Int, - farLimitEnabled: Boolean, - onClose: () -> Unit, - onReturnAltitudeChange: (Int) -> Unit, - onMaxAltitudeChange: (Int) -> Unit, - onFarLimitChange: (Boolean) -> Unit, - onToast: (String) -> Unit -) { - PilotPreflightScreen(sdkState, telemetry, onClose) + PilotLoginScreen( + url, onUrlChange, mqttAddress, onMqttAddressChange, + tenantName, onTenantNameChange, username, onUsernameChange, password, onPasswordChange, + cloudState, statusMessage, statusIsError, onBack, onLogin, onRefresh, onLogout + ) } @Composable @@ -1927,6 +1038,7 @@ private fun FlightScreen( alertState: DroneWarningState, flightMode: FlightMode, missionPath: String, + missionRevision: Int, missionId: String, uploadUpdate: MissionUploadUpdate, stickEnabled: Boolean, @@ -1940,7 +1052,7 @@ private fun FlightScreen( onBack: () -> Unit, onOpenPreflight: () -> Unit, onToggleFlightMode: () -> Unit, - onToggleMissionPanel: () -> Unit, + onCloseMissionPanel: () -> Unit, onMissionPathChange: (String) -> Unit, onMissionIdChange: (String) -> Unit, onPickMission: () -> Unit, @@ -1956,6 +1068,7 @@ private fun FlightScreen( onToggleSimulator: () -> Unit, onToggleLiveStream: () -> Unit, onSendStick: (StickPosition) -> Unit, + onZoomChange: (Double) -> Unit, onTakePhoto: () -> Unit, onToggleRecord: () -> Unit, onToggleLaserFillLight: () -> Unit, @@ -1963,6 +1076,11 @@ private fun FlightScreen( onToast: (String) -> Unit ) { var showAlertDetails by remember { mutableStateOf(false) } + var showDeviceDetails by remember { mutableStateOf(false) } + var showMapSettings by remember { mutableStateOf(false) } + var showMedia by remember { mutableStateOf(false) } + val missionPreview = rememberMissionPreview(missionPath, missionRevision) + val missionExecution = rememberPilotMissionExecution(sdkState.productConnected) var showCameraActionPicker by remember { mutableStateOf(false) } var cameraQuickAction by remember { mutableStateOf(CameraQuickAction.Photo) } var leftWheel by remember { mutableStateOf(Offset.Zero) } @@ -1976,10 +1094,10 @@ private fun FlightScreen( val flightCommandsEnabled = SafetyInterlock.FLIGHT_COMMANDS_ENABLED val aircraftAirborne = sdkState.productConnected && isAircraftAirborne(telemetry) val wheelControlling = flightCommandsEnabled && (aircraftAirborne || takeoffIssued) - val wheelControlEnabled = flightCommandsEnabled && sdkState.productConnected && stickEnabled - val wheelPrepareEnabled = flightCommandsEnabled && sdkState.productConnected && !stickEnabled + val wheelControlEnabled = flightCommandsEnabled && sdkState.productConnected && stickEnabled && !showMissionPanel && !showAlertDetails && !showDeviceDetails && !showMapSettings && !showMedia + val wheelPrepareEnabled = flightCommandsEnabled && sdkState.productConnected && !stickEnabled && !showMissionPanel && !showAlertDetails && !showDeviceDetails && !showMapSettings && !showMedia val wheelTakeoffEnabled = - flightCommandsEnabled && sdkState.productConnected && stickEnabled && !aircraftAirborne && !takeoffIssued && !takeoffLockedUntilRelease + wheelControlEnabled && !aircraftAirborne && !takeoffIssued && !takeoffLockedUntilRelease fun sendWheelPosition(nextLeft: Offset = leftWheel, nextRight: Offset = rightWheel) { onSendStick( StickPosition( @@ -2002,6 +1120,16 @@ private fun FlightScreen( cameraQuickAction = action showCameraActionPicker = false } + LaunchedEffect(wheelControlEnabled) { + if (!wheelControlEnabled) { + leftWheel = Offset.Zero; rightWheel = Offset.Zero + leftWheelPressed = false; rightWheelPressed = false + if (stickEnabled) onSendStick(StickPosition()) + } + } + DisposableEffect(Unit) { + onDispose { onSendStick(StickPosition()) } + } LaunchedEffect(sdkState.productConnected, stickEnabled) { if (!sdkState.productConnected || !stickEnabled) { leftWheel = Offset.Zero @@ -2035,7 +1163,7 @@ private fun FlightScreen( takeoffLockedUntilRelease = false } } - LaunchedEffect(sdkState.productConnected, stickEnabled, stickPower, leftWheel, rightWheel) { + LaunchedEffect(wheelControlEnabled, sdkState.productConnected, stickEnabled, stickPower, leftWheel, rightWheel) { if (!wheelControlEnabled) return@LaunchedEffect if (leftWheel == Offset.Zero && rightWheel == Offset.Zero) return@LaunchedEffect while (true) { @@ -2078,206 +1206,117 @@ private fun FlightScreen( Log.d(FlightControlLogTag, "takeoff gesture completed, sending takeoff") onTakeoff() } - BoxWithConstraints(Modifier.fillMaxSize().background(PilotBlack)) { + BoxWithConstraints(Modifier.fillMaxSize().background(PilotDesign.Background)) { val compact = maxHeight < 560.dp || maxWidth < 960.dp - val topBarHeight = if (compact) 46.dp else 54.dp - val railWidth = if (compact) 50.dp else 58.dp - val sideRailWidth = if (compact) 56.dp else 64.dp - val bottomInset = if (compact) 4.dp else 8.dp + val camera = flightMode == FlightMode.Camera + val showStickLabels = maxWidth > 1100.dp val wheelSize = if (compact) 100.dp else 120.dp - - if (flightMode == FlightMode.Map) { - NativeMap( - connected = sdkState.productConnected, - telemetry = telemetry, - modifier = Modifier.fillMaxSize() - ) - } else { - DjiCameraLivePreview( - connected = sdkState.productConnected, - modifier = Modifier.fillMaxSize() - ) + val topStatus = flightTopStatusText(sdkState, telemetry, simulatorEnabled, flightCommandsEnabled, stickEnabled, aircraftAirborne, takeoffIssued, prepareProgress, takeoffProgress, flightActionStatus) + Column(Modifier.fillMaxSize()) { + PilotFlightHeader(sdkState, telemetry, camera, topStatus, alertState, onBack, { showAlertDetails = true }, { showDeviceDetails = true }) + Row(Modifier.weight(1f).fillMaxWidth()) { + if (showMissionPanel) { + Column(Modifier.weight(0.64f).fillMaxHeight()) { + Box(Modifier.weight(1f).fillMaxWidth()) { + if (camera) DjiCameraLivePreview(sdkState.productConnected, Modifier.fillMaxSize()) + else PilotMap(sdkState.productConnected, telemetry, Modifier.fillMaxSize(), missionPreview.preview, controlsLeading = true, onConfigure = { showMapSettings = true }) + PilotSwapPreview(camera, sdkState.productConnected, telemetry, missionPreview.preview, onToggleFlightMode, + Modifier.align(Alignment.BottomStart).padding(12.dp).size(155.dp, 88.dp)) + } + PilotMissionFlightMetrics(sdkState.productConnected, telemetry, missionPreview.preview, Modifier.fillMaxWidth().height(67.dp)) + } + PilotMissionPanel( + sdkState.productConnected, telemetry, missionPath, missionId, uploadUpdate, missionPreview, missionExecution, + onMissionIdChange, onPickMission, onGenerateMission, onUploadMission, onStartMission, onPauseMission, onResumeMission, onStopMission, onCloseMissionPanel, + Modifier.weight(0.36f).fillMaxHeight() + ) + } else { + Column(Modifier.fillMaxSize()) { + Row(Modifier.weight(1f).fillMaxWidth()) { + Column(Modifier.width(if (camera) 60.dp else 68.dp).fillMaxHeight().padding(6.dp).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(6.dp)) { + PilotTool(if (camera) Icons.Filled.CameraAlt else Icons.Filled.Map, if (camera) "相机" else "地图", active = true) { } + PilotTool(Icons.Filled.Shield, "飞前检查", onClick = onOpenPreflight) + PilotTool(Icons.Filled.Home, "返航", enabled = sdkState.productConnected, onClick = onGoHome) + PilotTool(if (camera) Icons.Filled.Map else Icons.Filled.CameraAlt, if (camera) "地图" else "相机", onClick = onToggleFlightMode) + PilotTool(Icons.Filled.Description, "飞行记录") { showDeviceDetails = true } + PilotTool(Icons.Filled.Settings, "设备") { showDeviceDetails = true } + PilotTool(Icons.Filled.Layers, "图层配置") { showMapSettings = true } + } + Box(Modifier.weight(1f).fillMaxHeight().clip(RoundedCornerShape(8.dp))) { + if (camera) { + DjiCameraLivePreview(sdkState.productConnected, Modifier.fillMaxSize()) + FocusFrame(compact, Modifier.align(Alignment.Center)) + Surface(Modifier.align(Alignment.TopStart).padding(12.dp), color = Color(0xB829435C), shape = RoundedCornerShape(8.dp)) { + Row(Modifier.padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) { + Box(Modifier.size(10.dp).background(if (cameraRecording) PilotDanger else PilotMuted, CircleShape)) + Text(if (cameraRecording) " ${pilotDuration(telemetry.recordingTime)} · 录像中" else " 实时图传 · ${telemetry.cameraType.replace('_', ' ').ifBlank { "等待相机" }}", color = Color.White, fontSize = 11.sp) + } + } + } else { + PilotMap(sdkState.productConnected, telemetry, Modifier.fillMaxSize(), missionPreview.preview, onConfigure = { showMapSettings = true }) + } + PilotSwapPreview(camera, sdkState.productConnected, telemetry, missionPreview.preview, onToggleFlightMode, + Modifier.align(Alignment.BottomStart).padding(12.dp).size(174.dp, 99.dp)) + } + Column(Modifier.width(if (camera) 66.dp else 78.dp).fillMaxHeight().padding(6.dp).verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(7.dp)) { + Text(if (camera) "拍摄模式" else "相机模式", color = PilotText, fontSize = 10.sp, modifier = Modifier.padding(vertical = 5.dp)) + PilotTool(Icons.Filled.CameraAlt, "拍照", active = cameraQuickAction == CameraQuickAction.Photo, enabled = sdkState.productConnected) { changeCameraQuickAction(CameraQuickAction.Photo) } + PilotTool(Icons.Filled.Videocam, if (cameraRecording) "录像中" else "录像", active = cameraQuickAction == CameraQuickAction.Video, enabled = sdkState.productConnected) { changeCameraQuickAction(CameraQuickAction.Video) } + CameraShutterButton(sdkState.productConnected, cameraQuickAction, cameraRecording, laserFillLightEnabled, compact, ::triggerCameraShutter) + PilotTool(Icons.Filled.Image, "相册") { showMedia = true } + PilotTool(Icons.Filled.Panorama, "全景", active = cameraQuickAction == CameraQuickAction.Panorama, enabled = sdkState.productConnected) { changeCameraQuickAction(CameraQuickAction.Panorama) } + PilotTool(Icons.Filled.Lightbulb, "补光灯", active = laserFillLightEnabled, enabled = sdkState.productConnected, onClick = onToggleLaserFillLight) + if (camera) { + Surface(color = Color(0xFF405873), shape = RoundedCornerShape(7.dp)) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text(if (sdkState.productConnected) "${instrumentNumber(telemetry.zoomFactor)}x" else "—", color = Color.White, fontSize = 11.sp, modifier = Modifier.padding(top = 8.dp)) + IconButton(onClick = { onZoomChange((telemetry.zoomFactor + 1).coerceAtMost(200.0)) }, enabled = sdkState.productConnected) { Icon(Icons.Filled.Add, "增加相机变焦", tint = Color.White) } + IconButton(onClick = { onZoomChange((telemetry.zoomFactor - 1).coerceAtLeast(1.0)) }, enabled = sdkState.productConnected) { Icon(Icons.Filled.Remove, "减小相机变焦", tint = Color.White) } + } + } + } + } + } + Row(Modifier.fillMaxWidth().height(wheelSize + 12.dp).padding(horizontal = 20.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) { + FlightStickWheel("左摇杆", wheelStatusText(sdkState.productConnected, flightCommandsEnabled, stickEnabled, wheelControlling, takeoffLockedUntilRelease, "油门 / 偏航"), leftWheel, wheelControlEnabled, + flightCommandsEnabled && sdkState.productConnected && !showMissionPanel && !showAlertDetails && !showDeviceDetails && !showMapSettings && !showMedia, + if (!stickEnabled) prepareProgress else if (!wheelControlling) takeoffProgress else 0f, compact, Modifier.size(wheelSize), + { leftWheel = it; sendWheelPosition(nextLeft = it) }, { leftWheelPressed = it }) + if (camera && showStickLabels) Text("左摇杆\n上升 / 下降\n左转 / 右转", color = PilotMuted, fontSize = 11.sp) + PilotFlightMetrics(sdkState.productConnected, telemetry, camera, Modifier.weight(1f).padding(horizontal = 12.dp)) + FlightStickWheel("右摇杆", wheelStatusText(sdkState.productConnected, flightCommandsEnabled, stickEnabled, wheelControlling, takeoffLockedUntilRelease, "俯仰 / 横滚"), rightWheel, wheelControlEnabled, + flightCommandsEnabled && sdkState.productConnected && !showMissionPanel && !showAlertDetails && !showDeviceDetails && !showMapSettings && !showMedia, + if (!stickEnabled) prepareProgress else if (!wheelControlling) takeoffProgress else 0f, compact, Modifier.size(wheelSize), + { rightWheel = it; sendWheelPosition(nextRight = it) }, { rightWheelPressed = it }) + } + } + } + } } + if (!stickEnabled && !showMissionPanel) Text("双摇杆长按解锁 · 松开后再次长按起飞", color = PilotMuted, fontSize = 9.sp, modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 2.dp)) + if (showAlertDetails) PilotAlertsDialog(alertState, sdkState, telemetry) { showAlertDetails = false } + if (showDeviceDetails) PilotDeviceDialog(sdkState, telemetry, simulatorEnabled, liveStreaming, liveBusy, onToggleSimulator, onToggleLiveStream, + { showDeviceDetails = false; showMapSettings = true }) { showDeviceDetails = false } + if (showMapSettings) PilotMapSettings({ showMapSettings = false }, + if (telemetry.locationValid) telemetry.latitude else 35.0, if (telemetry.locationValid) telemetry.longitude else 104.0) + if (showMedia) PilotMediaDialog(sdkState.productConnected, telemetry) { showMedia = false } + } +} - FlightTopBar( - sdkState = sdkState, - telemetry = telemetry, - alertState = alertState, - centerStatus = flightTopStatusText( - sdkState = sdkState, - telemetry = telemetry, - simulatorEnabled = simulatorEnabled, - flightCommandsEnabled = flightCommandsEnabled, - stickEnabled = stickEnabled, - airborne = aircraftAirborne, - takeoffIssued = takeoffIssued, - prepareProgress = prepareProgress, - takeoffProgress = takeoffProgress, - flightActionStatus = flightActionStatus - ), - onBack = onBack, - onAlertClick = { showAlertDetails = !showAlertDetails }, - compact = compact, - modifier = Modifier - .fillMaxWidth() - .height(topBarHeight) - .align(Alignment.TopStart) - ) - - if (showAlertDetails) { - AlertDetailsPanel( - alertState = alertState, - compact = compact, - modifier = Modifier - .align(Alignment.TopStart) - .offset(x = if (compact) 116.dp else 132.dp, y = topBarHeight + 8.dp) - .width(if (compact) 420.dp else 560.dp) - .heightIn(max = maxHeight - topBarHeight - 24.dp) - .zIndex(5f) - ) +@Composable +private fun PilotSwapPreview(cameraMain: Boolean, connected: Boolean, telemetry: TelemetrySnapshot, + mission: com.zklh.dronecontroller.core.mission.MissionPreview?, onSwap: () -> Unit, modifier: Modifier = Modifier) { + val action = if (cameraMain) "切换到地图" else "切换到视频" + Box(modifier.clip(RoundedCornerShape(7.dp)).border(1.dp, Color.White.copy(alpha = 0.7f), RoundedCornerShape(7.dp))) { + if (cameraMain) PilotMap(connected, telemetry, Modifier.fillMaxSize(), mission, controls = false) + else DjiCameraLivePreview(connected, Modifier.fillMaxSize(), small = true) + Surface(Modifier.align(Alignment.TopStart), color = Color(0xAA193B55)) { + Text(if (cameraMain) "地图 · 点击切换" else "机载相机 · 点击切换", color = Color.White, fontSize = 8.sp, lineHeight = 11.sp, modifier = Modifier.padding(5.dp)) } - - LeftFlightRail( - width = railWidth, - compact = compact, - cameraStyle = flightMode == FlightMode.Camera, - simulatorEnabled = simulatorEnabled, - liveStreaming = liveStreaming, - liveBusy = liveBusy, - missionActive = showMissionPanel, - onMission = onToggleMissionPanel, - onOpenPreflight = onOpenPreflight, - onReturnHome = onGoHome, - onSwitchMode = onToggleFlightMode, - onToggleSimulator = onToggleSimulator, - onToggleLiveStream = onToggleLiveStream, - modifier = Modifier - .align(Alignment.TopStart) - .offset(x = 8.dp, y = topBarHeight + 12.dp) - .height(maxHeight - topBarHeight - wheelSize - 30.dp) - ) - - FlightTelemetryHud( - telemetry = telemetry, - connected = sdkState.productConnected, - compact = compact, - modifier = Modifier - .align(Alignment.BottomCenter) - .padding(bottom = bottomInset) - .width((maxWidth - (wheelSize + 18.dp) * 2 - 18.dp).coerceAtMost(if (compact) 430.dp else 560.dp)) - .height(if (compact) 122.dp else 168.dp) - ) - - RightCameraRail( - width = sideRailWidth, - connected = sdkState.productConnected, - recording = cameraRecording, - laserFillLightEnabled = laserFillLightEnabled, - selectedAction = cameraQuickAction, - compact = compact, - onOpenActionPicker = { showCameraActionPicker = true }, - onShutter = { triggerCameraShutter() }, - modifier = Modifier - .align(Alignment.TopEnd) - .offset(y = topBarHeight + 16.dp) - .padding(end = 10.dp) - .zIndex(4f) - ) - - if (showCameraActionPicker) { - CameraActionPicker( - selectedAction = cameraQuickAction, - recording = cameraRecording, - laserFillLightEnabled = laserFillLightEnabled, - compact = compact, - onSelect = ::changeCameraQuickAction, - onDismiss = { showCameraActionPicker = false }, - modifier = Modifier - .align(Alignment.CenterEnd) - .padding(end = sideRailWidth + 14.dp) - .zIndex(6f) - ) - } - - FlightStickWheel( - title = "左摇杆", - statusText = wheelStatusText( - connected = sdkState.productConnected, - flightCommandsEnabled = flightCommandsEnabled, - stickEnabled = stickEnabled, - airborne = wheelControlling, - takeoffLockedUntilRelease = takeoffLockedUntilRelease, - controlText = "油门 / 偏航" - ), - value = leftWheel, - enabled = wheelControlEnabled, - pressEnabled = flightCommandsEnabled && sdkState.productConnected, - progress = if (!stickEnabled) prepareProgress else if (!wheelControlling) takeoffProgress else 0f, - compact = compact, - modifier = Modifier - .align(Alignment.BottomStart) - .offset(x = if (compact) 10.dp else 14.dp, y = -bottomInset) - .size(wheelSize) - .zIndex(3f), - onValueChange = { value -> - leftWheel = value - sendWheelPosition(nextLeft = value) - }, - onPressedChange = { leftWheelPressed = it } - ) - - FlightStickWheel( - title = "右摇杆", - statusText = wheelStatusText( - connected = sdkState.productConnected, - flightCommandsEnabled = flightCommandsEnabled, - stickEnabled = stickEnabled, - airborne = wheelControlling, - takeoffLockedUntilRelease = takeoffLockedUntilRelease, - controlText = "俯仰 / 横滚" - ), - value = rightWheel, - enabled = wheelControlEnabled, - pressEnabled = flightCommandsEnabled && sdkState.productConnected, - progress = if (!stickEnabled) prepareProgress else if (!wheelControlling) takeoffProgress else 0f, - compact = compact, - modifier = Modifier - .align(Alignment.BottomEnd) - .padding(end = if (compact) 10.dp else 14.dp, bottom = bottomInset) - .size(wheelSize) - .zIndex(3f), - onValueChange = { value -> - rightWheel = value - sendWheelPosition(nextRight = value) - }, - onPressedChange = { rightWheelPressed = it } - ) - - if (showMissionPanel) { - MissionPanel( - connected = sdkState.productConnected, - missionPath = missionPath, - missionId = missionId, - uploadUpdate = uploadUpdate, - compact = compact, - onMissionPathChange = onMissionPathChange, - onMissionIdChange = onMissionIdChange, - onPickMission = onPickMission, - onUploadMission = onUploadMission, - onGenerateMission = onGenerateMission, - onStartMission = onStartMission, - onPauseMission = onPauseMission, - onResumeMission = onResumeMission, - onStopMission = onStopMission, - modifier = Modifier - .align(Alignment.TopStart) - .offset(x = railWidth + 12.dp, y = topBarHeight + 12.dp) - .width(if (compact) 320.dp else 410.dp) - .heightIn(max = maxHeight - topBarHeight - wheelSize - bottomInset - 58.dp) - .zIndex(6f) - ) - } - + Icon(if (cameraMain) Icons.Filled.Map else Icons.Filled.Fullscreen, null, tint = Color.White, + modifier = Modifier.align(Alignment.BottomEnd).size(30.dp).background(Color(0x991C374D), RoundedCornerShape(5.dp)).padding(6.dp)) + // Receive taps before the embedded native map/video can consume them. + Box(Modifier.matchParentSize().clickable(onClickLabel = action, role = androidx.compose.ui.semantics.Role.Button, onClick = onSwap)) } } @@ -2325,9 +1364,9 @@ private fun FlightStickWheel( Box( modifier = modifier .clip(CircleShape) - .background(Color(0x660B1119)) + .background(Color(0xFFF5F9FC)) .semantics { contentDescription = "$title,$statusText" } - .border(1.dp, if (enabled || pressEnabled) Color(0x99FFFFFF) else Color(0x557A7A7A), CircleShape) + .border(1.dp, if (enabled || pressEnabled) PilotDesign.Line else PilotDesign.Line, CircleShape) .pointerInput(pressEnabled) { if (!pressEnabled) return@pointerInput detectTapGestures( @@ -2368,8 +1407,8 @@ private fun FlightStickWheel( val center = Offset(size.width / 2f, size.height / 2f) val outer = size.minDimension * 0.47f val inner = size.minDimension * 0.16f - val lineColor = if (enabled) Color(0x88FFFFFF) else Color(0x447A7A7A) - drawCircle(Color(0x552A2A2A), radius = outer, center = center) + val lineColor = PilotDesign.Line + drawCircle(Color(0xFFE6EEF5), radius = outer, center = center) drawCircle(lineColor, radius = outer, center = center, style = Stroke(2f)) if (progress > 0f) { drawArc( @@ -2385,11 +1424,20 @@ private fun FlightStickWheel( drawLine(lineColor, center.copy(x = center.x - outer * 0.72f), center.copy(x = center.x + outer * 0.72f), 2f) drawLine(lineColor, center.copy(y = center.y - outer * 0.72f), center.copy(y = center.y + outer * 0.72f), 2f) drawCircle( - color = if (enabled) PilotGreen.copy(alpha = 0.92f) else Color(0xFF5F656A), + color = Color.White, radius = inner, center = center + knobOffset ) - drawCircle(Color.White.copy(alpha = if (enabled) 0.28f else 0.12f), radius = inner * 0.42f, center = center + knobOffset) + drawCircle(PilotDesign.Line, radius = inner, center = center + knobOffset, style = Stroke(1.dp.toPx())) + val arrowPaint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { + color = PilotDesign.Ink.toArgb(); textSize = 13.dp.toPx(); textAlign = android.graphics.Paint.Align.CENTER + } + drawIntoCanvas { canvas -> + canvas.nativeCanvas.drawText("⌃", center.x, center.y - outer * 0.69f, arrowPaint) + canvas.nativeCanvas.drawText("⌄", center.x, center.y + outer * 0.83f, arrowPaint) + canvas.nativeCanvas.drawText("‹", center.x - outer * 0.80f, center.y + 4.dp.toPx(), arrowPaint) + canvas.nativeCanvas.drawText("›", center.x + outer * 0.80f, center.y + 4.dp.toPx(), arrowPaint) + } } } @@ -2413,340 +1461,7 @@ private fun wheelStatusText( } @Composable -private fun AlertDetailsPanel(alertState: DroneWarningState, compact: Boolean, modifier: Modifier = Modifier) { - val messages = alertState.messages.ifEmpty { listOf(alertState.message) } - Surface( - color = Color(0xF2222222), - shape = RoundedCornerShape(8.dp), - border = BorderStroke(1.dp, alertBannerColor(alertState).copy(alpha = 0.85f)), - shadowElevation = 8.dp, - modifier = modifier - ) { - Column( - modifier = Modifier - .padding(if (compact) 10.dp else 12.dp) - .verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(if (compact) 6.dp else 8.dp) - ) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) { - Text( - if (alertState.active) "实时告警 ${messages.size} 条" else "实时告警", - color = Color.White, - fontSize = if (compact) 14.sp else 16.sp, - fontWeight = FontWeight.Black - ) - Text( - alertState.level.name, - color = Color(0xFFCBD5E1), - fontSize = if (compact) 10.sp else 11.sp, - fontWeight = FontWeight.Bold - ) - } - messages.forEachIndexed { index, message -> - Row( - modifier = Modifier - .fillMaxWidth() - .background(Color(0x332A2A2A), RoundedCornerShape(6.dp)) - .padding(horizontal = 10.dp, vertical = 8.dp), - verticalAlignment = Alignment.Top - ) { - Text( - "${index + 1}", - color = alertBannerColor(alertState), - fontSize = if (compact) 11.sp else 12.sp, - fontWeight = FontWeight.Black, - modifier = Modifier.width(20.dp) - ) - Text( - message, - color = Color.White, - fontSize = if (compact) 12.sp else 13.sp, - fontWeight = FontWeight.Bold, - lineHeight = if (compact) 16.sp else 18.sp, - modifier = Modifier.weight(1f) - ) - } - } - } - } -} - -@Composable -private fun SimpleTitleBar( - title: String, - onBack: (() -> Unit)?, - right: @Composable () -> Unit = {} -) { - Box( - modifier = Modifier - .fillMaxWidth() - .height(48.dp) - .background(Color.White) - .border(BorderStroke(0.5.dp, PilotLine)) - .padding(horizontal = 16.dp) - ) { - if (onBack != null) { - IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, null, modifier = Modifier.size(27.dp), tint = PilotText) - } - } - Text(title, color = PilotText, fontSize = 21.sp, fontWeight = FontWeight.Black, modifier = Modifier.align(Alignment.Center)) - Row( - modifier = Modifier.align(Alignment.CenterEnd), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp) - ) { - right() - } - } -} - -@Composable -private fun StatusChip(icon: ImageVector, text: String, color: Color) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { - Icon(icon, null, tint = if (color == PilotDanger) color else Color(0xFFA0A4A8), modifier = Modifier.size(16.dp)) - Text(text, color = color, fontSize = 13.sp, fontWeight = FontWeight.Black, maxLines = 1) - } -} - -@Composable -private fun HeightSetting(label: String, range: String, value: Int, onChange: (Int) -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(38.dp) - .border(BorderStroke(0.5.dp, PilotLine)), - verticalAlignment = Alignment.CenterVertically - ) { - Text(label, fontSize = 13.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.width(92.dp)) - Text(range, color = PilotMuted, fontSize = 11.sp, maxLines = 1, modifier = Modifier.width(70.dp)) - SmallStep("-100") { onChange(value - 100) } - SmallStep("-10") { onChange(value - 10) } - Text("$value", fontSize = 13.sp, textAlign = TextAlign.Center, modifier = Modifier.width(42.dp)) - SmallStep("+10") { onChange(value + 10) } - SmallStep("+100") { onChange(value + 100) } - } -} - -@Composable -private fun SmallStep(text: String, onClick: () -> Unit) { - TextButton( - onClick = onClick, - shape = RoundedCornerShape(6.dp), - colors = ButtonDefaults.textButtonColors(containerColor = Color(0xFFE8E8E8), contentColor = Color(0xFF444444)), - modifier = Modifier.size(width = 43.dp, height = 28.dp), - contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp) - ) { - Text(text, fontSize = 10.sp, maxLines = 1) - } -} - -@Composable -private fun PreflightSegment(label: String, values: List, selected: Int) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(38.dp) - .border(BorderStroke(0.5.dp, PilotLine)), - verticalAlignment = Alignment.CenterVertically - ) { - Text(label, fontSize = 13.sp, fontWeight = FontWeight.Bold, modifier = Modifier.width(168.dp)) - Row { - values.forEachIndexed { index, value -> - Surface( - color = if (index == selected) Color(0xFF4A4A4A) else Color.White, - contentColor = if (index == selected) Color.White else PilotText, - border = BorderStroke(1.dp, Color(0xFFB8B8B8)), - modifier = Modifier.height(28.dp).width(58.dp) - ) { - Box(contentAlignment = Alignment.Center) { - Text(value, fontSize = 12.sp, fontWeight = FontWeight.Bold) - } - } - } - } - } -} - -@Composable -private fun AvoidanceSetting(label: String, value: String, progress: Float) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(38.dp) - .border(BorderStroke(0.5.dp, PilotLine)), - verticalAlignment = Alignment.CenterVertically - ) { - Text(label, fontSize = 13.sp, fontWeight = FontWeight.Bold, modifier = Modifier.width(142.dp)) - Icon(Icons.Filled.CheckCircle, null, tint = PilotBlue, modifier = Modifier.size(23.dp)) - Text(value, color = PilotMuted, fontSize = 10.sp, textAlign = TextAlign.End, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) - LinearProgressIndicator( - progress = { progress }, - color = PilotOrange, - trackColor = Color(0xFFD9D9D9), - modifier = Modifier.width(82.dp).height(4.dp).padding(horizontal = 8.dp) - ) - } -} - -@Composable -private fun DropSetting(label: String, value: String, orangeDot: Boolean = false) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(38.dp) - .border(BorderStroke(0.5.dp, PilotLine)) - .padding(horizontal = 18.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Text(label, fontSize = 13.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f)) - if (orangeDot) { - Box(Modifier.size(7.dp).background(PilotOrange, CircleShape)) - Spacer(Modifier.width(7.dp)) - } - Text(value, color = if (orangeDot) PilotMuted else PilotText, fontSize = 12.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis) - Icon(Icons.Filled.ExpandMore, null, modifier = Modifier.size(18.dp)) - } -} - -@Composable -private fun SwitchSetting(label: String, checked: Boolean, onChange: (Boolean) -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(38.dp) - .border(BorderStroke(0.5.dp, PilotLine)) - .padding(horizontal = 18.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Text(label, fontSize = 13.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f)) - Switch(checked = checked, onCheckedChange = onChange) - Spacer(Modifier.width(10.dp)) - Box( - modifier = Modifier - .size(width = 88.dp, height = 28.dp) - .background(Color(0xFFF0F0F0), RoundedCornerShape(7.dp)) - ) - } -} - -@OptIn(ExperimentalFoundationApi::class) -@Composable -private fun FlightTopBar( - sdkState: DroneSdkState, - telemetry: TelemetrySnapshot, - alertState: DroneWarningState, - centerStatus: String, - onBack: () -> Unit, - onAlertClick: () -> Unit, - compact: Boolean, - modifier: Modifier = Modifier -) { - val warnWidth = if (compact) 150.dp else 240.dp - val topFont = if (compact) 16.sp else 19.sp - val isWarning = alertState.active || !sdkState.productConnected || sdkState.registerError != null - val alertColor = alertBannerColor(alertState) - val batteryPercent = batteryPercentText(sdkState.productConnected, telemetry) - val batteryVoltage = batteryVoltageText(sdkState.productConnected, telemetry) - val alertCount = effectiveAlertCount(alertState) - val rtkColor = rtkStatusColor(sdkState.productConnected, telemetry) - val rtkCount = rtkSatelliteText(sdkState.productConnected, telemetry) - - Column(modifier.background(Color(0xA80B1119))) { - Row( - modifier = Modifier - .fillMaxWidth() - .weight(1f) - .padding(horizontal = 8.dp), - verticalAlignment = Alignment.CenterVertically - ) { - IconButton(onClick = onBack, modifier = Modifier.size(if (compact) 42.dp else 48.dp)) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, null, tint = Color.White, modifier = Modifier.size(if (compact) 28.dp else 34.dp)) - } - Surface( - color = if (alertCount > 0) alertColor else Color(0xFF30363B), - shape = RoundedCornerShape(5.dp), - modifier = Modifier - .size(width = if (compact) 36.dp else 42.dp, height = if (compact) 38.dp else 44.dp) - .clickable(onClick = onAlertClick) - ) { - Box(contentAlignment = Alignment.Center) { - Text( - if (alertCount > 99) "99+" else alertCount.toString(), - color = Color.White, - fontSize = if (compact) 14.sp else 17.sp, - fontWeight = FontWeight.Bold - ) - } - } - Spacer(Modifier.width(8.dp)) - Surface( - color = if (isWarning) alertColor else Color(0xFF30363B), - shape = RoundedCornerShape(5.dp), - modifier = Modifier - .width(warnWidth) - .height(if (compact) 38.dp else 44.dp) - .clickable(onClick = onAlertClick) - ) { - Box(contentAlignment = Alignment.CenterStart, modifier = Modifier.padding(horizontal = 14.dp)) { - Text( - alertState.message, - color = Color.White, - fontSize = if (compact) 14.sp else 17.sp, - fontWeight = FontWeight.Bold, - maxLines = 1, - overflow = TextOverflow.Clip, - modifier = Modifier.basicMarquee(iterations = Int.MAX_VALUE) - ) - } - } - Text( - centerStatus, - color = Color.White, - fontSize = topFont, - fontWeight = FontWeight.Black, - textAlign = TextAlign.Center, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f) - ) - Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.width(44.dp)) { - Text("RTK", color = rtkColor, fontSize = 14.sp, fontWeight = FontWeight.Black) - Text(rtkCount, color = rtkColor, fontSize = 15.sp, fontWeight = FontWeight.Black) - } - Text(if (sdkState.productLinkConnected) "RC 在线" else "RC --", color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.Black, modifier = Modifier.width(72.dp)) - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.width(68.dp)) { - Icon(Icons.Filled.BatteryFull, null, tint = if (sdkState.productConnected) Color.White else Color(0xFF9CA3AF), modifier = Modifier.size(24.dp)) - Column { - Text(batteryPercent, color = if (sdkState.productConnected) Color.White else Color(0xFF9CA3AF), fontSize = 12.sp, fontWeight = FontWeight.Black) - Text(batteryVoltage, color = if (sdkState.productConnected) Color.White else Color(0xFF9CA3AF), fontSize = 12.sp, fontWeight = FontWeight.Black) - } - } - } - LinearProgressIndicator( - progress = { if (sdkState.productConnected) 1f else 0f }, - color = PilotGreen, - trackColor = Color(0xFF2E2E2E), - modifier = Modifier.fillMaxWidth().height(3.dp) - ) - } -} - -@Composable -private fun NativeMap(connected: Boolean, modifier: Modifier = Modifier, telemetry: TelemetrySnapshot = TelemetrySnapshot()) { - Box(modifier.background(Color(0xFF111922)), contentAlignment = Alignment.Center) { - Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) { - Icon(Icons.Filled.MyLocation, null, tint = if (connected && telemetry.locationValid) PilotGreen else PilotMuted, modifier = Modifier.size(36.dp)) - Text("定位信息", color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold) - Text(if (connected && telemetry.locationValid) "%.6f, %.6f".format(Locale.US, telemetry.latitude, telemetry.longitude) else "等待有效飞机定位", color = Color(0xFFADB8C6), fontSize = 14.sp) - Text("地图尚未接入,可在更多中切回图传", color = Color(0xFF7D8C9E), fontSize = 12.sp) - } - } -} - - -@Composable -private fun DjiCameraLivePreview(connected: Boolean, modifier: Modifier = Modifier) { +private fun DjiCameraLivePreview(connected: Boolean, modifier: Modifier = Modifier, small: Boolean = false) { val previewService = remember { DjiVideoPreviewService() } val previewState by previewService.state.collectAsState() @@ -2799,18 +1514,21 @@ private fun DjiCameraLivePreview(connected: Boolean, modifier: Modifier = Modifi modifier = Modifier .align(Alignment.Center) .background(Color(0x99000000), RoundedCornerShape(8.dp)) - .padding(horizontal = 22.dp, vertical = 14.dp), + .padding(horizontal = if (small) 8.dp else 22.dp, vertical = if (small) 5.dp else 14.dp), horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(6.dp) + verticalArrangement = Arrangement.spacedBy(if (small) 4.dp else 6.dp) ) { - Icon(Icons.Filled.Videocam, null, tint = Color.White, modifier = Modifier.size(34.dp)) + Icon(Icons.Filled.Videocam, null, tint = Color.White, modifier = Modifier.size(if (small) 20.dp else 34.dp)) Text( - if (connected) "正在接入无人机图传" else "等待飞机连接后显示图传", + if (connected) "正在接入无人机图传" else if (small) "等待飞行器连接" else "等待飞机连接后显示图传", color = Color.White, - fontSize = 17.sp, - fontWeight = FontWeight.Bold + fontSize = if (small) 10.sp else 17.sp, + lineHeight = if (small) 14.sp else 24.sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis ) - Text( + if (!small) Text( if (connected) previewState.message else "无人机未连接,未请求图传流", color = Color(0xFFCED4DA), fontSize = 11.sp, @@ -2822,88 +1540,6 @@ private fun DjiCameraLivePreview(connected: Boolean, modifier: Modifier = Modifi } } -@Composable -private fun LeftFlightRail( - width: Dp, - compact: Boolean, - cameraStyle: Boolean, - simulatorEnabled: Boolean, - liveStreaming: Boolean, - liveBusy: Boolean, - missionActive: Boolean, - onMission: () -> Unit, - onOpenPreflight: () -> Unit, - onReturnHome: () -> Unit, - onSwitchMode: () -> Unit, - onToggleSimulator: () -> Unit, - onToggleLiveStream: () -> Unit, - modifier: Modifier = Modifier -) { - var showMore by remember { mutableStateOf(false) } - val menuOffset = with(LocalDensity.current) { (width + 8.dp).roundToPx() } - Box(modifier.width(width)) { - Column(Modifier.fillMaxHeight().verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(if (compact) 6.dp else 8.dp)) { - RailButton(Icons.Filled.Route, "任务", compact, true, onMission, active = missionActive) - RailButton(Icons.Filled.Videocam, if (liveStreaming) "关直播" else if (liveBusy) "直播中" else "开直播", compact, true, onToggleLiveStream, active = liveStreaming || liveBusy) - RailButton(Icons.Filled.MoreHoriz, "更多", compact, true, { showMore = !showMore }, active = showMore) - RailButton(Icons.Filled.Home, "返航", compact, true, onReturnHome) - } - if (showMore) { - Popup(alignment = Alignment.TopStart, offset = IntOffset(menuOffset, 0), onDismissRequest = { showMore = false }, properties = PopupProperties(focusable = true)) { - Surface(color = Color(0xE6121B27), shape = RoundedCornerShape(12.dp), modifier = Modifier.width(116.dp).heightIn(max = 240.dp)) { - Column(Modifier.padding(8.dp).verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { - RailButton(Icons.Filled.Shield, "飞前检查", compact, true, { showMore = false; onOpenPreflight() }) - RailButton(if (cameraStyle) Icons.Filled.Map else Icons.Filled.Videocam, if (cameraStyle) "定位信息" else "图传", compact, true, { showMore = false; onSwitchMode() }) - RailButton(Icons.Filled.PowerSettingsNew, if (simulatorEnabled) "关模拟" else "开模拟", compact, true, onToggleSimulator, active = simulatorEnabled) - RailButton(Icons.Filled.Close, "收起", compact, true, { showMore = false }) - } - } - } - } - } -} - -@Composable -private fun RailButton( - icon: ImageVector, - text: String, - compact: Boolean, - dark: Boolean, - onClick: () -> Unit, - active: Boolean = false -) { - val contentColor = when { - active -> PilotGreen - dark -> Color.White - else -> PilotText - } - val labelColor = when { - active -> PilotGreen - dark -> Color(0xFFBDBDBD) - else -> Color(0xFF4A4A4A) - } - Column( - modifier = Modifier - .width(if (compact) 46.dp else 54.dp) - .clip(RoundedCornerShape(7.dp)) - .background(if (active) Color(0xBB144841) else Color(0x7A0B1119)) - .border(1.dp, if (active) PilotGreen.copy(alpha = 0.55f) else Color.White.copy(alpha = 0.10f), RoundedCornerShape(7.dp)) - .clickable(onClick = onClick) - .padding(vertical = if (compact) 4.dp else 5.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(2.dp) - ) { - Icon(icon, null, tint = contentColor, modifier = Modifier.size(if (compact) 22.dp else 26.dp)) - if (text.isNotBlank()) { - Text(text, color = labelColor, fontSize = if (compact) 9.sp else 10.sp, textAlign = TextAlign.Center, maxLines = 1) - } - } -} - - - - - @Composable private fun FocusFrame(compact: Boolean, modifier: Modifier = Modifier) { Box(modifier.size(if (compact) 100.dp else 130.dp)) { @@ -2926,515 +1562,6 @@ private fun FocusFrame(compact: Boolean, modifier: Modifier = Modifier) { } -@Composable -private fun FlightTelemetryHud(telemetry: TelemetrySnapshot, connected: Boolean, compact: Boolean, modifier: Modifier = Modifier) { - val readings = rememberFlightInstrumentReadings(connected, telemetry.cameraComponent) - FlightInstrumentDashboard(readings, compact, modifier) -} - -@Composable -private fun FlightInstrumentDashboard(readings: FlightInstrumentReadings, compact: Boolean, modifier: Modifier = Modifier) { - val headingDegrees = readings.heading ?: 0.0 - val headingValue = readings.heading?.let { "%03d".format(Locale.US, it.roundToInt() % 360) } ?: "—" - BoxWithConstraints(modifier, contentAlignment = Alignment.Center) { - val designWidth = if (compact) 430.dp else 560.dp - val designHeight = if (compact) 122.dp else 168.dp - val scale = minOf(maxWidth / designWidth, maxHeight / designHeight, 1f) - Row( - modifier = Modifier.requiredSize(designWidth, designHeight).graphicsLayer(scaleX = scale, scaleY = scale), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.Center - ) { - SpeedReadout(instrumentNumber(readings.horizontalSpeed), instrumentNumber(readings.windSpeed), compact, Modifier.width(if (compact) 104.dp else 138.dp).fillMaxHeight()) - PitchScale(readings.gimbalPitch, compact, Modifier.width(if (compact) 38.dp else 48.dp).fillMaxHeight()) - CompassInstrument(headingValue, headingDegrees, readings.obstacles, compact, Modifier.size(if (compact) 122.dp else 160.dp)) - AltitudeScale(compact, Modifier.width(if (compact) 30.dp else 40.dp).fillMaxHeight()) - AltitudeReadout(instrumentNumber(readings.relativeAltitude), "${instrumentNumber(readings.seaLevelAltitude)} ASL", instrumentNumber(readings.climbSpeed), readings.obstacles, compact, Modifier.width(if (compact) 136.dp else 174.dp).fillMaxHeight()) - } - } -} - -@Composable -private fun SpeedReadout(value: String, windSpeed: String, compact: Boolean, modifier: Modifier = Modifier) { - val valueSize = if (compact) 29.sp else 38.sp - Box(modifier) { - Text( - "WS $windSpeed", - color = Color.White, - fontSize = if (compact) 12.sp else 15.sp, - fontWeight = FontWeight.Black, - style = TextStyle(shadow = HudTextShadow), - modifier = Modifier.align(Alignment.TopStart).padding(top = if (compact) 14.dp else 24.dp) - ) - Row( - verticalAlignment = Alignment.Bottom, - horizontalArrangement = Arrangement.spacedBy(if (compact) 4.dp else 6.dp), - modifier = Modifier.align(Alignment.CenterStart).padding(top = if (compact) 18.dp else 24.dp) - ) { - Column(horizontalAlignment = Alignment.Start) { - Text( - "SPD", - color = PilotGreen, - fontSize = if (compact) 10.sp else 12.sp, - fontWeight = FontWeight.Black, - lineHeight = if (compact) 9.sp else 11.sp, - style = TextStyle(shadow = HudTextShadow) - ) - Text( - "m/s", - color = PilotGreen, - fontSize = if (compact) 9.sp else 11.sp, - fontWeight = FontWeight.Black, - lineHeight = if (compact) 8.sp else 10.sp, - style = TextStyle(shadow = HudTextShadow) - ) - } - Text( - value, - color = PilotGreen, - fontSize = valueSize, - fontWeight = FontWeight.Black, - maxLines = 1, - style = TextStyle(shadow = HudTextShadow) - ) - } - } -} - -@Composable -private fun PitchScale(pitch: Double?, compact: Boolean, modifier: Modifier = Modifier) { - Box(modifier.semantics { contentDescription = "云台俯仰角 ${instrumentNumber(pitch, 0)} 度" }, contentAlignment = Alignment.Center) { - Text( - "${instrumentNumber(pitch, 0)}°", - color = Color(0xFFFFC400), - fontSize = if (compact) 14.sp else 17.sp, - fontWeight = FontWeight.Black, - style = TextStyle(shadow = HudTextShadow), - modifier = Modifier.align(Alignment.CenterStart).offset(y = if (compact) (-24).dp else (-34).dp) - ) - Canvas(Modifier.fillMaxHeight(0.66f).width(if (compact) 8.dp else 10.dp).align(Alignment.CenterEnd)) { - val railX = size.width / 2f - drawRoundRect( - color = Color(0x990F1112), - topLeft = Offset(railX - size.width * 0.36f, 0f), - size = Size(size.width * 0.72f, size.height), - cornerRadius = CornerRadius(2f, 2f) - ) - drawLine(Color(0xAAFFFFFF), Offset(railX, 0f), Offset(railX, size.height), 1.5f) - for (step in 0..4) { - val y = size.height * step / 4f - drawLine(Color(0xAAFFFFFF), Offset(0f, y), Offset(size.width, y), 1.5f) - } - } - Canvas(Modifier.size(width = if (compact) 13.dp else 16.dp, height = if (compact) 8.dp else 9.dp).align(Alignment.CenterEnd).offset(x = if (compact) 7.dp else 8.dp, y = (-(pitch ?: 0.0).coerceIn(-90.0, 90.0) / 90.0 * if (compact) 35 else 44).dp)) { - val marker = Path().apply { - moveTo(0f, 0f) - lineTo(size.width, size.height / 2f) - lineTo(0f, size.height) - close() - } - if (pitch != null && pitch.isFinite()) drawPath(marker, Color(0xFF13D8FF)) - } - } -} - -@Composable -private fun CompassInstrument(headingText: String, headingDegrees: Double, obstacles: InstrumentObstacles, compact: Boolean, modifier: Modifier = Modifier) { - val red = Color(0xFFFF3333) - Box(modifier, contentAlignment = Alignment.Center) { - Canvas(Modifier.fillMaxSize()) { - val center = Offset(size.width / 2f, size.height / 2f) - val outerRadius = size.minDimension * 0.47f - val ringRadius = outerRadius * 0.78f - val textRadius = outerRadius * 0.84f - val headingOffset = -headingDegrees - - drawCircle(Color(0xF0121212), outerRadius, center) - drawCircle(Color(0xDD28231F), outerRadius * 0.72f, center) - drawCircle(Color(0x55323A40), outerRadius * 0.46f, center, style = Stroke(1.6f)) - drawCircle(Color(0x55323A40), outerRadius * 0.28f, center, style = Stroke(1.2f)) - drawLine(Color(0x662D343A), Offset(center.x - ringRadius, center.y), Offset(center.x + ringRadius, center.y), 1.4f) - drawLine(Color(0x662D343A), Offset(center.x, center.y - ringRadius), Offset(center.x, center.y + ringRadius), 1.4f) - - for (i in 0 until 36) { - val angle = i * 10.0 + headingOffset - val radians = (angle - 90.0) * PI / 180.0 - val tickOuter = outerRadius * 0.95f - val tickInner = outerRadius * if (i % 3 == 0) 0.82f else 0.88f - val start = Offset( - center.x + (cos(radians) * tickInner).toFloat(), - center.y + (sin(radians) * tickInner).toFloat() - ) - val end = Offset( - center.x + (cos(radians) * tickOuter).toFloat(), - center.y + (sin(radians) * tickOuter).toFloat() - ) - drawLine(Color(0xCCF2F2F2), start, end, if (i % 3 == 0) 2.1f else 1.1f, StrokeCap.Round) - } - - val aircraft = Path().apply { - moveTo(center.x, center.y - outerRadius * 0.22f) - lineTo(center.x - outerRadius * 0.12f, center.y + outerRadius * 0.18f) - lineTo(center.x, center.y + outerRadius * 0.08f) - lineTo(center.x + outerRadius * 0.12f, center.y + outerRadius * 0.18f) - close() - } - drawPath(aircraft, Color.White) - - drawIntoCanvas { canvas -> - val nativeCanvas = canvas.nativeCanvas - fun drawCompassLabel(text: String, baseAngle: Double, radius: Float, textSize: Float, color: Color) { - val rotatedAngle = baseAngle + headingOffset - val radians = (rotatedAngle - 90.0) * PI / 180.0 - val x = center.x + (cos(radians) * radius).toFloat() - val y = center.y + (sin(radians) * radius).toFloat() + textSize * 0.36f - val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - this.color = Color.Black.toArgb() - this.textAlign = Paint.Align.CENTER - this.textSize = textSize - this.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) - this.style = Paint.Style.STROKE - this.strokeWidth = textSize * 0.14f - } - val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - this.color = color.toArgb() - this.textAlign = Paint.Align.CENTER - this.textSize = textSize - this.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) - } - nativeCanvas.drawText(text, x, y, strokePaint) - nativeCanvas.drawText(text, x, y, fillPaint) - } - - val smallText = if (compact) 7.8.sp.toPx() else 9.8.sp.toPx() - (30..330 step 30).filter { it % 90 != 0 }.forEach { angle -> - drawCompassLabel((angle / 10).toString(), angle.toDouble(), textRadius, smallText, Color.White) - } - listOf("N" to 0.0, "E" to 90.0, "S" to 180.0, "W" to 270.0).forEach { (label, angle) -> - drawCompassLabel(label, angle, outerRadius * 0.84f, if (compact) 10.sp.toPx() else 13.sp.toPx(), Color.White) - } - } - } - Text( - headingText, - color = PilotGreen, - fontSize = if (compact) 16.sp else 20.sp, - fontWeight = FontWeight.Black, - style = TextStyle(shadow = HudTextShadow), - modifier = Modifier.align(Alignment.TopCenter).offset(y = if (compact) (-8).dp else (-10).dp) - ) - Box( - modifier = Modifier - .align(Alignment.TopCenter) - .offset(y = if (compact) 19.dp else 25.dp) - .size(width = if (compact) 8.dp else 10.dp, height = if (compact) 12.dp else 15.dp) - .clip(RoundedCornerShape(2.dp)) - .background(Color(0xFF10CFFF)) - ) - ObstacleReadout(obstacles.front, "前方", compact, Modifier.align(Alignment.TopCenter).offset(y = if (compact) 31.dp else 40.dp)) - ObstacleReadout(obstacles.left, "左方", compact, Modifier.align(Alignment.CenterStart).offset(x = if (compact) 27.dp else 35.dp)) - ObstacleReadout(obstacles.right, "右方", compact, Modifier.align(Alignment.CenterEnd).offset(x = if (compact) (-27).dp else (-35).dp)) - ObstacleReadout(obstacles.back, "后方", compact, Modifier.align(Alignment.BottomCenter).offset(y = if (compact) (-28).dp else (-36).dp)) - } -} - -@Composable -private fun AltitudeScale(compact: Boolean, modifier: Modifier = Modifier) { - Box(modifier, contentAlignment = Alignment.Center) { - Canvas(Modifier.fillMaxHeight(0.66f).width(if (compact) 8.dp else 10.dp).align(Alignment.CenterStart)) { - val railX = size.width / 2f - drawRoundRect( - color = Color(0x990F1112), - topLeft = Offset(railX - size.width * 0.36f, 0f), - size = Size(size.width * 0.72f, size.height), - cornerRadius = CornerRadius(2f, 2f) - ) - drawLine(Color(0xAAFFFFFF), Offset(railX, 0f), Offset(railX, size.height), 1.5f) - for (step in 0..4) { - val y = size.height * step / 4f - drawLine(Color(0xAAFFFFFF), Offset(0f, y), Offset(size.width, y), 1.5f) - } - } - Box(Modifier.width(if (compact) 12.dp else 16.dp).height(2.dp).align(Alignment.CenterStart).offset(x = (-4).dp).background(Color(0xFFADB8C6))) - } -} - -@Composable -private fun AltitudeReadout(value: String, aslValue: String, climbSpeed: String, obstacles: InstrumentObstacles, compact: Boolean, modifier: Modifier = Modifier) { - val red = Color(0xFFFF3333) - Box(modifier) { - Row( - modifier = Modifier.align(Alignment.TopStart).padding(top = if (compact) 13.dp else 22.dp).fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - ObstacleReadout(obstacles.up, "上方", compact) - Text("$climbSpeed VS", color = Color.White, fontSize = if (compact) 12.sp else 15.sp, fontWeight = FontWeight.Black, style = TextStyle(shadow = HudTextShadow)) - } - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(if (compact) 4.dp else 6.dp), - modifier = Modifier.align(Alignment.CenterStart).padding(top = if (compact) 18.dp else 24.dp) - ) { - Text( - value, - color = PilotGreen, - fontSize = if (compact) 29.sp else 38.sp, - fontWeight = FontWeight.Black, - maxLines = 1, - style = TextStyle(shadow = HudTextShadow) - ) - Column(horizontalAlignment = Alignment.Start) { - Text("ALT", color = PilotGreen, fontSize = if (compact) 10.sp else 12.sp, fontWeight = FontWeight.Black, lineHeight = if (compact) 10.sp else 12.sp, style = TextStyle(shadow = HudTextShadow)) - Text("m", color = PilotGreen, fontSize = if (compact) 9.sp else 11.sp, fontWeight = FontWeight.Black, lineHeight = if (compact) 9.sp else 11.sp, style = TextStyle(shadow = HudTextShadow)) - } - } - Row( - modifier = Modifier.align(Alignment.BottomStart).padding(bottom = if (compact) 14.dp else 22.dp).fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - ObstacleReadout(obstacles.down, "下方", compact) - Text(aslValue, color = Color.White, fontSize = if (compact) 12.sp else 15.sp, fontWeight = FontWeight.Black, style = TextStyle(shadow = HudTextShadow)) - } - } -} - -@Composable -private fun HudValue( - label: String, - unit: String, - value: String, - top: String, - compact: Boolean, - active: Boolean, - modifier: Modifier = Modifier -) { - val valueColor = if (active) PilotGreen else Color(0xFF9CA3AF) - val topColor = if (active) Color.White else Color(0xFF9CA3AF) - Column( - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.Center, - modifier = modifier.fillMaxHeight() - ) { - Text(top, color = topColor, fontSize = if (compact) 9.sp else 11.sp, fontWeight = FontWeight.Black, maxLines = 1) - Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.Center) { - Column(horizontalAlignment = Alignment.End) { - Text(label, color = valueColor, fontSize = if (compact) 9.sp else 10.sp, fontWeight = FontWeight.Black, lineHeight = 10.sp) - Text(unit, color = valueColor, fontSize = if (compact) 8.sp else 9.sp, fontWeight = FontWeight.Bold, lineHeight = 9.sp) - } - Spacer(Modifier.width(4.dp)) - Text(value, color = valueColor, fontSize = if (compact) 26.sp else 33.sp, fontWeight = FontWeight.Black, maxLines = 1) - } - } -} - -@Composable -private fun CompassHud(heading: Double?, compact: Boolean, modifier: Modifier = Modifier) { - val active = heading != null - val muted = Color(0xFF9CA3AF) - val direction = headingCardinal(heading) - Box(modifier.fillMaxHeight(), contentAlignment = Alignment.Center) { - val compassSize = if (compact) 88.dp else 110.dp - Box(Modifier.size(compassSize), contentAlignment = Alignment.Center) { - Canvas(Modifier.fillMaxSize()) { - val center = Offset(size.width / 2f, size.height / 2f) - drawCircle(Color(0xEE1D2023), radius = size.minDimension / 2f) - drawCircle(Color(0x663B444C), radius = size.minDimension / 2.4f, style = Stroke(2.5f)) - drawLine(PilotGreen.copy(alpha = if (active) 0.9f else 0.25f), Offset(center.x, 8f), Offset(center.x, 22f), 4f, StrokeCap.Round) - drawLine(Color(0x55FFFFFF), Offset(8f, center.y), Offset(22f, center.y), 2f, StrokeCap.Round) - drawLine(Color(0x55FFFFFF), Offset(size.width - 8f, center.y), Offset(size.width - 22f, center.y), 2f, StrokeCap.Round) - val path = Path().apply { - moveTo(center.x, size.height * 0.24f) - lineTo(size.width * 0.43f, size.height * 0.58f) - lineTo(center.x, size.height * 0.50f) - lineTo(size.width * 0.57f, size.height * 0.58f) - close() - } - drawPath(path, if (active) Color.White else muted) - } - Text( - heading?.toInt()?.toString() ?: "--", - color = if (active) PilotGreen else muted, - fontSize = if (compact) 11.sp else 13.sp, - fontWeight = FontWeight.Black, - modifier = Modifier.align(Alignment.TopCenter).padding(top = 5.dp) - ) - Text( - direction, - color = if (active) Color.White else muted, - fontSize = if (compact) 17.sp else 21.sp, - fontWeight = FontWeight.Black, - modifier = Modifier.align(Alignment.Center) - ) - Text( - "N", - color = if (active) PilotGreen else muted, - fontSize = if (compact) 10.sp else 12.sp, - fontWeight = FontWeight.Bold, - modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 5.dp) - ) - } - } -} - -@Composable -private fun RightCameraRail( - width: Dp, - connected: Boolean, - recording: Boolean, - laserFillLightEnabled: Boolean, - selectedAction: CameraQuickAction, - compact: Boolean, - onOpenActionPicker: () -> Unit, - onShutter: () -> Unit, - modifier: Modifier = Modifier -) { - Surface( - color = Color.Transparent, - shape = RoundedCornerShape(topStart = 10.dp, bottomStart = 10.dp), - modifier = modifier - .width(width) - .height(if (compact) 148.dp else 174.dp) - ) { - Column( - modifier = Modifier.fillMaxSize().padding(vertical = if (compact) 4.dp else 6.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.SpaceEvenly - ) { - CameraRailIcon( - icon = selectedAction.icon(), - label = selectedAction.displayLabel(recording), - tint = selectedAction.tint(recording, laserFillLightEnabled), - compact = compact, - enabled = connected, - onClick = onOpenActionPicker - ) - CameraShutterButton( - enabled = connected, - action = selectedAction, - recording = recording, - laserFillLightEnabled = laserFillLightEnabled, - compact = compact, - onClick = onShutter - ) - Text( - selectedAction.statusLabel(recording, laserFillLightEnabled), - color = Color(0xFFBDBDBD), - fontSize = if (compact) 8.sp else 9.sp, - fontWeight = FontWeight.Bold, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - textAlign = TextAlign.Center, - modifier = Modifier.width(width - 8.dp) - ) - } - } -} - -@OptIn(ExperimentalLayoutApi::class) -@Composable -private fun CameraActionPicker( - selectedAction: CameraQuickAction, - recording: Boolean, - laserFillLightEnabled: Boolean, - compact: Boolean, - onSelect: (CameraQuickAction) -> Unit, - onDismiss: () -> Unit, - modifier: Modifier = Modifier -) { - Surface( - color = Color(0xF7FFFFFF), - shape = RoundedCornerShape(10.dp), - shadowElevation = 8.dp, - border = BorderStroke(1.dp, Color(0xFFE7EAEE)), - modifier = modifier.width(if (compact) 260.dp else 318.dp) - ) { - Column( - modifier = Modifier.padding(if (compact) 10.dp else 14.dp), - verticalArrangement = Arrangement.spacedBy(if (compact) 8.dp else 10.dp) - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - modifier = Modifier.fillMaxWidth() - ) { - Text("相机动作", color = PilotText, fontSize = if (compact) 16.sp else 18.sp, fontWeight = FontWeight.Black) - IconButton(onClick = onDismiss, modifier = Modifier.size(if (compact) 30.dp else 34.dp)) { - Icon(Icons.Filled.Close, null, tint = PilotMuted, modifier = Modifier.size(if (compact) 18.dp else 20.dp)) - } - } - FlowRow( - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp) - ) { - CameraActionChoice(CameraQuickAction.Photo, selectedAction, recording, laserFillLightEnabled, compact, onSelect) - CameraActionChoice(CameraQuickAction.Video, selectedAction, recording, laserFillLightEnabled, compact, onSelect) - CameraActionChoice(CameraQuickAction.LaserFillLight, selectedAction, recording, laserFillLightEnabled, compact, onSelect) - CameraActionChoice(CameraQuickAction.Panorama, selectedAction, recording, laserFillLightEnabled, compact, onSelect) - } - } - } -} - -@Composable -private fun CameraActionChoice( - action: CameraQuickAction, - selectedAction: CameraQuickAction, - recording: Boolean, - laserFillLightEnabled: Boolean, - compact: Boolean, - onSelect: (CameraQuickAction) -> Unit -) { - val selected = action == selectedAction - Surface( - color = if (selected) Color(0xFFFFF4E5) else Color.White, - contentColor = if (selected) PilotOrange else PilotText, - shape = RoundedCornerShape(8.dp), - border = BorderStroke(1.dp, if (selected) PilotOrange else Color(0xFFE1E5EA)), - modifier = Modifier - .size(width = if (compact) 114.dp else 138.dp, height = if (compact) 58.dp else 66.dp) - .clickable { onSelect(action) } - ) { - Row( - modifier = Modifier.padding(horizontal = 10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp) - ) { - Icon(action.icon(), null, tint = action.choiceTint(recording, laserFillLightEnabled), modifier = Modifier.size(if (compact) 22.dp else 25.dp)) - Text(action.displayLabel(recording), fontSize = if (compact) 13.sp else 15.sp, fontWeight = FontWeight.Black, maxLines = 1) - } - } -} - -@Composable -private fun CameraRailIcon( - icon: ImageVector, - label: String?, - tint: Color, - compact: Boolean, - enabled: Boolean = true, - onClick: () -> Unit -) { - val content = if (enabled) tint else Color(0xFF7D8288) - Column( - modifier = Modifier - .size(width = if (compact) 48.dp else 56.dp, height = if (label == null) if (compact) 34.dp else 40.dp else if (compact) 50.dp else 58.dp) - .clip(RoundedCornerShape(10.dp)) - .background(Color(0x7A0B1119)) - .border(1.dp, Color.White.copy(alpha = 0.10f), RoundedCornerShape(10.dp)) - .clickable(enabled = enabled, onClick = onClick), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.Center - ) { - Icon(icon, null, tint = content, modifier = Modifier.size(if (compact) 22.dp else 26.dp)) - if (label != null) { - Spacer(Modifier.height(2.dp)) - Text(label, color = content, fontSize = if (compact) 9.sp else 10.sp, fontWeight = FontWeight.Black, maxLines = 1) - } - } -} - @Composable private fun CameraShutterButton( enabled: Boolean, @@ -3457,7 +1584,7 @@ private fun CameraShutterButton( Surface( shape = CircleShape, color = Color.Transparent, - border = BorderStroke(3.dp, if (enabled) Color.White else disabled), + border = BorderStroke(2.dp, if (enabled) PilotDesign.Ink else PilotDesign.Line), modifier = Modifier.fillMaxSize() ) { Box(contentAlignment = Alignment.Center) { @@ -3493,7 +1620,7 @@ private fun CameraShutterButton( Surface( shape = CircleShape, color = if (enabled) actionColor else disabled, - border = BorderStroke(3.dp, if (enabled) Color.White else disabled), + border = BorderStroke(2.dp, if (enabled) PilotDesign.Ink else PilotDesign.Line), modifier = Modifier.fillMaxSize() ) { if (action != CameraQuickAction.Photo) { @@ -3506,22 +1633,6 @@ private fun CameraShutterButton( } } -private fun CameraQuickAction.displayLabel(recording: Boolean): String = - when (this) { - CameraQuickAction.Photo -> "拍照" - CameraQuickAction.Video -> if (recording) "停止" else "录像" - CameraQuickAction.LaserFillLight -> "蓝光" - CameraQuickAction.Panorama -> "全景" - } - -private fun CameraQuickAction.statusLabel(recording: Boolean, laserFillLightEnabled: Boolean): String = - when (this) { - CameraQuickAction.Photo -> "单拍" - CameraQuickAction.Video -> if (recording) "录像中" else "待录像" - CameraQuickAction.LaserFillLight -> if (laserFillLightEnabled) "已开启" else "已关闭" - CameraQuickAction.Panorama -> "球形全景" - } - private fun CameraQuickAction.icon(): ImageVector = when (this) { CameraQuickAction.Photo -> Icons.Filled.CameraAlt @@ -3538,184 +1649,9 @@ private fun CameraQuickAction.tint(recording: Boolean, laserFillLightEnabled: Bo CameraQuickAction.Panorama -> Color(0xFFFFCC18) } -private fun CameraQuickAction.choiceTint(recording: Boolean, laserFillLightEnabled: Boolean): Color = - when (this) { - CameraQuickAction.Photo -> PilotOrange - CameraQuickAction.Video -> if (recording) PilotDanger else Color(0xFF4D5358) - CameraQuickAction.LaserFillLight -> if (laserFillLightEnabled) PilotBlue else Color(0xFF4D5358) - CameraQuickAction.Panorama -> PilotOrange - } - -@OptIn(ExperimentalLayoutApi::class) -@Composable -private fun MissionPanel( - connected: Boolean, - missionPath: String, - missionId: String, - uploadUpdate: MissionUploadUpdate, - compact: Boolean, - onMissionPathChange: (String) -> Unit, - onMissionIdChange: (String) -> Unit, - onPickMission: () -> Unit, - onUploadMission: () -> Unit, - onGenerateMission: () -> Unit, - onStartMission: () -> Unit, - onPauseMission: () -> Unit, - onResumeMission: () -> Unit, - onStopMission: () -> Unit, - modifier: Modifier = Modifier -) { - Surface(color = Color(0xF8FFFFFF), shape = RoundedCornerShape(10.dp), shadowElevation = 6.dp, modifier = modifier) { - Column( - modifier = Modifier - .padding(if (compact) 10.dp else 14.dp) - .verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(8.dp) - ) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) { - Text("航线库", color = PilotText, fontSize = if (compact) 18.sp else 22.sp, fontWeight = FontWeight.Black) - StatusPill(if (uploadUpdate.completed) "已上传" else "待上传", uploadUpdate.completed) - } - OutlinedTextField( - value = missionPath, - onValueChange = onMissionPathChange, - label = { Text("KMZ/WPML 文件") }, - singleLine = true, - textStyle = MaterialTheme.typography.bodySmall, - modifier = Modifier.fillMaxWidth() - ) - OutlinedTextField( - value = missionId, - onValueChange = onMissionIdChange, - label = { Text("任务 ID") }, - singleLine = true, - textStyle = MaterialTheme.typography.bodySmall, - modifier = Modifier.fillMaxWidth() - ) - if (uploadUpdate.progress > 0.0 || uploadUpdate.completed) { - LinearProgressIndicator( - progress = { uploadUpdate.progress.toFloat().coerceIn(0f, 1f) }, - color = PilotOrange, - trackColor = Color(0xFFE4E4E4), - modifier = Modifier.fillMaxWidth().height(6.dp) - ) - } - if (uploadUpdate.error != null) { - Text(uploadUpdate.error, color = PilotDanger, fontSize = 12.sp, maxLines = 2, overflow = TextOverflow.Ellipsis) - } - Text("航线任务", color = PilotMuted, fontSize = 12.sp, fontWeight = FontWeight.Bold) - FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - ActionButton("选择", Icons.Filled.FolderOpen, Color(0xFF4D5358), compact, onPickMission) - ActionButton("生成", Icons.Filled.Add, Color(0xFF4D5358), compact, onGenerateMission) - ActionButton("上传", Icons.Filled.UploadFile, PilotOrange, compact, onUploadMission) - ActionButton("开始", Icons.Filled.PlayArrow, PilotOrange, compact, onStartMission, enabled = connected) - ActionButton("暂停", Icons.Filled.Pause, Color(0xFF4D5358), compact, onPauseMission) - ActionButton("继续", Icons.Filled.PlayArrow, Color(0xFF4D5358), compact, onResumeMission, enabled = connected) - ActionButton("停止", Icons.Filled.Stop, PilotDanger, compact, onStopMission) - } - Surface(color = Color(0xFFFFF4E5), border = BorderStroke(1.dp, PilotOrange), shape = RoundedCornerShape(8.dp)) { - Row( - modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp) - ) { - Icon(Icons.Filled.Warning, null, tint = PilotOrange, modifier = Modifier.size(18.dp)) - Text( - if (connected) "调试解锁:航线开始/继续会下发飞行动作,请确认现场安全。" else "无人机未连接:航线开始/继续暂不可用。", - color = Color(0xFF7A4B00), - fontSize = if (compact) 11.sp else 12.sp, - fontWeight = FontWeight.Bold - ) - } - } - } - } -} - -@Composable -private fun ActionButton(text: String, icon: ImageVector, color: Color, compact: Boolean, onClick: () -> Unit, enabled: Boolean = true) { - Button( - onClick = onClick, - enabled = enabled, - shape = RoundedCornerShape(7.dp), - colors = ButtonDefaults.buttonColors(containerColor = color), - modifier = Modifier.size(width = if (compact) 86.dp else 96.dp, height = if (compact) 38.dp else 42.dp), - contentPadding = ButtonDefaults.ButtonWithIconContentPadding - ) { - Icon(icon, null, modifier = Modifier.size(14.dp)) - Spacer(Modifier.width(3.dp)) - Text(text, fontSize = 11.sp, fontWeight = FontWeight.Bold, maxLines = 1) - } -} - -@Composable -private fun StatusPill(text: String, active: Boolean) { - Surface(shape = RoundedCornerShape(999.dp), color = if (active) Color(0xFFE7F7EF) else Color(0xFFFFF4E5)) { - Text( - text, - color = if (active) Color(0xFF027A48) else PilotOrange, - fontSize = 11.sp, - fontWeight = FontWeight.Bold, - modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp) - ) - } -} - -@Composable -private fun StatusBadge(text: String, active: Boolean) { - Surface( - color = if (active) Color(0xFFE7F7EF) else Color(0xFFFFF4E5), - contentColor = if (active) Color(0xFF027A48) else PilotOrange, - shape = RoundedCornerShape(999.dp), - border = BorderStroke(1.dp, if (active) Color(0xFFABEFC6) else Color(0xFFFEC84B)) - ) { - Text(text, fontSize = 12.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp)) - } -} - private fun horizontalSpeed(snapshot: TelemetrySnapshot): Double = sqrt(snapshot.speedX * snapshot.speedX + snapshot.speedY * snapshot.speedY) -private fun batteryStatusText(connected: Boolean, telemetry: TelemetrySnapshot): String { - if (!connected) return "--" - return "${batteryPercentText(connected, telemetry)} ${batteryVoltageText(connected, telemetry)}" -} - -private fun batteryPercentText(connected: Boolean, telemetry: TelemetrySnapshot): String = - if (connected && telemetry.batteryPercent in 0..100) "${telemetry.batteryPercent}%" else "--" - -private fun batteryVoltageText(connected: Boolean, telemetry: TelemetrySnapshot): String = - if (connected && telemetry.batteryVoltageMv > 0) { - "%.1fV".format(Locale.US, telemetry.batteryVoltageMv / 1000.0) - } else { - "--" - } - -private fun rtkStatusText(connected: Boolean, telemetry: TelemetrySnapshot): String = - when { - !connected -> "RTK --" - !telemetry.rtkEnabled -> "RTK 关" - telemetry.hasReliableRtkPosition() -> "RTK 正常" - telemetry.rtkWorking || telemetry.rtkBeingUsed || telemetry.rtkSatelliteCount > 0 -> "RTK 收敛" - else -> "RTK 未就绪" - } - -private fun rtkStatusColor(connected: Boolean, telemetry: TelemetrySnapshot): Color = - when { - !connected -> PilotMuted - !telemetry.rtkEnabled -> PilotMuted - telemetry.hasReliableRtkPosition() -> PilotGreen - telemetry.rtkWorking || telemetry.rtkBeingUsed || telemetry.rtkSatelliteCount > 0 -> PilotOrange - else -> PilotDanger - } - -private fun rtkSatelliteText(connected: Boolean, telemetry: TelemetrySnapshot): String = - when { - !connected -> "--" - !telemetry.rtkEnabled -> "关" - else -> telemetry.rtkSatelliteCount.coerceAtLeast(0).toString() - } - private fun effectiveCommandMessage(sdkState: DroneSdkState, rawMessage: String): String { val passiveMessage = rawMessage.isBlank() || rawMessage.contains("等待设备") || @@ -3759,13 +1695,6 @@ private fun effectiveAlertState(sdkState: DroneSdkState, warningState: DroneWarn else -> DroneWarningState(message = "无实时告警") } -private fun effectiveAlertCount(alertState: DroneWarningState): Int = - when { - alertState.count > 0 -> alertState.count - alertState.active -> alertState.messages.size.coerceAtLeast(1) - else -> 0 - } - private fun flightTopStatusText( sdkState: DroneSdkState, telemetry: TelemetrySnapshot, @@ -3994,16 +1923,6 @@ private fun flightModeDisplayText(mode: String): String { private fun String.hasChineseText(): Boolean = any { it in '\u4e00'..'\u9fff' } -private fun alertBannerColor(alertState: DroneWarningState): Color = - when (alertState.level) { - WarningLevel.SERIOUS_WARNING, - WarningLevel.WARNING -> PilotDanger - WarningLevel.CAUTION, - WarningLevel.NOTICE, - WarningLevel.UNKNOWN -> PilotOrange - WarningLevel.NORMAL -> Color(0xFF30363B) - } - private fun sdkInitDisplayText(sdkState: DroneSdkState): String = when (sdkState.initEvent) { "REGISTER_SUCCESS" -> "SDK 已注册" @@ -4018,39 +1937,3 @@ private fun sdkInitDisplayText(sdkState: DroneSdkState): String = "REGISTER_RETRY_FAILED" -> "重试注册失败" else -> sdkState.initEvent } - -private fun formatLatLng(latitude: Double, longitude: Double): String = - "%.6f, %.6f".format(Locale.US, latitude, longitude) - -private fun normalizeHeading(heading: Double): Double = - ((heading % 360.0) + 360.0) % 360.0 - -private fun headingCardinal(heading: Double?): String { - if (heading == null) return "--" - val normalized = normalizeHeading(heading) - val directions = listOf("N", "NE", "E", "SE", "S", "SW", "W", "NW") - val index = ((normalized / 45.0).roundToInt()) % directions.size - return directions[index] -} - - -@Composable -private fun ObstacleReadout(distance: Double?, direction: String, compact: Boolean, modifier: Modifier = Modifier) { - val value = if (distance == null) "NA" else instrumentNumber(distance) - Text(value, color = if (distance == null) PilotDanger else Color.White, - fontSize = if (compact) 11.sp else 14.sp, fontWeight = FontWeight.Black, - style = TextStyle(shadow = HudTextShadow), maxLines = 1, - modifier = modifier.semantics { contentDescription = "$direction 障碍物距离 ${if (distance == null) "不可用" else "$value 米"}" }) -} - -@Preview(name = "Flight instrument · live sample", widthDp = 440, heightDp = 166) -@Composable -private fun FlightInstrumentPreview() { - Box(Modifier.fillMaxSize().background(Color(0xFF65716B)), contentAlignment = Alignment.Center) { - FlightInstrumentDashboard( - FlightInstrumentReadings(relativeAltitude = 30.0, seaLevelAltitude = 116.8, heading = 189.0, - horizontalSpeed = 0.0, climbSpeed = 0.0, windSpeed = 2.3, gimbalPitch = -12.0), - compact = true, modifier = Modifier.fillMaxSize().padding(12.dp) - ) - } -} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/MissionPreviewState.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/MissionPreviewState.kt new file mode 100644 index 0000000..15148af --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/MissionPreviewState.kt @@ -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 +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotCloudScreen.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotCloudScreen.kt new file mode 100644 index 0000000..9cb4bfc --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotCloudScreen.kt @@ -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, 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)) + } + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotDesign.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotDesign.kt new file mode 100644 index 0000000..3f8b8f6 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotDesign.kt @@ -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) diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotDeviceReadings.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotDeviceReadings.kt new file mode 100644 index 0000000..19d2563 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotDeviceReadings.kt @@ -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 observe(key: DJIKey, 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 +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotFlightChrome.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotFlightChrome.kt new file mode 100644 index 0000000..6ab362d --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotFlightChrome.kt @@ -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("关闭") } }) +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotHomeScreen.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotHomeScreen.kt index b13eb69..4c11c8c 100644 --- a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotHomeScreen.kt +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotHomeScreen.kt @@ -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)) { - 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) + 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)) - HomeConnectionBadge(if (sdkState.productLinkConnected) "遥控器已连接" else "等待连接遥控器", sdkState.productLinkConnected) + 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(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.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) { - 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)) + PilotStatus(if (connected) "已连接" else "未连接", connected) } - 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) - } - } - 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) + 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.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)) { - 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) - Spacer(Modifier.weight(1f)) - Text(if (cloudConnected) "已连接" else "未连接", color = if (cloudConnected) HomeOnline else HomeSecondary, fontSize = 12.sp) + 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 = 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(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) } - 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) + 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 "—")) } } } - 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) + PilotCard(Modifier.weight(0.92f).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 && telemetry.hasReliableRtkPosition()) "RTK 固定" else if (connected && telemetry.rtkEnabled) "等待 RTK" else "RTK 未启用", connected && telemetry.hasReliableRtkPosition()) + } + Spacer(Modifier.weight(1f)) + 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) + } + Spacer(Modifier.weight(1f)) + 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) - } -} - -@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) +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) + } + 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) + } } diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotLoginScreen.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotLoginScreen.kt new file mode 100644 index 0000000..e847f54 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotLoginScreen.kt @@ -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() + } + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMap.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMap.kt new file mode 100644 index 0000000..345b9e1 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMap.kt @@ -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(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(null) } + var annotations by remember { mutableStateOf>(emptyList()) } + var aircraftMarker by remember { mutableStateOf(null) } + var homeMarker by remember { mutableStateOf(null) } + var rcMarker by remember { mutableStateOf(null) } + val aircraftIcons = remember { mutableMapOf() } + 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(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() + 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 +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMapLocations.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMapLocations.kt new file mode 100644 index 0000000..bdac09e --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMapLocations.kt @@ -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) + } + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMapSettings.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMapSettings.kt new file mode 100644 index 0000000..d344cf2 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMapSettings.kt @@ -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(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 MapChoice(label: String, value: T, options: List>, 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 }) } + } + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMediaDialog.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMediaDialog.kt new file mode 100644 index 0000000..8aff893 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMediaDialog.kt @@ -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(null) } + val files by produceState(emptyList(), 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(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, "关闭照片预览") } } + } + } + } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMissionExecution.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMissionExecution.kt new file mode 100644 index 0000000..b32c0ce --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMissionExecution.kt @@ -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 +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMissionPanel.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMissionPanel.kt new file mode 100644 index 0000000..819eef0 --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotMissionPanel.kt @@ -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) } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotPreflightScreen.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotPreflightScreen.kt index 7650815..3eacbcd 100644 --- a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotPreflightScreen.kt +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotPreflightScreen.kt @@ -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) + } + 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) } - IconButton(onClick = onClose) { Icon(Icons.Filled.Close, "关闭飞前检查", tint = Color.White) } } - 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>, 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>, 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)) + } } } } } diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/PilotVendorMap.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotVendorMap.kt new file mode 100644 index 0000000..9763ddd --- /dev/null +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/PilotVendorMap.kt @@ -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(null) + val baiduError = MutableStateFlow(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, zoom: Float) + fun zoom(inside: Boolean) + fun north() + fun mission(points: List) + 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() + 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, 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) { + 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() + 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() + 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, 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) { + 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()) } +} diff --git a/sample/src/main/java/com/zklh/dronecontroller/ui/Theme.kt b/sample/src/main/java/com/zklh/dronecontroller/ui/Theme.kt index 98f64be..4b23fd9 100644 --- a/sample/src/main/java/com/zklh/dronecontroller/ui/Theme.kt +++ b/sample/src/main/java/com/zklh/dronecontroller/ui/Theme.kt @@ -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 ) } diff --git a/sample/src/main/res/drawable-nodpi/pilot_aircraft_reference.png b/sample/src/main/res/drawable-nodpi/pilot_aircraft_reference.png new file mode 100644 index 0000000..ae38f82 Binary files /dev/null and b/sample/src/main/res/drawable-nodpi/pilot_aircraft_reference.png differ diff --git a/sample/src/test/java/com/zklh/dronecontroller/core/map/MapConfigurationTest.kt b/sample/src/test/java/com/zklh/dronecontroller/core/map/MapConfigurationTest.kt new file mode 100644 index 0000000..2074148 --- /dev/null +++ b/sample/src/test/java/com/zklh/dronecontroller/core/map/MapConfigurationTest.kt @@ -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)) + } +} diff --git a/sample/src/test/java/com/zklh/dronecontroller/core/map/MapLivePositionsTest.kt b/sample/src/test/java/com/zklh/dronecontroller/core/map/MapLivePositionsTest.kt new file mode 100644 index 0000000..c995950 --- /dev/null +++ b/sample/src/test/java/com/zklh/dronecontroller/core/map/MapLivePositionsTest.kt @@ -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)) + } +} diff --git a/sample/src/test/java/com/zklh/dronecontroller/core/map/PlatformMapTest.kt b/sample/src/test/java/com/zklh/dronecontroller/core/map/PlatformMapTest.kt new file mode 100644 index 0000000..b7b2e66 --- /dev/null +++ b/sample/src/test/java/com/zklh/dronecontroller/core/map/PlatformMapTest.kt @@ -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() + 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) + } +} diff --git a/sample/src/test/java/com/zklh/dronecontroller/core/map/TiandituMapSourceTest.kt b/sample/src/test/java/com/zklh/dronecontroller/core/map/TiandituMapSourceTest.kt new file mode 100644 index 0000000..4629917 --- /dev/null +++ b/sample/src/test/java/com/zklh/dronecontroller/core/map/TiandituMapSourceTest.kt @@ -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}&")) + } + } +} diff --git a/sample/src/test/java/com/zklh/dronecontroller/core/mission/MissionPreviewReaderTest.kt b/sample/src/test/java/com/zklh/dronecontroller/core/mission/MissionPreviewReaderTest.kt new file mode 100644 index 0000000..766f14b --- /dev/null +++ b/sample/src/test/java/com/zklh/dronecontroller/core/mission/MissionPreviewReaderTest.kt @@ -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 = """ + goHomegoBack + 5relativeToStartPoint + 121.0,31.00100 + 121.0,31.0011120 + """ + + @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("", "130,40")) + 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("]>" + 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() } + } +} diff --git a/sample/src/test/java/com/zklh/dronecontroller/core/telemetry/LocationFixTrackerTest.kt b/sample/src/test/java/com/zklh/dronecontroller/core/telemetry/LocationFixTrackerTest.kt new file mode 100644 index 0000000..2bd830c --- /dev/null +++ b/sample/src/test/java/com/zklh/dronecontroller/core/telemetry/LocationFixTrackerTest.kt @@ -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)) + } +} diff --git a/sample/src/test/resources/platform-layers.json b/sample/src/test/resources/platform-layers.json new file mode 100644 index 0000000..87da0ed --- /dev/null +++ b/sample/src/test/resources/platform-layers.json @@ -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}" + } +] \ No newline at end of file