Files
suixinkan_uikit/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift
T
lujiuyin cd90c3648b 适配上传中订单并完善机巢操作与订阅兜底
支持订单状态 25 和持续拍摄、交付确认;安全指令点击后直接提交;鉴权超时保留 HTTP 兜底并退避换票重连。补充对应隔离回归测试。
2026-11-05 12:35:58 +08:00

983 lines
49 KiB
Swift

import SnapKit
import UIKit
/// 拍摄任务页:前台优先订阅快照、异常时 HTTP 兜底;自动开启图传,飞控仍由用户操作。
@MainActor
final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
let viewModel: DroneDockShootingTaskViewModel
/// 图传使用独立状态,刷新与播放不会影响任务阶段或固定布局。
let liveViewModel: DroneDockLiveViewModel
private let realtimeSession: DroneDockShootingRealtimeSession?
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: DroneDockTaskLiveView
private let telemetryView = DroneShootingTaskTelemetryView()
private let statusView = DroneDockTaskStatusView()
private let safetyView = DroneDockTaskSafetyView()
private var summaryHeight: Constraint?
private var safetyHeight: Constraint?
private var compactLayout: Bool?
private var bottomInset: CGFloat = -1
private let materialsControllerFactory: @MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private let simulationRecordsProvider: (@MainActor () -> String)?
private let shootingPollDelay: @Sendable (UInt64) async throws -> Void
private var pollTask: Task<Void, Never>?
private var pollGeneration = 0
private var refreshTask: Task<Void, Never>?
private var startTask: Task<Void, Never>?
private var commandTasks: [UUID: Task<Void, Never>] = [:]
private var commandAttemptIDs: [DroneDockSafetyCommand: UUID] = [:]
private var submittingCommands: Set<DroneDockSafetyCommand> = []
private var resummonTask: Task<Void, Never>?
private var liveTask: Task<Void, Never>?
private var liveParameterTask: Task<Void, Never>?
private let liveParameterDelay: @Sendable (TimeInterval) async throws -> Void
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: Bool { !submittingCommands.isEmpty }
private var isResummoningAction = false
private var wasRealtimeLive = false
private let coverURL: URL?
private var stoppedLiveExecutionTitles: [String: String] = [:]
private var displayedCompletionIDs: Set<String> = []
private var completionNotice: DroneDockRecordingCompletionView?
private let countdownDelay: @Sendable () async throws -> Void
private var countdownTask: Task<Void, Never>?
private var countdownGeneration = 0
private var diagnosticStateData: [String: Data] = [:]
private var countdownDiagnosticKey: String?
private var entrySource = "existing_task_or_direct"
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
init(viewModel: DroneDockShootingTaskViewModel,
liveViewModel: DroneDockLiveViewModel? = nil,
livePlayer: (any DroneDockLivePlaying)? = nil,
coverURL: URL? = nil,
realtimeSession: DroneDockShootingRealtimeSession? = nil,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
simulationRecordsProvider: (@MainActor () -> String)? = nil,
shootingPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) },
liveParameterDelay: @escaping @Sendable (TimeInterval) async throws -> Void = { try await Task.sleep(for: .seconds($0)) },
countdownDelay: @escaping @Sendable () async throws -> Void = { try await Task.sleep(for: .seconds(1)) }) {
self.viewModel = viewModel
self.coverURL = coverURL
self.feedPlaceholder = livePlayer.map { DroneDockTaskLiveView(rtcPlayer: $0) } ?? DroneDockTaskLiveView()
self.realtimeSession = realtimeSession
self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel(
context: viewModel.context, taskID: viewModel.taskID,
currentContext: { DroneDockHomeViewController.currentContext() })
self.simulationRecordsProvider = simulationRecordsProvider
self.shootingPollDelay = shootingPollDelay
self.liveParameterDelay = liveParameterDelay
self.countdownDelay = countdownDelay
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
context: context, order: order,
service: DroneDockMaterialsAPI(client: NetworkServices.shared.apiClient),
currentContext: { DroneDockHomeViewController.currentContext() }))
}
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
realtimeSession?.onSnapshot = { [weak self] snapshot in
guard let self, self.isPageVisible, self.isApplicationActive else { return .invalid }
let result = self.viewModel.applyTaskSnapshot(snapshot, source: .webSocket)
self.applySnapshot()
return result
}
realtimeSession?.onConnectionState = { [weak self] state in
self?.connectionStateChanged(state)
}
realtimeSession?.onHTTPSeedRequired = { [weak self] in
self?.refreshTaskIfVisible(isPolling: true)
}
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 仅记录导航来源与上游诊断会话,不改变任务身份、页面加载或设备操作。
func recordNavigationEntry(source: String, fields: [String: Any] = [:]) {
entrySource = source
logEvent("navigation.task_entry", fields: fields)
}
deinit {
pollTask?.cancel()
refreshTask?.cancel()
startTask?.cancel()
commandTasks.values.forEach { $0.cancel() }
resummonTask?.cancel()
liveTask?.cancel()
liveParameterTask?.cancel()
countdownTask?.cancel()
NotificationCenter.default.removeObserver(self)
}
/// 使用常规导航返回准备页,不劫持返回手势或自动创建任务。
override func setupNavigationBar() {
title = simulationRecordsProvider == nil ? "拍摄任务" : "拍摄任务 · 本地模拟"
navigationItem.backButtonDisplayMode = .minimal
let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain,
target: self, action: #selector(refreshTriggered))
refresh.accessibilityLabel = "刷新任务状态"
refresh.accessibilityIdentifier = "drone.task.remote.navigationRefresh"
navigationItem.rightBarButtonItem = refresh
if simulationRecordsProvider != nil {
let records = UIBarButtonItem(image: UIImage(systemName: "doc.text"), style: .plain,
target: self, action: #selector(showSimulationRecords))
records.accessibilityLabel = "查看模拟接口回执"
records.accessibilityIdentifier = "drone.task.mock.recordsButton"
navigationItem.rightBarButtonItems = [refresh, records]
}
}
/// 顶部、中间状态和安全控制分开布局,状态切换不影响外部区域大小。
override func setupUI() {
view.backgroundColor = .white
topView.accessibilityIdentifier = "drone.task.remote.top"
summaryView.accessibilityIdentifier = "drone.task.remote.summary"
statusView.accessibilityIdentifier = "drone.task.remote.stateContainer"
safetyView.accessibilityIdentifier = "drone.task.remote.safety"
view.addSubview(topView)
view.addSubview(statusView)
view.addSubview(safetyView)
topView.addSubview(summaryView)
summaryView.addSubview(taskTitleLabel)
summaryView.addSubview(subtitleLabel)
taskTitleLabel.numberOfLines = 1
taskTitleLabel.lineBreakMode = .byTruncatingTail
taskTitleLabel.accessibilityIdentifier = "drone.task.remote.title"
subtitleLabel.numberOfLines = 1
subtitleLabel.lineBreakMode = .byTruncatingTail
subtitleLabel.accessibilityIdentifier = "drone.task.remote.subtitle"
topView.addSubview(feedPlaceholder)
topView.addSubview(telemetryView)
telemetryView.accessibilityIdentifier = "drone.task.remote.telemetry"
telemetryView.configureFixedLayout(compact: false)
applySnapshot()
}
/// 图传保持 16:9,底部贴安全区,中间占满剩余空间且没有滚动容器。
override func setupConstraints() {
topView.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.equalToSuperview()
}
summaryView.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
summaryHeight = make.height.equalTo(60).constraint
}
taskTitleLabel.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(16)
make.bottom.equalTo(summaryView.snp.centerY).offset(-1)
}
subtitleLabel.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(16)
make.top.equalTo(summaryView.snp.centerY).offset(2)
}
feedPlaceholder.snp.makeConstraints { make in
make.top.equalTo(summaryView.snp.bottom)
make.leading.trailing.equalToSuperview()
make.height.equalTo(feedPlaceholder.snp.width).multipliedBy(9.0 / 16.0)
}
telemetryView.snp.makeConstraints { make in
make.top.equalTo(feedPlaceholder.snp.bottom)
make.leading.trailing.bottom.equalToSuperview()
}
safetyView.snp.makeConstraints { make in
make.leading.trailing.bottom.equalToSuperview()
safetyHeight = make.height.equalTo(104).constraint
}
statusView.snp.makeConstraints { make in
make.top.equalTo(topView.snp.bottom)
make.bottom.equalTo(safetyView.snp.top)
make.leading.trailing.equalToSuperview()
}
}
/// 只按设备可用尺寸调整固定区域,数据、错误和加载状态不会改变它们的高度。
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
defer { recordRenderedState() }
let availableHeight = view.bounds.height - view.safeAreaInsets.top - view.safeAreaInsets.bottom
let compact = availableHeight < 680
let inset = view.safeAreaInsets.bottom
guard compactLayout != compact || bottomInset != inset else { return }
compactLayout = compact
bottomInset = inset
summaryHeight?.update(offset: compact ? 44 : 60)
safetyHeight?.update(offset: (compact ? 90 : 104) + inset)
telemetryView.configureFixedLayout(compact: compact)
safetyView.configure(compact: compact)
taskTitleLabel.font = .systemFont(ofSize: compact ? 16 : 17, weight: .semibold)
}
/// 绑定页面操作与主线程播放回调;飞控仍受构建策略、服务注入及任务门禁约束。
override func bindActions() {
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() }
feedPlaceholder.onDiagnosticEvent = { [weak self] event, fields in self?.logEvent(event, fields: fields) }
feedPlaceholder.onPlaybackEvent = { [weak self] event, sessionID in
guard let self else { return }
self.recordPlaybackEvent(event, sessionID: sessionID)
guard self.isPageVisible, self.isApplicationActive else { return }
self.liveViewModel.receivePlaybackEvent(event, sessionID: sessionID)
if self.liveViewModel.playbackSessionID == nil {
self.liveParameterTask?.cancel()
self.liveParameterTask = nil
}
self.applySnapshot()
}
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
name: UIApplication.didBecomeActiveNotification, object: nil)
}
/// 完整进入任务页先读取一次,再启动同一任务的只读订阅。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isPageVisible = true
isApplicationActive = UIApplication.shared.applicationState == .active
logEvent("page.appeared", fields: ["navigation_stack": navigationController?.viewControllers.map { String(describing: type(of: $0)) } ?? []])
refreshTaskIfVisible()
refreshLiveIfVisible(automatically: true)
}
/// 离页立即取消未完成的读取,使迟到响应失效。
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
dismissCompletionNotice()
logEvent("page.disappeared", fields: ["moving_from_parent": isMovingFromParent, "being_dismissed": isBeingDismissed])
cancelRefresh()
stopLive()
}
private func applySnapshot() {
guard isViewLoaded else { return }
if viewModel.shouldStopLiveReception {
stoppedLiveExecutionTitles[viewModel.recordingExecutionID] = viewModel.isRecordingFinished
? "拍摄已完成" : "无人机已返回机巢"
}
let stoppedLiveTitle = stoppedLiveExecutionTitles[viewModel.recordingExecutionID]
let liveReceptionEnded = stoppedLiveTitle != nil
if !viewModel.shouldPresentRecordingCompletion { dismissCompletionNotice() }
if liveReceptionEnded, liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil {
stopLive()
}
feedPlaceholder.showRecordingCover(liveReceptionEnded, url: coverURL,
title: stoppedLiveTitle ?? "拍摄已完成")
let loading = (viewModel.response == nil && (isRequesting || viewModel.isLoading))
|| isStartingAction || viewModel.isStartingShooting
|| isResummoningAction || viewModel.isResummoning
feedPlaceholder.apply(liveViewModel)
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive && !liveReceptionEnded)
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle + (viewModel.response?.metricsStale == true ? " · 读数已过期" : "")
let telemetry = viewModel.telemetry
telemetryView.apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
telemetry.rainText, telemetry.signalText, telemetry.satelliteText],
isStale: viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric", preservingStaleValues: true)
let presentation = viewModel.presentation
setPageLoading(viewModel.response == nil && loading && presentation.phase != .navigating)
let value = loading && viewModel.response == nil && presentation.phase != .navigating ? DroneDockTaskPresentation(
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : presentation
let primaryActionLoading = value.action == .resume
&& (submittingCommands.contains(.resume) || viewModel.isCommandLoading(.resume))
|| value.action == .start && (isStartingAction || viewModel.isStartingShooting)
statusView.apply(value, isRefreshing: loading, isPrimaryActionLoading: primaryActionLoading)
updateArrivalCountdown()
safetyView.apply(model: viewModel, isSimulation: simulationRecordsProvider != nil,
isInteractive: isPageVisible && isApplicationActive && !loading,
submittingCommands: submittingCommands)
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItems?.forEach { $0.isEnabled = isPageVisible && isApplicationActive && !loading }
navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil
recordRenderedState()
presentCompletionNoticeIfNeeded()
refreshLiveIfVisible(automatically: true)
}
/// 倒计时只更新开拍按钮文案;网络读取、飞控及后端阶段仍由原有流程驱动。
private func updateArrivalCountdown() {
let seconds = viewModel.countdownRemainingSeconds
statusView.updateCountdown(seconds: seconds)
recordCountdownState(seconds)
guard isPageVisible, isApplicationActive, let seconds, seconds > 0 else {
stopArrivalCountdown()
return
}
guard countdownTask == nil else { return }
countdownGeneration += 1
let generation = countdownGeneration
let delay = countdownDelay
countdownTask = Task { @MainActor [weak self] in
while !Task.isCancelled {
do { try await delay() } catch { return }
guard let self, !Task.isCancelled, self.countdownGeneration == generation,
self.isPageVisible, self.isApplicationActive else { return }
let remaining = self.viewModel.countdownRemainingSeconds
self.statusView.updateCountdown(seconds: remaining)
self.recordCountdownState(remaining)
if remaining == nil || remaining == 0 {
self.countdownTask = nil
return
}
}
}
}
private func stopArrivalCountdown() {
countdownGeneration += 1
countdownTask?.cancel()
countdownTask = nil
}
private func presentCompletionNoticeIfNeeded() {
let id = viewModel.recordingExecutionID
guard viewModel.shouldPresentRecordingCompletion, isPageVisible, isApplicationActive, view.window != nil,
presentedViewController == nil, completionNotice == nil, !displayedCompletionIDs.contains(id) else { return }
displayedCompletionIDs.insert(id)
let notice = DroneDockRecordingCompletionView()
completionNotice = notice
logEvent("ui.completion_notice.shown")
notice.onLater = { [weak self] in
self?.logEvent("ui.completion_notice.later")
self?.dismissCompletionNotice()
}
notice.onViewMaterials = { [weak self] in
guard let self, self.isPageVisible, self.isApplicationActive,
self.viewModel.recordingExecutionID == id else { return }
self.logEvent("ui.completion_notice.view_materials")
self.dismissCompletionNotice()
self.openMaterials()
}
let container = navigationController?.view ?? view!
container.addSubview(notice)
notice.snp.makeConstraints { $0.edges.equalToSuperview() }
UIAccessibility.post(notification: .screenChanged, argument: notice)
}
private func dismissCompletionNotice() {
if completionNotice != nil { logEvent("ui.completion_notice.dismissed") }
completionNotice?.removeFromSuperview()
completionNotice = nil
}
private func openMaterials() {
guard isPageVisible, isApplicationActive, presentedViewController == nil,
viewModel.presentation.action == .materials, viewModel.presentation.isActionEnabled,
let navigationController, navigationController.topViewController === self else { return }
dismissCompletionNotice()
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
}
private func primaryActionTriggered() {
logEvent("action.primary", fields: ["action": String(describing: viewModel.presentation.action),
"enabled": viewModel.presentation.isActionEnabled])
guard isPageVisible, isApplicationActive,
!isStartingAction, !viewModel.isStartingShooting,
!isResummoningAction, !viewModel.isResummoning else {
logEvent("action.primary.rejected", fields: ["reason": "page_or_submission_guard", "ui": statusView.diagnosticFields])
return
}
let state = viewModel.presentation
guard state.isActionEnabled else {
logEvent("action.primary.rejected", fields: ["reason": "presentation_action_disabled", "ui": statusView.diagnosticFields])
return
}
switch state.action {
case .refresh:
refreshTaskIfVisible()
case .start:
startShootingIfAllowed()
case .retry:
resummonIfAllowed()
case .materials:
openMaterials()
case .resume:
safetyCommandTriggered(.resume)
case .none:
break
}
}
private func showStatusDetails() {
guard isPageVisible, isApplicationActive, presentedViewController == nil else { return }
let state = viewModel.presentation
var texts = [state.title, state.message, state.deviceStatus].filter { !$0.isEmpty && $0 != "—" }
if viewModel.response != nil, let error = viewModel.errorMessage {
texts.append("刷新失败,当前显示上次数据:\(error)")
}
if case .fallback(let message) = realtimeSession?.state {
texts.append("实时连接暂不可用,已使用接口更新:\(message)")
}
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)
alert.addAction(UIAlertAction(title: "关闭", style: .cancel))
present(alert, animated: true)
}
/// 前台可见时串行读取;轮询失败保留旧快照,下个周期再读,不重复弹出提示。
private func refreshTaskIfVisible(isPolling: Bool = false) {
guard isPageVisible, isApplicationActive, viewModel.readAccessError == nil, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting,
!isResummoningAction, !viewModel.isResummoning else { return }
cancelScheduledPoll()
requestGeneration &+= 1
let generation = requestGeneration
let httpSeedRequest = realtimeSession?.pendingHTTPSeedRequest
isRequesting = true
applySnapshot()
refreshTask = Task { @MainActor [weak self] in
guard let self else { return }
let seedResult: DroneDockHTTPSnapshotResult?
if httpSeedRequest != nil { seedResult = await self.viewModel.refreshForRealtimeSeed() }
else { await self.viewModel.refresh(); seedResult = nil }
guard self.isPageVisible, self.isApplicationActive,
self.requestGeneration == generation, !Task.isCancelled else { return }
self.refreshTask = nil
self.isRequesting = false
if let httpSeedRequest, let seedResult {
self.realtimeSession?.acceptHTTPSeed(seedResult, requestID: httpSeedRequest)
}
self.applySnapshot()
if self.viewModel.canContinuePolling { self.realtimeSession?.start() }
else { self.realtimeSession?.stop() }
// 无缓存提示可能在旧 HTTP 读取途中到达;旧请求不充当首包,结束后再串行补读。
if let pendingSeed = self.realtimeSession?.pendingHTTPSeedRequest, pendingSeed != httpSeedRequest,
self.viewModel.canContinuePolling {
self.refreshTaskIfVisible(isPolling: true)
return
}
self.scheduleNextPoll()
if !isPolling, self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.showToast("刷新失败,当前显示上次数据:\(error)")
}
}
}
/// 每次读取或控制流程结束后仅安排一个可取消的延时,不持有页面等待计时结束。
private func scheduleNextPoll() {
cancelScheduledPoll()
guard isPageVisible, isApplicationActive, viewModel.canContinuePolling,
realtimeSession?.state != .live,
!isRequesting, !isStartingAction, !isResummoningAction else { return }
let generation = pollGeneration
let delay = shootingPollDelay
let interval = viewModel.pollIntervalNanoseconds
pollTask = Task { @MainActor [weak self] in
do { try await delay(interval) } catch { return }
guard !Task.isCancelled, let self, self.pollGeneration == generation else { return }
self.pollTask = nil
self.refreshTaskIfVisible(isPolling: true)
}
}
private func cancelScheduledPoll() {
pollGeneration &+= 1
pollTask?.cancel()
pollTask = nil
}
/// 用户操作优先于后台读取;不停止 Socket,也不解除任何已提交操作的防重锁。
private func cancelPendingReadForAction() {
cancelScheduledPoll()
requestGeneration &+= 1
refreshTask?.cancel()
refreshTask = nil
isRequesting = false
viewModel.invalidatePendingRefresh()
}
private func cancelRefresh() {
stopArrivalCountdown()
wasRealtimeLive = false
realtimeSession?.stop()
cancelScheduledPoll()
requestGeneration &+= 1
refreshTask?.cancel()
refreshTask = nil
startTask?.cancel()
startTask = nil
commandTasks.values.forEach { $0.cancel() }
commandTasks.removeAll()
commandAttemptIDs.removeAll()
submittingCommands.removeAll()
resummonTask?.cancel()
resummonTask = nil
isResummoningAction = false
isStartingAction = false
isRequesting = false
viewModel.invalidate(preservingSnapshot: true)
applySnapshot()
}
private func connectionStateChanged(_ state: DroneDockShootingRealtimeSession.State) {
logChangedEvent("page.realtime_state", fields: ["state": String(describing: state)])
guard isPageVisible, isApplicationActive else { return }
switch state {
case .live:
wasRealtimeLive = true
cancelScheduledPoll()
applySnapshot()
case .denied(let message):
wasRealtimeLive = false
cancelScheduledPoll()
requestGeneration &+= 1
refreshTask?.cancel()
refreshTask = nil
isRequesting = false
viewModel.stopReading(message: message)
applySnapshot()
showToast(message)
case .fallback:
// 断线立即尝试一次 GET;已有读/写流程则由其完成回调安排下一轮,绝不并发。
let shouldRefreshImmediately = wasRealtimeLive
wasRealtimeLive = false
if shouldRefreshImmediately { refreshTaskIfVisible(isPolling: true) }
else if pollTask == nil { scheduleNextPoll() }
case .connecting:
// 重连不能不断重置 HTTP 计时,否则长时间异常会饿死兜底请求。
if pollTask == nil { scheduleNextPoll() }
case .stopped: wasRealtimeLive = false
}
}
/// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。
private func startShootingIfAllowed() {
guard !isStartingAction, !isSendingSafetyAction, !isResummoningAction, viewModel.canStartShooting else { return }
cancelPendingReadForAction()
let generation = requestGeneration
isStartingAction = true
applySnapshot()
startTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.startShooting { [weak self] in self?.applySnapshot() }
guard self.isPageVisible, self.isApplicationActive,
self.requestGeneration == generation, !Task.isCancelled else { return }
self.startTask = nil
self.isStartingAction = false
self.applySnapshot()
self.scheduleNextPoll()
if let error = self.viewModel.startErrorMessage {
self.showToast(error)
} else if let error = self.viewModel.errorMessage {
self.showToast("开始请求已受理,状态刷新失败:\(error)")
}
}
}
/// 重召唤使用原任务 ID,回执后再查询状态,避免从受理结果推断设备已到达。
private func resummonIfAllowed() {
guard isPageVisible, isApplicationActive,
!isResummoningAction, !isStartingAction, !isSendingSafetyAction,
viewModel.canResummon else { return }
cancelPendingReadForAction()
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()
self.scheduleNextPoll()
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(self.simulationRecordsProvider != nil
? "本地模拟重召唤已受理,未发送设备指令" : "重召唤请求已受理,请等待任务状态更新")
} else if let error = self.viewModel.errorMessage {
self.showToast(error)
}
}
}
/// 可见且活跃时自动开启一次;失败可手动重试,不随 shooting/Socket 刷新重复请求。
private func refreshLiveIfVisible(automatically: Bool = false, keepingPlayback: Bool = false) {
guard viewModel.response != nil, viewModel.readAccessError == nil,
stoppedLiveExecutionTitles[viewModel.recordingExecutionID] == nil, !viewModel.shouldStopLiveReception else { return }
guard !automatically || liveViewModel.loadsAutomatically else { return }
guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return }
liveParameterTask?.cancel()
liveParameterTask = nil
logEvent("live.request", fields: ["automatic": automatically, "keeping_playback": keepingPlayback])
liveGeneration &+= 1
let generation = liveGeneration
liveTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.liveViewModel.refresh(keepingPlayback: keepingPlayback) { [weak self] in self?.applySnapshot() }
guard self.liveGeneration == generation, self.isPageVisible, self.isApplicationActive,
!Task.isCancelled else { return }
self.liveTask = nil
self.applySnapshot()
self.scheduleLiveParameterRefresh()
}
}
/// 缺少第二路或凭证临期才重新取参数;补流/续期保留健康房间,不随 shooting 轮询。
private func scheduleLiveParameterRefresh() {
liveParameterTask?.cancel()
liveParameterTask = nil
guard isPageVisible, isApplicationActive, let interval = liveViewModel.nextParameterRefreshDelay else { return }
let generation = liveGeneration
let delay = liveParameterDelay
liveParameterTask = Task { @MainActor [weak self] in
do { try await delay(interval) } catch { return }
guard let self, !Task.isCancelled, self.liveGeneration == generation,
self.isPageVisible, self.isApplicationActive,
self.liveViewModel.nextParameterRefreshDelay != nil else { return }
self.liveParameterTask = nil
self.refreshLiveIfVisible(keepingPlayback: true)
}
}
/// 离页或进入后台立即释放播放器,使旧图传响应无法恢复播放。
private func stopLive() {
if liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil {
logEvent("live.reception_stopping", fields: ["recording_finished": viewModel.isRecordingFinished,
"task_requires_stop": viewModel.shouldStopLiveReception, "ui": feedPlaceholder.diagnosticFields])
}
liveGeneration &+= 1
liveParameterTask?.cancel()
liveParameterTask = nil
liveTask?.cancel()
liveTask = nil
liveViewModel.invalidate()
feedPlaceholder.setPlaybackActive(false)
feedPlaceholder.apply(liveViewModel)
}
/// 安全动作点击后直接提交,沿用当前任务的权限与防重校验。
private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) {
logEvent("action.safety", fields: ["command": command.rawValue, "enabled": viewModel.canSendCommand(command)])
guard isPageVisible, isApplicationActive,
presentedViewController == nil, !submittingCommands.contains(command), !isStartingAction,
!isResummoningAction, viewModel.canSendCommand(command) else {
logSafetyRejection(command, stage: "tap")
return
}
sendSafetyCommand(command)
}
/// 同步锁只覆盖同一按钮;不同安全动作可各自等待,设备确认由 ViewModel 和快照处理。
private func sendSafetyCommand(_ command: DroneDockSafetyCommand) {
guard isPageVisible, isApplicationActive,
!submittingCommands.contains(command), !isStartingAction, !isResummoningAction,
viewModel.canSendCommand(command) else {
logSafetyRejection(command, stage: "submit")
return
}
cancelPendingReadForAction()
let attemptID = UUID()
logEvent("action.safety.submitting", fields: ["command": command.rawValue, "ui_attempt_id": attemptID.uuidString])
commandAttemptIDs[command] = attemptID
submittingCommands.insert(command)
applySnapshot()
commandTasks[attemptID] = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.sendCommand(command) { [weak self] in
guard let self, self.commandAttemptIDs[command] == attemptID else { return }
// ViewModel 已建立本次操作后,加载状态完全交由其管理;后续只读回查不延长动画。
self.submittingCommands.remove(command)
self.applySnapshot()
}
self.commandTasks.removeValue(forKey: attemptID)
guard self.isPageVisible, self.isApplicationActive,
self.commandAttemptIDs[command] == attemptID, !Task.isCancelled else { return }
self.commandAttemptIDs.removeValue(forKey: command)
self.submittingCommands.remove(command)
self.applySnapshot()
self.scheduleNextPoll()
if let error = self.viewModel.commandErrorMessage(for: command) {
self.showToast(error)
}
}
}
/// 模拟入口专用记录页,内容由内存传输提供,不请求后端日志或设备。
@objc private func showSimulationRecords() {
guard let simulationRecordsProvider, presentedViewController == nil else { return }
let controller = DroneDockSimulationRecordsViewController(records: simulationRecordsProvider())
present(UINavigationController(rootViewController: controller), animated: true)
}
@objc private func refreshTriggered() {
logEvent("action.refresh")
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else {
logEvent("action.refresh.rejected", fields: ["reason": "page_or_read_guard", "read_in_progress": isRequesting || viewModel.isLoading])
return
}
refreshTaskIfVisible()
}
@objc private func applicationWillResignActive() {
isApplicationActive = false
logEvent("app.inactive")
cancelRefresh()
stopLive()
}
@objc private func applicationDidBecomeActive() {
guard !isApplicationActive else { return }
isApplicationActive = true
logEvent("app.active")
refreshTaskIfVisible()
refreshLiveIfVisible(automatically: true)
}
private func logEvent(_ name: String, fields: [String: Any] = [:]) {
var fields = fields
fields["source"] = simulationRecordsProvider == nil ? "task_page" : "local_simulation"
fields["entry_source"] = entrySource
fields["page_visible"] = isPageVisible
fields["app_active"] = isApplicationActive
fields["view_in_window"] = isViewLoaded && view.window != nil
viewModel.recordTaskEvent(name, fields: fields)
}
/// 去重只比较 UI 可观察值,不把快照版本或逐秒计时加入比较。
private func logChangedEvent(_ name: String, fields: [String: Any]) {
guard let data = try? JSONSerialization.data(withJSONObject: fields, options: [.sortedKeys]),
diagnosticStateData[name] != data else { return }
diagnosticStateData[name] = data
logEvent(name, fields: fields)
}
private func recordRenderedState() {
logChangedEvent("ui.render", fields: ["central": statusView.diagnosticFields,
"safety": safetyView.diagnosticFields, "page_visible": isPageVisible,
"app_active": isApplicationActive, "starting": isStartingAction || viewModel.isStartingShooting,
"resummoning": isResummoningAction || viewModel.isResummoning,
"submitting_commands": submittingCommands.map(\.rawValue).sorted()])
var liveFields = feedPlaceholder.diagnosticFields
switch liveViewModel.state {
case .idle: liveFields["state"] = "idle"
case .loading: liveFields["state"] = "loading"
case .connecting: liveFields["state"] = "connecting"
case .playing: liveFields["state"] = "playing"
case .localPreview: liveFields["state"] = "local_preview"
case .unavailable(let message): liveFields["state"] = "unavailable"; liveFields["reason"] = message
case .failed(let message): liveFields["state"] = "failed"; liveFields["reason"] = message
}
liveFields["active_role"] = liveViewModel.activeRole as Any? ?? NSNull()
liveFields["playback_session"] = liveViewModel.playbackSessionID?.uuidString as Any? ?? NSNull()
logChangedEvent("live.render", fields: liveFields)
}
private func recordCountdownState(_ seconds: Int?) {
let stage = !isPageVisible || !isApplicationActive || seconds == nil ? "hidden" : seconds == 0 ? "zero" : "running"
let key = viewModel.recordingExecutionID + ":" + stage
guard countdownDiagnosticKey != key else { return }
countdownDiagnosticKey = key
logEvent("ui.countdown", fields: ["state": stage, "remaining_seconds": seconds as Any? ?? NSNull(),
"execution_id": viewModel.recordingExecutionID])
}
private func recordPlaybackEvent(_ event: DroneDockLivePlaybackEvent, sessionID: UUID) {
var fields: [String: Any] = ["playback_session": sessionID.uuidString,
"page_session_valid": isPageVisible && isApplicationActive && liveViewModel.playbackSessionID == sessionID,
"previous_role": liveViewModel.activeRole as Any? ?? NSNull()]
let name: String
switch event {
case .firstFrame:
name = "live.first_frame"
fields["role"] = liveViewModel.rtcConfiguration?.role as Any? ?? NSNull()
case .sourceChanged(let role):
name = "live.source_changed"
fields["role"] = role as Any? ?? NSNull()
fields["fallback_to_airport"] = liveViewModel.activeRole == "drone" && role == "airport"
case .failed(let message): name = "live.receiver.failed"; fields["message"] = message
case .expired: name = "live.receiver.expired"
}
logChangedEvent(name, fields: fields)
}
private func logSafetyRejection(_ command: DroneDockSafetyCommand, stage: String) {
var reasons: [String] = []
if !isPageVisible { reasons.append("page_hidden") }
if !isApplicationActive { reasons.append("app_inactive") }
if stage == "tap", presentedViewController != nil { reasons.append("modal_presented") }
if submittingCommands.contains(command) { reasons.append("same_command_submitting") }
if isStartingAction { reasons.append("start_submitting") }
if isResummoningAction { reasons.append("resummon_submitting") }
if !viewModel.canSendCommand(command) { reasons.append("model_command_not_allowed") }
logEvent("action.safety.rejected", fields: ["command": command.rawValue, "stage": stage,
"reasons": reasons, "safety": safetyView.diagnosticFields])
}
}
/// 以可选择的 JSON 文本展示本地模拟请求与回执,避免与真实接口联调混淆。
@MainActor
final class DroneDockSimulationRecordsViewController: BaseViewController {
private let records: String
private let textView = UITextView()
/// 固定展示打开时的内存记录快照。
init(records: String) {
self.records = records
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() {
title = "本地模拟回执(未联网)"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: .done,
target: self, action: #selector(close))
}
override func setupUI() {
view.backgroundColor = .systemBackground
textView.isEditable = false
textView.font = .monospacedSystemFont(ofSize: 12, weight: .regular)
textView.text = records
textView.accessibilityIdentifier = "drone.task.mock.records"
textView.textContainerInset = UIEdgeInsets(top: 16, left: 12, bottom: 24, right: 12)
view.addSubview(textView)
}
override func setupConstraints() {
textView.snp.makeConstraints { make in make.edges.equalTo(view.safeAreaLayoutGuide) }
}
@objc private func close() { dismiss(animated: true) }
}
/// 固定底部的安全控制,文案来自本地阶段,操作许可统一由任务模型判断。
@MainActor
private final class DroneDockTaskSafetyView: UIView {
/// 将用户选择的白名单指令交给页面,不直接调用任何服务。
var onCommand: ((DroneDockSafetyCommand) -> Void)?
private let header = DroneDockStyle.label("安全控制", size: 11, color: DroneDockStyle.secondary)
private let pauseButton = DroneShootingTaskSafetyButton(symbol: "pause.circle", color: UIColor(hex: 0xEC982A), filled: true)
private let returnButton = DroneShootingTaskSafetyButton(symbol: "arrow.uturn.backward", color: UIColor(hex: 0xD85762), filled: false)
private let buttons = UIStackView()
private var headerTop: Constraint?
private var headerHeight: Constraint?
private var buttonGap: Constraint?
private var buttonHeight: Constraint?
/// 两个固定按钮实际显示的标题、字幕、启用和加载状态。
var diagnosticFields: [String: Any] {
["pause": pauseButton.diagnosticFields, "return_home": returnButton.diagnosticFields]
}
/// 复用安全按钮样式,初始没有状态数据时保持禁用。
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
let divider = UIView()
divider.backgroundColor = DroneDockStyle.border
addSubview(divider)
divider.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
make.height.equalTo(0.5)
}
header.textAlignment = .center
addSubview(header)
buttons.axis = .horizontal
buttons.spacing = 8
buttons.distribution = .fillEqually
buttons.addArrangedSubview(pauseButton)
buttons.addArrangedSubview(returnButton)
addSubview(buttons)
pauseButton.accessibilityIdentifier = "drone.task.remote.pause"
returnButton.accessibilityIdentifier = "drone.task.remote.return"
pauseButton.apply(title: "紧急暂停", subtitle: "暂不可用", enabled: false)
returnButton.apply(title: "立即返航", subtitle: "暂不可用", enabled: false)
pauseButton.addTarget(self, action: #selector(pauseTapped), for: .touchUpInside)
returnButton.addTarget(self, action: #selector(returnTapped), for: .touchUpInside)
header.snp.makeConstraints { make in
headerTop = make.top.equalToSuperview().offset(10).constraint
make.leading.trailing.equalToSuperview().inset(16)
headerHeight = make.height.equalTo(14).constraint
}
buttons.snp.makeConstraints { make in
buttonGap = make.top.equalTo(header.snp.bottom).offset(8).constraint
make.leading.trailing.equalToSuperview().inset(16)
buttonHeight = make.height.equalTo(62).constraint
}
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 两个按钮始终表示暂停与返航;已暂停、返航中和回巢使用本地文案,恢复入口位于中央。
func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool,
submittingCommands: Set<DroneDockSafetyCommand> = []) {
let phase = model.presentation.phase
var controlState = model.flightControlState
if model.response?.flightControl == nil {
switch phase {
case .paused: controlState = .paused
case .returning: controlState = .returning
case .returned: controlState = .returned
default: break
}
}
header.text = isSimulation ? "安全控制 · 本地模拟,不发送设备指令" : "安全控制"
for (button, command) in [(pauseButton, DroneDockSafetyCommand.pause), (returnButton, .returnHome)] {
var title = command == .pause ? "紧急暂停" : "立即返航"
var subtitle = command == .pause ? "悬停待命" : "中断任务"
if controlState == .paused, command == .pause {
title = "已暂停"
} else if controlState == .returning {
if command == .returnHome {
title = "返航中"
subtitle = "返回机巢"
}
} else if controlState == .returned {
title = command == .pause ? "紧急暂停" : "已返航"
subtitle = command == .pause ? "当前未执行任务" : "已返回机巢"
} else if controlState == .unknown, model.response?.flightControl != nil {
subtitle = "暂不可用"
} else if [.loading, .readError, .unknown].contains(phase) {
subtitle = "暂不可用"
}
if model.isCommandOutcomeUnknown(command) {
subtitle = "结果待核对"
}
let loading = submittingCommands.contains(command) || model.isCommandLoading(command)
let enabled = isInteractive && model.canSendCommand(command)
button.apply(title: title, subtitle: subtitle, enabled: enabled, isLoading: loading)
button.setControlSymbol(command == .pause ? "pause.circle" : "arrow.uturn.backward")
}
}
@objc private func pauseTapped() { guard pauseButton.isEnabled else { return }; onCommand?(.pause) }
@objc private func returnTapped() { guard returnButton.isEnabled else { return }; onCommand?(.returnHome) }
/// 高度仅依设备空间切换,不随任务状态、按钮文案或网络响应变化。
func configure(compact: Bool) {
headerTop?.update(offset: compact ? 8 : 10)
headerHeight?.update(offset: compact ? 12 : 14)
buttonGap?.update(offset: compact ? 6 : 8)
buttonHeight?.update(offset: compact ? 56 : 62)
}
}