feat: 完善机巢任务实时状态、双路图传与继续查看入口
This commit is contained in:
@@ -10,13 +10,24 @@ final class DroneDockLiveViewModel {
|
||||
private(set) var response: DroneDockLiveResponse?
|
||||
/// 图传区域当前可展示状态。
|
||||
private(set) var state: DroneDockLiveState
|
||||
/// 请求期间阻止重复获取,不安排定时轮询。
|
||||
/// 请求期间阻止重复获取,缺少流参数或凭证临期时由页面安排重查。
|
||||
private(set) var isLoading = false
|
||||
/// 仅显式正式入口允许解析设备 RTC;本地模拟即使收到参数也不连接设备。
|
||||
let allowsDevicePlayback: Bool
|
||||
/// 每次进入页面或回前台仅从空闲态自动加载,状态刷新不重复启动图传。
|
||||
var loadsAutomatically: Bool { canLoad && state == .idle }
|
||||
private(set) var rtcConfiguration: DroneDockVolcLiveConfiguration?
|
||||
/// 同一会话的机巢与无人机配置,可增补或续期而不重启正在播放的一路。
|
||||
private(set) var rtcConfigurations: [DroneDockVolcLiveConfiguration] = []
|
||||
private(set) var activeRole: String?
|
||||
|
||||
/// 只在缺一路参数或凭证临期时请求 live;普通状态刷新不触发推流请求。
|
||||
var nextParameterRefreshDelay: TimeInterval? {
|
||||
guard allowsDevicePlayback, !identityInvalidated, !rtcConfigurations.isEmpty else { return nil }
|
||||
let expiryDelay = rtcConfigurations.map { $0.expiresAt.timeIntervalSince(now()) - 30 }.min() ?? 30
|
||||
let discoveryDelay = rtcConfigurations.count < 2 ? Double(min(max(response?.refreshHintMS ?? 30_000, 5_000), 60_000)) / 1000 : .infinity
|
||||
return max(5, min(expiryDelay, discoveryDelay))
|
||||
}
|
||||
private(set) var playbackSessionID: UUID?
|
||||
|
||||
private let service: (any DroneDockLiveServing)?
|
||||
@@ -73,7 +84,7 @@ final class DroneDockLiveViewModel {
|
||||
case .unavailable(let reason), .failed(let reason): return reason
|
||||
case .localPreview: return "仅播放本地样片,未连接无人机"
|
||||
case .connecting: return "正在等待视频画面"
|
||||
case .playing: return rtcConfiguration?.role == "airport" ? "机巢摄像头" : "无人机摄像头"
|
||||
case .playing: return (activeRole ?? rtcConfiguration?.role) == "airport" ? "机巢摄像头" : "无人机摄像头"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +105,7 @@ final class DroneDockLiveViewModel {
|
||||
|
||||
/// 发起一次图传请求,拒绝重复点击、迟到响应、身份不符及远程模拟视频来源。
|
||||
@MainActor
|
||||
func refresh(onRequestStarted: (@MainActor () -> Void)? = nil) async {
|
||||
func refresh(keepingPlayback: Bool = false, onRequestStarted: (@MainActor () -> Void)? = nil) async {
|
||||
guard canLoad, let service else { return }
|
||||
generation &+= 1
|
||||
let requestGeneration = generation
|
||||
@@ -113,20 +124,31 @@ final class DroneDockLiveViewModel {
|
||||
guard accepts(requestGeneration) else { return }
|
||||
guard value.orderFlightTaskID == taskID, value.task?.id == nil || value.task?.id == taskID,
|
||||
value.task?.scenicID == nil || value.task?.scenicID == context.scenicID else {
|
||||
clearPlayback()
|
||||
throw APIError.decodeFailed("图传回执与当前拍摄任务不一致")
|
||||
}
|
||||
let previousResponse = response
|
||||
let sameDevice = previousResponse?.planeID == value.planeID && previousResponse?.airportSN == value.airportSN
|
||||
if previousResponse != nil && !sameDevice { clearPlayback() }
|
||||
response = value
|
||||
if allowsDevicePlayback {
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
do {
|
||||
rtcConfiguration = try DroneDockVolcLiveConfiguration.parse(value, now: now())
|
||||
playbackSessionID = UUID()
|
||||
state = .connecting
|
||||
DroneDockDiagnostics.event("live.parameters_valid", taskID: taskID, fields: ["provider": "volc", "playback_session": playbackSessionID?.uuidString ?? ""])
|
||||
let configurations = try DroneDockVolcLiveConfiguration.parseSources(value, now: now())
|
||||
let canKeepSession = keepingPlayback && playbackSessionID != nil
|
||||
&& sameDevice
|
||||
&& rtcConfigurations.first?.appID == configurations.first?.appID
|
||||
rtcConfigurations = configurations
|
||||
rtcConfiguration = configurations.first
|
||||
if !canKeepSession {
|
||||
activeRole = nil
|
||||
playbackSessionID = UUID()
|
||||
state = .connecting
|
||||
}
|
||||
} catch {
|
||||
state = .unavailable(error.localizedDescription)
|
||||
DroneDockDiagnostics.event("live.parameters_rejected", taskID: taskID, fields: ["reason": error.localizedDescription])
|
||||
if !keepingPlayback || rtcConfigurations.isEmpty {
|
||||
clearPlayback()
|
||||
state = .unavailable(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -145,12 +167,16 @@ final class DroneDockLiveViewModel {
|
||||
}
|
||||
} catch is CancellationError {
|
||||
guard generation == requestGeneration else { return }
|
||||
state = .idle
|
||||
if rtcConfigurations.isEmpty { state = .idle }
|
||||
} catch {
|
||||
guard accepts(requestGeneration) else { return }
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
state = .failed(error.localizedDescription)
|
||||
let accessDenied: Bool
|
||||
if case APIError.serverCode(let code, _) = error { accessDenied = code == 100098 || code == 100099 }
|
||||
else { accessDenied = false }
|
||||
if !keepingPlayback || rtcConfigurations.isEmpty || accessDenied {
|
||||
clearPlayback()
|
||||
state = .failed(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,8 +187,7 @@ final class DroneDockLiveViewModel {
|
||||
generation &+= 1
|
||||
isLoading = false
|
||||
response = nil
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
clearPlayback()
|
||||
state = service == nil ? .restricted : .idle
|
||||
}
|
||||
|
||||
@@ -179,18 +204,28 @@ final class DroneDockLiveViewModel {
|
||||
DroneDockDiagnostics.event("live.playback_event", taskID: taskID,
|
||||
fields: ["playback_session": sessionID.uuidString, "result": String(describing: event)])
|
||||
switch event {
|
||||
case .firstFrame: state = .playing
|
||||
case .firstFrame:
|
||||
activeRole = rtcConfiguration?.role
|
||||
state = .playing
|
||||
case .sourceChanged(let role):
|
||||
activeRole = role
|
||||
state = role == nil ? .connecting : .playing
|
||||
case .failed(let message):
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
clearPlayback()
|
||||
state = .failed(message)
|
||||
case .expired:
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
clearPlayback()
|
||||
state = .unavailable("图传凭证即将或已经过期,请重新获取")
|
||||
}
|
||||
}
|
||||
|
||||
private func clearPlayback() {
|
||||
rtcConfiguration = nil
|
||||
rtcConfigurations = []
|
||||
activeRole = nil
|
||||
playbackSessionID = nil
|
||||
}
|
||||
|
||||
/// 只接受当前页面与当前身份下的结果,身份变化后不允许重新请求旧任务。
|
||||
@MainActor
|
||||
private func accepts(_ requestGeneration: Int) -> Bool {
|
||||
|
||||
@@ -88,6 +88,13 @@ final class DroneDockShootingTaskViewModel {
|
||||
await refreshSnapshot(allowWhileStarting: false)
|
||||
}
|
||||
|
||||
/// 操作提交前仅作废在途读取,保留快照和操作防重锁;迟到的旧读取不能覆盖操作回查。
|
||||
@MainActor
|
||||
func invalidatePendingRefresh() {
|
||||
generation &+= 1
|
||||
isLoading = false
|
||||
}
|
||||
|
||||
/// 后端建议间隔限制为 2~30 秒;缺失或无效时默认 5 秒,从上次请求结束后计时。
|
||||
var pollIntervalNanoseconds: UInt64 {
|
||||
let hint = response?.planeStatus?.pollHintMS ?? 5_000
|
||||
@@ -109,7 +116,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
let requestGeneration = generation
|
||||
let revisionAtRequest = snapshotRevision
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
// 已失败的旧快照须等有效新响应再恢复操作,避免每次重查先短暂放开。
|
||||
defer {
|
||||
if generation == requestGeneration {
|
||||
isLoading = false
|
||||
@@ -137,7 +144,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
}
|
||||
// 迟到 HTTP 失败不能覆盖请求期间已收到的有效实时状态。
|
||||
guard snapshotRevision == revisionAtRequest else { return }
|
||||
errorMessage = error is CancellationError ? nil : error.localizedDescription
|
||||
if !(error is CancellationError) { errorMessage = error.localizedDescription }
|
||||
DroneDockDiagnostics.event("shooting.refresh_failed", taskID: taskID, fields: [
|
||||
"retained_snapshot": response != nil, "error": DroneDockDiagnostics.errorFields(error)
|
||||
])
|
||||
@@ -167,7 +174,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
"state_version": value.stateVersion as Any? ?? NSNull(),
|
||||
"plane_id": value.currentPlane?.id as Any? ?? NSNull()
|
||||
])
|
||||
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
|
||||
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .postShootUploading, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
|
||||
awaitingResummonSnapshot = false
|
||||
}
|
||||
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
|
||||
@@ -218,7 +225,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;Debug 真实页面保持禁用。
|
||||
var canStartShooting: Bool {
|
||||
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
|
||||
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& !hasSubmittedStart && !startOutcomeUnknown
|
||||
&& !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot && pendingAcceptedCommands.isEmpty
|
||||
&& resolvedDisplayPhase().0 == .ready
|
||||
@@ -238,6 +245,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
return
|
||||
}
|
||||
guard !Task.isCancelled else { return }
|
||||
invalidatePendingRefresh()
|
||||
let planeID = response?.currentPlane?.id
|
||||
startGeneration &+= 1
|
||||
let requestGeneration = startGeneration
|
||||
@@ -308,7 +316,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
/// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。
|
||||
func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool {
|
||||
commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated
|
||||
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot
|
||||
&& !pendingAcceptedCommands.contains(command)
|
||||
&& (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID)
|
||||
@@ -328,6 +336,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
return
|
||||
}
|
||||
guard !Task.isCancelled else { return }
|
||||
invalidatePendingRefresh()
|
||||
commandGeneration &+= 1
|
||||
let requestGeneration = commandGeneration
|
||||
isSendingCommand = true
|
||||
@@ -387,7 +396,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
/// 此门禁用于客户端模拟交互,不代表后端已提供真实重试许可。
|
||||
var canResummon: Bool {
|
||||
resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated
|
||||
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown
|
||||
&& !hasSubmittedResummon && pendingAcceptedCommands.isEmpty
|
||||
&& resolvedDisplayPhase().0 == .failed
|
||||
@@ -407,6 +416,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
return
|
||||
}
|
||||
guard !Task.isCancelled else { return }
|
||||
invalidatePendingRefresh()
|
||||
resummonGeneration &+= 1
|
||||
let requestGeneration = resummonGeneration
|
||||
isResummoning = true
|
||||
@@ -493,6 +503,9 @@ final class DroneDockShootingTaskViewModel {
|
||||
if isLoading { return "正在获取任务状态" }
|
||||
}
|
||||
if resolvedDisplayPhase().0 == .failed { return "任务执行失败" }
|
||||
if resolvedDisplayPhase().0 == .postShootUploading {
|
||||
return usable(response?.ui?.title) ?? "拍摄完毕上传中"
|
||||
}
|
||||
return usable(response?.ui?.title) ?? usable(response?.task?.statusLabel)
|
||||
?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认"
|
||||
}
|
||||
@@ -512,6 +525,9 @@ final class DroneDockShootingTaskViewModel {
|
||||
if let startErrorMessage { return startErrorMessage }
|
||||
if hasSubmittedStart { return "开始拍摄请求已受理,请刷新确认任务状态" }
|
||||
}
|
||||
if resolvedDisplayPhase().0 == .postShootUploading {
|
||||
return usable(response?.ui?.message) ?? "录制已结束,素材正在处理,请稍候。"
|
||||
}
|
||||
return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—"
|
||||
}
|
||||
|
||||
@@ -564,7 +580,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
}
|
||||
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
|
||||
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
|
||||
isActionEnabled: enabled && readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
|
||||
isActionEnabled: enabled && readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
|
||||
actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil)
|
||||
}
|
||||
|
||||
@@ -678,6 +694,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
let known: [String: DroneDockTaskDisplayPhase] = [
|
||||
"going_to_spot": .navigating, "failed_restartable": .failed, "waiting_summon": .blocked,
|
||||
"navigating": .navigating, "arrived_pending_start": .ready, "shooting": .shooting,
|
||||
"post_shoot_uploading": .postShootUploading,
|
||||
"paused": .paused, "returning": .returning, "completed": .completed, "failed": .failed, "blocked": .blocked
|
||||
]
|
||||
let rawPhase = usable(response.ui?.phase)
|
||||
@@ -686,7 +703,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
if phase == .failed { return (.failed, false) }
|
||||
if statuses.contains(30) {
|
||||
if phase == .returning { return (.returning, false) }
|
||||
if let phase, [.navigating, .ready, .shooting, .paused].contains(phase) { return (.unknown, true) }
|
||||
if let phase, [.navigating, .ready, .shooting, .postShootUploading, .paused].contains(phase) { return (.unknown, true) }
|
||||
return (.completed, false)
|
||||
}
|
||||
if phase == .completed {
|
||||
@@ -722,6 +739,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
case .navigating: return "无人机正在前往拍摄点"
|
||||
case .ready: return "无人机已到达"
|
||||
case .shooting: return "正在拍摄"
|
||||
case .postShootUploading: return "拍摄完毕上传中"
|
||||
case .paused: return "拍摄已暂停"
|
||||
case .returning: return "无人机正在返航"
|
||||
case .failed: return "任务执行失败"
|
||||
|
||||
Reference in New Issue
Block a user