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

This commit is contained in:
2026-11-03 09:06:38 +08:00
parent 687088326c
commit 980d16da9b
27 changed files with 1790 additions and 64 deletions
+4 -4
View File
@@ -430,7 +430,7 @@ final class APIClient {
}
let method = request.httpMethod ?? "REQUEST"
let url = request.url?.absoluteString ?? "<invalid url>"
var lines = ["[API][Request] \(method) \(url)"]
var lines = ["\(APIConsoleFormat.prefix("Request", path: request.url?.path ?? "")) \(method) \(url)"]
if let headers = request.allHTTPHeaderFields, !headers.isEmpty {
lines.append("headers: " + DroneDockDiagnostics.json(headers))
}
@@ -469,7 +469,7 @@ final class APIClient {
let headers = (response as? HTTPURLResponse)?.allHeaderFields.reduce(into: [String: String]()) {
$0[String(describing: $1.key)] = String(describing: $1.value)
} ?? [:]
debugLogSink("[API][Response] \(method) \(url) status=\(statusCode)\nheaders: \(DroneDockDiagnostics.json(headers))\n\(body)")
debugLogSink("\(APIConsoleFormat.prefix("Response", path: request.url?.path ?? "")) \(method) \(url) status=\(statusCode)\nheaders: \(DroneDockDiagnostics.json(headers))\n\(body)")
}
/// Debug/Release 均记录取消,取消不记作成功响应或网络失败。
@@ -480,7 +480,7 @@ final class APIClient {
}
let method = request.httpMethod ?? "REQUEST"
let url = request.url?.absoluteString ?? "<invalid url>"
debugLogSink("[API][Cancelled] \(method) \(url) reason=\(reason)")
debugLogSink("\(APIConsoleFormat.prefix("Cancelled", path: request.url?.path ?? "")) \(method) \(url) reason=\(reason)")
}
/// 所有业务模块均记录传输、业务拒绝或解码失败;保留显式模块日志策略。
@@ -490,7 +490,7 @@ final class APIClient {
debugLogSink(APIRedactedLog.event("Failure", for: request, category: category)
+ " error=\(error.domain)(\(error.code))")
} else {
debugLogSink("[API][Failure] \(request.httpMethod ?? "REQUEST") \(request.url?.absoluteString ?? "<invalid url>")"
debugLogSink("\(APIConsoleFormat.prefix("Failure", path: request.url?.path ?? "")) \(request.httpMethod ?? "REQUEST") \(request.url?.absoluteString ?? "<invalid url>")"
+ " error=\(error.domain)(\(error.code)) message=\(error.localizedDescription)")
}
}
@@ -9,9 +9,8 @@ enum APIConsoleDiagnostics {
/// 不依赖调试构建或 stdout;复用 UTF-8 分段规则,避免长 JSON 被系统截断。
static func write(_ message: String) {
let entry = String(UUID().uuidString.prefix(8))
let chunks = DroneDockDiagnostics.chunks(message)
for (index, chunk) in chunks.enumerated() {
let line = "[API] session=\(sessionID) entry=\(entry) part=\(index + 1)/\(chunks.count) \(chunk)"
for line in APIConsoleFormat.lines(message, sessionID: sessionID, entryID: entry,
fallbackModule: "通用接口") {
logger.notice("\(line, privacy: .public)")
}
}
@@ -0,0 +1,102 @@
import Foundation
/// 控制台统一使用中文业务模块标签;只格式化输出,不修改请求和响应内容。
enum APIConsoleFormat {
/// 根据接口路径匹配业务模块;共享接口按自身职责命名,未知接口保留通用标签。
static func module(for path: String) -> String {
let routes: [(String, String)] = [
("/api/app/airport", "机巢工作台"),
("/api/app/order-flight-task", "机巢工作台"),
("/api/yf-handset-app/photog/multi-plane", "机巢工作台"),
("/api/app/scenic-media", "景区空境库"),
("/api/app/config/get-sts-token", "文件上传"),
("/api/app/scenic-queue", "景区排队"),
("/api/app/socket-token", "消息连接"),
("/api/app/manual-live", "直播"),
("/api/app/view-album", "直播素材"),
("/api/app/media-album", "样片管理"),
("/api/app/msg", "消息中心"),
("/api/app/user/register-jpush-id", "消息推送"),
("/api/app/training", "培训"),
("/api/app/store/order", "订单"),
("/api/app/scenic-admin/order", "订单"),
("/api/app/store/analyse", "数据统计"),
("/api/app/scenic-admin/analyse", "数据统计"),
("/api/app/store", "门店"),
("/api/app/v9", "账号登录"),
("/api/yf-handset-app/account-deregister", "账号注销"),
("/api/yf-handset-app/photog/order", "订单"),
("/api/yf-handset-app/photog/task", "拍摄任务"),
("/api/yf-handset-app/photog/analyse", "数据统计"),
("/api/yf-handset-app/photog/cloud-driver", "云存储"),
("/api/yf-handset-app/photog/travel-album", "旅拍相册"),
("/api/yf-handset-app/photog/wallet", "钱包"),
("/api/yf-handset-app/photog/point", "积分"),
("/api/yf-handset-app/photog/scenic-spot", "打卡点"),
("/api/yf-handset-app/photog/scenic", "景区"),
("/api/yf-handset-app/photog/scenic-apply", "景区入驻"),
("/api/yf-handset-app/photog/role-apply", "角色申请"),
("/api/yf-handset-app/photog/loacation", "位置上报"),
("/api/yf-handset-app/photog/report", "摄影师举报"),
("/api/yf-handset-app/photog/sale-user", "销售员"),
("/api/yf-handset-app/photog/cooperative-salers", "销售员"),
("/api/yf-handset-app/photog/invite", "邀请"),
("/api/yf-handset-app/photog/invite-info", "邀请"),
("/api/yf-handset-app/photog/project", "套餐"),
("/api/yf-handset-app/photog/offline-pay-collect", "线下收款"),
("/api/yf-handset-app/photog/pay-code", "收款"),
("/api/yf-handset-app/photog/pay-page-config", "收款"),
("/api/yf-handset-app/photog/real-name", "实名认证"),
("/api/yf-handset-app/photog/profile", "个人资料"),
("/api/yf-handset-app/photog/schedule", "个人资料"),
("/api/yf-handset-app/photog/userinfo-update-avatar", "个人资料"),
("/api/yf-handset-app/userinfo", "个人资料"),
("/api/yf-handset-app/userinfo-update", "个人资料"),
("/api/yf-handset-app/userinfo-update-avatar-url", "个人资料"),
("/api/yf-handset-app/role-permission", "账号权限"),
("/api/app/config", "系统配置"),
("/api/app/latest-version", "版本更新")
]
return routes.first { path == $0.0 || path.hasPrefix($0.0 + "/") }?.1 ?? "通用接口"
}
/// 请求、响应以及明确失败/取消使用同一标签结构,模块可由调用方显式指定。
static func prefix(_ event: String, path: String, category: String? = nil) -> String {
"【\(category ?? module(for: path))-\(event)】"
}
/// 为每个完整分段重复添加模块标签,保留正文、会话、事件 ID 及分段顺序。
static func lines(_ message: String, sessionID: String, entryID: String,
fallbackModule: String) -> [String] {
let tag: String
let body: String
if message.hasPrefix("【"), let end = message.firstIndex(of: "】") {
tag = String(message[...end])
let remainder = message[message.index(after: end)...]
body = remainder.hasPrefix(" ") ? String(remainder.dropFirst()) : String(remainder)
} else if let fields = try? JSONSerialization.jsonObject(with: Data(message.utf8)) as? [String: Any] {
let event = fields["event"] as? String ?? ""
let module: String
if event.hasPrefix("file_download.") { module = "素材下载" }
else if event.hasPrefix("file_upload.") { module = "成片上传" }
else if let path = fields["path"] as? String { module = Self.module(for: path) }
else { module = fallbackModule }
let kind: String
if event.hasSuffix("request.started") { kind = "Request" }
else if event.hasSuffix("response.received") { kind = "Response" }
else if event.hasSuffix("request.cancelled") { kind = "Cancelled" }
else if event.hasSuffix("request.failed") || event.hasSuffix("response.rejected") { kind = "Failure" }
else if event.hasSuffix("request.blocked") { kind = "Blocked" }
else { kind = "Event" }
tag = "【\(module)-\(kind)】"
body = message
} else {
tag = "【\(fallbackModule)-Event】"
body = message
}
let chunks = DroneDockDiagnostics.chunks(body)
return chunks.enumerated().map { index, chunk in
"\(tag) session=\(sessionID) entry=\(entryID) part=\(index + 1)/\(chunks.count) \(chunk)"
}
}
}
@@ -31,7 +31,7 @@ nonisolated enum APIRedactedLog {
/// 生成请求、响应、失败和取消共用的模块标签与安全地址。
static func event(_ event: String, for request: URLRequest, category: String) -> String {
let url = request.url.map { redactedURL($0, keepsQuery: true) } ?? "<invalid url>"
return "[API][\(category)][\(event)] \(request.httpMethod ?? "REQUEST") \(url)"
return "\(APIConsoleFormat.prefix(event, path: request.url?.path ?? "", category: category)) \(request.httpMethod ?? "REQUEST") \(url)"
}
/// 非 JSON 正文可能包含凭证或服务端调试页面,不把原始文本写入控制台。
@@ -9,9 +9,8 @@ enum DroneDockDiagnostics {
/// 按 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)"
for line in APIConsoleFormat.lines(message, sessionID: sessionID, entryID: entry,
fallbackModule: "机巢工作台") {
logger.notice("\(line, privacy: .public)")
}
}
@@ -0,0 +1,33 @@
import Foundation
/// 拍摄任务订阅票据,与 App 登录 token 分开管理。
struct DroneDockSocketTicket: Decodable, Sendable {
/// 仅在 310 业务订阅中传递,不放入 WebSocket 握手 Header。
let socketToken: String
/// 后端票据有效期;每次重新连接均重新取票,不复用过期票据。
let expireSeconds: Int?
private enum CodingKeys: String, CodingKey {
case socketToken = "socket_token", expireSeconds = "expire_seconds"
}
}
/// 隔离票据获取,模拟测试无需登录或连接真实服务器。
protocol DroneDockSocketTicketServing: Sendable {
/// 使用当前 App 登录身份获取只读订阅票据。
@MainActor func socketTicket() async throws -> DroneDockSocketTicket
}
/// 复用公共 socket-token 接口的鉴权及请求日志。
@MainActor
final class DroneDockSocketTokenAPI: DroneDockSocketTicketServing {
private let client: APIClient
/// 注入与 shooting 相同环境的客户端。
init(client: APIClient) { self.client = client }
/// 不调用任何创建、飞控或图传接口。
func socketTicket() async throws -> DroneDockSocketTicket {
try await client.send(APIRequest(method: .get, path: "/api/app/socket-token"))
}
}
@@ -38,6 +38,24 @@ struct DroneDockPurchasedSpot: Decodable, Equatable, Sendable {
/// 购买范围内的航线,按服务端顺序展示。
let airLines: [DroneDockPurchasedAirLine]
/// 卡片优先使用点位封面,缺失或无效时取本点位已购航线的第一张有效样片封面。
var displayCoverURL: URL? {
if let url = Self.imageURL(coverURL) { return url }
for route in airLines {
for sample in route.samples {
if let url = Self.imageURL(sample.coverURL) { return url }
}
}
return nil
}
private static func imageURL(_ value: String?) -> URL? {
guard let text = DroneDockHomeMetric.usableText(value), let url = URL(string: text),
let scheme = url.scheme?.lowercased(), ["https", "http"].contains(scheme),
let host = url.host, !host.isEmpty else { return nil }
return url
}
/// 张工购买点位字段,不接收 workbench 的 name 作为替代。
private enum CodingKeys: String, CodingKey {
case id = "scenic_spot_id", name = "scenic_spot_name", available
@@ -2,6 +2,20 @@ import Foundation
/// 朱工 shooting 的只读快照;完整 data 用于展示,不表示已召唤或已开始拍摄。
struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
/// HTTP/推送共用的顶层任务身份。
let orderFlightTaskID: Int?
/// 同一执行批次下递增的完整快照版本。
let stateVersion: Int64?
/// 当前航线执行批次,先比较批次再比较版本,防止重召唤后的旧数据回退。
let executionBatch: Int64?
/// 第一版只接收 full 完整推送。
let snapshotKind: String?
/// 后端状态写入时间,不能作为设备读数采集时间。
let stateUpdatedAt: String?
/// 设备读数采集时间,用于显示来源和核对缓存。
let metricsUpdatedAt: String?
/// 设备缓存过期时保留数值,但标为非实时读数。
let metricsStale: Bool?
/// 后端若明确提供订单号则保留,不由请求上下文伪造响应身份。
let orderNumber: String?
/// 实测返回的订单飞行任务身份;存在时必须与请求上下文核对。
@@ -31,6 +45,9 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
/// 只映射已知展示字段,不假设响应中的任务 ID 位置。
private enum CodingKeys: String, CodingKey {
case orderFlightTaskID = "order_flight_task_id", stateVersion = "state_version"
case executionBatch = "execution_batch", snapshotKind = "snapshot_kind"
case stateUpdatedAt = "state_updated_at", metricsUpdatedAt = "metrics_updated_at", metricsStale = "metrics_stale"
case orderNumber = "order_number", orderFlightTask = "order_flight_task", task
case scenic, scenicSpot = "scenic_spot", airLine = "air_line"
case header, currentPlane = "current_plane", executeGate = "execute_gate", ui
@@ -40,6 +57,13 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
/// 可选字段缺失或为 null 时保持未知;不把缺失执行门禁推断为允许。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
orderFlightTaskID = try container.decodeIfPresent(Int.self, forKey: .orderFlightTaskID)
stateVersion = try container.decodeIfPresent(Int64.self, forKey: .stateVersion)
executionBatch = try container.decodeIfPresent(Int64.self, forKey: .executionBatch)
snapshotKind = try container.decodeIfPresent(String.self, forKey: .snapshotKind)
stateUpdatedAt = try container.decodeIfPresent(String.self, forKey: .stateUpdatedAt)
metricsUpdatedAt = try container.decodeIfPresent(String.self, forKey: .metricsUpdatedAt)
metricsStale = try container.decodeIfPresent(Bool.self, forKey: .metricsStale)
orderNumber = try container.decodeIfPresent(String.self, forKey: .orderNumber)
orderFlightTask = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .orderFlightTask)
task = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .task)
@@ -0,0 +1,49 @@
import Foundation
/// HTTP 和 WebSocket 共用的快照接收结果;重复包可证明订阅有效,但旧包不能恢复实时状态。
enum DroneDockSnapshotAcceptance {
case applied, duplicate, outdated, invalid
}
/// 先解析业务码再解析 data,兼容订阅失败时 data=[]。
enum DroneDockShootingSocketMessage {
case subscribed(taskID: Int, hasSnapshot: Bool)
case snapshot(DroneDockShootingResponse)
case rejected(code: Int, message: String)
case unrelated
/// WebSocket 成功码为 0,不使用 HTTP 的 100000 Envelope。
static func decode(_ data: Data) throws -> Self {
guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let code = root["code"] as? Int else { throw APIError.invalidResponse }
if code != 0 {
return .rejected(code: code, message: root["msg"] as? String ?? "任务订阅失败")
}
guard let body = root["data"] as? [String: Any] else { throw APIError.invalidResponse }
if let subscribed = body["subscribed"] as? Bool, subscribed {
guard let id = body["order_flight_task_id"] as? Int,
let hasSnapshot = body["has_snapshot"] as? Bool else { throw APIError.invalidResponse }
return .subscribed(taskID: id, hasSnapshot: hasSnapshot)
}
guard body["action"] as? String == "app_airport_shooting_updated" else { return .unrelated }
guard let params = body["params"] as? [String: Any] else { throw APIError.invalidResponse }
let value = try JSONDecoder().decode(DroneDockShootingResponse.self,
from: JSONSerialization.data(withJSONObject: params))
guard value.orderFlightTaskID != nil, value.snapshotKind == "full",
let version = value.stateVersion, version > 0,
let batch = value.executionBatch, batch >= 0, value.ui?.phase != nil else {
throw APIError.decodeFailed("任务推送缺少完整快照或版本信息")
}
return .snapshot(value)
}
/// 构造已确认的只读订阅协议,不暴露任意 type 的发送入口。
static func subscribe(taskID: Int, token: String) -> String {
DroneDockDiagnostics.json(["type": 310, "params": ["id": taskID, "socket_token": token]])
}
/// 离页尽力取消订阅;断开连接也会清除服务端 fd 订阅。
static func unsubscribe(taskID: Int) -> String {
DroneDockDiagnostics.json(["type": 311, "params": ["id": taskID]])
}
}
@@ -0,0 +1,272 @@
import Foundation
/// 前台任务订阅协调器:完整推送正常时停 HTTP,连接异常时通知页面恢复串行兜底读取。
@MainActor
final class DroneDockShootingRealtimeSession {
/// 明确区分订阅中、有效实时快照、兜底和永久权限失败。
enum State: Equatable {
case stopped, connecting, live, fallback(String), denied(String)
}
/// 接收完整快照,由业务 ViewModel 统一核对身份和 HTTP/推送版本。
var onSnapshot: ((DroneDockShootingResponse) -> DroneDockSnapshotAcceptance)?
/// 通知页面调整读取策略和提示,不直接持有 UIKit。
var onConnectionState: ((State) -> Void)?
/// 当前链路状态;仅 live 表示订阅和完整快照都已确认。
private(set) var state: State = .stopped
private let taskID: Int
private let ticketService: any DroneDockSocketTicketServing
private let makeTransport: () -> any DroneDockShootingSocketTransport
private let identityIsCurrent: () -> Bool
private let delay: @Sendable (UInt64) async throws -> Void
private let now: () -> TimeInterval
private let source: String
private var transport: (any DroneDockShootingSocketTransport)?
private var connectionTask: Task<Void, Never>?
private var deadlineTask: Task<Void, Never>?
private var heartbeatTask: Task<Void, Never>?
private var pongDeadlineTask: Task<Void, Never>?
private var retryTask: Task<Void, Never>?
private var active = false
private var generation = 0
private var retryAttempt = 0
private var subscribed = false
private var lastSnapshotAt: TimeInterval?
private var latestSnapshot: DroneDockShootingResponse?
/// 全部外部依赖可替换,延时按纳秒注入以确定性验证断线、超时与重连。
init(taskID: Int, ticketService: any DroneDockSocketTicketServing,
makeTransport: @escaping () -> any DroneDockShootingSocketTransport,
identityIsCurrent: @escaping () -> Bool,
source: String = "network",
now: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime },
delay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
self.taskID = taskID
self.ticketService = ticketService
self.makeTransport = makeTransport
self.identityIsCurrent = identityIsCurrent
self.delay = delay
self.now = now
self.source = source
}
deinit {
connectionTask?.cancel()
deadlineTask?.cancel()
heartbeatTask?.cancel()
pongDeadlineTask?.cancel()
retryTask?.cancel()
}
/// 初始 HTTP 完成后启动;重复出现事件不会重复订阅。
func start() {
guard !active, taskID > 0 else { return }
if case .denied = state { return }
active = true
retryAttempt = 0
connect()
}
/// 离页/后台取消计时和接收,所有迟到消息由 generation 丢弃。
func stop() {
active = false
retryTask?.cancel()
retryTask = nil
clearConnection(unsubscribe: true)
if case .denied = state { return }
update(.stopped)
}
private func connect() {
guard active else { return }
guard identityIsCurrent() else { deny("账号或景区已变化,请返回工作台重新进入"); return }
clearConnection(unsubscribe: false)
update(.connecting)
let current = generation
let ticketService = ticketService
let delay = delay
// 票据、握手、ack 或首包卡住时,HTTP 仍可兜底,随后重连。
deadlineTask = Task { @MainActor [weak self] in
do { try await delay(12_000_000_000) } catch { return }
guard let self, self.accepts(current) else { return }
self.fail("任务订阅超时,正在通过接口更新")
}
connectionTask = Task { @MainActor [weak self] in
do {
let ticket = try await ticketService.socketTicket()
guard let self, self.accepts(current) else { return }
guard !ticket.socketToken.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw APIError.decodeFailed("订阅票据为空")
}
let transport = self.makeTransport()
self.transport = transport
let request = DroneDockShootingSocketMessage.subscribe(taskID: self.taskID, token: ticket.socketToken)
self.log("request.started", fields: ["body": DroneDockDiagnostics.payload(Data(request.utf8))])
try await transport.send(request)
guard self.accepts(current) else { return }
self.startHeartbeat(generation: current, transport: transport)
// 不让无限 receive 循环强持有协调器或页面。
self.connectionTask = Task { @MainActor [weak self] in
do {
while !Task.isCancelled {
let data = try await transport.receive()
guard let self, self.accepts(current) else { return }
self.log("response.received", fields: ["body": DroneDockDiagnostics.payload(data)])
try self.handle(DroneDockShootingSocketMessage.decode(data))
}
} catch {
guard let self, self.accepts(current) else { return }
self.fail(error.localizedDescription)
}
}
} catch {
guard let self, self.accepts(current) else { return }
if Self.isAccessFailure(error) { self.deny(error.localizedDescription) }
else { self.fail(error.localizedDescription) }
}
}
}
private func handle(_ message: DroneDockShootingSocketMessage) throws {
switch message {
case .subscribed(let id, let hasSnapshot):
guard id == taskID else { throw APIError.decodeFailed("订阅回执任务不一致") }
subscribed = true
if !hasSnapshot { update(.fallback("任务缓存尚未就绪,正在通过接口更新")) }
case .snapshot(let snapshot):
guard snapshot.orderFlightTaskID == taskID else {
log("websocket.snapshot_ignored", fields: ["reason": "different_task"])
return
}
guard subscribed else { throw APIError.decodeFailed("任务快照先于订阅回执") }
switch onSnapshot?(snapshot) ?? .invalid {
case .applied, .duplicate:
deadlineTask?.cancel()
deadlineTask = nil
retryAttempt = 0
latestSnapshot = snapshot
lastSnapshotAt = now()
checkDataHealth()
case .outdated:
log("websocket.snapshot_ignored", fields: ["reason": "old_version"])
case .invalid: throw APIError.decodeFailed("任务快照身份或结构不一致")
}
case .rejected(let code, let message):
if code == 100099, message.contains("无权订阅") || message.contains("飞行任务不存在") {
deny(message)
} else {
// 100098 是 socket 票据失败,重新取票;不当成 App 登录失效。
fail(message)
}
case .unrelated: break
}
}
private func startHeartbeat(generation current: Int, transport: any DroneDockShootingSocketTransport) {
let delay = delay
heartbeatTask = Task { @MainActor [weak self] in
do {
while !Task.isCancelled {
try await delay(20_000_000_000)
guard let self, self.accepts(current) else { return }
self.pongDeadlineTask = Task { @MainActor [weak self] in
do { try await delay(10_000_000_000) } catch { return }
guard let self, self.accepts(current) else { return }
self.fail("任务连接心跳超时,正在通过接口更新")
}
try await transport.ping()
guard self.accepts(current) else { return }
self.pongDeadlineTask?.cancel()
self.pongDeadlineTask = nil
self.log("websocket.pong")
self.checkDataHealth()
// 没有业务变化时允许长期静默,不能按 5 秒未推送误判断线。
}
} catch {
guard let self, self.accepts(current) else { return }
self.fail(error.localizedDescription)
}
}
}
private func fail(_ message: String) {
guard active else { return }
clearConnection(unsubscribe: false)
update(.fallback(message))
guard active else { return }
retryTask?.cancel()
let seconds = [1, 2, 4, 8, 16, 30][min(retryAttempt, 5)]
retryAttempt += 1
log("websocket.reconnect_scheduled", fields: ["delay_seconds": seconds])
let current = generation
let delay = delay
retryTask = Task { @MainActor [weak self] in
do { try await delay(UInt64(seconds) * 1_000_000_000) } catch { return }
guard let self, self.accepts(current) else { return }
self.retryTask = nil
self.connect()
}
}
private func deny(_ message: String) {
active = false
retryTask?.cancel()
retryTask = nil
clearConnection(unsubscribe: false)
update(.denied(message))
}
private func accepts(_ current: Int) -> Bool {
guard active, generation == current, !Task.isCancelled else { return false }
guard identityIsCurrent() else { deny("账号或景区已变化,请返回工作台重新进入"); return false }
return true
}
private func clearConnection(unsubscribe: Bool) {
generation &+= 1
connectionTask?.cancel(); connectionTask = nil
deadlineTask?.cancel(); deadlineTask = nil
heartbeatTask?.cancel(); heartbeatTask = nil
pongDeadlineTask?.cancel(); pongDeadlineTask = nil
if unsubscribe, transport != nil {
log("request.started", fields: ["body": DroneDockDiagnostics.payload(Data(DroneDockShootingSocketMessage.unsubscribe(taskID: taskID).utf8))])
}
transport?.close(unsubscribing: unsubscribe ? taskID : nil)
transport = nil
subscribed = false
latestSnapshot = nil
lastSnapshotAt = nil
}
private func checkDataHealth() {
guard subscribed, let snapshot = latestSnapshot, let receivedAt = lastSnapshotAt else { return }
if snapshot.metricsStale == true {
update(.fallback("设备读数缓存已过期,正在通过接口核对"))
} else if snapshot.ui?.phase == "shooting", now() - receivedAt >= 120 {
// 拍摄中后端约每 30 秒更新;连续四个周期无完整包,保持连接并用只读 HTTP 核对。
// 其它阶段只在变化时推送,不能仅因静默判定异常。
update(.fallback("拍摄状态长时间未更新,正在通过接口核对"))
} else {
update(.live)
}
}
private static func isAccessFailure(_ error: Error) -> Bool {
if APIError.isAuthenticationExpired(error) { return true }
guard case APIError.serverCode(let code, let message) = error else { return false }
return code == 100099 && (message.contains("无权") || message.contains("无权限"))
}
private func update(_ value: State) {
guard state != value else { return }
state = value
log("websocket.state", fields: ["state": String(describing: value)])
onConnectionState?(value)
}
private func log(_ event: String, fields: [String: Any] = [:]) {
DroneDockDiagnostics.event(event, taskID: taskID,
fields: fields.merging(["transport": "websocket", "path": "/api/app/airport/shooting", "source": source]) { _, new in new })
}
}
@@ -0,0 +1,59 @@
import Foundation
/// 任务 WebSocket 的隔离传输边界,测试替身不能转发到真实网络。
@MainActor
protocol DroneDockShootingSocketTransport: AnyObject {
/// 发送订阅 JSON。
func send(_ text: String) async throws
/// 等待一条完整消息。
func receive() async throws -> Data
/// 使用原生 Ping/Pong 检查链路,不发送业务或设备指令。
func ping() async throws
/// 关闭连接,离页时尽力发送 311,最多等待一秒。
func close(unsubscribing taskID: Int?)
}
/// Foundation WebSocket 实现;连接生命周期由任务页的实时协调器管理。
@MainActor
final class DroneDockURLSessionShootingSocket: DroneDockShootingSocketTransport {
private let socket: URLSessionWebSocketTask
/// 仅使用环境指定的 wss 地址,无登录 Header、无设备连接。
init(url: URL, session: URLSession = .shared) {
socket = session.webSocketTask(with: url)
socket.resume()
}
deinit { socket.cancel(with: .goingAway, reason: nil) }
func send(_ text: String) async throws { try await socket.send(.string(text)) }
func receive() async throws -> Data {
switch try await socket.receive() {
case .string(let text): return Data(text.utf8)
case .data(let data): return data
@unknown default: throw APIError.invalidResponse
}
}
func ping() async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
socket.sendPing { error in
if let error { continuation.resume(throwing: error) }
else { continuation.resume() }
}
}
}
func close(unsubscribing taskID: Int?) {
guard let taskID else { socket.cancel(with: .goingAway, reason: nil); return }
let socket = socket
socket.send(.string(DroneDockShootingSocketMessage.unsubscribe(taskID: taskID))) { _ in
socket.cancel(with: .normalClosure, reason: nil)
}
Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
socket.cancel(with: .normalClosure, reason: nil)
}
}
}
@@ -50,6 +50,9 @@ final class DroneDockShootingTaskViewModel {
private let commandService: (any DroneDockCommandSending)?
private let resummonService: (any DroneDockResummonServing)?
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
/// 无权限或登录失效后停止自动读取,旧数据仅用于展示。
private(set) var readAccessError: String?
private var snapshotRevision = 0
private var generation = 0
private var identityInvalidated = false
private var startGeneration = 0
@@ -93,17 +96,18 @@ final class DroneDockShootingTaskViewModel {
/// 身份失效或缺少任务信息时停止安排下一次读取。
var canContinuePolling: Bool {
!identityInvalidated && context.canLoad && taskID > 0
!identityInvalidated && readAccessError == nil && context.canLoad && taskID > 0
&& DroneDockHomeMetric.usableText(order.orderNumber) != nil
}
@MainActor
private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false,
allowWhileResummoning: Bool = false) async {
guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting,
guard !isLoading, !identityInvalidated, readAccessError == nil, !isStartingShooting || allowWhileStarting,
!isSendingCommand || allowWhileCommand, !isResummoning || allowWhileResummoning else { return }
generation &+= 1
let requestGeneration = generation
let revisionAtRequest = snapshotRevision
isLoading = true
errorMessage = nil
defer {
@@ -121,23 +125,18 @@ final class DroneDockShootingTaskViewModel {
do {
let value = try await service.shooting(taskID: taskID, liveBattery: false)
guard accepts(requestGeneration) else { return }
guard matchesIdentity(value) else {
if applyTaskSnapshot(value) == .invalid {
response = nil
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
}
response = value
DroneDockDiagnostics.event("shooting.snapshot_applied", taskID: taskID, fields: [
"phase": presentation.phase.rawValue,
"plane_id": value.currentPlane?.id as Any? ?? NSNull(),
"can_execute": value.executeGate?.canExecute as Any? ?? NSNull(),
"primary_action": value.executeGate?.primaryAction as Any? ?? NSNull()
])
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
awaitingResummonSnapshot = false
}
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
} catch {
guard accepts(requestGeneration) else { return }
if Self.stopsTaskReading(error) {
stopReading(message: error.localizedDescription)
return
}
// 迟到 HTTP 失败不能覆盖请求期间已收到的有效实时状态。
guard snapshotRevision == revisionAtRequest else { return }
errorMessage = error is CancellationError ? nil : error.localizedDescription
DroneDockDiagnostics.event("shooting.refresh_failed", taskID: taskID, fields: [
"retained_snapshot": response != nil, "error": DroneDockDiagnostics.errorFields(error)
@@ -145,6 +144,52 @@ final class DroneDockShootingTaskViewModel {
}
}
/// HTTP 和推送共享完整快照入口,按执行批次、版本去重,绝不按到达顺序覆盖。
@MainActor
@discardableResult
func applyTaskSnapshot(_ value: DroneDockShootingResponse) -> DroneDockSnapshotAcceptance {
guard readAccessError == nil, accepts(generation), matchesIdentity(value) else { return .invalid }
if let oldBatch = response?.executionBatch, let oldVersion = response?.stateVersion {
guard let batch = value.executionBatch, let version = value.stateVersion else { return .outdated }
if batch < oldBatch || (batch == oldBatch && version < oldVersion) { return .outdated }
if batch == oldBatch && version == oldVersion {
errorMessage = nil
snapshotRevision &+= 1
return .duplicate
}
}
response = value
errorMessage = nil
snapshotRevision &+= 1
DroneDockDiagnostics.event("shooting.snapshot_applied", taskID: taskID, fields: [
"phase": presentation.phase.rawValue,
"execution_batch": value.executionBatch as Any? ?? NSNull(),
"state_version": value.stateVersion as Any? ?? NSNull(),
"plane_id": value.currentPlane?.id as Any? ?? NSNull()
])
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
awaitingResummonSnapshot = false
}
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
return .applied
}
/// 订阅明确无权限或 HTTP 鉴权失效时保留快照、禁用操作并停止后续读取。
@MainActor
func stopReading(message: String) {
generation &+= 1
isLoading = false
readAccessError = message
errorMessage = message
}
/// 只把已确认的权限信息视为终止条件,不把所有 100099 业务错误一概当成无权限。
private static func stopsTaskReading(_ error: Error) -> Bool {
if APIError.isAuthenticationExpired(error) { return true }
guard case APIError.serverCode(let code, let message) = error else { return false }
return code == 100099 && (message.contains("无权") || message.contains("无权限") || message.contains("飞行任务不存在"))
}
/// 使旧请求失效;同一身份离页或进入后台可保留快照,账号变化始终清除并停止旧任务读取。
@MainActor
func invalidate(preservingSnapshot: Bool = false) {
@@ -166,14 +211,14 @@ final class DroneDockShootingTaskViewModel {
errorMessage = "账号或景区已变化,请返回工作台重新进入"
} else {
if !preservingSnapshot { response = nil }
errorMessage = nil
errorMessage = readAccessError
}
}
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;Debug 真实页面保持禁用。
var canStartShooting: Bool {
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !hasSubmittedStart && !startOutcomeUnknown
&& !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot && pendingAcceptedCommands.isEmpty
&& resolvedDisplayPhase().0 == .ready
@@ -263,7 +308,7 @@ final class DroneDockShootingTaskViewModel {
/// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。
func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool {
commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot
&& !pendingAcceptedCommands.contains(command)
&& (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID)
@@ -342,7 +387,7 @@ final class DroneDockShootingTaskViewModel {
/// 此门禁用于客户端模拟交互,不代表后端已提供真实重试许可。
var canResummon: Bool {
resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown
&& !hasSubmittedResummon && pendingAcceptedCommands.isEmpty
&& resolvedDisplayPhase().0 == .failed
@@ -478,7 +523,7 @@ final class DroneDockShootingTaskViewModel {
}
if response == nil, let errorMessage {
return DroneDockTaskPresentation(phase: .readError, title: "任务状态读取失败", message: errorMessage,
deviceStatus: deviceStatusText, action: .refresh, actionTitle: "重新读取", isActionEnabled: !identityInvalidated)
deviceStatus: deviceStatusText, action: .refresh, actionTitle: "重新读取", isActionEnabled: !identityInvalidated && readAccessError == nil)
}
let (phase, conflict) = resolvedDisplayPhase()
let message = conflict ? "任务状态信息不一致,请刷新后确认。" + (statusMessage == "—" ? "" : statusMessage) : statusMessage
@@ -519,7 +564,7 @@ final class DroneDockShootingTaskViewModel {
}
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
isActionEnabled: enabled && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
isActionEnabled: enabled && readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil)
}
@@ -530,8 +575,8 @@ final class DroneDockShootingTaskViewModel {
windText: text("wind_speed"), rainText: text("rainfall"), signalText: text("signal"), satelliteText: text("satellite"))
}
/// 仅无快照时使用未知读数;刷新期间继续展示最近一次成功快照。
var isTelemetryStale: Bool { response == nil }
/// 无快照或后端标记缓存过期时使用非实时样式;已有读数仍保留展示。
var isTelemetryStale: Bool { response == nil || response?.metricsStale == true }
/// 完整服务端 data,供页面展示和联调查看。
var dataJSON: String? { response?.dataJSON }
@@ -612,7 +657,7 @@ final class DroneDockShootingTaskViewModel {
}
private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool {
let taskIDs = [value.orderFlightTask?.id, value.task?.id].compactMap { $0 }
let taskIDs = [value.orderFlightTaskID, value.orderFlightTask?.id, value.task?.id].compactMap { $0 }
let orderNumbers = [value.orderNumber, value.orderFlightTask?.orderNumber,
value.task?.orderNumber, value.header?.orderNumber].compactMap { $0 }
let scenicIDs = [value.scenic?.id, value.orderFlightTask?.scenicID,
@@ -631,6 +676,7 @@ final class DroneDockShootingTaskViewModel {
if statuses.contains(50) { return (.blocked, false) }
if statuses.count > 1 { return (.unknown, true) }
let known: [String: DroneDockTaskDisplayPhase] = [
"going_to_spot": .navigating, "failed_restartable": .failed, "waiting_summon": .blocked,
"navigating": .navigating, "arrived_pending_start": .ready, "shooting": .shooting,
"paused": .paused, "returning": .returning, "completed": .completed, "failed": .failed, "blocked": .blocked
]
@@ -7,6 +7,10 @@ enum DroneDockShootingTaskEntry {
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext) -> UIViewController {
let client = NetworkServices.shared.apiClient
let realtime = DroneDockShootingRealtimeSession(taskID: taskID,
ticketService: DroneDockSocketTokenAPI(client: client),
makeTransport: { DroneDockURLSessionShootingSocket(url: APIEnvironment.current.webSocketURL) },
identityIsCurrent: { context.hasSameIdentity(as: DroneDockHomeViewController.currentContext()) })
let live = DroneDockLiveViewModel(
context: context, taskID: taskID,
service: DeviceCommandDebugPolicy.blocksLiveRequests ? nil : DroneDockLiveAPI(client: client),
@@ -19,6 +23,6 @@ enum DroneDockShootingTaskEntry {
commandService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockCommandAPI(client: client),
resummonService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockShootAPI(client: client),
currentContext: { DroneDockHomeViewController.currentContext() }
), liveViewModel: live)
), liveViewModel: live, realtimeSession: realtime)
}
}
@@ -1,13 +1,14 @@
import SnapKit
import UIKit
/// 拍摄任务页:前台轮询状态、手动图传;Release 开放已授权控制,Debug 仅模拟控制。
/// 拍摄任务页:前台优先订阅快照、异常时 HTTP 兜底;图传与控制仍须用户手动操作。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
let viewModel: DroneDockShootingTaskViewModel
/// 图传使用独立状态,刷新与播放不会影响任务阶段或固定布局。
let liveViewModel: DroneDockLiveViewModel
private let realtimeSession: DroneDockShootingRealtimeSession?
private let topView = UIView()
private let summaryView = UIView()
@@ -39,14 +40,17 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private var isStartingAction = false
private var isSendingSafetyAction = false
private var isResummoningAction = false
private var wasRealtimeLive = false
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
init(viewModel: DroneDockShootingTaskViewModel,
liveViewModel: DroneDockLiveViewModel? = nil,
realtimeSession: DroneDockShootingRealtimeSession? = nil,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
simulationRecordsProvider: (@MainActor () -> String)? = nil,
shootingPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
self.viewModel = viewModel
self.realtimeSession = realtimeSession
self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel(
context: viewModel.context, taskID: viewModel.taskID,
currentContext: { DroneDockHomeViewController.currentContext() })
@@ -60,6 +64,15 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
realtimeSession?.onSnapshot = { [weak self] snapshot in
guard let self, self.isPageVisible, self.isApplicationActive else { return .invalid }
let result = self.viewModel.applyTaskSnapshot(snapshot)
self.applySnapshot()
return result
}
realtimeSession?.onConnectionState = { [weak self] state in
self?.connectionStateChanged(state)
}
}
@available(*, unavailable)
@@ -192,7 +205,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
name: UIApplication.didBecomeActiveNotification, object: nil)
}
/// 完整进入任务页立即读取,随后仅在前台可见时轮询同一任务。
/// 完整进入任务页先读取一次,再启动同一任务的只读订阅。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isPageVisible = true
@@ -218,11 +231,11 @@ final class DroneDockShootingTaskViewController: BaseViewController {
feedPlaceholder.apply(liveViewModel)
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive)
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle
subtitleLabel.text = viewModel.subtitle + (viewModel.response?.metricsStale == true ? " · 读数已过期" : "")
let telemetry = viewModel.telemetry
telemetryView.apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
telemetry.rainText, telemetry.signalText, telemetry.satelliteText],
isStale: viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric")
isStale: viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric", preservingStaleValues: true)
let value = loading && viewModel.response == nil ? DroneDockTaskPresentation(
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
@@ -265,6 +278,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
if viewModel.response != nil, let error = viewModel.errorMessage {
texts.append("刷新失败,当前显示上次数据:\(error)")
}
if case .fallback(let message) = realtimeSession?.state {
texts.append("实时连接暂不可用,已使用接口更新:\(message)")
}
if let error = viewModel.startErrorMessage { texts.append(error) }
if let error = viewModel.commandErrorMessage { texts.append(error) }
if let error = viewModel.resummonErrorMessage { texts.append(error) }
@@ -277,7 +293,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 前台可见时串行读取;轮询失败保留旧快照,下个周期再读,不重复弹出提示。
private func refreshTaskIfVisible(isPolling: Bool = false) {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
guard isPageVisible, isApplicationActive, viewModel.readAccessError == nil, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand,
!isResummoningAction, !viewModel.isResummoning else { return }
@@ -295,6 +311,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.refreshTask = nil
self.isRequesting = false
self.applySnapshot()
if self.viewModel.canContinuePolling { self.realtimeSession?.start() }
else { self.realtimeSession?.stop() }
self.scheduleNextPoll()
if !isPolling, self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.showToast("刷新失败,当前显示上次数据:\(error)")
@@ -306,6 +324,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func scheduleNextPoll() {
cancelScheduledPoll()
guard isPageVisible, isApplicationActive, viewModel.canContinuePolling,
realtimeSession?.state != .live,
!isRequesting, !isStartingAction, !isSendingSafetyAction, !isResummoningAction else { return }
let generation = pollGeneration
let delay = shootingPollDelay
@@ -327,6 +346,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
private func cancelRefresh() {
wasRealtimeLive = false
realtimeSession?.stop()
cancelScheduledPoll()
requestGeneration &+= 1
refreshTask?.cancel()
@@ -345,6 +366,36 @@ final class DroneDockShootingTaskViewController: BaseViewController {
applySnapshot()
}
private func connectionStateChanged(_ state: DroneDockShootingRealtimeSession.State) {
guard isPageVisible, isApplicationActive else { return }
switch state {
case .live:
wasRealtimeLive = true
cancelScheduledPoll()
applySnapshot()
case .denied(let message):
wasRealtimeLive = false
cancelScheduledPoll()
requestGeneration &+= 1
refreshTask?.cancel()
refreshTask = nil
isRequesting = false
viewModel.stopReading(message: message)
applySnapshot()
showToast(message)
case .fallback:
// 断线立即尝试一次 GET;已有读/写流程则由其完成回调安排下一轮,绝不并发。
let shouldRefreshImmediately = wasRealtimeLive
wasRealtimeLive = false
if shouldRefreshImmediately { refreshTaskIfVisible(isPolling: true) }
else if pollTask == nil { scheduleNextPoll() }
case .connecting:
// 重连不能不断重置 HTTP 计时,否则长时间异常会饿死兜底请求。
if pollTask == nil { scheduleNextPoll() }
case .stopped: wasRealtimeLive = false
}
}
/// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。
private func startShootingIfAllowed() {
guard !isStartingAction, !isSendingSafetyAction, !isResummoningAction, viewModel.canStartShooting else { return }
@@ -108,6 +108,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
thumbnail.backgroundColor = DroneDockStyle.background
thumbnail.layer.cornerRadius = 5
thumbnail.clipsToBounds = true
thumbnail.accessibilityIdentifier = "drone.preparation.point.cover"
nameLabel.numberOfLines = 0
nameLabel.lineBreakMode = .byWordWrapping
nameLabel.accessibilityIdentifier = "drone.preparation.point.name"
@@ -148,6 +149,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
/// 展示点位名称与次数,已拍摄的点位仍保持可选择。
func apply(point: DroneShootingPoint, selected: Bool) {
thumbnail.kf.cancelDownloadTask()
thumbnail.kf.setImage(with: nil as URL?)
contentView.alpha = 1
nameLabel.text = point.name
thumbnail.contentMode = .scaleAspectFill
@@ -164,14 +166,11 @@ final class DronePreparationPointCell: UICollectionViewCell {
func apply(spot: DroneDockPurchasedSpot, selected: Bool) {
nameLabel.text = spot.name
thumbnail.kf.cancelDownloadTask()
thumbnail.image = UIImage(systemName: "photo")
thumbnail.contentMode = .center
let coverURL = spot.displayCoverURL
thumbnail.contentMode = coverURL == nil ? .center : .scaleAspectFill
thumbnail.tintColor = DroneDockStyle.secondary
if let text = spot.coverURL, let url = URL(string: text),
let scheme = url.scheme?.lowercased(), ["https", "http"].contains(scheme), url.host != nil {
thumbnail.contentMode = .scaleAspectFill
thumbnail.kf.setImage(with: url, placeholder: UIImage(systemName: "photo"))
}
// nil 也交给 Kingfisher,撤销旧图片标识,防止复用后的迟到结果覆盖占位图。
thumbnail.kf.setImage(with: coverURL, placeholder: UIImage(systemName: "photo"))
if spot.available != true {
countLabel.text = spot.available == false ? "拍摄点不可用" : "可用性待确认"
} else {
@@ -189,7 +188,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
override func prepareForReuse() {
super.prepareForReuse()
thumbnail.kf.cancelDownloadTask()
thumbnail.image = nil
thumbnail.kf.setImage(with: nil as URL?)
}
}
@@ -210,12 +210,12 @@ final class DroneShootingTaskTelemetryView: UIView {
telemetry.rainText, telemetry.signalText, telemetry.satelliteText], isStale: isStale)
}
/// 展示后端已格式化的六项读数,保留单位;缺项与过期读数显示破折号。
func apply(values: [String], isStale: Bool, accessibilityPrefix: String? = nil) {
/// 展示后端格式化读数;缺项显示破折号,任务页可保留过期旧值并使用灰色提示。
func apply(values: [String], isStale: Bool, accessibilityPrefix: String? = nil, preservingStaleValues: Bool = false) {
staleLabel.isHidden = usesFixedLayout || !isStale
let keys = ["battery", "temperature", "wind", "rain", "signal", "satellite"]
for (index, cell) in cells.enumerated() {
let value = !isStale && values.indices.contains(index)
let value = (!isStale || preservingStaleValues) && values.indices.contains(index)
? DroneDockHomeMetric.usableText(values[index]) ?? "—" : "—"
cell.apply(value: value, isStale: isStale)
if let accessibilityPrefix { cell.accessibilityIdentifier = "\(accessibilityPrefix).\(keys[index])" }