增加红外切换红外测温,喊话器接口
This commit is contained in:
@@ -11,6 +11,8 @@ import com.zklh.dronecontroller.core.gimbal.GimbalControlService
|
|||||||
import com.zklh.dronecontroller.core.livestream.LiveStreamingService
|
import com.zklh.dronecontroller.core.livestream.LiveStreamingService
|
||||||
import com.zklh.dronecontroller.core.media.CameraControlService
|
import com.zklh.dronecontroller.core.media.CameraControlService
|
||||||
import com.zklh.dronecontroller.core.media.CameraMediaService
|
import com.zklh.dronecontroller.core.media.CameraMediaService
|
||||||
|
import com.zklh.dronecontroller.core.media.SpeakerCloudService
|
||||||
|
import com.zklh.dronecontroller.core.media.SpeakerCloudStatus
|
||||||
import com.zklh.dronecontroller.core.mission.MissionDroneInfo
|
import com.zklh.dronecontroller.core.mission.MissionDroneInfo
|
||||||
import com.zklh.dronecontroller.core.mission.MissionFinishAction
|
import com.zklh.dronecontroller.core.mission.MissionFinishAction
|
||||||
import com.zklh.dronecontroller.core.mission.MissionPayloadInfo
|
import com.zklh.dronecontroller.core.mission.MissionPayloadInfo
|
||||||
@@ -25,6 +27,10 @@ import com.zklh.dronecontroller.core.telemetry.hasReliableRtkPosition
|
|||||||
import com.zklh.dronecontroller.core.telemetry.isRtkBlockingWaypointMission
|
import com.zklh.dronecontroller.core.telemetry.isRtkBlockingWaypointMission
|
||||||
import com.zklh.dronecontroller.core.virtualstick.StickPosition
|
import com.zklh.dronecontroller.core.virtualstick.StickPosition
|
||||||
import com.zklh.dronecontroller.core.virtualstick.VirtualStickService
|
import com.zklh.dronecontroller.core.virtualstick.VirtualStickService
|
||||||
|
import dji.sdk.keyvalue.value.camera.CameraThermalPalette
|
||||||
|
import dji.sdk.keyvalue.value.camera.ThermalGainMode
|
||||||
|
import dji.sdk.keyvalue.value.camera.ThermalTemperatureMeasureMode
|
||||||
|
import dji.sdk.keyvalue.value.common.ComponentIndexType
|
||||||
import dji.sdk.keyvalue.value.flightcontroller.FlyToMode
|
import dji.sdk.keyvalue.value.flightcontroller.FlyToMode
|
||||||
import dji.sdk.keyvalue.value.flightcontroller.LookAtMode
|
import dji.sdk.keyvalue.value.flightcontroller.LookAtMode
|
||||||
import dji.v5.manager.aircraft.virtualstick.Stick
|
import dji.v5.manager.aircraft.virtualstick.Stick
|
||||||
@@ -47,6 +53,11 @@ import kotlinx.coroutines.launch
|
|||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
|
||||||
private const val CloudCommandLogTag = "ZklhCloudCommand"
|
private const val CloudCommandLogTag = "ZklhCloudCommand"
|
||||||
|
private val CloudThermalPaletteNames = listOf(
|
||||||
|
"WHITE_HOT", "BLACK_HOT", "RED_HOT", "GREEN_HOT", "FUSION", "RAINBOW",
|
||||||
|
"IRONBOW1", "IRONBOW2", "ICE_FIRE", "SEPIA", "GLOWBOW", "COLOR1",
|
||||||
|
"COLOR2", "RAIN", "HOT_SPOT", "RAINBOW2", "GRAY", "METAL", "COLD_SPOT"
|
||||||
|
)
|
||||||
private const val DefaultFlyToHeightMeters = 20.0
|
private const val DefaultFlyToHeightMeters = 20.0
|
||||||
private const val MinimumTakeoffTargetHeightMeters = 2.0
|
private const val MinimumTakeoffTargetHeightMeters = 2.0
|
||||||
private const val WaylineStartRetryCount = 6
|
private const val WaylineStartRetryCount = 6
|
||||||
@@ -126,6 +137,7 @@ class CloudCommandExecutor(
|
|||||||
private val cameraControl: CameraControlService = CameraControlService(),
|
private val cameraControl: CameraControlService = CameraControlService(),
|
||||||
private val gimbalControl: GimbalControlService = GimbalControlService(),
|
private val gimbalControl: GimbalControlService = GimbalControlService(),
|
||||||
private val mediaUpload: CloudMediaUploadService? = null,
|
private val mediaUpload: CloudMediaUploadService? = null,
|
||||||
|
private val speakerControl: SpeakerCloudService = SpeakerCloudService(context.applicationContext),
|
||||||
private val telemetryProvider: () -> TelemetrySnapshot = { TelemetrySnapshot() },
|
private val telemetryProvider: () -> TelemetrySnapshot = { TelemetrySnapshot() },
|
||||||
private val warningProvider: () -> DroneWarningState = { DroneWarningState() },
|
private val warningProvider: () -> DroneWarningState = { DroneWarningState() },
|
||||||
private val progressPublisher: CloudMissionProgressPublisher? = null
|
private val progressPublisher: CloudMissionProgressPublisher? = null
|
||||||
@@ -163,6 +175,10 @@ class CloudCommandExecutor(
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun detectedSpeakers(): List<SpeakerCloudStatus> = speakerControl.detect()
|
||||||
|
|
||||||
|
fun stopSpeakerMonitoring() = speakerControl.stopMonitoring()
|
||||||
|
|
||||||
suspend fun execute(method: String, data: JSONObject): DjiCommandResult =
|
suspend fun execute(method: String, data: JSONObject): DjiCommandResult =
|
||||||
execute(method.normalizeCloudCommand(), data, CloudCommandTopicType.Unknown)
|
execute(method.normalizeCloudCommand(), data, CloudCommandTopicType.Unknown)
|
||||||
|
|
||||||
@@ -217,6 +233,11 @@ class CloudCommandExecutor(
|
|||||||
command in CameraExposureModeCommands -> setCameraExposureMode(data)
|
command in CameraExposureModeCommands -> setCameraExposureMode(data)
|
||||||
command in CameraFocusModeCommands -> setCameraFocusMode(data)
|
command in CameraFocusModeCommands -> setCameraFocusMode(data)
|
||||||
command in CameraScreenSplitCommands -> setCameraScreenSplit(data)
|
command in CameraScreenSplitCommands -> setCameraScreenSplit(data)
|
||||||
|
command in ThermalPropertyCommands && topicType == CloudCommandTopicType.PropertySet -> setThermalProperties(data)
|
||||||
|
command in ThermalMeteringModeCommands -> setThermalMeteringMode(data)
|
||||||
|
command in ThermalMeteringPointCommands -> setThermalMeteringPoint(data)
|
||||||
|
command in ThermalMeteringAreaCommands -> setThermalMeteringArea(data)
|
||||||
|
command in SpeakerCommands -> speakerControl.execute(command, data)
|
||||||
command in CameraNightModeCommands -> setCameraNightMode(data)
|
command in CameraNightModeCommands -> setCameraNightMode(data)
|
||||||
command in GimbalDragCommands -> rotateGimbal(data)
|
command in GimbalDragCommands -> rotateGimbal(data)
|
||||||
command in GimbalResetCommands -> gimbalControl.reset()
|
command in GimbalResetCommands -> gimbalControl.reset()
|
||||||
@@ -1283,6 +1304,112 @@ class CloudCommandExecutor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private suspend fun setThermalPalette(data: JSONObject): DjiCommandResult {
|
||||||
|
val payloadIndex = data.optStringAny("payload_index", "payloadIndex")
|
||||||
|
val telemetry = telemetryProvider()
|
||||||
|
val cameraComponentName = telemetry.cloudCameraComponentForPayloadIndex(payloadIndex)
|
||||||
|
?: return DjiCommandResult.failed("红外色盘负载编号与当前相机不匹配:$payloadIndex,当前负载:${telemetry.cloudCameraPayloadIndexes().joinToString()}")
|
||||||
|
val cameraComponent = runCatching { ComponentIndexType.valueOf(cameraComponentName.uppercase()) }.getOrNull()
|
||||||
|
?: return DjiCommandResult.failed("未知相机位置:$cameraComponentName")
|
||||||
|
val style = data.optIntAny(-1, "thermal_current_palette_style")
|
||||||
|
val paletteName = CloudThermalPaletteNames.getOrNull(style)
|
||||||
|
?: return DjiCommandResult.failed("不支持的红外色盘编号:$style")
|
||||||
|
val palette = runCatching { CameraThermalPalette.valueOf(paletteName) }.getOrNull()
|
||||||
|
?: return DjiCommandResult.failed("当前 MSDK 不支持红外色盘:$paletteName")
|
||||||
|
if (cameraComponent == ComponentIndexType.LEFT_OR_MAIN &&
|
||||||
|
telemetry.thermalPaletteRange.isNotEmpty() && paletteName !in telemetry.thermalPaletteRange) {
|
||||||
|
return DjiCommandResult.failed("当前相机不支持红外色盘:$paletteName")
|
||||||
|
}
|
||||||
|
val control = if (cameraComponent == ComponentIndexType.LEFT_OR_MAIN) cameraControl else CameraControlService(cameraComponent)
|
||||||
|
return control.setThermalPalette(palette)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun setThermalProperties(data: JSONObject): DjiCommandResult {
|
||||||
|
val payloadIndex = data.optStringAny("payload_index", "payloadIndex")
|
||||||
|
val telemetry = telemetryProvider()
|
||||||
|
val component = telemetry.cloudCameraComponentForPayloadIndex(payloadIndex)
|
||||||
|
?.let { runCatching { ComponentIndexType.valueOf(it.uppercase()) }.getOrNull() }
|
||||||
|
?: return DjiCommandResult.failed("红外设置负载编号与当前相机不匹配:$payloadIndex")
|
||||||
|
val control = if (component == ComponentIndexType.LEFT_OR_MAIN) cameraControl else CameraControlService(component)
|
||||||
|
val commands = mutableListOf<suspend () -> DjiCommandResult>()
|
||||||
|
if (data.has("thermal_current_palette_style")) commands += { setThermalPalette(data) }
|
||||||
|
if (data.has("thermal_gain_mode")) {
|
||||||
|
val mode = when (data.optIntAny(-1, "thermal_gain_mode")) {
|
||||||
|
0 -> ThermalGainMode.AUTO
|
||||||
|
1 -> ThermalGainMode.LOW
|
||||||
|
2 -> ThermalGainMode.HIGH
|
||||||
|
else -> return DjiCommandResult.failed("红外增益模式无效")
|
||||||
|
}
|
||||||
|
commands += { control.setThermalGainMode(mode) }
|
||||||
|
}
|
||||||
|
val lower = data.optIntAny(Int.MIN_VALUE, "thermal_isotherm_lower_limit")
|
||||||
|
val upper = data.optIntAny(Int.MIN_VALUE, "thermal_isotherm_upper_limit")
|
||||||
|
if (lower != Int.MIN_VALUE || upper != Int.MIN_VALUE) {
|
||||||
|
if (lower == Int.MIN_VALUE || upper == Int.MIN_VALUE || lower >= upper || lower < -40 || upper > 550)
|
||||||
|
return DjiCommandResult.failed("等温线范围无效")
|
||||||
|
commands += { control.setThermalIsothermLower(lower) }
|
||||||
|
commands += { control.setThermalIsothermUpper(upper) }
|
||||||
|
}
|
||||||
|
if (data.has("thermal_isotherm_state")) {
|
||||||
|
val enabled = data.optIntAny(-1, "thermal_isotherm_state")
|
||||||
|
if (enabled !in 0..1) return DjiCommandResult.failed("等温线开关参数无效")
|
||||||
|
commands += { control.setThermalIsothermEnabled(enabled == 1) }
|
||||||
|
}
|
||||||
|
if (commands.isEmpty()) return DjiCommandResult.failed("红外设置缺少可执行属性")
|
||||||
|
for (command in commands) {
|
||||||
|
val result = command()
|
||||||
|
if (!result.success) return result
|
||||||
|
}
|
||||||
|
return DjiCommandResult.ok("红外设置已完成")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun thermalMeteringControl(data: JSONObject): CameraControlService? {
|
||||||
|
val component = telemetryProvider().cloudCameraComponentForPayloadIndex(data.optStringAny("payload_index", "payloadIndex"))
|
||||||
|
?.let { runCatching { ComponentIndexType.valueOf(it.uppercase()) }.getOrNull() } ?: return null
|
||||||
|
return if (component == ComponentIndexType.LEFT_OR_MAIN) cameraControl else CameraControlService(component)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun setThermalMeteringMode(data: JSONObject): DjiCommandResult {
|
||||||
|
val control = thermalMeteringControl(data) ?: return DjiCommandResult.failed("测温负载编号与当前相机不匹配")
|
||||||
|
val mode = when (data.optIntAny(-1, "mode")) {
|
||||||
|
0 -> ThermalTemperatureMeasureMode.DISABLED
|
||||||
|
1 -> ThermalTemperatureMeasureMode.SPOT
|
||||||
|
2 -> ThermalTemperatureMeasureMode.REGION
|
||||||
|
else -> return DjiCommandResult.failed("测温模式无效")
|
||||||
|
}
|
||||||
|
if (mode != ThermalTemperatureMeasureMode.DISABLED) {
|
||||||
|
val lens = control.setLens("ir")
|
||||||
|
if (!lens.success) return lens
|
||||||
|
}
|
||||||
|
return control.setThermalMeteringMode(mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun setThermalMeteringPoint(data: JSONObject): DjiCommandResult {
|
||||||
|
val control = thermalMeteringControl(data) ?: return DjiCommandResult.failed("点测温负载编号与当前相机不匹配")
|
||||||
|
val x = data.optDoubleAny("x")
|
||||||
|
val y = data.optDoubleAny("y")
|
||||||
|
if (!data.has("x") || !data.has("y") || !x.isFinite() || !y.isFinite() || x !in 0.0..1.0 || y !in 0.0..1.0)
|
||||||
|
return DjiCommandResult.failed("点测温坐标无效")
|
||||||
|
val mode = control.setThermalMeteringMode(ThermalTemperatureMeasureMode.SPOT)
|
||||||
|
if (!mode.success) return mode
|
||||||
|
return control.setThermalMeteringPoint(x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun setThermalMeteringArea(data: JSONObject): DjiCommandResult {
|
||||||
|
val control = thermalMeteringControl(data) ?: return DjiCommandResult.failed("区域测温负载编号与当前相机不匹配")
|
||||||
|
val x = data.optDoubleAny("x")
|
||||||
|
val y = data.optDoubleAny("y")
|
||||||
|
val width = data.optDoubleAny("width")
|
||||||
|
val height = data.optDoubleAny("height")
|
||||||
|
if (listOf("x", "y", "width", "height").any { !data.has(it) } ||
|
||||||
|
listOf(x, y, width, height).any { !it.isFinite() } ||
|
||||||
|
x !in 0.0..1.0 || y !in 0.0..1.0 || width <= 0.0 || height <= 0.0 || x + width > 1.0 || y + height > 1.0)
|
||||||
|
return DjiCommandResult.failed("区域测温范围无效")
|
||||||
|
val mode = control.setThermalMeteringMode(ThermalTemperatureMeasureMode.REGION)
|
||||||
|
if (!mode.success) return mode
|
||||||
|
return control.setThermalMeteringArea(x, y, width, height)
|
||||||
|
}
|
||||||
|
|
||||||
private suspend fun setLinkageZoom(data: JSONObject): DjiCommandResult {
|
private suspend fun setLinkageZoom(data: JSONObject): DjiCommandResult {
|
||||||
val enabled = when {
|
val enabled = when {
|
||||||
data.hasAny("state") -> data.optIntAny(0, "state") != 0
|
data.hasAny("state") -> data.optIntAny(0, "state") != 0
|
||||||
@@ -1884,6 +2011,13 @@ private val CameraExposureCommands = setOf("camera_exposure_set", "drc_camera_ex
|
|||||||
private val CameraExposureModeCommands = setOf("camera_exposure_mode_set", "drc_camera_exposure_mode_set")
|
private val CameraExposureModeCommands = setOf("camera_exposure_mode_set", "drc_camera_exposure_mode_set")
|
||||||
private val CameraFocusModeCommands = setOf("camera_focus_mode_set", "drc_camera_focus_mode_set")
|
private val CameraFocusModeCommands = setOf("camera_focus_mode_set", "drc_camera_focus_mode_set")
|
||||||
private val CameraScreenSplitCommands = setOf("camera_screen_split", "drc_camera_screen_split")
|
private val CameraScreenSplitCommands = setOf("camera_screen_split", "drc_camera_screen_split")
|
||||||
|
private val ThermalPropertyCommands = setOf("thermal_property_set", "thermal_current_palette_style",
|
||||||
|
"thermal_isotherm_state", "thermal_isotherm_lower_limit", "thermal_isotherm_upper_limit", "thermal_gain_mode")
|
||||||
|
private val ThermalMeteringModeCommands = setOf("ir_metering_mode_set", "drc_ir_metering_mode_set")
|
||||||
|
private val ThermalMeteringPointCommands = setOf("ir_metering_point_set", "drc_ir_metering_point_set")
|
||||||
|
private val ThermalMeteringAreaCommands = setOf("ir_metering_area_set", "drc_ir_metering_area_set")
|
||||||
|
private val SpeakerCommands = setOf("speaker_tts_play_start", "speaker_audio_play_start", "speaker_replay",
|
||||||
|
"speaker_play_stop", "speaker_play_mode_set", "speaker_play_volume_set")
|
||||||
private val CameraNightModeCommands = setOf("drc_camera_night_mode_set", "drc_camera_night_vision_enable", "camera_night_mode_set")
|
private val CameraNightModeCommands = setOf("drc_camera_night_mode_set", "drc_camera_night_vision_enable", "camera_night_mode_set")
|
||||||
private val GimbalDragCommands = setOf("camera_screen_drag", "drc_camera_screen_drag", "gimbal_rotate_by_speed")
|
private val GimbalDragCommands = setOf("camera_screen_drag", "drc_camera_screen_drag", "gimbal_rotate_by_speed")
|
||||||
private val GimbalResetCommands = setOf("gimbal_reset", "drc_gimbal_reset")
|
private val GimbalResetCommands = setOf("gimbal_reset", "drc_gimbal_reset")
|
||||||
|
|||||||
@@ -41,17 +41,20 @@ data class CloudCommandRequest(
|
|||||||
fun parse(topic: String, payload: String): CloudCommandRequest {
|
fun parse(topic: String, payload: String): CloudCommandRequest {
|
||||||
val request = JSONObject(payload)
|
val request = JSONObject(payload)
|
||||||
val rootData = request.optJSONObject("data") ?: JSONObject()
|
val rootData = request.optJSONObject("data") ?: JSONObject()
|
||||||
val data = rootData.unwrapNestedCommandData()
|
val type = topic.type()
|
||||||
|
val propertyData = if (type == CloudCommandTopicType.PropertySet) rootData.thermalPropertyData() else null
|
||||||
|
val data = propertyData ?: rootData.unwrapNestedCommandData()
|
||||||
val method = request.optString("method")
|
val method = request.optString("method")
|
||||||
.ifBlank { rootData.optString("method") }
|
.ifBlank { rootData.optString("method") }
|
||||||
.ifBlank { request.optString("cmd") }
|
.ifBlank { request.optString("cmd") }
|
||||||
.ifBlank { rootData.optString("cmd") }
|
.ifBlank { rootData.optString("cmd") }
|
||||||
.ifBlank { data.optString("method") }
|
.ifBlank { data.optString("method") }
|
||||||
.ifBlank { data.optString("cmd") }
|
.ifBlank { data.optString("cmd") }
|
||||||
|
.ifBlank { if (propertyData != null) "thermal_property_set" else "" }
|
||||||
return CloudCommandRequest(
|
return CloudCommandRequest(
|
||||||
topic = topic,
|
topic = topic,
|
||||||
targetSn = topic.split("/").getOrNull(2).orEmpty(),
|
targetSn = topic.split("/").getOrNull(2).orEmpty(),
|
||||||
type = topic.type(),
|
type = type,
|
||||||
method = method,
|
method = method,
|
||||||
data = data,
|
data = data,
|
||||||
tid = request.optString("tid"),
|
tid = request.optString("tid"),
|
||||||
@@ -62,6 +65,23 @@ data class CloudCommandRequest(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val ThermalPropertyNames = setOf(
|
||||||
|
"thermal_current_palette_style", "thermal_isotherm_state", "thermal_isotherm_lower_limit",
|
||||||
|
"thermal_isotherm_upper_limit", "thermal_gain_mode"
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun JSONObject.thermalPropertyData(): JSONObject? {
|
||||||
|
val property = ThermalPropertyNames.firstOrNull { has(it) }
|
||||||
|
if (property != null) {
|
||||||
|
optJSONObject(property)?.let { return JSONObject(it.toString()) }
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
val payloadIndex = keys().asSequence().firstOrNull { it.matches(Regex("\\d+-\\d+-\\d+")) } ?: return null
|
||||||
|
val payloadProperties = optJSONObject(payloadIndex) ?: return null
|
||||||
|
if (ThermalPropertyNames.none { payloadProperties.has(it) }) return null
|
||||||
|
return JSONObject(payloadProperties.toString()).put("payload_index", payloadIndex)
|
||||||
|
}
|
||||||
|
|
||||||
private val SnFields = listOf(
|
private val SnFields = listOf(
|
||||||
"sn",
|
"sn",
|
||||||
"device_sn",
|
"device_sn",
|
||||||
|
|||||||
@@ -111,6 +111,11 @@ class CloudMqttService(
|
|||||||
private var lastLiveCapacityAt = 0L
|
private var lastLiveCapacityAt = 0L
|
||||||
private var lastLiveStatusAt = 0L
|
private var lastLiveStatusAt = 0L
|
||||||
private var lastLiveStatusKey = ""
|
private var lastLiveStatusKey = ""
|
||||||
|
private var lastSpeakerStatusKey = ""
|
||||||
|
private var lastSpeakerStatusAt = 0L
|
||||||
|
private var lastSpeakerProbeAt = 0L
|
||||||
|
private var lastControlAvailabilityAt = 0L
|
||||||
|
private var lastControlAvailability: Boolean? = null
|
||||||
@Volatile private var liveCapacity: JSONObject? = null
|
@Volatile private var liveCapacity: JSONObject? = null
|
||||||
@Volatile private var liveState = LiveStreamingState()
|
@Volatile private var liveState = LiveStreamingState()
|
||||||
private val terminalOutbox = CloudTerminalOutbox(terminalEventsFile)
|
private val terminalOutbox = CloudTerminalOutbox(terminalEventsFile)
|
||||||
@@ -141,6 +146,58 @@ class CloudMqttService(
|
|||||||
lastLiveStatusKey = key; lastLiveStatusAt = now
|
lastLiveStatusKey = key; lastLiveStatusAt = now
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun publishSpeakerStatusIfReady() {
|
||||||
|
val cloudSession = session ?: return
|
||||||
|
val rcSn = deviceIdentity.remoteControllerSn
|
||||||
|
if (rcSn.isBlank()) return
|
||||||
|
val now = SystemClock.elapsedRealtime()
|
||||||
|
if (now - lastSpeakerProbeAt < 3_000L) return
|
||||||
|
lastSpeakerProbeAt = now
|
||||||
|
val speakers = runCatching { commandExecutor?.detectedSpeakers().orEmpty() }.getOrElse {
|
||||||
|
Log.w(CloudMqttLogTag, "speaker detection failed", it)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val values = JSONArray().apply {
|
||||||
|
speakers.forEach { speaker ->
|
||||||
|
val speakerState = JSONObject()
|
||||||
|
speaker.loop?.let { speakerState.put("play_mode", if (it) "1" else "0") }
|
||||||
|
speaker.volume?.let { speakerState.put("play_volume", it.toString()) }
|
||||||
|
speaker.systemState?.let { speakerState.put("system_state", it.toString()) }
|
||||||
|
if (speaker.fileName.isNotBlank()) speakerState.put("play_file_name", speaker.fileName)
|
||||||
|
put(JSONObject()
|
||||||
|
.put("psdk_index", speaker.psdkIndex)
|
||||||
|
.put("psdk_name", speaker.name)
|
||||||
|
.put("psdk_sn", speaker.serialNumber)
|
||||||
|
.put("speaker", speakerState))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val key = values.toString()
|
||||||
|
if (key == lastSpeakerStatusKey && now - lastSpeakerStatusAt < 15_000L) return
|
||||||
|
val payload = topicRequest(cloudSession).put("gateway", rcSn)
|
||||||
|
.put("data", JSONObject().put("psdk_widget_values", values))
|
||||||
|
if (publish("thing/product/$rcSn/state", payload, qos = 1)) {
|
||||||
|
lastSpeakerStatusKey = key
|
||||||
|
lastSpeakerStatusAt = now
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun publishRcControlAvailability(available: Boolean) {
|
||||||
|
val cloudSession = session ?: return
|
||||||
|
val rcSn = deviceIdentity.remoteControllerSn
|
||||||
|
if (rcSn.isBlank()) return
|
||||||
|
if (!available && lastOnlineIdentity?.remoteControllerSn != rcSn) return
|
||||||
|
val now = SystemClock.elapsedRealtime()
|
||||||
|
if (lastControlAvailability == available && now - lastControlAvailabilityAt < 30_000L) return
|
||||||
|
// 平台从 state/cloud_control_auth 更新遥控器控制状态;仅在 OSD 中设置该字段会被缓存值覆盖。
|
||||||
|
val payload = topicRequest(cloudSession)
|
||||||
|
.put("gateway", rcSn)
|
||||||
|
.put("data", JSONObject().put("cloud_control_auth", available))
|
||||||
|
if (publish("thing/product/$rcSn/state", payload, qos = 1)) {
|
||||||
|
lastControlAvailability = available
|
||||||
|
lastControlAvailabilityAt = now
|
||||||
|
}
|
||||||
|
}
|
||||||
private var warningHmsKey = ""
|
private var warningHmsKey = ""
|
||||||
private var warningDebugRaw = ""
|
private var warningDebugRaw = ""
|
||||||
private var hmsDebugKey = ""
|
private var hmsDebugKey = ""
|
||||||
@@ -169,11 +226,14 @@ class CloudMqttService(
|
|||||||
private suspend fun synchronizeCloudState() = synchronization.withLock {
|
private suspend fun synchronizeCloudState() = synchronization.withLock {
|
||||||
if (!isConnected()) return@withLock
|
if (!isConnected()) return@withLock
|
||||||
subscribeControlTopicsIfReady()
|
subscribeControlTopicsIfReady()
|
||||||
if (!publishOnlineIfReady()) return@withLock
|
val onlineReady = publishOnlineIfReady()
|
||||||
|
publishRcControlAvailability(onlineReady)
|
||||||
|
if (!onlineReady) return@withLock
|
||||||
publishOsdIfReady(force = false)
|
publishOsdIfReady(force = false)
|
||||||
if (registration.isReady()) {
|
if (registration.isReady()) {
|
||||||
publishLiveCapacityIfReady(deviceIdentity, force = false)
|
publishLiveCapacityIfReady(deviceIdentity, force = false)
|
||||||
publishLiveStatus()
|
publishLiveStatus()
|
||||||
|
publishSpeakerStatusIfReady()
|
||||||
flushTerminalEvents()
|
flushTerminalEvents()
|
||||||
publishHmsIfReady(force = false)
|
publishHmsIfReady(force = false)
|
||||||
}
|
}
|
||||||
@@ -186,6 +246,9 @@ class CloudMqttService(
|
|||||||
if (!connecting.compareAndSet(false, true)) return
|
if (!connecting.compareAndSet(false, true)) return
|
||||||
val generation = connectionGeneration.incrementAndGet()
|
val generation = connectionGeneration.incrementAndGet()
|
||||||
this.commandExecutor = commandExecutor
|
this.commandExecutor = commandExecutor
|
||||||
|
lastSpeakerStatusKey = ""
|
||||||
|
lastSpeakerStatusAt = 0L
|
||||||
|
lastSpeakerProbeAt = 0L
|
||||||
_state.update {
|
_state.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
connecting = true,
|
connecting = true,
|
||||||
@@ -288,6 +351,7 @@ class CloudMqttService(
|
|||||||
}
|
}
|
||||||
lastOnlineIdentity = null
|
lastOnlineIdentity = null
|
||||||
closeCurrentClient()
|
closeCurrentClient()
|
||||||
|
commandExecutor?.stopSpeakerMonitoring()
|
||||||
connecting.set(false)
|
connecting.set(false)
|
||||||
session = null
|
session = null
|
||||||
_state.update {
|
_state.update {
|
||||||
@@ -311,6 +375,7 @@ class CloudMqttService(
|
|||||||
}
|
}
|
||||||
lastOnlineIdentity = null
|
lastOnlineIdentity = null
|
||||||
closeCurrentClient()
|
closeCurrentClient()
|
||||||
|
commandExecutor?.stopSpeakerMonitoring()
|
||||||
session = null
|
session = null
|
||||||
connecting.set(false)
|
connecting.set(false)
|
||||||
scope.cancel()
|
scope.cancel()
|
||||||
@@ -923,7 +988,7 @@ class CloudMqttService(
|
|||||||
|
|
||||||
private fun osdCameraListJson(): JSONArray =
|
private fun osdCameraListJson(): JSONArray =
|
||||||
JSONArray().apply {
|
JSONArray().apply {
|
||||||
telemetry.cloudCameraPayloadIndexes().forEach { payloadIndex ->
|
telemetry.cloudCameraOsdPayloadIndexes().forEach { payloadIndex ->
|
||||||
put(osdCameraJson(payloadIndex))
|
put(osdCameraJson(payloadIndex))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -941,13 +1006,14 @@ class CloudMqttService(
|
|||||||
.put("ir_zoom_factor", telemetry.irZoomFactor)
|
.put("ir_zoom_factor", telemetry.irZoomFactor)
|
||||||
.put("screen_split_enable", false)
|
.put("screen_split_enable", false)
|
||||||
.apply {
|
.apply {
|
||||||
if (payloadIndex == telemetry.cloudCameraPayloadIndex())
|
if (payloadIndex == telemetry.cloudCameraPayloadIndex() ||
|
||||||
telemetry.cameraCloudFields.filterKeys { !it.startsWith("_") }.forEach { (key, value) -> put(key, value) }
|
isMatrice4ThermalPaletteAlias(payloadIndex, telemetry.cloudCameraPayloadIndex()))
|
||||||
|
telemetry.cameraCloudFields.filterKeys { !it.startsWith("_") }.forEach { (key, value) -> put(key, cloudJsonValue(value)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun rcDronePayloadListJson(): JSONArray =
|
private fun rcDronePayloadListJson(): JSONArray =
|
||||||
JSONArray().apply {
|
JSONArray().apply {
|
||||||
telemetry.cloudCameraPayloadIndexes().forEach { payloadIndex ->
|
telemetry.cloudCameraOsdPayloadIndexes().forEach { payloadIndex ->
|
||||||
put(rcDronePayloadJson(payloadIndex))
|
put(rcDronePayloadJson(payloadIndex))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -966,8 +1032,9 @@ class CloudMqttService(
|
|||||||
.put("measure_target_longitude", telemetry.laserTargetLongitude.toFloat())
|
.put("measure_target_longitude", telemetry.laserTargetLongitude.toFloat())
|
||||||
.put("smart_track_point", JSONArray())
|
.put("smart_track_point", JSONArray())
|
||||||
.apply {
|
.apply {
|
||||||
if (payloadIndex == telemetry.cloudCameraPayloadIndex())
|
if (payloadIndex == telemetry.cloudCameraPayloadIndex() ||
|
||||||
telemetry.payloadCloudFields.forEach { (key, value) -> put(key, value) }
|
isMatrice4ThermalPaletteAlias(payloadIndex, telemetry.cloudCameraPayloadIndex()))
|
||||||
|
telemetry.payloadCloudFields.forEach { (key, value) -> put(key, cloudJsonValue(value)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun topicRequest(cloudSession: CloudSession): JSONObject =
|
private fun topicRequest(cloudSession: CloudSession): JSONObject =
|
||||||
@@ -1106,6 +1173,8 @@ class CloudMqttService(
|
|||||||
liveCapacity = null
|
liveCapacity = null
|
||||||
lastLiveStatusKey = ""
|
lastLiveStatusKey = ""
|
||||||
lastLiveStatusAt = 0L
|
lastLiveStatusAt = 0L
|
||||||
|
lastControlAvailability = null
|
||||||
|
lastControlAvailabilityAt = 0L
|
||||||
warningHmsKey = ""
|
warningHmsKey = ""
|
||||||
hmsDebugKey = ""
|
hmsDebugKey = ""
|
||||||
}
|
}
|
||||||
@@ -1326,6 +1395,15 @@ private fun TelemetrySnapshot.cloudDroneDescriptor(): CloudDeviceDescriptor {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun cloudJsonValue(value: Any?): Any = when (value) {
|
||||||
|
null -> JSONObject.NULL
|
||||||
|
is Map<*, *> -> JSONObject().apply {
|
||||||
|
value.forEach { (key, item) -> if (key is String) put(key, cloudJsonValue(item)) }
|
||||||
|
}
|
||||||
|
is Iterable<*> -> JSONArray().apply { value.forEach { put(cloudJsonValue(it)) } }
|
||||||
|
else -> value
|
||||||
|
}
|
||||||
|
|
||||||
private fun TelemetrySnapshot.cloudApiDroneType(): Int {
|
private fun TelemetrySnapshot.cloudApiDroneType(): Int {
|
||||||
val product = productType.uppercase()
|
val product = productType.uppercase()
|
||||||
val camera = cloudCameraText()
|
val camera = cloudCameraText()
|
||||||
@@ -1369,13 +1447,42 @@ private fun TelemetrySnapshot.cloudDroneSubType(): Int {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun TelemetrySnapshot.cloudCameraPayloadIndexes(): List<String> {
|
internal fun TelemetrySnapshot.cloudCameraPayloadIndexes(): List<String> {
|
||||||
val detectedIndexes = cameraIdentities
|
val detectedIndexes = cameraIdentities
|
||||||
.mapNotNull { it.cloudCameraPayloadIndex(productType) }
|
.mapNotNull { it.cloudCameraPayloadIndex(productType) }
|
||||||
.distinct()
|
.distinct()
|
||||||
return detectedIndexes.ifEmpty { listOf(cloudCameraPayloadIndex()) }
|
return detectedIndexes.ifEmpty { listOf(cloudCameraPayloadIndex()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The platform can address Matrice 4 thermal controls as 89 while video/OSD identifies the camera as 99. */
|
||||||
|
internal fun TelemetrySnapshot.cloudCameraOsdPayloadIndexes(): List<String> {
|
||||||
|
val reported = cloudCameraPayloadIndexes()
|
||||||
|
val aliases = reported.mapNotNull { index ->
|
||||||
|
val parts = index.split('-')
|
||||||
|
if (parts.size == 3 && parts[0] == "99") "89-${parts[1]}-${parts[2]}" else null
|
||||||
|
}
|
||||||
|
return (reported + aliases).distinct()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun TelemetrySnapshot.cloudCameraComponentForPayloadIndex(payloadIndex: String): String? {
|
||||||
|
val detected = cameraIdentities.mapNotNull { identity ->
|
||||||
|
identity.cloudCameraPayloadIndex(productType)?.let { index -> index to identity.component }
|
||||||
|
}
|
||||||
|
val available = detected.ifEmpty { listOf(cloudCameraPayloadIndex() to cameraComponent) }
|
||||||
|
available.firstOrNull { it.first == payloadIndex }?.let { return it.second }
|
||||||
|
val aliases = available.filter { (index, _) -> isMatrice4ThermalPaletteAlias(payloadIndex, index) }
|
||||||
|
return aliases.singleOrNull()?.second
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isMatrice4ThermalPaletteAlias(requested: String, reported: String): Boolean {
|
||||||
|
val requestedParts = requested.split('-')
|
||||||
|
val reportedParts = reported.split('-')
|
||||||
|
if (requestedParts.size != 3 || reportedParts.size != 3) return false
|
||||||
|
val types = setOf(requestedParts[0], reportedParts[0])
|
||||||
|
return types == setOf("89", "99") && requestedParts[1] == reportedParts[1] &&
|
||||||
|
requestedParts[2] == reportedParts[2]
|
||||||
|
}
|
||||||
|
|
||||||
private fun TelemetrySnapshot.cloudCameraPayloadIndex(): String {
|
private fun TelemetrySnapshot.cloudCameraPayloadIndex(): String {
|
||||||
val payloadType = cloudPayloadTypeFor(
|
val payloadType = cloudPayloadTypeFor(
|
||||||
cameraTypeValue = cameraTypeValue,
|
cameraTypeValue = cameraTypeValue,
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import dji.sdk.keyvalue.value.camera.CameraFocusMode
|
|||||||
import dji.sdk.keyvalue.value.camera.CameraNightSceneMode
|
import dji.sdk.keyvalue.value.camera.CameraNightSceneMode
|
||||||
import dji.sdk.keyvalue.value.camera.CameraVideoStreamSourceType
|
import dji.sdk.keyvalue.value.camera.CameraVideoStreamSourceType
|
||||||
import dji.sdk.keyvalue.value.camera.CameraThermalPalette
|
import dji.sdk.keyvalue.value.camera.CameraThermalPalette
|
||||||
|
import dji.sdk.keyvalue.value.camera.ThermalGainMode
|
||||||
|
import dji.sdk.keyvalue.value.camera.ThermalTemperatureMeasureMode
|
||||||
import dji.sdk.keyvalue.value.camera.FrameZoomMsg
|
import dji.sdk.keyvalue.value.camera.FrameZoomMsg
|
||||||
import dji.sdk.keyvalue.value.camera.LiveViewSourceCameraType
|
import dji.sdk.keyvalue.value.camera.LiveViewSourceCameraType
|
||||||
import dji.sdk.keyvalue.value.camera.TapZoomMode
|
import dji.sdk.keyvalue.value.camera.TapZoomMode
|
||||||
@@ -18,6 +20,8 @@ import dji.sdk.keyvalue.value.camera.ThermalDisplayMode
|
|||||||
import dji.sdk.keyvalue.value.camera.ZoomTargetPointInfo
|
import dji.sdk.keyvalue.value.camera.ZoomTargetPointInfo
|
||||||
import dji.sdk.keyvalue.value.common.CameraLensType
|
import dji.sdk.keyvalue.value.common.CameraLensType
|
||||||
import dji.sdk.keyvalue.value.common.ComponentIndexType
|
import dji.sdk.keyvalue.value.common.ComponentIndexType
|
||||||
|
import dji.sdk.keyvalue.value.common.DoublePoint2D
|
||||||
|
import dji.sdk.keyvalue.value.common.DoubleRect
|
||||||
import dji.sdk.keyvalue.value.common.EmptyMsg
|
import dji.sdk.keyvalue.value.common.EmptyMsg
|
||||||
import dji.v5.common.error.IDJIError
|
import dji.v5.common.error.IDJIError
|
||||||
import dji.v5.et.action
|
import dji.v5.et.action
|
||||||
@@ -50,6 +54,55 @@ class CameraControlService(
|
|||||||
"红外色盘已切换:${palette.name}"
|
"红外色盘已切换:${palette.name}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
suspend fun setThermalMeteringMode(mode: ThermalTemperatureMeasureMode): DjiCommandResult =
|
||||||
|
setValueKey(
|
||||||
|
KeyTools.createCameraKey(DJICameraKey.KeyThermalTemperatureMeasureMode, cameraIndex, CameraLensType.CAMERA_LENS_THERMAL),
|
||||||
|
mode,
|
||||||
|
"红外测温模式已设置:${mode.name}"
|
||||||
|
)
|
||||||
|
|
||||||
|
suspend fun setThermalMeteringPoint(x: Double, y: Double): DjiCommandResult =
|
||||||
|
setValueKey(
|
||||||
|
KeyTools.createCameraKey(DJICameraKey.KeyThermalSpotMetersurePoint, cameraIndex, CameraLensType.CAMERA_LENS_THERMAL),
|
||||||
|
DoublePoint2D(x, y),
|
||||||
|
"红外点测温位置已设置"
|
||||||
|
)
|
||||||
|
|
||||||
|
suspend fun setThermalMeteringArea(x: Double, y: Double, width: Double, height: Double): DjiCommandResult =
|
||||||
|
setValueKey(
|
||||||
|
KeyTools.createCameraKey(DJICameraKey.KeyThermalRegionMetersureArea, cameraIndex, CameraLensType.CAMERA_LENS_THERMAL),
|
||||||
|
DoubleRect(x, y, width, height),
|
||||||
|
"红外区域测温位置已设置"
|
||||||
|
)
|
||||||
|
|
||||||
|
suspend fun setThermalIsothermEnabled(enabled: Boolean): DjiCommandResult =
|
||||||
|
setValueKey(
|
||||||
|
KeyTools.createCameraKey(DJICameraKey.KeyThermalIsothermEnabled, cameraIndex, CameraLensType.CAMERA_LENS_THERMAL),
|
||||||
|
enabled,
|
||||||
|
if (enabled) "等温线已开启" else "等温线已关闭"
|
||||||
|
)
|
||||||
|
|
||||||
|
suspend fun setThermalIsothermLower(value: Int): DjiCommandResult =
|
||||||
|
setValueKey(
|
||||||
|
KeyTools.createCameraKey(DJICameraKey.KeyThermalIsothermLowerValue, cameraIndex, CameraLensType.CAMERA_LENS_THERMAL),
|
||||||
|
value,
|
||||||
|
"等温线下限已设置"
|
||||||
|
)
|
||||||
|
|
||||||
|
suspend fun setThermalIsothermUpper(value: Int): DjiCommandResult =
|
||||||
|
setValueKey(
|
||||||
|
KeyTools.createCameraKey(DJICameraKey.KeyThermalIsothermUpperValue, cameraIndex, CameraLensType.CAMERA_LENS_THERMAL),
|
||||||
|
value,
|
||||||
|
"等温线上限已设置"
|
||||||
|
)
|
||||||
|
|
||||||
|
suspend fun setThermalGainMode(mode: ThermalGainMode): DjiCommandResult =
|
||||||
|
setValueKey(
|
||||||
|
KeyTools.createCameraKey(DJICameraKey.KeyThermalGainMode, cameraIndex, CameraLensType.CAMERA_LENS_THERMAL),
|
||||||
|
mode,
|
||||||
|
"红外增益模式已设置:${mode.name}"
|
||||||
|
)
|
||||||
|
|
||||||
suspend fun setLens(lens: String): DjiCommandResult {
|
suspend fun setLens(lens: String): DjiCommandResult {
|
||||||
val source = when (lens.normalizeLensName()) {
|
val source = when (lens.normalizeLensName()) {
|
||||||
"wide", "normal", "visible", "visible_wide", "camera_lens_wide" -> CameraVideoStreamSourceType.WIDE_CAMERA
|
"wide", "normal", "visible", "visible_wide", "camera_lens_wide" -> CameraVideoStreamSourceType.WIDE_CAMERA
|
||||||
|
|||||||
@@ -0,0 +1,259 @@
|
|||||||
|
package com.zklh.dronecontroller.core.media
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.zklh.dronecontroller.core.msdk.DjiCommandResult
|
||||||
|
import dji.sdk.keyvalue.key.KeyTools
|
||||||
|
import dji.sdk.keyvalue.key.DJIKey
|
||||||
|
import dji.sdk.keyvalue.key.PayloadKey
|
||||||
|
import dji.sdk.keyvalue.key.SpeakerKey
|
||||||
|
import dji.sdk.keyvalue.value.common.ComponentIndexType
|
||||||
|
import dji.v5.common.callback.CommonCallbacks
|
||||||
|
import dji.v5.common.recorder.PCMTools
|
||||||
|
import dji.v5.common.error.IDJIError
|
||||||
|
import dji.v5.manager.KeyManager
|
||||||
|
import dji.v5.manager.aircraft.megaphone.FileInfo
|
||||||
|
import dji.v5.manager.aircraft.megaphone.MegaphoneIndex
|
||||||
|
import dji.v5.manager.aircraft.megaphone.MegaphoneManager
|
||||||
|
import dji.v5.manager.aircraft.megaphone.MegaphoneInfo
|
||||||
|
import dji.v5.manager.aircraft.megaphone.MegaphoneInfoListener
|
||||||
|
import dji.v5.manager.aircraft.megaphone.MegaphoneStatus
|
||||||
|
import dji.v5.manager.aircraft.megaphone.PlayMode
|
||||||
|
import dji.v5.manager.aircraft.megaphone.UploadType
|
||||||
|
import dji.v5.manager.aircraft.megaphone.WorkMode
|
||||||
|
import java.io.File
|
||||||
|
import java.net.HttpURLConnection
|
||||||
|
import java.net.URL
|
||||||
|
import java.security.MessageDigest
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import org.json.JSONObject
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
|
data class SpeakerCloudStatus(
|
||||||
|
val psdkIndex: Int,
|
||||||
|
val name: String,
|
||||||
|
val serialNumber: String,
|
||||||
|
val volume: Int?,
|
||||||
|
val loop: Boolean?,
|
||||||
|
val systemState: Int?,
|
||||||
|
val fileName: String
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Adapts Cloud API speaker commands to MSDK's megaphone manager. */
|
||||||
|
class SpeakerCloudService(private val context: Context) {
|
||||||
|
private val manager = MegaphoneManager.getInstance()
|
||||||
|
private val commandMutex = Mutex()
|
||||||
|
private val listenHolder = Any()
|
||||||
|
private var listening = false
|
||||||
|
@Volatile private var selectedSpeakerIndex: Int? = null
|
||||||
|
@Volatile private var latestInfo: MegaphoneInfo? = null
|
||||||
|
private val infoListener = object : MegaphoneInfoListener {
|
||||||
|
override fun onUpdateMegaphoneInfo(megaphoneInfo: MegaphoneInfo?) {
|
||||||
|
latestInfo = megaphoneInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private val ports = listOf(
|
||||||
|
Triple(0, ComponentIndexType.LEFT_OR_MAIN, MegaphoneIndex.PORTSIDE),
|
||||||
|
Triple(1, ComponentIndexType.RIGHT, MegaphoneIndex.STARBOARD),
|
||||||
|
Triple(2, ComponentIndexType.UP, MegaphoneIndex.UPSIDE),
|
||||||
|
Triple(3, ComponentIndexType.PORT_1, MegaphoneIndex.PORT_1),
|
||||||
|
Triple(4, ComponentIndexType.PORT_2, MegaphoneIndex.PORT_2),
|
||||||
|
Triple(5, ComponentIndexType.PORT_3, MegaphoneIndex.PORT_3),
|
||||||
|
Triple(6, ComponentIndexType.PORT_4, MegaphoneIndex.PORT_4)
|
||||||
|
)
|
||||||
|
|
||||||
|
fun detect(): List<SpeakerCloudStatus> {
|
||||||
|
ensureListening()
|
||||||
|
return ports.mapNotNull { (index, component, _) ->
|
||||||
|
val connected = read { KeyManager.getInstance().getValue(KeyTools.createKey(SpeakerKey.KeyConnection, component)) }
|
||||||
|
val payloadName = read { KeyManager.getInstance().getValue(KeyTools.createKey(PayloadKey.KeyPayloadProductName, component)) }.orEmpty()
|
||||||
|
val payloadConnected = read { KeyManager.getInstance().getValue(KeyTools.createKey(PayloadKey.KeyConnection, component)) }
|
||||||
|
if (connected != true && !(payloadConnected == true &&
|
||||||
|
listOf("speaker", "megaphone", "loudspeaker", "喊话").any { payloadName.contains(it, ignoreCase = true) })) return@mapNotNull null
|
||||||
|
val volume = read { KeyManager.getInstance().getValue(KeyTools.createKey(SpeakerKey.KeyVolume, component)) }
|
||||||
|
val mode = read { KeyManager.getInstance().getValue(KeyTools.createKey(SpeakerKey.KeySpeakerPlayMode, component)) }
|
||||||
|
val playing = read { KeyManager.getInstance().getValue(KeyTools.createKey(SpeakerKey.KeyPlayingAudioFileInfo, component)) }
|
||||||
|
val selectedInfo = latestInfo.takeIf { selectedSpeakerIndex == index }
|
||||||
|
SpeakerCloudStatus(
|
||||||
|
psdkIndex = index,
|
||||||
|
name = payloadName.ifBlank { "DJI Speaker" },
|
||||||
|
serialNumber = read { KeyManager.getInstance().getValue(KeyTools.createKey(PayloadKey.KeyPayloadSerialNumber, component)) }.orEmpty(),
|
||||||
|
volume = selectedInfo?.volume ?: volume,
|
||||||
|
loop = selectedInfo?.playMode?.let { it == PlayMode.LOOP } ?: mode?.name?.contains("LOOP"),
|
||||||
|
systemState = when (selectedInfo?.status) {
|
||||||
|
MegaphoneStatus.IDLE -> 0
|
||||||
|
MegaphoneStatus.IN_TRANSMISSION -> 1
|
||||||
|
MegaphoneStatus.PLAYING -> 2
|
||||||
|
MegaphoneStatus.IN_EXCEPTION -> 3
|
||||||
|
MegaphoneStatus.TTS_IN_CONVERSION -> 4
|
||||||
|
else -> playing?.isPlaying?.let { if (it) 2 else 0 }
|
||||||
|
},
|
||||||
|
fileName = read { KeyManager.getInstance().getValue(KeyTools.createKey(PayloadKey.KeyMegaphoneFileName, component)) }.orEmpty()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized private fun ensureListening() {
|
||||||
|
if (listening) return
|
||||||
|
listening = true
|
||||||
|
runCatching { manager.addMegaphoneInfoListener(infoListener) }
|
||||||
|
ports.forEach { (_, component, _) ->
|
||||||
|
listen(KeyTools.createKey(SpeakerKey.KeyConnection, component))
|
||||||
|
listen(KeyTools.createKey(SpeakerKey.KeyVolume, component))
|
||||||
|
listen(KeyTools.createKey(SpeakerKey.KeySpeakerPlayMode, component))
|
||||||
|
listen(KeyTools.createKey(SpeakerKey.KeyPlayingAudioFileInfo, component))
|
||||||
|
listen(KeyTools.createKey(PayloadKey.KeyConnection, component))
|
||||||
|
listen(KeyTools.createKey(PayloadKey.KeyPayloadProductName, component))
|
||||||
|
listen(KeyTools.createKey(PayloadKey.KeyPayloadSerialNumber, component))
|
||||||
|
listen(KeyTools.createKey(PayloadKey.KeyMegaphoneFileName, component))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T> listen(key: DJIKey<T>) {
|
||||||
|
runCatching { KeyManager.getInstance().listen(key, listenHolder, true) { _, _ -> } }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized fun stopMonitoring() {
|
||||||
|
if (!listening) return
|
||||||
|
runCatching { KeyManager.getInstance().cancelListen(listenHolder) }
|
||||||
|
runCatching { manager.removeMegaphoneInfoListener(infoListener) }
|
||||||
|
selectedSpeakerIndex = null
|
||||||
|
latestInfo = null
|
||||||
|
listening = false
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun execute(method: String, data: JSONObject): DjiCommandResult = commandMutex.withLock {
|
||||||
|
executeLocked(method, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun executeLocked(method: String, data: JSONObject): DjiCommandResult {
|
||||||
|
val index = data.optInt("psdk_index", -1)
|
||||||
|
val port = ports.firstOrNull { it.first == index }
|
||||||
|
?: return DjiCommandResult.failed("喊话器索引无效:$index")
|
||||||
|
if (detect().none { it.psdkIndex == index }) return DjiCommandResult.failed("未检测到索引 $index 对应的喊话器")
|
||||||
|
val selected = callback { manager.setMegaphoneIndex(port.third, it) }
|
||||||
|
if (!selected.success) return selected
|
||||||
|
selectedSpeakerIndex = index
|
||||||
|
latestInfo = null
|
||||||
|
return when (method) {
|
||||||
|
"speaker_play_volume_set" -> {
|
||||||
|
val volume = data.optInt("play_volume", -1)
|
||||||
|
if (volume !in 0..100) DjiCommandResult.failed("喊话音量必须为 0 到 100")
|
||||||
|
else callback { manager.setVolume(volume, it) }
|
||||||
|
}
|
||||||
|
"speaker_play_mode_set" -> {
|
||||||
|
val mode = data.optInt("play_mode", -1)
|
||||||
|
when (mode) {
|
||||||
|
0, 1 -> callback { manager.setPlayMode(if (mode == 1) PlayMode.LOOP else PlayMode.SINGLE, it) }
|
||||||
|
else -> DjiCommandResult.failed("喊话播放模式无效")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"speaker_play_stop" -> callback { manager.stopPlay(it) }
|
||||||
|
"speaker_replay" -> callback { manager.startPlay(it) }
|
||||||
|
"speaker_tts_play_start" -> {
|
||||||
|
val tts = data.optJSONObject("tts") ?: return DjiCommandResult.failed("缺少喊话文本")
|
||||||
|
val text = tts.optString("text").trim()
|
||||||
|
if (text.isBlank() || text.length > 2000) return DjiCommandResult.failed("喊话文本为空或超过 2000 字")
|
||||||
|
val workMode = callback { manager.setWorkMode(WorkMode.TTS, it) }
|
||||||
|
if (!workMode.success) return workMode
|
||||||
|
val upload = upload(FileInfo(UploadType.TTS_DATA, null, text.toByteArray(Charsets.UTF_8)))
|
||||||
|
if (!upload.success) return upload
|
||||||
|
callback { manager.startPlay(it) }
|
||||||
|
}
|
||||||
|
"speaker_audio_play_start" -> {
|
||||||
|
val file = data.optJSONObject("file") ?: return DjiCommandResult.failed("缺少喊话音频文件")
|
||||||
|
val url = file.optString("url")
|
||||||
|
val format = file.optString("format").lowercase()
|
||||||
|
if (format !in setOf("pcm", "opus", "mp3", "wav"))
|
||||||
|
return DjiCommandResult.failed("当前 MSDK 音频播放仅支持 PCM、OPUS、MP3 或 WAV")
|
||||||
|
if (!url.startsWith("https://", ignoreCase = true) && !url.startsWith("http://", ignoreCase = true))
|
||||||
|
return DjiCommandResult.failed("喊话音频下载地址无效")
|
||||||
|
val local = runCatching { download(url, file.optString("md5"), format) }
|
||||||
|
.getOrElse { return DjiCommandResult.failed("喊话音频下载失败:${it.message}") }
|
||||||
|
var convertedPcm: File? = null
|
||||||
|
try {
|
||||||
|
val playable = if (format == "opus") local else {
|
||||||
|
val pcm = if (format == "pcm") local else {
|
||||||
|
val path = withContext(Dispatchers.IO) { PCMTools.convertToPcmFileSync(local.absolutePath) }
|
||||||
|
if (path.isNullOrBlank()) return DjiCommandResult.failed("音频转 PCM 失败")
|
||||||
|
File(path).also { convertedPcm = it }
|
||||||
|
}
|
||||||
|
val path = withContext(Dispatchers.IO) { PCMTools.convertToOpusFileSync(pcm.absolutePath) }
|
||||||
|
if (path.isNullOrBlank()) return DjiCommandResult.failed("PCM 转 OPUS 失败")
|
||||||
|
File(path)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
val workMode = callback { manager.setWorkMode(WorkMode.VOICE, it) }
|
||||||
|
if (!workMode.success) return workMode
|
||||||
|
val upload = upload(FileInfo(UploadType.VOICE_FILE, playable, null))
|
||||||
|
if (!upload.success) return upload
|
||||||
|
callback { manager.startPlay(it) }
|
||||||
|
} finally {
|
||||||
|
if (playable != local) playable.delete()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
convertedPcm?.takeIf { it != local }?.delete()
|
||||||
|
local.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> DjiCommandResult.failed("未支持的喊话指令:$method")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T> read(block: () -> T?): T? = runCatching(block).getOrNull()
|
||||||
|
|
||||||
|
private suspend fun callback(invoke: (CommonCallbacks.CompletionCallback) -> Unit): DjiCommandResult =
|
||||||
|
suspendCancellableCoroutine { continuation ->
|
||||||
|
invoke(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 suspend fun upload(file: FileInfo): DjiCommandResult = suspendCancellableCoroutine { continuation ->
|
||||||
|
manager.startPushingFileToMegaphone(file, object : CommonCallbacks.CompletionCallbackWithProgress<Int> {
|
||||||
|
override fun onProgressUpdate(progress: Int) = Unit
|
||||||
|
override fun onSuccess() { if (continuation.isActive) continuation.resume(DjiCommandResult.ok("喊话文件已上传")) }
|
||||||
|
override fun onFailure(error: IDJIError) { if (continuation.isActive) continuation.resume(DjiCommandResult.failed(error)) }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun download(address: String, expectedMd5: String, format: String): File = withContext(Dispatchers.IO) {
|
||||||
|
val destination = File.createTempFile("speaker-", ".$format", context.cacheDir)
|
||||||
|
try {
|
||||||
|
val connection = URL(address).openConnection() as HttpURLConnection
|
||||||
|
connection.connectTimeout = 10_000
|
||||||
|
connection.readTimeout = 30_000
|
||||||
|
connection.instanceFollowRedirects = false
|
||||||
|
try {
|
||||||
|
if (connection.responseCode !in 200..299) error("HTTP ${connection.responseCode}")
|
||||||
|
var total = 0L
|
||||||
|
connection.inputStream.use { input ->
|
||||||
|
destination.outputStream().use { output ->
|
||||||
|
val buffer = ByteArray(8192)
|
||||||
|
while (true) {
|
||||||
|
val count = input.read(buffer)
|
||||||
|
if (count < 0) break
|
||||||
|
total += count
|
||||||
|
if (total > 20L * 1024 * 1024) error("音频文件超过 20 MB")
|
||||||
|
output.write(buffer, 0, count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (total == 0L) error("音频文件为空")
|
||||||
|
if (expectedMd5.matches(Regex("[0-9a-fA-F]{32}"))) {
|
||||||
|
val digest = MessageDigest.getInstance("MD5").digest(destination.readBytes())
|
||||||
|
.joinToString("") { "%02x".format(it.toInt() and 0xff) }
|
||||||
|
if (!digest.equals(expectedMd5, ignoreCase = true)) error("音频校验失败")
|
||||||
|
}
|
||||||
|
destination
|
||||||
|
} finally { connection.disconnect() }
|
||||||
|
} catch (error: Exception) {
|
||||||
|
destination.delete()
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+59
-1
@@ -3,6 +3,9 @@ package com.zklh.dronecontroller.core.telemetry
|
|||||||
import dji.sdk.keyvalue.key.*
|
import dji.sdk.keyvalue.key.*
|
||||||
import dji.sdk.keyvalue.value.common.CameraLensType
|
import dji.sdk.keyvalue.value.common.CameraLensType
|
||||||
import dji.sdk.keyvalue.value.common.ComponentIndexType
|
import dji.sdk.keyvalue.value.common.ComponentIndexType
|
||||||
|
import dji.sdk.keyvalue.value.common.DoublePoint2D
|
||||||
|
import dji.sdk.keyvalue.value.common.DoubleRect
|
||||||
|
import dji.sdk.keyvalue.value.camera.ThermalAreaMetersureTemperature
|
||||||
import dji.v5.manager.KeyManager
|
import dji.v5.manager.KeyManager
|
||||||
|
|
||||||
/** Read-only camera telemetry. Never fabricate values for unsupported SDK keys. */
|
/** Read-only camera telemetry. Never fabricate values for unsupported SDK keys. */
|
||||||
@@ -12,6 +15,10 @@ internal class CameraCloudTelemetry(private val publish: (Map<String, Any>, Map<
|
|||||||
private val payload = mutableMapOf<String, Any>()
|
private val payload = mutableMapOf<String, Any>()
|
||||||
private val readers = mutableListOf<() -> Unit>()
|
private val readers = mutableListOf<() -> Unit>()
|
||||||
private var started = false
|
private var started = false
|
||||||
|
private var meteringPoint: DoublePoint2D? = null
|
||||||
|
private var meteringPointTemperature: Double? = null
|
||||||
|
private var meteringArea: DoubleRect? = null
|
||||||
|
private var meteringAreaTemperature: ThermalAreaMetersureTemperature? = null
|
||||||
|
|
||||||
@Synchronized private fun put(target: MutableMap<String, Any>, name: String, value: Any?) {
|
@Synchronized private fun put(target: MutableMap<String, Any>, name: String, value: Any?) {
|
||||||
if (target[name] == value) return
|
if (target[name] == value) return
|
||||||
@@ -57,6 +64,25 @@ internal class CameraCloudTelemetry(private val publish: (Map<String, Any>, Map<
|
|||||||
put(camera, "_storage_remaining_mb", storage?.storageLeftCapacity)
|
put(camera, "_storage_remaining_mb", storage?.storageLeftCapacity)
|
||||||
}
|
}
|
||||||
val thermal = CameraLensType.CAMERA_LENS_THERMAL
|
val thermal = CameraLensType.CAMERA_LENS_THERMAL
|
||||||
|
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalTemperatureMeasureMode, main, thermal)) { mode ->
|
||||||
|
put(camera, "ir_metering_mode", when (mode?.name) { "DISABLED" -> 0; "SPOT" -> 1; "REGION" -> 2; else -> null })
|
||||||
|
}
|
||||||
|
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalSpotMetersurePoint, main, thermal)) { point ->
|
||||||
|
meteringPoint = point
|
||||||
|
publishMeteringPoint()
|
||||||
|
}
|
||||||
|
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalSpotMetersureTemperature, main, thermal)) { temperature ->
|
||||||
|
meteringPointTemperature = temperature
|
||||||
|
publishMeteringPoint()
|
||||||
|
}
|
||||||
|
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalRegionMetersureArea, main, thermal)) { area ->
|
||||||
|
meteringArea = area
|
||||||
|
publishMeteringArea()
|
||||||
|
}
|
||||||
|
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalRegionMetersureTemperature, main, thermal)) { temperature ->
|
||||||
|
meteringAreaTemperature = temperature
|
||||||
|
publishMeteringArea()
|
||||||
|
}
|
||||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalGlobalMaxTemperature, main, thermal)) { put(payload, "thermal_global_temperature_max", it) }
|
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.KeyThermalGlobalMinTemperature, main, thermal)) { put(payload, "thermal_global_temperature_min", it) }
|
||||||
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalGainMode, main, thermal)) {
|
watch(KeyTools.createCameraKey(DJICameraKey.KeyThermalGainMode, main, thermal)) {
|
||||||
@@ -71,10 +97,42 @@ internal class CameraCloudTelemetry(private val publish: (Map<String, Any>, Map<
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun refresh() { readers.toList().forEach { it() } }
|
fun refresh() { readers.toList().forEach { it() } }
|
||||||
|
|
||||||
|
private fun publishMeteringPoint() {
|
||||||
|
val point = meteringPoint ?: return
|
||||||
|
val fields = mutableMapOf<String, Any>("x" to point.x, "y" to point.y)
|
||||||
|
meteringPointTemperature?.let { fields["temperature"] = it }
|
||||||
|
put(camera, "ir_metering_point", fields)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun publishMeteringArea() {
|
||||||
|
val area = meteringArea ?: return
|
||||||
|
val fields = mutableMapOf<String, Any>("x" to area.x, "y" to area.y,
|
||||||
|
"width" to area.width, "height" to area.height)
|
||||||
|
meteringAreaTemperature?.let { reading ->
|
||||||
|
reading.averageAreaTemperature?.let { fields["temperature"] = it }
|
||||||
|
reading.averageAreaTemperature?.let { fields["aver_temperature"] = it }
|
||||||
|
reading.minTemperaturePoint?.let { point ->
|
||||||
|
fields["min_temperature_point"] = mapOf("x" to point.x, "y" to point.y,
|
||||||
|
"temperature" to (reading.minAreaTemperature ?: 0.0))
|
||||||
|
}
|
||||||
|
reading.maxTemperaturePoint?.let { point ->
|
||||||
|
fields["max_temperature_point"] = mapOf("x" to point.x, "y" to point.y,
|
||||||
|
"temperature" to (reading.maxAreaTemperature ?: 0.0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
put(camera, "ir_metering_area", fields)
|
||||||
|
}
|
||||||
|
|
||||||
fun stop() {
|
fun stop() {
|
||||||
runCatching { KeyManager.getInstance().cancelListen(holder) }
|
runCatching { KeyManager.getInstance().cancelListen(holder) }
|
||||||
readers.clear()
|
readers.clear()
|
||||||
started = false
|
started = false
|
||||||
synchronized(this) { camera.clear(); payload.clear(); publish(emptyMap(), emptyMap()) }
|
synchronized(this) {
|
||||||
|
camera.clear(); payload.clear()
|
||||||
|
meteringPoint = null; meteringPointTemperature = null
|
||||||
|
meteringArea = null; meteringAreaTemperature = null
|
||||||
|
publish(emptyMap(), emptyMap())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user