feat: 接入拍摄任务实时订阅并完善日志与封面

This commit is contained in:
2026-11-03 09:06:38 +08:00
parent 687088326c
commit 980d16da9b
27 changed files with 1790 additions and 64 deletions
@@ -0,0 +1,33 @@
import Foundation
/// 拍摄任务订阅票据,与 App 登录 token 分开管理。
struct DroneDockSocketTicket: Decodable, Sendable {
/// 仅在 310 业务订阅中传递,不放入 WebSocket 握手 Header。
let socketToken: String
/// 后端票据有效期;每次重新连接均重新取票,不复用过期票据。
let expireSeconds: Int?
private enum CodingKeys: String, CodingKey {
case socketToken = "socket_token", expireSeconds = "expire_seconds"
}
}
/// 隔离票据获取,模拟测试无需登录或连接真实服务器。
protocol DroneDockSocketTicketServing: Sendable {
/// 使用当前 App 登录身份获取只读订阅票据。
@MainActor func socketTicket() async throws -> DroneDockSocketTicket
}
/// 复用公共 socket-token 接口的鉴权及请求日志。
@MainActor
final class DroneDockSocketTokenAPI: DroneDockSocketTicketServing {
private let client: APIClient
/// 注入与 shooting 相同环境的客户端。
init(client: APIClient) { self.client = client }
/// 不调用任何创建、飞控或图传接口。
func socketTicket() async throws -> DroneDockSocketTicket {
try await client.send(APIRequest(method: .get, path: "/api/app/socket-token"))
}
}
@@ -38,6 +38,24 @@ struct DroneDockPurchasedSpot: Decodable, Equatable, Sendable {
/// 购买范围内的航线,按服务端顺序展示。
let airLines: [DroneDockPurchasedAirLine]
/// 卡片优先使用点位封面,缺失或无效时取本点位已购航线的第一张有效样片封面。
var displayCoverURL: URL? {
if let url = Self.imageURL(coverURL) { return url }
for route in airLines {
for sample in route.samples {
if let url = Self.imageURL(sample.coverURL) { return url }
}
}
return nil
}
private static func imageURL(_ value: String?) -> URL? {
guard let text = DroneDockHomeMetric.usableText(value), let url = URL(string: text),
let scheme = url.scheme?.lowercased(), ["https", "http"].contains(scheme),
let host = url.host, !host.isEmpty else { return nil }
return url
}
/// 张工购买点位字段,不接收 workbench 的 name 作为替代。
private enum CodingKeys: String, CodingKey {
case id = "scenic_spot_id", name = "scenic_spot_name", available
@@ -2,6 +2,20 @@ import Foundation
/// 朱工 shooting 的只读快照;完整 data 用于展示,不表示已召唤或已开始拍摄。
struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
/// HTTP/推送共用的顶层任务身份。
let orderFlightTaskID: Int?
/// 同一执行批次下递增的完整快照版本。
let stateVersion: Int64?
/// 当前航线执行批次,先比较批次再比较版本,防止重召唤后的旧数据回退。
let executionBatch: Int64?
/// 第一版只接收 full 完整推送。
let snapshotKind: String?
/// 后端状态写入时间,不能作为设备读数采集时间。
let stateUpdatedAt: String?
/// 设备读数采集时间,用于显示来源和核对缓存。
let metricsUpdatedAt: String?
/// 设备缓存过期时保留数值,但标为非实时读数。
let metricsStale: Bool?
/// 后端若明确提供订单号则保留,不由请求上下文伪造响应身份。
let orderNumber: String?
/// 实测返回的订单飞行任务身份;存在时必须与请求上下文核对。
@@ -31,6 +45,9 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
/// 只映射已知展示字段,不假设响应中的任务 ID 位置。
private enum CodingKeys: String, CodingKey {
case orderFlightTaskID = "order_flight_task_id", stateVersion = "state_version"
case executionBatch = "execution_batch", snapshotKind = "snapshot_kind"
case stateUpdatedAt = "state_updated_at", metricsUpdatedAt = "metrics_updated_at", metricsStale = "metrics_stale"
case orderNumber = "order_number", orderFlightTask = "order_flight_task", task
case scenic, scenicSpot = "scenic_spot", airLine = "air_line"
case header, currentPlane = "current_plane", executeGate = "execute_gate", ui
@@ -40,6 +57,13 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
/// 可选字段缺失或为 null 时保持未知;不把缺失执行门禁推断为允许。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
orderFlightTaskID = try container.decodeIfPresent(Int.self, forKey: .orderFlightTaskID)
stateVersion = try container.decodeIfPresent(Int64.self, forKey: .stateVersion)
executionBatch = try container.decodeIfPresent(Int64.self, forKey: .executionBatch)
snapshotKind = try container.decodeIfPresent(String.self, forKey: .snapshotKind)
stateUpdatedAt = try container.decodeIfPresent(String.self, forKey: .stateUpdatedAt)
metricsUpdatedAt = try container.decodeIfPresent(String.self, forKey: .metricsUpdatedAt)
metricsStale = try container.decodeIfPresent(Bool.self, forKey: .metricsStale)
orderNumber = try container.decodeIfPresent(String.self, forKey: .orderNumber)
orderFlightTask = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .orderFlightTask)
task = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .task)
@@ -0,0 +1,49 @@
import Foundation
/// HTTP 和 WebSocket 共用的快照接收结果;重复包可证明订阅有效,但旧包不能恢复实时状态。
enum DroneDockSnapshotAcceptance {
case applied, duplicate, outdated, invalid
}
/// 先解析业务码再解析 data,兼容订阅失败时 data=[]。
enum DroneDockShootingSocketMessage {
case subscribed(taskID: Int, hasSnapshot: Bool)
case snapshot(DroneDockShootingResponse)
case rejected(code: Int, message: String)
case unrelated
/// WebSocket 成功码为 0,不使用 HTTP 的 100000 Envelope。
static func decode(_ data: Data) throws -> Self {
guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let code = root["code"] as? Int else { throw APIError.invalidResponse }
if code != 0 {
return .rejected(code: code, message: root["msg"] as? String ?? "任务订阅失败")
}
guard let body = root["data"] as? [String: Any] else { throw APIError.invalidResponse }
if let subscribed = body["subscribed"] as? Bool, subscribed {
guard let id = body["order_flight_task_id"] as? Int,
let hasSnapshot = body["has_snapshot"] as? Bool else { throw APIError.invalidResponse }
return .subscribed(taskID: id, hasSnapshot: hasSnapshot)
}
guard body["action"] as? String == "app_airport_shooting_updated" else { return .unrelated }
guard let params = body["params"] as? [String: Any] else { throw APIError.invalidResponse }
let value = try JSONDecoder().decode(DroneDockShootingResponse.self,
from: JSONSerialization.data(withJSONObject: params))
guard value.orderFlightTaskID != nil, value.snapshotKind == "full",
let version = value.stateVersion, version > 0,
let batch = value.executionBatch, batch >= 0, value.ui?.phase != nil else {
throw APIError.decodeFailed("任务推送缺少完整快照或版本信息")
}
return .snapshot(value)
}
/// 构造已确认的只读订阅协议,不暴露任意 type 的发送入口。
static func subscribe(taskID: Int, token: String) -> String {
DroneDockDiagnostics.json(["type": 310, "params": ["id": taskID, "socket_token": token]])
}
/// 离页尽力取消订阅;断开连接也会清除服务端 fd 订阅。
static func unsubscribe(taskID: Int) -> String {
DroneDockDiagnostics.json(["type": 311, "params": ["id": taskID]])
}
}
@@ -0,0 +1,272 @@
import Foundation
/// 前台任务订阅协调器:完整推送正常时停 HTTP,连接异常时通知页面恢复串行兜底读取。
@MainActor
final class DroneDockShootingRealtimeSession {
/// 明确区分订阅中、有效实时快照、兜底和永久权限失败。
enum State: Equatable {
case stopped, connecting, live, fallback(String), denied(String)
}
/// 接收完整快照,由业务 ViewModel 统一核对身份和 HTTP/推送版本。
var onSnapshot: ((DroneDockShootingResponse) -> DroneDockSnapshotAcceptance)?
/// 通知页面调整读取策略和提示,不直接持有 UIKit。
var onConnectionState: ((State) -> Void)?
/// 当前链路状态;仅 live 表示订阅和完整快照都已确认。
private(set) var state: State = .stopped
private let taskID: Int
private let ticketService: any DroneDockSocketTicketServing
private let makeTransport: () -> any DroneDockShootingSocketTransport
private let identityIsCurrent: () -> Bool
private let delay: @Sendable (UInt64) async throws -> Void
private let now: () -> TimeInterval
private let source: String
private var transport: (any DroneDockShootingSocketTransport)?
private var connectionTask: Task<Void, Never>?
private var deadlineTask: Task<Void, Never>?
private var heartbeatTask: Task<Void, Never>?
private var pongDeadlineTask: Task<Void, Never>?
private var retryTask: Task<Void, Never>?
private var active = false
private var generation = 0
private var retryAttempt = 0
private var subscribed = false
private var lastSnapshotAt: TimeInterval?
private var latestSnapshot: DroneDockShootingResponse?
/// 全部外部依赖可替换,延时按纳秒注入以确定性验证断线、超时与重连。
init(taskID: Int, ticketService: any DroneDockSocketTicketServing,
makeTransport: @escaping () -> any DroneDockShootingSocketTransport,
identityIsCurrent: @escaping () -> Bool,
source: String = "network",
now: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime },
delay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
self.taskID = taskID
self.ticketService = ticketService
self.makeTransport = makeTransport
self.identityIsCurrent = identityIsCurrent
self.delay = delay
self.now = now
self.source = source
}
deinit {
connectionTask?.cancel()
deadlineTask?.cancel()
heartbeatTask?.cancel()
pongDeadlineTask?.cancel()
retryTask?.cancel()
}
/// 初始 HTTP 完成后启动;重复出现事件不会重复订阅。
func start() {
guard !active, taskID > 0 else { return }
if case .denied = state { return }
active = true
retryAttempt = 0
connect()
}
/// 离页/后台取消计时和接收,所有迟到消息由 generation 丢弃。
func stop() {
active = false
retryTask?.cancel()
retryTask = nil
clearConnection(unsubscribe: true)
if case .denied = state { return }
update(.stopped)
}
private func connect() {
guard active else { return }
guard identityIsCurrent() else { deny("账号或景区已变化,请返回工作台重新进入"); return }
clearConnection(unsubscribe: false)
update(.connecting)
let current = generation
let ticketService = ticketService
let delay = delay
// 票据、握手、ack 或首包卡住时,HTTP 仍可兜底,随后重连。
deadlineTask = Task { @MainActor [weak self] in
do { try await delay(12_000_000_000) } catch { return }
guard let self, self.accepts(current) else { return }
self.fail("任务订阅超时,正在通过接口更新")
}
connectionTask = Task { @MainActor [weak self] in
do {
let ticket = try await ticketService.socketTicket()
guard let self, self.accepts(current) else { return }
guard !ticket.socketToken.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw APIError.decodeFailed("订阅票据为空")
}
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 {
while !Task.isCancelled {
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))
}
} catch {
guard let self, self.accepts(current) else { return }
self.fail(error.localizedDescription)
}
}
} catch {
guard let self, self.accepts(current) else { return }
if Self.isAccessFailure(error) { self.deny(error.localizedDescription) }
else { self.fail(error.localizedDescription) }
}
}
}
private func handle(_ message: DroneDockShootingSocketMessage) throws {
switch message {
case .subscribed(let id, let hasSnapshot):
guard id == taskID else { throw APIError.decodeFailed("订阅回执任务不一致") }
subscribed = true
if !hasSnapshot { update(.fallback("任务缓存尚未就绪,正在通过接口更新")) }
case .snapshot(let snapshot):
guard snapshot.orderFlightTaskID == taskID else {
log("websocket.snapshot_ignored", fields: ["reason": "different_task"])
return
}
guard subscribed else { throw APIError.decodeFailed("任务快照先于订阅回执") }
switch onSnapshot?(snapshot) ?? .invalid {
case .applied, .duplicate:
deadlineTask?.cancel()
deadlineTask = nil
retryAttempt = 0
latestSnapshot = snapshot
lastSnapshotAt = now()
checkDataHealth()
case .outdated:
log("websocket.snapshot_ignored", fields: ["reason": "old_version"])
case .invalid: throw APIError.decodeFailed("任务快照身份或结构不一致")
}
case .rejected(let code, let message):
if code == 100099, message.contains("无权订阅") || message.contains("飞行任务不存在") {
deny(message)
} else {
// 100098 是 socket 票据失败,重新取票;不当成 App 登录失效。
fail(message)
}
case .unrelated: break
}
}
private func startHeartbeat(generation current: Int, transport: any DroneDockShootingSocketTransport) {
let delay = delay
heartbeatTask = Task { @MainActor [weak self] in
do {
while !Task.isCancelled {
try await delay(20_000_000_000)
guard let self, self.accepts(current) else { return }
self.pongDeadlineTask = Task { @MainActor [weak self] in
do { try await delay(10_000_000_000) } catch { return }
guard let self, self.accepts(current) else { return }
self.fail("任务连接心跳超时,正在通过接口更新")
}
try await transport.ping()
guard self.accepts(current) else { return }
self.pongDeadlineTask?.cancel()
self.pongDeadlineTask = nil
self.log("websocket.pong")
self.checkDataHealth()
// 没有业务变化时允许长期静默,不能按 5 秒未推送误判断线。
}
} catch {
guard let self, self.accepts(current) else { return }
self.fail(error.localizedDescription)
}
}
}
private func fail(_ message: String) {
guard active else { return }
clearConnection(unsubscribe: false)
update(.fallback(message))
guard active else { return }
retryTask?.cancel()
let seconds = [1, 2, 4, 8, 16, 30][min(retryAttempt, 5)]
retryAttempt += 1
log("websocket.reconnect_scheduled", fields: ["delay_seconds": seconds])
let current = generation
let delay = delay
retryTask = Task { @MainActor [weak self] in
do { try await delay(UInt64(seconds) * 1_000_000_000) } catch { return }
guard let self, self.accepts(current) else { return }
self.retryTask = nil
self.connect()
}
}
private func deny(_ message: String) {
active = false
retryTask?.cancel()
retryTask = nil
clearConnection(unsubscribe: false)
update(.denied(message))
}
private func accepts(_ current: Int) -> Bool {
guard active, generation == current, !Task.isCancelled else { return false }
guard identityIsCurrent() else { deny("账号或景区已变化,请返回工作台重新进入"); return false }
return true
}
private func clearConnection(unsubscribe: Bool) {
generation &+= 1
connectionTask?.cancel(); connectionTask = nil
deadlineTask?.cancel(); deadlineTask = nil
heartbeatTask?.cancel(); heartbeatTask = nil
pongDeadlineTask?.cancel(); pongDeadlineTask = nil
if unsubscribe, transport != nil {
log("request.started", fields: ["body": DroneDockDiagnostics.payload(Data(DroneDockShootingSocketMessage.unsubscribe(taskID: taskID).utf8))])
}
transport?.close(unsubscribing: unsubscribe ? taskID : nil)
transport = nil
subscribed = false
latestSnapshot = nil
lastSnapshotAt = nil
}
private func checkDataHealth() {
guard subscribed, let snapshot = latestSnapshot, let receivedAt = lastSnapshotAt else { return }
if snapshot.metricsStale == true {
update(.fallback("设备读数缓存已过期,正在通过接口核对"))
} else if snapshot.ui?.phase == "shooting", now() - receivedAt >= 120 {
// 拍摄中后端约每 30 秒更新;连续四个周期无完整包,保持连接并用只读 HTTP 核对。
// 其它阶段只在变化时推送,不能仅因静默判定异常。
update(.fallback("拍摄状态长时间未更新,正在通过接口核对"))
} else {
update(.live)
}
}
private static func isAccessFailure(_ error: Error) -> Bool {
if APIError.isAuthenticationExpired(error) { return true }
guard case APIError.serverCode(let code, let message) = error else { return false }
return code == 100099 && (message.contains("无权") || message.contains("无权限"))
}
private func update(_ value: State) {
guard state != value else { return }
state = value
log("websocket.state", fields: ["state": String(describing: value)])
onConnectionState?(value)
}
private func log(_ event: String, fields: [String: Any] = [:]) {
DroneDockDiagnostics.event(event, taskID: taskID,
fields: fields.merging(["transport": "websocket", "path": "/api/app/airport/shooting", "source": source]) { _, new in new })
}
}
@@ -0,0 +1,59 @@
import Foundation
/// 任务 WebSocket 的隔离传输边界,测试替身不能转发到真实网络。
@MainActor
protocol DroneDockShootingSocketTransport: AnyObject {
/// 发送订阅 JSON。
func send(_ text: String) async throws
/// 等待一条完整消息。
func receive() async throws -> Data
/// 使用原生 Ping/Pong 检查链路,不发送业务或设备指令。
func ping() async throws
/// 关闭连接,离页时尽力发送 311,最多等待一秒。
func close(unsubscribing taskID: Int?)
}
/// Foundation WebSocket 实现;连接生命周期由任务页的实时协调器管理。
@MainActor
final class DroneDockURLSessionShootingSocket: DroneDockShootingSocketTransport {
private let socket: URLSessionWebSocketTask
/// 仅使用环境指定的 wss 地址,无登录 Header、无设备连接。
init(url: URL, session: URLSession = .shared) {
socket = session.webSocketTask(with: url)
socket.resume()
}
deinit { socket.cancel(with: .goingAway, reason: nil) }
func send(_ text: String) async throws { try await socket.send(.string(text)) }
func receive() async throws -> Data {
switch try await socket.receive() {
case .string(let text): return Data(text.utf8)
case .data(let data): return data
@unknown default: throw APIError.invalidResponse
}
}
func ping() async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
socket.sendPing { error in
if let error { continuation.resume(throwing: error) }
else { continuation.resume() }
}
}
}
func close(unsubscribing taskID: Int?) {
guard let taskID else { socket.cancel(with: .goingAway, reason: nil); return }
let socket = socket
socket.send(.string(DroneDockShootingSocketMessage.unsubscribe(taskID: taskID))) { _ in
socket.cancel(with: .normalClosure, reason: nil)
}
Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
socket.cancel(with: .normalClosure, reason: nil)
}
}
}
@@ -50,6 +50,9 @@ final class DroneDockShootingTaskViewModel {
private let commandService: (any DroneDockCommandSending)?
private let resummonService: (any DroneDockResummonServing)?
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
/// 无权限或登录失效后停止自动读取,旧数据仅用于展示。
private(set) var readAccessError: String?
private var snapshotRevision = 0
private var generation = 0
private var identityInvalidated = false
private var startGeneration = 0
@@ -93,17 +96,18 @@ final class DroneDockShootingTaskViewModel {
/// 身份失效或缺少任务信息时停止安排下一次读取。
var canContinuePolling: Bool {
!identityInvalidated && context.canLoad && taskID > 0
!identityInvalidated && readAccessError == nil && context.canLoad && taskID > 0
&& DroneDockHomeMetric.usableText(order.orderNumber) != nil
}
@MainActor
private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false,
allowWhileResummoning: Bool = false) async {
guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting,
guard !isLoading, !identityInvalidated, readAccessError == nil, !isStartingShooting || allowWhileStarting,
!isSendingCommand || allowWhileCommand, !isResummoning || allowWhileResummoning else { return }
generation &+= 1
let requestGeneration = generation
let revisionAtRequest = snapshotRevision
isLoading = true
errorMessage = nil
defer {
@@ -121,23 +125,18 @@ final class DroneDockShootingTaskViewModel {
do {
let value = try await service.shooting(taskID: taskID, liveBattery: false)
guard accepts(requestGeneration) else { return }
guard matchesIdentity(value) else {
if applyTaskSnapshot(value) == .invalid {
response = nil
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
}
response = value
DroneDockDiagnostics.event("shooting.snapshot_applied", taskID: taskID, fields: [
"phase": presentation.phase.rawValue,
"plane_id": value.currentPlane?.id as Any? ?? NSNull(),
"can_execute": value.executeGate?.canExecute as Any? ?? NSNull(),
"primary_action": value.executeGate?.primaryAction as Any? ?? NSNull()
])
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
awaitingResummonSnapshot = false
}
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
} catch {
guard accepts(requestGeneration) else { return }
if Self.stopsTaskReading(error) {
stopReading(message: error.localizedDescription)
return
}
// 迟到 HTTP 失败不能覆盖请求期间已收到的有效实时状态。
guard snapshotRevision == revisionAtRequest else { return }
errorMessage = error is CancellationError ? nil : error.localizedDescription
DroneDockDiagnostics.event("shooting.refresh_failed", taskID: taskID, fields: [
"retained_snapshot": response != nil, "error": DroneDockDiagnostics.errorFields(error)
@@ -145,6 +144,52 @@ final class DroneDockShootingTaskViewModel {
}
}
/// HTTP 和推送共享完整快照入口,按执行批次、版本去重,绝不按到达顺序覆盖。
@MainActor
@discardableResult
func applyTaskSnapshot(_ value: DroneDockShootingResponse) -> DroneDockSnapshotAcceptance {
guard readAccessError == nil, accepts(generation), matchesIdentity(value) else { return .invalid }
if let oldBatch = response?.executionBatch, let oldVersion = response?.stateVersion {
guard let batch = value.executionBatch, let version = value.stateVersion else { return .outdated }
if batch < oldBatch || (batch == oldBatch && version < oldVersion) { return .outdated }
if batch == oldBatch && version == oldVersion {
errorMessage = nil
snapshotRevision &+= 1
return .duplicate
}
}
response = value
errorMessage = nil
snapshotRevision &+= 1
DroneDockDiagnostics.event("shooting.snapshot_applied", taskID: taskID, fields: [
"phase": presentation.phase.rawValue,
"execution_batch": value.executionBatch as Any? ?? NSNull(),
"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) {
awaitingResummonSnapshot = false
}
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
return .applied
}
/// 订阅明确无权限或 HTTP 鉴权失效时保留快照、禁用操作并停止后续读取。
@MainActor
func stopReading(message: String) {
generation &+= 1
isLoading = false
readAccessError = message
errorMessage = message
}
/// 只把已确认的权限信息视为终止条件,不把所有 100099 业务错误一概当成无权限。
private static func stopsTaskReading(_ error: Error) -> Bool {
if APIError.isAuthenticationExpired(error) { return true }
guard case APIError.serverCode(let code, let message) = error else { return false }
return code == 100099 && (message.contains("无权") || message.contains("无权限") || message.contains("飞行任务不存在"))
}
/// 使旧请求失效;同一身份离页或进入后台可保留快照,账号变化始终清除并停止旧任务读取。
@MainActor
func invalidate(preservingSnapshot: Bool = false) {
@@ -166,14 +211,14 @@ final class DroneDockShootingTaskViewModel {
errorMessage = "账号或景区已变化,请返回工作台重新进入"
} else {
if !preservingSnapshot { response = nil }
errorMessage = nil
errorMessage = readAccessError
}
}
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;Debug 真实页面保持禁用。
var canStartShooting: Bool {
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !hasSubmittedStart && !startOutcomeUnknown
&& !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot && pendingAcceptedCommands.isEmpty
&& resolvedDisplayPhase().0 == .ready
@@ -263,7 +308,7 @@ final class DroneDockShootingTaskViewModel {
/// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。
func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool {
commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot
&& !pendingAcceptedCommands.contains(command)
&& (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID)
@@ -342,7 +387,7 @@ final class DroneDockShootingTaskViewModel {
/// 此门禁用于客户端模拟交互,不代表后端已提供真实重试许可。
var canResummon: Bool {
resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown
&& !hasSubmittedResummon && pendingAcceptedCommands.isEmpty
&& resolvedDisplayPhase().0 == .failed
@@ -478,7 +523,7 @@ final class DroneDockShootingTaskViewModel {
}
if response == nil, let errorMessage {
return DroneDockTaskPresentation(phase: .readError, title: "任务状态读取失败", message: errorMessage,
deviceStatus: deviceStatusText, action: .refresh, actionTitle: "重新读取", isActionEnabled: !identityInvalidated)
deviceStatus: deviceStatusText, action: .refresh, actionTitle: "重新读取", isActionEnabled: !identityInvalidated && readAccessError == nil)
}
let (phase, conflict) = resolvedDisplayPhase()
let message = conflict ? "任务状态信息不一致,请刷新后确认。" + (statusMessage == "—" ? "" : statusMessage) : statusMessage
@@ -519,7 +564,7 @@ final class DroneDockShootingTaskViewModel {
}
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
isActionEnabled: enabled && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
isActionEnabled: enabled && readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil)
}
@@ -530,8 +575,8 @@ final class DroneDockShootingTaskViewModel {
windText: text("wind_speed"), rainText: text("rainfall"), signalText: text("signal"), satelliteText: text("satellite"))
}
/// 仅无快照时使用未知读数;刷新期间继续展示最近一次成功快照。
var isTelemetryStale: Bool { response == nil }
/// 无快照或后端标记缓存过期时使用非实时样式;已有读数仍保留展示。
var isTelemetryStale: Bool { response == nil || response?.metricsStale == true }
/// 完整服务端 data,供页面展示和联调查看。
var dataJSON: String? { response?.dataJSON }
@@ -612,7 +657,7 @@ final class DroneDockShootingTaskViewModel {
}
private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool {
let taskIDs = [value.orderFlightTask?.id, value.task?.id].compactMap { $0 }
let taskIDs = [value.orderFlightTaskID, value.orderFlightTask?.id, value.task?.id].compactMap { $0 }
let orderNumbers = [value.orderNumber, value.orderFlightTask?.orderNumber,
value.task?.orderNumber, value.header?.orderNumber].compactMap { $0 }
let scenicIDs = [value.scenic?.id, value.orderFlightTask?.scenicID,
@@ -631,6 +676,7 @@ final class DroneDockShootingTaskViewModel {
if statuses.contains(50) { return (.blocked, false) }
if statuses.count > 1 { return (.unknown, true) }
let known: [String: DroneDockTaskDisplayPhase] = [
"going_to_spot": .navigating, "failed_restartable": .failed, "waiting_summon": .blocked,
"navigating": .navigating, "arrived_pending_start": .ready, "shooting": .shooting,
"paused": .paused, "returning": .returning, "completed": .completed, "failed": .failed, "blocked": .blocked
]