feat: 完善机巢任务安全控制与状态诊断
同步新版飞控与 WebSocket 回执合同,完善独立指令等待、暂停继续和返航状态;增加真机诊断并优化倒计时与素材库展示。
This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user