feat: 接入拍摄任务实时订阅并完善日志与封面

This commit is contained in:
2026-11-03 09:06:38 +08:00
parent 687088326c
commit 980d16da9b
27 changed files with 1790 additions and 64 deletions
@@ -50,6 +50,9 @@ final class DroneDockShootingTaskViewModel {
private let commandService: (any DroneDockCommandSending)?
private let resummonService: (any DroneDockResummonServing)?
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
/// 无权限或登录失效后停止自动读取,旧数据仅用于展示。
private(set) var readAccessError: String?
private var snapshotRevision = 0
private var generation = 0
private var identityInvalidated = false
private var startGeneration = 0
@@ -93,17 +96,18 @@ final class DroneDockShootingTaskViewModel {
/// 身份失效或缺少任务信息时停止安排下一次读取。
var canContinuePolling: Bool {
!identityInvalidated && context.canLoad && taskID > 0
!identityInvalidated && readAccessError == nil && context.canLoad && taskID > 0
&& DroneDockHomeMetric.usableText(order.orderNumber) != nil
}
@MainActor
private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false,
allowWhileResummoning: Bool = false) async {
guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting,
guard !isLoading, !identityInvalidated, readAccessError == nil, !isStartingShooting || allowWhileStarting,
!isSendingCommand || allowWhileCommand, !isResummoning || allowWhileResummoning else { return }
generation &+= 1
let requestGeneration = generation
let revisionAtRequest = snapshotRevision
isLoading = true
errorMessage = nil
defer {
@@ -121,23 +125,18 @@ final class DroneDockShootingTaskViewModel {
do {
let value = try await service.shooting(taskID: taskID, liveBattery: false)
guard accepts(requestGeneration) else { return }
guard matchesIdentity(value) else {
if applyTaskSnapshot(value) == .invalid {
response = nil
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
}
response = value
DroneDockDiagnostics.event("shooting.snapshot_applied", taskID: taskID, fields: [
"phase": presentation.phase.rawValue,
"plane_id": value.currentPlane?.id as Any? ?? NSNull(),
"can_execute": value.executeGate?.canExecute as Any? ?? NSNull(),
"primary_action": value.executeGate?.primaryAction as Any? ?? NSNull()
])
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
awaitingResummonSnapshot = false
}
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
} catch {
guard accepts(requestGeneration) else { return }
if Self.stopsTaskReading(error) {
stopReading(message: error.localizedDescription)
return
}
// 迟到 HTTP 失败不能覆盖请求期间已收到的有效实时状态。
guard snapshotRevision == revisionAtRequest else { return }
errorMessage = error is CancellationError ? nil : error.localizedDescription
DroneDockDiagnostics.event("shooting.refresh_failed", taskID: taskID, fields: [
"retained_snapshot": response != nil, "error": DroneDockDiagnostics.errorFields(error)
@@ -145,6 +144,52 @@ final class DroneDockShootingTaskViewModel {
}
}
/// HTTP 和推送共享完整快照入口,按执行批次、版本去重,绝不按到达顺序覆盖。
@MainActor
@discardableResult
func applyTaskSnapshot(_ value: DroneDockShootingResponse) -> DroneDockSnapshotAcceptance {
guard readAccessError == nil, accepts(generation), matchesIdentity(value) else { return .invalid }
if let oldBatch = response?.executionBatch, let oldVersion = response?.stateVersion {
guard let batch = value.executionBatch, let version = value.stateVersion else { return .outdated }
if batch < oldBatch || (batch == oldBatch && version < oldVersion) { return .outdated }
if batch == oldBatch && version == oldVersion {
errorMessage = nil
snapshotRevision &+= 1
return .duplicate
}
}
response = value
errorMessage = nil
snapshotRevision &+= 1
DroneDockDiagnostics.event("shooting.snapshot_applied", taskID: taskID, fields: [
"phase": presentation.phase.rawValue,
"execution_batch": value.executionBatch as Any? ?? NSNull(),
"state_version": value.stateVersion as Any? ?? NSNull(),
"plane_id": value.currentPlane?.id as Any? ?? NSNull()
])
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
awaitingResummonSnapshot = false
}
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
return .applied
}
/// 订阅明确无权限或 HTTP 鉴权失效时保留快照、禁用操作并停止后续读取。
@MainActor
func stopReading(message: String) {
generation &+= 1
isLoading = false
readAccessError = message
errorMessage = 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) {
@@ -166,14 +211,14 @@ final class DroneDockShootingTaskViewModel {
errorMessage = "账号或景区已变化,请返回工作台重新进入"
} else {
if !preservingSnapshot { response = nil }
errorMessage = nil
errorMessage = readAccessError
}
}
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;Debug 真实页面保持禁用。
var canStartShooting: Bool {
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !hasSubmittedStart && !startOutcomeUnknown
&& !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot && pendingAcceptedCommands.isEmpty
&& resolvedDisplayPhase().0 == .ready
@@ -263,7 +308,7 @@ final class DroneDockShootingTaskViewModel {
/// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。
func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool {
commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot
&& !pendingAcceptedCommands.contains(command)
&& (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID)
@@ -342,7 +387,7 @@ final class DroneDockShootingTaskViewModel {
/// 此门禁用于客户端模拟交互,不代表后端已提供真实重试许可。
var canResummon: Bool {
resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown
&& !hasSubmittedResummon && pendingAcceptedCommands.isEmpty
&& resolvedDisplayPhase().0 == .failed
@@ -478,7 +523,7 @@ final class DroneDockShootingTaskViewModel {
}
if response == nil, let errorMessage {
return DroneDockTaskPresentation(phase: .readError, title: "任务状态读取失败", message: errorMessage,
deviceStatus: deviceStatusText, action: .refresh, actionTitle: "重新读取", isActionEnabled: !identityInvalidated)
deviceStatus: deviceStatusText, action: .refresh, actionTitle: "重新读取", isActionEnabled: !identityInvalidated && readAccessError == nil)
}
let (phase, conflict) = resolvedDisplayPhase()
let message = conflict ? "任务状态信息不一致,请刷新后确认。" + (statusMessage == "—" ? "" : statusMessage) : statusMessage
@@ -519,7 +564,7 @@ final class DroneDockShootingTaskViewModel {
}
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
isActionEnabled: enabled && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
isActionEnabled: enabled && readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil)
}
@@ -530,8 +575,8 @@ final class DroneDockShootingTaskViewModel {
windText: text("wind_speed"), rainText: text("rainfall"), signalText: text("signal"), satelliteText: text("satellite"))
}
/// 仅无快照时使用未知读数;刷新期间继续展示最近一次成功快照。
var isTelemetryStale: Bool { response == nil }
/// 无快照或后端标记缓存过期时使用非实时样式;已有读数仍保留展示。
var isTelemetryStale: Bool { response == nil || response?.metricsStale == true }
/// 完整服务端 data,供页面展示和联调查看。
var dataJSON: String? { response?.dataJSON }
@@ -612,7 +657,7 @@ final class DroneDockShootingTaskViewModel {
}
private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool {
let taskIDs = [value.orderFlightTask?.id, value.task?.id].compactMap { $0 }
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,
@@ -631,6 +676,7 @@ final class DroneDockShootingTaskViewModel {
if statuses.contains(50) { return (.blocked, 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,
"paused": .paused, "returning": .returning, "completed": .completed, "failed": .failed, "blocked": .blocked
]