feat(drone-dock): 接入图传与重召唤的本地模拟流程

新增 live 接口、状态展示和本地视频预览;支持同任务重新召唤、单次回查和防重,保留禁飞拦截。同步测试、模拟证据、后端接口确认文档及景区空境库范围约定。

验证:168 个相关用例最终均通过;最后复跑 38 项零失败。真实设备指令未发送。
This commit is contained in:
2026-11-02 09:49:17 +08:00
parent 2913273e35
commit c1fd2d0859
33 changed files with 3246 additions and 84 deletions
@@ -0,0 +1,146 @@
import Foundation
/// 任务图传区域的单次请求与生命周期;正式入口不注入操作服务,模拟来源单独注入。
final class DroneDockLiveViewModel {
/// 当前图传所属的账号、景区与门店范围。
let context: DroneDockHomeContext
/// 固定订单飞行任务身份。
let taskID: Int
/// 最近一次通过身份核对的图传回执,不用作实时播放配置。
private(set) var response: DroneDockLiveResponse?
/// 图传区域当前可展示状态。
private(set) var state: DroneDockLiveState
/// 请求期间阻止重复获取,不安排定时轮询。
private(set) var isLoading = false
private let service: (any DroneDockLiveServing)?
private let localPreviewURL: URL?
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private var generation = 0
private var identityInvalidated = false
/// 本地素材仅供明确的模拟入口注入,后端 JSON 不能生成此 URL。
init(context: DroneDockHomeContext, taskID: Int, service: (any DroneDockLiveServing)? = nil,
localPreviewURL: URL? = nil,
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.taskID = taskID
self.service = service
self.localPreviewURL = localPreviewURL
self.currentContext = currentContext
state = service == nil ? .restricted : .idle
}
/// 仅有明确注入服务且身份有效时允许发起请求;正式禁飞入口始终为 false。
var canLoad: Bool { service != nil && !isLoading && !identityInvalidated && context.canLoad && taskID > 0 }
/// 仅返回明确注入且已经过本地文件检查的模拟视频,不使用后端未定义字段。
var playbackURL: URL? {
if case .localPreview(let url) = state { return url }
return nil
}
/// 图传区域主文案,不把接口受理视为设备连接成功。
var title: String {
switch state {
case .restricted: return "当前调试已停用实时图传"
case .idle: return "实时图传"
case .loading: return "正在获取图传信息"
case .unavailable: return "图传暂不可用"
case .failed: return "图传加载失败"
case .localPreview: return "本地模拟画面"
}
}
/// 缺失协议时说明真实限制,不给示例视频贴上实时来源。
var message: String {
switch state {
case .restricted: return "禁飞调试期间不启动设备图传"
case .idle: return "按当前任务获取图传信息"
case .loading: return "请稍候"
case .unavailable(let reason), .failed(let reason): return reason
case .localPreview: return "仅播放本地样片,未连接无人机"
}
}
/// 操作名称跟随当前阶段,模拟来源始终显式标记。
var actionTitle: String? {
guard service != nil else { return nil }
if isLoading { return "正在加载…" }
switch state {
case .restricted: return nil
case .idle: return localPreviewURL == nil ? "获取图传信息" : "查看模拟图传"
case .loading: return "正在加载…"
case .failed, .unavailable: return "重试"
case .localPreview: return "重新加载模拟图传"
}
}
/// 发起一次图传请求,拒绝重复点击、迟到响应、身份不符及远程模拟视频来源。
@MainActor
func refresh(onRequestStarted: (@MainActor () -> Void)? = nil) async {
guard canLoad, let service else { return }
generation &+= 1
let requestGeneration = generation
guard accepts(requestGeneration) else { return }
isLoading = true
if playbackURL == nil { state = .loading }
onRequestStarted?()
defer {
if generation == requestGeneration {
isLoading = false
if Task.isCancelled, state == .loading { state = .idle }
}
}
do {
let value = try await service.live(taskID: taskID)
guard accepts(requestGeneration) else { return }
guard value.orderFlightTaskID == taskID, value.task?.id == nil || value.task?.id == taskID,
value.task?.scenicID == nil || value.task?.scenicID == context.scenicID else {
throw APIError.decodeFailed("图传回执与当前拍摄任务不一致")
}
response = value
guard let airportSN = DroneDockHomeMetric.usableText(value.airportSN), !airportSN.isEmpty else {
state = .unavailable("当前任务尚未返回已锁定的机场信息")
return
}
if let localPreviewURL {
guard localPreviewURL.isFileURL, FileManager.default.fileExists(atPath: localPreviewURL.path) else {
state = .failed("本地模拟视频不可用")
return
}
state = .localPreview(localPreviewURL)
} else {
state = .unavailable("暂未提供图传播放参数")
}
} catch is CancellationError {
guard generation == requestGeneration else { return }
state = .idle
} catch {
guard accepts(requestGeneration) else { return }
state = .failed(error.localizedDescription)
}
}
/// 离页、后台或取消时作废旧请求并清除本地播放来源,不向设备发送停止指令。
@MainActor
func invalidate() {
generation &+= 1
isLoading = false
response = nil
state = service == nil ? .restricted : .idle
}
/// 只接受当前页面与当前身份下的结果,身份变化后不允许重新请求旧任务。
@MainActor
private func accepts(_ requestGeneration: Int) -> Bool {
guard generation == requestGeneration else { return false }
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
invalidate()
identityInvalidated = true
state = .failed("账号或景区已变化,请返回工作台重新进入")
return false
}
return !Task.isCancelled
}
}
@@ -34,10 +34,21 @@ final class DroneDockShootingTaskViewModel {
private(set) var commandErrorMessage: String?
/// 已发但结果不明确时保持锁定,普通读取不能自动解除或重发。
private(set) var commandOutcomeUnknown = false
/// 重新召唤提交及其后单次回查期间保留旧画面并锁定其他操作。
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 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 var generation = 0
private var identityInvalidated = false
@@ -45,6 +56,9 @@ final class DroneDockShootingTaskViewModel {
private var didSendStart = false
private var commandGeneration = 0
private var didSendCommand = false
private var resummonGeneration = 0
private var didSendResummon = false
private var awaitingResummonSnapshot = false
// 回查仍提供的已受理指令分别保留防重锁,避免另一条指令受理覆盖旧锁。
private var pendingAcceptedCommands: Set<DroneDockSafetyCommand> = []
@@ -53,6 +67,7 @@ final class DroneDockShootingTaskViewModel {
service: any DroneDockShootingServing,
startService: (any DroneDockStartShooting)? = nil,
commandService: (any DroneDockCommandSending)? = nil,
resummonService: (any DroneDockResummonServing)? = nil,
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.taskID = taskID
@@ -60,6 +75,7 @@ final class DroneDockShootingTaskViewModel {
self.service = service
self.startService = startService
self.commandService = commandService
self.resummonService = resummonService
self.currentContext = currentContext
}
@@ -70,9 +86,10 @@ final class DroneDockShootingTaskViewModel {
}
@MainActor
private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false) async {
private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false,
allowWhileResummoning: Bool = false) async {
guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting,
!isSendingCommand || allowWhileCommand else { return }
!isSendingCommand || allowWhileCommand, !isResummoning || allowWhileResummoning else { return }
generation &+= 1
let requestGeneration = generation
isLoading = true
@@ -97,6 +114,9 @@ final class DroneDockShootingTaskViewModel {
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
}
response = value
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
awaitingResummonSnapshot = false
}
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
} catch {
guard accepts(requestGeneration) else { return }
@@ -109,6 +129,7 @@ final class DroneDockShootingTaskViewModel {
func invalidate(preservingSnapshot: Bool = false) {
invalidateStartShooting()
invalidateCommand()
invalidateResummon()
generation &+= 1
isLoading = false
if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true }
@@ -118,6 +139,8 @@ final class DroneDockShootingTaskViewModel {
startErrorMessage = nil
commandResponse = nil
commandErrorMessage = nil
resummonResponse = nil
resummonErrorMessage = nil
pendingAcceptedCommands.removeAll()
errorMessage = "账号或景区已变化,请返回工作台重新进入"
} else {
@@ -129,9 +152,9 @@ final class DroneDockShootingTaskViewModel {
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;默认真实页面保持禁用。
var canStartShooting: Bool {
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && errorMessage == nil
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !hasSubmittedStart && !startOutcomeUnknown
&& !commandOutcomeUnknown && pendingAcceptedCommands.isEmpty
&& !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot && pendingAcceptedCommands.isEmpty
&& resolvedDisplayPhase().0 == .ready
&& response?.executeGate?.canExecute == true
&& response?.executeGate?.primaryAction == "start_shoot"
@@ -218,8 +241,9 @@ final class DroneDockShootingTaskViewModel {
/// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。
func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool {
commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !pendingAcceptedCommands.contains(command)
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot
&& !pendingAcceptedCommands.contains(command)
&& (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID)
&& (response?.currentPlane?.id ?? 0) > 0
&& availableSafetyCommands.contains(command)
@@ -291,6 +315,88 @@ final class DroneDockShootingTaskViewModel {
didSendCommand = false
}
/// 本地模拟服务显式注入、当前任务明确失败且没有在途或未知操作时才可重召唤。
/// 此门禁用于客户端模拟交互,不代表后端已提供真实重试许可。
var canResummon: Bool {
resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown
&& !hasSubmittedResummon && pendingAcceptedCommands.isEmpty
&& resolvedDisplayPhase().0 == .failed
&& (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 {
guard canResummon, let resummonService else { return }
guard context.hasSameIdentity(as: currentContext()) else {
identityInvalidated = true
invalidate()
onStateChange()
return
}
guard !Task.isCancelled else { return }
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
hasSubmittedResummon = true
resummonOutcomeUnknown = false
awaitingResummonSnapshot = true
hasSubmittedStart = false
startResponse = nil
startErrorMessage = nil
commandResponse = nil
commandErrorMessage = nil
onStateChange()
guard acceptsResummon(requestGeneration) else { return }
await refreshSnapshot(allowWhileStarting: false, allowWhileResummoning: true)
} catch {
if error is DeviceCommandDebugBlockedError, resummonGeneration == requestGeneration { didSendResummon = false }
guard acceptsResummon(requestGeneration) else { return }
if error is DeviceCommandDebugBlockedError {
resummonErrorMessage = DeviceCommandDebugPolicy.blockedMessage
} else 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 }
@@ -328,6 +434,8 @@ final class DroneDockShootingTaskViewModel {
if let errorMessage { return errorMessage }
if isLoading { return "正在读取当前拍摄任务" }
}
if let resummonErrorMessage { return resummonErrorMessage }
if awaitingResummonSnapshot { return "重新召唤请求已受理,请刷新核对任务状态" }
if let commandErrorMessage { return commandErrorMessage }
if resolvedDisplayPhase().0 == .failed { return failureMessage }
if startOutcomeUnknown, let startErrorMessage { return startErrorMessage }
@@ -355,7 +463,7 @@ final class DroneDockShootingTaskViewModel {
let actionTitle: String?
let enabled: Bool
switch phase {
case .ready where hasSubmittedStart || startOutcomeUnknown || commandOutcomeUnknown:
case .ready where hasSubmittedStart || startOutcomeUnknown || commandOutcomeUnknown || resummonOutcomeUnknown:
action = .refresh
actionTitle = "刷新状态"
enabled = !identityInvalidated
@@ -372,10 +480,14 @@ final class DroneDockShootingTaskViewModel {
action = .materials
actionTitle = "查看素材"
enabled = true
case .failed where hasSubmittedResummon || resummonOutcomeUnknown:
action = .refresh
actionTitle = "刷新状态"
enabled = !identityInvalidated
case .failed:
action = .retry
actionTitle = "重新召唤无人机"
enabled = false
actionTitle = isResummoning ? "正在重新召唤…" : "重新召唤无人机"
enabled = canResummon
default:
action = .refresh
actionTitle = "刷新状态"
@@ -383,8 +495,8 @@ final class DroneDockShootingTaskViewModel {
}
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
isActionEnabled: enabled && !isLoading && !isStartingShooting && !isSendingCommand && !identityInvalidated && (errorMessage == nil || action == .refresh),
actionNote: phase == .failed ? retryUnavailableNote : nil)
isActionEnabled: enabled && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil)
}
/// 后端六项展示读数,不解析文案反推设备状态或数值单位。
@@ -433,6 +545,35 @@ final class DroneDockShootingTaskViewModel {
return !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)。" } ?? "") + "重新召唤结果待核对,请刷新任务状态,勿重复提交"
}
/// 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 markCommandUnknown(reason: String? = nil) {
commandOutcomeUnknown = true
commandErrorMessage = (reason.map { "\($0)。" } ?? "") + "安全指令结果待核对,请刷新任务状态,勿重复提交"
@@ -524,7 +665,15 @@ final class DroneDockShootingTaskViewModel {
?? usable(response?.executeGate?.message) ?? usable(response?.ui?.message) ?? "暂未返回具体失败原因"
}
/// 重新召唤尚未接入;只补充明确设备状态,不将开始许可、空闲或失败推断为允许重试。
/// 明确离线或返航时保持禁用,不从普通空闲文案推导后端重试许可。
private var isResummonDeviceUnavailable: Bool {
let plane = response?.currentPlane
return response?.planeStatus?.connected == false || plane?.onlineStatus == 2 || plane?.workStatus == 0
|| ["离线", "返航中", "正在返航"].contains(usable(plane?.workStatusLabel) ?? "")
|| response?.ui?.phase == "returning"
}
/// 正式入口未注入操作服务时说明当前限制;模拟页保留实际设备不可用原因。
private var retryUnavailableNote: String {
let plane = response?.currentPlane
if plane?.onlineStatus == 2 || plane?.workStatus == 0 || usable(plane?.workStatusLabel) == "离线" {