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,31 @@
import Foundation
/// 朱工任务图传参数服务;请求可能启动设备图传,禁飞期间只允许隔离模拟注入。
protocol DroneDockLiveServing: Sendable {
/// 读取同一订单飞行任务的图传回执,不创建任务或更换飞机。
@MainActor
func live(taskID: Int) async throws -> DroneDockLiveResponse
}
/// 按已提供的 live 合同发送请求;不猜测 RTC 厂商、播放地址或连接凭证。
@MainActor
final class DroneDockLiveAPI: DroneDockLiveServing {
private let client: APIClient
/// 注入统一客户端,保留 Debug 禁飞阻断与纯内存测试传输。
init(client: APIClient) { self.client = client }
/// 只发送一次 GET,请求失败不自动重试或发出其他设备请求。
func live(taskID: Int) async throws -> DroneDockLiveResponse {
try Task.checkCancellation()
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID") }
let value: DroneDockLiveResponse = try await client.send(APIRequest(
method: .get, path: "/api/app/airport/live",
queryItems: [URLQueryItem(name: "id", value: String(taskID))]
))
guard value.orderFlightTaskID == taskID, value.task?.id == nil || value.task?.id == taskID else {
throw APIError.decodeFailed("图传回执与当前拍摄任务不一致")
}
return value
}
}
@@ -7,9 +7,16 @@ protocol DroneDockShootServing: Sendable {
func shoot(taskID: Int) async throws -> DroneDockShootResponse
}
/// 为已有失败任务提交重新召唤,不创建新任务或更换锁定飞机。
protocol DroneDockResummonServing: Sendable {
/// 发送一次 restart=true 的召唤请求,调用方负责防重及受理后的状态核对。
@MainActor
func resummon(taskID: Int) async throws -> DroneDockShootResponse
}
/// 朱工 shoot 接口适配,业务成功仅表示接口受理结果,不推断飞机已经到达。
@MainActor
final class DroneDockShootAPI: DroneDockShootServing {
final class DroneDockShootAPI: DroneDockShootServing, DroneDockResummonServing {
private let client: APIClient
/// 注入统一网络客户端,沿用登录凭证、HTTP 与业务码处理。
@@ -17,13 +24,22 @@ final class DroneDockShootAPI: DroneDockShootServing {
/// 仅发送一次召唤 POST;不创建任务、不重试、不修改任务已选航线。
func shoot(taskID: Int) async throws -> DroneDockShootResponse {
try await send(taskID: taskID, restart: false)
}
/// 复用同一订单飞行任务请求重启;当前仅由隔离模拟入口注入,真实传输仍受禁飞保护。
func resummon(taskID: Int) async throws -> DroneDockShootResponse {
try await send(taskID: taskID, restart: true)
}
private func send(taskID: Int, restart: Bool) async throws -> DroneDockShootResponse {
try Task.checkCancellation()
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请先创建任务") }
do {
return try await client.send(APIRequest(
method: .post,
path: "/api/app/airport/shoot",
body: ShootBody(taskID: taskID)
body: ShootBody(taskID: taskID, restart: restart)
))
} catch APIError.emptyData {
// 统一客户端仅在 HTTP 和业务码均成功后抛 emptyData;此接口尚未约定成功 data 结构。
@@ -31,10 +47,10 @@ final class DroneDockShootAPI: DroneDockShootServing {
}
}
/// 本轮联调仅发送任务身份和非重启标记,完全省略 plane_id 与航线覆盖字段。
/// 仅发送任务身份和重启标记,完全省略 plane_id 与航线覆盖字段。
private struct ShootBody: Encodable {
let taskID: Int
let restart = false
let restart: Bool
/// 朱工已建任务召唤参数映射。
private enum CodingKeys: String, CodingKey {
@@ -0,0 +1,68 @@
import Foundation
/// live 文档已明确的任务与设备回执;当前合同没有可用于播放的字段。
struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
/// 后端回显的订单飞行任务 ID,不能用请求值补齐。
let orderFlightTaskID: Int
/// 设备明细尚未定义字段,保留原 JSON 类型。
let airport: DroneDockHomeJSONValue?
/// 无人机明细尚未定义字段,保留原 JSON 类型。
let drone: DroneDockHomeJSONValue?
/// 文档中的任务摘要,若提供身份必须与顶层任务一致。
let task: DroneDockShootingTaskIdentity?
/// 已锁定机场序列号,不用于客户端选择或重新绑定设备。
let airportSN: String?
/// 随接口返回的展示读数,不触发额外实时采集。
let metrics: [DroneDockHomeMetric]
/// 完整回执,包含尚未建模字段,不解释成播放器配置。
let dataJSON: String
/// live 文档中的已知字段映射。
private enum CodingKeys: String, CodingKey {
case orderFlightTaskID = "order_flight_task_id", airport, drone, task
case airportSN = "airport_sn", metrics
}
/// 任务 ID 必须明确提供;未知字段及 null 留在完整 JSON 中供后续合同核对。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
orderFlightTaskID = try container.decode(Int.self, forKey: .orderFlightTaskID)
airport = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .airport)
drone = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .drone)
task = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .task)
airportSN = try container.decodeIfPresent(String.self, forKey: .airportSN)
metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? []
let raw = try DroneDockHomeJSONValue(from: decoder)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
dataJSON = String(decoding: try encoder.encode(DroneDockLiveJSONSnapshot(value: raw)), as: UTF8.self)
}
}
/// 只负责原样编码解码所得的 JSON,不追加猜测的流媒体参数。
private struct DroneDockLiveJSONSnapshot: Encodable {
let value: DroneDockHomeJSONValue
/// 保持字典、数组、空值、数值与字符串的原始类型。
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch value {
case .object(let value): try container.encode(value.mapValues { Self(value: $0) })
case .array(let value): try container.encode(value.map { Self(value: $0) })
case .string(let value): try container.encode(value)
case .number(let value): try container.encode(value)
case .bool(let value): try container.encode(value)
case .null: try container.encodeNil()
}
}
}
/// 图传区域的明确状态;本地视频预览不代表设备连接或真实图传成功。
enum DroneDockLiveState: Equatable, Sendable {
case restricted
case idle
case loading
case unavailable(String)
case failed(String)
case localPreview(URL)
}
@@ -17,6 +17,36 @@ struct DroneDockShootResponse: Decodable, Equatable, Sendable {
}
}
/// 重新召唤回执中可核对的订单任务身份;顶层 task_id 属于实际航线任务,不作订单任务 ID 使用。
struct DroneDockResummonReceiptIdentity: Decodable, Sendable {
/// 后端明确回显的订单飞行任务 ID,缺失时由后续 shooting 核对。
let orderFlightTaskID: Int?
/// 后端已提供的订单任务摘要身份。
let orderFlightTask: TaskIdentity?
/// 已锁定任务的飞机 ID;实际提供时核对是否仍为原任务飞机。
let planeID: Int?
/// 只读取已约定的订单任务身份字段。
private enum CodingKeys: String, CodingKey {
case orderFlightTaskID = "order_flight_task_id", orderFlightTask = "order_flight_task", planeID = "plane_id"
}
/// 嵌套订单任务的可选身份字段,不读取或推断设备执行阶段。
struct TaskIdentity: Decodable, Sendable {
/// 原订单飞行任务 ID。
let id: Int?
/// 任务所属订单。
let orderNumber: String?
/// 任务所属景区。
let scenicID: Int?
/// 订单任务摘要字段映射。
private enum CodingKeys: String, CodingKey {
case id, orderNumber = "order_number", scenicID = "scenic_id"
}
}
}
/// 将现有 JSON 值解码结果格式化,完整保留 shoot 尚未约定的成功数据结构。
private struct DroneDockShootJSONSnapshot: Encodable {
let value: DroneDockHomeJSONValue
@@ -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) == "离线" {
@@ -150,7 +150,7 @@ final class ScenicMaterialsViewModel {
var emptyMessage: String {
if isLoading { return "请稍候" }
if let loadError { return loadError }
return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里"
return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "试试其他航线或时间范围" : "景区素材更新后,将显示在这里"
}
/// 刷新当前筛选第一页,并读取该页完整片段;详情失败时整页可重试,不混入演示数据。
@@ -1,17 +1,19 @@
import SnapKit
import UIKit
/// 拍摄任务页:真实入口只读,本地模拟入口可验证开拍与底部安全指令合同。
/// 拍摄任务页:真实入口只读,本地模拟入口可验证图传、重召唤、开拍与安全指令合同。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
let viewModel: DroneDockShootingTaskViewModel
/// 图传使用独立状态,刷新与播放不会影响任务阶段或固定布局。
let liveViewModel: DroneDockLiveViewModel
private let topView = UIView()
private let summaryView = UIView()
private let taskTitleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
private let subtitleLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let feedPlaceholder = DroneDockTaskFeedPlaceholderView()
private let feedPlaceholder = DroneDockTaskLiveView()
private let telemetryView = DroneShootingTaskTelemetryView()
private let statusView = DroneDockTaskStatusView()
private let safetyView = DroneDockTaskSafetyView()
@@ -24,18 +26,26 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private var refreshTask: Task<Void, Never>?
private var startTask: Task<Void, Never>?
private var commandTask: Task<Void, Never>?
private var resummonTask: Task<Void, Never>?
private var liveTask: Task<Void, Never>?
private var liveGeneration = 0
private var requestGeneration = 0
private var isPageVisible = false
private var isApplicationActive = false
private var isRequesting = false
private var isStartingAction = false
private var isSendingSafetyAction = false
private var isResummoningAction = false
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
init(viewModel: DroneDockShootingTaskViewModel,
liveViewModel: DroneDockLiveViewModel? = nil,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
simulationRecordsProvider: (@MainActor () -> String)? = nil) {
self.viewModel = viewModel
self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel(
context: viewModel.context, taskID: viewModel.taskID,
currentContext: { DroneDockHomeViewController.currentContext() })
self.simulationRecordsProvider = simulationRecordsProvider
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
@@ -54,6 +64,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
refreshTask?.cancel()
startTask?.cancel()
commandTask?.cancel()
resummonTask?.cancel()
liveTask?.cancel()
NotificationCenter.default.removeObserver(self)
}
@@ -160,6 +172,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
statusView.onPrimaryAction = { [weak self] in self?.primaryActionTriggered() }
statusView.onDetails = { [weak self] in self?.showStatusDetails() }
safetyView.onCommand = { [weak self] command in self?.safetyCommandTriggered(command) }
feedPlaceholder.onRequest = { [weak self] in self?.refreshLiveIfVisible() }
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
@@ -172,6 +185,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
isPageVisible = true
isApplicationActive = UIApplication.shared.applicationState == .active
refreshTaskIfVisible()
refreshLiveIfVisible()
}
/// 离页立即取消未完成的读取,使迟到响应失效。
@@ -179,12 +193,15 @@ final class DroneDockShootingTaskViewController: BaseViewController {
super.viewWillDisappear(animated)
isPageVisible = false
cancelRefresh()
stopLive()
}
private func applySnapshot() {
guard isViewLoaded else { return }
let loading = isRequesting || viewModel.isLoading || isStartingAction || viewModel.isStartingShooting
|| isSendingSafetyAction || viewModel.isSendingCommand
|| isSendingSafetyAction || viewModel.isSendingCommand || isResummoningAction || viewModel.isResummoning
feedPlaceholder.apply(liveViewModel)
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive)
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle
let telemetry = viewModel.telemetry
@@ -205,7 +222,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func primaryActionTriggered() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand else { return }
!isSendingSafetyAction, !viewModel.isSendingCommand,
!isResummoningAction, !viewModel.isResummoning else { return }
let state = viewModel.presentation
guard state.isActionEnabled else { return }
switch state.action {
@@ -213,10 +231,12 @@ final class DroneDockShootingTaskViewController: BaseViewController {
refreshTaskIfVisible()
case .start:
startShootingIfAllowed()
case .retry:
resummonIfAllowed()
case .materials:
guard let navigationController, navigationController.topViewController === self else { return }
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
case .resume, .retry, .none:
case .resume, .none:
break
}
}
@@ -230,6 +250,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
if let error = viewModel.startErrorMessage { texts.append(error) }
if let error = viewModel.commandErrorMessage { texts.append(error) }
if let error = viewModel.resummonErrorMessage { texts.append(error) }
var distinct: [String] = []
for text in texts where !distinct.contains(text) { distinct.append(text) }
let alert = UIAlertController(title: "任务状态详情", message: distinct.joined(separator: "\n\n"), preferredStyle: .alert)
@@ -241,7 +262,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func refreshTaskIfVisible() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand else { return }
!isSendingSafetyAction, !viewModel.isSendingCommand,
!isResummoningAction, !viewModel.isResummoning else { return }
requestGeneration &+= 1
let generation = requestGeneration
isRequesting = true
@@ -268,6 +290,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
startTask = nil
commandTask?.cancel()
commandTask = nil
resummonTask?.cancel()
resummonTask = nil
isResummoningAction = false
isSendingSafetyAction = false
isStartingAction = false
isRequesting = false
@@ -277,7 +302,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。
private func startShootingIfAllowed() {
guard !isStartingAction, !isSendingSafetyAction, viewModel.canStartShooting else { return }
guard !isStartingAction, !isSendingSafetyAction, !isResummoningAction, viewModel.canStartShooting else { return }
requestGeneration &+= 1
let generation = requestGeneration
isStartingAction = true
@@ -298,11 +323,65 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
}
/// 重召唤只在显式模拟入口开放;点击后锁定按钮,使用原任务 ID,并由状态回查更新页面。
private func resummonIfAllowed() {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
!isResummoningAction, !isStartingAction, !isSendingSafetyAction,
!isRequesting, viewModel.canResummon else { return }
requestGeneration &+= 1
let generation = requestGeneration
isResummoningAction = true
applySnapshot()
resummonTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.resummon { [weak self] in self?.applySnapshot() }
guard self.isPageVisible, self.isApplicationActive,
self.requestGeneration == generation, !Task.isCancelled else { return }
self.resummonTask = nil
self.isResummoningAction = false
self.applySnapshot()
if let error = self.viewModel.resummonErrorMessage {
self.showToast(error)
} else if self.viewModel.hasSubmittedResummon, let error = self.viewModel.errorMessage {
self.showToast("模拟重召唤已受理,状态刷新失败:\(error)")
} else if self.viewModel.hasSubmittedResummon {
self.showToast("本地模拟重召唤已受理,未发送设备指令")
} else if let error = self.viewModel.errorMessage {
self.showToast(error)
}
}
}
/// 图传只读取一次,不轮询;正式入口没有图传服务,不能向设备发出开流请求。
private func refreshLiveIfVisible() {
guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return }
liveGeneration &+= 1
let generation = liveGeneration
liveTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.liveViewModel.refresh { [weak self] in self?.applySnapshot() }
guard self.liveGeneration == generation, self.isPageVisible, self.isApplicationActive,
!Task.isCancelled else { return }
self.liveTask = nil
self.applySnapshot()
}
}
/// 离页或进入后台立即释放播放器,使旧图传响应无法恢复播放。
private func stopLive() {
liveGeneration &+= 1
liveTask?.cancel()
liveTask = nil
liveViewModel.invalidate()
feedPlaceholder.setPlaybackActive(false)
feedPlaceholder.apply(liveViewModel)
}
/// 仅模拟入口响应安全按钮;返航会中断任务,先明确展示其含义再提交一次。
private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
presentedViewController == nil, !isSendingSafetyAction, !isStartingAction,
!isRequesting, viewModel.canSendCommand(command) else { return }
!isResummoningAction, !isRequesting, viewModel.canSendCommand(command) else { return }
if command == .returnHome {
let alert = UIAlertController(title: "立即返航(本地模拟)",
message: "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。", preferredStyle: .alert)
@@ -319,7 +398,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 同步锁覆盖异步调度间隙;界面保留旧快照,只有同任务回查成功才更新阶段。
private func sendSafetyCommand(_ command: DroneDockSafetyCommand) {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
!isSendingSafetyAction, !isStartingAction, !isRequesting,
!isSendingSafetyAction, !isStartingAction, !isResummoningAction, !isRequesting,
viewModel.canSendCommand(command) else { return }
requestGeneration &+= 1
let generation = requestGeneration
@@ -360,12 +439,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
@objc private func applicationWillResignActive() {
isApplicationActive = false
cancelRefresh()
stopLive()
}
@objc private func applicationDidBecomeActive() {
guard !isApplicationActive else { return }
isApplicationActive = true
refreshTaskIfVisible()
refreshLiveIfVisible()
}
}
@@ -501,34 +582,3 @@ private final class DroneDockTaskSafetyView: UIView {
buttonHeight?.update(offset: compact ? 56 : 62)
}
}
/// 真实图传尚未接入时的中性占位,不使用演示图片、播放进度或虚假连接状态。
@MainActor
private final class DroneDockTaskFeedPlaceholderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(hex: 0x172033)
accessibilityIdentifier = "drone.task.remote.feedPlaceholder"
let icon = UIImageView(image: UIImage(systemName: "video.slash"))
icon.contentMode = .scaleAspectFit
icon.tintColor = UIColor.white.withAlphaComponent(0.6)
let title = DroneDockStyle.label("图传暂未接入", size: 15, weight: .medium, color: .white)
let detail = DroneDockStyle.label("任务状态将在下方更新", size: 12, color: .white.withAlphaComponent(0.65))
let stack = UIStackView(arrangedSubviews: [icon, title, detail])
stack.axis = .vertical
stack.spacing = 9
stack.alignment = .center
addSubview(stack)
icon.snp.makeConstraints { make in make.size.equalTo(31) }
stack.snp.makeConstraints { make in
make.center.equalToSuperview()
make.leading.greaterThanOrEqualToSuperview().offset(20)
make.trailing.lessThanOrEqualToSuperview().offset(-20)
}
isAccessibilityElement = true
accessibilityLabel = "图传暂未接入,任务状态将在下方更新"
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
@@ -9,7 +9,10 @@ enum DroneDockStartShootSimulation {
static func makeController(arguments: [String]) -> UIViewController? {
let startsAtPreparation = arguments.contains("--dock-preparation-mock")
let startsAtCommands = arguments.contains("--dock-command-mock")
guard startsAtPreparation || startsAtCommands || arguments.contains("--dock-start-shoot-mock") else { return nil }
let startsAtResummon = arguments.contains("--dock-resummon-mock")
let showsLive = arguments.contains("--dock-live-mock")
guard startsAtPreparation || startsAtCommands || startsAtResummon || showsLive
|| arguments.contains("--dock-start-shoot-mock") else { return nil }
let resultArgument = arguments.first { $0.hasPrefix("--dock-start-shoot-result=") }
let result = resultArgument.flatMap {
DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-start-shoot-result=".count)))
@@ -18,8 +21,16 @@ enum DroneDockStartShootSimulation {
let commandResult = commandResultArgument.flatMap {
DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-command-result=".count)))
} ?? .success
let resummonResult = arguments.first { $0.hasPrefix("--dock-resummon-result=") }.flatMap {
DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-resummon-result=".count)))
} ?? .success
let liveResult = arguments.first { $0.hasPrefix("--dock-live-result=") }.map {
String($0.dropFirst("--dock-live-result=".count))
} ?? "success"
return makeFlow(result: result, startsAtPreparation: startsAtPreparation,
commandResult: commandResult, startsAtCommands: startsAtCommands)
commandResult: commandResult, startsAtCommands: startsAtCommands,
startsAtResummon: startsAtResummon, resummonResult: resummonResult,
showsLive: showsLive, liveResult: liveResult)
}
/// 从正式准备页进入全新的纯内存模拟,不携带真实订单、账号或设备身份。
@@ -30,9 +41,13 @@ enum DroneDockStartShootSimulation {
private static func makeFlow(result: DroneDockStartShootMockResult,
startsAtPreparation: Bool,
commandResult: DroneDockStartShootMockResult = .success,
startsAtCommands: Bool = false) -> UIViewController? {
startsAtCommands: Bool = false, startsAtResummon: Bool = false,
resummonResult: DroneDockStartShootMockResult = .success,
showsLive: Bool = false, liveResult: String = "success") -> UIViewController? {
let session = DroneDockStartShootMockSession(result: result, requiresPreparation: startsAtPreparation,
commandResult: commandResult, hasStarted: startsAtCommands && !startsAtPreparation)
commandResult: commandResult, hasStarted: startsAtCommands && !startsAtPreparation,
hasFailed: startsAtResummon && !startsAtPreparation, resummonResult: resummonResult,
liveResult: liveResult)
let environment = APIEnvironment(baseURL: URL(string: "https://mock.invalid")!,
webSocketURL: URL(string: "wss://mock.invalid/unused")!)
let client = APIClient(environment: environment, session: session)
@@ -45,8 +60,14 @@ enum DroneDockStartShootSimulation {
let model = DroneDockShootingTaskViewModel(context: taskContext, taskID: taskID, order: taskOrder,
service: DroneDockShootingAPI(client: client),
startService: DroneDockStartShootAPI(client: client),
commandService: DroneDockCommandAPI(client: client), currentContext: { context })
return DroneDockShootingTaskViewController(viewModel: model,
commandService: DroneDockCommandAPI(client: client),
resummonService: startsAtResummon ? DroneDockShootAPI(client: client) : nil,
currentContext: { context })
let live = showsLive ? DroneDockLiveViewModel(context: taskContext, taskID: taskID,
service: DroneDockLiveAPI(client: client),
localPreviewURL: liveResult == "success" ? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4") : nil,
currentContext: { context }) : nil
return DroneDockShootingTaskViewController(viewModel: model, liveViewModel: live,
materialsControllerFactory: { _, _ in
let unavailable = UIViewController()
unavailable.title = "本地模拟不连接素材库"
@@ -79,6 +100,8 @@ private enum DroneDockStartShootMockResult: String {
private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
private let result: DroneDockStartShootMockResult
private let commandResult: DroneDockStartShootMockResult
private let resummonResult: DroneDockStartShootMockResult
private let liveResult: String
private let lock = NSLock()
private var hasCreated: Bool
private var hasSummoned: Bool
@@ -86,14 +109,19 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
private var isPaused = false
private var isReturning = false
private var wasInterrupted = false
private var hasFailed: Bool
private var exchanges: [Exchange] = []
/// 固定当前实例结果,不能用参数切换到真实传输。
init(result: DroneDockStartShootMockResult, requiresPreparation: Bool,
commandResult: DroneDockStartShootMockResult, hasStarted: Bool) {
commandResult: DroneDockStartShootMockResult, hasStarted: Bool,
hasFailed: Bool, resummonResult: DroneDockStartShootMockResult, liveResult: String) {
self.result = result
self.commandResult = commandResult
self.hasStarted = hasStarted
self.hasFailed = hasFailed
self.resummonResult = resummonResult
self.liveResult = liveResult
hasCreated = !requiresPreparation
hasSummoned = !requiresPreparation
}
@@ -188,8 +216,22 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
Set(object.keys) == ["id", "restart"],
let values = try? JSONDecoder().decode(ShootBody.self, from: body),
values.id == 901, !values.restart else { throw URLError(.badURL) }
guard hasCreated, !hasSummoned else {
values.id == 901 else { throw URLError(.badURL) }
if values.restart {
guard hasCreated, hasSummoned, hasFailed else {
return try envelope([:], code: 100099, message: "本地模拟:当前任务不允许重新召唤")
}
switch resummonResult {
case .businessFailure:
return try envelope([:], code: 100099, message: "本地模拟:设备暂不可用,重新召唤被拒绝")
case .timeout:
throw URLError(.timedOut)
case .success:
hasFailed = false
hasStarted = false
isPaused = false
}
} else if !hasCreated || hasSummoned {
return try envelope([:], code: 100099, message: "本地模拟:任务尚未创建或已召唤")
}
hasSummoned = true
@@ -207,6 +249,16 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") }
return try envelope(shootingData())
}
if request.httpMethod == "GET", url.path == "/api/app/airport/live" {
guard queryMatches(url, required: ["id": "901"]), hasSummoned else { throw URLError(.badURL) }
if liveResult == "timeout" { throw URLError(.timedOut) }
if liveResult == "business-failure" {
return try envelope([:], code: 100099, message: "本地模拟:图传连接不可用")
}
// 文档未提供播放协议;这里只模拟已知字段,本地视频通过独立依赖注入,绝不伪装成后端字段。
return try envelope(["order_flight_task_id": 901, "airport": [:], "drone": [:],
"task": taskData(), "airport_sn": "LOCAL-MOCK-DOCK-201", "metrics": simulatedMetrics])
}
if request.httpMethod == "POST", url.path == "/api/app/airport/command" {
guard url.query == nil, let body = request.httpBody,
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
@@ -243,7 +295,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
throw URLError(.unsupportedURL)
}
guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") }
guard !isPaused, !wasInterrupted else {
guard !isPaused, !wasInterrupted, !hasFailed else {
return try envelope([:], code: 100099, message: "本地模拟:任务暂停或已中断,不可开始拍摄")
}
guard !hasStarted else {
@@ -282,9 +334,11 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
}
private func shootingData() -> [String: Any] {
let canStart = !hasStarted && !isPaused && !wasInterrupted
let canStart = !hasStarted && !isPaused && !wasInterrupted && !hasFailed
let phaseTitle: String
if wasInterrupted {
if hasFailed {
phaseTitle = "本地模拟:航线执行失败,可验证重新召唤流程"
} else if wasInterrupted {
phaseTitle = isReturning ? "本地模拟:立即返航中断任务;无人机返航中" : "本地模拟:返航已取消,任务仍已中断"
} else if isPaused {
phaseTitle = "拍摄已暂停(模拟)"
@@ -322,7 +376,13 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
private func taskData() -> [String: Any] {
var task: [String: Any] = ["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128,
"status": 20, "status_label": "执行中(模拟)", "wayline_status": 20, "wayline_status_label": "执行中(模拟)"]
if wasInterrupted {
if hasFailed {
task["status"] = 40
task["status_label"] = "任务失败(模拟)"
task["wayline_status"] = 91
task["wayline_status_label"] = "执行失败(模拟)"
task["result_message"] = "本地模拟:航线执行失败,无人机空闲待命。"
} else if wasInterrupted {
task["status"] = 40
task["status_label"] = "任务已中断(模拟)"
task["wayline_status"] = 40
@@ -335,13 +395,14 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
}
private var availableCommands: [DroneDockSafetyCommand] {
guard hasSummoned else { return [] }
guard hasSummoned, !hasFailed else { return [] }
if isReturning { return [.cancelReturn] }
if wasInterrupted { return [] }
return [isPaused ? .resume : .pause, .returnHome]
}
private var simulatedPhase: String {
if hasFailed { return "failed" }
if isReturning { return "returning" }
if wasInterrupted { return "failed" }
if isPaused { return "paused" }
@@ -380,7 +441,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
}
}
/// 召唤只接受同一模拟任务且禁止重启,不产生真实设备操作。
/// 首次召唤或失败重召唤只接受同一模拟任务,不产生真实设备操作。
private struct ShootBody: Decodable {
let id: Int
let restart: Bool
@@ -1,11 +1,13 @@
import SnapKit
import UIKit
/// 对齐体验网页的任务失败组合:警示、原因、排查提示、重召占位及设备提示。
/// 对齐体验网页的任务失败组合:警示、原因、排查提示、重召或刷新操作及设备提示。
@MainActor
final class DroneDockTaskFailureView: UIView {
/// 点击原因区域查看完整后端说明,页面无需额外占用一个详情按钮。
var onDetails: (() -> Void)?
/// 将重召唤或结果核对操作交给任务页,视图不直接发送请求。
var onPrimaryAction: (() -> Void)?
/// 内部排版参考比例,不对视图或点击区域使用整体缩放。
private(set) var effectiveScale: CGFloat = 1
/// 当前是否使用适配固定小高度的紧凑排版。
@@ -44,13 +46,16 @@ final class DroneDockTaskFailureView: UIView {
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 更新真实失败原因及不可重召原因,不把开始拍摄许可当作重召许可。
func apply(_ value: DroneDockTaskPresentation) {
func apply(_ value: DroneDockTaskPresentation, isRefreshing: Bool = false) {
presentation = value
titleLabel.text = value.title
let reason = DroneDockHomeMetric.usableText(value.message).flatMap { $0 == "—" ? nil : $0 }
?? "服务端暂未提供具体原因"
reasonLabel.text = reason.hasPrefix("失败原因:") ? reason : "失败原因:\(reason)"
noteLabel.text = value.actionNote ?? "暂不可重新召唤,请返回准备页确认设备状态"
noteLabel.text = value.actionNote ?? (value.action == .refresh ? "请核对原任务状态,勿重复召唤" : "")
retryButton.configuration?.title = value.actionTitle
retryButton.configuration?.image = UIImage(systemName: value.action == .refresh ? "arrow.clockwise" : "arrow.triangle.2.circlepath")
retryButton.isEnabled = value.isActionEnabled && !isRefreshing
notice.accessibilityLabel = [value.title, reasonLabel.text, adviceLabel.text].compactMap { $0 }.joined(separator: "。")
setNeedsLayout()
}
@@ -107,11 +112,12 @@ final class DroneDockTaskFailureView: UIView {
configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8)
retryButton.configuration = configuration
retryButton.configurationUpdateHandler = { button in
button.configuration?.baseForegroundColor = UIColor(hex: 0x939CB0)
button.configuration?.background.backgroundColor = UIColor(hex: 0xE8EBF1)
button.configuration?.baseForegroundColor = button.isEnabled ? .white : UIColor(hex: 0x939CB0)
button.configuration?.background.backgroundColor = button.isEnabled ? DroneDockStyle.primary : UIColor(hex: 0xE8EBF1)
}
retryButton.isEnabled = false
retryButton.accessibilityIdentifier = "drone.task.remote.failureRetry"
retryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
}
private func setupConstraints() {
@@ -205,4 +211,9 @@ final class DroneDockTaskFailureView: UIView {
}
@objc private func showDetails() { onDetails?() }
@objc private func primaryTapped() {
guard retryButton.isEnabled else { return }
onPrimaryAction?()
}
}
@@ -0,0 +1,143 @@
import AVFoundation
import SnapKit
import UIKit
/// 固定图传区域:展示接口状态或明确标记的本地样片,不自行发请求或读取远程视频。
@MainActor
final class DroneDockTaskLiveView: UIView {
/// 用户主动获取或重试图传信息,具体请求由控制器协调。
var onRequest: (() -> Void)?
private let playerLayer = AVPlayerLayer()
private let titleLabel = DroneDockStyle.label(size: 15, weight: .medium, color: .white)
private let messageLabel = DroneDockStyle.label(size: 12, color: .lightGray)
private let sourceLabel = DroneDockStyle.label(size: 11, weight: .medium, color: .white)
private let requestButton = UIButton(type: .system)
private let labels = UIStackView()
private var player: AVQueuePlayer?
private var looper: AVPlayerLooper?
private var requestedURL: URL?
private var activeURL: URL?
private var isPlaybackActive = false
/// 保留原任务页图传区域的访问标识,外部负责 16:9 约束。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 根据外部固定容器尺寸更新播放器画面,不改变任务布局。
override func layoutSubviews() {
super.layoutSubviews()
CATransaction.begin()
CATransaction.setDisableActions(true)
playerLayer.frame = bounds
CATransaction.commit()
}
/// 在明确时机应用模型;远程 URL 即使错误传入也不会创建播放器。
func apply(_ model: DroneDockLiveViewModel) {
titleLabel.text = model.title
messageLabel.text = model.message
requestButton.setTitle(model.actionTitle, for: .normal)
requestButton.isHidden = model.actionTitle == nil
requestButton.isEnabled = model.canLoad
requestedURL = model.playbackURL.flatMap { $0.isFileURL ? $0 : nil }
let hasLocalPreview = requestedURL != nil
sourceLabel.text = hasLocalPreview ? "本地模拟画面 · 未连接无人机" : nil
sourceLabel.isHidden = !hasLocalPreview
titleLabel.isHidden = hasLocalPreview
messageLabel.isHidden = hasLocalPreview
accessibilityLabel = hasLocalPreview ? sourceLabel.text : "\(model.title),\(model.message)"
updatePlayback()
}
/// 页面离开或进入后台立即释放播放器;回来后仅恢复已经明确注入的本地来源。
func setPlaybackActive(_ active: Bool) {
isPlaybackActive = active
updatePlayback()
}
private func setupUI() {
backgroundColor = UIColor(hex: 0x171B22)
clipsToBounds = true
accessibilityIdentifier = "drone.task.remote.feedPlaceholder"
layer.addSublayer(playerLayer)
playerLayer.videoGravity = .resizeAspect
titleLabel.textAlignment = .center
messageLabel.textAlignment = .center
messageLabel.numberOfLines = 2
messageLabel.accessibilityIdentifier = "drone.task.remote.live.status"
titleLabel.accessibilityIdentifier = "drone.task.remote.live.title"
sourceLabel.accessibilityIdentifier = "drone.task.remote.live.source"
sourceLabel.backgroundColor = UIColor.black.withAlphaComponent(0.65)
sourceLabel.textAlignment = .center
sourceLabel.layer.cornerRadius = 4
sourceLabel.clipsToBounds = true
sourceLabel.isHidden = true
requestButton.tintColor = .white
requestButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
requestButton.backgroundColor = UIColor.black.withAlphaComponent(0.45)
requestButton.layer.cornerRadius = 6
requestButton.accessibilityIdentifier = "drone.task.remote.live.request"
requestButton.addTarget(self, action: #selector(requestTapped), for: .touchUpInside)
labels.axis = .vertical
labels.spacing = 8
labels.alignment = .fill
labels.addArrangedSubview(titleLabel)
labels.addArrangedSubview(messageLabel)
addSubview(labels)
addSubview(sourceLabel)
addSubview(requestButton)
}
private func setupConstraints() {
labels.snp.makeConstraints { make in
make.centerY.equalToSuperview().offset(-15)
make.leading.trailing.equalToSuperview().inset(20)
}
requestButton.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.bottom.equalToSuperview().inset(12)
make.width.greaterThanOrEqualTo(150)
make.height.equalTo(36)
}
sourceLabel.snp.makeConstraints { make in
make.top.leading.equalToSuperview().inset(10)
make.height.equalTo(24)
make.width.equalTo(200)
}
}
private func updatePlayback() {
guard isPlaybackActive, let requestedURL, requestedURL.isFileURL else {
releasePlayer()
return
}
guard activeURL != requestedURL || player == nil else { return }
releasePlayer()
let queue = AVQueuePlayer()
queue.isMuted = true
looper = AVPlayerLooper(player: queue, templateItem: AVPlayerItem(url: requestedURL))
player = queue
activeURL = requestedURL
playerLayer.player = queue
queue.play()
}
private func releasePlayer() {
player?.pause()
looper?.disableLooping()
player?.removeAllItems()
playerLayer.player = nil
looper = nil
player = nil
activeURL = nil
}
@objc private func requestTapped() { onRequest?() }
}
@@ -55,7 +55,7 @@ final class DroneDockTaskStatusView: UIView {
contentStack.isHidden = isFailure
failureView.isHidden = !isFailure
if isFailure {
failureView.apply(presentation)
failureView.apply(presentation, isRefreshing: isRefreshing)
setNeedsLayout()
return
}
@@ -94,6 +94,7 @@ final class DroneDockTaskStatusView: UIView {
addSubview(failureView)
failureView.isHidden = true
failureView.onDetails = { [weak self] in self?.onDetails?() }
failureView.onPrimaryAction = { [weak self] in self?.onPrimaryAction?() }
contentStack.axis = .vertical
contentStack.alignment = .fill
contentStack.spacing = 10