docs(project): 更新项目说明文档并添加相机遥测功能
- 重写 AGENTS.md 为 drone-controller-v5 项目说明与打包指南 - 添加系统概述、项目结构、开发环境和关键配置说明 - 补充 Android Studio 和命令行打包 APK 详细步骤 - 增加签名说明、安装指导和打包前检查清单 - 添加常用构建命令、代码规范和验证建议 - 新增 CameraCloudTelemetry 类用于读取相机遥测数据 - 添加 CameraStreamCapabilities 类获取相机流能力 - 实现 CloudCameraValues 映射 SDK 枚举到云端协议 - 添加云端绑定响应验证功能和单元测试 - 集成紧急停止和航线暂停恢复云控命令 - 重构航线任务管理为独立的 CloudWaylineService
This commit is contained in:
@@ -2,6 +2,7 @@ apply plugin: 'com.android.application'
|
||||
apply plugin: 'kotlin-android'
|
||||
apply plugin: 'kotlin-kapt'
|
||||
apply plugin: 'org.jetbrains.kotlin.plugin.compose'
|
||||
apply from: 'deployment-config.gradle'
|
||||
|
||||
android {
|
||||
namespace "dji.sampleV5.aircraft"
|
||||
@@ -111,6 +112,8 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation "junit:junit:4.13.2"
|
||||
testImplementation "org.json:json:20210307"
|
||||
/** <-----------------依赖MSDK--------------------> **/
|
||||
compileOnly deps.aircraftProvided
|
||||
implementation deps.aircraft
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// deployment.properties is the only source for app deployment addresses.
|
||||
def configFile = rootProject.file(project.findProperty('deploymentConfig') ?: 'deployment.properties')
|
||||
if (!configFile.isFile()) throw new GradleException("Deployment config not found: ${configFile}")
|
||||
def deployment = new Properties()
|
||||
configFile.withReader('UTF-8') { deployment.load(it) }
|
||||
def required = { String key ->
|
||||
def value = deployment.getProperty(key, '').trim()
|
||||
if (!value) throw new GradleException("${configFile.name}: ${key} must not be empty")
|
||||
value
|
||||
}
|
||||
def validateHost = { String host ->
|
||||
// Host names and IPv4 only; reject URL syntax and XML metacharacters.
|
||||
if (!(host ==~ /[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?/)) {
|
||||
throw new GradleException("Invalid deployment host '${host}': use an IP or domain without scheme, port or path")
|
||||
}
|
||||
host.toLowerCase(java.util.Locale.ROOT)
|
||||
}
|
||||
def baseUrl = required('CLOUD_BASE_URL')
|
||||
def baseUri
|
||||
try { baseUri = new URI(baseUrl) } catch (Exception e) {
|
||||
throw new GradleException('CLOUD_BASE_URL must be a valid http/https URL', e)
|
||||
}
|
||||
if (!(baseUri.scheme in ['http', 'https']) || !baseUri.host || baseUri.userInfo ||
|
||||
baseUri.query || baseUri.fragment || baseUri.port == 0 || baseUri.port > 65535) {
|
||||
throw new GradleException('CLOUD_BASE_URL must be an http/https URL without credentials, query or fragment')
|
||||
}
|
||||
def platformHost = validateHost(baseUri.host)
|
||||
def fallbackHost = deployment.getProperty('CLOUD_FALLBACK_HOST', '').trim()
|
||||
if (fallbackHost) fallbackHost = validateHost(fallbackHost)
|
||||
def httpHosts = ([platformHost, fallbackHost] + deployment.getProperty('HTTP_EXTRA_HOSTS', '').split(',').toList())
|
||||
.collect { it.trim() }.findAll { it }.collect { validateHost(it) }.unique()
|
||||
def rtmpPortText = required('RTMP_PORT')
|
||||
if (!rtmpPortText.isInteger() || !(rtmpPortText.toInteger() in 1..65535)) {
|
||||
throw new GradleException('RTMP_PORT must be between 1 and 65535')
|
||||
}
|
||||
def rtmpApp = required('RTMP_DEFAULT_APP')
|
||||
if (!(rtmpApp ==~ /[A-Za-z0-9_-]+/)) throw new GradleException('RTMP_DEFAULT_APP must be a single app name')
|
||||
|
||||
android.defaultConfig {
|
||||
buildConfigField 'String', 'CLOUD_BASE_URL', groovy.json.JsonOutput.toJson(baseUrl)
|
||||
buildConfigField 'String', 'CLOUD_PLATFORM_HOST', groovy.json.JsonOutput.toJson(platformHost)
|
||||
buildConfigField 'String', 'CLOUD_FALLBACK_HOST', groovy.json.JsonOutput.toJson(fallbackHost)
|
||||
buildConfigField 'int', 'CLOUD_RTMP_PORT', rtmpPortText.toInteger().toString()
|
||||
buildConfigField 'String', 'CLOUD_RTMP_DEFAULT_APP', groovy.json.JsonOutput.toJson(rtmpApp)
|
||||
}
|
||||
|
||||
def generatedRes = layout.buildDirectory.dir('generated/res/deployment')
|
||||
android.sourceSets.main.res.srcDir(generatedRes)
|
||||
def generateNetworkConfig = tasks.register('generateDeploymentNetworkConfig') {
|
||||
inputs.file(configFile)
|
||||
inputs.property('httpHosts', httpHosts)
|
||||
outputs.dir(generatedRes)
|
||||
doLast {
|
||||
def output = new File(generatedRes.get().asFile, 'xml/network_security_config.xml')
|
||||
output.parentFile.mkdirs()
|
||||
output.setText('''<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated from deployment.properties. Do not edit this build output. -->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="false" />
|
||||
<domain-config cleartextTrafficPermitted="true">
|
||||
''' + httpHosts.collect { ' <domain includeSubdomains="true">' + it + '</domain>' }.join('\n') + '''
|
||||
</domain-config>
|
||||
</network-security-config>
|
||||
''', 'UTF-8')
|
||||
}
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn(generateNetworkConfig) }
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
internal fun validateCloudBindingResponse(body: String) {
|
||||
val response = JSONObject(body)
|
||||
require(response.has("code") && response.optInt("code", -1) == 0) {
|
||||
"设备绑定失败:" + response.optString("message", response.optString("msg", "业务接口未返回成功"))
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import android.content.Context
|
||||
|
||||
import android.util.Log
|
||||
import com.zklh.dronecontroller.core.diagnostics.DroneWarningItem
|
||||
import com.zklh.dronecontroller.core.diagnostics.DroneWarningState
|
||||
@@ -97,7 +99,8 @@ interface CloudMissionProgressPublisher {
|
||||
waylineId: Int = 0,
|
||||
currentWaypointIndex: Int = 0,
|
||||
resultCode: Int = 0,
|
||||
resultMessage: String = "success"
|
||||
resultMessage: String = "success",
|
||||
missionState: Int = 4
|
||||
)
|
||||
|
||||
fun publishPointFlightProgress(
|
||||
@@ -113,6 +116,7 @@ interface CloudMissionProgressPublisher {
|
||||
}
|
||||
|
||||
class CloudCommandExecutor(
|
||||
private val context: Context,
|
||||
private val flightControl: FlightControlService,
|
||||
private val cameraMedia: CameraMediaService,
|
||||
private val flyToService: FlyToService,
|
||||
@@ -128,7 +132,11 @@ class CloudCommandExecutor(
|
||||
) {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
private val virtualStickEnabling = AtomicBoolean(false)
|
||||
private val preparedMissionIds = ConcurrentHashMap<String, String>()
|
||||
private val cloudWaylines by lazy {
|
||||
// Use app cache storage, like the working M350 temporary KMZ upload path.
|
||||
val files = java.io.File(context.applicationContext.cacheDir, "cloud-waylines")
|
||||
CloudWaylineService(waypointMission, progressPublisher, files)
|
||||
}
|
||||
private var lastStickAt = 0L
|
||||
private var lastStickLogAt = 0L
|
||||
private var stickTimeoutJob: Job? = null
|
||||
@@ -188,12 +196,17 @@ class CloudCommandExecutor(
|
||||
command in LaserMeasureCommands -> setLaserMeasure(data)
|
||||
command in FlyToUpdateCommands -> updateFlyTo(data)
|
||||
command in FlyToCommands -> startFlyTo(data, PointFlightProgressKind.FlyToPoint)
|
||||
command == "drone_emergency_stop" -> {
|
||||
val result = flyToService.stopFlyTo()
|
||||
if (result.success) cancelPointFlightProgressMonitors()
|
||||
result
|
||||
}
|
||||
command in StopFlyToCommands -> stopFlyTo()
|
||||
command in WaylinePrepareCommands -> prepareWayline(data)
|
||||
command in WaylineExecuteCommands -> executeWayline(data)
|
||||
command in WaylinePauseCommands -> waypointMission.pauseMission()
|
||||
command in WaylineRecoveryCommands -> waypointMission.resumeMission()
|
||||
command in WaylineUndoCommands -> stopWayline(data)
|
||||
command in WaylinePauseCommands -> cloudWaylines.pause(data)
|
||||
command in WaylineRecoveryCommands -> cloudWaylines.resume(data)
|
||||
command in WaylineUndoCommands -> cloudWaylines.stop(data, command == "flighttask_undo")
|
||||
command in CameraZoomCommands -> setCameraZoom(data)
|
||||
command in LinkageZoomCommands -> setLinkageZoom(data)
|
||||
command in LensSwitchCommands -> switchLens(data)
|
||||
@@ -452,7 +465,8 @@ class CloudCommandExecutor(
|
||||
height = command.height,
|
||||
maxSpeed = command.maxSpeed,
|
||||
securityTakeoffHeight = command.securityTakeoffHeight,
|
||||
flyToMode = command.flyToMode
|
||||
flyToMode = command.flyToMode,
|
||||
commanderFlightHeight = command.commanderFlightHeight
|
||||
)
|
||||
if (result.success) {
|
||||
clearActivePointFlight()
|
||||
@@ -654,7 +668,8 @@ class CloudCommandExecutor(
|
||||
height = command.height,
|
||||
maxSpeed = command.maxSpeed,
|
||||
securityTakeoffHeight = command.securityTakeoffHeight,
|
||||
flyToMode = command.flyToMode
|
||||
flyToMode = command.flyToMode,
|
||||
commanderFlightHeight = command.commanderFlightHeight
|
||||
)
|
||||
Log.d(
|
||||
CloudCommandLogTag,
|
||||
@@ -1198,7 +1213,7 @@ class CloudCommandExecutor(
|
||||
return target
|
||||
}
|
||||
val param = flyToService.updateFlyToParam(
|
||||
height = command.height.roundToInt().coerceAtLeast(1),
|
||||
height = command.commanderFlightHeight?.roundToInt(),
|
||||
mode = command.flyToMode
|
||||
)
|
||||
return if (param.success) {
|
||||
@@ -1252,81 +1267,9 @@ class CloudCommandExecutor(
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun prepareWayline(data: JSONObject): DjiCommandResult {
|
||||
val flightId = data.flightTaskId()
|
||||
val kmzPath = data.optStringAny("kmz_path", "kmzPath", "file_path", "filePath", "path")
|
||||
val fileUrl = data.optKmzFileUrl()
|
||||
val preferredMissionId = data.preferredMissionId(fileUrl)
|
||||
val localKmzPath = when {
|
||||
kmzPath.isNotBlank() -> kmzPath
|
||||
fileUrl.isNotBlank() -> downloadKmz(fileUrl, preferredMissionId)
|
||||
else -> return DjiCommandResult.failed("航线准备失败:未收到 KMZ 本地路径或下载地址")
|
||||
}
|
||||
val upload = waypointMission.uploadKmzFile(localKmzPath)
|
||||
if (!upload.success) return upload
|
||||
val missionId = data.optStringAny("mission_id", "missionId")
|
||||
.ifBlank { waypointMission.missionIdFromPath(localKmzPath) }
|
||||
if (flightId.isNotBlank()) {
|
||||
preparedMissionIds[flightId] = missionId
|
||||
}
|
||||
preparedMissionIds[missionId] = missionId
|
||||
return DjiCommandResult.ok("航线准备完成:$missionId")
|
||||
}
|
||||
private suspend fun prepareWayline(data: JSONObject): DjiCommandResult = cloudWaylines.prepare(data)
|
||||
|
||||
private suspend fun executeWayline(data: JSONObject): DjiCommandResult {
|
||||
var missionId = resolveMissionId(data)
|
||||
if (missionId == null && data.hasKmzFile()) {
|
||||
val prepare = prepareWayline(data)
|
||||
if (!prepare.success) return prepare
|
||||
missionId = resolveMissionId(data)
|
||||
}
|
||||
missionId ?: return DjiCommandResult.failed("航线执行失败:缺少 flight_id 或 mission_id")
|
||||
val result = waypointMission.startMission(missionId, data.optWaylineIds())
|
||||
val flightId = data.flightTaskId().ifBlank { missionId }
|
||||
if (result.success) {
|
||||
progressPublisher?.publishFlightTaskProgress(
|
||||
flightId = flightId,
|
||||
status = "IN_PROGRESS",
|
||||
percent = 1
|
||||
)
|
||||
} else {
|
||||
progressPublisher?.publishFlightTaskProgress(
|
||||
flightId = flightId,
|
||||
status = "FAILED",
|
||||
percent = 0,
|
||||
resultCode = -1,
|
||||
resultMessage = result.message
|
||||
)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private suspend fun stopWayline(data: JSONObject): DjiCommandResult {
|
||||
val missionId = resolveMissionId(data)
|
||||
?: return DjiCommandResult.failed("航线停止失败:缺少 flight_id 或 mission_id")
|
||||
return waypointMission.stopMission(missionId)
|
||||
}
|
||||
|
||||
private fun resolveMissionId(data: JSONObject): String? {
|
||||
val raw = data.optStringAny("mission_id", "missionId", "flight_id", "flightId", "job_id", "jobId")
|
||||
if (raw.isBlank()) return null
|
||||
return preparedMissionIds[raw] ?: raw
|
||||
}
|
||||
|
||||
private fun downloadKmz(fileUrl: String, preferredMissionId: String): String {
|
||||
val safeMissionId = preferredMissionId.toSafeMissionFileStem()
|
||||
val file = if (safeMissionId.isNotBlank()) {
|
||||
File(cloudWaylineTempDirectory(), "$safeMissionId.kmz").also {
|
||||
if (it.exists()) it.delete()
|
||||
}
|
||||
} else {
|
||||
File.createTempFile("cloud-wayline-", ".kmz")
|
||||
}
|
||||
URL(fileUrl).openStream().use { input ->
|
||||
file.outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
return file.absolutePath
|
||||
}
|
||||
private suspend fun executeWayline(data: JSONObject): DjiCommandResult = cloudWaylines.execute(data)
|
||||
|
||||
private suspend fun setCameraZoom(data: JSONObject): DjiCommandResult {
|
||||
val zoomFactor = data.optDoubleAny("zoom_factor", "zoomFactor", "focal_length", "focalLength")
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.w3c.dom.Document
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
import java.util.zip.ZipFile
|
||||
import java.util.zip.ZipInputStream
|
||||
import javax.xml.parsers.DocumentBuilderFactory
|
||||
|
||||
/** Download and stage the original KMZ without changing its XML or ZIP bytes. */
|
||||
object CloudKmzFile {
|
||||
data class Prepared(val file: File, val counts: Map<Int, Int>, val originalFile: File)
|
||||
|
||||
fun prepare(data: JSONObject, flightId: String, directory: File): Prepared {
|
||||
val nested = data.optJSONObject("file")
|
||||
val url = (listOf("file_url", "fileUrl", "url", "kmz_url", "kmzUrl", "wayline_url", "waylineUrl")
|
||||
.map { data.optString(it) } + listOf(nested?.optString("url").orEmpty(), data.optString("file")))
|
||||
.firstOrNull { it.startsWith("https://") || it.startsWith("http://") }
|
||||
val local = listOf("kmz_path", "kmzPath", "file_path", "filePath", "path").map { data.optString(it) }.firstOrNull { it.isNotBlank() }
|
||||
require(url != null || local != null) { "未收到 KMZ 下载地址或本地路径" }
|
||||
require(directory.isDirectory || directory.mkdirs()) { "无法创建航线工作目录:" + directory.absolutePath }
|
||||
require(directory.canRead() && directory.canWrite()) { "航线工作目录不可读写:" + directory.absolutePath }
|
||||
val source = File.createTempFile("cloud-download-", ".kmz", directory)
|
||||
val target = File(source.parentFile, "cloud-" + digest(flightId.toByteArray()) + ".kmz")
|
||||
try {
|
||||
if (local != null) File(local).inputStream().use { input -> source.outputStream().use { input.copyTo(it) } }
|
||||
else {
|
||||
val connection = URL(url!!).openConnection() as HttpURLConnection
|
||||
connection.connectTimeout = 15_000; connection.readTimeout = 30_000
|
||||
try {
|
||||
require(connection.responseCode in 200..299) { "KMZ 下载失败:HTTP " + connection.responseCode }
|
||||
val deadline = System.currentTimeMillis() + 60_000L
|
||||
connection.inputStream.use { input -> source.outputStream().use { output ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
check(System.currentTimeMillis() < deadline) { "KMZ 下载超时" }
|
||||
val size = input.read(buffer)
|
||||
if (size < 0) break
|
||||
output.write(buffer, 0, size)
|
||||
}
|
||||
} }
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
val fingerprint = nested?.optString("fingerprint").orEmpty()
|
||||
if (fingerprint.isNotBlank()) {
|
||||
val md5 = MessageDigest.getInstance("MD5")
|
||||
source.inputStream().use { input -> val buffer=ByteArray(65536); while(true) { val n=input.read(buffer); if(n<0)break; md5.update(buffer,0,n) } }
|
||||
require(md5.digest().joinToString("") { "%02x".format(it) }.equals(fingerprint, true)) { "KMZ 文件校验失败" }
|
||||
}
|
||||
// Consume every entry so truncated ZIP streams and CRC errors fail before invoking MSDK.
|
||||
ZipInputStream(source.inputStream()).use { input ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (input.nextEntry != null) {
|
||||
while (input.read(buffer) >= 0) { /* Read-only archive integrity check. */ }
|
||||
input.closeEntry()
|
||||
}
|
||||
}
|
||||
val counts = linkedMapOf<Int, Int>()
|
||||
ZipFile(source).use { zip ->
|
||||
val entry = requireNotNull(zip.getEntry("wpmz/waylines.wpml")) { "KMZ 缺少 wpmz/waylines.wpml" }
|
||||
val doc = zip.getInputStream(entry).use { parseXml(it) }
|
||||
val folders = doc.getElementsByTagNameNS("*", "Folder")
|
||||
for (i in 0 until folders.length) {
|
||||
val folder = folders.item(i) as org.w3c.dom.Element
|
||||
val id = folder.getElementsByTagNameNS("*", "waylineId").item(0)?.textContent?.toIntOrNull() ?: continue
|
||||
counts[id] = folder.getElementsByTagNameNS("*", "Placemark").length
|
||||
}
|
||||
}
|
||||
require(counts.isNotEmpty() && counts.values.all { it > 0 }) { "KMZ 没有可执行航点" }
|
||||
// Only the local filename changes to identify the cloud job. Never regenerate a downloaded mission.
|
||||
source.copyTo(target, overwrite = true)
|
||||
require(source.length() == target.length() && sha256(source) == sha256(target)) { "KMZ 保存不完整" }
|
||||
require(target.isFile && target.length() > 0 && target.canRead()) { "生成的 KMZ 不可读或为空:" + target.absolutePath }
|
||||
target.inputStream().use { require(it.read() >= 0) { "生成的 KMZ 为空" } }
|
||||
return Prepared(target, counts, source)
|
||||
} catch (e: Exception) { target.delete(); source.delete(); throw e }
|
||||
}
|
||||
|
||||
/** Keep only the most recent SDK upload failure for comparison; never save signed URLs or credentials. */
|
||||
fun preserveFailure(prepared: Prepared, diagnostic: String): File {
|
||||
val directory = File(prepared.file.parentFile, "last-failed")
|
||||
require(directory.isDirectory || directory.mkdirs()) { "无法保存航线诊断文件" }
|
||||
prepared.originalFile.copyTo(File(directory, "original.kmz"), overwrite = true)
|
||||
prepared.file.copyTo(File(directory, "prepared.kmz"), overwrite = true)
|
||||
File(directory, "details.txt").writeText(diagnostic)
|
||||
return directory
|
||||
}
|
||||
|
||||
fun sha256(file: File): String {
|
||||
val hash = MessageDigest.getInstance("SHA-256")
|
||||
file.inputStream().use { input ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
hash.update(buffer, 0, n)
|
||||
}
|
||||
}
|
||||
return hash.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
fun returnHeight(file: File): Int? = ZipFile(file).use { zip ->
|
||||
zip.getInputStream(zip.getEntry("wpmz/waylines.wpml")).use { input ->
|
||||
parseXml(input).getElementsByTagNameNS("*", "globalRTHHeight").item(0)?.textContent?.toIntOrNull()
|
||||
}
|
||||
}
|
||||
private fun parseXml(input: java.io.InputStream): Document {
|
||||
val bytes = input.readBytes()
|
||||
require(!bytes.toString(Charsets.UTF_8).contains("<!DOCTYPE", ignoreCase = true)) { "WPML 不允许 DTD" }
|
||||
val builder = DocumentBuilderFactory.newInstance().apply {
|
||||
isNamespaceAware = true
|
||||
isExpandEntityReferences = false
|
||||
}.newDocumentBuilder()
|
||||
builder.setEntityResolver { _, _ -> throw org.xml.sax.SAXException("External entities are not allowed") }
|
||||
return builder.parse(bytes.inputStream())
|
||||
}
|
||||
private fun digest(bytes: ByteArray) = MessageDigest.getInstance("MD5").digest(bytes).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Preserve one normal-0 stream per payload; advertise only lens switches implemented by the app. */
|
||||
internal fun buildCloudLiveCapacity(aircraftSn: String, cameraSources: Map<String, List<String>>): JSONObject {
|
||||
val cameras = JSONArray()
|
||||
cameraSources.forEach { (cameraIndex, sources) ->
|
||||
val supported = sources.toSet()
|
||||
val types = JSONArray().put("normal")
|
||||
if ("WIDE_CAMERA" in supported) types.put("wide")
|
||||
if ("ZOOM_CAMERA" in supported) types.put("zoom")
|
||||
if ("INFRARED_CAMERA" in supported) types.put("ir")
|
||||
val video = JSONObject().put("video_index", "normal-0").put("video_type", "normal")
|
||||
.put("switchable_video_types", types)
|
||||
cameras.put(JSONObject().put("available_video_number", 1).put("coexist_video_number_max", 1)
|
||||
.put("camera_index", cameraIndex).put("video_list", JSONArray().put(video)))
|
||||
}
|
||||
val device = JSONObject().put("sn", aircraftSn).put("available_video_number", cameraSources.size)
|
||||
.put("coexist_video_number_max", 1).put("camera_list", cameras)
|
||||
return JSONObject().put("available_video_number", cameraSources.size).put("coexist_video_number_max", 1)
|
||||
.put("device_list", JSONArray().put(device))
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import dji.sampleV5.aircraft.BuildConfig
|
||||
|
||||
import android.util.Log
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
@@ -12,8 +14,8 @@ import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
|
||||
private const val CloudLoginLogTag = "ZklhCloudLogin"
|
||||
private const val CloudPlatformHost = "uav.zklhjs.com"
|
||||
private const val CloudPlatformFallbackIp = "221.226.33.58"
|
||||
private const val CloudPlatformHost = BuildConfig.CLOUD_PLATFORM_HOST
|
||||
private const val CloudPlatformFallbackIp = BuildConfig.CLOUD_FALLBACK_HOST
|
||||
|
||||
class CloudLoginClient {
|
||||
suspend fun login(request: CloudLoginRequest): Result<CloudSession> = withContext(Dispatchers.IO) {
|
||||
@@ -188,12 +190,13 @@ class CloudLoginClient {
|
||||
val body = JSONObject()
|
||||
.put("workspace_id", session.workspaceId)
|
||||
.put("workspaceId", session.workspaceId)
|
||||
postJson(
|
||||
val response = postJson(
|
||||
url = "${session.baseUrl}/manage/api/v1/devices/$encodedSn/binding",
|
||||
tenantId = session.tenantId,
|
||||
token = session.accessToken,
|
||||
body = body
|
||||
)
|
||||
validateCloudBindingResponse(response)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,7 +249,7 @@ class CloudLoginClient {
|
||||
}
|
||||
|
||||
private fun normalizeOrigin(rawUrl: String): String {
|
||||
val withScheme = rawUrl.trim().ifBlank { "http://uav.zklhjs.com" }.let {
|
||||
val withScheme = rawUrl.trim().ifBlank { BuildConfig.CLOUD_BASE_URL }.let {
|
||||
if (it.startsWith("http://", true) || it.startsWith("https://", true)) it else "http://$it"
|
||||
}
|
||||
val uri = URI(withScheme)
|
||||
@@ -281,6 +284,7 @@ class CloudLoginClient {
|
||||
}
|
||||
|
||||
private fun platformFallbackOrigin(origin: String): String? {
|
||||
if (CloudPlatformFallbackIp.isBlank()) return null
|
||||
val uri = URI(origin)
|
||||
val scheme = uri.scheme ?: return null
|
||||
val host = uri.host ?: return null
|
||||
@@ -292,6 +296,7 @@ class CloudLoginClient {
|
||||
}
|
||||
|
||||
private fun platformFallbackMqttAddress(address: String): String? {
|
||||
if (CloudPlatformFallbackIp.isBlank()) return null
|
||||
val uri = runCatching { URI(address) }.getOrNull() ?: return null
|
||||
val host = uri.host ?: return null
|
||||
if (!host.equals(CloudPlatformHost, ignoreCase = true)) return null
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import dji.sampleV5.aircraft.BuildConfig
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.zklh.dronecontroller.core.msdk.DjiCommandResult
|
||||
@@ -33,8 +35,8 @@ private const val MediaFetchTimeoutMs = 25_000L
|
||||
private const val MediaDownloadMinTimeoutMs = 120_000L
|
||||
private const val MediaDownloadMaxTimeoutMs = 600_000L
|
||||
private const val UploadReadTimeoutMs = 600_000
|
||||
private const val PlatformHost = "uav.zklhjs.com"
|
||||
private const val PlatformFallbackIp = "221.226.33.58"
|
||||
private const val PlatformHost = BuildConfig.CLOUD_PLATFORM_HOST
|
||||
private const val PlatformFallbackIp = BuildConfig.CLOUD_FALLBACK_HOST
|
||||
|
||||
class CloudMediaUploadService(
|
||||
context: Context,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import android.util.Log
|
||||
import com.zklh.dronecontroller.core.telemetry.cloudGear
|
||||
import com.zklh.dronecontroller.core.livestream.LiveStreamingState
|
||||
import com.zklh.dronecontroller.core.diagnostics.DroneWarningItem
|
||||
import com.zklh.dronecontroller.core.diagnostics.DroneWarningState
|
||||
import com.zklh.dronecontroller.core.msdk.DroneSdkState
|
||||
@@ -25,6 +27,10 @@ import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import android.os.SystemClock
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended
|
||||
@@ -82,22 +88,59 @@ private data class CloudDeviceDescriptor(
|
||||
}
|
||||
|
||||
class CloudMqttService(
|
||||
private val loginClient: CloudLoginClient = CloudLoginClient()
|
||||
private val loginClient: CloudLoginClient = CloudLoginClient(),
|
||||
terminalEventsFile: java.io.File? = null
|
||||
) : CloudMissionProgressPublisher {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private val _state = MutableStateFlow(CloudMqttState())
|
||||
val state: StateFlow<CloudMqttState> = _state.asStateFlow()
|
||||
|
||||
private val connecting = AtomicBoolean(false)
|
||||
private var client: MqttClient? = null
|
||||
@Volatile private var client: MqttClient? = null
|
||||
private var commandExecutor: CloudCommandExecutor? = null
|
||||
private var session: CloudSession? = null
|
||||
private var deviceIdentity = CloudDeviceIdentity()
|
||||
private var telemetry = TelemetrySnapshot()
|
||||
@Volatile private var session: CloudSession? = null
|
||||
@Volatile private var deviceIdentity = CloudDeviceIdentity()
|
||||
@Volatile private var telemetry = TelemetrySnapshot()
|
||||
private var warningState = DroneWarningState()
|
||||
private var subscribedControlKey = ""
|
||||
private var onlineKey = ""
|
||||
private val registration = CloudOnlineRegistration()
|
||||
private val synchronization = Mutex()
|
||||
private val lifecycle = Mutex()
|
||||
private val connectionGeneration = java.util.concurrent.atomic.AtomicLong()
|
||||
private var liveCapacityKey = ""
|
||||
private var lastLiveCapacityAt = 0L
|
||||
private var lastLiveStatusAt = 0L
|
||||
private var lastLiveStatusKey = ""
|
||||
@Volatile private var liveCapacity: JSONObject? = null
|
||||
@Volatile private var liveState = LiveStreamingState()
|
||||
private val terminalOutbox = CloudTerminalOutbox(terminalEventsFile)
|
||||
fun updateLiveState(value: LiveStreamingState) { liveState = value }
|
||||
private fun eventScope(): String = session?.let { "${it.mqttAddress}|${it.tenantId}|${it.workspaceId}|${deviceIdentity.remoteControllerSn}" }.orEmpty()
|
||||
private fun flushTerminalEvents() {
|
||||
if (!isConnected()) return
|
||||
terminalOutbox.due(eventScope(), SystemClock.elapsedRealtime()).forEach { item ->
|
||||
publish(item.getString("topic"), item.getJSONObject("payload"), qos = 1)
|
||||
}
|
||||
}
|
||||
private fun liveStatusData(): JSONArray {
|
||||
val state = liveState
|
||||
return JSONArray().apply {
|
||||
if (state.videoId.startsWith(deviceIdentity.aircraftSn + "/") && deviceIdentity.aircraftSn.isNotBlank())
|
||||
put(JSONObject().put("video_id", state.videoId).put("status", state.streaming).put("video_quality", state.quality))
|
||||
}
|
||||
}
|
||||
private fun publishLiveStatus() {
|
||||
val cloudSession = session ?: return
|
||||
val data = liveStatusData()
|
||||
val key = data.toString()
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (lastLiveStatusKey == key && now - lastLiveStatusAt < 30_000) return
|
||||
val rc = deviceIdentity.remoteControllerSn
|
||||
if (publish("thing/product/$rc/state", topicRequest(cloudSession).put("gateway", rc)
|
||||
.put("data", JSONObject().put("live_status", data)), qos = 1)) {
|
||||
lastLiveStatusKey = key; lastLiveStatusAt = now
|
||||
}
|
||||
}
|
||||
private var warningHmsKey = ""
|
||||
private var warningDebugRaw = ""
|
||||
private var hmsDebugKey = ""
|
||||
@@ -111,12 +154,37 @@ class CloudMqttService(
|
||||
private val osdThrottleLock = Any()
|
||||
private val clientInstanceId = UUID.randomUUID().toString().replace("-", "")
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
while (isActive) {
|
||||
runCatching { synchronizeCloudState() }.onFailure {
|
||||
Log.w(CloudMqttLogTag, "cloud synchronization will retry: ${it.message}")
|
||||
_state.update { state -> state.copy(lastError = it.message) }
|
||||
}
|
||||
delay(OSD_MIN_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun synchronizeCloudState() = synchronization.withLock {
|
||||
if (!isConnected()) return@withLock
|
||||
subscribeControlTopicsIfReady()
|
||||
if (!publishOnlineIfReady()) return@withLock
|
||||
publishOsdIfReady(force = false)
|
||||
if (registration.isReady()) {
|
||||
publishLiveCapacityIfReady(deviceIdentity, force = false)
|
||||
publishLiveStatus()
|
||||
flushTerminalEvents()
|
||||
publishHmsIfReady(force = false)
|
||||
}
|
||||
}
|
||||
|
||||
fun connect(
|
||||
session: CloudSession,
|
||||
commandExecutor: CloudCommandExecutor
|
||||
) {
|
||||
if (!connecting.compareAndSet(false, true)) return
|
||||
this.session = session
|
||||
val generation = connectionGeneration.incrementAndGet()
|
||||
this.commandExecutor = commandExecutor
|
||||
_state.update {
|
||||
it.copy(
|
||||
@@ -127,106 +195,124 @@ class CloudMqttService(
|
||||
)
|
||||
}
|
||||
scope.launch {
|
||||
var attemptClient: MqttClient? = null
|
||||
runCatching {
|
||||
closeCurrentClient()
|
||||
val clientId = buildClientId()
|
||||
val mqttAddresses = CloudLoginClient.mqttAddressCandidates(session.mqttAddress)
|
||||
.ifEmpty { listOf(session.mqttAddress) }
|
||||
var connectedClient: MqttClient? = null
|
||||
var connectedSession = session
|
||||
var lastConnectError: Throwable? = null
|
||||
for (mqttAddress in mqttAddresses) {
|
||||
val result = runCatching {
|
||||
Log.i(
|
||||
CloudMqttLogTag,
|
||||
"connect attempt address=$mqttAddress clientId=$clientId username=${session.mqttUsername}"
|
||||
)
|
||||
val mqttClient = MqttClient(mqttAddress, clientId, MemoryPersistence())
|
||||
attemptClient = mqttClient
|
||||
mqttClient.setCallback(callback())
|
||||
val options = MqttConnectOptions().apply {
|
||||
isAutomaticReconnect = true
|
||||
isCleanSession = true
|
||||
connectionTimeout = 10
|
||||
keepAliveInterval = 20
|
||||
maxInflight = MQTT_MAX_INFLIGHT
|
||||
userName = session.mqttUsername
|
||||
password = session.mqttPassword.toCharArray()
|
||||
lifecycle.withLock {
|
||||
if (generation != connectionGeneration.get()) { connecting.set(false); return@withLock }
|
||||
var attemptClient: MqttClient? = null
|
||||
runCatching {
|
||||
closeCurrentClient()
|
||||
this@CloudMqttService.session = session
|
||||
val clientId = buildClientId()
|
||||
val mqttAddresses = CloudLoginClient.mqttAddressCandidates(session.mqttAddress)
|
||||
.ifEmpty { listOf(session.mqttAddress) }
|
||||
var connectedClient: MqttClient? = null
|
||||
var connectedSession = session
|
||||
var lastConnectError: Throwable? = null
|
||||
for (mqttAddress in mqttAddresses) {
|
||||
val result = runCatching {
|
||||
Log.i(
|
||||
CloudMqttLogTag,
|
||||
"connect attempt address=$mqttAddress clientId=$clientId username=${session.mqttUsername}"
|
||||
)
|
||||
val mqttClient = MqttClient(mqttAddress, clientId, MemoryPersistence())
|
||||
attemptClient = mqttClient
|
||||
mqttClient.setCallback(callback(mqttClient))
|
||||
val options = MqttConnectOptions().apply {
|
||||
isAutomaticReconnect = true
|
||||
isCleanSession = true
|
||||
connectionTimeout = 10
|
||||
keepAliveInterval = 20
|
||||
maxInflight = MQTT_MAX_INFLIGHT
|
||||
userName = session.mqttUsername
|
||||
password = session.mqttPassword.toCharArray()
|
||||
}
|
||||
mqttClient.setTimeToWait(15_000L)
|
||||
mqttClient.connect(options)
|
||||
mqttClient
|
||||
}
|
||||
if (result.isSuccess) {
|
||||
connectedClient = result.getOrThrow()
|
||||
connectedSession = session.copy(mqttAddress = mqttAddress)
|
||||
break
|
||||
} else {
|
||||
val error = result.exceptionOrNull()
|
||||
Log.w(CloudMqttLogTag, "connect attempt failed address=$mqttAddress: ${error?.message}")
|
||||
closeMqttClient(attemptClient)
|
||||
attemptClient = null
|
||||
lastConnectError = error
|
||||
}
|
||||
mqttClient.connect(options)
|
||||
mqttClient
|
||||
}
|
||||
if (result.isSuccess) {
|
||||
connectedClient = result.getOrThrow()
|
||||
connectedSession = session.copy(mqttAddress = mqttAddress)
|
||||
break
|
||||
} else {
|
||||
val error = result.exceptionOrNull()
|
||||
Log.w(CloudMqttLogTag, "connect attempt failed address=$mqttAddress: ${error?.message}")
|
||||
closeMqttClient(attemptClient)
|
||||
attemptClient = null
|
||||
lastConnectError = error
|
||||
val mqttClient = connectedClient ?: throw lastConnectError ?: IllegalStateException("MQTT 连接失败")
|
||||
if (generation != connectionGeneration.get()) {
|
||||
closeMqttClient(mqttClient); connecting.set(false); return@withLock
|
||||
}
|
||||
client = mqttClient
|
||||
this@CloudMqttService.session = connectedSession
|
||||
_state.update {
|
||||
it.copy(
|
||||
connected = true,
|
||||
connecting = false,
|
||||
session = connectedSession,
|
||||
message = "MQTT 已连接",
|
||||
lastError = null
|
||||
)
|
||||
}
|
||||
runCatching { synchronizeCloudState() }.onFailure {
|
||||
Log.w(CloudMqttLogTag, "Initial cloud synchronization will retry", it)
|
||||
}
|
||||
}.onFailure { error ->
|
||||
Log.e(CloudMqttLogTag, "connect failed", error)
|
||||
closeMqttClient(attemptClient)
|
||||
if (generation != connectionGeneration.get()) { connecting.set(false); return@withLock }
|
||||
_state.update {
|
||||
it.copy(
|
||||
connected = false,
|
||||
connecting = false,
|
||||
message = "MQTT 连接失败",
|
||||
lastError = error.message ?: error.toString()
|
||||
)
|
||||
}
|
||||
}
|
||||
val mqttClient = connectedClient ?: throw lastConnectError ?: IllegalStateException("MQTT 连接失败")
|
||||
client = mqttClient
|
||||
this@CloudMqttService.session = connectedSession
|
||||
_state.update {
|
||||
it.copy(
|
||||
connected = true,
|
||||
connecting = false,
|
||||
session = connectedSession,
|
||||
message = "MQTT 已连接",
|
||||
lastError = null
|
||||
)
|
||||
}
|
||||
subscribeControlTopicsIfReady()
|
||||
publishOnlineIfReady(force = true)
|
||||
publishOsdIfReady(force = true)
|
||||
publishHmsIfReady(force = true)
|
||||
}.onFailure { error ->
|
||||
Log.e(CloudMqttLogTag, "connect failed", error)
|
||||
closeMqttClient(attemptClient)
|
||||
_state.update {
|
||||
it.copy(
|
||||
connected = false,
|
||||
connecting = false,
|
||||
message = "MQTT 连接失败",
|
||||
lastError = error.message ?: error.toString()
|
||||
)
|
||||
}
|
||||
connecting.set(false)
|
||||
}
|
||||
connecting.set(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun disconnect() {
|
||||
val generation = connectionGeneration.incrementAndGet()
|
||||
scope.launch {
|
||||
cancelPendingOfflineTopo()
|
||||
runCatching {
|
||||
publishStatusOnline(online = false, identity = lastOnlineIdentity ?: deviceIdentity)
|
||||
}
|
||||
lastOnlineIdentity = null
|
||||
closeCurrentClient()
|
||||
_state.update {
|
||||
it.copy(
|
||||
connected = false,
|
||||
connecting = false,
|
||||
message = "第三方云已断开",
|
||||
lastError = null
|
||||
)
|
||||
lifecycle.withLock {
|
||||
if (generation != connectionGeneration.get()) return@withLock
|
||||
cancelPendingOfflineTopo()
|
||||
runCatching {
|
||||
publishStatusOnline(online = false, identity = lastOnlineIdentity ?: deviceIdentity)
|
||||
}
|
||||
lastOnlineIdentity = null
|
||||
closeCurrentClient()
|
||||
connecting.set(false)
|
||||
session = null
|
||||
_state.update {
|
||||
it.copy(
|
||||
connected = false,
|
||||
connecting = false,
|
||||
session = null,
|
||||
message = "第三方云已断开",
|
||||
lastError = null
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
connectionGeneration.incrementAndGet()
|
||||
cancelPendingOfflineTopo()
|
||||
runCatching {
|
||||
publishStatusOnline(online = false, identity = lastOnlineIdentity ?: deviceIdentity)
|
||||
}
|
||||
lastOnlineIdentity = null
|
||||
closeCurrentClient()
|
||||
session = null
|
||||
connecting.set(false)
|
||||
scope.cancel()
|
||||
}
|
||||
|
||||
@@ -254,19 +340,11 @@ class CloudMqttService(
|
||||
if (nextIdentity.readyForOnline && nextIdentity.productConnected) {
|
||||
cancelPendingOfflineTopo(nextIdentity)
|
||||
}
|
||||
scope.launch {
|
||||
subscribeControlTopicsIfReady()
|
||||
publishOnlineIfReady(force = identityChanged && nextIdentity.readyForOnline && nextIdentity.productConnected)
|
||||
publishLiveCapacityIfReady(deviceIdentity, force = false)
|
||||
publishHmsIfReady(force = false)
|
||||
}
|
||||
// The single synchronization loop retries after SN, connection and telemetry become ready.
|
||||
}
|
||||
|
||||
fun updateTelemetry(snapshot: TelemetrySnapshot) {
|
||||
telemetry = snapshot
|
||||
scope.launch {
|
||||
publishOsdIfReady(force = false)
|
||||
}
|
||||
}
|
||||
|
||||
fun updateWarnings(state: DroneWarningState) {
|
||||
@@ -283,9 +361,10 @@ class CloudMqttService(
|
||||
}
|
||||
}
|
||||
|
||||
private fun callback(): MqttCallback =
|
||||
private fun callback(source: MqttClient): MqttCallback =
|
||||
object : MqttCallbackExtended {
|
||||
override fun connectComplete(reconnect: Boolean, serverURI: String?) {
|
||||
if (client !== source) return
|
||||
Log.i(CloudMqttLogTag, "connect complete reconnect=$reconnect serverURI=$serverURI")
|
||||
_state.update {
|
||||
it.copy(
|
||||
@@ -296,24 +375,14 @@ class CloudMqttService(
|
||||
)
|
||||
}
|
||||
if (reconnect) {
|
||||
subscribedControlKey = ""
|
||||
onlineKey = ""
|
||||
liveCapacityKey = ""
|
||||
scope.launch {
|
||||
subscribeControlTopicsIfReady()
|
||||
publishOnlineIfReady(force = true)
|
||||
publishOsdIfReady(force = true)
|
||||
publishHmsIfReady(force = true)
|
||||
}
|
||||
resetPublishState()
|
||||
}
|
||||
}
|
||||
|
||||
override fun connectionLost(cause: Throwable?) {
|
||||
if (client !== source) return
|
||||
Log.e(CloudMqttLogTag, "connection lost", cause)
|
||||
subscribedControlKey = ""
|
||||
onlineKey = ""
|
||||
liveCapacityKey = ""
|
||||
warningHmsKey = ""
|
||||
resetPublishState()
|
||||
_state.update {
|
||||
it.copy(
|
||||
connected = false,
|
||||
@@ -325,9 +394,19 @@ class CloudMqttService(
|
||||
}
|
||||
|
||||
override fun messageArrived(topic: String, message: MqttMessage) {
|
||||
if (client !== source) return
|
||||
val payload = message.payload.toString(Charsets.UTF_8)
|
||||
Log.d(CloudMqttLogTag, "message arrived topic=$topic payload=$payload")
|
||||
scope.launch { handleCommand(topic, payload) }
|
||||
if (topic == "sys/product/${deviceIdentity.remoteControllerSn}/status_reply") {
|
||||
runCatching {
|
||||
registration.acknowledgePayload(payload)
|
||||
}.onFailure { Log.w(CloudMqttLogTag, "Invalid topology reply", it) }
|
||||
} else if (topic.endsWith("/events_reply")) {
|
||||
runCatching { terminalOutbox.acknowledge(eventScope(), JSONObject(payload)) }
|
||||
.onFailure { Log.w(CloudMqttLogTag, "Invalid terminal event reply", it) }
|
||||
} else {
|
||||
scope.launch { handleCommand(topic, payload) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun deliveryComplete(token: IMqttDeliveryToken?) = Unit
|
||||
@@ -340,6 +419,8 @@ class CloudMqttService(
|
||||
val key = "$rcSn/$aircraftSn"
|
||||
if (!mqttClient.isConnected || rcSn.isBlank() || subscribedControlKey == key) return
|
||||
val topics = buildList {
|
||||
add("sys/product/$rcSn/status_reply")
|
||||
add("thing/product/$rcSn/events_reply")
|
||||
add("thing/product/$rcSn/services")
|
||||
add("thing/product/$rcSn/property/set")
|
||||
add("thing/product/$rcSn/drc/down")
|
||||
@@ -386,34 +467,48 @@ class CloudMqttService(
|
||||
publishReply(request, result.success, result.message)
|
||||
}
|
||||
|
||||
private fun publishOnlineIfReady(force: Boolean): Boolean {
|
||||
private fun publishOnlineIfReady(): Boolean {
|
||||
if (!isConnected()) return false
|
||||
val identity = deviceIdentity
|
||||
if (!identity.readyForOnline || !identity.productConnected) return false
|
||||
val key = "${identity.remoteControllerSn}/${identity.aircraftSn}/${session?.workspaceId}"
|
||||
if (!force && onlineKey == key) return true
|
||||
if (!publishStatusOnline(online = true, identity = identity)) return false
|
||||
onlineKey = key
|
||||
lastOnlineIdentity = identity
|
||||
cancelPendingOfflineTopo(identity)
|
||||
val now = System.currentTimeMillis()
|
||||
_state.update { it.copy(lastOnlineAt = now, message = "设备上线信息已上报") }
|
||||
publishLiveCapacityIfReady(identity, force = true)
|
||||
bindDevices(identity)
|
||||
if (!identity.readyForOnline || !identity.productConnected) {
|
||||
_state.update { it.copy(message = "MQTT 已连接,等待飞机连接和设备 SN") }
|
||||
return false
|
||||
}
|
||||
val drone = telemetry.cloudDroneDescriptor()
|
||||
if (drone.type == 0) {
|
||||
_state.update { it.copy(message = "MQTT 已连接,等待飞机型号信息") }
|
||||
return false
|
||||
}
|
||||
val cloudSession = session ?: return false
|
||||
val key = "${identity.remoteControllerSn}/${identity.aircraftSn}/${cloudSession.tenantId}/${cloudSession.workspaceId}/${telemetry.cloudRcDescriptor().deviceType}/${drone.deviceType}"
|
||||
registration.select(key)
|
||||
registration.beginPublish(SystemClock.elapsedRealtime())?.let { attempt ->
|
||||
if (publishStatusOnline(true, identity, attempt)) {
|
||||
lastOnlineIdentity = identity
|
||||
cancelPendingOfflineTopo(identity)
|
||||
}
|
||||
}
|
||||
registration.beginBinding(SystemClock.elapsedRealtime())?.let { attempt ->
|
||||
scope.launch {
|
||||
val result = runCatching {
|
||||
loginClient.bindDevice(cloudSession, identity.remoteControllerSn).getOrThrow()
|
||||
loginClient.bindDevice(cloudSession, identity.aircraftSn).getOrThrow()
|
||||
}
|
||||
val current = registration.completeBinding(attempt, result.isSuccess, SystemClock.elapsedRealtime())
|
||||
if (current && result.isFailure) {
|
||||
Log.w(CloudMqttLogTag, "Device binding will retry", result.exceptionOrNull())
|
||||
_state.update { it.copy(message = "设备绑定未完成,正在重试", lastError = result.exceptionOrNull()?.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!registration.isReady()) return false
|
||||
if (_state.value.lastOnlineAt == 0L) {
|
||||
_state.update { it.copy(lastOnlineAt = System.currentTimeMillis(), message = "设备已上线,正在同步无人机数据", lastError = null) }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun bindDevices(identity: CloudDeviceIdentity) {
|
||||
val cloudSession = session ?: return
|
||||
scope.launch {
|
||||
loginClient.bindDevice(cloudSession, identity.remoteControllerSn)
|
||||
.onFailure { Log.w(CloudMqttLogTag, "bind rc failed: ${it.message}") }
|
||||
loginClient.bindDevice(cloudSession, identity.aircraftSn)
|
||||
.onFailure { Log.w(CloudMqttLogTag, "bind drone failed: ${it.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
private fun publishStatusOnline(online: Boolean, identity: CloudDeviceIdentity = deviceIdentity): Boolean {
|
||||
private fun publishStatusOnline(online: Boolean, identity: CloudDeviceIdentity = deviceIdentity, attempt: CloudOnlineRegistration.Attempt? = null): Boolean {
|
||||
val cloudSession = session ?: return false
|
||||
val rcSn = identity.remoteControllerSn
|
||||
if (rcSn.isBlank()) return false
|
||||
@@ -443,6 +538,7 @@ class CloudMqttService(
|
||||
.put("access_type", CloudAccessType)
|
||||
.put("sub_devices", subDevices)
|
||||
)
|
||||
attempt?.let { payload.put("tid", it.tid).put("bid", it.bid) }
|
||||
return publish("sys/product/$rcSn/status", payload, qos = 1)
|
||||
}
|
||||
|
||||
@@ -452,45 +548,24 @@ class CloudMqttService(
|
||||
val rcSn = identity.remoteControllerSn
|
||||
val aircraftSn = identity.aircraftSn
|
||||
if (rcSn.isBlank() || aircraftSn.isBlank()) return
|
||||
val cameraIndexes = telemetry.cloudCameraPayloadIndexes()
|
||||
val key = "$rcSn/$aircraftSn/${cloudSession.workspaceId}/${cameraIndexes.joinToString(",")}"
|
||||
if (!force && liveCapacityKey == key) return
|
||||
|
||||
val video = JSONObject()
|
||||
.put("video_index", DefaultLiveVideoIndex)
|
||||
.put("video_type", "normal")
|
||||
.put("switchable_video_types", JSONArray().put("normal"))
|
||||
val cameras = JSONArray().apply {
|
||||
cameraIndexes.forEach { cameraIndex ->
|
||||
put(
|
||||
JSONObject()
|
||||
.put("available_video_number", 1)
|
||||
.put("coexist_video_number_max", 1)
|
||||
.put("camera_index", cameraIndex)
|
||||
.put("video_list", JSONArray().put(JSONObject(video.toString())))
|
||||
)
|
||||
}
|
||||
val snapshot = telemetry
|
||||
val cameraSources = snapshot.cloudCameraPayloadIndexes().associateWith { cameraIndex ->
|
||||
snapshot.cameraStreamSources.entries
|
||||
.filter { (component, _) -> component.toCloudPayloadPositionIndex().toString() == cameraIndex.substringAfterLast('-') }
|
||||
.flatMap { it.value }.distinct().sorted()
|
||||
}
|
||||
val device = JSONObject()
|
||||
.put("sn", aircraftSn)
|
||||
.put("available_video_number", cameraIndexes.size)
|
||||
.put("coexist_video_number_max", 1)
|
||||
.put("camera_list", cameras)
|
||||
val capacity = buildCloudLiveCapacity(aircraftSn, cameraSources)
|
||||
// Include capabilities so a late SDK range update is published immediately, not after 30 seconds.
|
||||
val key = rcSn + "/" + aircraftSn + "/" + cloudSession.workspaceId + "/" + capacity.toString()
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (!force && liveCapacityKey == key && now - lastLiveCapacityAt < 30_000) return
|
||||
val payload = topicRequest(cloudSession)
|
||||
.put("gateway", rcSn)
|
||||
.put("method", "livestream_ability_update")
|
||||
.put(
|
||||
"data",
|
||||
JSONObject()
|
||||
.put(
|
||||
"live_capacity",
|
||||
JSONObject()
|
||||
.put("available_video_number", cameraIndexes.size)
|
||||
.put("coexist_video_number_max", 1)
|
||||
.put("device_list", JSONArray().put(device))
|
||||
)
|
||||
)
|
||||
.put("data", JSONObject().put("live_capacity", capacity))
|
||||
liveCapacity = payload.getJSONObject("data").getJSONObject("live_capacity")
|
||||
if (publish("thing/product/$rcSn/state", payload, qos = 1)) {
|
||||
lastLiveCapacityAt = now
|
||||
liveCapacityKey = key
|
||||
Log.d(CloudMqttLogTag, "live capacity published rc=$rcSn aircraft=$aircraftSn force=$force")
|
||||
}
|
||||
@@ -547,34 +622,42 @@ class CloudMqttService(
|
||||
waylineId: Int,
|
||||
currentWaypointIndex: Int,
|
||||
resultCode: Int,
|
||||
resultMessage: String
|
||||
resultMessage: String,
|
||||
missionState: Int
|
||||
) {
|
||||
if (flightId.isBlank()) return
|
||||
val data = JSONObject()
|
||||
.put("result", cloudApiResult(resultCode, resultMessage))
|
||||
.put("result", resultCode)
|
||||
.put("message", resultMessage)
|
||||
.put(
|
||||
"output",
|
||||
JSONObject()
|
||||
.put("status", status)
|
||||
.put("status", status.lowercase())
|
||||
.put(
|
||||
"progress",
|
||||
JSONObject()
|
||||
.put("percent", percent.coerceIn(0, 100))
|
||||
.put("wayline_id", waylineId)
|
||||
.put("waylineId", waylineId)
|
||||
.put("current_waypoint_index", currentWaypointIndex)
|
||||
.put("currentWaypointIndex", currentWaypointIndex)
|
||||
.put("current_step", if (missionState == 9) 32 else if (missionState == 4) 20 else 21)
|
||||
)
|
||||
.put(
|
||||
"ext",
|
||||
JSONObject()
|
||||
.put("flight_id", flightId)
|
||||
.put("flightId", flightId)
|
||||
.put("wayline_id", waylineId)
|
||||
.put("current_waypoint_index", currentWaypointIndex)
|
||||
.put("wayline_mission_state", missionState)
|
||||
.put("media_count", 0)
|
||||
.put("mediaCount", 0)
|
||||
)
|
||||
)
|
||||
publishCloudEvent("flighttask_progress", flightId, data)
|
||||
if (status in setOf("ok", "failed", "canceled", "rejected", "timeout")) {
|
||||
val cloudSession = session ?: return
|
||||
val rc = deviceIdentity.remoteControllerSn
|
||||
val payload = topicRequest(cloudSession).put("bid", flightId).put("method", "flighttask_progress")
|
||||
.put("gateway", rc).put("need_reply", true).put("data", data)
|
||||
terminalOutbox.offer(eventScope(), "thing/product/$rc/events", payload)
|
||||
flushTerminalEvents()
|
||||
} else publishCloudEvent("flighttask_progress", flightId, data)
|
||||
}
|
||||
|
||||
override fun publishPointFlightProgress(
|
||||
@@ -631,7 +714,7 @@ class CloudMqttService(
|
||||
val rcSn = identity.remoteControllerSn
|
||||
if (rcSn.isBlank()) return false
|
||||
val fromSn = identity.aircraftSn.ifBlank { rcSn }
|
||||
val topicSn = fromSn
|
||||
val topicSn = if (method == "flighttask_progress") rcSn else fromSn
|
||||
val payload = topicRequest(cloudSession)
|
||||
.put("bid", bid.ifBlank { UUID.randomUUID().toString() })
|
||||
.put("method", method)
|
||||
@@ -661,7 +744,7 @@ class CloudMqttService(
|
||||
if (!isConnected()) return
|
||||
val identity = deviceIdentity
|
||||
if (!identity.readyForOnline || !identity.productConnected) return
|
||||
if (onlineKey.isBlank() && !publishOnlineIfReady(force = true)) return
|
||||
if (!registration.isReady()) return
|
||||
val now = System.currentTimeMillis()
|
||||
val shouldPublish = synchronized(osdThrottleLock) {
|
||||
when {
|
||||
@@ -674,13 +757,13 @@ class CloudMqttService(
|
||||
}
|
||||
}
|
||||
if (!shouldPublish) return
|
||||
publishRcOsd(identity)
|
||||
publishDroneOsd(identity)
|
||||
_state.update { it.copy(lastOsdAt = now) }
|
||||
val rcSent = publishRcOsd(identity)
|
||||
val droneSent = publishDroneOsd(identity)
|
||||
if (rcSent && droneSent) _state.update { it.copy(lastOsdAt = now) }
|
||||
}
|
||||
|
||||
private fun publishRcOsd(identity: CloudDeviceIdentity) {
|
||||
val cloudSession = session ?: return
|
||||
private fun publishRcOsd(identity: CloudDeviceIdentity): Boolean {
|
||||
val cloudSession = session ?: return false
|
||||
Log.d(
|
||||
CloudMqttLogTag,
|
||||
"RcOsdPosition lat=${telemetry.rcLatitude} lon=${telemetry.rcLongitude} valid=${telemetry.rcLocationValid} satellites=${telemetry.rcGpsSatelliteCount}"
|
||||
@@ -696,6 +779,8 @@ class CloudMqttService(
|
||||
.put("height", telemetry.rcAltitude.toFloat())
|
||||
.put("capacity_percent", telemetry.rcBatteryPercent.takeIf { it in 0..100 } ?: 0)
|
||||
.put("is_cloud_control_auth", 1)
|
||||
.put("live_capacity", liveCapacity)
|
||||
.put("live_status", liveStatusData())
|
||||
.put(
|
||||
"wireless_link",
|
||||
JSONObject()
|
||||
@@ -711,11 +796,11 @@ class CloudMqttService(
|
||||
.put("4g_uav_quality", 0)
|
||||
)
|
||||
)
|
||||
publish("thing/product/${identity.remoteControllerSn}/osd", payload, qos = 0)
|
||||
return publish("thing/product/${identity.remoteControllerSn}/osd", payload, qos = 0)
|
||||
}
|
||||
|
||||
private fun publishDroneOsd(identity: CloudDeviceIdentity) {
|
||||
val cloudSession = session ?: return
|
||||
private fun publishDroneOsd(identity: CloudDeviceIdentity): Boolean {
|
||||
val cloudSession = session ?: return false
|
||||
val horizontalSpeed = sqrt(telemetry.speedX * telemetry.speedX + telemetry.speedY * telemetry.speedY)
|
||||
val latitude = telemetry.droneOsdLatitude()
|
||||
val longitude = telemetry.droneOsdLongitude()
|
||||
@@ -738,7 +823,7 @@ class CloudMqttService(
|
||||
.put("attitude_pitch", telemetry.attitudePitch)
|
||||
.put("attitude_roll", telemetry.attitudeRoll)
|
||||
.put("elevation", relativeAltitude)
|
||||
.put("gear", telemetry.gear)
|
||||
.put("gear", cloudGear(telemetry.gear))
|
||||
.put("height", relativeAltitude)
|
||||
.put("original_height", relativeAltitude)
|
||||
.put("home_distance", telemetry.homeDistanceMeters())
|
||||
@@ -762,7 +847,7 @@ class CloudMqttService(
|
||||
.put("distance_limit_status", rcDistanceLimitStatusJson())
|
||||
.put("track_id", "")
|
||||
)
|
||||
publish("thing/product/${identity.aircraftSn}/osd", payload, qos = 0)
|
||||
return publish("thing/product/${identity.aircraftSn}/osd", payload, qos = 0)
|
||||
}
|
||||
|
||||
private fun droneBatteryJson(): JSONObject {
|
||||
@@ -829,8 +914,12 @@ class CloudMqttService(
|
||||
private fun storageJson(): JSONObject =
|
||||
JSONObject()
|
||||
.put(JsonClassKey, StorageClass)
|
||||
.put("total", telemetry.storageTotal.toCloudStorageUnit())
|
||||
.put("used", telemetry.storageUsed().toCloudStorageUnit())
|
||||
.apply {
|
||||
val total = (telemetry.cameraCloudFields["_storage_total_mb"] as? Number)?.toInt()
|
||||
val remain = (telemetry.cameraCloudFields["_storage_remaining_mb"] as? Number)?.toInt()
|
||||
if (total != null) put("total", total.toCloudStorageUnit())
|
||||
if (total != null && remain != null) put("used", (total - remain).coerceAtLeast(0).toCloudStorageUnit())
|
||||
}
|
||||
|
||||
private fun osdCameraListJson(): JSONArray =
|
||||
JSONArray().apply {
|
||||
@@ -847,11 +936,14 @@ class CloudMqttService(
|
||||
.put("photo_state", telemetry.photoState)
|
||||
.put("recording_state", telemetry.recordingState)
|
||||
.put("record_time", telemetry.recordingTime)
|
||||
.put("remain_photo_num", telemetry.remainPhotoNum.toLong())
|
||||
.put("remain_record_duration", telemetry.remainRecordDuration)
|
||||
|
||||
.put("zoom_factor", telemetry.zoomFactor)
|
||||
.put("ir_zoom_factor", telemetry.irZoomFactor)
|
||||
.put("screen_split_enable", false)
|
||||
.apply {
|
||||
if (payloadIndex == telemetry.cloudCameraPayloadIndex())
|
||||
telemetry.cameraCloudFields.filterKeys { !it.startsWith("_") }.forEach { (key, value) -> put(key, value) }
|
||||
}
|
||||
|
||||
private fun rcDronePayloadListJson(): JSONArray =
|
||||
JSONArray().apply {
|
||||
@@ -873,7 +965,10 @@ class CloudMqttService(
|
||||
.put("measure_target_latitude", telemetry.laserTargetLatitude.toFloat())
|
||||
.put("measure_target_longitude", telemetry.laserTargetLongitude.toFloat())
|
||||
.put("smart_track_point", JSONArray())
|
||||
.put("thermal_global_temperature_max", telemetry.thermalMaxTemperature.toFloat())
|
||||
.apply {
|
||||
if (payloadIndex == telemetry.cloudCameraPayloadIndex())
|
||||
telemetry.payloadCloudFields.forEach { (key, value) -> put(key, value) }
|
||||
}
|
||||
|
||||
private fun topicRequest(cloudSession: CloudSession): JSONObject =
|
||||
JSONObject()
|
||||
@@ -1004,8 +1099,13 @@ class CloudMqttService(
|
||||
|
||||
private fun resetPublishState() {
|
||||
subscribedControlKey = ""
|
||||
onlineKey = ""
|
||||
registration.reset()
|
||||
lastOsdAt = 0L
|
||||
_state.update { it.copy(lastOnlineAt = 0L, lastOsdAt = 0L) }
|
||||
liveCapacityKey = ""
|
||||
liveCapacity = null
|
||||
lastLiveStatusKey = ""
|
||||
lastLiveStatusAt = 0L
|
||||
warningHmsKey = ""
|
||||
hmsDebugKey = ""
|
||||
}
|
||||
@@ -1019,7 +1119,9 @@ class CloudMqttService(
|
||||
val recoveredSameDevice = currentIdentity.readyForOnline &&
|
||||
currentIdentity.productConnected &&
|
||||
currentIdentity.sameCloudDevice(identity)
|
||||
if (!recoveredSameDevice) {
|
||||
val replacedOnSameRc = currentIdentity.readyForOnline && currentIdentity.productConnected &&
|
||||
currentIdentity.remoteControllerSn == identity.remoteControllerSn
|
||||
if (!recoveredSameDevice && !replacedOnSameRc) {
|
||||
val published = publishStatusOnline(online = false, identity = identity)
|
||||
if (published && lastOnlineIdentity?.sameCloudDevice(identity) == true) {
|
||||
lastOnlineIdentity = null
|
||||
@@ -1232,6 +1334,7 @@ private fun TelemetrySnapshot.cloudApiDroneType(): Int {
|
||||
product.contains("MATRICE_300") || product.contains("M300") -> 60
|
||||
product.contains("M30") -> 67
|
||||
product.contains("MAVIC_3_ENTERPRISE") -> 77
|
||||
product.contains("MATRICE_3D") || product.contains("M3D") || product.contains("M3TD") -> 91
|
||||
product.contains("MATRICE_400") || product.contains("M400") -> 103
|
||||
product.contains("MATRICE_4TD") || product.contains("M4TD") || product.contains("4TD") -> CloudMatrice4DockType
|
||||
product.contains("MATRICE_4D") || product.contains("M4D") || product.contains("4D") -> CloudMatrice4DockType
|
||||
@@ -1251,6 +1354,7 @@ private fun TelemetrySnapshot.cloudDroneSubType(): Int {
|
||||
camera.contains("M4D") || camera.contains("M4E") -> 0
|
||||
camera.contains("M3TD") || camera.contains("M3T") -> 1
|
||||
camera.contains("M30T") -> 1
|
||||
product.contains("MATRICE_3TD") || product.contains("M3TD") -> 1
|
||||
product.contains("MATRICE_4TD") || product.contains("M4TD") || product.contains("4TD") -> 1
|
||||
product.contains("MATRICE_4D") || product.contains("M4D") || product.contains("4D") -> 0
|
||||
product.contains("MATRICE_4T") || product.contains("M4T") || product.contains("4T") -> 1
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import java.util.UUID
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Broker delivery is not application registration. Wait for topology replies, then bind and announce again. */
|
||||
internal class CloudOnlineRegistration {
|
||||
data class Attempt(val key: String, val generation: Long, val tid: String, val bid: String)
|
||||
private var key = ""
|
||||
private var generation = 0L
|
||||
private var pending: Attempt? = null
|
||||
private var lastSentAt: Long? = null
|
||||
private var confirmed = false
|
||||
private var bound = false
|
||||
private var binding = false
|
||||
private var nextBindingAt = 0L
|
||||
|
||||
@Synchronized fun select(nextKey: String) {
|
||||
if (key != nextKey) { reset(); key = nextKey }
|
||||
}
|
||||
@Synchronized fun reset() {
|
||||
generation++; key = ""; pending = null; lastSentAt = null
|
||||
confirmed = false; bound = false; binding = false; nextBindingAt = 0L
|
||||
}
|
||||
@Synchronized fun beginPublish(now: Long): Attempt? {
|
||||
if (key.isBlank() || binding) return null
|
||||
val interval = if (pending != null || !confirmed) 5_000L else 30_000L
|
||||
if (lastSentAt?.let { now - it < interval } == true) return null
|
||||
return Attempt(key, generation, UUID.randomUUID().toString(), UUID.randomUUID().toString()).also {
|
||||
pending = it; lastSentAt = now
|
||||
}
|
||||
}
|
||||
fun acknowledgePayload(payload: String): Boolean {
|
||||
val reply = JSONObject(payload)
|
||||
// This backend echoes tid/bid but older Cloud SDK versions omit the status method.
|
||||
val method = if (reply.isNull("method")) "" else reply.optString("method")
|
||||
if (method.isNotBlank() && method != "update_topo") return false
|
||||
val success = reply.optJSONObject("data")?.optInt("result", -1) == 0
|
||||
return acknowledge(reply.optString("tid"), reply.optString("bid"), success)
|
||||
}
|
||||
@Synchronized fun acknowledge(tid: String, bid: String, success: Boolean): Boolean {
|
||||
val attempt = pending ?: return false
|
||||
if (attempt.tid != tid || attempt.bid != bid) return false
|
||||
if (!success) return false
|
||||
pending = null; confirmed = true
|
||||
return true
|
||||
}
|
||||
@Synchronized fun beginBinding(now: Long): Attempt? {
|
||||
if (!confirmed || bound || binding || now < nextBindingAt) return null
|
||||
binding = true
|
||||
return Attempt(key, generation, "", "")
|
||||
}
|
||||
@Synchronized fun completeBinding(attempt: Attempt, success: Boolean, now: Long): Boolean {
|
||||
if (attempt.generation != generation || attempt.key != key) return false
|
||||
binding = false; nextBindingAt = now + 5_000L
|
||||
if (success) {
|
||||
bound = true; confirmed = false; pending = null; lastSentAt = null
|
||||
}
|
||||
return true
|
||||
}
|
||||
@Synchronized fun isReady(): Boolean = bound && confirmed
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/** Store terminal events until the business backend acknowledges processing them. */
|
||||
internal class CloudTerminalOutbox(private val file: File?) {
|
||||
private val pending = linkedMapOf<String, JSONObject>()
|
||||
private val sentAt = mutableMapOf<String, Long>()
|
||||
init {
|
||||
file?.let { target ->
|
||||
val backup = File(target.parentFile, target.name + ".bak")
|
||||
if (!target.exists() && backup.exists()) check(backup.renameTo(target))
|
||||
}
|
||||
file?.takeIf { it.exists() }?.let {
|
||||
val array = JSONArray(it.readText())
|
||||
for (i in 0 until array.length()) {
|
||||
val item = array.getJSONObject(i)
|
||||
pending[item.getJSONObject("payload").getString("tid")] = item
|
||||
}
|
||||
}
|
||||
}
|
||||
@Synchronized fun offer(scope: String, topic: String, payload: JSONObject) {
|
||||
pending[payload.getString("tid")] = JSONObject().put("scope", scope).put("topic", topic).put("payload", payload)
|
||||
save()
|
||||
}
|
||||
@Synchronized fun due(scope: String, now: Long): List<JSONObject> = pending.filter { (id, item) ->
|
||||
item.getString("scope") == scope && (sentAt[id] == null || now - sentAt.getValue(id) >= 5_000)
|
||||
}.map { (id, item) -> sentAt[id] = now; JSONObject(item.toString()) }
|
||||
|
||||
@Synchronized fun acknowledge(scope: String, reply: JSONObject): Boolean {
|
||||
if (reply.optString("method") != "flighttask_progress" || reply.optJSONObject("data")?.optInt("result", -1) != 0) return false
|
||||
val id = reply.optString("tid")
|
||||
val item = pending[id] ?: return false
|
||||
if (item.getString("scope") != scope || item.getJSONObject("payload").optString("bid") != reply.optString("bid")) return false
|
||||
pending.remove(id); sentAt.remove(id); save()
|
||||
return true
|
||||
}
|
||||
private fun save() {
|
||||
file?.let {
|
||||
it.parentFile?.mkdirs()
|
||||
val temp = File(it.parentFile, it.name + ".tmp")
|
||||
temp.writeText(JSONArray(pending.values.toList()).toString())
|
||||
// File.renameTo cannot replace an existing file on Windows. Keep a recoverable backup.
|
||||
val backup = File(it.parentFile, it.name + ".bak")
|
||||
if (backup.exists()) check(backup.delete())
|
||||
if (it.exists()) check(it.renameTo(backup))
|
||||
if (!temp.renameTo(it)) {
|
||||
if (backup.exists()) backup.renameTo(it)
|
||||
error("Cannot persist terminal event queue")
|
||||
}
|
||||
backup.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
// DJI FINISHED is emitted for both a completed route and an explicit stop.
|
||||
internal fun cloudWaylineTerminalStatus(stopping: Boolean, interrupted: Boolean, state: Int,
|
||||
lastWayline: Boolean, waypointIndex: Int, waypointCount: Int): String = when {
|
||||
stopping -> "canceled"
|
||||
interrupted || state !in setOf(5, 6, 8) -> "failed"
|
||||
lastWayline && waypointCount > 0 && waypointIndex >= waypointCount - 1 -> "ok"
|
||||
else -> "canceled"
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import android.util.Log
|
||||
import com.dji.wpmzsdk.manager.WPMZManager
|
||||
|
||||
import com.zklh.dronecontroller.core.mission.WaypointMissionService
|
||||
import com.zklh.dronecontroller.core.msdk.DjiCommandResult
|
||||
import dji.sdk.keyvalue.key.FlightControllerKey
|
||||
import dji.v5.et.create
|
||||
import dji.v5.manager.KeyManager
|
||||
import dji.v5.common.callback.CommonCallbacks
|
||||
import dji.v5.common.error.IDJIError
|
||||
import dji.v5.manager.aircraft.waypoint3.WaypointMissionManager
|
||||
import dji.v5.manager.aircraft.waypoint3.WaylineExecutingInfoListener
|
||||
import dji.v5.manager.aircraft.waypoint3.model.WaylineExecutingInfo
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import kotlin.coroutines.resume
|
||||
|
||||
/** Owns cloud KMZ jobs only. Local UI and temporary FlyTo missions retain their own lifecycle. */
|
||||
class CloudWaylineService(
|
||||
private val missions: WaypointMissionService,
|
||||
private val publisher: CloudMissionProgressPublisher?,
|
||||
private val directory: File
|
||||
) {
|
||||
private data class Job(val flightId: String, val file: File, val counts: Map<Int, Int>, val signature: String) {
|
||||
var status = "sent"
|
||||
var percent = 0
|
||||
var waylineId = 0
|
||||
var index = 0
|
||||
var state = 2
|
||||
var started = false
|
||||
var stopping = false
|
||||
var interrupted = false
|
||||
var selectedIds: List<Int> = counts.keys.toList()
|
||||
val missionId get() = file.nameWithoutExtension
|
||||
}
|
||||
private val commands = Mutex()
|
||||
private val jobs = LinkedHashMap<String, Job>()
|
||||
@Volatile private var active: Job? = null
|
||||
private var listenersInstalled = false
|
||||
|
||||
suspend fun prepare(data: JSONObject): DjiCommandResult = commands.withLock { prepareLocked(data) }
|
||||
|
||||
private suspend fun prepareLocked(data: JSONObject): DjiCommandResult {
|
||||
val id = data.taskId()
|
||||
if (id.isBlank()) return DjiCommandResult.failed("缺少 flight_id")
|
||||
val signature = listOf(data.optJSONObject("file")?.optString("fingerprint").orEmpty(),
|
||||
data.optInt("rth_altitude", -1), data.optInt("out_of_control_action", -1)).joinToString("|")
|
||||
jobs[id]?.let {
|
||||
if (it.signature != signature) return DjiCommandResult.failed("同一任务 ID 的航线参数已改变,请创建新任务")
|
||||
return DjiCommandResult.ok("航线任务已准备:" + it.missionId)
|
||||
}
|
||||
if (active != null) return DjiCommandResult.failed("已有云端航线执行中,请先结束当前任务")
|
||||
val prepared = CloudKmzFile.prepare(data, id, directory)
|
||||
val job = Job(id, prepared.file, prepared.counts, signature)
|
||||
Log.i("ZklhCloudWayline", "KMZ ready job=" + id + " path=" + job.file.absolutePath + " bytes=" + job.file.length() + " readable=" + job.file.canRead() + " writable=" + job.file.canWrite() +
|
||||
" sha256=" + CloudKmzFile.sha256(job.file) + " sha256=" + CloudKmzFile.sha256(job.file) + " uploadMode=original-kmz")
|
||||
try {
|
||||
val upload = withTimeout(90_000L) { missions.uploadKmzFile(job.file.absolutePath) }
|
||||
if (!upload.success) {
|
||||
// Diagnostic checks only: do not reinterpret partial SDK validation as permission to fly.
|
||||
fun validation(file: File): String = runCatching {
|
||||
WPMZManager.getInstance().checkValidation(file.absolutePath).toString()
|
||||
}.getOrElse { "校验异常:" + it.message }
|
||||
val diagnostic = "SDK 上传失败:" + upload.message +
|
||||
"\npath=" + job.file.absolutePath + " bytes=" + job.file.length() +
|
||||
" readable=" + job.file.canRead() + " writable=" + job.file.canWrite() +
|
||||
"\noriginalValidation=" + validation(prepared.originalFile) +
|
||||
"\npreparedValidation=" + validation(job.file)
|
||||
Log.e("ZklhCloudWayline", diagnostic)
|
||||
val saved = runCatching { CloudKmzFile.preserveFailure(prepared, diagnostic) }
|
||||
.fold({ ";诊断文件:" + it.absolutePath }, { ";保存诊断失败:" + it.message })
|
||||
job.file.delete()
|
||||
return DjiCommandResult.failed(diagnostic + saved)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
job.file.delete()
|
||||
throw e
|
||||
} finally {
|
||||
prepared.originalFile.delete()
|
||||
}
|
||||
jobs[id] = job
|
||||
// Retain terminal IDs during this app session to prevent retransmitted starts.
|
||||
return DjiCommandResult.ok("航线准备完成:" + job.missionId)
|
||||
}
|
||||
|
||||
suspend fun execute(data: JSONObject): DjiCommandResult = commands.withLock {
|
||||
val id = data.taskId()
|
||||
if (!jobs.containsKey(id)) {
|
||||
val prepared = prepareLocked(data)
|
||||
if (!prepared.success) return@withLock prepared
|
||||
}
|
||||
val job = jobs[id] ?: return@withLock DjiCommandResult.failed("请先下发航线准备命令")
|
||||
if (job.started) return@withLock DjiCommandResult.ok("该任务已启动过,不重复执行:" + id)
|
||||
if (active != null) return@withLock DjiCommandResult.failed("已有云端航线执行中")
|
||||
val array = data.optJSONArray("wayline_ids") ?: data.optJSONArray("waylineIds")
|
||||
val ids = if (array == null) job.counts.keys.toList() else (0 until array.length()).map { array.getInt(it) }.distinct()
|
||||
if (ids.isEmpty() || ids.any { !job.counts.containsKey(it) }) return@withLock DjiCommandResult.failed("航线 ID 不存在于 KMZ")
|
||||
// Native KMZ missions do not require acquiring or releasing virtual-stick authority.
|
||||
val altitude = CloudKmzFile.returnHeight(job.file)
|
||||
if (altitude != null) {
|
||||
val setting = withTimeout(15_000L) { setReturnHeight(altitude) }
|
||||
if (!setting.success) return@withLock setting
|
||||
}
|
||||
installListeners()
|
||||
synchronized(job) {
|
||||
job.selectedIds = ids
|
||||
job.started = true
|
||||
job.waylineId = ids.first()
|
||||
job.status = "in_progress"
|
||||
job.state = 4
|
||||
active = job
|
||||
publish(job)
|
||||
}
|
||||
val result = try { withTimeout(30_000L) { missions.startMission(job.missionId, ids) } }
|
||||
catch (e: Exception) {
|
||||
// Timeout means outcome unknown: keep the active job so a retry cannot start a second flight.
|
||||
synchronized(job) { publish(job, -1, "启动结果待确认:" + e.message) }
|
||||
return@withLock DjiCommandResult.failed("启动结果待确认,请查看飞机状态")
|
||||
}
|
||||
if (!result.success) synchronized(job) { finish(job, "failed", -1, result.message) }
|
||||
result
|
||||
}
|
||||
|
||||
suspend fun pause(data: JSONObject): DjiCommandResult = commands.withLock {
|
||||
val job = matchingActive(data) ?: return@withLock DjiCommandResult.failed("没有匹配的执行中航线")
|
||||
val result = missions.pauseMission()
|
||||
if (result.success) synchronized(job) { job.status = "paused"; job.state = 7; publish(job) }
|
||||
result
|
||||
}
|
||||
|
||||
suspend fun resume(data: JSONObject): DjiCommandResult = commands.withLock {
|
||||
val job = matchingActive(data) ?: return@withLock DjiCommandResult.failed("没有匹配的暂停航线")
|
||||
val result = missions.resumeMission()
|
||||
if (result.success) synchronized(job) { job.interrupted = false; job.status = "in_progress"; job.state = 8; publish(job) }
|
||||
result
|
||||
}
|
||||
|
||||
suspend fun stop(data: JSONObject, cancelPreparedOnly: Boolean = false): DjiCommandResult = commands.withLock {
|
||||
val idsArray = data.optJSONArray("flight_ids")
|
||||
val ids = if (idsArray != null) (0 until idsArray.length()).map { idsArray.getString(it) } else listOf(data.taskId())
|
||||
if (ids.any { it.isBlank() }) return@withLock DjiCommandResult.failed("缺少 flight_id")
|
||||
if (cancelPreparedOnly && ids.any { active?.flightId == it }) return@withLock DjiCommandResult.failed("执行中的任务请使用停止命令")
|
||||
for (id in ids) {
|
||||
val job = jobs[id] ?: continue
|
||||
if (job.status in setOf("ok", "failed", "canceled")) continue
|
||||
if (active === job) {
|
||||
synchronized(job) { job.stopping = true }
|
||||
val result = missions.stopMission(job.missionId)
|
||||
if (!result.success) { synchronized(job) { job.stopping = false }; return@withLock result }
|
||||
}
|
||||
synchronized(job) { if (job.status != "canceled") finish(job, "canceled") }
|
||||
}
|
||||
DjiCommandResult.ok("航线任务已取消")
|
||||
}
|
||||
|
||||
private fun matchingActive(data: JSONObject): Job? = active?.takeIf { data.taskId().isBlank() || data.taskId() == it.flightId }
|
||||
|
||||
private fun installListeners() {
|
||||
if (listenersInstalled) return
|
||||
val manager = WaypointMissionManager.getInstance()
|
||||
manager.addWaypointMissionExecuteStateListener { sdkState ->
|
||||
val job = active ?: return@addWaypointMissionExecuteStateListener
|
||||
synchronized(job) {
|
||||
if (active !== job) return@synchronized
|
||||
Log.i("ZklhCloudWayline", "mission state job=${job.flightId} state=${sdkState?.name} wayline=${job.waylineId} index=${job.index}")
|
||||
when (sdkState?.name) {
|
||||
"PREPARING" -> { job.state = 4; job.status = "in_progress" }
|
||||
"ENTER_WAYLINE" -> { job.state = 5; job.status = "in_progress" }
|
||||
"EXECUTING" -> { job.state = 6; job.status = "in_progress"; job.interrupted = false }
|
||||
"INTERRUPTED" -> { job.state = 7; job.status = "paused" }
|
||||
"RECOVERING" -> { job.state = 8; job.status = "in_progress"; job.interrupted = false }
|
||||
"FINISHED" -> {
|
||||
finish(job, cloudWaylineTerminalStatus(job.stopping, job.interrupted, job.state,
|
||||
job.selectedIds.lastOrNull() == job.waylineId, job.index, job.counts[job.waylineId] ?: 0))
|
||||
return@synchronized
|
||||
}
|
||||
else -> return@synchronized
|
||||
}
|
||||
publish(job)
|
||||
}
|
||||
}
|
||||
manager.addWaylineExecutingInfoListener(object : WaylineExecutingInfoListener {
|
||||
override fun onWaylineExecutingInfoUpdate(info: WaylineExecutingInfo) {
|
||||
val job = active ?: return
|
||||
if (info.missionFileName.removeSuffix(".kmz") != job.missionId) return
|
||||
synchronized(job) {
|
||||
if (active !== job) return@synchronized
|
||||
job.waylineId = info.waylineID
|
||||
job.index = info.currentWaypointIndex
|
||||
val position = job.selectedIds.indexOf(job.waylineId)
|
||||
if (position >= 0) {
|
||||
val previous = job.selectedIds.take(position).sumOf { job.counts[it] ?: 0 }
|
||||
val total = job.selectedIds.sumOf { job.counts[it] ?: 0 }.coerceAtLeast(1)
|
||||
job.percent = maxOf(job.percent, ((previous + job.index) * 100 / total).coerceIn(1, 99))
|
||||
}
|
||||
publish(job)
|
||||
}
|
||||
}
|
||||
override fun onWaylineExecutingInterruptReasonUpdate(error: IDJIError?) {
|
||||
val job = active ?: return
|
||||
if (error != null) synchronized(job) {
|
||||
if (active !== job || job.stopping) return@synchronized
|
||||
job.interrupted = true; job.status = "paused"; job.state = 7
|
||||
publish(job, -1, error.toString())
|
||||
}
|
||||
}
|
||||
})
|
||||
listenersInstalled = true
|
||||
}
|
||||
|
||||
private fun finish(job: Job, status: String, code: Int = 0, message: String = status) {
|
||||
Log.i("ZklhCloudWayline", "mission terminal job=${job.flightId} status=$status code=$code")
|
||||
job.status = status; job.state = 9; job.started = true
|
||||
if (status == "ok") job.percent = 100
|
||||
publish(job, if (status == "failed" && code == 0) -1 else code, message)
|
||||
if (active === job) active = null
|
||||
job.file.delete()
|
||||
}
|
||||
|
||||
private fun publish(job: Job, code: Int = 0, message: String = "success") {
|
||||
publisher?.publishFlightTaskProgress(job.flightId, job.status, job.percent, job.waylineId, job.index,
|
||||
code, message, job.state)
|
||||
}
|
||||
|
||||
private suspend fun setReturnHeight(height: Int): DjiCommandResult = suspendCancellableCoroutine { continuation ->
|
||||
KeyManager.getInstance().setValue(FlightControllerKey.KeyGoHomeHeight.create(), height,
|
||||
object : CommonCallbacks.CompletionCallback {
|
||||
override fun onSuccess() { if (continuation.isActive) continuation.resume(DjiCommandResult.ok("返航高度已设置")) }
|
||||
override fun onFailure(error: IDJIError) { if (continuation.isActive) continuation.resume(DjiCommandResult.failed(error)) }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private fun JSONObject.taskId(): String = listOf("flight_id", "flightId", "job_id", "jobId", "mission_id", "missionId")
|
||||
.firstNotNullOfOrNull { optString(it).takeIf(String::isNotBlank) }.orEmpty()
|
||||
@@ -107,52 +107,58 @@ class FlyToService {
|
||||
height: Double,
|
||||
maxSpeed: Int = 14,
|
||||
securityTakeoffHeight: Int = 20,
|
||||
flyToMode: FlyToMode = FlyToMode.SET_HEIGHT
|
||||
): DjiCommandResult =
|
||||
flyToMode: FlyToMode = FlyToMode.SET_HEIGHT,
|
||||
commanderFlightHeight: Double? = null
|
||||
): DjiCommandResult {
|
||||
if (!SafetyInterlock.FLIGHT_COMMANDS_ENABLED) {
|
||||
DjiCommandResult.failed(SafetyInterlock.LOCKED_MESSAGE)
|
||||
} else {
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
val targetHeight = height.normalizedFlyToHeight()
|
||||
val safeTakeoffHeight = securityTakeoffHeight
|
||||
.coerceAtLeast(1)
|
||||
.coerceAtMost(targetHeight)
|
||||
val target = FlyToTarget().apply {
|
||||
targetLocation = LocationCoordinate3D(latitude, longitude, targetHeight.toDouble())
|
||||
this.maxSpeed = maxSpeed
|
||||
this.securityTakeoffHeight = safeTakeoffHeight
|
||||
}
|
||||
Log.d(
|
||||
FlyToLogTag,
|
||||
"startFlyTo lat=$latitude lon=$longitude requestedHeight=$height targetHeight=$targetHeight " +
|
||||
"mode=$flyToMode maxSpeed=$maxSpeed securityTakeoffHeight=$safeTakeoffHeight " +
|
||||
"heightRange=${status.value.heightMin}..${status.value.heightMax}"
|
||||
)
|
||||
manager.startMission(
|
||||
target,
|
||||
null,
|
||||
callback(
|
||||
continuation,
|
||||
"指点飞行已开始",
|
||||
onSuccess = {
|
||||
_status.update {
|
||||
it.copy(
|
||||
state = FlyToMissionState.PREPARE,
|
||||
mode = flyToMode,
|
||||
height = targetHeight,
|
||||
targetLatitude = latitude,
|
||||
targetLongitude = longitude,
|
||||
targetAltitude = targetHeight.toDouble()
|
||||
)
|
||||
}
|
||||
},
|
||||
onFailure = {
|
||||
_status.update { it.copy(state = FlyToMissionState.IDLE) }
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
return DjiCommandResult.failed(SafetyInterlock.LOCKED_MESSAGE)
|
||||
}
|
||||
val targetHeight = height.normalizedFlyToHeight()
|
||||
val flightHeight = commanderFlightHeight?.normalizedFlyToHeight()
|
||||
val safeTakeoffHeight = securityTakeoffHeight.coerceAtLeast(1).coerceAtMost(targetHeight)
|
||||
|
||||
// MSDK 5.18's industry delegate prioritizes mode over height when both are set.
|
||||
// Apply each setting separately and await its acknowledgement before starting.
|
||||
val configured = updateFlyToParam(height = flightHeight, mode = flyToMode)
|
||||
if (!configured.success) {
|
||||
return DjiCommandResult.failed("指点飞行参数设置失败,未启动任务:${configured.message}")
|
||||
}
|
||||
return suspendCancellableCoroutine { continuation ->
|
||||
val target = FlyToTarget().apply {
|
||||
targetLocation = LocationCoordinate3D(latitude, longitude, targetHeight.toDouble())
|
||||
this.maxSpeed = maxSpeed
|
||||
this.securityTakeoffHeight = safeTakeoffHeight
|
||||
}
|
||||
Log.d(
|
||||
FlyToLogTag,
|
||||
"flight-height-v2 startMission lat=$latitude lon=$longitude targetHeight=$targetHeight " +
|
||||
"flightHeight=$flightHeight requestedFlightHeight=$commanderFlightHeight " +
|
||||
"mode=$flyToMode securityTakeoffHeight=$safeTakeoffHeight maxSpeed=$maxSpeed"
|
||||
)
|
||||
manager.startMission(
|
||||
target,
|
||||
null, // Settings above have already been acknowledged; avoid asynchronous reapplication.
|
||||
callback(
|
||||
continuation,
|
||||
"指点飞行已开始",
|
||||
onSuccess = {
|
||||
_status.update {
|
||||
it.copy(
|
||||
state = FlyToMissionState.PREPARE,
|
||||
mode = flyToMode,
|
||||
height = flightHeight ?: it.height,
|
||||
targetLatitude = latitude,
|
||||
targetLongitude = longitude,
|
||||
targetAltitude = targetHeight.toDouble()
|
||||
)
|
||||
}
|
||||
},
|
||||
onFailure = { _status.update { it.copy(state = FlyToMissionState.IDLE) } }
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
suspend fun stopFlyTo(): DjiCommandResult =
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
@@ -213,21 +219,21 @@ class FlyToService {
|
||||
suspend fun updateFlyToParam(
|
||||
height: Int? = null,
|
||||
mode: FlyToMode? = null
|
||||
): DjiCommandResult =
|
||||
): DjiCommandResult {
|
||||
if (!SafetyInterlock.FLIGHT_COMMANDS_ENABLED) {
|
||||
DjiCommandResult.failed(SafetyInterlock.LOCKED_MESSAGE)
|
||||
} else {
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
val param = FlyToParam().apply {
|
||||
if (mode != null) flyToMode = mode
|
||||
if (height != null) this.height = height.toDouble().normalizedFlyToHeight()
|
||||
}
|
||||
manager.updateMissionParam(
|
||||
param,
|
||||
callback(continuation, "指点飞行参数已更新")
|
||||
)
|
||||
}
|
||||
return DjiCommandResult.failed(SafetyInterlock.LOCKED_MESSAGE)
|
||||
}
|
||||
if (mode != null) {
|
||||
val modeResult = setFlyToMode(mode)
|
||||
if (!modeResult.success) return modeResult
|
||||
}
|
||||
if (height != null) {
|
||||
val heightResult = setFlyToHeight(height)
|
||||
if (!heightResult.success) return heightResult
|
||||
}
|
||||
return DjiCommandResult.ok("指点飞行参数已更新")
|
||||
}
|
||||
|
||||
|
||||
suspend fun setFlyToMode(mode: FlyToMode): DjiCommandResult =
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
|
||||
+4
-2
@@ -1,5 +1,7 @@
|
||||
package com.zklh.dronecontroller.core.livestream
|
||||
|
||||
import dji.sampleV5.aircraft.BuildConfig
|
||||
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import com.zklh.dronecontroller.core.msdk.DjiCommandResult
|
||||
@@ -29,8 +31,8 @@ import kotlin.coroutines.resume
|
||||
private const val LiveStreamLogTag = "ZklhLiveStream"
|
||||
private const val UrlTypeRtmp = 1
|
||||
private const val UrlTypeWhip = 4
|
||||
private const val ZlmRtmpPort = 1935
|
||||
private const val ZlmDefaultApp = "live"
|
||||
private const val ZlmRtmpPort = BuildConfig.CLOUD_RTMP_PORT
|
||||
private const val ZlmDefaultApp = BuildConfig.CLOUD_RTMP_DEFAULT_APP
|
||||
private const val DefaultLiveQuality = 3
|
||||
|
||||
data class LiveStreamingState(
|
||||
|
||||
+3
-3
@@ -56,7 +56,7 @@ class WaypointMissionService {
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
var resumed = false
|
||||
uploadKmzFile(kmzPath) { update ->
|
||||
if (resumed) {
|
||||
if (resumed || !continuation.isActive) {
|
||||
return@uploadKmzFile
|
||||
}
|
||||
when {
|
||||
@@ -166,11 +166,11 @@ class WaypointMissionService {
|
||||
): CommonCallbacks.CompletionCallback {
|
||||
return object : CommonCallbacks.CompletionCallback {
|
||||
override fun onSuccess() {
|
||||
continuation.resume(DjiCommandResult.ok(successMessage))
|
||||
if (continuation.isActive) continuation.resume(DjiCommandResult.ok(successMessage))
|
||||
}
|
||||
|
||||
override fun onFailure(error: IDJIError) {
|
||||
continuation.resume(DjiCommandResult.failed(error))
|
||||
if (continuation.isActive) continuation.resume(DjiCommandResult.failed(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.zklh.dronecontroller.core.telemetry
|
||||
|
||||
import dji.sdk.keyvalue.key.*
|
||||
import dji.sdk.keyvalue.value.common.CameraLensType
|
||||
import dji.sdk.keyvalue.value.common.ComponentIndexType
|
||||
import dji.v5.manager.KeyManager
|
||||
|
||||
/** Read-only camera telemetry. Never fabricate values for unsupported SDK keys. */
|
||||
internal class CameraCloudTelemetry(private val publish: (Map<String, Any>, Map<String, Any>) -> Unit) {
|
||||
private val holder = Any()
|
||||
private val camera = mutableMapOf<String, Any>()
|
||||
private val payload = mutableMapOf<String, Any>()
|
||||
private val readers = mutableListOf<() -> Unit>()
|
||||
private var started = false
|
||||
|
||||
@Synchronized private fun put(target: MutableMap<String, Any>, name: String, value: Any?) {
|
||||
if (target[name] == value) return
|
||||
if (value == null) target.remove(name) else target[name] = value
|
||||
publish(camera.toMap(), payload.toMap())
|
||||
}
|
||||
|
||||
private fun <T> watch(key: DJIKey<T>, receive: (T?) -> Unit) {
|
||||
readers += { runCatching { KeyManager.getInstance().getValue(key) }.getOrNull()?.let(receive) }
|
||||
runCatching { KeyManager.getInstance().listen(key, holder, true) { _, value -> receive(value) } }
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (started) return
|
||||
started = true
|
||||
val main = ComponentIndexType.LEFT_OR_MAIN
|
||||
listOf("wide" to CameraLensType.CAMERA_LENS_WIDE, "zoom" to CameraLensType.CAMERA_LENS_ZOOM).forEach { (prefix, lens) ->
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyExposureMode, main, lens)) {
|
||||
put(camera, "${prefix}_exposure_mode", cloudExposureMode(it?.name))
|
||||
}
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyISO, main, lens)) {
|
||||
put(camera, "${prefix}_iso", cloudCameraIso(it?.name))
|
||||
}
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyShutterSpeed, main, lens)) {
|
||||
put(camera, "${prefix}_shutter_speed", cloudShutterSpeed(it?.name))
|
||||
}
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyExposureCompensation, main, lens)) {
|
||||
put(camera, "${prefix}_exposure_value", cloudExposureValue(it?.name))
|
||||
}
|
||||
}
|
||||
val zoom = CameraLensType.CAMERA_LENS_ZOOM
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyCameraFocusMode, main, zoom)) {
|
||||
put(camera, "zoom_focus_mode", cloudFocusMode(it?.name))
|
||||
}
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyCameraFocusRingValue, main, zoom)) { put(camera, "zoom_focus_value", it) }
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyCameraFocusRingMinValue, main, zoom)) { put(camera, "zoom_min_focus_value", it) }
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyCameraFocusRingMaxValue, main, zoom)) { put(camera, "zoom_max_focus_value", it) }
|
||||
watch(KeyTools.createKey(CameraKey.KeyCameraStorageInfos, main)) { infos ->
|
||||
val storage = infos?.currentCameraStorageInfo
|
||||
put(camera, "remain_photo_num", storage?.availablePhotoCount)
|
||||
put(camera, "remain_record_duration", storage?.availableVideoDuration)
|
||||
put(camera, "_storage_total_mb", storage?.storageCapacity)
|
||||
put(camera, "_storage_remaining_mb", storage?.storageLeftCapacity)
|
||||
}
|
||||
val thermal = CameraLensType.CAMERA_LENS_THERMAL
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalGlobalMaxTemperature, main, thermal)) { put(payload, "thermal_global_temperature_max", it) }
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalGlobalMinTemperature, main, thermal)) { put(payload, "thermal_global_temperature_min", it) }
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalGainMode, main, thermal)) {
|
||||
put(payload, "thermal_gain_mode", when(it?.name) { "AUTO" -> 0; "LOW" -> 1; "HIGH" -> 2; else -> null })
|
||||
}
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalIsothermEnabled, main, thermal)) {
|
||||
put(payload, "thermal_isotherm_state", it?.let { enabled -> if(enabled) 1 else 0 })
|
||||
}
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalIsothermLowerValue, main, thermal)) { put(payload, "thermal_isotherm_lower_limit", it) }
|
||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalIsothermUpperValue, main, thermal)) { put(payload, "thermal_isotherm_upper_limit", it) }
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun refresh() { readers.toList().forEach { it() } }
|
||||
fun stop() {
|
||||
runCatching { KeyManager.getInstance().cancelListen(holder) }
|
||||
readers.clear()
|
||||
started = false
|
||||
synchronized(this) { camera.clear(); payload.clear(); publish(emptyMap(), emptyMap()) }
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.zklh.dronecontroller.core.telemetry
|
||||
|
||||
import android.util.Log
|
||||
import dji.sdk.keyvalue.key.CameraKey
|
||||
import dji.sdk.keyvalue.key.KeyTools
|
||||
import dji.sdk.keyvalue.value.common.ComponentIndexType
|
||||
import dji.v5.manager.KeyManager
|
||||
|
||||
/** Reads the same source range used by DJI's lens selector. Never switches lenses. */
|
||||
internal class CameraStreamCapabilities(private val publish: (Map<String, List<String>>) -> Unit) {
|
||||
private val holder = Any()
|
||||
private val sources = mutableMapOf<String, List<String>>()
|
||||
private val cameras = listOf(ComponentIndexType.LEFT_OR_MAIN, ComponentIndexType.RIGHT,
|
||||
ComponentIndexType.UP, ComponentIndexType.PORT_1, ComponentIndexType.PORT_2,
|
||||
ComponentIndexType.PORT_3, ComponentIndexType.PORT_4)
|
||||
private var started = false
|
||||
|
||||
@Synchronized private fun update(component: String, values: List<String>) {
|
||||
val normalized = values.distinct().sorted()
|
||||
if (sources[component].orEmpty() == normalized) return
|
||||
if (normalized.isEmpty()) sources.remove(component) else sources[component] = normalized
|
||||
Log.d("CloudCameraCapacity", "camera=$component streamSources=$normalized")
|
||||
publish(sources.toMap())
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (started) return
|
||||
started = true
|
||||
cameras.forEach { camera ->
|
||||
runCatching {
|
||||
KeyManager.getInstance().listen(KeyTools.createKey(CameraKey.KeyCameraVideoStreamSourceRange, camera), holder, true) { _, value ->
|
||||
update(camera.name, value.orEmpty().map { it.name })
|
||||
}
|
||||
KeyManager.getInstance().listen(KeyTools.createKey(CameraKey.KeyConnection, camera), holder, true) { _, connected ->
|
||||
if (connected == false) update(camera.name, emptyList())
|
||||
}
|
||||
}.onFailure { Log.d("CloudCameraCapacity", "source range unavailable: $camera", it) }
|
||||
}
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
if (!started) return
|
||||
cameras.forEach { camera ->
|
||||
runCatching {
|
||||
val manager = KeyManager.getInstance()
|
||||
val connected = manager.getValue(KeyTools.createKey(CameraKey.KeyConnection, camera))
|
||||
val range = if (connected == false) null else
|
||||
manager.getValue(KeyTools.createKey(CameraKey.KeyCameraVideoStreamSourceRange, camera))
|
||||
update(camera.name, range.orEmpty().map { it.name })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
started = false
|
||||
runCatching { KeyManager.getInstance().cancelListen(holder) }
|
||||
synchronized(this) { sources.clear(); publish(emptyMap()) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.zklh.dronecontroller.core.telemetry
|
||||
|
||||
internal fun cloudCameraIso(name: String?): Int? = isoCodes[name]
|
||||
internal fun cloudShutterSpeed(name: String?): Int? = shutterCodes[name]
|
||||
internal fun cloudExposureValue(name: String?): Int? = evCodes[name]
|
||||
internal fun cloudExposureMode(name: String?): Int? = when(name) { "PROGRAM" -> 1; "SHUTTER_PRIORITY" -> 2; "APERTURE_PRIORITY" -> 3; "MANUAL" -> 4; else -> null }
|
||||
internal fun cloudFocusMode(name: String?): Int? = when(name) { "MANUAL" -> 0; "AF" -> 1; "AFC" -> 2; else -> null }
|
||||
internal fun cloudGear(raw: Int): Int? = when(raw) { 0 -> 6; 1 -> 0; 2 -> 1; 3 -> 5; 4 -> 8; 5 -> 7; 6 -> 9; else -> null }
|
||||
private val isoCodes = mapOf(
|
||||
"ISO_AUTO" to 0,
|
||||
"ISO_AUTO_HIGH_SENSE" to 1,
|
||||
"ISO_50" to 2,
|
||||
"ISO_100" to 3,
|
||||
"ISO_200" to 4,
|
||||
"ISO_400" to 5,
|
||||
"ISO_800" to 6,
|
||||
"ISO_1600" to 7,
|
||||
"ISO_3200" to 8,
|
||||
"ISO_6400" to 9,
|
||||
"ISO_12800" to 10,
|
||||
"ISO_25600" to 11,
|
||||
"ISO_51200" to 12,
|
||||
"ISO_102400" to 13,
|
||||
"ISO_FIXED" to 255
|
||||
)
|
||||
private val shutterCodes = mapOf(
|
||||
"SHUTTER_SPEED1_8000" to 0,
|
||||
"SHUTTER_SPEED1_6400" to 1,
|
||||
"SHUTTER_SPEED1_6000" to 2,
|
||||
"SHUTTER_SPEED1_5000" to 3,
|
||||
"SHUTTER_SPEED1_4000" to 4,
|
||||
"SHUTTER_SPEED1_3200" to 5,
|
||||
"SHUTTER_SPEED1_3000" to 6,
|
||||
"SHUTTER_SPEED1_2500" to 7,
|
||||
"SHUTTER_SPEED1_2000" to 8,
|
||||
"SHUTTER_SPEED1_1600" to 9,
|
||||
"SHUTTER_SPEED1_1500" to 10,
|
||||
"SHUTTER_SPEED1_1250" to 11,
|
||||
"SHUTTER_SPEED1_1000" to 12,
|
||||
"SHUTTER_SPEED1_800" to 13,
|
||||
"SHUTTER_SPEED1_725" to 14,
|
||||
"SHUTTER_SPEED1_640" to 15,
|
||||
"SHUTTER_SPEED1_500" to 16,
|
||||
"SHUTTER_SPEED1_400" to 17,
|
||||
"SHUTTER_SPEED1_350" to 18,
|
||||
"SHUTTER_SPEED1_320" to 19,
|
||||
"SHUTTER_SPEED1_250" to 20,
|
||||
"SHUTTER_SPEED1_240" to 21,
|
||||
"SHUTTER_SPEED1_200" to 22,
|
||||
"SHUTTER_SPEED1_180" to 23,
|
||||
"SHUTTER_SPEED1_160" to 24,
|
||||
"SHUTTER_SPEED1_125" to 25,
|
||||
"SHUTTER_SPEED1_120" to 26,
|
||||
"SHUTTER_SPEED1_100" to 27,
|
||||
"SHUTTER_SPEED1_90" to 28,
|
||||
"SHUTTER_SPEED1_80" to 29,
|
||||
"SHUTTER_SPEED1_60" to 30,
|
||||
"SHUTTER_SPEED1_50" to 31,
|
||||
"SHUTTER_SPEED1_40" to 32,
|
||||
"SHUTTER_SPEED1_30" to 33,
|
||||
"SHUTTER_SPEED1_25" to 34,
|
||||
"SHUTTER_SPEED1_20" to 35,
|
||||
"SHUTTER_SPEED1_15" to 36,
|
||||
"SHUTTER_SPEED1_12DOT5" to 37,
|
||||
"SHUTTER_SPEED1_10" to 38,
|
||||
"SHUTTER_SPEED1_8" to 39,
|
||||
"SHUTTER_SPEED1_6DOT25" to 40,
|
||||
"SHUTTER_SPEED1_5" to 41,
|
||||
"SHUTTER_SPEED1_4" to 42,
|
||||
"SHUTTER_SPEED1_3" to 43,
|
||||
"SHUTTER_SPEED1_2DOT5" to 44,
|
||||
"SHUTTER_SPEED1_2" to 45,
|
||||
"SHUTTER_SPEED1_1DOT67" to 46,
|
||||
"SHUTTER_SPEED1_1DOT25" to 47,
|
||||
"SHUTTER_SPEED1" to 48,
|
||||
"SHUTTER_SPEED1DOT3" to 49,
|
||||
"SHUTTER_SPEED1DOT6" to 50,
|
||||
"SHUTTER_SPEED2" to 51,
|
||||
"SHUTTER_SPEED2DOT5" to 52,
|
||||
"SHUTTER_SPEED3" to 53,
|
||||
"SHUTTER_SPEED3DOT2" to 54,
|
||||
"SHUTTER_SPEED4" to 55,
|
||||
"SHUTTER_SPEED5" to 56,
|
||||
"SHUTTER_SPEED6" to 57,
|
||||
"SHUTTER_SPEED7" to 58,
|
||||
"SHUTTER_SPEED8" to 59,
|
||||
"SHUTTER_SPEED_AUTO" to 65534
|
||||
)
|
||||
private val evCodes = mapOf(
|
||||
"NEG_5P0EV" to 1,
|
||||
"NEG_4P7EV" to 2,
|
||||
"NEG_4P3EV" to 3,
|
||||
"NEG_4P0EV" to 4,
|
||||
"NEG_3P7EV" to 5,
|
||||
"NEG_3P3EV" to 6,
|
||||
"NEG_3P0EV" to 7,
|
||||
"NEG_2P7EV" to 8,
|
||||
"NEG_2P3EV" to 9,
|
||||
"NEG_2P0EV" to 10,
|
||||
"NEG_1P7EV" to 11,
|
||||
"NEG_1P3EV" to 12,
|
||||
"NEG_1P0EV" to 13,
|
||||
"NEG_0P7EV" to 14,
|
||||
"NEG_0P3EV" to 15,
|
||||
"NEG_0EV" to 16,
|
||||
"POS_0P3EV" to 17,
|
||||
"POS_0P7EV" to 18,
|
||||
"POS_1P0EV" to 19,
|
||||
"POS_1P3EV" to 20,
|
||||
"POS_1P7EV" to 21,
|
||||
"POS_2P0EV" to 22,
|
||||
"POS_2P3EV" to 23,
|
||||
"POS_2P7EV" to 24,
|
||||
"POS_3P0EV" to 25,
|
||||
"POS_3P3EV" to 26,
|
||||
"POS_3P7EV" to 27,
|
||||
"POS_4P0EV" to 28,
|
||||
"POS_4P3EV" to 29,
|
||||
"POS_4P7EV" to 30,
|
||||
"POS_5P0EV" to 31,
|
||||
"FIXED" to 255
|
||||
)
|
||||
+22
-2
@@ -127,7 +127,7 @@ data class TelemetrySnapshot(
|
||||
val landingConfirmationNeeded: Boolean = false,
|
||||
val simulatorStarted: Boolean = false,
|
||||
val firmwareVersion: String = "",
|
||||
val gear: Int = 1,
|
||||
val gear: Int = 65535, // SDK UNKNOWN; do not invent a switch mode before telemetry arrives.
|
||||
val gpsSatelliteCount: Int = 0,
|
||||
val gpsSignalLevel: Int = 0,
|
||||
val gpsValid: Boolean = false,
|
||||
@@ -152,6 +152,7 @@ data class TelemetrySnapshot(
|
||||
val payloadCameraTypeValue: Int = 0,
|
||||
val cameraComponent: String = ComponentIndexType.LEFT_OR_MAIN.name,
|
||||
val cameraIdentities: List<TelemetryCameraIdentity> = emptyList(),
|
||||
val cameraStreamSources: Map<String, List<String>> = emptyMap(),
|
||||
val batteryPercentNeededToLand: Int = 7,
|
||||
val batteryPercentNeededToLandKnown: Boolean = false,
|
||||
val batteryPercentNeededToGoHome: Int = 14,
|
||||
@@ -187,6 +188,8 @@ data class TelemetrySnapshot(
|
||||
val laserTargetLongitude: Double = 0.0,
|
||||
val laserTargetAltitude: Double = 0.0,
|
||||
val thermalMaxTemperature: Double = 0.0,
|
||||
val cameraCloudFields: Map<String, Any> = emptyMap(),
|
||||
val payloadCloudFields: Map<String, Any> = emptyMap(),
|
||||
val error: String? = null
|
||||
)
|
||||
|
||||
@@ -256,6 +259,12 @@ class TelemetryRepository(
|
||||
}
|
||||
private val _state = MutableStateFlow(TelemetrySnapshot())
|
||||
val state: StateFlow<TelemetrySnapshot> = _state.asStateFlow()
|
||||
private val cameraStreamCapabilities = CameraStreamCapabilities { sources ->
|
||||
_state.update { it.copy(cameraStreamSources = sources) }
|
||||
}
|
||||
private val cameraCloudTelemetry = CameraCloudTelemetry { camera, payload ->
|
||||
_state.update { it.copy(cameraCloudFields = camera, payloadCloudFields = payload) }
|
||||
}
|
||||
|
||||
private var started = false
|
||||
private var rtkStartInProgress = false
|
||||
@@ -382,7 +391,7 @@ class TelemetryRepository(
|
||||
}
|
||||
}
|
||||
listenSafely("KeyRemoteControllerFlightMode", KeyTools.createKey(FlightControllerKey.KeyRemoteControllerFlightMode)) { mode: RemoteControllerFlightMode? ->
|
||||
_state.update { it.copy(gear = mode?.value() ?: it.gear, error = null) }
|
||||
_state.update { it.copy(gear = mode?.value() ?: 65535, error = null) }
|
||||
}
|
||||
listenSafely("KeyGPSSatelliteCount", KeyTools.createKey(FlightControllerKey.KeyGPSSatelliteCount)) { count: Int? ->
|
||||
val value = count ?: 0
|
||||
@@ -583,6 +592,8 @@ class TelemetryRepository(
|
||||
listenRemoteControllerTelemetry()
|
||||
startAndroidLocationFallback()
|
||||
listenCameraTelemetry()
|
||||
cameraCloudTelemetry.start()
|
||||
cameraStreamCapabilities.start()
|
||||
listenAdditionalCameraIdentities()
|
||||
listenGimbalTelemetry()
|
||||
listenRtkTelemetry()
|
||||
@@ -590,6 +601,8 @@ class TelemetryRepository(
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
cameraCloudTelemetry.stop()
|
||||
cameraStreamCapabilities.stop()
|
||||
runCatching { KeyManager.getInstance().cancelListen(listenHolder) }
|
||||
runCatching { locationManager?.removeUpdates(androidLocationListener) }
|
||||
runCatching { rtkCenter.removeRTKLocationInfoListener(rtkLocationInfoListener) }
|
||||
@@ -633,11 +646,17 @@ class TelemetryRepository(
|
||||
}
|
||||
}
|
||||
|
||||
/** Recover values that were unavailable during the initial SDK connection callbacks. */
|
||||
fun refreshForCloud() {
|
||||
if (started) refreshCurrentValues("cloud_periodic_refresh")
|
||||
}
|
||||
|
||||
private fun refreshCurrentValues(reason: String, force: Boolean = false) {
|
||||
val now = System.currentTimeMillis()
|
||||
if (!force && now - lastCurrentValueRefreshAtMs < CURRENT_VALUE_REFRESH_MIN_INTERVAL_MS) return
|
||||
lastCurrentValueRefreshAtMs = now
|
||||
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) }
|
||||
@@ -759,6 +778,7 @@ class TelemetryRepository(
|
||||
currentValue("KeyWindSpeed", KeyTools.createKey(FlightControllerKey.KeyWindSpeed))
|
||||
?.let { speed: Int -> _state.update { it.copy(windSpeed = speed, error = null) } }
|
||||
|
||||
cameraCloudTelemetry.refresh()
|
||||
refreshBatteryValues()
|
||||
refreshRemoteControllerValues()
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.zklh.dronecontroller.ui
|
||||
|
||||
import dji.sampleV5.aircraft.BuildConfig
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.Paint
|
||||
@@ -204,7 +206,7 @@ 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 = "http://uav.zklhjs.com/p"
|
||||
private const val DefaultThirdCloudUrl = BuildConfig.CLOUD_BASE_URL
|
||||
private const val DefaultThirdCloudTenantName = "中科联航"
|
||||
private const val DefaultThirdCloudUsername = "zklh"
|
||||
private const val DefaultThirdCloudPassword = "zklh@123"
|
||||
@@ -325,12 +327,13 @@ fun DroneControllerScreen() {
|
||||
val warningState by warningRepository.state.collectAsState()
|
||||
val latestWarningState by rememberUpdatedState(warningState)
|
||||
val cloudLoginClient = remember { CloudLoginClient() }
|
||||
val cloudMqttService = remember { CloudMqttService(cloudLoginClient) }
|
||||
val cloudMqttService = remember { CloudMqttService(cloudLoginClient, java.io.File(context.applicationContext.filesDir, "cloud-terminal-events.json")) }
|
||||
val cloudMediaUpload = remember(appContext, cloudMqttService) {
|
||||
CloudMediaUploadService(appContext) { cloudMqttService.state.value.session }
|
||||
}
|
||||
val cloudCommandExecutor = remember(flightControl, cameraMedia, flyToService, liveStreaming, virtualStick, waypointMission, cloudMediaUpload) {
|
||||
CloudCommandExecutor(
|
||||
context = appContext,
|
||||
flightControl = flightControl,
|
||||
cameraMedia = cameraMedia,
|
||||
flyToService = flyToService,
|
||||
@@ -442,6 +445,17 @@ fun DroneControllerScreen() {
|
||||
cloudMqttService.updateDeviceState(sdkState)
|
||||
}
|
||||
|
||||
LaunchedEffect(cloudState.connected, sdkState.productConnected) {
|
||||
if (cloudState.connected && sdkState.productConnected) {
|
||||
while (true) {
|
||||
telemetryRepository.refreshForCloud()
|
||||
delay(5000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(liveState) { cloudMqttService.updateLiveState(liveState) }
|
||||
|
||||
LaunchedEffect(telemetry) {
|
||||
cloudMqttService.updateTelemetry(telemetry)
|
||||
}
|
||||
@@ -2017,7 +2031,7 @@ private fun ThirdPartyActionRow(label: String) {
|
||||
|
||||
private fun normalizeCloudUrl(rawUrl: String): String {
|
||||
val trimmed = rawUrl.trim()
|
||||
if (trimmed.isBlank()) return "http://uav.zklhjs.com/p"
|
||||
if (trimmed.isBlank()) return BuildConfig.CLOUD_BASE_URL
|
||||
return when {
|
||||
trimmed.startsWith("http://", ignoreCase = true) -> trimmed
|
||||
trimmed.startsWith("https://", ignoreCase = true) -> trimmed
|
||||
@@ -2029,7 +2043,7 @@ 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 ?: "uav.zklhjs.com"
|
||||
val host = parsed.host ?: BuildConfig.CLOUD_PLATFORM_HOST
|
||||
val port = parsed.port.takeIf { it > 0 }?.let { ":$it" }.orEmpty()
|
||||
return "$scheme://$host$port"
|
||||
}
|
||||
@@ -2213,7 +2227,7 @@ private fun PreflightScreen(
|
||||
Text("健康管理", fontSize = 14.sp, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
StatusChip(Icons.Filled.Route, if (sdkState.productConnected) "N 挡" else "--", if (sdkState.productConnected) Color.Black else PilotMuted)
|
||||
StatusChip(Icons.Filled.Route, if (sdkState.productConnected) remoteControllerGearText(telemetry.gear) else "--", if (sdkState.productConnected) Color.Black else PilotMuted)
|
||||
StatusChip(Icons.Filled.BatteryFull, batteryStatusText(sdkState.productConnected, telemetry), if (sdkState.productConnected) Color.Black else PilotMuted)
|
||||
StatusChip(Icons.Filled.Radio, if (sdkState.productConnected) "100%" else "--", if (sdkState.productConnected) Color.Black else PilotMuted)
|
||||
StatusChip(Icons.Filled.Home, if (sdkState.productConnected) "未设置" else "--", if (sdkState.productConnected) PilotOrange else PilotMuted)
|
||||
@@ -4349,27 +4363,27 @@ private fun flightTopStatusText(
|
||||
!sdkState.isRegistered -> "SDK 已初始化 - 等待注册"
|
||||
!sdkState.productConnected && sdkState.productLinkConnected -> "RC 在线 - 无人机未连接"
|
||||
!sdkState.productConnected -> "无人机未连接"
|
||||
!flightCommandsEnabled -> "N 挡 - 飞控安全锁定"
|
||||
prepareProgress > 0f -> "N 挡 - 起飞准备 ${(prepareProgress * 100).roundToInt()}%"
|
||||
takeoffProgress > 0f -> "N 挡 - 起飞确认 ${(takeoffProgress * 100).roundToInt()}%"
|
||||
telemetry.landingConfirmationNeeded -> "N 挡 - 自动降落确认中"
|
||||
autoLanding -> "N 挡 - 自动降落"
|
||||
returningHome -> "N 挡 - 自动返航"
|
||||
!flightCommandsEnabled -> "${remoteControllerGearText(telemetry.gear)} - 飞控安全锁定"
|
||||
prepareProgress > 0f -> "${remoteControllerGearText(telemetry.gear)} - 起飞准备 ${(prepareProgress * 100).roundToInt()}%"
|
||||
takeoffProgress > 0f -> "${remoteControllerGearText(telemetry.gear)} - 起飞确认 ${(takeoffProgress * 100).roundToInt()}%"
|
||||
telemetry.landingConfirmationNeeded -> "${remoteControllerGearText(telemetry.gear)} - 自动降落确认中"
|
||||
autoLanding -> "${remoteControllerGearText(telemetry.gear)} - 自动降落"
|
||||
returningHome -> "${remoteControllerGearText(telemetry.gear)} - 自动返航"
|
||||
grounded -> groundedTopStatusText(telemetry, simulatorEnabled, stickEnabled, modeText)
|
||||
takeoffIssued && !airborne -> "N 挡 - 起飞中"
|
||||
modeText in activeFlightModeLabels -> "N 挡 - $modeText"
|
||||
takeoffIssued && !airborne -> "${remoteControllerGearText(telemetry.gear)} - 起飞中"
|
||||
modeText in activeFlightModeLabels -> "${remoteControllerGearText(telemetry.gear)} - $modeText"
|
||||
flightActionStatus.isNotBlank() &&
|
||||
(airborne || flightActionStatus.contains("起飞") || flightActionStatus.contains("返航") || flightActionStatus.contains("降落")) ->
|
||||
"N 挡 - $flightActionStatus"
|
||||
"${remoteControllerGearText(telemetry.gear)} - $flightActionStatus"
|
||||
airborne -> {
|
||||
val mode = if (simulatorEnabled) "模拟飞行" else if (moving) "飞行中" else "空中悬停"
|
||||
val stick = if (stickEnabled) " · 虚拟摇杆" else ""
|
||||
"N 挡 - $mode · $modeText · H ${"%.1f".format(Locale.US, telemetry.altitude.coerceAtLeast(0.0))}m$stick"
|
||||
"${remoteControllerGearText(telemetry.gear)} - $mode · $modeText · H ${"%.1f".format(Locale.US, telemetry.altitude.coerceAtLeast(0.0))}m$stick"
|
||||
}
|
||||
stickEnabled -> "N 挡 - 待起飞 · 虚拟摇杆已开"
|
||||
simulatorEnabled -> "N 挡 - 模拟器已开 · 地面待机"
|
||||
modeText != "模式 --" -> "N 挡 - $modeText"
|
||||
else -> "N 挡 - 地面待机"
|
||||
stickEnabled -> "${remoteControllerGearText(telemetry.gear)} - 待起飞 · 虚拟摇杆已开"
|
||||
simulatorEnabled -> "${remoteControllerGearText(telemetry.gear)} - 模拟器已开 · 地面待机"
|
||||
modeText != "模式 --" -> "${remoteControllerGearText(telemetry.gear)} - $modeText"
|
||||
else -> "${remoteControllerGearText(telemetry.gear)} - 地面待机"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4389,11 +4403,11 @@ private fun groundedTopStatusText(
|
||||
modeText: String
|
||||
): String =
|
||||
when {
|
||||
modeText in explicitGroundedFlightModeLabels -> "N 挡 - $modeText"
|
||||
stickEnabled -> "N 挡 - 待起飞 · 虚拟摇杆已开"
|
||||
simulatorEnabled -> "N 挡 - 模拟器已开 · 地面待机"
|
||||
telemetry.motorsOn -> "N 挡 - 待起飞"
|
||||
else -> "N 挡 - 地面待机"
|
||||
modeText in explicitGroundedFlightModeLabels -> "${remoteControllerGearText(telemetry.gear)} - $modeText"
|
||||
stickEnabled -> "${remoteControllerGearText(telemetry.gear)} - 待起飞 · 虚拟摇杆已开"
|
||||
simulatorEnabled -> "${remoteControllerGearText(telemetry.gear)} - 模拟器已开 · 地面待机"
|
||||
telemetry.motorsOn -> "${remoteControllerGearText(telemetry.gear)} - 待起飞"
|
||||
else -> "${remoteControllerGearText(telemetry.gear)} - 地面待机"
|
||||
}
|
||||
|
||||
private fun isReturningHomeTelemetry(telemetry: TelemetrySnapshot): Boolean =
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.zklh.dronecontroller.ui
|
||||
|
||||
import dji.sdk.keyvalue.value.flightcontroller.RemoteControllerFlightMode
|
||||
|
||||
// Use the same SDK switch mode reported in MQTT gear; flight state is separate.
|
||||
internal fun remoteControllerGearText(gear: Int): String = when (gear) {
|
||||
RemoteControllerFlightMode.P.value() -> "N 挡"
|
||||
RemoteControllerFlightMode.S.value() -> "S 挡"
|
||||
RemoteControllerFlightMode.T.value() -> "T 挡"
|
||||
RemoteControllerFlightMode.A.value() -> "A 挡"
|
||||
RemoteControllerFlightMode.F.value() -> "F 挡"
|
||||
RemoteControllerFlightMode.G.value() -> "G 挡"
|
||||
RemoteControllerFlightMode.M.value() -> "M 挡"
|
||||
else -> "挡位未知"
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="false" />
|
||||
<domain-config cleartextTrafficPermitted="true">
|
||||
<domain includeSubdomains="true">uav.zklhjs.com</domain>
|
||||
<domain>221.226.33.58</domain>
|
||||
</domain-config>
|
||||
</network-security-config>
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class CloudBindingResponseTest {
|
||||
@Test fun acceptsBusinessSuccess() { validateCloudBindingResponse("{\"code\":0}") }
|
||||
@Test fun rejectsHttp200WithBusinessError() {
|
||||
assertThrows(IllegalArgumentException::class.java) { validateCloudBindingResponse("{\"code\":-1,\"message\":\"device missing\"}") }
|
||||
}
|
||||
@Test fun missingBusinessCodeIsNotSuccess() {
|
||||
assertThrows(IllegalArgumentException::class.java) { validateCloudBindingResponse("{}") }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Test
|
||||
import org.junit.Rule
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.Assert.*
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipFile
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
class CloudKmzFileTest {
|
||||
@get:Rule val storage = TemporaryFolder()
|
||||
private fun kmz(xml: String = """
|
||||
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:wpml="http://www.dji.com/wpmz/1.0.6">
|
||||
<Document><wpml:missionConfig><wpml:exitOnRCLost>goContinue</wpml:exitOnRCLost>
|
||||
<wpml:executeRCLostAction>goBack</wpml:executeRCLostAction></wpml:missionConfig>
|
||||
<Folder><wpml:waylineId>0</wpml:waylineId><Placemark/><Placemark/></Folder>
|
||||
<Folder><wpml:waylineId>3</wpml:waylineId><Placemark/></Folder></Document>
|
||||
</kml>
|
||||
""".trimIndent()): File {
|
||||
val file = File.createTempFile("kmz-test-", ".kmz")
|
||||
ZipOutputStream(file.outputStream()).use { out ->
|
||||
for (name in listOf("wpmz/waylines.wpml", "wpmz/template.kml")) {
|
||||
out.putNextEntry(ZipEntry(name)); out.write(xml.toByteArray()); out.closeEntry()
|
||||
}
|
||||
out.putNextEntry(ZipEntry("wpmz/res/photo.bin")); out.write(byteArrayOf(1, 2, 3)); out.closeEntry()
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
@Test fun originalKmzBytesAreUnchangedEvenWhenCommandIncludesPolicyFields() {
|
||||
val source=kmz()
|
||||
try {
|
||||
val prepared=CloudKmzFile.prepare(JSONObject().put("kmz_path",source.path).put("rth_altitude",90).put("out_of_control_action",1),"job-1",storage.root)
|
||||
try {
|
||||
assertEquals(mapOf(0 to 2, 3 to 1),prepared.counts)
|
||||
assertEquals(storage.root.canonicalFile, prepared.file.parentFile?.canonicalFile)
|
||||
assertArrayEquals(source.readBytes(), prepared.originalFile.readBytes())
|
||||
assertArrayEquals(source.readBytes(), prepared.file.readBytes())
|
||||
assertEquals(CloudKmzFile.sha256(source), CloudKmzFile.sha256(prepared.file))
|
||||
ZipFile(prepared.file).use { zip ->
|
||||
for(name in listOf("wpmz/template.kml","wpmz/waylines.wpml")) {
|
||||
val xml=zip.getInputStream(zip.getEntry(name)).bufferedReader().readText()
|
||||
assertTrue(xml.contains(">goContinue<")); assertTrue(xml.contains(">goBack<"))
|
||||
}
|
||||
assertArrayEquals(byteArrayOf(1,2,3),zip.getInputStream(zip.getEntry("wpmz/res/photo.bin")).readBytes())
|
||||
}
|
||||
} finally { prepared.file.delete() }
|
||||
} finally { source.delete() }
|
||||
}
|
||||
|
||||
@Test fun fingerprintMismatchRejectsDownloadBeforeUpload() {
|
||||
val source=kmz()
|
||||
try {
|
||||
val md5=MessageDigest.getInstance("MD5").digest(source.readBytes()).joinToString("") { "%02x".format(it) }
|
||||
val request=JSONObject().put("kmz_path",source.path).put("file",JSONObject().put("fingerprint",md5))
|
||||
val prepared=CloudKmzFile.prepare(request,"job-2",storage.root); prepared.file.delete()
|
||||
request.getJSONObject("file").put("fingerprint","00000000000000000000000000000000")
|
||||
assertThrows(IllegalArgumentException::class.java) { CloudKmzFile.prepare(request,"job-2",storage.root) }
|
||||
} finally { source.delete() }
|
||||
}
|
||||
|
||||
@Test fun dtdIsRejectedBeforeAircraftUpload() {
|
||||
val dtd=kmz("<!DOCTYPE kml [<!ENTITY x SYSTEM 'file:///secret'>]><kml/>")
|
||||
try { assertThrows(IllegalArgumentException::class.java) { CloudKmzFile.prepare(JSONObject().put("kmz_path",dtd.path),"job-4",storage.root) } }
|
||||
finally { dtd.delete() }
|
||||
}
|
||||
|
||||
@Test fun invalidWorkingDirectoryFailsBeforeDownloadOrSdkUpload() {
|
||||
val blockedDirectory = storage.newFile("blocked")
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
CloudKmzFile.prepare(JSONObject().put("url", "http://unused.invalid/mission.kmz"), "blocked", blockedDirectory)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun failureEvidenceRetainsBothVersionsAndReplacesOnlyLastFailure() {
|
||||
val source = kmz()
|
||||
try {
|
||||
val prepared = CloudKmzFile.prepare(JSONObject().put("kmz_path", source.path).put("rth_altitude", 90), "failed", storage.root)
|
||||
val saved = CloudKmzFile.preserveFailure(prepared, "first failure")
|
||||
assertArrayEquals(source.readBytes(), File(saved, "original.kmz").readBytes())
|
||||
assertArrayEquals(prepared.file.readBytes(), File(saved, "prepared.kmz").readBytes())
|
||||
assertArrayEquals(source.readBytes(), File(saved, "prepared.kmz").readBytes())
|
||||
assertEquals(saved, CloudKmzFile.preserveFailure(prepared, "second failure"))
|
||||
assertEquals("second failure", File(saved, "details.txt").readText())
|
||||
assertEquals(setOf("original.kmz", "prepared.kmz", "details.txt"), saved.list()!!.toSet())
|
||||
} finally { source.delete() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class CloudLiveCapacityTest {
|
||||
private fun cameras(data: JSONObject) = data.getJSONArray("device_list").getJSONObject(0).getJSONArray("camera_list")
|
||||
private fun types(camera: JSONObject): List<String> {
|
||||
val values = camera.getJSONArray("video_list").getJSONObject(0).getJSONArray("switchable_video_types")
|
||||
return (0 until values.length()).map { values.getString(it) }
|
||||
}
|
||||
@Test fun supportedMainLensPassesExistingAiRuleWithoutChangingStreamIdentity() {
|
||||
val data = buildCloudLiveCapacity("drone", mapOf("99-0-0" to listOf("WIDE_CAMERA", "ZOOM_CAMERA", "INFRARED_CAMERA")))
|
||||
val camera = cameras(data).getJSONObject(0)
|
||||
assertEquals(listOf("normal", "wide", "zoom", "ir"), types(camera))
|
||||
assertTrue(types(camera).containsAll(listOf("wide", "zoom")))
|
||||
assertEquals("99-0-0", camera.getString("camera_index"))
|
||||
assertEquals("normal-0", camera.getJSONArray("video_list").getJSONObject(0).getString("video_index"))
|
||||
assertEquals(1, data.getInt("available_video_number"))
|
||||
}
|
||||
@Test fun unknownAndSingleLensCamerasAreNotPromotedToMultiLensMain() {
|
||||
val data = buildCloudLiveCapacity("drone", linkedMapOf("99-0-0" to emptyList(), "50-65535-1" to listOf("WIDE_CAMERA", "UNKNOWN", "MS_NIR_CAMERA")))
|
||||
assertEquals(listOf("normal"), types(cameras(data).getJSONObject(0)))
|
||||
assertEquals(listOf("normal", "wide"), types(cameras(data).getJSONObject(1)))
|
||||
assertEquals(2, data.getInt("available_video_number"))
|
||||
}
|
||||
@Test fun refreshedCapabilityRemovesUnsupportedLensAndKeepsOtherPayloadIndependent() {
|
||||
val before = buildCloudLiveCapacity("drone", mapOf("99-0-0" to listOf("WIDE_CAMERA", "ZOOM_CAMERA")))
|
||||
val after = buildCloudLiveCapacity("drone", linkedMapOf("99-0-0" to listOf("WIDE_CAMERA"), "83-0-1" to listOf("INFRARED_CAMERA")))
|
||||
assertTrue(types(cameras(before).getJSONObject(0)).contains("zoom"))
|
||||
assertFalse(types(cameras(after).getJSONObject(0)).contains("zoom"))
|
||||
assertEquals(listOf("normal", "ir"), types(cameras(after).getJSONObject(1)))
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class CloudOnlineRegistrationTest {
|
||||
private fun registration() = CloudOnlineRegistration().apply { select("rc/drone/workspace/model") }
|
||||
private fun ack(r: CloudOnlineRegistration, a: CloudOnlineRegistration.Attempt) = r.acknowledge(a.tid, a.bid, true)
|
||||
|
||||
@Test fun acceptsActualBackendReplyWithoutMethodButStillRequiresMatchingIds() {
|
||||
for (method in listOf("", ",\"method\":null", ",\"method\":\"update_topo\"")) {
|
||||
val r = registration(); val a = r.beginPublish(0)!!
|
||||
assertTrue(r.acknowledgePayload("{\"tid\":\"${a.tid}\",\"bid\":\"${a.bid}\"$method,\"data\":{\"result\":0}}"))
|
||||
assertNotNull(r.beginBinding(0))
|
||||
}
|
||||
}
|
||||
@Test fun rejectsUnrelatedStatusReply() {
|
||||
val r = registration(); val a = r.beginPublish(0)!!
|
||||
assertFalse(r.acknowledgePayload("{\"tid\":\"${a.tid}\",\"bid\":\"${a.bid}\",\"method\":\"other\",\"data\":{\"result\":0}}"))
|
||||
assertNull(r.beginBinding(0))
|
||||
}
|
||||
@Test fun missingReplyRetriesWithoutRequiringAnotherLogin() {
|
||||
val r = registration(); val first = r.beginPublish(0)!!
|
||||
assertFalse(r.isReady()); assertNull(r.beginBinding(0)); assertNull(r.beginPublish(4999))
|
||||
val retry = r.beginPublish(5000)!!
|
||||
assertFalse(ack(r, first)); assertTrue(ack(r, retry)); assertNotNull(r.beginBinding(5000))
|
||||
}
|
||||
@Test fun bindingRequiresServerAckAndASecondTopologyAfterBinding() {
|
||||
val r = registration(); ack(r, r.beginPublish(0)!!)
|
||||
val binding = r.beginBinding(0)!!
|
||||
assertNull(r.beginBinding(1)); assertNull(r.beginPublish(6000))
|
||||
assertTrue(r.completeBinding(binding, true, 100)); assertFalse(r.isReady())
|
||||
assertTrue(ack(r, r.beginPublish(101)!!)); assertTrue(r.isReady()); assertNull(r.beginBinding(102))
|
||||
assertNull(r.beginPublish(30100)); assertNotNull(r.beginPublish(30101))
|
||||
}
|
||||
@Test fun failedBindingIsRetriedAndNotMistakenForOnline() {
|
||||
val r = registration(); ack(r, r.beginPublish(0)!!)
|
||||
r.completeBinding(r.beginBinding(0)!!, false, 200)
|
||||
assertFalse(r.isReady()); assertNull(r.beginBinding(5199)); assertNotNull(r.beginBinding(5200))
|
||||
}
|
||||
@Test fun reconnectIgnoresOldRepliesAndOldBindingResults() {
|
||||
val r = registration(); val first = r.beginPublish(0)!!; ack(r, first)
|
||||
val binding = r.beginBinding(0)!!
|
||||
r.reset(); r.select(first.key)
|
||||
assertFalse(r.completeBinding(binding,true,0)); assertFalse(ack(r,first)); assertFalse(r.isReady())
|
||||
assertNotNull(r.beginPublish(0))
|
||||
}
|
||||
@Test fun delayedModelOrDeviceChangeRestartsRegistration() {
|
||||
val r = registration(); val first = r.beginPublish(0)!!
|
||||
r.select("rc/new-drone/workspace/new-model")
|
||||
assertFalse(ack(r,first)); assertNotNull(r.beginPublish(1)); assertFalse(r.isReady())
|
||||
}
|
||||
@Test fun wrongBidAndBusinessErrorCannotConfirmOnline() {
|
||||
val r = registration(); val first = r.beginPublish(0)!!
|
||||
assertFalse(r.acknowledge(first.tid,"wrong",true))
|
||||
assertFalse(r.acknowledge(first.tid,first.bid,false))
|
||||
assertNull(r.beginBinding(0)); assertNotNull(r.beginPublish(5000))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.nio.file.Files
|
||||
|
||||
class CloudTerminalOutboxTest {
|
||||
private fun event() = JSONObject("""{"tid":"t1","bid":"job1","method":"flighttask_progress","data":{"output":{"status":"ok"}}}""")
|
||||
private fun reply(result: Int = 0) = JSONObject().put("tid", "t1").put("bid", "job1")
|
||||
.put("method", "flighttask_progress").put("data", JSONObject().put("result", result))
|
||||
@Test fun terminalSurvivesRestartAndRetriesUntilMatchingAck() {
|
||||
val dir = Files.createTempDirectory("terminal-outbox").toFile()
|
||||
try {
|
||||
val file = java.io.File(dir, "pending.json")
|
||||
val first = CloudTerminalOutbox(file)
|
||||
first.offer("tenant-a", "thing/product/rc/events", event())
|
||||
val restored = CloudTerminalOutbox(file)
|
||||
assertEquals(1, restored.due("tenant-a", 100).size)
|
||||
assertTrue(restored.due("tenant-a", 200).isEmpty())
|
||||
assertEquals(1, restored.due("tenant-a", 5100).size)
|
||||
assertFalse(restored.acknowledge("tenant-a", reply(-1)))
|
||||
assertFalse(restored.acknowledge("tenant-b", reply()))
|
||||
assertFalse(restored.acknowledge("tenant-a", reply().put("bid", "other-job")))
|
||||
assertTrue(restored.acknowledge("tenant-a", reply()))
|
||||
assertTrue(CloudTerminalOutbox(file).due("tenant-a", 10000).isEmpty())
|
||||
} finally { dir.deleteRecursively() }
|
||||
}
|
||||
@Test fun anotherTenantNeverPublishesPendingEvent() {
|
||||
val queue = CloudTerminalOutbox(null)
|
||||
queue.offer("tenant-a", "thing/product/rc/events", event())
|
||||
assertTrue(queue.due("tenant-b", 100).isEmpty())
|
||||
assertEquals("job1", queue.due("tenant-a", 100).single().getJSONObject("payload").getString("bid"))
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.zklh.dronecontroller.core.cloud
|
||||
import org.junit.Test
|
||||
import org.junit.Assert.assertEquals
|
||||
class CloudWaylineCompletionTest {
|
||||
@Test fun stoppingOnLastWaypointIsCanceled() { assertEquals("canceled", cloudWaylineTerminalStatus(true,false,6,true,4,5)) }
|
||||
@Test fun finishedAfterInterruptedIsNotSuccess() { assertEquals("failed", cloudWaylineTerminalStatus(false,true,7,true,4,5)) }
|
||||
@Test fun naturalFinishAtLastWaypointSucceeds() { assertEquals("ok", cloudWaylineTerminalStatus(false,false,6,true,4,5)) }
|
||||
@Test fun earlyStopDoesNotReportFullCompletion() { assertEquals("canceled", cloudWaylineTerminalStatus(false,false,6,true,2,5)) }
|
||||
@Test fun intermediateWaylineDoesNotCompleteWholeJob() { assertEquals("canceled", cloudWaylineTerminalStatus(false,false,6,false,4,5)) }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.zklh.dronecontroller.core.telemetry
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class CloudCameraValuesTest {
|
||||
@Test fun sdkEnumsTranslateToCloudProtocol() {
|
||||
assertEquals(1, cloudGear(2)) // MSDK P/N=2; Cloud P=1.
|
||||
assertEquals(5, cloudGear(3))
|
||||
assertEquals(9, cloudGear(6))
|
||||
assertEquals(4, cloudCameraIso("ISO_200"))
|
||||
assertEquals(27, cloudShutterSpeed("SHUTTER_SPEED1_100"))
|
||||
assertEquals(37, cloudShutterSpeed("SHUTTER_SPEED1_12DOT5"))
|
||||
assertEquals(49, cloudShutterSpeed("SHUTTER_SPEED1DOT3"))
|
||||
assertEquals(65534, cloudShutterSpeed("SHUTTER_SPEED_AUTO"))
|
||||
assertEquals(255, cloudExposureValue("FIXED"))
|
||||
assertEquals(16, cloudExposureValue("NEG_0EV"))
|
||||
assertEquals(1, cloudExposureMode("PROGRAM"))
|
||||
assertEquals(0, cloudFocusMode("MANUAL"))
|
||||
}
|
||||
@Test fun unsupportedValuesAreOmittedInsteadOfFabricated() {
|
||||
assertNull(cloudGear(65535))
|
||||
assertNull(cloudCameraIso("ISO_819200"))
|
||||
assertNull(cloudShutterSpeed("UNKNOWN"))
|
||||
assertNull(cloudExposureValue(null))
|
||||
assertNull(cloudFocusMode("FINE_TUNE"))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user