feat: 完善机巢任务实时状态、双路图传与继续查看入口
This commit is contained in:
@@ -213,7 +213,11 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable {
|
||||
let materialStatus: Int?
|
||||
/// 已有成片的有效任务数。
|
||||
let filmCount: Int?
|
||||
/// 后端是否允许新增待飞任务。
|
||||
/// orders 选定的执行中订单飞行任务 ID;详情和旧摘要未提供时为空。
|
||||
let activeTaskID: Int?
|
||||
/// orders 返回的执行中状态,当前合同有任务时为 20,不作为任务页阶段。
|
||||
let activeTaskStatus: Int?
|
||||
/// 后端是否允许新增待飞任务;有执行中任务时优先查看该任务。
|
||||
let canCreateTask: Bool?
|
||||
/// 后端是否允许上传成片。
|
||||
let canUploadFilm: Bool?
|
||||
@@ -230,6 +234,7 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable {
|
||||
case touristPhoneMask = "user_phone", packageName = "project_name"
|
||||
case shotTotal = "shoot_count", shotUsed = "shot_count", shotRemain = "remaining_count"
|
||||
case shootStatus = "shoot_status", orderStatus = "order_status", materialStatus = "material_status"
|
||||
case activeTaskID = "active_task_id", activeTaskStatus = "active_task_status"
|
||||
case filmCount = "film_count", canCreateTask = "can_create_task", canUploadFilm = "can_upload_film"
|
||||
case canConfirm = "can_confirm", confirmStatus = "confirm_status", confirmedAt = "confirmed_at"
|
||||
}
|
||||
@@ -263,6 +268,11 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable {
|
||||
shootStatus = try container.decodeIfPresent(String.self, forKey: .shootStatus)
|
||||
orderStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .orderStatus)?.value
|
||||
materialStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .materialStatus)?.value
|
||||
activeTaskID = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .activeTaskID)?.value
|
||||
activeTaskStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .activeTaskStatus)?.value
|
||||
if let activeTaskID, activeTaskID <= 0 {
|
||||
throw DecodingError.dataCorruptedError(forKey: .activeTaskID, in: container, debugDescription: "进行中任务 ID 必须为正整数")
|
||||
}
|
||||
canCreateTask = try container.decodeIfPresent(Bool.self, forKey: .canCreateTask)
|
||||
canUploadFilm = try container.decodeIfPresent(Bool.self, forKey: .canUploadFilm)
|
||||
canConfirm = try container.decodeIfPresent(Bool.self, forKey: .canConfirm)
|
||||
@@ -312,8 +322,9 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable {
|
||||
/// 邀请游客确认须拍满套餐次数,且后端明确允许发起确认。
|
||||
var canInviteVisitorConfirmation: Bool { hasCompletedShootingQuota && canConfirm == true }
|
||||
|
||||
/// 依据后端权限提供入口标识;邀请确认额外要求成功拍满套餐次数。
|
||||
/// 后端选定的执行中任务优先于新增拍摄;无任务时沿用交付和次数规则。
|
||||
var primaryAction: String? {
|
||||
if activeTaskID != nil { return "view_task" }
|
||||
if canCreateTask == true { return "start_shoot" }
|
||||
if canInviteVisitorConfirmation { return "confirm_delivery" }
|
||||
if canUploadFilm == true { return "view_materials" }
|
||||
@@ -323,6 +334,7 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable {
|
||||
/// 与后端权限对应的按钮文案。
|
||||
var actionTitle: String? {
|
||||
switch primaryAction {
|
||||
case "view_task": return "继续查看任务"
|
||||
case "start_shoot": return "开始拍摄"
|
||||
case "confirm_delivery": return "邀请确认"
|
||||
case "view_materials": return "查看素材"
|
||||
|
||||
@@ -21,6 +21,33 @@ struct DroneDockVolcLiveConfiguration: Equatable, Sendable, CustomDebugStringCon
|
||||
guard let stream = response.play, stream.available == true else {
|
||||
throw DroneDockLiveConnectionError("图传尚未提供可用的视频流")
|
||||
}
|
||||
return try parse(stream, response: response, now: now)
|
||||
}
|
||||
|
||||
/// 解析两路参数,机巢排在首位;一路缺失或参数无效不影响另一路播放。
|
||||
static func parseSources(_ response: DroneDockLiveResponse, now: Date) throws -> [Self] {
|
||||
guard response.playable == true else { return [try parse(response, now: now)] }
|
||||
var values: [Self] = []
|
||||
var lastError: Error?
|
||||
for role in ["airport", "drone"] {
|
||||
let explicit = role == "airport" ? response.airportStream : response.droneStream
|
||||
let stream = explicit?.available != nil ? explicit : (response.play?.role == role ? response.play : nil)
|
||||
guard let stream, stream.available == true else { continue }
|
||||
do {
|
||||
guard stream.role == role else { throw DroneDockLiveConnectionError("图传来源与设备角色不一致") }
|
||||
values.append(try parse(stream, response: response, now: now))
|
||||
} catch { lastError = error }
|
||||
}
|
||||
guard !values.isEmpty else { throw lastError ?? DroneDockLiveConnectionError("图传尚未提供可用的视频流") }
|
||||
if values.count == 2 {
|
||||
guard values[0].appID == values[1].appID, values[0].roomID != values[1].roomID else {
|
||||
throw DroneDockLiveConnectionError("机巢与无人机图传需使用同一应用下的不同房间,请联系后台确认")
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
private static func parse(_ stream: DroneDockLiveStream, response: DroneDockLiveResponse, now: Date) throws -> Self {
|
||||
guard stream.urlType == "volc" else {
|
||||
throw DroneDockLiveConnectionError("暂不支持当前图传类型,请联系后台确认使用火山图传")
|
||||
}
|
||||
@@ -79,6 +106,25 @@ struct DroneDockLiveConnectionError: Error, LocalizedError, Equatable, Sendable
|
||||
/// 播放器明确回调;只有首帧到达才算已显示真实画面。
|
||||
enum DroneDockLivePlaybackEvent: Equatable, Sendable {
|
||||
case firstFrame
|
||||
/// 实际有画面的来源切换;nil 表示两路当前均无视频,继续等待推流。
|
||||
case sourceChanged(String?)
|
||||
case failed(String)
|
||||
case expired
|
||||
}
|
||||
|
||||
/// 双路选流只使用视频就绪/中断事件;HTTP 的 available 不代表首帧已经到达。
|
||||
struct DroneDockLiveSourceSelection {
|
||||
private(set) var readyRoles: Set<String> = []
|
||||
/// 无人机有视频时优先;无人机停流立即退回仍有画面的机巢。
|
||||
var selectedRole: String? {
|
||||
if readyRoles.contains("drone") { return "drone" }
|
||||
if readyRoles.contains("airport") { return "airport" }
|
||||
return nil
|
||||
}
|
||||
|
||||
/// 重复回调幂等,未知来源不会参与展示。
|
||||
mutating func setReady(_ ready: Bool, role: String) {
|
||||
guard ["airport", "drone"].contains(role) else { return }
|
||||
if ready { readyRoles.insert(role) } else { readyRoles.remove(role) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,11 @@ struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
|
||||
let playable: Bool?
|
||||
let unavailableMessage: String?
|
||||
let play: DroneDockLiveStream?
|
||||
/// 两路独立接收参数;是否真正有画面由 RTC 视频事件判断。
|
||||
let airportStream: DroneDockLiveStream?
|
||||
let droneStream: DroneDockLiveStream?
|
||||
/// 后端建议的缺流重查间隔,缺失时按 30 秒处理。
|
||||
let refreshHintMS: Int?
|
||||
/// 随接口返回的展示读数,不触发额外实时采集。
|
||||
let metrics: [DroneDockHomeMetric]
|
||||
/// 脱敏回执,不包含 RTC 连接串或 Token。
|
||||
@@ -24,6 +29,7 @@ struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
|
||||
/// live 文档中的已知字段映射。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case orderFlightTaskID = "order_flight_task_id", airport, drone, task
|
||||
case protocolInfo = "protocol"
|
||||
case airportSN = "airport_sn", metrics
|
||||
case planeID = "plane_id", playable, play, unavailableMessage = "unavailable_message"
|
||||
}
|
||||
@@ -40,6 +46,13 @@ struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
|
||||
playable = try container.decodeIfPresent(Bool.self, forKey: .playable)
|
||||
unavailableMessage = try container.decodeIfPresent(String.self, forKey: .unavailableMessage)
|
||||
play = try container.decodeIfPresent(DroneDockLiveStream.self, forKey: .play)
|
||||
airportStream = try? container.decodeIfPresent(DroneDockLiveStream.self, forKey: .airport)
|
||||
droneStream = try? container.decodeIfPresent(DroneDockLiveStream.self, forKey: .drone)
|
||||
let protocolInfo = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .protocolInfo)
|
||||
if case .object(let fields) = protocolInfo, case .number(let milliseconds) = fields["refresh_hint_ms"],
|
||||
milliseconds.isFinite, milliseconds > 0, milliseconds < 3_600_000 {
|
||||
refreshHintMS = NSDecimalNumber(decimal: milliseconds).intValue
|
||||
} else { refreshHintMS = nil }
|
||||
metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? []
|
||||
let raw = try DroneDockHomeJSONValue(from: decoder)
|
||||
let encoder = JSONEncoder()
|
||||
|
||||
@@ -7,22 +7,23 @@ enum DroneDockSnapshotAcceptance {
|
||||
|
||||
/// 先解析业务码再解析 data,兼容订阅失败时 data=[]。
|
||||
enum DroneDockShootingSocketMessage {
|
||||
case opened
|
||||
case subscribed(taskID: Int, hasSnapshot: Bool)
|
||||
case snapshot(DroneDockShootingResponse)
|
||||
case rejected(code: Int, message: String)
|
||||
case unrelated
|
||||
|
||||
/// WebSocket 成功码为 0,不使用 HTTP 的 100000 Envelope。
|
||||
/// 按新版协议解析 100000 成功包,欢迎帧仅用于触发 310,不代表订阅成功。
|
||||
static func decode(_ data: Data) throws -> Self {
|
||||
// 服务端建连先发 Opened。它不代表 310 订阅成功,也不能取消订阅超时或 HTTP 兜底。
|
||||
if String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) == "Opened" {
|
||||
return .unrelated
|
||||
return .opened
|
||||
}
|
||||
let json = try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed)
|
||||
if json as? String == "Opened" { return .unrelated }
|
||||
if json as? String == "Opened" { return .opened }
|
||||
guard let root = json as? [String: Any],
|
||||
let code = root["code"] as? Int else { throw APIError.invalidResponse }
|
||||
if code != 0 {
|
||||
if code != 100000 {
|
||||
return .rejected(code: code, message: root["msg"] as? String ?? "任务订阅失败")
|
||||
}
|
||||
guard let body = root["data"] as? [String: Any] else { throw APIError.invalidResponse }
|
||||
|
||||
@@ -10,6 +10,8 @@ enum DroneDockTaskDisplayPhase: String, Equatable, Sendable {
|
||||
case ready
|
||||
/// 服务端明确正在拍摄。
|
||||
case shooting
|
||||
/// 录制已结束,素材仍在下载、上传或渲染,尚未就绪。
|
||||
case postShootUploading
|
||||
/// 服务端明确已暂停。
|
||||
case paused
|
||||
/// 服务端明确正在返航。
|
||||
|
||||
@@ -31,6 +31,7 @@ final class DroneDockShootingRealtimeSession {
|
||||
private var active = false
|
||||
private var generation = 0
|
||||
private var retryAttempt = 0
|
||||
private var subscriptionSent = false
|
||||
private var subscribed = false
|
||||
private var lastSnapshotAt: TimeInterval?
|
||||
private var latestSnapshot: DroneDockShootingResponse?
|
||||
@@ -101,11 +102,6 @@ final class DroneDockShootingRealtimeSession {
|
||||
}
|
||||
let transport = self.makeTransport()
|
||||
self.transport = transport
|
||||
let request = DroneDockShootingSocketMessage.subscribe(taskID: self.taskID, token: ticket.socketToken)
|
||||
self.log("request.started", fields: ["body": DroneDockDiagnostics.payload(Data(request.utf8))])
|
||||
try await transport.send(request)
|
||||
guard self.accepts(current) else { return }
|
||||
self.startHeartbeat(generation: current, transport: transport)
|
||||
// 不让无限 receive 循环强持有协调器或页面。
|
||||
self.connectionTask = Task { @MainActor [weak self] in
|
||||
do {
|
||||
@@ -113,7 +109,8 @@ final class DroneDockShootingRealtimeSession {
|
||||
let data = try await transport.receive()
|
||||
guard let self, self.accepts(current) else { return }
|
||||
self.log("response.received", fields: ["body": DroneDockDiagnostics.payload(data)])
|
||||
try self.handle(DroneDockShootingSocketMessage.decode(data))
|
||||
try await self.handle(DroneDockShootingSocketMessage.decode(data),
|
||||
generation: current, transport: transport, token: ticket.socketToken)
|
||||
}
|
||||
} catch {
|
||||
guard let self, self.accepts(current) else { return }
|
||||
@@ -128,9 +125,21 @@ final class DroneDockShootingRealtimeSession {
|
||||
}
|
||||
}
|
||||
|
||||
private func handle(_ message: DroneDockShootingSocketMessage) throws {
|
||||
private func handle(_ message: DroneDockShootingSocketMessage, generation current: Int,
|
||||
transport: any DroneDockShootingSocketTransport, token: String) async throws {
|
||||
switch message {
|
||||
case .opened:
|
||||
// 必须先等应用层 Opened,再发文本帧;重复欢迎消息不能重复订阅或延长首包期限。
|
||||
guard !subscriptionSent else { return }
|
||||
let request = DroneDockShootingSocketMessage.subscribe(taskID: taskID, token: token)
|
||||
try await transport.send(request)
|
||||
guard accepts(current) else { return }
|
||||
subscriptionSent = true
|
||||
// 记录实际完成本地发送的 310;服务端是否接受仍以 ack 和完整快照为准。
|
||||
log("request.started", fields: ["body": DroneDockDiagnostics.payload(Data(request.utf8))])
|
||||
startHeartbeat(generation: current, transport: transport)
|
||||
case .subscribed(let id, let hasSnapshot):
|
||||
guard subscriptionSent else { throw APIError.decodeFailed("订阅回执先于 310 发送") }
|
||||
guard id == taskID else { throw APIError.decodeFailed("订阅回执任务不一致") }
|
||||
subscribed = true
|
||||
if !hasSnapshot { update(.fallback("任务缓存尚未就绪,正在通过接口更新")) }
|
||||
@@ -229,11 +238,13 @@ final class DroneDockShootingRealtimeSession {
|
||||
deadlineTask?.cancel(); deadlineTask = nil
|
||||
heartbeatTask?.cancel(); heartbeatTask = nil
|
||||
pongDeadlineTask?.cancel(); pongDeadlineTask = nil
|
||||
if unsubscribe, transport != nil {
|
||||
let unsubscribeTaskID = unsubscribe && subscriptionSent ? taskID : nil
|
||||
if unsubscribeTaskID != nil, transport != nil {
|
||||
log("request.started", fields: ["body": DroneDockDiagnostics.payload(Data(DroneDockShootingSocketMessage.unsubscribe(taskID: taskID).utf8))])
|
||||
}
|
||||
transport?.close(unsubscribing: unsubscribe ? taskID : nil)
|
||||
transport?.close(unsubscribing: unsubscribeTaskID)
|
||||
transport = nil
|
||||
subscriptionSent = false
|
||||
subscribed = false
|
||||
latestSnapshot = nil
|
||||
lastSnapshotAt = nil
|
||||
|
||||
@@ -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