feat: 接入拍摄任务实时订阅并完善日志与封面
This commit is contained in:
@@ -7,6 +7,10 @@ enum DroneDockShootingTaskEntry {
|
||||
static func makeController(taskID: Int, order: DroneDockHomeOrder,
|
||||
context: DroneDockHomeContext) -> UIViewController {
|
||||
let client = NetworkServices.shared.apiClient
|
||||
let realtime = DroneDockShootingRealtimeSession(taskID: taskID,
|
||||
ticketService: DroneDockSocketTokenAPI(client: client),
|
||||
makeTransport: { DroneDockURLSessionShootingSocket(url: APIEnvironment.current.webSocketURL) },
|
||||
identityIsCurrent: { context.hasSameIdentity(as: DroneDockHomeViewController.currentContext()) })
|
||||
let live = DroneDockLiveViewModel(
|
||||
context: context, taskID: taskID,
|
||||
service: DeviceCommandDebugPolicy.blocksLiveRequests ? nil : DroneDockLiveAPI(client: client),
|
||||
@@ -19,6 +23,6 @@ enum DroneDockShootingTaskEntry {
|
||||
commandService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockCommandAPI(client: client),
|
||||
resummonService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockShootAPI(client: client),
|
||||
currentContext: { DroneDockHomeViewController.currentContext() }
|
||||
), liveViewModel: live)
|
||||
), liveViewModel: live, realtimeSession: realtime)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -108,6 +108,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
|
||||
thumbnail.backgroundColor = DroneDockStyle.background
|
||||
thumbnail.layer.cornerRadius = 5
|
||||
thumbnail.clipsToBounds = true
|
||||
thumbnail.accessibilityIdentifier = "drone.preparation.point.cover"
|
||||
nameLabel.numberOfLines = 0
|
||||
nameLabel.lineBreakMode = .byWordWrapping
|
||||
nameLabel.accessibilityIdentifier = "drone.preparation.point.name"
|
||||
@@ -148,6 +149,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
|
||||
/// 展示点位名称与次数,已拍摄的点位仍保持可选择。
|
||||
func apply(point: DroneShootingPoint, selected: Bool) {
|
||||
thumbnail.kf.cancelDownloadTask()
|
||||
thumbnail.kf.setImage(with: nil as URL?)
|
||||
contentView.alpha = 1
|
||||
nameLabel.text = point.name
|
||||
thumbnail.contentMode = .scaleAspectFill
|
||||
@@ -164,14 +166,11 @@ final class DronePreparationPointCell: UICollectionViewCell {
|
||||
func apply(spot: DroneDockPurchasedSpot, selected: Bool) {
|
||||
nameLabel.text = spot.name
|
||||
thumbnail.kf.cancelDownloadTask()
|
||||
thumbnail.image = UIImage(systemName: "photo")
|
||||
thumbnail.contentMode = .center
|
||||
let coverURL = spot.displayCoverURL
|
||||
thumbnail.contentMode = coverURL == nil ? .center : .scaleAspectFill
|
||||
thumbnail.tintColor = DroneDockStyle.secondary
|
||||
if let text = spot.coverURL, let url = URL(string: text),
|
||||
let scheme = url.scheme?.lowercased(), ["https", "http"].contains(scheme), url.host != nil {
|
||||
thumbnail.contentMode = .scaleAspectFill
|
||||
thumbnail.kf.setImage(with: url, placeholder: UIImage(systemName: "photo"))
|
||||
}
|
||||
// nil 也交给 Kingfisher,撤销旧图片标识,防止复用后的迟到结果覆盖占位图。
|
||||
thumbnail.kf.setImage(with: coverURL, placeholder: UIImage(systemName: "photo"))
|
||||
if spot.available != true {
|
||||
countLabel.text = spot.available == false ? "拍摄点不可用" : "可用性待确认"
|
||||
} else {
|
||||
@@ -189,7 +188,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
|
||||
override func prepareForReuse() {
|
||||
super.prepareForReuse()
|
||||
thumbnail.kf.cancelDownloadTask()
|
||||
thumbnail.image = nil
|
||||
thumbnail.kf.setImage(with: nil as URL?)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -210,12 +210,12 @@ final class DroneShootingTaskTelemetryView: UIView {
|
||||
telemetry.rainText, telemetry.signalText, telemetry.satelliteText], isStale: isStale)
|
||||
}
|
||||
|
||||
/// 展示后端已格式化的六项读数,保留单位;缺项与过期读数显示破折号。
|
||||
func apply(values: [String], isStale: Bool, accessibilityPrefix: String? = nil) {
|
||||
/// 展示后端格式化读数;缺项显示破折号,任务页可保留过期旧值并使用灰色提示。
|
||||
func apply(values: [String], isStale: Bool, accessibilityPrefix: String? = nil, preservingStaleValues: Bool = false) {
|
||||
staleLabel.isHidden = usesFixedLayout || !isStale
|
||||
let keys = ["battery", "temperature", "wind", "rain", "signal", "satellite"]
|
||||
for (index, cell) in cells.enumerated() {
|
||||
let value = !isStale && values.indices.contains(index)
|
||||
let value = (!isStale || preservingStaleValues) && values.indices.contains(index)
|
||||
? DroneDockHomeMetric.usableText(values[index]) ?? "—" : "—"
|
||||
cell.apply(value: value, isStale: isStale)
|
||||
if let accessibilityPrefix { cell.accessibilityIdentifier = "\(accessibilityPrefix).\(keys[index])" }
|
||||
|
||||
Reference in New Issue
Block a user