feat(drone-dock): 完善真实联调、状态轮询与准备页反馈

开放 Release 真实操作并保留 Debug 拦截;恢复前台 shooting 串行轮询;统一打印机巢请求与完整原值响应;优化长点位名称、未拍摄文案、报备失败及已结束任务提示,移除成功回执 UI。补充相关测试、离线策略检查和联调说明。
This commit is contained in:
2026-11-02 16:26:50 +08:00
parent b21a3b6cb6
commit 2d86ec8cd7
37 changed files with 1298 additions and 411 deletions
@@ -181,6 +181,14 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
/// 首次创建并召唤;成功后进入原任务,再次查看不经过创建或召唤接口。
private func createSelectedTask() {
DroneDockDiagnostics.event("preparation.confirm_tapped", taskID: viewModel.createdTask?.taskID, fields: [
"order_number": viewModel.order.orderNumber as Any? ?? NSNull(),
"scenic_id": viewModel.context.scenicID,
"spot_id": viewModel.selectedSpotID as Any? ?? NSNull(),
"air_line_id": viewModel.selectedRouteID as Any? ?? NSNull(),
"enabled": viewModel.isPrimaryActionEnabled,
"blocked": viewModel.isTaskSubmissionBlocked
])
guard !isRefreshing, !isStartingCreation else { return }
if viewModel.canOpenShootingTask {
_ = openShootingTask(automatically: false)
@@ -199,17 +207,29 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
guard let self,
let path = self.dataSource.indexPath(for: .shootResult) ?? self.dataSource.indexPath(for: .creationResult) else { return }
self.collectionView.scrollToItem(at: path, at: .top, animated: true)
self.showFilingFailureIfNeeded()
}
}
}
/// 只在准备页可见且召唤已成功时导航一次;返回后允许主动查看同一任务。
/// 报备问题在明确提交失败后提示一次,后台及设备轮询不会反复弹窗。
private func showFilingFailureIfNeeded() {
guard isPageVisible, isApplicationActive, presentedViewController == nil,
let failure = viewModel.summonFailure ?? viewModel.creationFailure,
failure.requiresFiling else { return }
let alert = UIAlertController(title: failure.title, message: failure.message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "我知道了", style: .default))
present(alert, animated: true)
}
/// 成功后自动导航一次;失败的已结束任务只在用户明确点击时查看原任务。
@discardableResult
private func openShootingTask(automatically: Bool) -> Bool {
guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask,
let taskID = viewModel.createdTask?.taskID,
let navigationController, navigationController.topViewController === self,
!automatically || automaticallyOpenedTaskID != taskID else { return false }
!automatically || (viewModel.shootResponse != nil && automaticallyOpenedTaskID != taskID) else { return false }
DroneDockDiagnostics.event("navigation.open_task", taskID: taskID)
automaticallyOpenedTaskID = taskID
let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context)
navigationController.pushViewController(controller, animated: true)
@@ -284,17 +304,15 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
return cell
case .creationResult:
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
cell.apply(task: self.viewModel.createdTask, errorMessage: self.viewModel.taskCreationErrorMessage,
outcomeUnknown: self.viewModel.taskCreationOutcomeUnknown)
if let failure = self.viewModel.creationFailure {
cell.apply(failure: failure, identifier: "drone.preparation.creationResponse")
}
return cell
case .shootResult:
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
cell.applyShoot(taskID: self.viewModel.createdTask?.taskID,
dataJSON: self.viewModel.shootDataJSON,
errorMessage: self.viewModel.shootErrorMessage,
isLoading: self.viewModel.isSummoning,
hasSucceeded: self.viewModel.shootResponse != nil,
outcomeUnknown: self.viewModel.summonOutcomeUnknown)
if let failure = self.viewModel.summonFailure {
cell.apply(failure: failure, identifier: "drone.preparation.shootResponse")
}
return cell
case .emptyPoints, .emptyRoutes, .status:
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DronePreparationEmptyCell
@@ -344,11 +362,10 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
} else {
snapshot.appendItems([.status], toSection: .status)
}
if viewModel.createdTask != nil || (viewModel.errorMessage == nil && viewModel.projectInfo != nil && viewModel.taskCreationErrorMessage != nil) {
if viewModel.creationFailure != nil {
snapshot.appendItems([.creationResult], toSection: .creationResult)
}
if viewModel.createdTask != nil,
viewModel.isSummoning || viewModel.shootResponse != nil || viewModel.shootErrorMessage != nil {
if viewModel.summonFailure != nil {
snapshot.appendItems([.shootResult], toSection: .shootResult)
}
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
@@ -360,7 +377,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|| previous.itemIdentifiers.contains(.emptyPoints) != snapshot.itemIdentifiers.contains(.emptyPoints)
|| previous.itemIdentifiers.contains(.emptyRoutes) != snapshot.itemIdentifiers.contains(.emptyRoutes)
|| previousRouteCount != snapshot.numberOfItems(inSection: .routes)
if layoutChanged { collectionView.collectionViewLayout.invalidateLayout() }
if layoutChanged || viewModel.projectInfo != nil { collectionView.collectionViewLayout.invalidateLayout() }
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
guard let self else { return }
let kind = UICollectionView.elementKindSectionHeader
@@ -374,21 +391,21 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, _ in
UICollectionViewCompositionalLayout { [weak self] index, environment in
guard let self, let section = Section(rawValue: index) else { return nil }
let height: NSCollectionLayoutDimension
let width: NSCollectionLayoutDimension
switch section {
case .order: height = .estimated(100); width = .fractionalWidth(1)
case .points:
height = .absolute(self.viewModel.spots.isEmpty ? 150 : 64)
width = self.viewModel.spots.isEmpty ? .fractionalWidth(1) : .absolute(160)
height = .absolute(self.viewModel.spots.isEmpty ? 150 : DronePreparationPointCell.preferredHeight(
names: self.viewModel.spots.map(\.name), width: 200))
width = self.viewModel.spots.isEmpty ? .fractionalWidth(1) : .absolute(200)
case .routes:
height = self.viewModel.routes.isEmpty ? .absolute(160) : .estimated(64)
width = .fractionalWidth(1)
case .status: height = .absolute(160); width = .fractionalWidth(1)
case .creationResult: height = .absolute(380); width = .fractionalWidth(1)
case .shootResult: height = .absolute(420); width = .fractionalWidth(1)
case .creationResult, .shootResult: height = .estimated(100); width = .fractionalWidth(1)
}
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
let group = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item])
@@ -402,7 +419,9 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
&& (section == .points || (section == .routes && !self.viewModel.spots.isEmpty))
if showsHeading {
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(section == .points ? 46 : 64)),
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(section == .points ? 46 : DronePreparationHeadingView.preferredHeight(
title: self.viewModel.selectedSpot.map { "\($0.name)的航线" } ?? "拍摄航线",
detail: "共 \(self.viewModel.routes.count) 条", width: environment.container.effectiveContentSize.width - 32))),
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)]
}
return layout
@@ -3,7 +3,7 @@ import UIKit
/// 组装真实拍摄任务页;构造时不发请求,页面出现后才读取同一任务。
@MainActor
enum DroneDockShootingTaskEntry {
/// 使用已有任务读取状态,Release 可手动图传;不注入任务创建或飞控服务。
/// 使用已有任务读取状态;Release 注入已授权的真实控制,Debug 保持只读。
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext) -> UIViewController {
let client = NetworkServices.shared.apiClient
@@ -14,7 +14,10 @@ enum DroneDockShootingTaskEntry {
currentContext: { DroneDockHomeViewController.currentContext() })
return DroneDockShootingTaskViewController(viewModel: DroneDockShootingTaskViewModel(
context: context, taskID: taskID, order: order,
service: DroneDockShootingAPI(client: NetworkServices.shared.apiClient),
service: DroneDockShootingAPI(client: client),
startService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockStartShootAPI(client: client),
commandService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockCommandAPI(client: client),
resummonService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockShootAPI(client: client),
currentContext: { DroneDockHomeViewController.currentContext() }
), liveViewModel: live)
}
@@ -1,7 +1,7 @@
import SnapKit
import UIKit
/// 拍摄任务页:正式入口读取状态并手动开启图传,飞控仅在隔离模拟入口注入。
/// 拍摄任务页:前台轮询状态、手动图传;Release 开放已授权控制,Debug 仅模拟控制。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
@@ -23,6 +23,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private var bottomInset: CGFloat = -1
private let materialsControllerFactory: @MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private let simulationRecordsProvider: (@MainActor () -> String)?
private let shootingPollDelay: @Sendable (UInt64) async throws -> Void
private var pollTask: Task<Void, Never>?
private var pollGeneration = 0
private var refreshTask: Task<Void, Never>?
private var startTask: Task<Void, Never>?
private var commandTask: Task<Void, Never>?
@@ -41,12 +44,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
init(viewModel: DroneDockShootingTaskViewModel,
liveViewModel: DroneDockLiveViewModel? = nil,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
simulationRecordsProvider: (@MainActor () -> String)? = nil) {
simulationRecordsProvider: (@MainActor () -> String)? = nil,
shootingPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
self.viewModel = viewModel
self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel(
context: viewModel.context, taskID: viewModel.taskID,
currentContext: { DroneDockHomeViewController.currentContext() })
self.simulationRecordsProvider = simulationRecordsProvider
self.shootingPollDelay = shootingPollDelay
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
context: context, order: order,
@@ -61,6 +66,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
deinit {
pollTask?.cancel()
refreshTask?.cancel()
startTask?.cancel()
commandTask?.cancel()
@@ -186,10 +192,11 @@ final class DroneDockShootingTaskViewController: BaseViewController {
name: UIApplication.didBecomeActiveNotification, object: nil)
}
/// 每次完整进入任务页只查询一次,不定时重读同一任务。
/// 完整进入任务页立即读取,随后仅在前台可见时轮询同一任务。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isPageVisible = true
logEvent("page.appeared")
isApplicationActive = UIApplication.shared.applicationState == .active
refreshTaskIfVisible()
refreshLiveIfVisible(automatically: true)
@@ -199,6 +206,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
logEvent("page.disappeared")
cancelRefresh()
stopLive()
}
@@ -227,6 +235,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
private func primaryActionTriggered() {
logEvent("action.primary", fields: ["action": String(describing: viewModel.presentation.action),
"enabled": viewModel.presentation.isActionEnabled])
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand,
@@ -265,12 +275,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
present(alert, animated: true)
}
/// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。
private func refreshTaskIfVisible() {
/// 前台可见时串行读取;轮询失败保留旧快照,下个周期再读,不重复弹出提示。
private func refreshTaskIfVisible(isPolling: Bool = false) {
guard isPageVisible, isApplicationActive, !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
@@ -283,13 +295,39 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.refreshTask = nil
self.isRequesting = false
self.applySnapshot()
if self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.scheduleNextPoll()
if !isPolling, self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.showToast("刷新失败,当前显示上次数据:\(error)")
}
}
}
/// 每次读取或控制流程结束后仅安排一个可取消的延时,不持有页面等待计时结束。
private func scheduleNextPoll() {
cancelScheduledPoll()
guard isPageVisible, isApplicationActive, viewModel.canContinuePolling,
!isRequesting, !isStartingAction, !isSendingSafetyAction, !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 }
self.pollTask = nil
self.refreshTaskIfVisible(isPolling: true)
}
}
private func cancelScheduledPoll() {
if pollTask != nil { logEvent("poll.cancelled") }
pollGeneration &+= 1
pollTask?.cancel()
pollTask = nil
}
private func cancelRefresh() {
cancelScheduledPoll()
requestGeneration &+= 1
refreshTask?.cancel()
refreshTask = nil
@@ -310,6 +348,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。
private func startShootingIfAllowed() {
guard !isStartingAction, !isSendingSafetyAction, !isResummoningAction, viewModel.canStartShooting else { return }
cancelScheduledPoll()
requestGeneration &+= 1
let generation = requestGeneration
isStartingAction = true
@@ -322,6 +361,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.startTask = nil
self.isStartingAction = false
self.applySnapshot()
self.scheduleNextPoll()
if let error = self.viewModel.startErrorMessage {
self.showToast(error)
} else if let error = self.viewModel.errorMessage {
@@ -330,11 +370,12 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
}
/// 重召唤只在显式模拟入口开放;点击后锁定按钮,使用原任务 ID,并由状态回查更新页面。
/// 重召唤使用原任务 ID,回执后再查询状态,避免从受理结果推断设备已到达。
private func resummonIfAllowed() {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
guard allowsControlActions, isPageVisible, isApplicationActive,
!isResummoningAction, !isStartingAction, !isSendingSafetyAction,
!isRequesting, viewModel.canResummon else { return }
cancelScheduledPoll()
requestGeneration &+= 1
let generation = requestGeneration
isResummoningAction = true
@@ -347,12 +388,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.resummonTask = nil
self.isResummoningAction = false
self.applySnapshot()
self.scheduleNextPoll()
if let error = self.viewModel.resummonErrorMessage {
self.showToast(error)
} else if self.viewModel.hasSubmittedResummon, let error = self.viewModel.errorMessage {
self.showToast("模拟重召唤已受理,状态刷新失败:\(error)")
self.showToast("重召唤已受理,状态刷新失败:\(error)")
} else if self.viewModel.hasSubmittedResummon {
self.showToast("本地模拟重召唤已受理,未发送设备指令")
self.showToast(self.simulationRecordsProvider != nil
? "本地模拟重召唤已受理,未发送设备指令" : "重召唤请求已受理,请等待任务状态更新")
} else if let error = self.viewModel.errorMessage {
self.showToast(error)
}
@@ -363,6 +406,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func refreshLiveIfVisible(automatically: Bool = false) {
guard !automatically || liveViewModel.loadsAutomatically else { return }
guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return }
logEvent("live.request", fields: ["automatic": automatically])
liveGeneration &+= 1
let generation = liveGeneration
liveTask = Task { @MainActor [weak self] in
@@ -385,16 +429,20 @@ final class DroneDockShootingTaskViewController: BaseViewController {
feedPlaceholder.apply(liveViewModel)
}
/// 仅模拟入口响应安全按钮;返航会中断任务,先明确展示其含义再提交一次。
/// 返航会中断任务,先明确展示其含义再提交一次;Debug 只开放隔离模拟入口。
private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
logEvent("action.safety", fields: ["command": command.rawValue, "enabled": viewModel.canSendCommand(command)])
guard allowsControlActions, isPageVisible, isApplicationActive,
presentedViewController == nil, !isSendingSafetyAction, !isStartingAction,
!isResummoningAction, !isRequesting, viewModel.canSendCommand(command) else { return }
if command == .returnHome {
let alert = UIAlertController(title: "立即返航(本地模拟)",
message: "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。", preferredStyle: .alert)
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: .destructive) { [weak self] _ in
alert.addAction(UIAlertAction(title: simulated ? "模拟返航" : "立即返航", style: .destructive) { [weak self] _ in
self?.sendSafetyCommand(command)
})
present(alert, animated: true)
@@ -405,9 +453,10 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 同步锁覆盖异步调度间隙;界面保留旧快照,只有同任务回查成功才更新阶段。
private func sendSafetyCommand(_ command: DroneDockSafetyCommand) {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
guard allowsControlActions, isPageVisible, isApplicationActive,
!isSendingSafetyAction, !isStartingAction, !isResummoningAction, !isRequesting,
viewModel.canSendCommand(command) else { return }
cancelScheduledPoll()
requestGeneration &+= 1
let generation = requestGeneration
isSendingSafetyAction = true
@@ -420,12 +469,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.commandTask = nil
self.isSendingSafetyAction = false
self.applySnapshot()
self.scheduleNextPoll()
if let error = self.viewModel.commandErrorMessage {
self.showToast(error)
} else if let error = self.viewModel.errorMessage {
self.showToast("模拟指令已受理,状态刷新失败:\(error)")
self.showToast("指令已受理,状态刷新失败:\(error)")
} else {
self.showToast("本地模拟指令已受理,未发送设备指令")
self.showToast(self.simulationRecordsProvider != nil
? "本地模拟指令已受理,未发送设备指令" : "指令已受理,请等待任务状态更新")
}
}
}
@@ -445,6 +496,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
@objc private func applicationWillResignActive() {
logEvent("app.inactive")
isApplicationActive = false
cancelRefresh()
stopLive()
@@ -453,9 +505,22 @@ final class DroneDockShootingTaskViewController: BaseViewController {
@objc private func applicationDidBecomeActive() {
guard !isApplicationActive else { return }
isApplicationActive = true
logEvent("app.active")
refreshTaskIfVisible()
refreshLiveIfVisible(automatically: true)
}
private func logEvent(_ name: String, fields: [String: Any] = [:]) {
var fields = fields
fields["source"] = simulationRecordsProvider == nil ? "task_page" : "local_simulation"
fields["scenic_id"] = viewModel.context.scenicID
fields["order_number"] = viewModel.order.orderNumber
DroneDockDiagnostics.event(name, taskID: viewModel.taskID, fields: fields)
}
private var allowsControlActions: Bool {
simulationRecordsProvider != nil || !DeviceCommandDebugPolicy.blocksFlightRequests
}
}
/// 以可选择的 JSON 文本展示本地模拟请求与回执,避免与真实接口联调混淆。
@@ -555,10 +620,11 @@ private final class DroneDockTaskSafetyView: UIView {
/// 保持两列固定布局,暂停/继续与返航/取消由快照中的指令白名单决定。
func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool) {
let commands = model.availableSafetyCommands
let allowsControls = isSimulation || !DeviceCommandDebugPolicy.blocksFlightRequests
pauseCommand = commands.contains(.resume) ? .resume : .pause
returnCommand = commands.contains(.cancelReturn) ? .cancelReturn : .returnHome
header.text = model.commandOutcomeUnknown ? "安全控制 · 结果待核对"
: model.isSendingCommand ? "安全控制 · 本地模拟发送中"
: model.isSendingCommand ? (isSimulation ? "安全控制 · 本地模拟发送中" : "安全控制 · 指令发送中")
: isSimulation ? "安全控制 · 本地模拟,不发送设备指令" : "安全控制"
for (button, command) in [(pauseButton, pauseCommand), (returnButton, returnCommand)] {
let title: String
@@ -569,10 +635,10 @@ private final class DroneDockTaskSafetyView: UIView {
case .returnHome: title = "立即返航"; subtitle = "中断任务"
case .cancelReturn: title = "取消返航"; subtitle = "不恢复已中断任务"
}
let enabled = isSimulation && isInteractive && model.canSendCommand(command)
let detail = model.activeCommand == command ? "本地模拟发送中…"
let enabled = allowsControls && isInteractive && model.canSendCommand(command)
let detail = model.activeCommand == command ? (isSimulation ? "本地模拟发送中…" : "指令发送中…")
: model.commandOutcomeUnknown ? "结果待核对"
: !isSimulation || !commands.contains(command) ? "暂不可用" : subtitle
: !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")
@@ -1,12 +1,11 @@
import SnapKit
import UIKit
/// 在准备页展示任务创建或召唤请求的回执,保留 data 原文结构并支持滚动与选择文本。
/// 准备页业务失败卡片,完整换行展示原因,不展示成功回执或接口 JSON。
@MainActor
final class DroneDockTaskCreationResultCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 16, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let responseView = UITextView()
private let detailLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
@@ -14,23 +13,13 @@ final class DroneDockTaskCreationResultCell: UICollectionViewCell {
contentView.layer.cornerRadius = 10
titleLabel.numberOfLines = 0
detailLabel.numberOfLines = 0
responseView.backgroundColor = .clear
responseView.isEditable = false
responseView.isSelectable = true
responseView.alwaysBounceVertical = true
responseView.textContainerInset = .zero
responseView.textContainer.lineFragmentPadding = 0
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
[titleLabel, detailLabel, responseView].forEach(contentView.addSubview)
titleLabel.textColor = DroneDockStyle.warning
[titleLabel, detailLabel].forEach(contentView.addSubview)
titleLabel.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview().inset(12)
}
detailLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(6)
make.leading.trailing.equalTo(titleLabel)
}
responseView.snp.makeConstraints { make in
make.top.equalTo(detailLabel.snp.bottom).offset(12)
make.top.equalTo(titleLabel.snp.bottom).offset(8)
make.leading.trailing.equalTo(titleLabel)
make.bottom.equalToSuperview().inset(12)
}
@@ -39,42 +28,10 @@ final class DroneDockTaskCreationResultCell: UICollectionViewCell {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 成功保留完整 data,失败显示真实错误,不构造任务 ID 或成功响应。
func apply(task: DroneDockCreatedTask?, errorMessage: String?, outcomeUnknown: Bool) {
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
if let task {
titleLabel.text = "任务已创建 · ID \(task.taskID)"
titleLabel.textColor = DroneDockStyle.success
detailLabel.text = "tasks/create 返回的 data"
responseView.font = .monospacedSystemFont(ofSize: 12, weight: .regular)
if responseView.text != task.dataJSON { responseView.text = task.dataJSON }
} else {
titleLabel.text = outcomeUnknown ? "任务创建结果待确认" : "任务创建未成功"
titleLabel.textColor = DroneDockStyle.warning
detailLabel.text = outcomeUnknown ? "请先核对订单任务,避免重复创建" : "接口返回的错误信息"
responseView.font = .systemFont(ofSize: 14)
responseView.text = errorMessage
}
responseView.textColor = DroneDockStyle.text
}
/// 展示 shoot 回执;提交成功不代表无人机已到达,结果未知不能引导直接重发。
func applyShoot(taskID: Int?, dataJSON: String?, errorMessage: String?, isLoading: Bool,
hasSucceeded: Bool, outcomeUnknown: Bool) {
responseView.accessibilityIdentifier = "drone.preparation.shootResponse"
let suffix = taskID.map { " · ID \($0)" } ?? ""
let title: String
if isLoading { title = "正在召唤无人机" }
else if hasSucceeded { title = "召唤请求已提交" }
else { title = outcomeUnknown ? "召唤结果待核对" : "召唤请求未成功" }
titleLabel.text = title + suffix
titleLabel.textColor = hasSucceeded ? DroneDockStyle.success : errorMessage == nil ? DroneDockStyle.text : DroneDockStyle.warning
if isLoading { detailLabel.text = "正在为已创建的任务提交召唤请求" }
else if hasSucceeded { detailLabel.text = "shoot 返回信息;飞行进度以任务状态为准" }
else { detailLabel.text = outcomeUnknown ? "请先核对任务状态,避免重复发送召唤" : "任务已保留,可重试召唤" }
responseView.font = dataJSON == nil ? .systemFont(ofSize: 14) : .monospacedSystemFont(ofSize: 12, weight: .regular)
let text = dataJSON ?? errorMessage ?? (hasSucceeded ? "接口已返回业务成功,未提供可展示的 data。" : "")
if responseView.text != text { responseView.text = text }
responseView.textColor = DroneDockStyle.text
/// 只接收面向用户的错误模型,成功 data 不进入视图层。
func apply(failure: DroneDockPreparationFailure, identifier: String) {
titleLabel.text = failure.title
detailLabel.text = failure.message
detailLabel.accessibilityIdentifier = identifier
}
}
@@ -58,7 +58,9 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
roomConfig.isAutoSubscribeVideo = false
let user = ByteRTCUserInfo()
user.userId = configuration.userID
DroneDockDiagnostics.event("rtc.join_requested", fields: ["engine_session": generation.uuidString])
let result = room.joinRoom(configuration.token, userInfo: user, userVisibility: false, roomConfig: roomConfig)
DroneDockDiagnostics.event("rtc.join_returned", fields: ["engine_session": generation.uuidString, "code": result])
guard result == 0 else {
onEvent(.failed("图传进房失败(\(result))")); stop(); return
}
@@ -93,6 +95,8 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
}
private func receive(_ event: DroneDockVolcEvent, roomID: String) {
// 不把 SDK 回调对象、房间 ID、用户 ID 或 extraInfo 原样写入日志。
DroneDockDiagnostics.event("rtc.callback", fields: ["engine_session": generation.uuidString, "result": event.diagnosticValue])
switch event {
case .published(let id, let sourceRoom, let index, let published):
guard sourceRoom == roomID, index == 0 else { return }
@@ -107,6 +111,8 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
canvas.renderMode = .fit
let renderResult = engine?.setRemoteVideoCanvas(id, withCanvas: canvas)
let subscribeResult = room?.subscribeStreamVideo(id, subscribe: true)
DroneDockDiagnostics.event("rtc.subscribe_returned", fields: ["engine_session": generation.uuidString,
"render_code": renderResult as Any? ?? NSNull(), "subscribe_code": subscribeResult as Any? ?? NSNull()])
if renderResult != 0 || subscribeResult != 0 { onEvent?(.failed("图传订阅失败,请重试")) }
case .frame(let id):
guard streamID == id else { return }
@@ -114,6 +120,7 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
onEvent?(.firstFrame)
case .failed(let code): onEvent?(.failed("图传连接失败(\(code)),请重试"))
case .expired: onEvent?(.expired)
case .roomState: break
}
}
}
@@ -124,6 +131,18 @@ private enum DroneDockVolcEvent: Sendable {
case frame(String)
case failed(Int)
case expired
case roomState(Int)
/// 仅输出事件种类及错误码,不含 SDK 身份和凭证。
var diagnosticValue: String {
switch self {
case .published(_, _, let index, let published): return "published(index=\(index),published=\(published))"
case .frame: return "first_frame"
case .failed(let code): return "failed(code=\(code))"
case .expired: return "expired"
case .roomState(let code): return "room_state(code=\(code))"
}
}
}
/// SDK 回调桥接;所有 UI 与引擎操作由上层切回主 Actor 后执行。
@@ -138,6 +157,7 @@ private final class DroneDockVolcDelegate: NSObject, ByteRTCEngineDelegate, Byte
func rtcRoom(_ rtcRoom: ByteRTCRoom, onRoomStateChanged roomId: String, withUid uid: String,
state: Int, extraInfo: String) {
emit(.roomState(state))
if state != 0 { emit(.failed(state)) }
}
@@ -108,21 +108,24 @@ final class DronePreparationPointCell: UICollectionViewCell {
thumbnail.backgroundColor = DroneDockStyle.background
thumbnail.layer.cornerRadius = 5
thumbnail.clipsToBounds = true
[thumbnail, nameLabel, countLabel].forEach(contentView.addSubview)
nameLabel.numberOfLines = 0
nameLabel.lineBreakMode = .byWordWrapping
nameLabel.accessibilityIdentifier = "drone.preparation.point.name"
let labels = UIStackView(arrangedSubviews: [nameLabel, countLabel])
labels.axis = .vertical
labels.spacing = 6
[thumbnail, labels].forEach(contentView.addSubview)
thumbnail.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(8)
make.centerY.equalToSuperview()
make.size.equalTo(48)
}
nameLabel.snp.makeConstraints { make in
make.bottom.equalTo(contentView.snp.centerY).offset(-3)
labels.snp.makeConstraints { make in
make.centerY.equalToSuperview()
make.top.greaterThanOrEqualToSuperview().offset(8)
make.bottom.lessThanOrEqualToSuperview().inset(8)
make.leading.equalTo(thumbnail.snp.trailing).offset(8)
make.trailing.equalToSuperview().inset(6)
}
countLabel.snp.makeConstraints { make in
make.top.equalTo(contentView.snp.centerY).offset(3)
make.leading.equalTo(nameLabel)
make.trailing.equalToSuperview().inset(5)
make.trailing.equalToSuperview().inset(8)
}
isAccessibilityElement = true
}
@@ -130,6 +133,18 @@ final class DronePreparationPointCell: UICollectionViewCell {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 横向同组卡片采用最长名称所需的高度,名称完整换行且不压缩字号。
static func preferredHeight(names: [String], width: CGFloat) -> CGFloat {
let label = DroneDockStyle.label(size: 13, weight: .semibold)
label.numberOfLines = 0
let nameWidth = max(1, width - 72)
let nameHeight = names.map { name -> CGFloat in
label.text = name
return label.sizeThatFits(CGSize(width: nameWidth, height: .greatestFiniteMagnitude)).height
}.max() ?? 0
return max(64, ceil(nameHeight) + 6 + ceil(UIFont.systemFont(ofSize: 11).lineHeight) + 16)
}
/// 展示点位名称与次数,已拍摄的点位仍保持可选择。
func apply(point: DroneShootingPoint, selected: Bool) {
thumbnail.kf.cancelDownloadTask()
@@ -145,7 +160,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
accessibilityIdentifier = "drone.preparation.point.\(point.id)"
}
/// 展示已购点位与可用性;点位已拍次数缺失时保持未知占位。
/// 展示已购点位与可用性;无拍摄记录时显示“未拍摄”。
func apply(spot: DroneDockPurchasedSpot, selected: Bool) {
nameLabel.text = spot.name
thumbnail.kf.cancelDownloadTask()
@@ -160,7 +175,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
if spot.available != true {
countLabel.text = spot.available == false ? "拍摄点不可用" : "可用性待确认"
} else {
countLabel.text = "已拍摄 — 次"
countLabel.text = "未拍摄"
}
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.07) : .white
contentView.layer.borderColor = (selected ? DroneDockStyle.primary : DroneDockStyle.border).cgColor
@@ -331,13 +346,16 @@ final class DronePreparationHeadingView: UICollectionReusableView {
stack.axis = .horizontal
stack.alignment = .firstBaseline
stack.spacing = 12
titleLabel.numberOfLines = 0
titleLabel.accessibilityIdentifier = "drone.preparation.heading.title"
addSubview(stack)
stack.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(4)
make.trailing.equalToSuperview()
make.centerY.equalToSuperview().offset(3)
}
titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
detailLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
accessibilityTraits = .header
isAccessibilityElement = true
}
@@ -352,6 +370,16 @@ final class DronePreparationHeadingView: UICollectionReusableView {
detailLabel.isHidden = detail == nil
accessibilityLabel = [title, detail].compactMap { $0 }.joined(separator: ",")
}
/// 为长点位名称预留完整标题高度,右侧航线数量保持可见。
static func preferredHeight(title: String, detail: String, width: CGFloat) -> CGFloat {
let label = DroneDockStyle.label(size: 18, weight: .semibold)
label.numberOfLines = 0
label.text = title
let detailWidth = (detail as NSString).size(withAttributes: [.font: UIFont.systemFont(ofSize: 13)]).width
let titleWidth = max(1, width - 4 - ceil(detailWidth) - 24)
return max(64, ceil(label.sizeThatFits(CGSize(width: titleWidth, height: .greatestFiniteMagnitude)).height) + 26)
}
}
/// 无点位或无航线时保留就地提示,不增加额外的选择弹窗。