feat(drone-dock): 完善真实联调、状态轮询与准备页反馈

开放 Release 真实操作并保留 Debug 拦截;恢复前台 shooting 串行轮询;统一打印机巢请求与完整原值响应;优化长点位名称、未拍摄文案、报备失败及已结束任务提示,移除成功回执 UI。补充相关测试、离线策略检查和联调说明。
This commit is contained in:
2026-11-02 16:26:50 +08:00
parent b21a3b6cb6
commit 2d86ec8cd7
37 changed files with 1298 additions and 411 deletions
+48 -12
View File
@@ -24,6 +24,7 @@ final class APIClient {
private let decoder: JSONDecoder
private let notificationCenter: NotificationCenter
private let debugLogSink: (String) -> Void
private let droneDockLogSink: (String) -> Void
private var authTokenProvider: (() -> String?)?
private let environment: APIEnvironment
@@ -39,7 +40,8 @@ final class APIClient {
appVersion: String = AppClientInfo.appVersion(),
osType: String = AppClientInfo.osType,
notificationCenter: NotificationCenter = .default,
debugLogSink: @escaping (String) -> Void = { print($0) }
debugLogSink: @escaping (String) -> Void = { print($0) },
droneDockLogSink: @escaping (String) -> Void = DroneDockDiagnostics.write
) {
self.environment = environment
self.session = session
@@ -47,6 +49,7 @@ final class APIClient {
self.decoder = decoder
self.notificationCenter = notificationCenter
self.debugLogSink = debugLogSink
self.droneDockLogSink = droneDockLogSink
self.appVersion = appVersion.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? "1.0.0"
self.osType = osType.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? AppClientInfo.osType
}
@@ -69,36 +72,69 @@ final class APIClient {
_ apiRequest: APIRequest<Response>,
tokenOverride: String? = nil
) async throws -> Response {
let request = try DeviceCommandDebugPolicy.prepare(
makeURLRequest(apiRequest, tokenOverride: tokenOverride),
isLocalSimulation: session is any LocalSimulationURLSession)
logRequest(request, includeBody: apiRequest.logsPayload, category: apiRequest.redactedLogCategory)
let original = try 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)]))
} else {
logRequest(request, includeBody: apiRequest.logsPayload, category: apiRequest.redactedLogCategory)
}
let data: Data
let response: URLResponse
do {
(data, response) = try await session.data(for: request)
} catch is CancellationError {
logCancelled(for: request, reason: "CancellationError", category: apiRequest.redactedLogCategory)
if let trace { droneDockLogSink(trace.message("request.cancelled")) }
else { logCancelled(for: request, reason: "CancellationError", category: apiRequest.redactedLogCategory) }
throw CancellationError()
} catch let error as URLError {
if let trace { droneDockLogSink(trace.message(error.code == .cancelled ? "request.cancelled" : "request.failed",
fields: DroneDockDiagnostics.errorFields(error))) }
if error.code == .cancelled {
logCancelled(for: request, reason: "URLError.cancelled", category: apiRequest.redactedLogCategory)
if trace == nil { logCancelled(for: request, reason: "URLError.cancelled", category: apiRequest.redactedLogCategory) }
throw CancellationError()
}
logFailure(for: request, error: error, category: apiRequest.redactedLogCategory)
if trace == nil { logFailure(for: request, error: error, category: apiRequest.redactedLogCategory) }
throw APIError.networkFailed(networkErrorMessage(for: error))
} catch {
logFailure(for: request, error: error, category: apiRequest.redactedLogCategory)
if let trace { droneDockLogSink(trace.message("request.failed", fields: DroneDockDiagnostics.errorFields(error))) }
if trace == nil { logFailure(for: request, error: error, category: apiRequest.redactedLogCategory) }
throw APIError.networkFailed(error.localizedDescription)
}
logResponse(for: request, response: response, data: data, includeBody: apiRequest.logsPayload,
category: apiRequest.redactedLogCategory)
if let trace {
// 用户要求机巢接口原样记录请求和响应,含 live / STS;统一通路避免重复打印。
droneDockLogSink(trace.message("response.received", fields: [
"http_status": (response as? HTTPURLResponse)?.statusCode ?? 0,
"response_headers": (response as? HTTPURLResponse)?.allHeaderFields.reduce(into: [String: String]()) {
$0[String(describing: $1.key)] = String(describing: $1.value)
} ?? [:],
"body": DroneDockDiagnostics.payload(data)
]))
} else {
logResponse(for: request, response: response, data: data, includeBody: apiRequest.logsPayload,
category: apiRequest.redactedLogCategory)
}
do {
try validateHTTPResponse(response, data: data)
return try decodeEnvelope(Response.self, from: data)
let value = try decodeEnvelope(Response.self, from: data)
if let trace { droneDockLogSink(trace.message("response.decoded")) }
return value
} catch let error as APIError {
if let trace { droneDockLogSink(trace.message("response.rejected", fields: DroneDockDiagnostics.errorFields(error))) }
notifySessionErrorIfNeeded(for: error, request: request)
throw error
}
+1 -1
View File
@@ -21,7 +21,7 @@ nonisolated struct APIRequest<Response: Decodable> {
var queryItems: [URLQueryItem]
var headers: [String: String]
var body: AnyEncodable?
/// 敏感请求关闭正文日志,避免验证码和注销资产进入调试日志。
/// 控制普通正文日志;机巢范围按用户要求始终记录完整请求和响应。
var logsPayload: Bool
/// 为指定模块输出带标签的脱敏日志;隐藏凭证字段和响应中媒体 URL 的查询参数。
var redactedLogCategory: String?
@@ -1,9 +1,15 @@
import Foundation
/// 禁飞期间的请求边界;正式包仅允许用户手动图传,不允许创建或飞控。
/// 调试请求边界:Debug 禁止真实设备操作,Release 按用户授权开放已对接的操作。
enum DeviceCommandDebugPolicy {
/// 飞控与真实待飞任务在所有构建中关闭,不因打 Release 包而解除禁飞。
static let blocksFlightRequests = true
/// 2026-11-02 用户授权 Release 真机联调;Debug 仍无运行时放行开关。
static var blocksFlightRequests: Bool {
#if DEBUG
true
#else
false
#endif
}
/// 所有 Debug 构建禁止真实设备操作,没有启动参数或设置开关可临时放行。
static var blocksLiveRequests: Bool {
#if DEBUG
@@ -20,12 +26,15 @@ enum DeviceCommandDebugPolicy {
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" {
throw DeviceCommandDebugBlockedError()
guard !blocksFlightRequests, request.httpMethod == "POST" else { throw DeviceCommandDebugBlockedError() }
return request
}
guard path == "/api/app/airport" || path.hasPrefix("/api/app/airport/") else { return request }
// 2026-11-02 仅为用户后续手动图传测试提供 Release 入口;Debug 仍禁止开流。
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",
@@ -0,0 +1,153 @@
import Foundation
import OSLog
/// 机巢联调日志:按用户要求在 Debug 与 Release 控制台原样记录字段,不做脱敏。
enum DroneDockDiagnostics {
private static let logger = Logger(subsystem: "com.yuanzhixiang.suixinkan", category: "DroneDock")
private static let sessionID = String(UUID().uuidString.prefix(8))
/// 按 UTF-8 字节分段,避免系统日志截断大响应;每段携带同一事件 ID 和序号。
static func write(_ message: String) {
let entry = String(UUID().uuidString.prefix(8))
let chunks = chunks(message)
for (index, chunk) in chunks.enumerated() {
let line = "[DroneDock] session=\(sessionID) entry=\(entry) part=\(index + 1)/\(chunks.count) \(chunk)"
logger.notice("\(line, privacy: .public)")
}
}
/// 页面、业务与 RTC 事件以结构化字段记录。
static func event(_ name: String, taskID: Int? = nil, fields: [String: Any] = [:]) {
var fields = fields
fields["task_id"] = taskID
fields["event"] = name
write(json(fields))
}
/// 覆盖机巢全部业务接口、景区空境库及共用 STS;不依赖页面或构建环境开关。
static func includes(path: String) -> Bool {
["/api/app/airport/", "/api/yf-handset-app/photog/multi-plane/", "/api/app/scenic-media/"]
.contains(where: path.hasPrefix) || path == "/api/app/config/get-sts-token"
}
/// JSON 保留完整字段,文本错误页原样记录;二进制正文只记录字节数。
static func payload(_ data: Data?) -> Any {
guard let data, !data.isEmpty else { return "<empty>" }
return (try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed))
?? String(data: data, encoding: .utf8)
?? "<binary: \(data.count) bytes>"
}
/// 排序 JSON 便于复制比对,所有字段值保持原样。
static func json(_ object: Any) -> String {
guard let data = try? JSONSerialization.data(withJSONObject: object,
options: [.sortedKeys, .fragmentsAllowed, .withoutEscapingSlashes]),
let text = String(data: data, encoding: .utf8) else { return "<invalid diagnostic fields>" }
return text
}
/// 记录业务码、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]
}
if case APIError.decodeFailed(let message) = error { return ["kind": "decode_failed", "message": message] }
if case APIError.httpStatus(let code, let message) = error {
return ["kind": "http_rejected", "http_status": code, "message": message]
}
if case APIError.emptyData = error { return ["kind": "empty_data"] }
let value = error as NSError
var fields: [String: Any] = ["kind": "error", "domain": value.domain, "code": value.code,
"message": value.localizedDescription]
fields["failing_url"] = value.userInfo[NSURLErrorFailingURLStringErrorKey] as? String
return fields
}
/// 单段最多 600 字节,长 JSON 可按 entry 和 part 拼回完整响应。
static func chunks(_ text: String) -> [String] {
var result: [String] = []
var current = ""
var bytes = 0
for scalar in text.unicodeScalars {
let next = String(scalar)
if bytes + next.utf8.count > 600 { result.append(current); current = ""; bytes = 0 }
current += next
bytes += next.utf8.count
}
if !current.isEmpty { result.append(current) }
return result.isEmpty ? [""] : result
}
}
/// 视频上传和素材下载的网络摘要,保留完整地址和传输状态。
struct DroneDockFileTransferTrace: Sendable {
private let requestID = UUID().uuidString
private let started = ProcessInfo.processInfo.systemUptime
private let operation: String
private let method: String
private let remoteURL: URL?
/// 仅在实际文件传输边界创建,记录传入的完整目标地址。
init(operation: String, method: String, remoteURL: URL?) {
self.operation = operation
self.method = method
self.remoteURL = remoteURL
}
/// 请求、响应和错误共用同一关联 ID;文件响应仅记录状态与大小。
func message(_ event: String, fields: [String: Any] = [:]) -> String {
var fields = fields
fields["event"] = operation + "." + event
fields["request_id"] = requestID
fields["elapsed_ms"] = Int((ProcessInfo.processInfo.systemUptime - started) * 1_000)
fields["source"] = "network"
fields["method"] = method
fields["host"] = remoteURL?.host
fields["url"] = remoteURL?.absoluteString
return DroneDockDiagnostics.json(fields)
}
}
/// 一次请求的关联 ID 与耗时;模拟/真实传输明确区分,不把 HTTP 成功当作设备执行成功。
struct DroneDockRequestTrace {
private let requestID = UUID().uuidString
private let started = ProcessInfo.processInfo.systemUptime
private let request: URLRequest
private let isSimulation: Bool
/// 未在机巢范围的请求不生成日志。
init?(request: URLRequest, isSimulation: Bool) {
guard DroneDockDiagnostics.includes(path: request.url?.path ?? "") else { return nil }
self.request = request
self.isSimulation = isSimulation
}
/// 保留完整地址、请求头、业务参数与固定身份。
func message(_ event: String, fields: [String: Any] = [:]) -> String {
var fields = fields
fields["event"] = event
fields["request_id"] = requestID
fields["elapsed_ms"] = Int((ProcessInfo.processInfo.systemUptime - started) * 1_000)
fields["source"] = isSimulation ? "local_simulation" : "network"
fields["host"] = request.url?.host
fields["path"] = request.url?.path
fields["method"] = request.httpMethod
fields["url"] = request.url?.absoluteString
fields["request_headers"] = request.allHTTPHeaderFields ?? [:]
fields["app_version"] = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
fields["app_build"] = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
#if DEBUG
fields["build"] = "Debug"
#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)
}
}
@@ -1,6 +1,6 @@
import Foundation
/// 基于既有订单飞行任务发送单次安全指令;禁飞期间仅向本地模拟页面注入。
/// 基于既有订单飞行任务发送单次安全指令;Release 注入真实页面,Debug 仅向本地模拟页面注入。
protocol DroneDockCommandSending: Sendable {
/// 提交任务 ID 和白名单指令,不创建任务、不选机,也不自动重试。
@MainActor
@@ -1,6 +1,6 @@
import Foundation
/// 朱工任务图传参数服务;请求可能启动设备图传,禁飞期间只允许隔离模拟注入。
/// 朱工任务图传参数服务;请求可能启动设备图传,Release 可手动开启,Debug 只允许隔离模拟注入。
protocol DroneDockLiveServing: Sendable {
/// 读取同一订单飞行任务的图传回执,不创建任务或更换飞机。
@MainActor
@@ -27,7 +27,7 @@ final class DroneDockShootAPI: DroneDockShootServing, DroneDockResummonServing {
try await send(taskID: taskID, restart: false)
}
/// 复用同一订单飞行任务请求重启;当前仅由隔离模拟入口注入,真实传输仍受禁飞保护。
/// 复用同一订单飞行任务请求重启;Release 真实入口及隔离模拟入口按策略注入。
func resummon(taskID: Int) async throws -> DroneDockShootResponse {
try await send(taskID: taskID, restart: true)
}
@@ -7,7 +7,7 @@ protocol DroneDockStartShooting: Sendable {
func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse
}
/// start-shoot 合同适配;禁飞期间真实传输仍由统一客户端阻断,仅用 Mock 验证。
/// start-shoot 合同适配;Debug 真实传输由统一客户端阻断,Release 按用户授权开放。
@MainActor
final class DroneDockStartShootAPI: DroneDockStartShooting {
private let client: APIClient
@@ -0,0 +1,43 @@
import Foundation
/// 准备页的业务失败提示;区分创建与召唤,不把通用业务错误码当作未报备。
struct DroneDockPreparationFailure: Equatable, Sendable {
/// 失败发生的提交步骤。
enum Stage: Sendable { case creation, summon }
/// 面向工作人员的标题。
let title: String
/// 原因及下一步操作,不包含接口 JSON。
let message: String
/// 后端文字明确指出报备问题时,额外弹出提醒。
let requiresFiling: Bool
/// 未获得专用错误码前,仅匹配明确报备/备案失败的文字,其他原因保持后端原意。
init(message: String, stage: Stage, outcomeUnknown: Bool) {
requiresFiling = !outcomeUnknown && Self.isFilingFailure(message)
if outcomeUnknown {
title = stage == .creation ? "任务创建结果待核对" : "召唤结果待核对"
self.message = message
} else if requiresFiling {
title = "请先完成飞行报备"
self.message = message + "\n请联系相关负责人核实并完成飞行报备,确认生效后再重试。"
} else if stage == .summon && Self.requiresTaskReview(message) {
title = "任务已结束"
self.message = "当前任务已结束,无法直接召唤。请先查看拍摄任务状态;如需重新召唤,在任务页确认后操作。"
} else {
title = stage == .creation ? "任务创建失败" : "召唤失败"
self.message = message
}
}
/// 仅识别实际返回的明确终止提示;不会据此自动发送 restart=true。
static func requiresTaskReview(_ message: String) -> Bool {
message.contains("任务已结束") && message.contains("无法召唤")
}
private static func isFilingFailure(_ message: String) -> Bool {
["未报备", "未完成报备", "报备未", "报备失败", "报备过期", "报备已过期",
"报备失效", "报备已失效", "无有效报备", "没有报备", "无报备", "请先报备", "需要报备",
"未备案", "未完成备案", "备案未", "备案失败", "备案已过期", "请先备案"]
.contains(where: message.contains)
}
}
@@ -92,7 +92,7 @@ struct DroneDockShootingPlaneStatus: Decodable, Equatable, Sendable {
let scenicID: Int?
/// 后端景区连接状态。
let connected: Bool?
/// 保留后端建议间隔;当前任务页不据此安排定时请求。
/// 后端建议轮询间隔,任务页校验并限制频率后使用。
let pollHintMS: Int?
/// 设备快照字段映射,其余字段仍保留在完整 dataJSON 中。
@@ -92,14 +92,33 @@ struct DroneDockOSSFilmTransport: DroneDockFilmTransporting {
let sdkConfiguration = Configuration.default().withRegion(configuration.region).withCredentialsProvider(credentials)
sdkConfiguration.withEndpoint(configuration.endpoint)
let client = Client(sdkConfiguration)
_ = try await client.putObject(PutObjectRequest(
bucket: configuration.bucket, key: objectKey, contentType: contentType, body: .file(fileURL),
progress: ProgressClosure { _, transferred, expected in
guard expected > 0 else { return }
let value = Int(min(100, max(0, Double(transferred) / Double(expected) * 100)))
Task { @MainActor in onProgress(value) }
}
))
let trace = DroneDockFileTransferTrace(operation: "file_upload", method: "PUT",
remoteURL: URL(string: configuration.endpoint))
let fileSize = (try? fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0
DroneDockDiagnostics.write(trace.message("request.started", fields: [
"bucket": configuration.bucket, "object_key": objectKey,
"bytes": fileSize, "content_type": contentType, "body": "<binary omitted>"
]))
do {
let result = try await client.putObject(PutObjectRequest(
bucket: configuration.bucket, key: objectKey, contentType: contentType, body: .file(fileURL),
progress: ProgressClosure { _, transferred, expected in
guard expected > 0 else { return }
let value = Int(min(100, max(0, Double(transferred) / Double(expected) * 100)))
Task { @MainActor in onProgress(value) }
}
))
DroneDockDiagnostics.write(trace.message("response.received", fields: [
"http_status": result.statusCode, "oss_request_id": result.requestId,
"response_headers": result.headers ?? [:],
"body": DroneDockDiagnostics.payload(result.callbackResult)
]))
} catch {
let cancelled = error is CancellationError || (error as? URLError)?.code == .cancelled
DroneDockDiagnostics.write(trace.message(cancelled ? "request.cancelled" : "request.failed",
fields: DroneDockDiagnostics.errorFields(error)))
throw error
}
try Task.checkCancellation()
#else
throw OSSUploadError.sdkUnavailable
@@ -123,8 +123,10 @@ final class DroneDockLiveViewModel {
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 ?? ""])
} catch {
state = .unavailable(error.localizedDescription)
DroneDockDiagnostics.event("live.parameters_rejected", taskID: taskID, fields: ["reason": error.localizedDescription])
}
return
}
@@ -155,6 +157,7 @@ final class DroneDockLiveViewModel {
/// 离页、后台或取消时作废旧请求并清除本地播放来源,不向设备发送停止指令。
@MainActor
func invalidate() {
if playbackSessionID != nil { DroneDockDiagnostics.event("live.stopped", taskID: taskID) }
generation &+= 1
isLoading = false
response = nil
@@ -173,6 +176,8 @@ final class DroneDockLiveViewModel {
state = .failed("账号或景区已变化,请返回工作台重新进入")
return
}
DroneDockDiagnostics.event("live.playback_event", taskID: taskID,
fields: ["playback_session": sessionID.uuidString, "result": String(describing: event)])
switch event {
case .firstFrame: state = .playing
case .failed(let message):
@@ -38,6 +38,20 @@ final class DroneDockPreparationViewModel {
private(set) var shootErrorMessage: String?
/// 召唤写请求结果不明确时禁止重发,等待后续核对任务状态。
private(set) var summonOutcomeUnknown = false
/// 后端明确说明原任务已结束时,转为查看原任务,禁止继续重复首次召唤。
private(set) var summonRequiresTaskReview = false
/// 创建失败的用户提示;成功回执仅供业务与日志使用,不在页面输出。
var creationFailure: DroneDockPreparationFailure? {
guard createdTask == nil, let message = taskCreationErrorMessage else { return nil }
return DroneDockPreparationFailure(message: message, stage: .creation, outcomeUnknown: taskCreationOutcomeUnknown)
}
/// 召唤失败与创建失败分开表达,保留已经创建的任务。
var summonFailure: DroneDockPreparationFailure? {
guard let message = shootErrorMessage else { return nil }
return DroneDockPreparationFailure(message: message, stage: .summon, outcomeUnknown: summonOutcomeUnknown)
}
private let service: any DroneDockPreparationServing
private let planeStatusService: any DroneDockPlaneStatusServing
@@ -96,18 +110,18 @@ final class DroneDockPreparationViewModel {
var isTaskSelectionLocked: Bool {
isCreatingTask || isSummoning || isPerformingPrimaryAction || hasCreatedTask || taskCreationOutcomeUnknown
}
/// 仅展示真实返回的 data JSON,不拼造业务包裹或召唤结果。
/// 为诊断保留实际 data JSON,正式准备页不展示此内容。
var creationDataJSON: String? { createdTask?.dataJSON }
/// 仅保留 shoot 实际返回的 data;缺失时不拼造成功 JSON。
var shootDataJSON: String? { shootResponse?.dataJSON }
/// 创建回执携带的最新订单摘要优先于创建前购买摘要。
var latestOrderSummary: DroneDockHomeOrder? { createdTask?.order ?? projectInfo?.order }
/// 召唤已明确受理后只允许查看原任务,导航与再次提交召唤分开判断。
/// 已受理或后端明确要求核对已结束的任务时允许查看,导航不重复提交召唤。
var canOpenShootingTask: Bool {
context.canLoad && !creationContextInvalidated && !isLoading && !isCreatingTask
&& !isSummoning && !isPerformingPrimaryAction && !taskCreationOutcomeUnknown
&& !summonOutcomeUnknown && hasSubmittedSummon && shootResponse != nil
&& !summonOutcomeUnknown && ((hasSubmittedSummon && shootResponse != nil) || summonRequiresTaskReview)
&& (createdTask?.taskID ?? 0) > 0
}
@@ -115,7 +129,7 @@ final class DroneDockPreparationViewModel {
var isPrimaryActionEnabled: Bool {
guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
!isSummoning, !isPerformingPrimaryAction, !taskCreationOutcomeUnknown,
!hasSubmittedSummon, !summonOutcomeUnknown else { return false }
!hasSubmittedSummon, !summonOutcomeUnknown, !summonRequiresTaskReview else { return false }
if let createdTask { return createdTask.taskID > 0 }
return canCreateTask
}
@@ -166,6 +180,7 @@ final class DroneDockPreparationViewModel {
let response = try await shootService.shoot(taskID: taskID)
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
shootResponse = response
DroneDockDiagnostics.event("summon.receipt_accepted", taskID: taskID)
hasSubmittedSummon = true
summonOutcomeUnknown = false
} catch {
@@ -177,6 +192,7 @@ final class DroneDockPreparationViewModel {
shootErrorMessage = DeviceCommandDebugPolicy.blockedMessage
} else if case APIError.serverCode = error {
shootErrorMessage = error.localizedDescription
summonRequiresTaskReview = DroneDockPreparationFailure.requiresTaskReview(error.localizedDescription)
} else {
markSummonUnknown(reason: error.localizedDescription)
}
@@ -195,6 +211,7 @@ final class DroneDockPreparationViewModel {
if creationContextInvalidated {
shootResponse = nil
shootErrorMessage = nil
summonRequiresTaskReview = false
}
}
@@ -247,6 +264,7 @@ final class DroneDockPreparationViewModel {
throw APIError.decodeFailed("创建回执与当前订单或项目不一致,请核对任务")
}
createdTask = response
DroneDockDiagnostics.event("create.receipt_accepted", taskID: response.taskID)
hasCreatedTask = true
taskCreationOutcomeUnknown = false
} catch {
@@ -430,7 +448,7 @@ final class DroneDockPreparationViewModel {
var primaryButtonTitle: String {
if isCreatingTask { return "正在创建任务…" }
if isSummoning { return "正在召唤无人机…" }
if hasSubmittedSummon { return "查看拍摄任务" }
if hasSubmittedSummon || summonRequiresTaskReview { return "查看拍摄任务" }
if !allowsTaskSubmission { return "仅限模拟调试" }
if summonOutcomeUnknown { return "召唤结果待核对" }
if hasCreatedTask { return shootErrorMessage == nil ? "确认并召唤" : "重试召唤" }
@@ -445,13 +463,13 @@ final class DroneDockPreparationViewModel {
if isSummoning { return "任务已创建,正在提交召唤请求" }
if creationContextInvalidated, let errorMessage { return errorMessage }
if !allowsTaskSubmission && !hasSubmittedSummon { return DeviceCommandDebugPolicy.blockedMessage }
if let createdTask {
if hasSubmittedSummon { return "任务 \(createdTask.taskID) 的召唤请求已提交,请等待任务状态更新" }
if let shootErrorMessage { return shootErrorMessage }
if createdTask != nil {
if hasSubmittedSummon { return "召唤请求已提交,请等待任务状态更新" }
if let summonFailure { return summonFailure.message }
if summonOutcomeUnknown { return "召唤结果待核对,请勿重复提交" }
return "任务 \(createdTask.taskID) 已创建,等待召唤"
return "任务已创建,等待召唤"
}
if let taskCreationErrorMessage { return taskCreationErrorMessage }
if let creationFailure { return creationFailure.message }
if taskCreationOutcomeUnknown { return "创建结果待核对,请勿重复提交" }
if isLoading { return "正在获取拍摄准备信息" }
if let errorMessage { return errorMessage }
@@ -555,11 +573,13 @@ final class DroneDockPreparationViewModel {
}
private func markSummonUnknown(reason: String? = nil) {
DroneDockDiagnostics.event("summon.outcome_unknown", taskID: createdTask?.taskID)
summonOutcomeUnknown = true
shootErrorMessage = (reason.map { "\($0)。" } ?? "") + "召唤结果待核对,请先核对任务状态,勿重复提交"
}
private func markTaskCreationUnknown(reason: String? = nil) {
DroneDockDiagnostics.event("taskcreation.outcome_unknown", taskID: createdTask?.taskID)
taskCreationOutcomeUnknown = true
taskCreationErrorMessage = (reason.map { "\($0)。" } ?? "") + "创建结果待核对,请先查看订单任务,勿重复提交"
}
@@ -1,6 +1,6 @@
import Foundation
/// 拍摄任务状态及可选控制流程,始终复用同一任务;禁飞调试仅为本地模拟注入操作服务。
/// 拍摄任务状态及可选控制流程,始终复用同一任务;Release 真实入口与隔离模拟入口按策略注入操作服务。
final class DroneDockShootingTaskViewModel {
/// 页面绑定的账号、景区和门店身份。
let context: DroneDockHomeContext
@@ -62,7 +62,7 @@ final class DroneDockShootingTaskViewModel {
// 回查仍提供的已受理指令分别保留防重锁,避免另一条指令受理覆盖旧锁。
private var pendingAcceptedCommands: Set<DroneDockSafetyCommand> = []
/// 默认只读;仅显式注入模拟操作服务时开放对应动作,当前正式入口不注入。
/// 默认只读;仅显式注入操作服务时开放对应动作,Release 入口按授权注入。
init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder,
service: any DroneDockShootingServing,
startService: (any DroneDockStartShooting)? = nil,
@@ -85,6 +85,18 @@ final class DroneDockShootingTaskViewModel {
await refreshSnapshot(allowWhileStarting: false)
}
/// 后端建议间隔限制为 2~30 秒;缺失或无效时默认 5 秒,从上次请求结束后计时。
var pollIntervalNanoseconds: UInt64 {
let hint = response?.planeStatus?.pollHintMS ?? 5_000
return UInt64(min(max(hint > 0 ? hint : 5_000, 2_000), 30_000)) * 1_000_000
}
/// 身份失效或缺少任务信息时停止安排下一次读取。
var canContinuePolling: Bool {
!identityInvalidated && context.canLoad && taskID > 0
&& DroneDockHomeMetric.usableText(order.orderNumber) != nil
}
@MainActor
private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false,
allowWhileResummoning: Bool = false) async {
@@ -114,6 +126,12 @@ final class DroneDockShootingTaskViewModel {
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
}
@@ -121,6 +139,9 @@ final class DroneDockShootingTaskViewModel {
} catch {
guard accepts(requestGeneration) 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)
])
}
}
@@ -149,7 +170,7 @@ final class DroneDockShootingTaskViewModel {
}
}
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;默认真实页面保持禁用。
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;Debug 真实页面保持禁用。
var canStartShooting: Bool {
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
@@ -161,7 +182,7 @@ final class DroneDockShootingTaskViewModel {
&& (response?.currentPlane?.id ?? 0) > 0
}
/// 提交一次开拍并单次读取同任务;失败保留原快照,不轮询、不重建、不自动重发。
/// 提交一次开拍并单次读取同任务;失败保留原快照,不重建、不自动重发控制请求。
@MainActor
func startShooting(onStateChange: @escaping @MainActor () -> Void = {}) async {
guard canStartShooting, let startService else { return }
@@ -200,6 +221,7 @@ final class DroneDockShootingTaskViewModel {
throw APIError.decodeFailed("开始拍摄回执与当前任务或飞机不一致,请先核对任务状态")
}
startResponse = value
DroneDockDiagnostics.event("start.receipt_accepted", taskID: taskID)
hasSubmittedStart = true
startOutcomeUnknown = false
onStateChange()
@@ -287,6 +309,7 @@ final class DroneDockShootingTaskViewModel {
throw APIError.decodeFailed("安全指令回执与当前任务或指令不一致,请先核对任务状态")
}
commandResponse = value
DroneDockDiagnostics.event("command.receipt_accepted", taskID: taskID)
pendingAcceptedCommands.insert(command)
commandOutcomeUnknown = false
onStateChange()
@@ -363,6 +386,7 @@ final class DroneDockShootingTaskViewModel {
throw APIError.decodeFailed("重新召唤回执与当前任务或订单不一致,请先核对任务状态")
}
resummonResponse = value
DroneDockDiagnostics.event("resummon.receipt_accepted", taskID: taskID)
hasSubmittedResummon = true
resummonOutcomeUnknown = false
awaitingResummonSnapshot = true
@@ -557,6 +581,7 @@ final class DroneDockShootingTaskViewModel {
}
private func markResummonUnknown(reason: String? = nil) {
DroneDockDiagnostics.event("resummon.outcome_unknown", taskID: taskID)
resummonOutcomeUnknown = true
resummonErrorMessage = (reason.map { "\($0)。" } ?? "") + "重新召唤结果待核对,请刷新任务状态,勿重复提交"
}
@@ -575,11 +600,13 @@ final class DroneDockShootingTaskViewModel {
}
private func markCommandUnknown(reason: String? = nil) {
DroneDockDiagnostics.event("command.outcome_unknown", taskID: taskID)
commandOutcomeUnknown = true
commandErrorMessage = (reason.map { "\($0)。" } ?? "") + "安全指令结果待核对,请刷新任务状态,勿重复提交"
}
private func markStartUnknown(reason: String? = nil) {
DroneDockDiagnostics.event("start.outcome_unknown", taskID: taskID)
startOutcomeUnknown = true
startErrorMessage = (reason.map { "\($0)。" } ?? "") + "开始拍摄结果待核对,请刷新任务状态,勿重复提交"
}
@@ -100,18 +100,41 @@ final class ScenicMaterialDownloadService {
/// 检查 HTTP 状态与非空响应文件的空境原片下载器。
struct ScenicMaterialURLSessionDownloader: CloudFileDownloading {
private let session: URLSession
private let logSink: @Sendable (String) -> Void
/// 注入 URLSession 便于使用 URLProtocol 验证状态码及错误响应。
init(session: URLSession = .shared) { self.session = session }
init(session: URLSession = .shared, logSink: @escaping @Sendable (String) -> Void = DroneDockDiagnostics.write) {
self.session = session
self.logSink = logSink
}
/// 下载到唯一临时路径;失败响应及取消下载均清理 URLSession 临时文件。
func downloadFile(remoteURL: String, fileName: String,
onProgress: @escaping @Sendable (Int) -> Void) async throws -> URL {
guard let url = URL(string: remoteURL), ["https", "http"].contains(url.scheme?.lowercased() ?? ""),
url.host != nil else { throw ScenicMaterialDownloadError.invalidURL }
let delegate = ScenicMaterialDownloadProgress(onProgress: onProgress)
let (temporaryURL, response) = try await session.download(from: url, delegate: delegate)
let trace = DroneDockFileTransferTrace(operation: "file_download", method: "GET", remoteURL: url)
logSink(trace.message("request.started"))
let temporaryURL: URL
let response: URLResponse
do {
let delegate = ScenicMaterialDownloadProgress(onProgress: onProgress)
(temporaryURL, response) = try await session.download(from: url, delegate: delegate)
} catch {
let cancelled = error is CancellationError || (error as? URLError)?.code == .cancelled
logSink(trace.message(cancelled ? "request.cancelled" : "request.failed",
fields: DroneDockDiagnostics.errorFields(error)))
throw error
}
defer { try? FileManager.default.removeItem(at: temporaryURL) }
let receivedSize = (try? FileManager.default.attributesOfItem(atPath: temporaryURL.path)[.size] as? NSNumber)?.int64Value ?? 0
logSink(trace.message("response.received", fields: [
"http_status": (response as? HTTPURLResponse)?.statusCode ?? 0,
"response_headers": (response as? HTTPURLResponse)?.allHeaderFields.reduce(into: [String: String]()) {
$0[String(describing: $1.key)] = String(describing: $1.value)
} ?? [:],
"bytes": receivedSize, "content_type": response.mimeType ?? "unknown", "body": "<binary omitted>"
]))
try Task.checkCancellation()
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
throw ScenicMaterialDownloadError.httpFailure((response as? HTTPURLResponse)?.statusCode ?? 0)
@@ -181,6 +181,14 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
/// 首次创建并召唤;成功后进入原任务,再次查看不经过创建或召唤接口。
private func createSelectedTask() {
DroneDockDiagnostics.event("preparation.confirm_tapped", taskID: viewModel.createdTask?.taskID, fields: [
"order_number": viewModel.order.orderNumber as Any? ?? NSNull(),
"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
])
guard !isRefreshing, !isStartingCreation else { return }
if viewModel.canOpenShootingTask {
_ = openShootingTask(automatically: false)
@@ -199,17 +207,29 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
guard let self,
let path = self.dataSource.indexPath(for: .shootResult) ?? self.dataSource.indexPath(for: .creationResult) else { return }
self.collectionView.scrollToItem(at: path, at: .top, animated: true)
self.showFilingFailureIfNeeded()
}
}
}
/// 只在准备页可见且召唤已成功时导航一次;返回后允许主动查看同一任务。
/// 报备问题在明确提交失败后提示一次,后台及设备轮询不会反复弹窗。
private func showFilingFailureIfNeeded() {
guard isPageVisible, isApplicationActive, presentedViewController == nil,
let failure = viewModel.summonFailure ?? viewModel.creationFailure,
failure.requiresFiling else { return }
let alert = UIAlertController(title: failure.title, message: failure.message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "我知道了", style: .default))
present(alert, animated: true)
}
/// 成功后自动导航一次;失败的已结束任务只在用户明确点击时查看原任务。
@discardableResult
private func openShootingTask(automatically: Bool) -> Bool {
guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask,
let taskID = viewModel.createdTask?.taskID,
let navigationController, navigationController.topViewController === self,
!automatically || automaticallyOpenedTaskID != taskID else { return false }
!automatically || (viewModel.shootResponse != nil && automaticallyOpenedTaskID != taskID) else { return false }
DroneDockDiagnostics.event("navigation.open_task", taskID: taskID)
automaticallyOpenedTaskID = taskID
let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context)
navigationController.pushViewController(controller, animated: true)
@@ -284,17 +304,15 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
return cell
case .creationResult:
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
cell.apply(task: self.viewModel.createdTask, errorMessage: self.viewModel.taskCreationErrorMessage,
outcomeUnknown: self.viewModel.taskCreationOutcomeUnknown)
if let failure = self.viewModel.creationFailure {
cell.apply(failure: failure, identifier: "drone.preparation.creationResponse")
}
return cell
case .shootResult:
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
cell.applyShoot(taskID: self.viewModel.createdTask?.taskID,
dataJSON: self.viewModel.shootDataJSON,
errorMessage: self.viewModel.shootErrorMessage,
isLoading: self.viewModel.isSummoning,
hasSucceeded: self.viewModel.shootResponse != nil,
outcomeUnknown: self.viewModel.summonOutcomeUnknown)
if let failure = self.viewModel.summonFailure {
cell.apply(failure: failure, identifier: "drone.preparation.shootResponse")
}
return cell
case .emptyPoints, .emptyRoutes, .status:
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DronePreparationEmptyCell
@@ -344,11 +362,10 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
} else {
snapshot.appendItems([.status], toSection: .status)
}
if viewModel.createdTask != nil || (viewModel.errorMessage == nil && viewModel.projectInfo != nil && viewModel.taskCreationErrorMessage != nil) {
if viewModel.creationFailure != nil {
snapshot.appendItems([.creationResult], toSection: .creationResult)
}
if viewModel.createdTask != nil,
viewModel.isSummoning || viewModel.shootResponse != nil || viewModel.shootErrorMessage != nil {
if viewModel.summonFailure != nil {
snapshot.appendItems([.shootResult], toSection: .shootResult)
}
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
@@ -360,7 +377,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|| previous.itemIdentifiers.contains(.emptyPoints) != snapshot.itemIdentifiers.contains(.emptyPoints)
|| previous.itemIdentifiers.contains(.emptyRoutes) != snapshot.itemIdentifiers.contains(.emptyRoutes)
|| previousRouteCount != snapshot.numberOfItems(inSection: .routes)
if layoutChanged { collectionView.collectionViewLayout.invalidateLayout() }
if layoutChanged || viewModel.projectInfo != nil { collectionView.collectionViewLayout.invalidateLayout() }
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
guard let self else { return }
let kind = UICollectionView.elementKindSectionHeader
@@ -374,21 +391,21 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, _ in
UICollectionViewCompositionalLayout { [weak self] index, environment in
guard let self, let section = Section(rawValue: index) else { return nil }
let height: NSCollectionLayoutDimension
let width: NSCollectionLayoutDimension
switch section {
case .order: height = .estimated(100); width = .fractionalWidth(1)
case .points:
height = .absolute(self.viewModel.spots.isEmpty ? 150 : 64)
width = self.viewModel.spots.isEmpty ? .fractionalWidth(1) : .absolute(160)
height = .absolute(self.viewModel.spots.isEmpty ? 150 : DronePreparationPointCell.preferredHeight(
names: self.viewModel.spots.map(\.name), width: 200))
width = self.viewModel.spots.isEmpty ? .fractionalWidth(1) : .absolute(200)
case .routes:
height = self.viewModel.routes.isEmpty ? .absolute(160) : .estimated(64)
width = .fractionalWidth(1)
case .status: height = .absolute(160); width = .fractionalWidth(1)
case .creationResult: height = .absolute(380); width = .fractionalWidth(1)
case .shootResult: height = .absolute(420); width = .fractionalWidth(1)
case .creationResult, .shootResult: height = .estimated(100); width = .fractionalWidth(1)
}
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
let group = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item])
@@ -402,7 +419,9 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
&& (section == .points || (section == .routes && !self.viewModel.spots.isEmpty))
if showsHeading {
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(section == .points ? 46 : 64)),
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(section == .points ? 46 : DronePreparationHeadingView.preferredHeight(
title: self.viewModel.selectedSpot.map { "\($0.name)的航线" } ?? "拍摄航线",
detail: "共 \(self.viewModel.routes.count) 条", width: environment.container.effectiveContentSize.width - 32))),
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)]
}
return layout
@@ -3,7 +3,7 @@ import UIKit
/// 组装真实拍摄任务页;构造时不发请求,页面出现后才读取同一任务。
@MainActor
enum DroneDockShootingTaskEntry {
/// 使用已有任务读取状态,Release 可手动图传;不注入任务创建或飞控服务。
/// 使用已有任务读取状态;Release 注入已授权的真实控制,Debug 保持只读。
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext) -> UIViewController {
let client = NetworkServices.shared.apiClient
@@ -14,7 +14,10 @@ enum DroneDockShootingTaskEntry {
currentContext: { DroneDockHomeViewController.currentContext() })
return DroneDockShootingTaskViewController(viewModel: DroneDockShootingTaskViewModel(
context: context, taskID: taskID, order: order,
service: DroneDockShootingAPI(client: NetworkServices.shared.apiClient),
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),
currentContext: { DroneDockHomeViewController.currentContext() }
), liveViewModel: live)
}
@@ -1,7 +1,7 @@
import SnapKit
import UIKit
/// 拍摄任务页:正式入口读取状态并手动开启图传,飞控仅在隔离模拟入口注入。
/// 拍摄任务页:前台轮询状态、手动图传;Release 开放已授权控制,Debug 仅模拟控制。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
@@ -23,6 +23,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private var bottomInset: CGFloat = -1
private let materialsControllerFactory: @MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private let simulationRecordsProvider: (@MainActor () -> String)?
private let shootingPollDelay: @Sendable (UInt64) async throws -> Void
private var pollTask: Task<Void, Never>?
private var pollGeneration = 0
private var refreshTask: Task<Void, Never>?
private var startTask: Task<Void, Never>?
private var commandTask: Task<Void, Never>?
@@ -41,12 +44,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
init(viewModel: DroneDockShootingTaskViewModel,
liveViewModel: DroneDockLiveViewModel? = nil,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
simulationRecordsProvider: (@MainActor () -> String)? = nil) {
simulationRecordsProvider: (@MainActor () -> String)? = nil,
shootingPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
self.viewModel = viewModel
self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel(
context: viewModel.context, taskID: viewModel.taskID,
currentContext: { DroneDockHomeViewController.currentContext() })
self.simulationRecordsProvider = simulationRecordsProvider
self.shootingPollDelay = shootingPollDelay
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
context: context, order: order,
@@ -61,6 +66,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
deinit {
pollTask?.cancel()
refreshTask?.cancel()
startTask?.cancel()
commandTask?.cancel()
@@ -186,10 +192,11 @@ final class DroneDockShootingTaskViewController: BaseViewController {
name: UIApplication.didBecomeActiveNotification, object: nil)
}
/// 每次完整进入任务页只查询一次,不定时重读同一任务。
/// 完整进入任务页立即读取,随后仅在前台可见时轮询同一任务。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isPageVisible = true
logEvent("page.appeared")
isApplicationActive = UIApplication.shared.applicationState == .active
refreshTaskIfVisible()
refreshLiveIfVisible(automatically: true)
@@ -199,6 +206,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
logEvent("page.disappeared")
cancelRefresh()
stopLive()
}
@@ -227,6 +235,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
private func primaryActionTriggered() {
logEvent("action.primary", fields: ["action": String(describing: viewModel.presentation.action),
"enabled": viewModel.presentation.isActionEnabled])
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand,
@@ -265,12 +275,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
present(alert, animated: true)
}
/// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。
private func refreshTaskIfVisible() {
/// 前台可见时串行读取;轮询失败保留旧快照,下个周期再读,不重复弹出提示。
private func refreshTaskIfVisible(isPolling: Bool = false) {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand,
!isResummoningAction, !viewModel.isResummoning else { return }
cancelScheduledPoll()
logEvent("shooting.refresh", fields: ["trigger": isPolling ? "poll" : "page_or_manual", "live_battery": 0])
requestGeneration &+= 1
let generation = requestGeneration
isRequesting = true
@@ -283,13 +295,39 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.refreshTask = nil
self.isRequesting = false
self.applySnapshot()
if self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.scheduleNextPoll()
if !isPolling, self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.showToast("刷新失败,当前显示上次数据:\(error)")
}
}
}
/// 每次读取或控制流程结束后仅安排一个可取消的延时,不持有页面等待计时结束。
private func scheduleNextPoll() {
cancelScheduledPoll()
guard isPageVisible, isApplicationActive, viewModel.canContinuePolling,
!isRequesting, !isStartingAction, !isSendingSafetyAction, !isResummoningAction else { return }
let generation = pollGeneration
let delay = shootingPollDelay
let interval = viewModel.pollIntervalNanoseconds
logEvent("poll.scheduled", fields: ["delay_ms": interval / 1_000_000])
pollTask = Task { @MainActor [weak self] in
do { try await delay(interval) } catch { return }
guard !Task.isCancelled, let self, self.pollGeneration == generation else { return }
self.pollTask = nil
self.refreshTaskIfVisible(isPolling: true)
}
}
private func cancelScheduledPoll() {
if pollTask != nil { logEvent("poll.cancelled") }
pollGeneration &+= 1
pollTask?.cancel()
pollTask = nil
}
private func cancelRefresh() {
cancelScheduledPoll()
requestGeneration &+= 1
refreshTask?.cancel()
refreshTask = nil
@@ -310,6 +348,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。
private func startShootingIfAllowed() {
guard !isStartingAction, !isSendingSafetyAction, !isResummoningAction, viewModel.canStartShooting else { return }
cancelScheduledPoll()
requestGeneration &+= 1
let generation = requestGeneration
isStartingAction = true
@@ -322,6 +361,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.startTask = nil
self.isStartingAction = false
self.applySnapshot()
self.scheduleNextPoll()
if let error = self.viewModel.startErrorMessage {
self.showToast(error)
} else if let error = self.viewModel.errorMessage {
@@ -330,11 +370,12 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
}
/// 重召唤只在显式模拟入口开放;点击后锁定按钮,使用原任务 ID,并由状态回查更新页面。
/// 重召唤使用原任务 ID,回执后再查询状态,避免从受理结果推断设备已到达。
private func resummonIfAllowed() {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
guard allowsControlActions, isPageVisible, isApplicationActive,
!isResummoningAction, !isStartingAction, !isSendingSafetyAction,
!isRequesting, viewModel.canResummon else { return }
cancelScheduledPoll()
requestGeneration &+= 1
let generation = requestGeneration
isResummoningAction = true
@@ -347,12 +388,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.resummonTask = nil
self.isResummoningAction = false
self.applySnapshot()
self.scheduleNextPoll()
if let error = self.viewModel.resummonErrorMessage {
self.showToast(error)
} else if self.viewModel.hasSubmittedResummon, let error = self.viewModel.errorMessage {
self.showToast("模拟重召唤已受理,状态刷新失败:\(error)")
self.showToast("重召唤已受理,状态刷新失败:\(error)")
} else if self.viewModel.hasSubmittedResummon {
self.showToast("本地模拟重召唤已受理,未发送设备指令")
self.showToast(self.simulationRecordsProvider != nil
? "本地模拟重召唤已受理,未发送设备指令" : "重召唤请求已受理,请等待任务状态更新")
} else if let error = self.viewModel.errorMessage {
self.showToast(error)
}
@@ -363,6 +406,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func refreshLiveIfVisible(automatically: Bool = false) {
guard !automatically || liveViewModel.loadsAutomatically else { return }
guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return }
logEvent("live.request", fields: ["automatic": automatically])
liveGeneration &+= 1
let generation = liveGeneration
liveTask = Task { @MainActor [weak self] in
@@ -385,16 +429,20 @@ final class DroneDockShootingTaskViewController: BaseViewController {
feedPlaceholder.apply(liveViewModel)
}
/// 仅模拟入口响应安全按钮;返航会中断任务,先明确展示其含义再提交一次。
/// 返航会中断任务,先明确展示其含义再提交一次;Debug 只开放隔离模拟入口。
private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
logEvent("action.safety", fields: ["command": command.rawValue, "enabled": viewModel.canSendCommand(command)])
guard allowsControlActions, isPageVisible, isApplicationActive,
presentedViewController == nil, !isSendingSafetyAction, !isStartingAction,
!isResummoningAction, !isRequesting, viewModel.canSendCommand(command) else { return }
if command == .returnHome {
let alert = UIAlertController(title: "立即返航(本地模拟)",
message: "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。", preferredStyle: .alert)
let simulated = simulationRecordsProvider != nil
let alert = UIAlertController(title: simulated ? "立即返航(本地模拟)" : "立即返航",
message: simulated
? "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。"
: "返航会中断本次任务。取消返航也不会恢复已经中断的任务。确定立即返航?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "模拟返航", style: .destructive) { [weak self] _ in
alert.addAction(UIAlertAction(title: simulated ? "模拟返航" : "立即返航", style: .destructive) { [weak self] _ in
self?.sendSafetyCommand(command)
})
present(alert, animated: true)
@@ -405,9 +453,10 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 同步锁覆盖异步调度间隙;界面保留旧快照,只有同任务回查成功才更新阶段。
private func sendSafetyCommand(_ command: DroneDockSafetyCommand) {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
guard allowsControlActions, isPageVisible, isApplicationActive,
!isSendingSafetyAction, !isStartingAction, !isResummoningAction, !isRequesting,
viewModel.canSendCommand(command) else { return }
cancelScheduledPoll()
requestGeneration &+= 1
let generation = requestGeneration
isSendingSafetyAction = true
@@ -420,12 +469,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.commandTask = nil
self.isSendingSafetyAction = false
self.applySnapshot()
self.scheduleNextPoll()
if let error = self.viewModel.commandErrorMessage {
self.showToast(error)
} else if let error = self.viewModel.errorMessage {
self.showToast("模拟指令已受理,状态刷新失败:\(error)")
self.showToast("指令已受理,状态刷新失败:\(error)")
} else {
self.showToast("本地模拟指令已受理,未发送设备指令")
self.showToast(self.simulationRecordsProvider != nil
? "本地模拟指令已受理,未发送设备指令" : "指令已受理,请等待任务状态更新")
}
}
}
@@ -445,6 +496,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
@objc private func applicationWillResignActive() {
logEvent("app.inactive")
isApplicationActive = false
cancelRefresh()
stopLive()
@@ -453,9 +505,22 @@ final class DroneDockShootingTaskViewController: BaseViewController {
@objc private func applicationDidBecomeActive() {
guard !isApplicationActive else { return }
isApplicationActive = true
logEvent("app.active")
refreshTaskIfVisible()
refreshLiveIfVisible(automatically: true)
}
private func logEvent(_ name: String, fields: [String: Any] = [:]) {
var fields = fields
fields["source"] = simulationRecordsProvider == nil ? "task_page" : "local_simulation"
fields["scenic_id"] = viewModel.context.scenicID
fields["order_number"] = viewModel.order.orderNumber
DroneDockDiagnostics.event(name, taskID: viewModel.taskID, fields: fields)
}
private var allowsControlActions: Bool {
simulationRecordsProvider != nil || !DeviceCommandDebugPolicy.blocksFlightRequests
}
}
/// 以可选择的 JSON 文本展示本地模拟请求与回执,避免与真实接口联调混淆。
@@ -555,10 +620,11 @@ private final class DroneDockTaskSafetyView: UIView {
/// 保持两列固定布局,暂停/继续与返航/取消由快照中的指令白名单决定。
func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool) {
let commands = model.availableSafetyCommands
let allowsControls = isSimulation || !DeviceCommandDebugPolicy.blocksFlightRequests
pauseCommand = commands.contains(.resume) ? .resume : .pause
returnCommand = commands.contains(.cancelReturn) ? .cancelReturn : .returnHome
header.text = model.commandOutcomeUnknown ? "安全控制 · 结果待核对"
: model.isSendingCommand ? "安全控制 · 本地模拟发送中"
: model.isSendingCommand ? (isSimulation ? "安全控制 · 本地模拟发送中" : "安全控制 · 指令发送中")
: isSimulation ? "安全控制 · 本地模拟,不发送设备指令" : "安全控制"
for (button, command) in [(pauseButton, pauseCommand), (returnButton, returnCommand)] {
let title: String
@@ -569,10 +635,10 @@ private final class DroneDockTaskSafetyView: UIView {
case .returnHome: title = "立即返航"; subtitle = "中断任务"
case .cancelReturn: title = "取消返航"; subtitle = "不恢复已中断任务"
}
let enabled = isSimulation && isInteractive && model.canSendCommand(command)
let detail = model.activeCommand == command ? "本地模拟发送中…"
let enabled = allowsControls && isInteractive && model.canSendCommand(command)
let detail = model.activeCommand == command ? (isSimulation ? "本地模拟发送中…" : "指令发送中…")
: model.commandOutcomeUnknown ? "结果待核对"
: !isSimulation || !commands.contains(command) ? "暂不可用" : subtitle
: !allowsControls || !commands.contains(command) ? "暂不可用" : subtitle
button.apply(title: title, subtitle: detail, enabled: enabled)
button.setControlSymbol(command == .resume ? "play.circle" : command == .pause ? "pause.circle"
: command == .cancelReturn ? "xmark.circle" : "arrow.uturn.backward")
@@ -1,12 +1,11 @@
import SnapKit
import UIKit
/// 在准备页展示任务创建或召唤请求的回执,保留 data 原文结构并支持滚动与选择文本。
/// 准备页业务失败卡片,完整换行展示原因,不展示成功回执或接口 JSON。
@MainActor
final class DroneDockTaskCreationResultCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 16, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let responseView = UITextView()
private let detailLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
@@ -14,23 +13,13 @@ final class DroneDockTaskCreationResultCell: UICollectionViewCell {
contentView.layer.cornerRadius = 10
titleLabel.numberOfLines = 0
detailLabel.numberOfLines = 0
responseView.backgroundColor = .clear
responseView.isEditable = false
responseView.isSelectable = true
responseView.alwaysBounceVertical = true
responseView.textContainerInset = .zero
responseView.textContainer.lineFragmentPadding = 0
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
[titleLabel, detailLabel, responseView].forEach(contentView.addSubview)
titleLabel.textColor = DroneDockStyle.warning
[titleLabel, detailLabel].forEach(contentView.addSubview)
titleLabel.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview().inset(12)
}
detailLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(6)
make.leading.trailing.equalTo(titleLabel)
}
responseView.snp.makeConstraints { make in
make.top.equalTo(detailLabel.snp.bottom).offset(12)
make.top.equalTo(titleLabel.snp.bottom).offset(8)
make.leading.trailing.equalTo(titleLabel)
make.bottom.equalToSuperview().inset(12)
}
@@ -39,42 +28,10 @@ final class DroneDockTaskCreationResultCell: UICollectionViewCell {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 成功保留完整 data,失败显示真实错误,不构造任务 ID 或成功响应。
func apply(task: DroneDockCreatedTask?, errorMessage: String?, outcomeUnknown: Bool) {
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
if let task {
titleLabel.text = "任务已创建 · ID \(task.taskID)"
titleLabel.textColor = DroneDockStyle.success
detailLabel.text = "tasks/create 返回的 data"
responseView.font = .monospacedSystemFont(ofSize: 12, weight: .regular)
if responseView.text != task.dataJSON { responseView.text = task.dataJSON }
} else {
titleLabel.text = outcomeUnknown ? "任务创建结果待确认" : "任务创建未成功"
titleLabel.textColor = DroneDockStyle.warning
detailLabel.text = outcomeUnknown ? "请先核对订单任务,避免重复创建" : "接口返回的错误信息"
responseView.font = .systemFont(ofSize: 14)
responseView.text = errorMessage
}
responseView.textColor = DroneDockStyle.text
}
/// 展示 shoot 回执;提交成功不代表无人机已到达,结果未知不能引导直接重发。
func applyShoot(taskID: Int?, dataJSON: String?, errorMessage: String?, isLoading: Bool,
hasSucceeded: Bool, outcomeUnknown: Bool) {
responseView.accessibilityIdentifier = "drone.preparation.shootResponse"
let suffix = taskID.map { " · ID \($0)" } ?? ""
let title: String
if isLoading { title = "正在召唤无人机" }
else if hasSucceeded { title = "召唤请求已提交" }
else { title = outcomeUnknown ? "召唤结果待核对" : "召唤请求未成功" }
titleLabel.text = title + suffix
titleLabel.textColor = hasSucceeded ? DroneDockStyle.success : errorMessage == nil ? DroneDockStyle.text : DroneDockStyle.warning
if isLoading { detailLabel.text = "正在为已创建的任务提交召唤请求" }
else if hasSucceeded { detailLabel.text = "shoot 返回信息;飞行进度以任务状态为准" }
else { detailLabel.text = outcomeUnknown ? "请先核对任务状态,避免重复发送召唤" : "任务已保留,可重试召唤" }
responseView.font = dataJSON == nil ? .systemFont(ofSize: 14) : .monospacedSystemFont(ofSize: 12, weight: .regular)
let text = dataJSON ?? errorMessage ?? (hasSucceeded ? "接口已返回业务成功,未提供可展示的 data。" : "")
if responseView.text != text { responseView.text = text }
responseView.textColor = DroneDockStyle.text
/// 只接收面向用户的错误模型,成功 data 不进入视图层。
func apply(failure: DroneDockPreparationFailure, identifier: String) {
titleLabel.text = failure.title
detailLabel.text = failure.message
detailLabel.accessibilityIdentifier = identifier
}
}
@@ -58,7 +58,9 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
roomConfig.isAutoSubscribeVideo = false
let user = ByteRTCUserInfo()
user.userId = configuration.userID
DroneDockDiagnostics.event("rtc.join_requested", fields: ["engine_session": generation.uuidString])
let result = room.joinRoom(configuration.token, userInfo: user, userVisibility: false, roomConfig: roomConfig)
DroneDockDiagnostics.event("rtc.join_returned", fields: ["engine_session": generation.uuidString, "code": result])
guard result == 0 else {
onEvent(.failed("图传进房失败(\(result))")); stop(); return
}
@@ -93,6 +95,8 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
}
private func receive(_ event: DroneDockVolcEvent, roomID: String) {
// 不把 SDK 回调对象、房间 ID、用户 ID 或 extraInfo 原样写入日志。
DroneDockDiagnostics.event("rtc.callback", fields: ["engine_session": generation.uuidString, "result": event.diagnosticValue])
switch event {
case .published(let id, let sourceRoom, let index, let published):
guard sourceRoom == roomID, index == 0 else { return }
@@ -107,6 +111,8 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
canvas.renderMode = .fit
let renderResult = engine?.setRemoteVideoCanvas(id, withCanvas: canvas)
let subscribeResult = room?.subscribeStreamVideo(id, subscribe: true)
DroneDockDiagnostics.event("rtc.subscribe_returned", fields: ["engine_session": generation.uuidString,
"render_code": renderResult as Any? ?? NSNull(), "subscribe_code": subscribeResult as Any? ?? NSNull()])
if renderResult != 0 || subscribeResult != 0 { onEvent?(.failed("图传订阅失败,请重试")) }
case .frame(let id):
guard streamID == id else { return }
@@ -114,6 +120,7 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
onEvent?(.firstFrame)
case .failed(let code): onEvent?(.failed("图传连接失败(\(code)),请重试"))
case .expired: onEvent?(.expired)
case .roomState: break
}
}
}
@@ -124,6 +131,18 @@ private enum DroneDockVolcEvent: Sendable {
case frame(String)
case failed(Int)
case expired
case roomState(Int)
/// 仅输出事件种类及错误码,不含 SDK 身份和凭证。
var diagnosticValue: String {
switch self {
case .published(_, _, let index, let published): return "published(index=\(index),published=\(published))"
case .frame: return "first_frame"
case .failed(let code): return "failed(code=\(code))"
case .expired: return "expired"
case .roomState(let code): return "room_state(code=\(code))"
}
}
}
/// SDK 回调桥接;所有 UI 与引擎操作由上层切回主 Actor 后执行。
@@ -138,6 +157,7 @@ private final class DroneDockVolcDelegate: NSObject, ByteRTCEngineDelegate, Byte
func rtcRoom(_ rtcRoom: ByteRTCRoom, onRoomStateChanged roomId: String, withUid uid: String,
state: Int, extraInfo: String) {
emit(.roomState(state))
if state != 0 { emit(.failed(state)) }
}
@@ -108,21 +108,24 @@ final class DronePreparationPointCell: UICollectionViewCell {
thumbnail.backgroundColor = DroneDockStyle.background
thumbnail.layer.cornerRadius = 5
thumbnail.clipsToBounds = true
[thumbnail, nameLabel, countLabel].forEach(contentView.addSubview)
nameLabel.numberOfLines = 0
nameLabel.lineBreakMode = .byWordWrapping
nameLabel.accessibilityIdentifier = "drone.preparation.point.name"
let labels = UIStackView(arrangedSubviews: [nameLabel, countLabel])
labels.axis = .vertical
labels.spacing = 6
[thumbnail, labels].forEach(contentView.addSubview)
thumbnail.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(8)
make.centerY.equalToSuperview()
make.size.equalTo(48)
}
nameLabel.snp.makeConstraints { make in
make.bottom.equalTo(contentView.snp.centerY).offset(-3)
labels.snp.makeConstraints { make in
make.centerY.equalToSuperview()
make.top.greaterThanOrEqualToSuperview().offset(8)
make.bottom.lessThanOrEqualToSuperview().inset(8)
make.leading.equalTo(thumbnail.snp.trailing).offset(8)
make.trailing.equalToSuperview().inset(6)
}
countLabel.snp.makeConstraints { make in
make.top.equalTo(contentView.snp.centerY).offset(3)
make.leading.equalTo(nameLabel)
make.trailing.equalToSuperview().inset(5)
make.trailing.equalToSuperview().inset(8)
}
isAccessibilityElement = true
}
@@ -130,6 +133,18 @@ final class DronePreparationPointCell: UICollectionViewCell {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 横向同组卡片采用最长名称所需的高度,名称完整换行且不压缩字号。
static func preferredHeight(names: [String], width: CGFloat) -> CGFloat {
let label = DroneDockStyle.label(size: 13, weight: .semibold)
label.numberOfLines = 0
let nameWidth = max(1, width - 72)
let nameHeight = names.map { name -> CGFloat in
label.text = name
return label.sizeThatFits(CGSize(width: nameWidth, height: .greatestFiniteMagnitude)).height
}.max() ?? 0
return max(64, ceil(nameHeight) + 6 + ceil(UIFont.systemFont(ofSize: 11).lineHeight) + 16)
}
/// 展示点位名称与次数,已拍摄的点位仍保持可选择。
func apply(point: DroneShootingPoint, selected: Bool) {
thumbnail.kf.cancelDownloadTask()
@@ -145,7 +160,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
accessibilityIdentifier = "drone.preparation.point.\(point.id)"
}
/// 展示已购点位与可用性;点位已拍次数缺失时保持未知占位。
/// 展示已购点位与可用性;无拍摄记录时显示“未拍摄”。
func apply(spot: DroneDockPurchasedSpot, selected: Bool) {
nameLabel.text = spot.name
thumbnail.kf.cancelDownloadTask()
@@ -160,7 +175,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
if spot.available != true {
countLabel.text = spot.available == false ? "拍摄点不可用" : "可用性待确认"
} else {
countLabel.text = "已拍摄 — 次"
countLabel.text = "未拍摄"
}
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.07) : .white
contentView.layer.borderColor = (selected ? DroneDockStyle.primary : DroneDockStyle.border).cgColor
@@ -331,13 +346,16 @@ final class DronePreparationHeadingView: UICollectionReusableView {
stack.axis = .horizontal
stack.alignment = .firstBaseline
stack.spacing = 12
titleLabel.numberOfLines = 0
titleLabel.accessibilityIdentifier = "drone.preparation.heading.title"
addSubview(stack)
stack.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(4)
make.trailing.equalToSuperview()
make.centerY.equalToSuperview().offset(3)
}
titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
detailLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
accessibilityTraits = .header
isAccessibilityElement = true
}
@@ -352,6 +370,16 @@ final class DronePreparationHeadingView: UICollectionReusableView {
detailLabel.isHidden = detail == nil
accessibilityLabel = [title, detail].compactMap { $0 }.joined(separator: ",")
}
/// 为长点位名称预留完整标题高度,右侧航线数量保持可见。
static func preferredHeight(title: String, detail: String, width: CGFloat) -> CGFloat {
let label = DroneDockStyle.label(size: 18, weight: .semibold)
label.numberOfLines = 0
label.text = title
let detailWidth = (detail as NSString).size(withAttributes: [.font: UIFont.systemFont(ofSize: 13)]).width
let titleWidth = max(1, width - 4 - ceil(detailWidth) - 24)
return max(64, ceil(label.sizeThatFits(CGSize(width: titleWidth, height: .greatestFiniteMagnitude)).height) + 26)
}
}
/// 无点位或无航线时保留就地提示,不增加额外的选择弹窗。