完善机巢任务实时同步并开放双构建真实操作

订阅明确无缓存时使用新发起的有效 HTTP 全量响应衔接首包,保留任务、批次和版本校验。
移除 Debug/Release 的设备指令、图传和 RTC 构建拦截,保留后端权限、身份、防重复提交及结果未知保护。
更新开发约定并补充隔离传输、飞控状态和页面回归测试。

验证:iPhone 真机 500 项相关测试通过;iOS Release 无签名编译通过。
This commit is contained in:
2026-11-05 10:59:26 +08:00
parent 477bf611e6
commit 34ee60b8b2
46 changed files with 914 additions and 461 deletions
+3 -14
View File
@@ -72,19 +72,8 @@ final class APIClient {
_ apiRequest: APIRequest<Response>,
tokenOverride: String? = nil
) async throws -> Response {
let original = try makeURLRequest(apiRequest, tokenOverride: tokenOverride)
let request = try DroneDockReadRequestPolicy.prepare(makeURLRequest(apiRequest, tokenOverride: tokenOverride))
let isSimulation = session is any LocalSimulationURLSession
let request: URLRequest
do {
request = try DeviceCommandDebugPolicy.prepare(original, isLocalSimulation: isSimulation)
} catch {
if let trace = DroneDockRequestTrace(request: original, isSimulation: isSimulation) {
var fields = DroneDockDiagnostics.errorFields(error)
fields["body"] = DroneDockDiagnostics.payload(original.httpBody)
droneDockLogSink(trace.message("request.blocked", fields: fields))
}
throw error
}
let trace = DroneDockRequestTrace(request: request, isSimulation: isSimulation)
if let trace {
droneDockLogSink(trace.message("request.started", fields: ["body": DroneDockDiagnostics.payload(request.httpBody)]))
@@ -167,7 +156,7 @@ final class APIClient {
}
request.httpBody = jsonBody.data(using: .utf8)
request = try DeviceCommandDebugPolicy.prepare(request, isLocalSimulation: session is any LocalSimulationURLSession)
request = try DroneDockReadRequestPolicy.prepare(request)
logRequest(request)
let data: Data
@@ -241,7 +230,7 @@ final class APIClient {
request.setValue(token, forHTTPHeaderField: "token")
}
request.httpBody = body
request = try DeviceCommandDebugPolicy.prepare(request, isLocalSimulation: session is any LocalSimulationURLSession)
request = try DroneDockReadRequestPolicy.prepare(request)
logRequest(request)
let responseData: Data
@@ -1,72 +0,0 @@
import Foundation
/// 调试请求边界:Debug 禁止真实设备操作,Release 按用户授权开放已对接的操作。
enum DeviceCommandDebugPolicy {
/// 2026-11-02 用户授权 Release 真机联调;Debug 仍无运行时放行开关。
static var blocksFlightRequests: Bool {
#if DEBUG
true
#else
false
#endif
}
/// 所有 Debug 构建禁止真实设备操作,没有启动参数或设置开关可临时放行。
static var blocksLiveRequests: Bool {
#if DEBUG
true
#else
false
#endif
}
/// 页面与本地拦截共用的说明,不将未发送的请求表述为服务端执行失败。
static let blockedMessage = "当前禁止真实设备指令,请使用本地模拟调试"
/// 在日志和传输之前阻断操作请求;Release 准备页可读实时电量,其余状态读取关闭实时采集。
static func prepare(_ request: URLRequest, isLocalSimulation: Bool) throws -> URLRequest {
guard !isLocalSimulation, let url = request.url else { return request }
let path = "/" + url.path.split(separator: "/").joined(separator: "/")
// Debug 创建也必须拦截,避免调试残留真实待飞任务。
if path == "/api/yf-handset-app/photog/multi-plane/tasks/create" {
guard !blocksFlightRequests, request.httpMethod == "POST" else { throw DeviceCommandDebugBlockedError() }
return request
}
guard path == "/api/app/airport" || path.hasPrefix("/api/app/airport/") else { return request }
let flightPaths: Set<String> = ["/api/app/airport/shoot", "/api/app/airport/start-shoot", "/api/app/airport/command"]
if !blocksFlightRequests, request.httpMethod == "POST", flightPaths.contains(path) { return request }
// 仅允许已确认的图传和飞控接口;未知设备操作仍阻断。
if request.httpMethod == "GET", path == "/api/app/airport/live", !blocksLiveRequests { return request }
let readablePaths: Set<String> = [
"/api/app/airport/home", "/api/app/airport/plane-status",
"/api/app/airport/shooting", "/api/app/airport/status"
]
guard request.httpMethod == "GET", readablePaths.contains(path) else {
throw DeviceCommandDebugBlockedError()
}
#if !DEBUG
// 2026-11-03 用户要求准备页获取电量;保留调用方的 live_battery,任务页仍强制读缓存。
if path == "/api/app/airport/plane-status" { return request }
#endif
let liveKey: String
switch path {
case "/api/app/airport/plane-status", "/api/app/airport/shooting": liveKey = "live_battery"
case "/api/app/airport/status": liveKey = "live_metrics"
default: return request
}
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { throw APIError.invalidURL }
var items = components.queryItems ?? []
items.removeAll { $0.name == liveKey }
items.append(URLQueryItem(name: liveKey, value: "0"))
components.queryItems = items
guard let safeURL = components.url else { throw APIError.invalidURL }
var safeRequest = request
safeRequest.url = safeURL
return safeRequest
}
}
/// 明确表示请求在本机被阻断,任何设备指令或任务创建都未发送。
struct DeviceCommandDebugBlockedError: Error, LocalizedError {
/// 提示使用本地模拟,不伪造后端错误码或成功回执。
var errorDescription: String? { DeviceCommandDebugPolicy.blockedMessage }
}
@@ -40,7 +40,6 @@ enum DroneDockDiagnostics {
/// 记录业务码、HTTP 状态及原始错误说明,便于与后端回包对应。
static func errorFields(_ error: Error) -> [String: Any] {
if error is CancellationError { return ["kind": "cancelled"] }
if error is DeviceCommandDebugBlockedError { return ["kind": "locally_blocked", "sent": false] }
if case APIError.serverCode(let code, let message) = error {
return ["kind": "business_rejected", "code": code, "message": message]
}
@@ -136,8 +135,6 @@ struct DroneDockRequestTrace {
#else
fields["build"] = "Release"
#endif
fields["flight_blocked"] = DeviceCommandDebugPolicy.blocksFlightRequests
fields["live_blocked"] = DeviceCommandDebugPolicy.blocksLiveRequests
let items = request.url.flatMap { URLComponents(url: $0, resolvingAgainstBaseURL: false)?.queryItems } ?? []
fields["query"] = items.map { [$0.name: $0.value ?? ""] }
return DroneDockDiagnostics.json(fields)
@@ -0,0 +1,25 @@
import Foundation
/// 任务与工作台状态使用缓存读数;设备操作和准备页电量保留调用方请求。
enum DroneDockReadRequestPolicy {
/// Debug 与 Release 使用相同规则,不改写创建、飞控或图传请求。
static func prepare(_ request: URLRequest) throws -> URLRequest {
guard request.httpMethod == "GET", let url = request.url else { return request }
let path = "/" + url.path.split(separator: "/").joined(separator: "/")
let liveKey: String
switch path {
case "/api/app/airport/shooting": liveKey = "live_battery"
case "/api/app/airport/status": liveKey = "live_metrics"
default: return request
}
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { throw APIError.invalidURL }
var items = components.queryItems ?? []
items.removeAll { $0.name == liveKey }
items.append(URLQueryItem(name: liveKey, value: "0"))
components.queryItems = items
guard let cachedURL = components.url else { throw APIError.invalidURL }
var cachedRequest = request
cachedRequest.url = cachedURL
return cachedRequest
}
}
@@ -1,13 +1,13 @@
import Foundation
/// 基于既有订单飞行任务发送单次安全指令;Release 注入真实页面,Debug 仅向本地模拟页面注入。
/// 基于既有订单飞行任务发送单次安全指令;测试使用独立的本地模拟服务。
protocol DroneDockCommandSending: Sendable {
/// 提交任务 ID 和白名单指令,不创建任务、不选机,也不自动重试。
@MainActor
func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse
}
/// 朱工 command 合同适配,真实传输仍受统一 Debug 禁飞策略阻断。
/// 朱工 command 合同适配,校验任务身份及幂等指令回执。
@MainActor
final class DroneDockCommandAPI: DroneDockCommandSending {
private let client: APIClient
@@ -1,6 +1,6 @@
import Foundation
/// 朱工任务图传参数服务;请求可能启动设备图传,Release 随页面自动开启,Debug 只允许隔离模拟注入。
/// 朱工任务图传参数服务;请求可能启动设备图传,由页面生命周期管理。
protocol DroneDockLiveServing: Sendable {
/// 读取同一订单飞行任务的图传回执,不创建任务或更换飞机。
@MainActor
@@ -12,7 +12,7 @@ protocol DroneDockLiveServing: Sendable {
final class DroneDockLiveAPI: DroneDockLiveServing {
private let client: APIClient
/// 注入统一客户端,保留 Debug 禁飞阻断与纯内存测试传输。
/// 注入统一客户端,测试使用纯内存传输。
init(client: APIClient) { self.client = client }
/// 只发送一次 GET,请求失败不自动重试或发出其他设备请求。
@@ -7,7 +7,7 @@ protocol DroneDockStartShooting: Sendable {
func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse
}
/// start-shoot 合同适配;Debug 真实传输由统一客户端阻断,Release 按用户授权开放。
/// start-shoot 合同适配;两种构建共用任务身份校验和单次提交规则。
@MainActor
final class DroneDockStartShootAPI: DroneDockStartShooting {
private let client: APIClient
@@ -84,7 +84,6 @@ private struct DroneDockLiveJSONSnapshot: Encodable {
/// 图传区域的明确状态;本地视频预览不代表设备连接或真实图传成功。
enum DroneDockLiveState: Equatable, Sendable {
case restricted
case idle
case loading
case unavailable(String)
@@ -38,7 +38,7 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
let metrics: [DroneDockHomeMetric]
/// 景区设备连接与轮询建议,不在客户端改选推荐飞机。
let planeStatus: DroneDockShootingPlaneStatus?
/// 执行门禁参与展示及本地模拟开拍校验,不能解除真实飞控禁令。
/// 执行门禁参与展示和开拍校验,缺失许可时不开放操作。
let executeGate: DroneDockShootingExecuteGate?
/// 重召唤许可独立于开拍门禁,缺失不视为允许。
let restartGate: DroneDockShootingRestartGate?
@@ -6,11 +6,17 @@ enum DroneDockSnapshotAcceptance {
case applied, duplicate, outdated, invalid
}
/// 本次 HTTP 实际读取且已通过业务校验的结果,不用页面保留的旧快照证明订阅首包。
struct DroneDockHTTPSnapshotResult {
let snapshot: DroneDockShootingResponse
let acceptance: DroneDockSnapshotAcceptance
}
/// 先解析业务码再解析 data,兼容订阅失败时 data=[]。
enum DroneDockShootingSocketMessage {
case opened
case subscribed(taskID: Int)
case subscriptionMetadata(taskID: Int, hasSnapshot: Bool)
case subscriptionMetadata(taskID: Int, hasSnapshot: Bool, executionBatch: Int?)
case snapshot(DroneDockShootingResponse)
case subscriptionRejected(code: Int, message: String)
case rejected(code: Int, message: String)
@@ -51,7 +57,8 @@ enum DroneDockShootingSocketMessage {
guard boolean(body["subscribed"]) == true,
let id = body["order_flight_task_id"] as? Int, id > 0,
let hasSnapshot = boolean(body["has_snapshot"]) else { return .unrelated }
return .subscriptionMetadata(taskID: id, hasSnapshot: hasSnapshot)
return .subscriptionMetadata(taskID: id, hasSnapshot: hasSnapshot,
executionBatch: (body["execution_batch"] as? Int).flatMap { $0 > 0 ? $0 : nil })
default:
return .unrelated
}
@@ -12,6 +12,10 @@ final class DroneDockShootingRealtimeSession {
var onSnapshot: ((DroneDockShootingResponse) -> DroneDockSnapshotAcceptance)?
/// 通知页面调整读取策略和提示,不直接持有 UIKit。
var onConnectionState: ((State) -> Void)?
/// 正式订阅确认无缓存后,请页面在现有串行读取通道补取一份新 HTTP 全量。
var onHTTPSeedRequired: (() -> Void)?
/// 请求开始时捕获此标识;连接、缓存提示或首包变化后,旧标识不能完成新订阅。
private(set) var pendingHTTPSeedRequest: UUID?
/// 当前链路状态;仅 live 表示订阅和完整快照都已确认。
private(set) var state: State = .stopped
@@ -35,6 +39,8 @@ final class DroneDockShootingRealtimeSession {
private var subscribed = false
private var lastSnapshotAt: TimeInterval?
private var latestSnapshot: DroneDockShootingResponse?
private var requestedHTTPSeed = false
private var httpSeedMinimumBatch: Int?
/// 全部外部依赖可替换,延时按纳秒注入以确定性验证断线、超时与重连。
init(taskID: Int, ticketService: any DroneDockSocketTicketServing,
@@ -79,6 +85,28 @@ final class DroneDockShootingRealtimeSession {
update(.stopped)
}
/// 仅接受当前无缓存订阅之后新发起、并已由业务层采纳或去重的完整 HTTP 结果。
func acceptHTTPSeed(_ result: DroneDockHTTPSnapshotResult, requestID: UUID) {
guard active, subscribed, pendingHTTPSeedRequest == requestID, accepts(generation) else { return }
switch result.acceptance {
case .applied, .duplicate: break
case .outdated, .invalid: return
}
let snapshot = result.snapshot
guard snapshot.orderFlightTaskID == taskID, snapshot.snapshotKind == "full",
let batch = snapshot.executionBatch, batch >= 0,
httpSeedMinimumBatch.map({ batch >= $0 }) ?? true,
let version = snapshot.stateVersion, version > 0, snapshot.ui?.phase != nil else { return }
pendingHTTPSeedRequest = nil
deadlineTask?.cancel()
deadlineTask = nil
retryAttempt = 0
latestSnapshot = snapshot
lastSnapshotAt = now()
log("websocket.http_seed_accepted", fields: ["execution_batch": batch, "state_version": version])
checkDataHealth()
}
private func connect() {
guard active else { return }
guard identityIsCurrent() else { deny("账号或景区已变化,请返回工作台重新进入"); return }
@@ -142,10 +170,18 @@ final class DroneDockShootingRealtimeSession {
guard subscriptionSent else { throw APIError.decodeFailed("订阅回执先于 310 发送") }
guard id == taskID else { throw APIError.decodeFailed("订阅回执任务不一致") }
subscribed = true
case .subscriptionMetadata(let id, let hasSnapshot):
case .subscriptionMetadata(let id, let hasSnapshot, let batch):
// 元数据仅描述缓存,不确认订阅、不延长首包期限,也不能降级已有有效快照。
guard subscribed, id == taskID, latestSnapshot == nil else { return }
if !hasSnapshot { update(.fallback("任务缓存尚未就绪,正在通过接口更新")) }
if hasSnapshot {
pendingHTTPSeedRequest = nil
} else if !requestedHTTPSeed {
requestedHTTPSeed = true
httpSeedMinimumBatch = batch
pendingHTTPSeedRequest = UUID()
update(.fallback("任务缓存尚未就绪,正在通过接口更新"))
onHTTPSeedRequired?()
}
case .snapshot(let snapshot):
guard snapshot.orderFlightTaskID == taskID else {
log("websocket.snapshot_ignored", fields: ["reason": "different_task"])
@@ -154,6 +190,7 @@ final class DroneDockShootingRealtimeSession {
guard subscribed else { throw APIError.decodeFailed("任务快照先于订阅回执") }
switch onSnapshot?(snapshot) ?? .invalid {
case .applied, .duplicate:
pendingHTTPSeedRequest = nil
deadlineTask?.cancel()
deadlineTask = nil
retryAttempt = 0
@@ -255,6 +292,9 @@ final class DroneDockShootingRealtimeSession {
subscribed = false
latestSnapshot = nil
lastSnapshotAt = nil
requestedHTTPSeed = false
pendingHTTPSeedRequest = nil
httpSeedMinimumBatch = nil
}
private func checkDataHealth() {
@@ -49,10 +49,10 @@ final class DroneDockLiveViewModel {
self.allowsDevicePlayback = allowsDevicePlayback
self.now = now
self.currentContext = currentContext
state = service == nil ? .restricted : .idle
state = service == nil ? .unavailable("当前页面未配置图传服务") : .idle
}
/// 仅有明确注入服务且身份有效时允许发起请求;正式禁飞入口始终为 false。
/// 有明确注入服务且身份有效时允许发起请求。
var canLoad: Bool { service != nil && !isLoading && !identityInvalidated && context.canLoad && taskID > 0 }
/// 仅返回明确注入且已经过本地文件检查的模拟视频,不使用后端未定义字段。
@@ -64,7 +64,6 @@ final class DroneDockLiveViewModel {
/// 图传区域主文案,不把接口受理视为设备连接成功。
var title: String {
switch state {
case .restricted: return "当前调试已停用实时图传"
case .idle: return "实时图传"
case .loading: return "正在获取图传信息"
case .unavailable: return "图传暂不可用"
@@ -78,7 +77,6 @@ final class DroneDockLiveViewModel {
/// 缺失协议时说明真实限制,不给示例视频贴上实时来源。
var message: String {
switch state {
case .restricted: return "禁飞调试期间不启动设备图传"
case .idle: return allowsDevicePlayback ? "正在准备连接图传" : "按当前任务获取图传信息"
case .loading: return "请稍候"
case .unavailable(let reason), .failed(let reason): return reason
@@ -93,7 +91,6 @@ final class DroneDockLiveViewModel {
guard service != nil else { return nil }
if isLoading { return allowsDevicePlayback ? nil : "正在加载…" }
switch state {
case .restricted: return nil
case .idle: return nil
case .loading: return allowsDevicePlayback ? nil : "正在加载…"
case .failed, .unavailable: return "重试"
@@ -194,7 +191,7 @@ final class DroneDockLiveViewModel {
isLoading = false
response = nil
clearPlayback()
state = service == nil ? .restricted : .idle
state = service == nil ? .unavailable("当前页面未配置图传服务") : .idle
}
/// 只接受当前播放器会话的事件;首帧之前不显示已连接,旧回调不能恢复画面。
@@ -59,7 +59,6 @@ final class DroneDockPreparationViewModel {
private let planeStatusService: any DroneDockPlaneStatusServing
private let taskCreationService: any DroneDockTaskCreating
private let shootService: any DroneDockShootServing
private let allowsTaskSubmission: Bool
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private var generation = 0
private var planeStatusGeneration = 0
@@ -80,7 +79,6 @@ final class DroneDockPreparationViewModel {
planeStatusService: any DroneDockPlaneStatusServing,
taskCreationService: any DroneDockTaskCreating,
shootService: any DroneDockShootServing,
allowsTaskSubmission: Bool = true,
diagnostics: DroneDockTaskDiagnostics = DroneDockTaskDiagnostics(),
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.diagnostics = diagnostics
@@ -90,7 +88,6 @@ final class DroneDockPreparationViewModel {
self.planeStatusService = planeStatusService
self.taskCreationService = taskCreationService
self.shootService = shootService
self.allowsTaskSubmission = allowsTaskSubmission
self.currentContext = currentContext
}
@@ -106,14 +103,14 @@ final class DroneDockPreparationViewModel {
"created_task_id": DroneDockTaskTraceFields.value(createdTask?.taskID),
"is_creating": isCreatingTask, "is_summoning": isSummoning,
"creation_outcome_unknown": taskCreationOutcomeUnknown, "summon_outcome_unknown": summonOutcomeUnknown,
"allows_task_submission": allowsTaskSubmission, "primary_action_enabled": isPrimaryActionEnabled]
"primary_action_enabled": isPrimaryActionEnabled]
diagnostics.record(event, taskID: createdTask?.taskID ?? 0,
fields: summary.merging(fields) { _, new in new })
}
/// 当前阶段只创建待飞任务,不以设备电量或位置作为创建任务条件。
var canCreateTask: Bool {
guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
guard context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
!hasCreatedTask, !taskCreationOutcomeUnknown, errorMessage == nil,
let info = projectInfo, info.order.canCreateTask == true,
let total = info.order.shotTotal, total > 0,
@@ -125,9 +122,6 @@ final class DroneDockPreparationViewModel {
return info.order.orderNumber == number && info.order.projectID == projectID
}
/// 当前入口是否被禁飞限制禁止提交,用于提供独立模拟入口而不放开真实写入。
var isTaskSubmissionBlocked: Bool { !allowsTaskSubmission }
/// 提交中和已有回执/不确定结果时冻结点位航线,避免显示与任务归属不一致。
var isTaskSelectionLocked: Bool {
isCreatingTask || isSummoning || isPerformingPrimaryAction || hasCreatedTask || taskCreationOutcomeUnknown
@@ -149,7 +143,7 @@ final class DroneDockPreparationViewModel {
/// 首次允许创建再召唤;明确业务拒绝后可对同任务重试,成功和未知结果锁定。
var isPrimaryActionEnabled: Bool {
guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
guard context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
!isSummoning, !isPerformingPrimaryAction, !taskCreationOutcomeUnknown,
!hasSubmittedSummon, !summonOutcomeUnknown, !summonRequiresTaskReview else { return false }
if let createdTask { return createdTask.taskID > 0 }
@@ -160,8 +154,7 @@ final class DroneDockPreparationViewModel {
@MainActor
func prepareAndSummon(onStateChange: @escaping @MainActor () -> Void = {}) async {
recordPreparationEvent("preparation.primary_requested")
// 禁飞调试在整条链开始前阻断,避免先残留真实待飞任务再拦截召唤。
guard allowsTaskSubmission, isPrimaryActionEnabled else { return }
guard isPrimaryActionEnabled else { return }
primaryActionGeneration &+= 1
let actionGeneration = primaryActionGeneration
isPerformingPrimaryAction = true
@@ -180,7 +173,7 @@ final class DroneDockPreparationViewModel {
/// 对明确创建成功的任务发送一次召唤;只有明确业务拒绝允许之后再次提交。
@MainActor
private func summonCreatedTask(onStateChange: @escaping @MainActor () -> Void) async {
guard allowsTaskSubmission, !isCreatingTask, !isSummoning, !taskCreationOutcomeUnknown,
guard !isCreatingTask, !isSummoning, !taskCreationOutcomeUnknown,
!hasSubmittedSummon, !summonOutcomeUnknown,
let taskID = createdTask?.taskID, taskID > 0 else { return }
summonGeneration &+= 1
@@ -211,14 +204,9 @@ final class DroneDockPreparationViewModel {
hasSubmittedSummon = true
summonOutcomeUnknown = false
} catch {
if error is DeviceCommandDebugBlockedError, summonGeneration == requestGeneration {
didSendSummon = false
}
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
recordPreparationEvent("summon.failed_or_unknown", fields: ["error": DroneDockDiagnostics.errorFields(error)])
if error is DeviceCommandDebugBlockedError {
shootErrorMessage = DeviceCommandDebugPolicy.blockedMessage
} else if case let APIError.serverCode(code, message) = error {
if case let APIError.serverCode(code, message) = error {
shootErrorCode = code
shootErrorMessage = message
summonRequiresTaskReview = DroneDockPreparationFailure.requiresTaskReview(message)
@@ -249,7 +237,7 @@ final class DroneDockPreparationViewModel {
@MainActor
func createTask(onStateChange: @escaping @MainActor () -> Void = {}) async {
recordPreparationEvent("create.requested", fields: ["allowed": canCreateTask])
guard allowsTaskSubmission, canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID,
guard canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID,
let number = order.orderNumber, let projectID = order.projectID else { return }
taskCreationGeneration &+= 1
let requestGeneration = taskCreationGeneration
@@ -300,14 +288,9 @@ final class DroneDockPreparationViewModel {
hasCreatedTask = true
taskCreationOutcomeUnknown = false
} catch {
if error is DeviceCommandDebugBlockedError, taskCreationGeneration == requestGeneration {
didSendTaskCreation = false
}
guard acceptsTaskCreation(requestGeneration) else { return }
recordPreparationEvent("create.failed_or_unknown", fields: ["error": DroneDockDiagnostics.errorFields(error)])
if error is DeviceCommandDebugBlockedError {
taskCreationErrorMessage = DeviceCommandDebugPolicy.blockedMessage
} else if didSendTaskCreation {
if didSendTaskCreation {
if case APIError.serverCode = error {
taskCreationErrorMessage = error.localizedDescription
} else {
@@ -484,7 +467,6 @@ final class DroneDockPreparationViewModel {
if isCreatingTask { return "正在创建任务…" }
if isSummoning { return "正在召唤无人机…" }
if hasSubmittedSummon || summonRequiresTaskReview { return "查看拍摄任务" }
if !allowsTaskSubmission { return "仅限模拟调试" }
if summonOutcomeUnknown { return "召唤结果待核对" }
if hasCreatedTask { return shootErrorMessage == nil ? "确认并召唤" : "重试召唤" }
if taskCreationOutcomeUnknown { return "结果待核对" }
@@ -497,7 +479,6 @@ final class DroneDockPreparationViewModel {
if isCreatingTask { return "正在创建待飞任务,请勿重复点击" }
if isSummoning { return "任务已创建,正在提交召唤请求" }
if creationContextInvalidated, let errorMessage { return errorMessage }
if !allowsTaskSubmission && !hasSubmittedSummon { return DeviceCommandDebugPolicy.blockedMessage }
if createdTask != nil {
if hasSubmittedSummon { return "召唤请求已提交,请等待任务状态更新" }
if let summonFailure { return summonFailure.message }
@@ -108,9 +108,7 @@ final class DroneDockShootingTaskViewModel {
self.hasInitialTravelReceipt = context.canLoad && initialSummonReceipt?.confirmsTravel(
taskID: taskID, orderNumber: order.orderNumber, scenicID: context.scenicID) == true
recordTaskEvent("task.created", fields: ["initial_travel_receipt": hasInitialTravelReceipt,
"summon_receipt": DroneDockTaskTraceFields.summon(initialSummonReceipt),
"debug_flight_blocked": DeviceCommandDebugPolicy.blocksFlightRequests,
"debug_live_blocked": DeviceCommandDebugPolicy.blocksLiveRequests])
"summon_receipt": DroneDockTaskTraceFields.summon(initialSummonReceipt)])
}
/// 页面与业务层共享会话标识,串联准备页导航、快照和按钮事件。
@@ -154,6 +152,12 @@ final class DroneDockShootingTaskViewModel {
await refreshSnapshot(allowWhileStarting: false)
}
/// 无缓存订阅只认此调用新读取且采纳的 HTTP 结果;读取未发起、失败或旧版本均返回 nil。
@MainActor
func refreshForRealtimeSeed() async -> DroneDockHTTPSnapshotResult? {
await refreshSnapshot(allowWhileStarting: false)
}
/// 操作提交前仅作废在途读取,保留快照和操作防重锁;迟到的旧读取不能覆盖操作回查。
@MainActor
func invalidatePendingRefresh() {
@@ -174,10 +178,11 @@ final class DroneDockShootingTaskViewModel {
}
@MainActor
@discardableResult
private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false,
allowWhileResummoning: Bool = false) async {
allowWhileResummoning: Bool = false) async -> DroneDockHTTPSnapshotResult? {
guard !isLoading, !identityInvalidated, readAccessError == nil, !isStartingShooting || allowWhileStarting,
!isResummoning || allowWhileResummoning else { return }
!isResummoning || allowWhileResummoning else { return nil }
generation &+= 1
let requestGeneration = generation
let revisionAtRequest = snapshotRevision
@@ -189,12 +194,12 @@ final class DroneDockShootingTaskViewModel {
isLoading = false
}
}
guard accepts(requestGeneration) else { return }
guard accepts(requestGeneration) else { return nil }
guard context.canLoad, taskID > 0,
DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
response = nil
errorMessage = "缺少有效任务、订单或景区信息,请返回工作台重新进入"
return
return nil
}
do {
let value = try await service.shooting(taskID: taskID, liveBattery: false)
@@ -202,24 +207,31 @@ final class DroneDockShootingTaskViewModel {
recordTaskEvent("snapshot.http_ignored", fields: ["read_generation": requestGeneration,
"current_generation": generation, "reason": "cancelled_or_stale_read",
"incoming": DroneDockTaskTraceFields.snapshot(value)])
return
return nil
}
if applyTaskSnapshot(value, source: .http) == .invalid {
let acceptance = applyTaskSnapshot(value, source: .http)
if acceptance == .invalid {
response = nil
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
}
switch acceptance {
case .applied, .duplicate:
return DroneDockHTTPSnapshotResult(snapshot: value, acceptance: acceptance)
case .outdated, .invalid: return nil
}
} catch {
guard accepts(requestGeneration) else { return }
guard accepts(requestGeneration) else { return nil }
if Self.stopsTaskReading(error) {
stopReading(message: error.localizedDescription)
return
return nil
}
// 迟到 HTTP 失败不能覆盖请求期间已收到的有效实时状态。
guard snapshotRevision == revisionAtRequest else { return }
guard snapshotRevision == revisionAtRequest else { return nil }
if !(error is CancellationError) { errorMessage = error.localizedDescription }
recordTaskEvent("snapshot.http_failed", fields: [
"retained_snapshot": response != nil, "error": DroneDockDiagnostics.errorFields(error)
])
return nil
}
}
@@ -353,7 +365,7 @@ final class DroneDockShootingTaskViewModel {
}
}
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;Debug 真实页面保持禁用。
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放。
var canStartShooting: Bool {
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& hasControlSnapshotIdentity
@@ -418,11 +430,8 @@ final class DroneDockShootingTaskViewModel {
guard acceptsStart(requestGeneration) else { return }
await refreshSnapshot(allowWhileStarting: true)
} catch {
if error is DeviceCommandDebugBlockedError, startGeneration == requestGeneration { didSendStart = false }
guard acceptsStart(requestGeneration) else { return }
if error is DeviceCommandDebugBlockedError {
startErrorMessage = DeviceCommandDebugPolicy.blockedMessage
} else if case APIError.serverCode = error {
if case APIError.serverCode = error {
startErrorMessage = error.localizedDescription
} else {
markStartUnknown(reason: error.localizedDescription)
@@ -629,10 +638,7 @@ final class DroneDockShootingTaskViewModel {
fields: ["reason": "stale_task_context", "error": DroneDockDiagnostics.errorFields(error)])
return
}
if error is DeviceCommandDebugBlockedError {
commandOperations[operation.command]?.phase = .finished
commandOperations[operation.command]?.error = DeviceCommandDebugPolicy.blockedMessage
} else if case APIError.serverCode = error {
if case APIError.serverCode = error {
commandOperations[operation.command]?.phase = .finished
commandOperations[operation.command]?.error = error.localizedDescription
} else {
@@ -731,11 +737,8 @@ final class DroneDockShootingTaskViewModel {
guard acceptsResummon(requestGeneration) else { return }
await refreshSnapshot(allowWhileStarting: false, allowWhileResummoning: true)
} catch {
if error is DeviceCommandDebugBlockedError, resummonGeneration == requestGeneration { didSendResummon = false }
guard acceptsResummon(requestGeneration) else { return }
if error is DeviceCommandDebugBlockedError {
resummonErrorMessage = DeviceCommandDebugPolicy.blockedMessage
} else if case APIError.serverCode = error {
if case APIError.serverCode = error {
didSendResummon = false
resummonErrorMessage = error.localizedDescription
} else {
@@ -318,7 +318,6 @@ final class DroneDockHomeViewController: GlobalLoadingPageViewController {
planeStatusService: DroneDockPlaneStatusAPI(client: NetworkServices.shared.apiClient),
taskCreationService: DroneDockTaskCreationAPI(client: NetworkServices.shared.apiClient),
shootService: DroneDockShootAPI(client: NetworkServices.shared.apiClient),
allowsTaskSubmission: !DeviceCommandDebugPolicy.blocksFlightRequests,
currentContext: { Self.currentContext() }
))
}
@@ -66,8 +66,7 @@ final class DroneDockRemotePreparationViewController: GlobalLoadingPageViewContr
navigationItem.rightBarButtonItem = records
}
#if DEBUG
if simulationRecordsProvider == nil, DeviceCommandDebugPolicy.blocksLiveRequests,
viewModel.isTaskSubmissionBlocked {
if simulationRecordsProvider == nil {
let simulation = UIBarButtonItem(title: "本地模拟", style: .plain,
target: self, action: #selector(openLocalSimulation))
simulation.accessibilityIdentifier = "drone.preparation.mock.entry"
@@ -192,8 +191,7 @@ final class DroneDockRemotePreparationViewController: GlobalLoadingPageViewContr
"scenic_id": viewModel.context.scenicID,
"spot_id": viewModel.selectedSpotID as Any? ?? NSNull(),
"air_line_id": viewModel.selectedRouteID as Any? ?? NSNull(),
"enabled": viewModel.isPrimaryActionEnabled,
"blocked": viewModel.isTaskSubmissionBlocked
"enabled": viewModel.isPrimaryActionEnabled
])
guard !isRefreshing, !isStartingCreation else {
logPreparationEvent("preparation.confirm_rejected", fields: ["reason": "refresh_or_submission_in_progress"])
@@ -325,7 +323,6 @@ final class DroneDockRemotePreparationViewController: GlobalLoadingPageViewContr
fields["app_active"] = isApplicationActive
fields["refreshing"] = isRefreshing
fields["submitting"] = isStartingCreation
fields["debug_flight_blocked"] = DeviceCommandDebugPolicy.blocksFlightRequests
viewModel.recordPreparationEvent(name, fields: fields)
}
@@ -3,7 +3,7 @@ import UIKit
/// 组装真实拍摄任务页;构造时不发请求,页面出现后才读取同一任务。
@MainActor
enum DroneDockShootingTaskEntry {
/// 使用已有任务读取状态;Release 注入已授权的真实控制,Debug 保持只读。
/// 使用已有任务读取状态,两种构建均注入真实服务并按后端权限操作。
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext) -> UIViewController {
makeController(taskID: taskID, order: order, context: context, coverURL: nil)
@@ -20,15 +20,15 @@ enum DroneDockShootingTaskEntry {
identityIsCurrent: { context.hasSameIdentity(as: DroneDockHomeViewController.currentContext()) })
let live = DroneDockLiveViewModel(
context: context, taskID: taskID,
service: DeviceCommandDebugPolicy.blocksLiveRequests ? nil : DroneDockLiveAPI(client: client),
allowsDevicePlayback: !DeviceCommandDebugPolicy.blocksLiveRequests,
service: DroneDockLiveAPI(client: client),
allowsDevicePlayback: true,
currentContext: { DroneDockHomeViewController.currentContext() })
return DroneDockShootingTaskViewController(viewModel: DroneDockShootingTaskViewModel(
context: context, taskID: taskID, order: order,
service: DroneDockShootingAPI(client: client),
startService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockStartShootAPI(client: client),
commandService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockCommandAPI(client: client),
resummonService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockShootAPI(client: client),
startService: DroneDockStartShootAPI(client: client),
commandService: DroneDockCommandAPI(client: client),
resummonService: DroneDockShootAPI(client: client),
initialSummonReceipt: initialSummonReceipt,
currentContext: { DroneDockHomeViewController.currentContext() }
), liveViewModel: live, coverURL: coverURL, realtimeSession: realtime)
@@ -95,6 +95,9 @@ final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController
realtimeSession?.onConnectionState = { [weak self] state in
self?.connectionStateChanged(state)
}
realtimeSession?.onHTTPSeedRequired = { [weak self] in
self?.refreshTaskIfVisible(isPolling: true)
}
}
@available(*, unavailable)
@@ -439,18 +442,30 @@ final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController
cancelScheduledPoll()
requestGeneration &+= 1
let generation = requestGeneration
let httpSeedRequest = realtimeSession?.pendingHTTPSeedRequest
isRequesting = true
applySnapshot()
refreshTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.refresh()
let seedResult: DroneDockHTTPSnapshotResult?
if httpSeedRequest != nil { seedResult = await self.viewModel.refreshForRealtimeSeed() }
else { await self.viewModel.refresh(); seedResult = nil }
guard self.isPageVisible, self.isApplicationActive,
self.requestGeneration == generation, !Task.isCancelled else { return }
self.refreshTask = nil
self.isRequesting = false
if let httpSeedRequest, let seedResult {
self.realtimeSession?.acceptHTTPSeed(seedResult, requestID: httpSeedRequest)
}
self.applySnapshot()
if self.viewModel.canContinuePolling { self.realtimeSession?.start() }
else { self.realtimeSession?.stop() }
// 无缓存提示可能在旧 HTTP 读取途中到达;旧请求不充当首包,结束后再串行补读。
if let pendingSeed = self.realtimeSession?.pendingHTTPSeedRequest, pendingSeed != httpSeedRequest,
self.viewModel.canContinuePolling {
self.refreshTaskIfVisible(isPolling: true)
return
}
self.scheduleNextPoll()
if !isPolling, self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.showToast("刷新失败,当前显示上次数据:\(error)")
@@ -571,7 +586,7 @@ final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController
/// 重召唤使用原任务 ID,回执后再查询状态,避免从受理结果推断设备已到达。
private func resummonIfAllowed() {
guard allowsControlActions, isPageVisible, isApplicationActive,
guard isPageVisible, isApplicationActive,
!isResummoningAction, !isStartingAction, !isSendingSafetyAction,
viewModel.canResummon else { return }
cancelPendingReadForAction()
@@ -655,10 +670,10 @@ final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController
feedPlaceholder.apply(liveViewModel)
}
/// 返航会中断任务,先明确展示其含义再提交一次;Debug 只开放隔离模拟入口。
/// 返航会中断任务,先明确展示其含义再提交一次。
private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) {
logEvent("action.safety", fields: ["command": command.rawValue, "enabled": viewModel.canSendCommand(command)])
guard allowsControlActions, isPageVisible, isApplicationActive,
guard isPageVisible, isApplicationActive,
presentedViewController == nil, !submittingCommands.contains(command), !isStartingAction,
!isResummoningAction, viewModel.canSendCommand(command) else {
logSafetyRejection(command, stage: "tap")
@@ -686,7 +701,7 @@ final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController
/// 同步锁只覆盖同一按钮;不同安全动作可各自等待,设备确认由 ViewModel 和快照处理。
private func sendSafetyCommand(_ command: DroneDockSafetyCommand) {
guard allowsControlActions, isPageVisible, isApplicationActive,
guard isPageVisible, isApplicationActive,
!submittingCommands.contains(command), !isStartingAction, !isResummoningAction,
viewModel.canSendCommand(command) else {
logSafetyRejection(command, stage: "submit")
@@ -757,9 +772,6 @@ final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController
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)
}
@@ -779,7 +791,6 @@ final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController
"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"
@@ -823,7 +834,6 @@ final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController
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") }
@@ -835,9 +845,6 @@ final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController
"reasons": reasons, "safety": safetyView.diagnosticFields])
}
private var allowsControlActions: Bool {
simulationRecordsProvider != nil || !DeviceCommandDebugPolicy.blocksFlightRequests
}
}
/// 以可选择的 JSON 文本展示本地模拟请求与回执,避免与真实接口联调混淆。
@@ -940,7 +947,6 @@ private final class DroneDockTaskSafetyView: UIView {
/// 两个按钮始终表示暂停与返航;已暂停、返航中和回巢使用本地文案,恢复入口位于中央。
func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool,
submittingCommands: Set<DroneDockSafetyCommand> = []) {
let allowsControls = isSimulation || !DeviceCommandDebugPolicy.blocksFlightRequests
let phase = model.presentation.phase
var controlState = model.flightControlState
if model.response?.flightControl == nil {
@@ -974,7 +980,7 @@ private final class DroneDockTaskSafetyView: UIView {
subtitle = "结果待核对"
}
let loading = submittingCommands.contains(command) || model.isCommandLoading(command)
let enabled = allowsControls && isInteractive && model.canSendCommand(command)
let enabled = isInteractive && model.canSendCommand(command)
button.apply(title: title, subtitle: subtitle, enabled: enabled, isLoading: loading)
button.setControlSymbol(command == .pause ? "pause.circle" : "arrow.uturn.backward")
}
@@ -81,7 +81,7 @@ enum DroneDockStartShootSimulation {
service: DroneDockPreparationAPI(client: client),
planeStatusService: DroneDockPlaneStatusAPI(client: client),
taskCreationService: DroneDockTaskCreationAPI(client: client),
shootService: DroneDockShootAPI(client: client), allowsTaskSubmission: true,
shootService: DroneDockShootAPI(client: client),
currentContext: { context })
return DroneDockRemotePreparationViewController(viewModel: model,
taskControllerFactory: taskFactory,
@@ -31,7 +31,7 @@ protocol DroneDockRTCReceivingRoom: AnyObject {
func destroy()
}
/// 火山 SDK 适配器;真实创建点再次拦截 Debug,测试不能通过注入绕开保护。
/// 火山 SDK 适配器,封装当前任务的只收视频引擎与房间。
@MainActor
final class DroneDockVolcEngineAdapter: DroneDockRTCReceivingEngine {
private let engine: ByteRTCEngine
@@ -45,9 +45,8 @@ final class DroneDockVolcEngineAdapter: DroneDockRTCReceivingEngine {
self.delegate = delegate
}
/// 仅在构建策略允许真实图传时构造 SDK。
/// 按已验证的当前任务播放配置构造 SDK。
static func make(appID: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)? {
guard !DeviceCommandDebugPolicy.blocksLiveRequests else { return nil }
let delegate = DroneDockVolcDelegate(emit: onEvent)
let config = ByteRTCEngineConfig()
config.appID = appID
@@ -18,7 +18,7 @@ extension DroneDockLivePlaying {
func setGeometryHandler(_ handler: (@MainActor (DroneDockLiveGeometry) -> Void)?) {}
}
/// 真实 SDK 入口始终执行编译期禁飞保护,没有运行时放行参数。
/// 通过双路接收器播放真实图传,生命周期由任务页管理。
@MainActor
final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
private let receiver = DroneDockLiveReceiver(makeEngine: DroneDockVolcEngineAdapter.make)
@@ -28,12 +28,9 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
receiver.setGeometryHandler(handler)
}
/// Release 通过接收器播放;Debug 在创建 SDK 之前拒绝连接。
/// 两种构建均通过同一接收器播放当前任务的图传。
func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView,
onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) {
guard !DeviceCommandDebugPolicy.blocksLiveRequests else {
stop(); onEvent(.failed(DeviceCommandDebugPolicy.blockedMessage)); return
}
receiver.start(configurations, in: view, onEvent: onEvent)
}
@@ -48,7 +45,7 @@ final class DroneDockLiveReceiver: DroneDockLivePlaying {
private let makeEngine: (String, @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)?
private let firstFrameDelay: @Sendable () async throws -> Void
/// 生产环境注入带 Debug 保护的适配器;测试只注入内存接收端。
/// 正式页面注入 SDK 适配器;测试注入内存接收端。
init(makeEngine: @escaping (String, @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)?,
firstFrameDelay: @escaping @Sendable () async throws -> Void = { try await Task.sleep(for: .seconds(20)) }) {
self.makeEngine = makeEngine