feat: 完善机巢任务安全控制与状态诊断

同步新版飞控与 WebSocket 回执合同,完善独立指令等待、暂停继续和返航状态;增加真机诊断并优化倒计时与素材库展示。
This commit is contained in:
2026-11-04 17:34:28 +08:00
parent 1c766ff12f
commit e3979e9e32
44 changed files with 4575 additions and 581 deletions
@@ -16,8 +16,6 @@ final class DroneDockMaterialsViewController: BaseViewController {
private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController
private let downloadSourceDescription: String?
private let downloadIsSimulated: Bool
private let taskControllerFactory: (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private var taskButton: UIBarButtonItem?
/// 元数据与媒体分区独立,任务没有素材时也保留其状态。
private enum Section: Hashable { case order, filters, summary, task(Int), media(Int), message }
@@ -45,16 +43,12 @@ final class DroneDockMaterialsViewController: BaseViewController {
mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)? = nil,
downloadViewModel: DroneDockMaterialDownloadViewModel? = nil,
downloadSourceDescription: String? = nil,
downloadIsSimulated: Bool = false,
taskControllerFactory: ((Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
downloadIsSimulated: Bool = false) {
self.viewModel = viewModel
self.downloadViewModel = downloadViewModel ?? DroneDockMaterialDownloadViewModel(
isContextValid: { [weak viewModel] in viewModel?.acceptsDownloadContext() == true })
self.downloadSourceDescription = downloadSourceDescription
self.downloadIsSimulated = downloadIsSimulated
self.taskControllerFactory = taskControllerFactory ?? { id, order, context in
DroneDockShootingTaskEntry.makeController(taskID: id, order: order, context: context)
}
self.thumbnailProvider = thumbnailProvider
self.mediaPreviewControllerFactory = mediaPreviewControllerFactory
self.deliveryControllerFactory = deliveryControllerFactory ?? DroneDockDeliveryEntry.makeController
@@ -73,11 +67,7 @@ final class DroneDockMaterialsViewController: BaseViewController {
let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain, target: self, action: #selector(refreshTapped))
refresh.accessibilityLabel = "刷新素材状态"
refresh.accessibilityIdentifier = "drone.materials.remote.refresh"
let tasks = UIBarButtonItem(title: "查看任务", style: .plain, target: self, action: #selector(viewTasksTapped))
tasks.accessibilityIdentifier = "drone.materials.remote.viewTasks"
tasks.isEnabled = false
taskButton = tasks
navigationItem.rightBarButtonItems = [refresh, tasks]
navigationItem.rightBarButtonItems = [refresh]
}
override func setupUI() {
@@ -168,8 +158,8 @@ final class DroneDockMaterialsViewController: BaseViewController {
return cell
case .filter(let id):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "filter", for: path) as! DroneMaterialFilterCell
let title = id.flatMap { id in self.viewModel.spots.first { $0.id == id } }.map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位"
cell.apply(title: title, id: id.map(String.init), selected: id == self.displayedSpotID, locked: self.viewModel.detail == nil || self.selectionLocked)
cell.apply(title: self.filterTitle(for: id), id: id.map(String.init), selected: id == self.displayedSpotID,
locked: self.viewModel.detail == nil || self.selectionLocked, wrapsTitle: true)
return cell
case .task(let taskID):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "record", for: path) as! DroneDockMaterialRecordCell
@@ -228,8 +218,20 @@ final class DroneDockMaterialsViewController: BaseViewController {
guard sections.indices.contains(index) else { return nil }
switch sections[index] {
case .filters:
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .estimated(104), heightDimension: .absolute(36)), subitems: [item])
let maximumWidth = min(200, max(1, environment.container.effectiveContentSize.width - 32))
let sizes = dataSource.snapshot().itemIdentifiers(inSection: .filters).compactMap { item -> CGSize? in
guard case .filter(let id) = item else { return nil }
return DroneMaterialFilterCell.wrappedSize(title: self.filterTitle(for: id), maximumWidth: maximumWidth)
}
let width = sizes.reduce(0) { $0 + $1.width } + CGFloat(max(0, sizes.count - 1)) * 8
let height = sizes.map(\.height).max() ?? 40
let group = NSCollectionLayoutGroup.custom(layoutSize: .init(widthDimension: .absolute(max(1, width)), heightDimension: .absolute(height))) { _ in
var x: CGFloat = 0
return sizes.map { size in
defer { x += size.width + 8 }
return NSCollectionLayoutGroupCustomItem(frame: CGRect(x: x, y: 0, width: size.width, height: size.height))
}
}
let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .continuous
section.interGroupSpacing = 8
@@ -267,7 +269,6 @@ final class DroneDockMaterialsViewController: BaseViewController {
private func applySnapshot(animated: Bool) {
guard dataSource != nil else { return }
taskButton?.isEnabled = operation == nil && !selectionLocked && viewModel.canViewRecordedTasks
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
if viewModel.detail != nil {
snapshot.appendSections([.order, .filters])
@@ -375,7 +376,6 @@ final class DroneDockMaterialsViewController: BaseViewController {
private func updateDownloadFooter() {
navigationItem.rightBarButtonItem?.isEnabled = !selectionLocked
taskButton?.isEnabled = operation == nil && !selectionLocked && viewModel.canViewRecordedTasks
let model = downloadViewModel
let identifier = "drone.materials.remote.download"
switch model.phase {
@@ -401,31 +401,6 @@ final class DroneDockMaterialsViewController: BaseViewController {
}
}
/// 从张工已返回的任务中选择并进入状态页,不创建新任务或调用召唤接口。
@objc private func viewTasksTapped() {
guard operation == nil, !selectionLocked, viewModel.canViewRecordedTasks,
viewModel.acceptsDownloadContext(), presentedViewController == nil else { return }
if let task = viewModel.tasks.first, viewModel.tasks.count == 1 {
openRecordedTask(id: task.id)
return
}
let sheet = UIAlertController(title: "选择拍摄任务", message: nil, preferredStyle: .actionSheet)
for task in viewModel.tasks {
let spot = task.spotName.isEmpty ? "拍摄任务" : task.spotName
let sequence = task.sequence.map { "第\($0)次拍摄" } ?? "拍摄记录"
let title = "\(spot) · \(sequence)" + (task.createdAt.map { " · \($0)" } ?? "")
sheet.addAction(UIAlertAction(title: title, style: .default) { [weak self] _ in self?.openRecordedTask(id: task.id) })
}
sheet.addAction(UIAlertAction(title: "取消", style: .cancel))
present(sheet, animated: true)
}
private func openRecordedTask(id: Int) {
guard operation == nil, !selectionLocked, viewModel.taskForViewing(id: id) != nil,
navigationController?.topViewController === self else { return }
navigationController?.pushViewController(taskControllerFactory(id, viewModel.order, viewModel.context), animated: true)
}
private func previewFile(taskID: Int, fileID: Int) {
guard operation == nil, let file = task(taskID)?.materials.first(where: { $0.id == fileID }), let url = file.previewURL else { return }
preview(url: url, isVideo: file.fileType == 2, title: file.fileName ?? "原素材")
@@ -447,6 +422,11 @@ final class DroneDockMaterialsViewController: BaseViewController {
DroneDockHomeMetric.usableText(value) ?? fallback
}
private func filterTitle(for id: Int?) -> String {
id.flatMap { id in viewModel.spots.first { $0.id == id } }
.map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位"
}
}
@@ -140,12 +140,14 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
super.viewWillAppear(animated)
isPageVisible = true
isApplicationActive = UIApplication.shared.applicationState == .active
logPreparationEvent("preparation.page.appeared")
refreshPreparation()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
logPreparationEvent("preparation.page.disappeared", fields: ["moving_from_parent": isMovingFromParent])
stopPlaneStatusPolling()
refreshTask?.cancel()
creationTask?.cancel()
@@ -183,7 +185,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
/// 首次创建并召唤;成功后进入原任务,再次查看不经过创建或召唤接口。
private func createSelectedTask() {
DroneDockDiagnostics.event("preparation.confirm_tapped", taskID: viewModel.createdTask?.taskID, fields: [
logPreparationEvent("preparation.confirm_tapped", fields: [
"order_number": viewModel.order.orderNumber as Any? ?? NSNull(),
"scenic_id": viewModel.context.scenicID,
"spot_id": viewModel.selectedSpotID as Any? ?? NSNull(),
@@ -191,12 +193,18 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
"enabled": viewModel.isPrimaryActionEnabled,
"blocked": viewModel.isTaskSubmissionBlocked
])
guard !isRefreshing, !isStartingCreation else { return }
guard !isRefreshing, !isStartingCreation else {
logPreparationEvent("preparation.confirm_rejected", fields: ["reason": "refresh_or_submission_in_progress"])
return
}
if viewModel.canOpenShootingTask {
_ = openShootingTask(automatically: false)
return
}
guard viewModel.isPrimaryActionEnabled else { return }
guard viewModel.isPrimaryActionEnabled else {
logPreparationEvent("preparation.confirm_rejected", fields: ["reason": "primary_action_disabled"])
return
}
isStartingCreation = true
applySnapshot(animated: false)
creationTask = Task { @MainActor [weak self] in
@@ -204,6 +212,10 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
await self.viewModel.prepareAndSummon { [weak self] in self?.applySnapshot(animated: false) }
guard !Task.isCancelled else { return }
self.isStartingCreation = false
self.logPreparationEvent("preparation.submission_presented", fields: [
"has_summon_receipt": self.viewModel.shootResponse != nil,
"can_open_task": self.viewModel.canOpenShootingTask,
"error_message": self.viewModel.errorMessage as Any? ?? NSNull()])
if self.openShootingTask(automatically: true) { return }
self.applySnapshot(animated: true) { [weak self] in
guard let self,
@@ -230,11 +242,23 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask,
let taskID = viewModel.createdTask?.taskID,
let navigationController, navigationController.topViewController === self,
!automatically || (viewModel.shootResponse != nil && automaticallyOpenedTaskID != taskID) else { return false }
DroneDockDiagnostics.event("navigation.open_task", taskID: taskID)
!automatically || (viewModel.shootResponse != nil && automaticallyOpenedTaskID != taskID) else {
logPreparationEvent("navigation.open_task_rejected", fields: ["automatic": automatically,
"can_open_task": viewModel.canOpenShootingTask,
"is_navigation_top": navigationController?.topViewController === self,
"has_summon_receipt": viewModel.shootResponse != nil,
"previously_opened_task_id": automaticallyOpenedTaskID as Any? ?? NSNull()])
return false
}
automaticallyOpenedTaskID = taskID
let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context)
let stack = navigationController.viewControllers
let fields: [String: Any] = ["automatic": automatically, "task_id": taskID,
"preparation_session_id": viewModel.diagnosticSessionID,
"replaces_preparation": stack.count > 1,
"navigation_stack_before": stack.map { String(describing: type(of: $0)) }]
logPreparationEvent("navigation.open_task", fields: fields)
(controller as? DroneDockShootingTaskViewController)?.recordNavigationEntry(source: "preparation", fields: fields)
if stack.count > 1 {
navigationController.setViewControllers(Array(stack.dropLast()) + [controller], animated: true)
} else {
@@ -278,6 +302,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
@objc private func applicationWillResignActive() {
isApplicationActive = false
logPreparationEvent("preparation.app.inactive")
stopPlaneStatusPolling()
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation,
isLocalSimulation: simulationRecordsProvider != nil)
@@ -285,9 +310,23 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
@objc private func applicationDidBecomeActive() {
isApplicationActive = true
logPreparationEvent("preparation.app.active")
startPlaneStatusPolling()
}
/// 准备页 UI 事件沿用业务会话,可与后续任务页的导航记录关联。
private func logPreparationEvent(_ name: String, fields: [String: Any] = [:]) {
var fields = fields
fields["source"] = simulationRecordsProvider == nil ? "preparation_page" : "local_simulation"
fields["task_id"] = viewModel.createdTask?.taskID as Any? ?? NSNull()
fields["page_visible"] = isPageVisible
fields["app_active"] = isApplicationActive
fields["refreshing"] = isRefreshing
fields["submitting"] = isStartingCreation
fields["debug_flight_blocked"] = DeviceCommandDebugPolicy.blocksFlightRequests
viewModel.recordPreparationEvent(name, fields: fields)
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, path, item in
guard let self else { return nil }
@@ -29,7 +29,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private var pollGeneration = 0
private var refreshTask: Task<Void, Never>?
private var startTask: Task<Void, Never>?
private var commandTask: 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>?
@@ -40,16 +42,19 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private var isApplicationActive = false
private var isRequesting = false
private var isStartingAction = false
private var isSendingSafetyAction = false
private var isSendingSafetyAction: Bool { !submittingCommands.isEmpty }
private var isResummoningAction = false
private var wasRealtimeLive = false
private let coverURL: URL?
private var finishedExecutions: Set<String> = []
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,
@@ -83,7 +88,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
hidesBottomBarWhenPushed = true
realtimeSession?.onSnapshot = { [weak self] snapshot in
guard let self, self.isPageVisible, self.isApplicationActive else { return .invalid }
let result = self.viewModel.applyTaskSnapshot(snapshot)
let result = self.viewModel.applyTaskSnapshot(snapshot, source: .webSocket)
self.applySnapshot()
return result
}
@@ -95,11 +100,17 @@ final class DroneDockShootingTaskViewController: BaseViewController {
@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()
commandTask?.cancel()
commandTasks.values.forEach { $0.cancel() }
resummonTask?.cancel()
liveTask?.cancel()
liveParameterTask?.cancel()
@@ -192,6 +203,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 只按设备可用尺寸调整固定区域,数据、错误和加载状态不会改变它们的高度。
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
@@ -211,8 +223,11 @@ final class DroneDockShootingTaskViewController: BaseViewController {
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, self.isPageVisible, self.isApplicationActive else { return }
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()
@@ -230,8 +245,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isPageVisible = true
logEvent("page.appeared")
isApplicationActive = UIApplication.shared.applicationState == .active
logEvent("page.appeared", fields: ["navigation_stack": navigationController?.viewControllers.map { String(describing: type(of: $0)) } ?? []])
refreshTaskIfVisible()
refreshLiveIfVisible(automatically: true)
}
@@ -241,25 +256,30 @@ final class DroneDockShootingTaskViewController: BaseViewController {
super.viewWillDisappear(animated)
isPageVisible = false
dismissCompletionNotice()
logEvent("page.disappeared")
logEvent("page.disappeared", fields: ["moving_from_parent": isMovingFromParent, "being_dismissed": isBeingDismissed])
cancelRefresh()
stopLive()
}
private func applySnapshot() {
guard isViewLoaded else { return }
if viewModel.isRecordingFinished { finishedExecutions.insert(viewModel.recordingExecutionID) }
let recordingFinished = finishedExecutions.contains(viewModel.recordingExecutionID)
if viewModel.shouldStopLiveReception {
stoppedLiveExecutionTitles[viewModel.recordingExecutionID] = viewModel.isRecordingFinished
? "拍摄已完成" : "无人机已返回机巢"
}
let stoppedLiveTitle = stoppedLiveExecutionTitles[viewModel.recordingExecutionID]
let liveReceptionEnded = stoppedLiveTitle != nil
if !viewModel.shouldPresentRecordingCompletion { dismissCompletionNotice() }
if recordingFinished, liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil {
if liveReceptionEnded, liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil {
stopLive()
}
feedPlaceholder.showRecordingCover(recordingFinished, url: coverURL)
feedPlaceholder.showRecordingCover(liveReceptionEnded, url: coverURL,
title: stoppedLiveTitle ?? "拍摄已完成")
let loading = (viewModel.response == nil && (isRequesting || viewModel.isLoading))
|| isStartingAction || viewModel.isStartingShooting
|| isSendingSafetyAction || viewModel.isSendingCommand || isResummoningAction || viewModel.isResummoning
|| isResummoningAction || viewModel.isResummoning
feedPlaceholder.apply(liveViewModel)
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive && !recordingFinished)
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive && !liveReceptionEnded)
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle + (viewModel.response?.metricsStale == true ? " · 读数已过期" : "")
let telemetry = viewModel.telemetry
@@ -270,21 +290,25 @@ final class DroneDockShootingTaskViewController: BaseViewController {
let value = loading && viewModel.response == nil && presentation.phase != .navigating ? DroneDockTaskPresentation(
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : presentation
statusView.apply(value, isRefreshing: loading)
statusView.apply(value, isRefreshing: loading, isPrimaryActionLoading: value.action == .resume
&& (submittingCommands.contains(.resume) || viewModel.isCommandLoading(.resume)))
updateArrivalCountdown()
safetyView.apply(model: viewModel, isSimulation: simulationRecordsProvider != nil,
isInteractive: isPageVisible && isApplicationActive && !loading)
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
@@ -300,6 +324,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
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
@@ -321,10 +346,15 @@ final class DroneDockShootingTaskViewController: BaseViewController {
displayedCompletionIDs.insert(id)
let notice = DroneDockRecordingCompletionView()
completionNotice = notice
notice.onLater = { [weak self] in self?.dismissCompletionNotice() }
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()
}
@@ -335,6 +365,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
private func dismissCompletionNotice() {
if completionNotice != nil { logEvent("ui.completion_notice.dismissed") }
completionNotice?.removeFromSuperview()
completionNotice = nil
}
@@ -352,10 +383,15 @@ final class DroneDockShootingTaskViewController: BaseViewController {
"enabled": viewModel.presentation.isActionEnabled])
guard isPageVisible, isApplicationActive,
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand,
!isResummoningAction, !viewModel.isResummoning else { return }
!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 { return }
guard state.isActionEnabled else {
logEvent("action.primary.rejected", fields: ["reason": "presentation_action_disabled", "ui": statusView.diagnosticFields])
return
}
switch state.action {
case .refresh:
refreshTaskIfVisible()
@@ -365,7 +401,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
resummonIfAllowed()
case .materials:
openMaterials()
case .resume, .none:
case .resume:
safetyCommandTriggered(.resume)
case .none:
break
}
}
@@ -394,10 +432,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func refreshTaskIfVisible(isPolling: Bool = false) {
guard isPageVisible, isApplicationActive, viewModel.readAccessError == nil, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand,
!isResummoningAction, !viewModel.isResummoning else { return }
cancelScheduledPoll()
logEvent("shooting.refresh", fields: ["trigger": isPolling ? "poll" : "page_or_manual", "live_battery": 0])
requestGeneration &+= 1
let generation = requestGeneration
isRequesting = true
@@ -424,11 +460,10 @@ final class DroneDockShootingTaskViewController: BaseViewController {
cancelScheduledPoll()
guard isPageVisible, isApplicationActive, viewModel.canContinuePolling,
realtimeSession?.state != .live,
!isRequesting, !isStartingAction, !isSendingSafetyAction, !isResummoningAction else { return }
!isRequesting, !isStartingAction, !isResummoningAction else { return }
let generation = pollGeneration
let delay = shootingPollDelay
let interval = viewModel.pollIntervalNanoseconds
logEvent("poll.scheduled", fields: ["delay_ms": interval / 1_000_000])
pollTask = Task { @MainActor [weak self] in
do { try await delay(interval) } catch { return }
guard !Task.isCancelled, let self, self.pollGeneration == generation else { return }
@@ -438,7 +473,6 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
private func cancelScheduledPoll() {
if pollTask != nil { logEvent("poll.cancelled") }
pollGeneration &+= 1
pollTask?.cancel()
pollTask = nil
@@ -464,12 +498,13 @@ final class DroneDockShootingTaskViewController: BaseViewController {
refreshTask = nil
startTask?.cancel()
startTask = nil
commandTask?.cancel()
commandTask = nil
commandTasks.values.forEach { $0.cancel() }
commandTasks.removeAll()
commandAttemptIDs.removeAll()
submittingCommands.removeAll()
resummonTask?.cancel()
resummonTask = nil
isResummoningAction = false
isSendingSafetyAction = false
isStartingAction = false
isRequesting = false
viewModel.invalidate(preservingSnapshot: true)
@@ -477,6 +512,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
private func connectionStateChanged(_ state: DroneDockShootingRealtimeSession.State) {
logChangedEvent("page.realtime_state", fields: ["state": String(describing: state)])
guard isPageVisible, isApplicationActive else { return }
switch state {
case .live:
@@ -564,12 +600,12 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 可见且活跃时自动开启一次;失败可手动重试,不随 shooting/Socket 刷新重复请求。
private func refreshLiveIfVisible(automatically: Bool = false, keepingPlayback: Bool = false) {
guard viewModel.response != nil, viewModel.readAccessError == nil,
!finishedExecutions.contains(viewModel.recordingExecutionID), !viewModel.isRecordingFinished else { return }
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])
logEvent("live.request", fields: ["automatic": automatically, "keeping_playback": keepingPlayback])
liveGeneration &+= 1
let generation = liveGeneration
liveTask = Task { @MainActor [weak self] in
@@ -602,6 +638,10 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 离页或进入后台立即释放播放器,使旧图传响应无法恢复播放。
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
@@ -616,49 +656,62 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) {
logEvent("action.safety", fields: ["command": command.rawValue, "enabled": viewModel.canSendCommand(command)])
guard allowsControlActions, isPageVisible, isApplicationActive,
presentedViewController == nil, !isSendingSafetyAction, !isStartingAction,
!isResummoningAction, viewModel.canSendCommand(command) else { return }
presentedViewController == nil, !submittingCommands.contains(command), !isStartingAction,
!isResummoningAction, viewModel.canSendCommand(command) else {
logSafetyRejection(command, stage: "tap")
return
}
if command == .returnHome {
let simulated = simulationRecordsProvider != nil
let alert = UIAlertController(title: simulated ? "立即返航(本地模拟)" : "立即返航",
message: simulated
? "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。"
: "返航会中断本次任务。取消返航也不会恢复已经中断的任务。确定立即返航?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "取消", style: .cancel) { [weak self] _ in
self?.logEvent("action.return_confirmation.cancelled")
})
alert.addAction(UIAlertAction(title: simulated ? "模拟返航" : "立即返航", style: .destructive) { [weak self] _ in
self?.logEvent("action.return_confirmation.confirmed")
self?.sendSafetyCommand(command)
})
logEvent("action.return_confirmation.shown")
present(alert, animated: true)
} else {
sendSafetyCommand(command)
}
}
/// 同步锁覆盖异步调度间隙;界面保留旧快照,只有同任务回查成功才更新阶段。
/// 同步锁只覆盖同一按钮;不同安全动作可各自等待,设备确认由 ViewModel 和快照处理。
private func sendSafetyCommand(_ command: DroneDockSafetyCommand) {
guard allowsControlActions, isPageVisible, isApplicationActive,
!isSendingSafetyAction, !isStartingAction, !isResummoningAction,
viewModel.canSendCommand(command) else { return }
!submittingCommands.contains(command), !isStartingAction, !isResummoningAction,
viewModel.canSendCommand(command) else {
logSafetyRejection(command, stage: "submit")
return
}
cancelPendingReadForAction()
let generation = requestGeneration
isSendingSafetyAction = true
let attemptID = UUID()
logEvent("action.safety.submitting", fields: ["command": command.rawValue, "ui_attempt_id": attemptID.uuidString])
commandAttemptIDs[command] = attemptID
submittingCommands.insert(command)
applySnapshot()
commandTask = Task { @MainActor [weak self] in
commandTasks[attemptID] = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.sendCommand(command) { [weak self] in self?.applySnapshot() }
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.requestGeneration == generation, !Task.isCancelled else { return }
self.commandTask = nil
self.isSendingSafetyAction = false
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 {
if let error = self.viewModel.commandErrorMessage(for: command) {
self.showToast(error)
} else if let error = self.viewModel.errorMessage {
self.showToast("指令已受理,状态刷新失败:\(error)")
} else {
self.showToast(self.simulationRecordsProvider != nil
? "本地模拟指令已受理,未发送设备指令" : "指令已受理,请等待任务状态更新")
}
}
}
@@ -671,15 +724,17 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
@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() {
logEvent("app.inactive")
isApplicationActive = false
logEvent("app.inactive")
cancelRefresh()
stopLive()
}
@@ -695,9 +750,86 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func logEvent(_ name: String, fields: [String: Any] = [:]) {
var fields = fields
fields["source"] = simulationRecordsProvider == nil ? "task_page" : "local_simulation"
fields["scenic_id"] = viewModel.context.scenicID
fields["order_number"] = viewModel.order.orderNumber
DroneDockDiagnostics.event(name, taskID: viewModel.taskID, fields: fields)
fields["entry_source"] = entrySource
fields["page_visible"] = isPageVisible
fields["app_active"] = isApplicationActive
fields["view_in_window"] = isViewLoaded && view.window != nil
fields["debug_flight_blocked"] = DeviceCommandDebugPolicy.blocksFlightRequests
fields["debug_live_blocked"] = DeviceCommandDebugPolicy.blocksLiveRequests
fields["allows_control_actions"] = allowsControlActions
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 .restricted: liveFields["state"] = "restricted"
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 !allowsControlActions { reasons.append("debug_policy") }
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])
}
private var allowsControlActions: Bool {
@@ -743,13 +875,11 @@ final class DroneDockSimulationRecordsViewController: BaseViewController {
@objc private func close() { dismiss(animated: true) }
}
/// 固定底部的安全控制,只在隔离模拟入口按当前接口提供的指令展示可用操作。
/// 固定底部的安全控制,文案来自本地阶段,操作许可统一由任务模型判断。
@MainActor
private final class DroneDockTaskSafetyView: UIView {
/// 将用户选择的白名单指令交给页面,不直接调用任何服务。
var onCommand: ((DroneDockSafetyCommand) -> Void)?
private var pauseCommand = DroneDockSafetyCommand.pause
private var returnCommand = DroneDockSafetyCommand.returnHome
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)
@@ -759,6 +889,11 @@ private final class DroneDockTaskSafetyView: UIView {
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)
@@ -799,36 +934,51 @@ private final class DroneDockTaskSafetyView: UIView {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 保持两列固定布局,暂停/继续与返航/取消由快照中的指令白名单决定。
func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool) {
let commands = model.availableSafetyCommands
/// 两个按钮始终表示暂停与返航;已暂停、返航中和回巢使用本地文案,恢复入口位于中央。
func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool,
submittingCommands: Set<DroneDockSafetyCommand> = []) {
let allowsControls = isSimulation || !DeviceCommandDebugPolicy.blocksFlightRequests
pauseCommand = commands.contains(.resume) ? .resume : .pause
returnCommand = commands.contains(.cancelReturn) ? .cancelReturn : .returnHome
header.text = model.commandOutcomeUnknown ? "安全控制 · 结果待核对"
: model.isSendingCommand ? (isSimulation ? "安全控制 · 本地模拟发送中" : "安全控制 · 指令发送中")
: isSimulation ? "安全控制 · 本地模拟,不发送设备指令" : "安全控制"
for (button, command) in [(pauseButton, pauseCommand), (returnButton, returnCommand)] {
let title: String
let subtitle: String
switch command {
case .pause: title = "紧急暂停"; subtitle = "悬停待命"
case .resume: title = "继续拍摄"; subtitle = "恢复航线"
case .returnHome: title = "立即返航"; subtitle = "中断任务"
case .cancelReturn: title = "取消返航"; subtitle = "不恢复已中断任务"
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 = allowsControls && isInteractive && model.canSendCommand(command)
let detail = model.activeCommand == command ? (isSimulation ? "本地模拟发送中…" : "指令发送中…")
: model.commandOutcomeUnknown ? "结果待核对"
: !allowsControls || !commands.contains(command) ? "暂不可用" : subtitle
button.apply(title: title, subtitle: detail, enabled: enabled)
button.setControlSymbol(command == .resume ? "play.circle" : command == .pause ? "pause.circle"
: command == .cancelReturn ? "xmark.circle" : "arrow.uturn.backward")
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?(pauseCommand) }
@objc private func returnTapped() { guard returnButton.isEnabled else { return }; onCommand?(returnCommand) }
@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) {
@@ -106,10 +106,13 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
private var hasCreated: Bool
private var hasSummoned: Bool
private var hasStarted: Bool
private var lastCommandProgress: [String: Any]?
private var isPaused = false
private var isReturning = false
private var wasInterrupted = false
private var hasFailed: Bool
private var executionBatch = 9_001
private var stateVersion = 1
private var exchanges: [Exchange] = []
/// 固定当前实例结果,不能用参数切换到真实传输。
@@ -191,7 +194,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
}
if request.httpMethod == "GET", url.path == "/api/app/airport/plane-status" {
guard queryMatches(url, required: ["scenic_id": "128", "live_battery": "1"]) else { throw URLError(.badURL) }
let plane: [String: Any] = ["id": 201, "name": "本地模拟无人机", "sn_number": "LOCAL-MOCK-PLANE-201",
let plane: [String: Any] = ["id": 201, "name": "本地模拟无人机", "sn_number": "LOCAL-MOCK-DOCK-201",
"online_status": 1, "work_status": 1, "work_status_label": "空闲(模拟)",
"status_text": "本地模拟 · 电量 95%", "battery_percent": 95,
"can_fly": true, "is_receive_order": 1]
@@ -230,11 +233,15 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
hasFailed = false
hasStarted = false
isPaused = false
isReturning = false
wasInterrupted = false
executionBatch += 1
}
} else if !hasCreated || hasSummoned {
return try envelope([:], code: 100099, message: "本地模拟:任务尚未创建或已召唤")
}
hasSummoned = true
stateVersion += 1
return try envelope(["order_flight_task": taskData(), "order_flight_task_id": 901,
"plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201",
"task_uuid": "LOCAL-MOCK-TASK-UUID-901",
@@ -262,7 +269,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
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],
Set(object.keys) == ["id", "command"],
Set(object.keys) == ["id", "command", "client_request_id"],
let values = try? JSONDecoder().decode(CommandBody.self, from: body),
values.id == 901, let command = DroneDockSafetyCommand(rawValue: values.command) else {
throw URLError(.badURL)
@@ -282,7 +289,17 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
case .returnHome: isReturning = true; wasInterrupted = true; isPaused = false
case .cancelReturn: isReturning = false; isPaused = true
}
return try envelope(["command": command.rawValue, "order_flight_task_id": 901,
stateVersion += 1
let commandID = "LOCAL-MOCK-COMMAND-\(stateVersion)"
lastCommandProgress = ["command_id": commandID, "client_request_id": values.clientRequestID,
"command": command.rawValue, "status": "succeeded"]
return try envelope(["accepted": true, "device_confirmed": true,
"command_id": commandID, "client_request_id": values.clientRequestID,
"pending_command": lastCommandProgress ?? [:],
"acceptance": command == .returnHome ? "accepted" : "device_confirmed",
"command": command.rawValue, "order_flight_task_id": 901,
"execution_batch": executionBatch, "state_version": stateVersion,
"flight_control": flightControlData(),
"airport_sn": "LOCAL-MOCK-DOCK-201", "dji_status": simulatedPhase,
"metrics": simulatedMetrics])
}
@@ -308,6 +325,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
throw URLError(.timedOut)
case .success:
hasStarted = true
stateVersion += 1
return try envelope([
"task_uuid": "LOCAL-MOCK-TASK-UUID-901", "order_flight_task_id": 901,
"order_flight_task": taskData(), "plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201",
@@ -355,13 +373,15 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
}
let deviceLabel = isReturning ? "返航中" : isPaused ? "悬停中" : hasStarted ? "拍摄中" : "空闲"
return ["order_number": "LOCAL-MOCK-ORDER-901", "order_flight_task": taskData(), "task": taskData(),
"execution_batch": executionBatch, "state_version": stateVersion, "snapshot_kind": "full",
"flight_control": flightControlData(),
"scenic": ["id": 128, "name": "本地模拟景区"],
"scenic_spot": ["id": 301, "name": "模拟点位"],
"air_line": ["id": 401, "name": "模拟航线", "scenic_spot_id": 301],
"header": ["order_number": "LOCAL-MOCK-ORDER-901", "title": "模拟点位 · 模拟航线",
"tourist_label": "本地模拟,无设备指令", "package_name": "模拟套餐 · 含5次拍摄"],
"current_plane": ["id": 201, "sn_number": "LOCAL-MOCK-PLANE-201", "online_status": 1,
"work_status": hasStarted ? 2 : 1, "work_status_label": deviceLabel,
"current_plane": ["id": 201, "sn_number": "LOCAL-MOCK-DOCK-201", "online_status": 1,
"work_status": hasFailed ? 1 : 2, "work_status_label": deviceLabel,
"status_text": "本地模拟 · \(deviceLabel) · 电量95%"],
"metrics": simulatedMetrics,
"plane_status": ["scenic_id": 128, "connected": true, "poll_hint_ms": 5000],
@@ -369,12 +389,14 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
"message": hasStarted ? "本地模拟:开拍已受理" : "本地模拟:允许验证开拍请求",
"primary_action": canStart ? "start_shoot" : simulatedPhase,
"primary_action_label": hasStarted ? "拍摄中" : "开始拍摄"],
"restart_gate": ["can_restart": hasFailed, "code": hasFailed ? "ok" : "running"],
"ui": ["phase": simulatedPhase, "title": phaseTitle, "commands": commands,
"message": wasInterrupted ? phaseTitle : "本地模拟状态回查,未向设备发送指令。"]]
}
private func taskData() -> [String: Any] {
var task: [String: Any] = ["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128,
"wayline_task_id": executionBatch, "plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201",
"status": 20, "status_label": "执行中(模拟)", "wayline_status": 20, "wayline_status_label": "执行中(模拟)"]
if hasFailed {
task["status"] = 40
@@ -385,7 +407,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
} else if wasInterrupted {
task["status"] = 40
task["status_label"] = "任务已中断(模拟)"
task["wayline_status"] = 40
task["wayline_status"] = 91
task["wayline_status_label"] = "已中断(模拟)"
task["result_code"] = "return_home"
task["result_message"] = isReturning ? "本地模拟:立即返航中断任务;无人机返航中。"
@@ -396,19 +418,34 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
private var availableCommands: [DroneDockSafetyCommand] {
guard hasSummoned, !hasFailed else { return [] }
if isReturning { return [.cancelReturn] }
if isReturning { return [isPaused ? .resume : .pause] }
if wasInterrupted { return [] }
return [isPaused ? .resume : .pause, .returnHome]
}
private var simulatedPhase: String {
if hasFailed { return "failed" }
if isReturning { return "returning" }
if isPaused { return "manual_paused" }
if isReturning { return "returning_home" }
if wasInterrupted { return "failed" }
if isPaused { return "paused" }
return hasStarted ? "shooting" : "arrived_pending_start"
}
/// 同一模拟批次的执行状态和权限;回巢仅在显式失败起始场景中提供 inside 证据。
private func flightControlData() -> [String: Any] {
let state = hasFailed ? "returned" : isPaused ? "paused" : isReturning ? "returning" : "executing"
let pauseReason: Any = isPaused ? "manual" : (hasStarted ? NSNull() : "arrival_wait" as Any)
return ["state": state, "execution_batch": executionBatch,
"is_airborne": !hasFailed, "pause_reason": pauseReason,
"pending_command": lastCommandProgress ?? [:],
"resume_phase": isReturning ? "returning" : hasStarted ? "shooting" : "arrived_pending_start",
"return_reason": wasInterrupted ? "manual" : NSNull(),
"drone_in_dock": hasFailed ? "inside" : "outside",
"can_pause": availableCommands.contains(.pause),
"can_resume": availableCommands.contains(.resume),
"can_return_home": availableCommands.contains(.returnHome)]
}
private var simulatedMetrics: [[String: String]] {
[["key": "battery", "value": "95%"], ["key": "env_temp", "value": "20.3℃"],
["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": "无雨"],
@@ -456,6 +493,8 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
private struct CommandBody: Decodable {
let id: Int
let command: String
let clientRequestID: String
private enum CodingKeys: String, CodingKey { case id, command, clientRequestID = "client_request_id" }
}
}
#endif
@@ -0,0 +1,249 @@
import SnapKit
import UIKit
/// 暂停、返航及回巢面板,使用本地状态文案及整行主按钮,不显示设备摘要。
@MainActor
final class DroneDockTaskControlStateView: UIView {
/// 用户点击已允许的主操作时交给任务页面执行。
var onPrimaryAction: (() -> Void)?
/// 当前固定区域使用的排版比例,不通过 transform 缩小点击区域。
private(set) var effectiveScale: CGFloat = 1
/// 可用高度不足时收紧图标、字号与间距。
private(set) var usesCompactLayout = false
private let content = UIView()
private let header = UIView()
private let iconBackground = UIView()
private let icon = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold, color: UIColor(hex: 0x101523))
private let messageLabel = DroneDockStyle.label(size: 14, color: UIColor(hex: 0x6A79A0))
private let actionButton = UIButton(type: .system)
private let actionActivityIndicator = UIActivityIndicatorView(style: .medium)
private let noteLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private var presentation: DroneDockTaskPresentation?
private var identifiersActive = false
private var isPrimaryActionLoading = false
private var headerHeight: Constraint?
private var iconSize: Constraint?
private var textLeading: Constraint?
private var titleHeight: Constraint?
private var messageTop: Constraint?
private var messageHeight: Constraint?
private var actionTop: Constraint?
private var actionHeight: Constraint?
private var noteTop: Constraint?
private var noteHeight: Constraint?
/// 创建与任务固定状态区域配合的控制状态视图。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 文案和动作均由本地展示模型提供,禁用按钮只显示状态且不会触发回调。
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false, isPrimaryActionLoading: Bool = false) {
self.presentation = presentation
self.isPrimaryActionLoading = isPrimaryActionLoading
titleLabel.text = presentation.title
messageLabel.text = presentation.message
noteLabel.text = presentation.actionNote
switch presentation.phase {
case .paused: icon.image = UIImage(systemName: "pause.fill")
case .returning: icon.image = UIImage(systemName: "arrow.uturn.backward")
case .returned: icon.image = UIImage(systemName: "house.fill")
default: icon.image = UIImage(systemName: "clock")
}
actionButton.isEnabled = presentation.action != .none && presentation.isActionEnabled && !isRefreshing && !isPrimaryActionLoading
actionButton.configuration?.title = presentation.actionTitle
let actionSymbol: String? = switch presentation.action {
case .resume: "play.fill"
case .retry: "paperplane.fill"
case .refresh: "arrow.clockwise"
default: nil
}
actionButton.configuration?.image = actionSymbol.flatMap { UIImage(systemName: $0) }
if isPrimaryActionLoading { actionActivityIndicator.startAnimating() }
else { actionActivityIndicator.stopAnimating() }
actionButton.accessibilityValue = isPrimaryActionLoading ? "处理中" : nil
setIdentifiersActive(identifiersActive)
actionButton.setNeedsUpdateConfiguration()
setNeedsLayout()
}
/// 只有可见面板暴露通用标识,状态切换后不会匹配到隐藏的旧按钮。
func setIdentifiersActive(_ active: Bool) {
identifiersActive = active
if !active { actionActivityIndicator.stopAnimating() }
titleLabel.accessibilityIdentifier = active ? "drone.task.remote.statusTitle" : nil
messageLabel.accessibilityIdentifier = active ? "drone.task.remote.statusMessage" : nil
actionButton.accessibilityIdentifier = active
? (presentation?.action == .refresh ? "drone.task.remote.refresh" : "drone.task.remote.primary") : nil
actionActivityIndicator.accessibilityIdentifier = active ? "drone.task.remote.primary.loading" : nil
}
/// 在固定区域内收紧排版,主按钮始终至少 44 点高。
override func layoutSubviews() {
updateContentLayout()
super.layoutSubviews()
}
private func setupUI() {
accessibilityIdentifier = "drone.task.remote.controlState"
backgroundColor = .white
addSubview(content)
[header, actionButton, noteLabel].forEach(content.addSubview)
[iconBackground, titleLabel, messageLabel].forEach(header.addSubview)
iconBackground.addSubview(icon)
iconBackground.backgroundColor = UIColor(hex: 0xFFF3E0)
iconBackground.layer.cornerRadius = 20.5
icon.contentMode = .scaleAspectFit
icon.tintColor = UIColor(hex: 0xF39819)
titleLabel.accessibilityTraits = .header
titleLabel.numberOfLines = 1
titleLabel.lineBreakMode = .byTruncatingTail
messageLabel.numberOfLines = 3
messageLabel.lineBreakMode = .byTruncatingTail
noteLabel.numberOfLines = 1
noteLabel.textAlignment = .center
noteLabel.accessibilityIdentifier = "drone.task.remote.controlNote"
var configuration = UIButton.Configuration.filled()
configuration.imagePadding = 10
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 20, weight: .semibold)
configuration.background.cornerRadius = 8
configuration.cornerStyle = .fixed
configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8)
actionButton.configuration = configuration
actionButton.configurationUpdateHandler = { [weak self] button in
guard let self, var configuration = button.configuration else { return }
let emphasizesAction = button.isEnabled || self.isPrimaryActionLoading
let foreground = emphasizesAction ? UIColor.white : UIColor(hex: 0x929BAE)
let font = UIFont.systemFont(ofSize: self.usesCompactLayout ? 16 : 18, weight: .semibold)
configuration.background.backgroundColor = emphasizesAction
? DroneDockStyle.primary : UIColor(hex: 0xEDF0F5)
configuration.baseForegroundColor = foreground
configuration.imageColorTransformer = UIConfigurationColorTransformer { _ in foreground }
// loading 会禁用按钮;显式设置最终文字色,避免系统禁用态再次把白字变暗。
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var result = attributes
result.font = font
result.foregroundColor = foreground
return result
}
button.configuration = configuration
}
actionActivityIndicator.color = .white
actionActivityIndicator.hidesWhenStopped = true
actionActivityIndicator.isUserInteractionEnabled = false
actionButton.addSubview(actionActivityIndicator)
actionButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
}
private func setupConstraints() {
content.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(18)
make.centerY.equalToSuperview()
}
header.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
headerHeight = make.height.equalTo(81).constraint
}
iconBackground.snp.makeConstraints { make in
make.top.leading.equalToSuperview()
iconSize = make.size.equalTo(41).constraint
}
icon.snp.makeConstraints { make in
make.center.equalToSuperview()
make.size.equalTo(iconBackground.snp.width).multipliedBy(24.0 / 41.0)
}
titleLabel.snp.makeConstraints { make in
make.top.trailing.equalToSuperview()
textLeading = make.leading.equalTo(iconBackground.snp.trailing).offset(12).constraint
titleHeight = make.height.equalTo(28).constraint
}
messageLabel.snp.makeConstraints { make in
messageTop = make.top.equalTo(titleLabel.snp.bottom).offset(6).constraint
make.leading.trailing.equalTo(titleLabel)
messageHeight = make.height.equalTo(45).constraint
}
actionButton.snp.makeConstraints { make in
actionTop = make.top.equalTo(header.snp.bottom).offset(16).constraint
make.leading.trailing.equalToSuperview()
actionHeight = make.height.equalTo(50).constraint
}
actionActivityIndicator.snp.makeConstraints { make in
make.centerY.equalToSuperview()
make.trailing.equalToSuperview().inset(14)
make.size.equalTo(20)
}
noteLabel.snp.makeConstraints { make in
noteTop = make.top.equalTo(actionButton.snp.bottom).offset(6).constraint
make.leading.trailing.bottom.equalToSuperview()
noteHeight = make.height.equalTo(16).constraint
}
}
private func updateContentLayout() {
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
let wasCompact = usesCompactLayout
usesCompactLayout = bounds.height < 190
let extreme = bounds.height < 120
let compact = usesCompactLayout
let diameter: CGFloat = extreme ? 24 : compact ? 32 : 41
let iconGap: CGFloat = extreme ? 8 : compact ? 10 : 12
let titleSize: CGFloat = extreme ? 17 : compact ? 20 : 22
let messageSize: CGFloat = compact ? 13 : 14
let textGap: CGFloat = extreme ? 3 : compact ? 4 : 6
let buttonGap: CGFloat = extreme ? 8 : compact ? 12 : 16
let buttonHeight: CGFloat = compact ? 44 : 50
let available = max(1, bounds.height - (extreme ? 8 : 12))
let textWidth = max(1, bounds.width - 36 - diameter - iconGap)
titleLabel.font = .systemFont(ofSize: titleSize, weight: .semibold)
let title = ceil(titleLabel.font.lineHeight)
let paragraph = NSMutableParagraphStyle()
paragraph.minimumLineHeight = messageSize * 1.5
paragraph.maximumLineHeight = messageSize * 1.5
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: messageSize),
.foregroundColor: UIColor(hex: 0x6A79A0), .paragraphStyle: paragraph
]
messageLabel.attributedText = NSAttributedString(string: presentation.message, attributes: attributes)
let measured = (presentation.message as NSString).boundingRect(
with: CGSize(width: textWidth, height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil).height
let hasNote = !extreme && DroneDockHomeMetric.usableText(presentation.actionNote) != nil
let note = hasNote ? ceil(noteLabel.font.lineHeight) : 0
let noteGap: CGFloat = hasNote ? 6 : 0
var lines = extreme || presentation.message.isEmpty ? 0 : 3
var body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines)))
while max(diameter, title + (lines > 0 ? textGap + body : 0)) + buttonGap + buttonHeight + note + noteGap > available,
lines > 0 {
lines -= 1
body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines)))
}
messageLabel.numberOfLines = max(1, lines)
messageLabel.isHidden = lines == 0
noteLabel.isHidden = !hasNote
effectiveScale = compact ? 0.8 : 1
headerHeight?.update(offset: max(diameter, title + (lines > 0 ? textGap + body : 0)))
iconSize?.update(offset: diameter)
iconBackground.layer.cornerRadius = diameter / 2
textLeading?.update(offset: iconGap)
titleHeight?.update(offset: title)
messageTop?.update(offset: lines > 0 ? textGap : 0)
messageHeight?.update(offset: body)
actionTop?.update(offset: buttonGap)
actionHeight?.update(offset: buttonHeight)
noteTop?.update(offset: noteGap)
noteHeight?.update(offset: note)
if wasCompact != usesCompactLayout { actionButton.setNeedsUpdateConfiguration() }
}
@objc private func primaryTapped() {
guard !isHidden, actionButton.isEnabled else { return }
onPrimaryAction?()
}
}
@@ -10,6 +10,8 @@ final class DroneDockTaskLiveView: UIView {
var onRequest: (() -> Void)?
/// 播放事件附带会话 ID,控制器据此丢弃离页或重连后的旧回调。
var onPlaybackEvent: ((DroneDockLivePlaybackEvent, UUID) -> Void)?
/// 只上报接收端启动、更新和停止等离散事件;不输出帧数据或解锁旧 SDK 日志。
var onDiagnosticEvent: ((String, [String: Any]) -> Void)?
private let playerLayer = AVPlayerLayer()
private let titleLabel = DroneDockStyle.label(size: 15, weight: .medium, color: .white)
@@ -31,12 +33,25 @@ final class DroneDockTaskLiveView: UIView {
private var labelsCenterY: Constraint?
private var isShowingCover = false
private var coverURL: URL?
private var coverTitle = "拍摄已完成"
private let rtcPlayer: any DroneDockLivePlaying
private var requestedRTC: [DroneDockVolcLiveConfiguration] = []
private var activeRTC: [DroneDockVolcLiveConfiguration] = []
private var requestedSessionID: UUID?
private var activeSessionID: UUID?
/// 图传区域实际显示与接收状态;不记录 RTC token 或播放地址。
var diagnosticFields: [String: Any] {
["playback_active": isPlaybackActive, "showing_cover": isShowingCover,
"cover_title": isShowingCover ? coverTitle : "",
"badge_visible": !sourceBadge.isHidden, "badge_title": sourceLabel.text ?? "",
"display_title": titleLabel.isHidden ? "" : titleLabel.text ?? "",
"display_message": messageLabel.isHidden ? "" : messageLabel.text ?? "",
"receiver_session": activeSessionID?.uuidString as Any? ?? NSNull(),
"receiver_rooms": activeRTC.map { ["role": $0.role, "room_id": $0.roomID] },
"local_preview_active": player != nil]
}
/// 保留原任务页图传区域的访问标识,外部负责 16:9 约束。
override init(frame: CGRect) {
rtcPlayer = DroneDockVolcLivePlayer()
@@ -99,11 +114,12 @@ final class DroneDockTaskLiveView: UIView {
updatePlayback()
}
/// 录制结束后仅展示静态封面;隐藏实时标记和重试按钮,旧模型不能恢复播放。
func showRecordingCover(_ show: Bool, url: URL?) {
guard isShowingCover != show || coverURL != url else { return }
/// 录制结束或中断回巢后展示静态封面;调用方提供本地标题,避免将中断任务显示为成功。
func showRecordingCover(_ show: Bool, url: URL?, title: String = "拍摄已完成") {
guard isShowingCover != show || coverURL != url || coverTitle != title else { return }
isShowingCover = show
coverURL = url
coverTitle = title
coverView.isHidden = !show
coverShade.isHidden = !show
coverIcon.isHidden = !show || url != nil
@@ -112,13 +128,13 @@ final class DroneDockTaskLiveView: UIView {
setPlaybackActive(false)
coverView.contentMode = .scaleAspectFill
coverView.kf.setImage(with: url)
titleLabel.text = "拍摄已完成"
titleLabel.text = title
titleLabel.isHidden = false
messageLabel.text = "拍摄封面 · 实时图传已结束"
messageLabel.isHidden = false
sourceBadge.isHidden = true
requestButton.isHidden = true
accessibilityLabel = "拍摄已完成,拍摄封面,实时图传已结束"
accessibilityLabel = "\(title),拍摄封面,实时图传已结束"
}
private func setupUI() {
@@ -209,9 +225,13 @@ final class DroneDockTaskLiveView: UIView {
if !requestedRTC.isEmpty, let sessionID = requestedSessionID {
releasePlayer()
guard activeSessionID != sessionID || activeRTC != requestedRTC else { return }
if activeSessionID != sessionID { releaseRTC() }
let isNewSession = activeSessionID != sessionID
if isNewSession { releaseRTC() }
activeSessionID = sessionID
activeRTC = requestedRTC
onDiagnosticEvent?(isNewSession ? "live.receiver.start_requested" : "live.receiver.rooms_updated", [
"receiver_session": sessionID.uuidString,
"rooms": requestedRTC.map { ["role": $0.role, "room_id": $0.roomID] }])
rtcPlayer.start(requestedRTC, in: rtcView) { [weak self] event in
guard let self, self.activeSessionID == sessionID else { return }
self.onPlaybackEvent?(event, sessionID)
@@ -232,16 +252,20 @@ final class DroneDockTaskLiveView: UIView {
activeURL = requestedURL
playerLayer.player = queue
queue.play()
onDiagnosticEvent?("live.local_preview.started", ["simulation": true])
}
private func releaseRTC() {
guard activeSessionID != nil else { return }
guard let sessionID = activeSessionID else { return }
onDiagnosticEvent?("live.receiver.stopped", ["receiver_session": sessionID.uuidString,
"rooms": activeRTC.map { ["role": $0.role, "room_id": $0.roomID] }])
activeSessionID = nil
activeRTC = []
rtcPlayer.stop()
}
private func releasePlayer() {
if player != nil { onDiagnosticEvent?("live.local_preview.stopped", ["simulation": true]) }
player?.pause()
looper?.disableLooping()
player?.removeAllItems()
@@ -18,13 +18,13 @@ final class DroneDockTaskStatusView: UIView {
private let iconView = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold)
private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
private let countdownLabel = DroneDockStyle.label(size: 13, weight: .medium, color: DroneDockStyle.primary)
private let deviceLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let actionRow = UIView()
private let primaryButton = UIButton(type: .system)
private let failureView = DroneDockTaskFailureView()
private let completedView = DroneDockTaskCompletedView()
private let shootingView = DroneDockTaskShootingView()
private let controlStateView = DroneDockTaskControlStateView()
private var presentation: DroneDockTaskPresentation?
private var countdownSeconds: Int?
private var contentTop: Constraint?
@@ -36,6 +36,35 @@ final class DroneDockTaskStatusView: UIView {
private var messageHeight: Constraint?
private var deviceHeight: Constraint?
/// 读取当前可见控件的实际文案和许可,用于对照录屏;不改变布局或任务状态。
var diagnosticFields: [String: Any] {
func descendants(_ root: UIView) -> [UIView] { [root] + root.subviews.flatMap(descendants) }
func isVisible(_ view: UIView) -> Bool {
if view === self { return !view.isHidden }
return !view.isHidden && (view.superview.map(isVisible) ?? false)
}
let visible = descendants(self).filter(isVisible)
let buttonIDs = ["drone.task.remote.primary", "drone.task.remote.refresh", "drone.task.remote.failureRetry",
"drone.task.remote.shooting.indicator"]
let button = visible.compactMap { $0 as? UIButton }.first { buttonIDs.contains($0.accessibilityIdentifier ?? "") }
?? visible.compactMap { $0 as? UIButton }.first
let label = visible.compactMap { $0 as? UILabel }.first {
["drone.task.remote.statusTitle", "drone.task.remote.failureTitle"].contains($0.accessibilityIdentifier ?? "")
}
let message = visible.compactMap { $0 as? UILabel }.first {
["drone.task.remote.statusMessage", "drone.task.remote.failureReason"].contains($0.accessibilityIdentifier ?? "")
}
let countdownState = countdownSeconds == nil ? "hidden" : countdownSeconds == 0 ? "zero" : "running"
return ["phase": presentation?.phase.rawValue ?? "uninitialized",
"title": label?.text ?? presentation?.title ?? "",
"message": message?.text ?? "", "message_visible": message != nil,
"action": presentation.map { String(describing: $0.action) } ?? "none",
"action_title": button?.configuration?.title ?? button?.title(for: .normal) ?? "",
"action_enabled": button?.isEnabled == true && isUserInteractionEnabled,
"action_loading": visible.compactMap { $0 as? UIActivityIndicatorView }.contains { $0.isAnimating },
"interactive": isUserInteractionEnabled, "countdown": countdownState]
}
/// 创建固定状态槽,完成、失败与进行中使用各自的内容布局。
override init(frame: CGRect) {
super.init(frame: frame)
@@ -52,20 +81,29 @@ final class DroneDockTaskStatusView: UIView {
}
/// 更新真实状态与动作许可;刷新期间保留内容,只暂时禁用主操作。
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false) {
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false, isPrimaryActionLoading: Bool = false) {
self.presentation = presentation
updateCountdown(seconds: presentation.countdownSeconds)
let isFailure = presentation.phase == .failed
let isCompleted = [.postShootUploading, .completed].contains(presentation.phase)
let isShooting = presentation.phase == .shooting
contentStack.isHidden = isFailure || isCompleted || isShooting
let isControlState = [.paused, .returning, .returned].contains(presentation.phase)
contentStack.isHidden = isFailure || isCompleted || isShooting || isControlState
failureView.isHidden = !isFailure
completedView.isHidden = !isCompleted
shootingView.isHidden = !isShooting
controlStateView.isHidden = !isControlState
completedView.setIdentifiersActive(isCompleted)
shootingView.setIdentifiersActive(isShooting)
titleLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusTitle"
messageLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusMessage"
controlStateView.setIdentifiersActive(isControlState)
titleLabel.accessibilityIdentifier = isCompleted || isShooting || isControlState ? nil : "drone.task.remote.statusTitle"
messageLabel.accessibilityIdentifier = isCompleted || isShooting || isControlState ? nil : "drone.task.remote.statusMessage"
if isControlState {
primaryButton.accessibilityIdentifier = nil
controlStateView.apply(presentation, isRefreshing: isRefreshing, isPrimaryActionLoading: isPrimaryActionLoading)
setNeedsLayout()
return
}
if isShooting {
primaryButton.accessibilityIdentifier = nil
shootingView.apply(presentation)
@@ -91,7 +129,7 @@ final class DroneDockTaskStatusView: UIView {
iconView.tintColor = style.color
let actionTitle = DroneDockHomeMetric.usableText(presentation.actionTitle)
primaryButton.isHidden = presentation.action == .none || actionTitle == nil
primaryButton.setTitle(actionTitle, for: .normal)
updatePrimaryButtonTitle()
primaryButton.isEnabled = presentation.isActionEnabled && !primaryButton.isHidden && !isRefreshing
primaryButton.backgroundColor = primaryButton.isEnabled
? DroneDockStyle.primary : DroneDockStyle.primary.withAlphaComponent(0.35)
@@ -100,19 +138,41 @@ final class DroneDockTaskStatusView: UIView {
setNeedsLayout()
}
/// 只刷新已到达阶段的剩余秒数,不变更主操作、服务端阶段或执行任何回调。
/// 只刷新开拍按钮中的剩余秒数,不变更操作许可、服务端阶段或执行任何回调。
func updateCountdown(seconds: Int?) {
let value = presentation?.phase == .ready ? seconds.map { max(0, $0) } : nil
let value = presentation?.phase == .ready && presentation?.action == .start
? seconds.map { max(0, $0) } : nil
guard value != countdownSeconds else { return }
let visibilityChanged = (value == nil) != (countdownSeconds == nil)
countdownSeconds = value
countdownLabel.text = value.map { "自动开拍倒计时:\($0) 秒" }
countdownLabel.isHidden = value == nil
if visibilityChanged { setNeedsLayout() }
updatePrimaryButtonTitle()
}
private func updatePrimaryButtonTitle() {
guard let presentation else { return }
let title = DroneDockHomeMetric.usableText(presentation.actionTitle)
let displayedTitle: String?
if presentation.phase == .ready, presentation.action == .start,
let title, let countdownSeconds {
displayedTitle = "\(title)(\(countdownSeconds)s)"
} else {
displayedTitle = title
}
// 秒数直接替换,避免系统按钮的标题过渡暂时保留旧数字。
UIView.performWithoutAnimation {
primaryButton.setTitle(displayedTitle, for: .normal)
primaryButton.layoutIfNeeded()
}
}
/// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。
override func layoutSubviews() {
if let phase = presentation?.phase, [.paused, .returning, .returned].contains(phase) {
super.layoutSubviews()
controlStateView.layoutIfNeeded()
effectiveScale = controlStateView.effectiveScale
usesCompactLayout = controlStateView.usesCompactLayout
return
}
if presentation?.phase == .shooting {
super.layoutSubviews()
shootingView.layoutIfNeeded()
@@ -140,6 +200,9 @@ final class DroneDockTaskStatusView: UIView {
private func setupUI() {
backgroundColor = .white
addSubview(controlStateView)
controlStateView.isHidden = true
controlStateView.onPrimaryAction = { [weak self] in self?.onPrimaryAction?() }
addSubview(shootingView)
shootingView.isHidden = true
addSubview(completedView)
@@ -155,7 +218,6 @@ final class DroneDockTaskStatusView: UIView {
addSubview(contentStack)
contentStack.addArrangedSubview(titleRow)
contentStack.addArrangedSubview(messageLabel)
contentStack.addArrangedSubview(countdownLabel)
contentStack.addArrangedSubview(deviceLabel)
contentStack.addArrangedSubview(actionRow)
titleRow.addSubview(iconView)
@@ -168,16 +230,12 @@ final class DroneDockTaskStatusView: UIView {
messageLabel.numberOfLines = 3
messageLabel.lineBreakMode = .byTruncatingTail
messageLabel.accessibilityIdentifier = "drone.task.remote.statusMessage"
countdownLabel.font = .monospacedDigitSystemFont(ofSize: 13, weight: .medium)
countdownLabel.numberOfLines = 1
countdownLabel.isHidden = true
countdownLabel.accessibilityIdentifier = "drone.task.remote.countdown"
deviceLabel.numberOfLines = 1
deviceLabel.lineBreakMode = .byTruncatingTail
deviceLabel.accessibilityIdentifier = "drone.task.remote.deviceStatus"
actionRow.addSubview(primaryButton)
primaryButton.layer.cornerRadius = 9
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
primaryButton.titleLabel?.font = .monospacedDigitSystemFont(ofSize: 15, weight: .semibold)
primaryButton.titleLabel?.lineBreakMode = .byTruncatingTail
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(.white.withAlphaComponent(0.9), for: .disabled)
@@ -185,6 +243,7 @@ final class DroneDockTaskStatusView: UIView {
}
private func setupConstraints() {
controlStateView.snp.makeConstraints { $0.edges.equalToSuperview() }
shootingView.snp.makeConstraints { $0.edges.equalToSuperview() }
completedView.snp.makeConstraints { $0.edges.equalToSuperview() }
failureView.snp.makeConstraints { make in make.edges.equalToSuperview() }
@@ -203,7 +262,6 @@ final class DroneDockTaskStatusView: UIView {
make.trailing.centerY.equalToSuperview()
}
messageLabel.snp.makeConstraints { make in messageHeight = make.height.equalTo(34).priority(999).constraint }
countdownLabel.snp.makeConstraints { make in make.height.equalTo(ceil(countdownLabel.font.lineHeight)).priority(999) }
deviceLabel.snp.makeConstraints { make in deviceHeight = make.height.equalTo(16).priority(999).constraint }
actionRow.snp.makeConstraints { make in make.height.equalTo(44) }
primaryButton.snp.makeConstraints { make in
@@ -214,9 +272,8 @@ final class DroneDockTaskStatusView: UIView {
private func updateContentLayout() {
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
let isExtreme = bounds.height < 120
let hasCountdown = countdownSeconds != nil
let horizontalInset: CGFloat = isExtreme ? 12 : 16
let verticalInset: CGFloat = isExtreme ? (hasCountdown ? 4 : 6) : 12
let verticalInset: CGFloat = isExtreme ? 6 : 12
let width = max(1, bounds.width - horizontalInset * 2)
let availableHeight = max(1, bounds.height - verticalInset * 2)
let message = DroneDockHomeMetric.usableText(presentation.message)
@@ -228,20 +285,18 @@ final class DroneDockTaskStatusView: UIView {
width: width - 46, lines: 2))
let naturalMessage = hasMessage ? Self.textHeight(message, font: .systemFont(ofSize: 14), width: width, lines: 3) : 0
let naturalDevice = hasDevice ? UIFont.systemFont(ofSize: 12).lineHeight : 0
let countdownTextHeight = hasCountdown ? ceil(countdownLabel.font.lineHeight) : 0
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0) + (hasCountdown ? 1 : 0)) * 10
let naturalHeight = naturalTitle + naturalMessage + countdownTextHeight + naturalDevice + 44 + naturalGaps
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0)) * 10
let naturalHeight = naturalTitle + naturalMessage + naturalDevice + 44 + naturalGaps
effectiveScale = min(1, max(0.8, availableHeight / max(1, naturalHeight)))
usesCompactLayout = bounds.height < 190 || naturalHeight * effectiveScale > availableHeight
// 先收紧图标和间距;只有不足九成空间时才缩小文字。
let fontScale: CGFloat = effectiveScale >= 0.9 ? 1 : effectiveScale / 0.9
titleLabel.font = .systemFont(ofSize: isExtreme && hasCountdown ? 17 : max(17, 22 * fontScale), weight: .semibold)
titleLabel.font = .systemFont(ofSize: max(17, 22 * fontScale), weight: .semibold)
messageLabel.font = .systemFont(ofSize: max(12, 14 * fontScale))
deviceLabel.font = .systemFont(ofSize: 12)
let icon: CGFloat = isExtreme ? 20 : usesCompactLayout ? 24 : 36 * effectiveScale
let gap: CGFloat = isExtreme ? (hasCountdown ? 2 : 4)
: hasCountdown && usesCompactLayout ? 6 : max(4, 10 * effectiveScale)
let gap: CGFloat = isExtreme ? 4 : max(4, 10 * effectiveScale)
let titleGap: CGFloat = usesCompactLayout ? 8 : 10 * effectiveScale
titleLabel.numberOfLines = usesCompactLayout ? 1 : 2
messageLabel.numberOfLines = usesCompactLayout ? 2 : 3
@@ -255,8 +310,8 @@ final class DroneDockTaskStatusView: UIView {
width: width, lines: messageLineCount)
let deviceTextHeight = deviceLabel.isHidden ? 0 : ceil(deviceLabel.font.lineHeight)
var contentHeight: CGFloat {
titleHeight + bodyHeight + countdownTextHeight + deviceTextHeight + 44
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1) + (hasCountdown ? 1 : 0)) * gap
titleHeight + bodyHeight + deviceTextHeight + 44
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1)) * gap
}
while contentHeight > availableHeight && messageLineCount > 1 && !messageLabel.isHidden {
messageLineCount -= 1
@@ -301,6 +356,7 @@ final class DroneDockTaskStatusView: UIView {
case .postShootUploadFailed: ("exclamationmark.circle.fill", DroneDockStyle.warning)
case .paused: ("pause.circle.fill", DroneDockStyle.warning)
case .returning: ("arrow.uturn.backward.circle.fill", DroneDockStyle.warning)
case .returned: ("house.circle.fill", DroneDockStyle.warning)
case .completed: ("checkmark.circle.fill", DroneDockStyle.success)
case .failed: ("xmark.circle.fill", UIColor(hex: 0xD46B62))
case .blocked, .readError: ("exclamationmark.circle.fill", DroneDockStyle.warning)
@@ -279,6 +279,14 @@ final class DroneShootingTaskSafetyButton: UIButton {
private let controlTitleLabel = DroneDockStyle.label(size: 15, weight: .semibold)
private let controlSubtitleLabel = DroneDockStyle.label(size: 10)
private let controlIconView: UIImageView
private let activityIndicator = UIActivityIndicatorView(style: .medium)
/// 输出实际呈现的控件状态,供页面按变化记录;不推导业务许可。
var diagnosticFields: [String: Any] {
["title": controlTitleLabel.text ?? "", "subtitle": controlSubtitleLabel.text ?? "",
"enabled": isEnabled, "loading": activityIndicator.isAnimating,
"accessibility_value": accessibilityValue ?? ""]
}
/// 创建暂停或返航按钮;返回状态只由 ViewModel 决定。
init(symbol: String, color: UIColor, filled: Bool) {
@@ -292,6 +300,9 @@ final class DroneShootingTaskSafetyButton: UIButton {
controlSubtitleLabel.textColor = filled ? UIColor.white.withAlphaComponent(0.85) : DroneDockStyle.secondary
controlIconView.tintColor = filled ? .white : color
controlIconView.contentMode = .scaleAspectFit
activityIndicator.color = filled ? .white : color
activityIndicator.hidesWhenStopped = true
activityIndicator.isUserInteractionEnabled = false
let titles = UIStackView(arrangedSubviews: [controlTitleLabel, controlSubtitleLabel])
titles.axis = .vertical
titles.spacing = 3
@@ -308,6 +319,11 @@ final class DroneShootingTaskSafetyButton: UIButton {
make.trailing.lessThanOrEqualToSuperview().offset(-9)
}
controlIconView.snp.makeConstraints { make in make.size.equalTo(27) }
addSubview(activityIndicator)
activityIndicator.snp.makeConstraints { make in
make.center.equalTo(controlIconView)
make.size.equalTo(27)
}
controlTitleLabel.adjustsFontSizeToFitWidth = true
controlTitleLabel.minimumScaleFactor = 0.8
controlSubtitleLabel.adjustsFontSizeToFitWidth = true
@@ -317,14 +333,18 @@ final class DroneShootingTaskSafetyButton: UIButton {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 应用语义明确的按钮标题、辅助说明及防重复点击状态。
func apply(title: String, subtitle: String, enabled: Bool) {
/// 应用独立操作许可和加载状态;加载时仅替换本按钮图标,不改变布局或其他按钮。
func apply(title: String, subtitle: String, enabled: Bool, isLoading: Bool = false) {
controlTitleLabel.text = title
controlSubtitleLabel.text = subtitle
isEnabled = enabled
alpha = enabled ? 1 : 0.42
isEnabled = enabled && !isLoading
alpha = enabled || isLoading ? 1 : 0.42
controlIconView.alpha = isLoading ? 0 : 1
if isLoading { activityIndicator.startAnimating() }
else { activityIndicator.stopAnimating() }
activityIndicator.accessibilityIdentifier = accessibilityIdentifier.map { "\($0).loading" }
accessibilityLabel = title
accessibilityValue = subtitle
accessibilityValue = isLoading ? "处理中,\(subtitle)" : subtitle
}
/// 切换同一位置的暂停/继续或返航/取消图标,不改变按钮布局。