Files
suixinkan_uikit/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift
T
lujiuyin 34ee60b8b2 完善机巢任务实时同步并开放双构建真实操作
订阅明确无缓存时使用新发起的有效 HTTP 全量响应衔接首包,保留任务、批次和版本校验。
移除 Debug/Release 的设备指令、图传和 RTC 构建拦截,保留后端权限、身份、防重复提交及结果未知保护。
更新开发约定并补充隔离传输、飞控状态和页面回归测试。

验证:iPhone 真机 500 项相关测试通过;iOS Release 无签名编译通过。
2026-11-05 10:59:26 +08:00

1373 lines
75 KiB
Swift

import Foundation
/// 拍摄任务状态及可选控制流程,始终复用同一任务;Release 真实入口与隔离模拟入口按策略注入操作服务。
final class DroneDockShootingTaskViewModel {
/// 页面绑定的账号、景区和门店身份。
let context: DroneDockHomeContext
/// 创建并召唤时使用的同一订单飞行任务 ID。
let taskID: Int
/// 进入页面携带的订单摘要,仅作未返回展示字段时的订单文案备用。
let order: DroneDockHomeOrder
/// 最近一次通过身份检查的服务端快照,刷新期间保留,成功后整体替换。
private(set) var response: DroneDockShootingResponse?
/// 同一页面最多存在一个读取请求。
private(set) var isLoading = false
/// 读取失败或身份变化时的提示。
private(set) var errorMessage: String?
/// 开拍提交及其后单次状态核对期间禁用重复操作,保留之前的显示快照。
private(set) var isStartingShooting = false
/// 开拍业务拒绝、本地拦截或结果待核对的说明。
private(set) var startErrorMessage: String?
/// 已发送但无法确认的开拍请求,不因后续读取仍允许开始而自动解除。
private(set) var startOutcomeUnknown = false
/// 当前页面是否已收到明确开拍受理回执,收到后不会再次提交。
private(set) var hasSubmittedStart = false
/// 同任务开拍回执;受理成功不直接替代 shooting 的完整状态快照。
private(set) var startResponse: DroneDockStartShootResponse?
/// 当前有安全指令 HTTP 提交,供生命周期取消使用,不作为其他安全按钮的总锁。
var isSendingCommand: Bool { commandOperations.values.contains { $0.phase == .sending } }
/// 最近正在提交的动作,仅供诊断;按钮分别读取 isCommandLoading。
var activeCommand: DroneDockSafetyCommand? {
commandOperations.values.filter { $0.phase == .sending }.max { $0.sequence < $1.sequence }?.command
}
/// 最近一次明确受理且身份一致的指令回执,不替代任务快照。
private(set) var commandResponse: DroneDockCommandResponse?
/// 最近一次操作提示,界面按对应动作读取,不覆盖中央业务文案。
var commandErrorMessage: String? {
commandOperations.values.filter { $0.error != nil }.max { $0.sequence < $1.sequence }?.error
}
/// 任一动作结果未知时,开拍和重召唤保持保护,安全动作仍独立授权。
var commandOutcomeUnknown: Bool { commandOperations.values.contains { $0.phase == .unknown } }
/// 重新召唤提交及其后单次回查期间保留旧画面并锁定其他操作。
private(set) var isResummoning = false
/// 重新召唤明确拒绝、本地拦截或待核对的说明。
private(set) var resummonErrorMessage: String?
/// 请求已发送但受理结果未知,普通刷新不能解除重发锁。
private(set) var resummonOutcomeUnknown = false
/// 当前页面已受理一次重召唤;旧失败快照不能使同一请求再次提交。
private(set) var hasSubmittedResummon = false
/// 重新召唤的原始受理回执,不替代 shooting 的设备状态。
private(set) var resummonResponse: DroneDockShootResponse?
private let diagnostics: DroneDockTaskDiagnostics
private let service: any DroneDockShootingServing
private let startService: (any DroneDockStartShooting)?
private let commandService: (any DroneDockCommandSending)?
private let resummonService: (any DroneDockResummonServing)?
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private let countdownNow: @Sendable () -> ContinuousClock.Instant
private var arrivalCountdownDeadlines: [String: ContinuousClock.Instant] = [:]
/// 无权限或登录失效后停止自动读取,旧数据仅用于展示。
private(set) var readAccessError: String?
private var snapshotRevision = 0
private var generation = 0
private var identityInvalidated = false
private var startGeneration = 0
private var didSendStart = false
private var commandGeneration = 0
private var resummonGeneration = 0
private var didSendResummon = false
private var awaitingResummonSnapshot = false
// 仅在首份完整快照返回之前使用同一任务的 going_to_spot 回执,不补造设备状态。
private var hasInitialTravelReceipt: Bool
private var commandOperations: [DroneDockSafetyCommand: DroneDockCommandOperation] = [:]
private var commandSequence = 0
private var commandTasks: [String: Task<Void, Never>] = [:]
private var commandTransportTail: Task<Void, Never>?
private var supersededCommandIDs: Set<String> = []
private var minimumCommandSnapshotVersion: Int64?
private var retainedMetrics: [String: DroneDockHomeMetric] = [:]
private var isUsingRetainedMetrics = false
/// 当前等待确认的动作,仅用于开拍/重召唤保护,不覆盖页面阶段。
var pendingCommand: DroneDockSafetyCommand? {
commandOperations.values.filter { $0.phase == .pending || $0.phase == .unknown || $0.phase == .confirmed }
.max { $0.sequence < $1.sequence }?.command ?? remotePendingCommand
}
/// 默认只读;仅显式注入操作服务时开放对应动作,Release 入口按授权注入。
init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder,
service: any DroneDockShootingServing,
startService: (any DroneDockStartShooting)? = nil,
commandService: (any DroneDockCommandSending)? = nil,
resummonService: (any DroneDockResummonServing)? = nil,
initialSummonReceipt: DroneDockShootResponse? = nil,
countdownNow: @escaping @Sendable () -> ContinuousClock.Instant = { ContinuousClock.now },
diagnostics: DroneDockTaskDiagnostics = DroneDockTaskDiagnostics(),
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.diagnostics = diagnostics
self.context = context
self.taskID = taskID
self.order = order
self.service = service
self.startService = startService
self.commandService = commandService
self.resummonService = resummonService
self.currentContext = currentContext
self.countdownNow = countdownNow
self.hasInitialTravelReceipt = context.canLoad && initialSummonReceipt?.confirmsTravel(
taskID: taskID, orderNumber: order.orderNumber, scenicID: context.scenicID) == true
recordTaskEvent("task.created", fields: ["initial_travel_receipt": hasInitialTravelReceipt,
"summon_receipt": DroneDockTaskTraceFields.summon(initialSummonReceipt)])
}
/// 页面与业务层共享会话标识,串联准备页导航、快照和按钮事件。
var diagnosticSessionID: String { diagnostics.sessionID }
/// 记录任务关键事件,不改变接口、定时器、门禁或任何业务状态。
func recordTaskEvent(_ event: String, fields: [String: Any] = [:]) {
let contextFields: [String: Any] = ["scenic_id": context.scenicID,
"order_number": DroneDockTaskTraceFields.value(order.orderNumber),
"execution_batch": DroneDockTaskTraceFields.value(response?.executionBatch),
"state_version": DroneDockTaskTraceFields.value(response?.stateVersion)]
diagnostics.record(event, taskID: taskID, fields: contextFields.merging(fields) { _, new in new })
}
/// 同一时刻的后端证据与本地判断,用于和录屏中的实际显示逐段对照。
var taskDiagnosticFields: [String: Any] {
let state = presentation
let metrics = telemetry
return ["backend": DroneDockTaskTraceFields.snapshot(response), "local": [
"phase": state.phase.rawValue, "conflict": resolvedDisplayPhase().1,
"title": state.title, "message": state.message, "action": String(describing: state.action),
"action_enabled": state.isActionEnabled, "countdown_seconds": DroneDockTaskTraceFields.value(state.countdownSeconds),
"pause_allowed": canSendCommand(.pause), "resume_allowed": canSendCommand(.resume),
"return_allowed": canSendCommand(.returnHome), "start_allowed": canStartShooting,
"restart_allowed": canResummon, "pause_loading": isCommandLoading(.pause),
"resume_loading": isCommandLoading(.resume), "return_loading": isCommandLoading(.returnHome),
"start_outcome_unknown": startOutcomeUnknown, "command_outcome_unknown": commandOutcomeUnknown,
"resummon_outcome_unknown": resummonOutcomeUnknown,
"read_access_error": DroneDockTaskTraceFields.value(readAccessError),
"read_error": DroneDockTaskTraceFields.value(errorMessage),
"recording_finished": isRecordingFinished, "stop_live": shouldStopLiveReception,
"using_retained_metrics": isUsingRetainedMetrics, "telemetry_stale": isTelemetryStale,
"telemetry": ["battery": metrics.batteryText, "env_temp": metrics.temperatureText,
"wind_speed": metrics.windText, "rainfall": metrics.rainText,
"signal": metrics.signalText, "satellite": metrics.satelliteText]]]
}
/// 页面可见时读取同一任务;刷新及普通失败保留旧快照,身份失效立即清除。
@MainActor
func refresh() async {
await refreshSnapshot(allowWhileStarting: false)
}
/// 无缓存订阅只认此调用新读取且采纳的 HTTP 结果;读取未发起、失败或旧版本均返回 nil。
@MainActor
func refreshForRealtimeSeed() async -> DroneDockHTTPSnapshotResult? {
await refreshSnapshot(allowWhileStarting: false)
}
/// 操作提交前仅作废在途读取,保留快照和操作防重锁;迟到的旧读取不能覆盖操作回查。
@MainActor
func invalidatePendingRefresh() {
generation &+= 1
isLoading = false
}
/// 后端建议间隔限制为 2~30 秒;缺失或无效时默认 5 秒,从上次请求结束后计时。
var pollIntervalNanoseconds: UInt64 {
let hint = response?.planeStatus?.pollHintMS ?? 5_000
return UInt64(min(max(hint > 0 ? hint : 5_000, 2_000), 30_000)) * 1_000_000
}
/// 身份失效或缺少任务信息时停止安排下一次读取。
var canContinuePolling: Bool {
!identityInvalidated && readAccessError == nil && context.canLoad && taskID > 0
&& DroneDockHomeMetric.usableText(order.orderNumber) != nil
}
@MainActor
@discardableResult
private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false,
allowWhileResummoning: Bool = false) async -> DroneDockHTTPSnapshotResult? {
guard !isLoading, !identityInvalidated, readAccessError == nil, !isStartingShooting || allowWhileStarting,
!isResummoning || allowWhileResummoning else { return nil }
generation &+= 1
let requestGeneration = generation
let revisionAtRequest = snapshotRevision
isLoading = true
recordTaskEvent("snapshot.http_requested", fields: ["read_generation": requestGeneration, "live_battery": 0])
// 已失败的旧快照须等有效新响应再恢复操作,避免每次重查先短暂放开。
defer {
if generation == requestGeneration {
isLoading = false
}
}
guard accepts(requestGeneration) else { return nil }
guard context.canLoad, taskID > 0,
DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
response = nil
errorMessage = "缺少有效任务、订单或景区信息,请返回工作台重新进入"
return nil
}
do {
let value = try await service.shooting(taskID: taskID, liveBattery: false)
guard accepts(requestGeneration) else {
recordTaskEvent("snapshot.http_ignored", fields: ["read_generation": requestGeneration,
"current_generation": generation, "reason": "cancelled_or_stale_read",
"incoming": DroneDockTaskTraceFields.snapshot(value)])
return nil
}
let acceptance = applyTaskSnapshot(value, source: .http)
if acceptance == .invalid {
response = nil
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
}
switch acceptance {
case .applied, .duplicate:
return DroneDockHTTPSnapshotResult(snapshot: value, acceptance: acceptance)
case .outdated, .invalid: return nil
}
} catch {
guard accepts(requestGeneration) else { return nil }
if Self.stopsTaskReading(error) {
stopReading(message: error.localizedDescription)
return nil
}
// 迟到 HTTP 失败不能覆盖请求期间已收到的有效实时状态。
guard snapshotRevision == revisionAtRequest else { return nil }
if !(error is CancellationError) { errorMessage = error.localizedDescription }
recordTaskEvent("snapshot.http_failed", fields: [
"retained_snapshot": response != nil, "error": DroneDockDiagnostics.errorFields(error)
])
return nil
}
}
/// HTTP 和推送共享完整快照入口,按执行批次、版本去重,绝不按到达顺序覆盖。
@MainActor
@discardableResult
func applyTaskSnapshot(_ value: DroneDockShootingResponse,
source: DroneDockTaskSnapshotSource = .unspecified) -> DroneDockSnapshotAcceptance {
let incoming = DroneDockTaskTraceFields.snapshot(value)
func rejected(_ result: DroneDockSnapshotAcceptance, reason: String) -> DroneDockSnapshotAcceptance {
recordTaskEvent("snapshot.ignored", fields: ["source": source.rawValue,
"result": String(describing: result), "reason": reason, "incoming": incoming])
return result
}
guard readAccessError == nil else { return rejected(.invalid, reason: "read_access_denied") }
guard accepts(generation) else { return rejected(.invalid, reason: "cancelled_or_identity_changed") }
guard matchesIdentity(value) else { return rejected(.invalid, reason: "task_order_or_scenic_mismatch") }
let previousBatch = response?.executionBatch
let previousVersion = response?.stateVersion
let previousPhase = presentation.phase.rawValue
if let oldBatch = response?.executionBatch, let oldVersion = response?.stateVersion {
guard let batch = value.executionBatch, let version = value.stateVersion else {
return rejected(.outdated, reason: "missing_batch_or_version")
}
if batch == oldBatch, version < (minimumCommandSnapshotVersion ?? 0) {
return rejected(.outdated, reason: "below_command_receipt_version_floor")
}
if batch < oldBatch || (batch == oldBatch && version < oldVersion) {
return rejected(.outdated, reason: "older_batch_or_version")
}
if batch == oldBatch && version == oldVersion {
errorMessage = nil
snapshotRevision &+= 1
return rejected(.duplicate, reason: "same_batch_and_version")
}
}
if let oldBatch = response?.executionBatch, let newBatch = value.executionBatch, newBatch > oldBatch {
recordTaskEvent("task.new_batch", fields: ["old_batch": oldBatch, "new_batch": newBatch])
// 新批次是新的控制上下文;旧请求无论成功、失败还是取消均不得重建旧锁。
startGeneration &+= 1
invalidateCommand()
resummonGeneration &+= 1
isStartingShooting = false
isResummoning = false
didSendStart = false
didSendResummon = false
awaitingResummonSnapshot = false
clearPendingCommand()
minimumCommandSnapshotVersion = nil
commandResponse = nil
hasSubmittedStart = false
startOutcomeUnknown = false
startErrorMessage = nil
startResponse = nil
hasSubmittedResummon = false
resummonOutcomeUnknown = false
resummonErrorMessage = nil
resummonResponse = nil
}
if response?.executionBatch != value.executionBatch || response?.currentPlane?.id != value.currentPlane?.id {
retainedMetrics.removeAll()
}
isUsingRetainedMetrics = false
for key in ["battery", "env_temp", "wind_speed", "rainfall", "signal", "satellite"] {
if let metric = value.metrics.first(where: { $0.key == key && $0.displayText != "—" }) {
retainedMetrics[key] = metric
} else if retainedMetrics[key] != nil {
isUsingRetainedMetrics = true
}
}
response = value
reconcilePendingCommand()
if resolvedDisplayPhase().0 == .ready, arrivalCountdownDeadlines[recordingExecutionID] == nil {
arrivalCountdownDeadlines[recordingExecutionID] = countdownNow().advanced(by: .seconds(30))
recordTaskEvent("countdown.started", fields: ["seconds": 30, "source": source.rawValue])
}
hasInitialTravelReceipt = false
errorMessage = nil
snapshotRevision &+= 1
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .postShootUploading, .postShootUploadFailed, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
awaitingResummonSnapshot = false
}
recordTaskEvent("snapshot.applied", fields: ["source": source.rawValue,
"previous_batch": DroneDockTaskTraceFields.value(previousBatch),
"previous_version": DroneDockTaskTraceFields.value(previousVersion),
"previous_local_phase": previousPhase, "state": taskDiagnosticFields])
return .applied
}
/// 订阅明确无权限或 HTTP 鉴权失效时保留快照、禁用操作并停止后续读取。
@MainActor
func stopReading(message: String) {
generation &+= 1
isLoading = false
readAccessError = message
errorMessage = message
recordTaskEvent("task.read_access_stopped", fields: ["message": message])
}
/// 只把已确认的权限信息视为终止条件,不把所有 100099 业务错误一概当成无权限。
private static func stopsTaskReading(_ error: Error) -> Bool {
if APIError.isAuthenticationExpired(error) { return true }
guard case APIError.serverCode(let code, let message) = error else { return false }
return code == 100099 && (message.contains("无权") || message.contains("无权限") || message.contains("飞行任务不存在"))
}
/// 使旧请求失效;同一身份离页或进入后台可保留快照,账号变化始终清除并停止旧任务读取。
@MainActor
func invalidate(preservingSnapshot: Bool = false) {
recordTaskEvent("task.invalidated", fields: ["preserving_snapshot": preservingSnapshot])
invalidateStartShooting()
invalidateCommand()
invalidateResummon()
generation &+= 1
isLoading = false
if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true }
if identityInvalidated || !preservingSnapshot { hasInitialTravelReceipt = false }
if identityInvalidated || !preservingSnapshot { arrivalCountdownDeadlines.removeAll() }
if identityInvalidated {
response = nil
startResponse = nil
startErrorMessage = nil
commandResponse = nil
resummonResponse = nil
resummonErrorMessage = nil
clearPendingCommand()
errorMessage = "账号或景区已变化,请返回工作台重新进入"
} else {
if !preservingSnapshot { response = nil }
errorMessage = readAccessError
}
}
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放。
var canStartShooting: Bool {
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& hasControlSnapshotIdentity
&& hasKnownShootingTaskState
&& readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !hasSubmittedStart && !startOutcomeUnknown
&& !commandOperations.values.contains(where: { $0.isWaiting })
&& !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot && pendingCommand == nil
&& flightControlState == .executing
&& resolvedDisplayPhase().0 == .ready
&& response?.executeGate?.canExecute == true
&& response?.executeGate?.primaryAction == "start_shoot"
&& (response?.currentPlane?.id ?? 0) > 0
}
/// 提交一次开拍并单次读取同任务;失败保留原快照,不重建、不自动重发控制请求。
@MainActor
func startShooting(onStateChange: @escaping @MainActor () -> Void = {}) async {
recordTaskEvent("start.requested", fields: ["allowed": canStartShooting, "state": taskDiagnosticFields])
guard canStartShooting, let startService else { return }
guard context.hasSameIdentity(as: currentContext()) else {
identityInvalidated = true
invalidate()
onStateChange()
return
}
guard !Task.isCancelled else { return }
invalidatePendingRefresh()
let planeID = response?.currentPlane?.id
startGeneration &+= 1
let requestGeneration = startGeneration
isStartingShooting = true
didSendStart = false
startErrorMessage = nil
onStateChange()
defer {
if startGeneration == requestGeneration {
if Task.isCancelled && didSendStart && !hasSubmittedStart { markStartUnknown() }
isStartingShooting = false
didSendStart = false
onStateChange()
}
}
guard acceptsStart(requestGeneration) else { return }
do {
didSendStart = true
let value = try await startService.startShooting(taskID: taskID)
guard acceptsStart(requestGeneration) else { return }
guard value.orderFlightTaskID == taskID,
value.orderFlightTask?.id == nil || value.orderFlightTask?.id == taskID,
value.orderFlightTask?.orderNumber == nil || value.orderFlightTask?.orderNumber == order.orderNumber,
value.orderFlightTask?.scenicID == nil || value.orderFlightTask?.scenicID == context.scenicID,
value.planeID == nil || value.planeID == planeID else {
throw APIError.decodeFailed("开始拍摄回执与当前任务或飞机不一致,请先核对任务状态")
}
startResponse = value
recordTaskEvent("start.receipt_accepted", fields: ["receipt_task_id": DroneDockTaskTraceFields.value(value.orderFlightTaskID),
"receipt_plane_id": DroneDockTaskTraceFields.value(value.planeID)])
hasSubmittedStart = true
startOutcomeUnknown = false
onStateChange()
guard acceptsStart(requestGeneration) else { return }
await refreshSnapshot(allowWhileStarting: true)
} catch {
guard acceptsStart(requestGeneration) else { return }
if case APIError.serverCode = error {
startErrorMessage = error.localizedDescription
} else {
markStartUnknown(reason: error.localizedDescription)
}
}
}
/// 离页或进入后台后拒绝迟到回执;已发而未确认的请求保留待核对锁。
@MainActor
func invalidateStartShooting() {
if isStartingShooting && didSendStart && !hasSubmittedStart { markStartUnknown() }
startGeneration &+= 1
isStartingShooting = false
didSendStart = false
}
/// 设备执行态必须属于当前完整快照批次;空对象、未知枚举或缺少回巢依据保持未知。
var flightControlState: DroneDockFlightControlState {
response?.flightControl?.resolvedState(for: response?.executionBatch) ?? .unknown
}
/// 安全操作服从同批次的后端明确许可;遥测未知或拍摄结果不单独否决权限。
var availableSafetyCommands: [DroneDockSafetyCommand] {
guard hasControlSnapshotIdentity, let control = response?.flightControl else { return [] }
switch flightControlState {
case .starting:
return control.canReturnHome == true ? [.returnHome] : []
case .executing:
return [(DroneDockSafetyCommand.pause, control.canPause), (.returnHome, control.canReturnHome)]
.compactMap { $0.1 == true ? $0.0 : nil }
case .paused:
return [(DroneDockSafetyCommand.resume, control.canResume), (.returnHome, control.canReturnHome)]
.compactMap { $0.1 == true ? $0.0 : nil }
case .returning:
return control.canPause == true ? [.pause] : []
case .returned, .unknown:
return []
}
}
/// 本次按钮独立等待,包括重进页读取到的服务端 pending;未知结果不自动重发。
func isCommandLoading(_ command: DroneDockSafetyCommand) -> Bool {
commandOperations[command]?.isLoading == true || remotePendingCommand == command
}
/// 指令结果未知仅影响该动作的辅助提示和防重。
func isCommandOutcomeUnknown(_ command: DroneDockSafetyCommand) -> Bool {
commandOperations[command]?.phase == .unknown
}
/// 读取对应动作的错误,不让暂停失败污染返航按钮。
func commandErrorMessage(for command: DroneDockSafetyCommand) -> String? {
commandOperations[command]?.error
}
/// 已知飞行状态与逐项权限授权,不按业务失败/素材状态或另一按钮 loading 拦截。
func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool {
commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& readAccessError == nil && !isStartingShooting && !isResummoning
&& !resummonOutcomeUnknown && !awaitingResummonSnapshot
&& commandOperations[command]?.isWaiting != true && !isCommandLoading(command)
&& (response?.currentPlane?.id ?? 0) > 0
&& availableSafetyCommands.contains(command)
}
/// 每次点击立即进入对应按钮等待;只串行 HTTP 提交,不等待前一设备指令确认。
@MainActor
func sendCommand(_ command: DroneDockSafetyCommand,
onStateChange: @escaping @MainActor () -> Void = {}) async {
recordTaskEvent("command.requested", fields: ["command": command.rawValue,
"allowed": canSendCommand(command), "state": taskDiagnosticFields])
guard canSendCommand(command), let batch = response?.executionBatch,
let plane = response?.currentPlane else { return }
guard context.hasSameIdentity(as: currentContext()) else {
identityInvalidated = true
invalidate()
onStateChange()
return
}
guard !Task.isCancelled else { return }
commandSequence += 1
let operation = DroneDockCommandOperation(requestID: UUID().uuidString, command: command,
batch: batch, sequence: commandSequence, generation: commandGeneration,
submittedVersion: response?.stateVersion ?? 0, planeID: plane.id ?? 0,
airportSN: plane.snNumber, resumePhase: response?.flightControl?.resumePhase)
commandOperations[command] = operation
recordCommandEvent("command.queued", operation: operation)
let predecessor = commandTransportTail
let task = Task { @MainActor [weak self] in
await predecessor?.value
guard let self else { return }
await self.submitCommand(operation, onStateChange: onStateChange)
}
commandTransportTail = task
commandTasks[operation.requestID] = task
onStateChange()
await withTaskCancellationHandler {
await task.value
} onCancel: {
task.cancel()
}
commandTasks[operation.requestID] = nil
guard acceptsCommand(operation) else { return }
if commandOperations[command]?.commandID != nil {
await refreshSnapshot(allowWhileStarting: false, allowWhileCommand: true)
}
onStateChange()
}
/// 回执只处理对应请求的按钮进度;随后由统一快照更新业务阶段。
@MainActor
private func submitCommand(_ operation: DroneDockCommandOperation,
onStateChange: @escaping @MainActor () -> Void) async {
guard acceptsCommand(operation), let commandService else {
recordCommandEvent("command.queue_discarded", operation: operation,
fields: ["reason": "cancelled_or_task_context_changed"])
if commandOperations[operation.command]?.requestID == operation.requestID,
commandOperations[operation.command]?.phase == .queued { commandOperations[operation.command] = nil }
onStateChange()
return
}
guard readAccessError == nil, !isStartingShooting, !isResummoning,
response?.currentPlane?.id == operation.planeID,
response?.currentPlane?.snNumber == operation.airportSN,
availableSafetyCommands.contains(operation.command) else {
commandOperations[operation.command]?.phase = .finished
commandOperations[operation.command]?.error = "设备状态或操作权限已变化,本次指令未发送"
recordCommandEvent("command.queue_discarded", operation: operation,
fields: ["reason": "latest_permission_or_plane_changed", "state": taskDiagnosticFields])
onStateChange()
return
}
invalidatePendingRefresh()
commandOperations[operation.command]?.phase = .sending
recordCommandEvent("command.sending", operation: operation)
onStateChange()
defer { onStateChange() }
do {
let value = try await commandService.sendCommand(taskID: taskID, command: operation.command,
clientRequestID: operation.requestID)
try Task.checkCancellation()
guard acceptsCommand(operation) else {
recordCommandEvent("command.receipt_ignored", operation: operation,
fields: ["reason": "stale_task_context", "receipt_batch": DroneDockTaskTraceFields.value(value.executionBatch),
"receipt_command_id": DroneDockTaskTraceFields.value(value.commandID)])
return
}
recordCommandEvent("command.receipt_received", operation: operation, fields: [
"receipt_task_id": DroneDockTaskTraceFields.value(value.orderFlightTaskID),
"receipt_batch": DroneDockTaskTraceFields.value(value.executionBatch),
"receipt_version": DroneDockTaskTraceFields.value(value.stateVersion),
"receipt_command": DroneDockTaskTraceFields.value(value.command),
"receipt_command_id": DroneDockTaskTraceFields.value(value.commandID),
"receipt_client_request_id": DroneDockTaskTraceFields.value(value.clientRequestID),
"accepted": DroneDockTaskTraceFields.value(value.accepted),
"device_confirmed": DroneDockTaskTraceFields.value(value.deviceConfirmed),
"pending_command": DroneDockTaskTraceFields.progress(value.pendingCommand)])
guard value.orderFlightTaskID == taskID, value.command == operation.command.rawValue,
value.executionBatch == operation.batch,
value.clientRequestID == nil || value.clientRequestID == operation.requestID,
value.flightControl == nil || value.flightControl?.executionBatch == operation.batch,
value.planeID == nil || value.planeID == operation.planeID,
value.airportSN == nil || value.airportSN == operation.airportSN,
value.stateVersion == nil || value.stateVersion! >= operation.submittedVersion else {
throw APIError.decodeFailed("安全指令回执与当前任务、批次、设备或请求不一致,请核对状态")
}
if value.accepted == false { throw APIError.serverCode(100099, "指令未受理,请核对任务状态后重试") }
guard value.accepted == true, let commandID = usable(value.commandID) else {
throw APIError.decodeFailed("指令回执缺少明确受理结果或 command_id,请核对状态")
}
commandResponse = value
if let version = value.stateVersion {
minimumCommandSnapshotVersion = max(minimumCommandSnapshotVersion ?? 0, version)
}
// HTTP 严格按点击顺序提交;后受理的本地请求按合同取代之前的等待意图。
for (command, old) in commandOperations where old.sequence < operation.sequence && old.isWaiting {
if let id = old.commandID { supersededCommandIDs.insert(id) }
commandOperations[command]?.phase = .finished
commandOperations[command]?.error = nil
recordCommandEvent("command.superseded", operation: old,
fields: ["superseded_by_client_request_id": operation.requestID,
"superseded_by_command_id": commandID])
}
if let old = response?.flightControl?.pendingCommand, let id = old.commandID,
id != commandID { supersededCommandIDs.insert(id) }
commandOperations[operation.command]?.commandID = commandID
commandOperations[operation.command]?.minimumVersion = value.stateVersion
commandOperations[operation.command]?.phase = .pending
commandOperations[operation.command]?.error = nil
if let progress = value.pendingCommand {
guard progressMatches(progress, operation: commandOperations[operation.command]!) else {
throw APIError.decodeFailed("指令进度与本次请求不一致,请核对状态")
}
applyCommandProgress(progress, command: operation.command)
} else if value.deviceConfirmed == true {
commandOperations[operation.command]?.phase = .confirmed
supersededCommandIDs.insert(commandID)
}
reconcilePendingCommand()
recordCommandEvent("command.receipt_applied", operation: operation)
} catch {
guard acceptsCommand(operation, allowingCancellation: true) else {
recordCommandEvent("command.error_ignored", operation: operation,
fields: ["reason": "stale_task_context", "error": DroneDockDiagnostics.errorFields(error)])
return
}
if case APIError.serverCode = error {
commandOperations[operation.command]?.phase = .finished
commandOperations[operation.command]?.error = error.localizedDescription
} else {
commandOperations[operation.command]?.phase = .unknown
commandOperations[operation.command]?.error = "安全指令结果待核对,请刷新任务状态,勿重复提交"
}
recordCommandEvent("command.failed_or_unknown", operation: operation,
fields: ["error": DroneDockDiagnostics.errorFields(error)])
}
}
/// 离页取消在途请求;已发送的结果保持待核对,回前台仅通过快照核对。
@MainActor
func invalidateCommand() {
recordTaskEvent("command.lifecycle_cancelled", fields: ["operation_count": commandOperations.count,
"transport_count": commandTasks.count])
commandGeneration &+= 1
for task in commandTasks.values { task.cancel() }
commandTasks.removeAll()
commandTransportTail = nil
for (command, operation) in commandOperations {
switch operation.phase {
case .queued: commandOperations[command] = nil
case .sending:
commandOperations[command]?.phase = .unknown
commandOperations[command]?.error = "安全指令结果待核对,请刷新任务状态,勿重复提交"
default: break
}
}
}
/// 任务失败或中断回巢后,设备空闲且后端明确允许,无在途或未知操作时才可重召唤。
var canResummon: Bool {
resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& hasControlSnapshotIdentity
&& !isTaskAwaitingConfirmation
&& readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown
&& !hasSubmittedResummon && pendingCommand == nil
&& !commandOperations.values.contains(where: { $0.isWaiting })
&& [.failed, .returned].contains(resolvedDisplayPhase().0)
&& response?.restartGate?.canRestart == true
&& flightControlState == .returned
&& response?.currentPlane?.workStatus == 1
&& (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID)
&& (response?.currentPlane?.id ?? 0) > 0
&& !isResummonDeviceUnavailable
}
/// 复用同一任务提交一次 restart=true;受理后只查询一次 shooting,不推断已经到达。
@MainActor
func resummon(onStateChange: @escaping @MainActor () -> Void = {}) async {
recordTaskEvent("resummon.requested", fields: ["allowed": canResummon, "state": taskDiagnosticFields])
guard canResummon, let resummonService else { return }
guard context.hasSameIdentity(as: currentContext()) else {
identityInvalidated = true
invalidate()
onStateChange()
return
}
guard !Task.isCancelled else { return }
invalidatePendingRefresh()
resummonGeneration &+= 1
let requestGeneration = resummonGeneration
isResummoning = true
didSendResummon = false
resummonResponse = nil
resummonErrorMessage = nil
onStateChange()
defer {
if resummonGeneration == requestGeneration {
if Task.isCancelled && didSendResummon && !hasSubmittedResummon { markResummonUnknown() }
isResummoning = false
didSendResummon = false
onStateChange()
}
}
guard acceptsResummon(requestGeneration) else { return }
do {
didSendResummon = true
let value = try await resummonService.resummon(taskID: taskID)
guard acceptsResummon(requestGeneration) else { return }
guard try matchesResummonReceipt(value) else {
throw APIError.decodeFailed("重新召唤回执与当前任务或订单不一致,请先核对任务状态")
}
resummonResponse = value
recordTaskEvent("resummon.receipt_accepted", fields: ["receipt": DroneDockTaskTraceFields.summon(value)])
hasSubmittedResummon = true
resummonOutcomeUnknown = false
awaitingResummonSnapshot = true
hasSubmittedStart = false
startResponse = nil
startErrorMessage = nil
commandResponse = nil
onStateChange()
guard acceptsResummon(requestGeneration) else { return }
await refreshSnapshot(allowWhileStarting: false, allowWhileResummoning: true)
} catch {
guard acceptsResummon(requestGeneration) else { return }
if case APIError.serverCode = error {
didSendResummon = false
resummonErrorMessage = error.localizedDescription
} else {
markResummonUnknown(reason: error.localizedDescription)
}
}
}
/// 离页或进入后台后忽略旧回执;发出后未确认的重新召唤继续保持待核对锁。
@MainActor
func invalidateResummon() {
if isResummoning && didSendResummon && !hasSubmittedResummon { markResummonUnknown() }
resummonGeneration &+= 1
isResummoning = false
didSendResummon = false
}
/// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。
var title: String {
if let title = usable(response?.header?.title) { return title }
let names = [usable(response?.scenicSpot?.name), usable(response?.airLine?.name)].compactMap { $0 }
return names.isEmpty ? "拍摄任务" : names.joined(separator: " · ")
}
/// 服务端游客和套餐文案优先,后端已返回的套餐不被进入页摘要覆盖。
var subtitle: String {
let tourist = usable(response?.header?.touristLabel) ?? usable(order.touristPhoneMask)
let package = usable(response?.header?.packageName) ?? usable(order.packageName)
let parts = [tourist, package].compactMap { $0 }
return parts.isEmpty ? "—" : parts.joined(separator: " · ")
}
/// 只展示本任务当前设备状态,不以景区推荐设备替代任务锁定设备。
var deviceStatusText: String {
usable(response?.currentPlane?.statusText) ?? usable(response?.currentPlane?.workStatusLabel) ?? "—"
}
/// 录制完成与素材就绪分别保留;只由可信阶段触发完成提示,不修改后端任务状态。
var isRecordingFinished: Bool {
guard !isInterruptedReturn else { return false }
let phase = resolvedBusinessPhase().0
let tasks = [response?.task, response?.orderFlightTask].compactMap { $0 }
let statuses = tasks.compactMap(\.status)
let completedWhilePaused = response?.flightControl?.returnReason == "normal_complete"
&& !statuses.contains(where: { [40, 50, 60].contains($0) })
&& statuses.contains(where: { [25, 30].contains($0) })
&& tasks.contains(where: { [24, 30, 40, 50].contains($0.waylineStatus ?? -1) })
return [.postShootUploading, .postShootUploadFailed, .completed].contains(phase)
|| (phase == .failed && hasMediaProcessingFailure)
|| completedWhilePaused
}
/// 已正常拍完或中断后确认回巢均停止本机接收;回巢不触发拍摄成功提示。
var shouldStopLiveReception: Bool {
isRecordingFinished || resolvedDevicePhase().0 == .returned
}
/// 只有录制正常结束或素材就绪才弹出完成提示,素材处理失败只展示失败状态。
var shouldPresentRecordingCompletion: Bool {
[.postShootUploading, .completed].contains(resolvedDisplayPhase().0)
}
/// 正常拍完后的返航说明仅取本批次可信完成阶段,上传/渲染或显式清标记后不沿用。
var isShootCompleteReturning: Bool {
guard resolvedDisplayPhase().0 == .postShootUploading else { return false }
let waylines = [response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus].compactMap { $0 }
guard !waylines.contains(where: { [30, 40, 50].contains($0) }) else { return false }
let flags = [response?.shootCompleteReturning, response?.ui?.shootCompleteReturning].compactMap { $0 }
if flags.contains(false) { return false }
if let control = response?.flightControl {
return flightControlState == .returning && control.returnReason == "normal_complete"
}
if flags.contains(true) || response?.ui?.waylineStage == "shoot_done_returning" { return true }
// 旧回包仍保留明确的设备返航文案;新合同不再依赖只有忙闲的 work_status。
guard response?.ui?.waylineStage == nil else { return false }
return ["返航中", "正在返航"].contains(usable(response?.currentPlane?.workStatusLabel) ?? "")
}
/// 完成提示按当前任务的执行批次去重,旧快照仍由统一版本校验拒绝。
var recordingExecutionID: String {
"\(taskID):\(response?.executionBatch ?? 0)"
}
/// App 首次确认本批次到达后显示 30 秒本地倒计时;到零仍等待后端阶段,不触发控制或状态读取。
var countdownRemainingSeconds: Int? {
guard !identityInvalidated, readAccessError == nil, resolvedDisplayPhase().0 == .ready,
let deadline = arrivalCountdownDeadlines[recordingExecutionID] else { return nil }
let remaining = countdownNow().duration(to: deadline)
guard remaining > .zero else { return 0 }
let parts = remaining.components
return Int(min(30, parts.seconds + (parts.attoseconds > 0 ? 1 : 0)))
}
/// 页面标题由本地显示阶段决定,服务端文案只保留在诊断数据中。
var statusTitle: String {
if response == nil {
if errorMessage != nil { return "任务状态读取失败" }
if hasInitialTravelReceipt { return "无人机正在赶来" }
if isLoading { return "正在获取任务状态" }
}
let (phase, conflict) = resolvedDisplayPhase()
return presentationTitle(for: phase, conflict: conflict)
}
/// 拍摄阶段使用产品提示,其余保留服务端说明;操作结果未知时优先提示核对。
var statusMessage: String {
if response == nil {
if let errorMessage { return errorMessage }
if hasInitialTravelReceipt { return "召唤已受理,正在等待设备到达确认,请留在拍摄点。" }
if isLoading { return "正在读取当前拍摄任务" }
}
if let resummonErrorMessage { return resummonErrorMessage }
if awaitingResummonSnapshot { return "重新召唤请求已受理,请刷新核对任务状态" }
switch resolvedDisplayPhase().0 {
case .paused:
return response?.flightControl?.resumePhase == "returning"
? "当前悬停待命。\n确认安全后,继续任务将恢复返航。"
: "当前悬停待命。\n确认安全后,可继续任务或立即返航。"
case .returning: return "本次拍摄已中断。请留意实时画面与无人机状态。"
case .returned: return "无人机已返回机巢,可在满足条件后重新召唤。"
case .unknown where isInterruptedReturn: return "暂无法确认无人机是否已返回机巢,请等待设备状态更新。"
default: break
}
if resolvedDisplayPhase().0 == .failed { return failureMessage }
if resolvedDisplayPhase().0 == .postShootUploadFailed { return mediaFailureMessage }
if isTaskAwaitingConfirmation { return usable(response?.ui?.message) ?? "任务结果待确认,请刷新核对状态。" }
if startOutcomeUnknown, let startErrorMessage { return startErrorMessage }
if resolvedDisplayPhase().0 == .ready {
if let startErrorMessage { return startErrorMessage }
if hasSubmittedStart { return "开始拍摄请求已受理,请刷新确认任务状态" }
if response?.executeGate?.canExecute != true, let message = usable(response?.executeGate?.message) {
return message
}
}
if resolvedDisplayPhase().0 == .postShootUploading {
let waylines = [response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus]
let note: String
if isShootCompleteReturning { note = "无人机正在返航,请留意现场。" }
else if waylines.contains(30) { note = "素材上传中,可在素材库查看进度。" }
else if waylines.contains(40) { note = "素材渲染中,可在素材库查看进度。" }
else { note = "素材处理中,可在素材库查看进度。" }
return "本次拍摄已结束,可前往查看素材。\n" + note
}
if resolvedDisplayPhase().0 == .shooting { return "请关注现场及实时画面。\n请勿关闭本页或息屏。" }
switch resolvedDisplayPhase().0 {
case .navigating: return "请留在拍摄点,等待无人机到达。"
case .ready: return "确认游客站位与取景后开始"
case .completed: return "素材已就绪,可前往素材库查看。"
case .unknown: return "暂无法确认任务状态,请刷新后重试。"
default: return usable(response?.executeGate?.message) ?? "请等待任务状态更新。"
}
}
/// 组合可信阶段与本轮可用动作,不从请求成功、执行中或指令列表推断飞行进度。
var presentation: DroneDockTaskPresentation {
if response == nil, hasInitialTravelReceipt, errorMessage == nil, !identityInvalidated {
return DroneDockTaskPresentation(phase: .navigating, title: statusTitle, message: statusMessage,
deviceStatus: deviceStatusText, action: .none, actionTitle: nil, isActionEnabled: false)
}
if response == nil, isLoading {
return DroneDockTaskPresentation(phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: deviceStatusText, action: .none, actionTitle: nil, isActionEnabled: false)
}
if response == nil, let errorMessage {
return DroneDockTaskPresentation(phase: .readError, title: "任务状态读取失败", message: errorMessage,
deviceStatus: deviceStatusText, action: .refresh, actionTitle: "重新读取", isActionEnabled: !identityInvalidated && readAccessError == nil)
}
let (phase, conflict) = resolvedDisplayPhase()
let message = conflict ? "任务状态信息不一致,请刷新后确认。" + (statusMessage == "—" ? "" : statusMessage) : statusMessage
let title = presentationTitle(for: phase, conflict: conflict)
let action: DroneDockTaskDisplayAction
let actionTitle: String?
let enabled: Bool
switch phase {
case .shooting:
action = .none
actionTitle = "拍摄中"
enabled = false
case .ready where hasSubmittedStart || startOutcomeUnknown || commandOutcomeUnknown || resummonOutcomeUnknown:
action = .refresh
actionTitle = "刷新状态"
enabled = !identityInvalidated
case .ready:
action = .start
actionTitle = isStartingShooting ? "正在提交开拍…"
: startErrorMessage == nil ? "开始拍摄" : "重试开始拍摄"
enabled = canStartShooting
case .paused:
action = .resume
actionTitle = "继续任务"
enabled = canSendCommand(.resume)
case .returning:
action = .none
actionTitle = "拍摄已中断"
enabled = false
case .completed, .postShootUploading, .postShootUploadFailed:
action = .materials
actionTitle = "查看素材"
enabled = true
case .failed where hasSubmittedResummon || resummonOutcomeUnknown,
.returned where hasSubmittedResummon || resummonOutcomeUnknown:
action = .refresh
actionTitle = "刷新状态"
enabled = !identityInvalidated
case .failed, .returned:
action = .retry
actionTitle = isResummoning ? "正在重新召唤…" : "重新召唤无人机"
enabled = canResummon
default:
action = .refresh
actionTitle = "刷新状态"
enabled = !identityInvalidated
}
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
isActionEnabled: enabled && readAccessError == nil && !isStartingShooting && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
actionNote: [.failed, .returned].contains(phase) && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil,
countdownSeconds: countdownRemainingSeconds)
}
/// 后端六项展示读数,不解析文案反推设备状态或数值单位。
var telemetry: DroneDockShootingTelemetry {
func text(_ key: String) -> String { response == nil ? "—" : retainedMetrics[key]?.displayText ?? "—" }
return DroneDockShootingTelemetry(batteryText: text("battery"), temperatureText: text("env_temp"),
windText: text("wind_speed"), rainText: text("rainfall"), signalText: text("signal"), satelliteText: text("satellite"))
}
/// 无快照或后端标记缓存过期时使用非实时样式;已有读数仍保留展示。
var isTelemetryStale: Bool { response == nil || response?.metricsStale == true || isUsingRetainedMetrics }
/// 完整服务端 data,供页面展示和联调查看。
var dataJSON: String? { response?.dataJSON }
@MainActor
private func accepts(_ requestGeneration: Int) -> Bool {
guard generation == requestGeneration else { return false }
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
identityInvalidated = true
invalidate()
errorMessage = "账号或景区已变化,请返回工作台重新进入"
return false
}
return !Task.isCancelled
}
@MainActor
private func acceptsStart(_ requestGeneration: Int) -> Bool {
guard startGeneration == requestGeneration else { return false }
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
identityInvalidated = true
invalidate()
return false
}
return !Task.isCancelled
}
@MainActor
private func acceptsCommand(_ operation: DroneDockCommandOperation, allowingCancellation: Bool = false) -> Bool {
guard commandGeneration == operation.generation, response?.executionBatch == operation.batch,
commandOperations[operation.command]?.requestID == operation.requestID else { return false }
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
identityInvalidated = true
invalidate()
return false
}
return allowingCancellation || !Task.isCancelled
}
@MainActor
private func acceptsResummon(_ requestGeneration: Int) -> Bool {
guard resummonGeneration == requestGeneration else { return false }
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
identityInvalidated = true
invalidate()
return false
}
return !Task.isCancelled
}
private func markResummonUnknown(reason: String? = nil) {
resummonOutcomeUnknown = true
resummonErrorMessage = (reason.map { "\($0)。" } ?? "") + "重新召唤结果待核对,请刷新任务状态,勿重复提交"
recordTaskEvent("resummon.outcome_unknown")
}
/// shoot 顶层 task_id 是实际航线任务 ID;只核对明确的订单任务身份,不混淆两种任务。
private func matchesResummonReceipt(_ value: DroneDockShootResponse) throws -> Bool {
guard let json = value.dataJSON else { return true }
let data = Data(json.utf8)
guard case .object = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: data) else { return true }
let identity = try JSONDecoder().decode(DroneDockResummonReceiptIdentity.self, from: data)
return (identity.orderFlightTaskID == nil || identity.orderFlightTaskID == taskID)
&& (identity.orderFlightTask?.id == nil || identity.orderFlightTask?.id == taskID)
&& (identity.orderFlightTask?.orderNumber == nil || identity.orderFlightTask?.orderNumber == order.orderNumber)
&& (identity.orderFlightTask?.scenicID == nil || identity.orderFlightTask?.scenicID == context.scenicID)
&& (identity.planeID == nil || identity.planeID == response?.currentPlane?.id)
}
private func markStartUnknown(reason: String? = nil) {
startOutcomeUnknown = true
startErrorMessage = (reason.map { "\($0)。" } ?? "") + "开始拍摄结果待核对,请刷新任务状态,勿重复提交"
recordTaskEvent("start.outcome_unknown")
}
private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool {
let taskIDs = [value.orderFlightTaskID, value.orderFlightTask?.id, value.task?.id].compactMap { $0 }
let orderNumbers = [value.orderNumber, value.orderFlightTask?.orderNumber,
value.task?.orderNumber, value.header?.orderNumber].compactMap { $0 }
let scenicIDs = [value.scenic?.id, value.orderFlightTask?.scenicID,
value.task?.scenicID, value.planeStatus?.scenicID].compactMap { $0 }
return taskIDs.allSatisfy { $0 == taskID }
&& orderNumbers.allSatisfy { $0 == order.orderNumber }
&& scenicIDs.allSatisfy { $0 == context.scenicID }
}
/// 手动或保护返航独立于拍摄结果,不能被普通失败摘要隐藏,也不升级为成功。
private var isInterruptedReturn: Bool {
["manual", "abnormal"].contains(response?.flightControl?.returnReason ?? "")
|| response?.orderFlightTask?.resultCode == "return_home"
|| response?.task?.resultCode == "return_home"
|| response?.ui?.phase == "returning_home"
}
/// 缺任务身份、版本或未知任务枚举的快照可只读展示,不能作为控制指令的授权依据。
private var hasControlSnapshotIdentity: Bool {
guard let response, (response.stateVersion ?? 0) > 0, (response.executionBatch ?? 0) > 0,
response.orderFlightTaskID == taskID || response.orderFlightTask?.id == taskID || response.task?.id == taskID else { return false }
return matchesIdentity(response)
}
/// 开拍仍要求已知任务业务态;紧急控制只依赖有效设备身份和逐项飞控许可。
private var hasKnownShootingTaskState: Bool {
let statuses = [response?.task?.status, response?.orderFlightTask?.status].compactMap { $0 }
return !statuses.isEmpty && statuses.allSatisfy { [10, 20, 25, 30, 40, 50, 60].contains($0) }
}
private func resolvedDisplayPhase() -> (DroneDockTaskDisplayPhase, Bool) { resolvedDevicePhase() }
/// 先校验业务冲突,再用同批次设备状态覆盖暂停和中断返航;正常录制完成单独保留。
private func resolvedDevicePhase() -> (DroneDockTaskDisplayPhase, Bool) {
let business = resolvedBusinessPhase()
guard let response else { return business }
let tasks = [response.task, response.orderFlightTask].compactMap { $0 }
let statuses = Set(tasks.compactMap(\.status))
if statuses.contains(50) || statuses.contains(60) || tasks.contains(where: { $0.waylineStatus == 90 }) {
return (.blocked, false)
}
guard let control = response.flightControl else {
return isInterruptedReturn ? (.unknown, false) : business
}
if statuses.count > 1 { return (.unknown, true) }
if isInterruptedReturn && control.returnReason == "normal_complete" { return (.unknown, true) }
let recorded = [.postShootUploading, .postShootUploadFailed, .completed].contains(business.0)
&& !isInterruptedReturn && !business.1
switch flightControlState {
case .starting:
return business.0 == .navigating && !business.1 ? business : (.unknown, true)
case .unknown:
// 飞控暂缺不抹掉已明确的业务进度,操作许可仍需单独的可信飞控数据。
return recorded || [.navigating, .ready, .shooting].contains(business.0) ? business : (.unknown, false)
case .returned:
if isInterruptedReturn {
guard !statuses.contains(30), !statuses.contains(25) else { return (.unknown, true) }
return (.returned, false)
}
if recorded || business.0 == .failed { return business }
return (.unknown, true)
case .returning:
if isInterruptedReturn {
guard !statuses.contains(30), !statuses.contains(25) else { return (.unknown, true) }
return (.returning, false)
}
if recorded && control.returnReason == "normal_complete" { return business }
return (.unknown, true)
case .paused:
guard ["going_to_spot", "arrived_pending_start", "shooting", "returning"].contains(control.resumePhase ?? "") else {
return (.unknown, false)
}
if isInterruptedReturn {
guard control.resumePhase == "returning", !statuses.contains(30), !statuses.contains(25) else {
return (.unknown, true)
}
return (.paused, false)
}
if isRecordingFinished && control.returnReason == "normal_complete" && control.resumePhase == "returning" {
return (.paused, false)
}
guard !business.1, [.navigating, .ready, .shooting, .paused, .blocked, .failed].contains(business.0) else { return business }
return (.paused, false)
case .executing:
if isInterruptedReturn { return (.unknown, true) }
// 执行态不是到达证据,正常业务进度仍由 ui.phase 和开拍门禁共同决定。
return business
}
}
/// 重进页也展示服务端当前指令的等待,仅识别已知且有唯一标识的动作。
private var remotePendingCommand: DroneDockSafetyCommand? {
guard let control = response?.flightControl, control.executionBatch == response?.executionBatch,
let progress = control.pendingCommand, progress.status == "pending",
let id = usable(progress.commandID), !supersededCommandIDs.contains(id),
let command = progress.command.flatMap(DroneDockSafetyCommand.init(rawValue:)) else { return nil }
return command
}
private func progressMatches(_ progress: DroneDockCommandProgress, operation: DroneDockCommandOperation) -> Bool {
guard progress.command == operation.command.rawValue,
progress.clientRequestID == nil || progress.clientRequestID == operation.requestID,
progress.commandID == nil || operation.commandID == nil || progress.commandID == operation.commandID else { return false }
return progress.clientRequestID == operation.requestID || (operation.commandID != nil && progress.commandID == operation.commandID)
}
private func applyCommandProgress(_ progress: DroneDockCommandProgress, command: DroneDockSafetyCommand) {
let previousPhase = commandOperations[command]?.phase
defer {
if let operation = commandOperations[command], previousPhase != operation.phase {
recordCommandEvent("command.progress_changed", operation: operation,
fields: ["previous_phase": previousPhase.map { String(describing: $0) } ?? "none",
"server_progress": DroneDockTaskTraceFields.progress(progress)])
}
}
switch progress.status {
case "pending":
if commandOperations[command]?.phase != .confirmed { commandOperations[command]?.phase = .pending }
case "succeeded":
if let id = progress.commandID { supersededCommandIDs.insert(id) }
commandOperations[command]?.phase = .confirmed
commandOperations[command]?.error = nil
case "superseded":
if let id = progress.commandID { supersededCommandIDs.insert(id) }
commandOperations[command]?.phase = .finished
commandOperations[command]?.error = nil
case "failed":
if let id = progress.commandID { supersededCommandIDs.insert(id) }
commandOperations[command]?.phase = .finished
commandOperations[command]?.error = usable(progress.message) ?? "安全指令执行失败,请核对设备状态"
default: break
}
}
/// 匹配本次 command_id/幂等键的进度优先;无进度样例仅由更新的明确设备状态核对。
private func reconcilePendingCommand() {
guard let response, let batch = response.executionBatch, let version = response.stateVersion else { return }
for (command, operation) in commandOperations where operation.batch == batch && operation.isWaiting {
if let progress = response.flightControl?.pendingCommand, progressMatches(progress, operation: operation) {
commandOperations[command]?.commandID = progress.commandID ?? operation.commandID
applyCommandProgress(progress, command: command)
if commandOperations[command]?.phase != .confirmed { continue }
}
guard version > operation.submittedVersion, version >= (operation.minimumVersion ?? 0),
commandOperations[command]?.commandID != nil,
response.flightControl?.pendingCommand == nil || commandOperations[command]?.phase == .confirmed else { continue }
let confirmed: Bool
switch command {
case .pause: confirmed = flightControlState == .paused
case .resume:
confirmed = operation.resumePhase == "returning" ? flightControlState == .returning
: flightControlState == .executing && response.ui?.phase == operation.resumePhase
case .returnHome: confirmed = flightControlState == .returned
case .cancelReturn: confirmed = false
}
if confirmed || flightControlState == .returned {
commandOperations[command]?.phase = .finished
recordCommandEvent("command.snapshot_confirmed", operation: operation,
fields: ["confirmed_flight_state": flightControlState.rawValue,
"confirmed_ui_phase": DroneDockTaskTraceFields.value(response.ui?.phase)])
}
}
}
/// 指令日志同时记录提交时与当前批次,便于识别旧回执、被替代动作和按钮等待原因。
private func recordCommandEvent(_ event: String, operation: DroneDockCommandOperation,
fields: [String: Any] = [:]) {
let current = commandOperations[operation.command]
let summary: [String: Any] = ["command": operation.command.rawValue,
"client_request_id": operation.requestID, "command_id": DroneDockTaskTraceFields.value(current?.commandID ?? operation.commandID),
"submitted_batch": operation.batch, "submitted_version": operation.submittedVersion,
"command_sequence": operation.sequence, "submitted_plane_id": operation.planeID,
"submitted_airport_sn": DroneDockTaskTraceFields.value(operation.airportSN),
"operation_phase": current.map { String(describing: $0.phase) } ?? "discarded",
"button_loading": isCommandLoading(operation.command),
"button_allowed": canSendCommand(operation.command),
"command_error": DroneDockTaskTraceFields.value(current?.error)]
recordTaskEvent(event, fields: summary.merging(fields) { _, new in new })
}
private func clearPendingCommand() {
commandOperations.removeAll()
supersededCommandIDs.removeAll()
}
/// 按任务终态、明确 UI 阶段与航线失败判断,不把机巢忙闲或订单执行中当作拍摄进度。
private func resolvedBusinessPhase() -> (DroneDockTaskDisplayPhase, Bool) {
guard let response else { return (.unknown, false) }
let tasks = [response.task, response.orderFlightTask].compactMap { $0 }
let statuses = Set(tasks.compactMap(\.status))
let waylines = Set(tasks.compactMap(\.waylineStatus))
let rawPhase = usable(response.ui?.phase)
if statuses.contains(50) || waylines.contains(90) || statuses.contains(60) { return (.blocked, false) }
if tasks.contains(where: { $0.resultCode == "return_home" }) { return (.failed, false) }
if !waylines.isDisjoint(with: [29, 39, 49, 91]) || statuses.contains(40) {
let isMediaFailure = rawPhase == "post_shoot_upload_failed"
|| (hasMediaProcessingFailure && rawPhase != "failed_restartable")
return (isMediaFailure ? .postShootUploadFailed : .failed, false)
}
if statuses.count > 1 { return (.unknown, true) }
let known: [String: DroneDockTaskDisplayPhase] = [
"going_to_spot": .navigating, "failed_restartable": .failed, "waiting_summon": .blocked,
"navigating": .navigating, "arrived_pending_start": .ready, "shooting": .shooting,
"post_shoot_uploading": .postShootUploading,
"post_shoot_upload_failed": .postShootUploadFailed,
"manual_paused": .paused, "returning_home": .returning, "completed": .completed, "failed": .failed, "blocked": .blocked
]
let phase = rawPhase.flatMap { known[$0] }
if rawPhase != nil && phase == nil { return (.unknown, false) }
if phase == .failed { return (.failed, false) }
if statuses.contains(30) {
if phase == .returning { return (.returning, false) }
if let phase, [.navigating, .ready, .shooting, .postShootUploading, .postShootUploadFailed, .paused].contains(phase) { return (.unknown, true) }
return (.completed, false)
}
if phase == .completed {
return statuses.isEmpty ? (.completed, false) : (.unknown, true)
}
if phase == .ready, response.executeGate?.canExecute == true {
if let action = usable(response.executeGate?.primaryAction), action != "start_shoot" {
return (.unknown, true)
}
}
return (phase ?? .unknown, false)
}
private func presentationTitle(for phase: DroneDockTaskDisplayPhase, conflict: Bool) -> String {
if conflict { return "状态待确认" }
switch phase {
case .loading: return "正在获取任务状态"
case .readError: return "任务状态读取失败"
case .navigating: return "无人机正在赶来"
case .ready: return "无人机已到达"
case .shooting: return "无人机正在拍摄中"
case .postShootUploading, .completed: return "拍摄已完成"
case .postShootUploadFailed: return mediaFailureTitle
case .paused: return "无人机已暂停"
case .returning: return "无人机正在返航"
case .returned: return "本次拍摄已中断"
case .failed: return "任务执行失败"
case .blocked:
if isTaskAwaitingConfirmation { return "任务待确认" }
let tasks = [response?.task, response?.orderFlightTask].compactMap { $0 }
if tasks.contains(where: { $0.status == 50 || $0.waylineStatus == 90 }) { return "任务已取消" }
if response?.ui?.phase == "arrived_pending_start" { return "暂不可开始拍摄" }
return "当前任务暂不可执行"
case .unknown: return "状态待确认"
}
}
private func usable(_ value: String?) -> String? { DroneDockHomeMetric.usableText(value) }
/// 明确失败后优先展示任务结果原因,再保留执行门禁的实际限制,不用通用阶段标题充当原因。
private var failureMessage: String {
usable(response?.orderFlightTask?.resultMessage) ?? usable(response?.task?.resultMessage)
?? usable(response?.executeGate?.message) ?? usable(response?.ui?.message) ?? "暂未返回具体失败原因"
}
/// 39/49 表示录制后的素材处理失败,不能据此生成起飞或重召唤许可。
private var hasMediaProcessingFailure: Bool {
[response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus]
.compactMap { $0 }.contains { [39, 49].contains($0) }
}
private var isTaskAwaitingConfirmation: Bool {
response?.orderFlightTask?.status == 60 || response?.task?.status == 60
}
private var mediaFailureTitle: String {
return [response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus].contains(49)
? "素材渲染失败" : "素材上传失败"
}
private var mediaFailureMessage: String {
usable(response?.orderFlightTask?.resultMessage) ?? usable(response?.task?.resultMessage)
?? usable(response?.ui?.message) ?? usable(response?.task?.waylineStatusLabel)
?? usable(response?.orderFlightTask?.waylineStatusLabel) ?? "素材处理失败,请前往素材库查看。"
}
/// 工作态优先;工作态缺失或未识别时才用飞机表在线标记保守兜底。
private var isResummonDeviceOffline: Bool {
switch response?.currentPlane?.workStatus {
case 0: return true
case 1, 2: return false
default:
if let online = response?.currentPlane?.onlineStatus { return online != 1 }
return usable(response?.currentPlane?.workStatusLabel) == "离线"
}
}
/// 设备断连、离线或忙碌时禁用重召唤,不从显示文案推导设备可用性。
private var isResummonDeviceUnavailable: Bool {
let plane = response?.currentPlane
return response?.planeStatus?.connected == false || isResummonDeviceOffline || plane?.workStatus == 2
}
/// 正式入口未注入操作服务时说明当前限制;模拟页保留实际设备不可用原因。
private var retryUnavailableNote: String {
let plane = response?.currentPlane
if isResummonDeviceOffline {
return "无人机离线,暂不可召唤"
}
if plane?.workStatus == 2 { return "无人机忙碌,暂不可召唤" }
if let status = usable(plane?.workStatusLabel), ["返航中", "正在返航"].contains(status) {
return "无人机返航中,暂不可召唤"
}
if flightControlState != .returned { return "等待设备确认已返回机巢后再重新召唤" }
return usable(response?.restartGate?.message) ?? "暂不可重新召唤,请返回准备页确认设备状态"
}
}
/// 任务页六项读数的后端展示文本,保持服务端单位与零值。
struct DroneDockShootingTelemetry: Equatable, Sendable {
/// 电量读数。
let batteryText: String
/// 环境温度读数。
let temperatureText: String
/// 风速读数。
let windText: String
/// 雨量读数。
let rainText: String
/// 信号状态。
let signalText: String
/// 搜星状态。
let satelliteText: String
}