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
@@ -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