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

This commit is contained in:
2026-11-03 09:06:38 +08:00
parent 687088326c
commit 980d16da9b
27 changed files with 1790 additions and 64 deletions
@@ -1,13 +1,14 @@
import SnapKit
import UIKit
/// 拍摄任务页:前台轮询状态、手动图传;Release 开放已授权控制,Debug 仅模拟控制。
/// 拍摄任务页:前台优先订阅快照、异常时 HTTP 兜底;图传与控制仍须用户手动操作。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
let viewModel: DroneDockShootingTaskViewModel
/// 图传使用独立状态,刷新与播放不会影响任务阶段或固定布局。
let liveViewModel: DroneDockLiveViewModel
private let realtimeSession: DroneDockShootingRealtimeSession?
private let topView = UIView()
private let summaryView = UIView()
@@ -39,14 +40,17 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private var isStartingAction = false
private var isSendingSafetyAction = false
private var isResummoningAction = false
private var wasRealtimeLive = false
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
init(viewModel: DroneDockShootingTaskViewModel,
liveViewModel: DroneDockLiveViewModel? = 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) }) {
self.viewModel = viewModel
self.realtimeSession = realtimeSession
self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel(
context: viewModel.context, taskID: viewModel.taskID,
currentContext: { DroneDockHomeViewController.currentContext() })
@@ -60,6 +64,15 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
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)
self.applySnapshot()
return result
}
realtimeSession?.onConnectionState = { [weak self] state in
self?.connectionStateChanged(state)
}
}
@available(*, unavailable)
@@ -192,7 +205,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
name: UIApplication.didBecomeActiveNotification, object: nil)
}
/// 完整进入任务页立即读取,随后仅在前台可见时轮询同一任务。
/// 完整进入任务页先读取一次,再启动同一任务的只读订阅。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isPageVisible = true
@@ -218,11 +231,11 @@ final class DroneDockShootingTaskViewController: BaseViewController {
feedPlaceholder.apply(liveViewModel)
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive)
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle
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")
isStale: viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric", preservingStaleValues: true)
let value = loading && viewModel.response == nil ? DroneDockTaskPresentation(
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
@@ -265,6 +278,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
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) }
@@ -277,7 +293,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 前台可见时串行读取;轮询失败保留旧快照,下个周期再读,不重复弹出提示。
private func refreshTaskIfVisible(isPolling: Bool = false) {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
guard isPageVisible, isApplicationActive, viewModel.readAccessError == nil, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand,
!isResummoningAction, !viewModel.isResummoning else { return }
@@ -295,6 +311,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.refreshTask = nil
self.isRequesting = false
self.applySnapshot()
if self.viewModel.canContinuePolling { self.realtimeSession?.start() }
else { self.realtimeSession?.stop() }
self.scheduleNextPoll()
if !isPolling, self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.showToast("刷新失败,当前显示上次数据:\(error)")
@@ -306,6 +324,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func scheduleNextPoll() {
cancelScheduledPoll()
guard isPageVisible, isApplicationActive, viewModel.canContinuePolling,
realtimeSession?.state != .live,
!isRequesting, !isStartingAction, !isSendingSafetyAction, !isResummoningAction else { return }
let generation = pollGeneration
let delay = shootingPollDelay
@@ -327,6 +346,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
private func cancelRefresh() {
wasRealtimeLive = false
realtimeSession?.stop()
cancelScheduledPoll()
requestGeneration &+= 1
refreshTask?.cancel()
@@ -345,6 +366,36 @@ final class DroneDockShootingTaskViewController: BaseViewController {
applySnapshot()
}
private func connectionStateChanged(_ state: DroneDockShootingRealtimeSession.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 }