feat: 完善机巢任务安全控制与状态诊断
同步新版飞控与 WebSocket 回执合同,完善独立指令等待、暂停继续和返航状态;增加真机诊断并优化倒计时与素材库展示。
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// 控制台只展示路径、入参及原始返回 JSON,不输出诊断信封或业务事件。
|
||||
/// 接口日志保留路径、入参及原始返回;仅额外放行明确标识的拍摄任务关键事件。
|
||||
enum APIConsoleFormat {
|
||||
/// 发起请求时立即输出路径和参数;响应记录携带同样参数,方便并发请求核对。
|
||||
static func message(path: String, params: Any, response: Any? = nil) -> String {
|
||||
@@ -51,9 +51,14 @@ enum APIConsoleFormat {
|
||||
self.message(path: path, params: params, response: ["local_error": ["kind": kind, "message": message]])
|
||||
}
|
||||
|
||||
/// 将内部诊断记录转换为简洁输出;解码、页面、心跳、RTC 等事件不进入控制台。
|
||||
/// 接口记录转换为简洁输出;只有 drone_task 专用事件保留诊断字段,其余内部事件仍过滤。
|
||||
static func render(_ text: String) -> String? {
|
||||
guard let fields = try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] else { return nil }
|
||||
if fields["diagnostic"] as? String == "drone_task" {
|
||||
guard let event = fields["event"] as? String,
|
||||
!event.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil }
|
||||
return pretty(fields)
|
||||
}
|
||||
if fields["event"] == nil, let path = fields["path"] as? String, let params = fields["params"] {
|
||||
return message(path: path, params: params, response: fields["response"])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import Foundation
|
||||
|
||||
/// 拍摄任务会话的关键事件日志;与接口正文分开标识,Debug 和 Release 使用同一安全输出通道。
|
||||
final class DroneDockTaskDiagnostics: @unchecked Sendable {
|
||||
/// 同一任务页及其 ViewModel 共用的会话标识,用于与录屏和接口日志对照。
|
||||
let sessionID: String
|
||||
|
||||
private let lock = NSLock()
|
||||
private let metadata: DroneDockTaskDiagnosticMetadata
|
||||
private let now: @Sendable () -> Date
|
||||
private let uptime: @Sendable () -> TimeInterval
|
||||
private let sink: @Sendable (String) -> Void
|
||||
private let startedUptime: TimeInterval
|
||||
private var sequence = 0
|
||||
|
||||
/// 默认写入已有串行控制台出口;测试可注入时钟和纯内存 sink,不修改全局日志通道。
|
||||
init(sessionID: String = UUID().uuidString,
|
||||
metadata: DroneDockTaskDiagnosticMetadata = .current,
|
||||
now: @escaping @Sendable () -> Date = { Date() },
|
||||
uptime: @escaping @Sendable () -> TimeInterval = { ProcessInfo.processInfo.systemUptime },
|
||||
sink: @escaping @Sendable (String) -> Void = { DroneDockDiagnostics.write($0) }) {
|
||||
self.sessionID = sessionID
|
||||
self.metadata = metadata
|
||||
self.now = now
|
||||
self.uptime = uptime
|
||||
self.sink = sink
|
||||
startedUptime = uptime()
|
||||
}
|
||||
|
||||
/// 按同一会话顺序同步生成并输出关键事件;业务字段完整保留,不能覆盖关联身份及时间字段。
|
||||
func record(_ event: String, taskID: Int, fields: [String: Any] = [:]) {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
sequence += 1
|
||||
let elapsed = max(0, (uptime() - startedUptime) * 1_000)
|
||||
let milliseconds = elapsed.isFinite && elapsed < Double(Int.max) ? Int(elapsed) : 0
|
||||
sink(Self.makeMessage(event, taskID: taskID, fields: fields, sessionID: sessionID,
|
||||
sequence: sequence, timestamp: now(), elapsedMilliseconds: milliseconds, metadata: metadata))
|
||||
}
|
||||
|
||||
/// 纯格式化入口:使用上海时区的毫秒时间,单调耗时与系统墙钟彼此独立。
|
||||
static func makeMessage(_ event: String, taskID: Int, fields: [String: Any] = [:],
|
||||
sessionID: String, sequence: Int, timestamp: Date,
|
||||
elapsedMilliseconds: Int,
|
||||
metadata: DroneDockTaskDiagnosticMetadata = .current) -> String {
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
formatter.calendar = Calendar(identifier: .gregorian)
|
||||
formatter.timeZone = TimeZone(identifier: "Asia/Shanghai")
|
||||
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
|
||||
var value = fields
|
||||
value["diagnostic"] = "drone_task"
|
||||
value["event"] = event
|
||||
value["timestamp"] = formatter.string(from: timestamp)
|
||||
value["timezone"] = "Asia/Shanghai"
|
||||
value["elapsed_ms"] = max(0, elapsedMilliseconds)
|
||||
value["sequence"] = sequence
|
||||
value["session_id"] = sessionID
|
||||
value["task_id"] = taskID
|
||||
value["app_version"] = metadata.appVersion
|
||||
value["app_build"] = metadata.appBuild
|
||||
value["configuration"] = metadata.configuration
|
||||
return DroneDockDiagnostics.json(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// 构建信息在会话创建时固定,不因后续事件或外部传入字段变化。
|
||||
struct DroneDockTaskDiagnosticMetadata: Sendable {
|
||||
/// App 对外版本号。
|
||||
let appVersion: String
|
||||
/// App 构建号。
|
||||
let appBuild: String
|
||||
/// 当前构建配置,值为 Debug 或 Release。
|
||||
let configuration: String
|
||||
|
||||
/// 从当前 App 获取只读构建信息;缺失时明确标为 unknown。
|
||||
static var current: Self {
|
||||
#if DEBUG
|
||||
let configuration = "Debug"
|
||||
#else
|
||||
let configuration = "Release"
|
||||
#endif
|
||||
return Self(appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown",
|
||||
appBuild: Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown",
|
||||
configuration: configuration)
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import Foundation
|
||||
protocol DroneDockCommandSending: Sendable {
|
||||
/// 提交任务 ID 和白名单指令,不创建任务、不选机,也不自动重试。
|
||||
@MainActor
|
||||
func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse
|
||||
func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse
|
||||
}
|
||||
|
||||
/// 朱工 command 合同适配,真实传输仍受统一 Debug 禁飞策略阻断。
|
||||
@@ -15,15 +15,17 @@ final class DroneDockCommandAPI: DroneDockCommandSending {
|
||||
/// 注入统一客户端;模拟调试使用完全不转发网络的响应替身。
|
||||
init(client: APIClient) { self.client = client }
|
||||
|
||||
/// 每次仅发送 id 和 command,回执必须对应同一任务及同一指令。
|
||||
func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse {
|
||||
/// 每次点击使用独立幂等键,回执必须对应同一任务、指令及请求。
|
||||
func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse {
|
||||
try Task.checkCancellation()
|
||||
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请返回任务页确认") }
|
||||
guard taskID > 0, !clientRequestID.isEmpty else { throw APIError.networkFailed("缺少有效拍摄任务或指令标识,请返回任务页确认") }
|
||||
let response: DroneDockCommandResponse = try await client.send(APIRequest(
|
||||
method: .post, path: "/api/app/airport/command",
|
||||
body: CommandBody(taskID: taskID, command: command.rawValue)
|
||||
body: CommandBody(taskID: taskID, command: command.rawValue, clientRequestID: clientRequestID)
|
||||
))
|
||||
guard response.orderFlightTaskID == taskID, response.command == command.rawValue else {
|
||||
guard response.orderFlightTaskID == taskID, response.command == command.rawValue,
|
||||
DroneDockHomeMetric.usableText(response.commandID) != nil,
|
||||
response.clientRequestID == nil || response.clientRequestID == clientRequestID else {
|
||||
throw APIError.decodeFailed("安全指令回执的任务或指令不一致,请核对原任务状态")
|
||||
}
|
||||
return response
|
||||
@@ -33,8 +35,9 @@ final class DroneDockCommandAPI: DroneDockCommandSending {
|
||||
private struct CommandBody: Encodable {
|
||||
let taskID: Int
|
||||
let command: String
|
||||
let clientRequestID: String
|
||||
|
||||
/// 朱工请求字段映射,不附加飞机或模拟标志。
|
||||
private enum CodingKeys: String, CodingKey { case taskID = "id", command }
|
||||
private enum CodingKeys: String, CodingKey { case taskID = "id", command, clientRequestID = "client_request_id" }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ enum DroneDockSafetyCommand: String, CaseIterable, Sendable {
|
||||
case pause = "flighttask_pause"
|
||||
/// 恢复已暂停的航线。
|
||||
case resume = "flighttask_recovery"
|
||||
/// 立即返航;服务端会中断当前任务并释放飞行锁。
|
||||
/// 立即返航;中断拍摄结果,回巢前仍占用设备。
|
||||
case returnHome = "return_home"
|
||||
/// 取消返航,不代表已恢复或重新创建原拍摄任务。
|
||||
case cancelReturn = "return_home_cancel"
|
||||
@@ -14,6 +14,26 @@ enum DroneDockSafetyCommand: String, CaseIterable, Sendable {
|
||||
|
||||
/// 指令受理回执;仅保留后端返回的身份、读数与状态,不推断设备已完成动作。
|
||||
struct DroneDockCommandResponse: Decodable, Equatable, Sendable {
|
||||
/// 明确受理标记,仅受理不表示设备已执行。
|
||||
let accepted: Bool?
|
||||
/// 回执探测时是否确认设备状态;页面最终仍读取完整 shooting/WS。
|
||||
let deviceConfirmed: Bool?
|
||||
/// 本次指令的服务端唯一标识。
|
||||
let commandID: String?
|
||||
/// 回显本次点击的幂等键,提供时必须与请求一致。
|
||||
let clientRequestID: String?
|
||||
/// 回执顶层的指令进度;完整任务快照位于 flight_control 内。
|
||||
let pendingCommand: DroneDockCommandProgress?
|
||||
/// 受理提示原文,用于诊断,不作为展示状态。
|
||||
let hint: String?
|
||||
/// 回执所属批次,必须与提交时一致。
|
||||
let executionBatch: Int64?
|
||||
/// 回执对应快照版本,用作后续状态核对的最低版本。
|
||||
let stateVersion: Int64?
|
||||
/// 设备身份在提供时必须匹配任务锁定设备。
|
||||
let planeID: Int?
|
||||
/// 回执中的设备状态不替代完整任务快照。
|
||||
let flightControl: DroneDockFlightControl?
|
||||
/// 文档要求回显的订单飞行任务 ID。
|
||||
let orderFlightTaskID: Int?
|
||||
/// 本次回显的指令码,API 核验其与请求一致。
|
||||
@@ -29,6 +49,9 @@ struct DroneDockCommandResponse: Decodable, Equatable, Sendable {
|
||||
|
||||
/// 朱工指令回执字段映射。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case accepted, deviceConfirmed = "device_confirmed", hint, executionBatch = "execution_batch"
|
||||
case commandID = "command_id", clientRequestID = "client_request_id", pendingCommand = "pending_command"
|
||||
case stateVersion = "state_version", planeID = "plane_id", flightControl = "flight_control"
|
||||
case orderFlightTaskID = "order_flight_task_id", command, airportSN = "airport_sn"
|
||||
case djiStatus = "dji_status", metrics
|
||||
}
|
||||
@@ -36,6 +59,16 @@ struct DroneDockCommandResponse: Decodable, Equatable, Sendable {
|
||||
/// 不补造身份、状态或读数,完整 JSON 仍保留实际出现的 null 字段。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
accepted = try container.decodeIfPresent(Bool.self, forKey: .accepted)
|
||||
deviceConfirmed = try container.decodeIfPresent(Bool.self, forKey: .deviceConfirmed)
|
||||
commandID = try container.decodeIfPresent(String.self, forKey: .commandID)
|
||||
clientRequestID = try container.decodeIfPresent(String.self, forKey: .clientRequestID)
|
||||
pendingCommand = try container.decodeIfPresent(DroneDockCommandProgress.self, forKey: .pendingCommand)
|
||||
hint = try container.decodeIfPresent(String.self, forKey: .hint)
|
||||
executionBatch = try container.decodeIfPresent(Int64.self, forKey: .executionBatch)
|
||||
stateVersion = try container.decodeIfPresent(Int64.self, forKey: .stateVersion)
|
||||
planeID = try container.decodeIfPresent(Int.self, forKey: .planeID)
|
||||
flightControl = try container.decodeIfPresent(DroneDockFlightControl.self, forKey: .flightControl)
|
||||
orderFlightTaskID = try container.decodeIfPresent(Int.self, forKey: .orderFlightTaskID)
|
||||
command = try container.decodeIfPresent(String.self, forKey: .command)
|
||||
airportSN = try container.decodeIfPresent(String.self, forKey: .airportSN)
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import Foundation
|
||||
|
||||
/// 单次点击的本地生命周期;等待只作用于对应按钮,不充当页面业务阶段。
|
||||
enum DroneDockCommandOperationPhase: Sendable {
|
||||
case queued, sending, pending, unknown, confirmed, finished
|
||||
}
|
||||
|
||||
/// 同任务批次内的幂等指令上下文;设备身份和提交版本防止迟到响应恢复旧锁。
|
||||
struct DroneDockCommandOperation: Sendable {
|
||||
let requestID: String
|
||||
let command: DroneDockSafetyCommand
|
||||
let batch: Int64
|
||||
let sequence: Int
|
||||
let generation: Int
|
||||
let submittedVersion: Int64
|
||||
let planeID: Int
|
||||
let airportSN: String?
|
||||
let resumePhase: String?
|
||||
var commandID: String?
|
||||
var minimumVersion: Int64?
|
||||
var phase: DroneDockCommandOperationPhase = .queued
|
||||
var error: String?
|
||||
|
||||
/// 未获得明确结果时禁止重复提交同一动作,其他安全动作独立授权。
|
||||
var isWaiting: Bool { phase != .finished }
|
||||
/// 已确认但尚未收到更新快照时停止动画,仍防止按旧权限重复点击同一动作。
|
||||
var isLoading: Bool { isWaiting && phase != .confirmed && phase != .unknown }
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import Foundation
|
||||
|
||||
/// 设备执行态独立于拍摄结果;未知或不一致状态不提供控制权限。
|
||||
enum DroneDockFlightControlState: String, Sendable {
|
||||
case starting, executing, paused, returning, returned, unknown
|
||||
}
|
||||
|
||||
/// shooting/WS 的批次设备状态;原值保留以兼容未来枚举,但未知值不会开放操作。
|
||||
struct DroneDockFlightControl: Decodable, Equatable, Sendable {
|
||||
/// 后端原始执行态。
|
||||
let state: String?
|
||||
/// 设备遥测确认是否仍在飞行;未知保持原值,不单独覆盖后端操作许可。
|
||||
let isAirborne: Bool?
|
||||
/// arrival_wait 是自动到点等待,manual 才是已确认的手动暂停。
|
||||
let pauseReason: String?
|
||||
/// 司空原始航线态仅用于联调对照,不能直接代替手动暂停判定。
|
||||
let djiTaskStatus: String?
|
||||
/// 继续任务将恢复的业务阶段,返航暂停后仍恢复返航。
|
||||
let resumePhase: String?
|
||||
/// manual、normal_complete 或 abnormal,区分拍摄中断和正常拍完。
|
||||
let returnReason: String?
|
||||
/// 明确允许暂停。
|
||||
let canPause: Bool?
|
||||
/// 明确允许继续任务。
|
||||
let canResume: Bool?
|
||||
/// 明确允许立即返航。
|
||||
let canReturnHome: Bool?
|
||||
/// inside 是已回巢的必要依据,缺失或 outside 均不能视为回巢。
|
||||
let droneInDock: String?
|
||||
/// 状态所属航线批次。
|
||||
let executionBatch: Int64?
|
||||
/// 当前批次指令进度,供对应按钮结束等待,不覆盖业务阶段。
|
||||
let pendingCommand: DroneDockCommandProgress?
|
||||
|
||||
/// 字段与 HTTP/WS 共用合同对应。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case state, isAirborne = "is_airborne", pauseReason = "pause_reason"
|
||||
case djiTaskStatus = "dji_task_status"
|
||||
case resumePhase = "resume_phase", returnReason = "return_reason"
|
||||
case canPause = "can_pause", canResume = "can_resume", canReturnHome = "can_return_home"
|
||||
case droneInDock = "drone_in_dock", executionBatch = "execution_batch"
|
||||
case pendingCommand = "pending_command"
|
||||
}
|
||||
|
||||
/// 仅同一有效批次返回已知执行态;回巢仍须 inside,遥测缺失不覆盖后端状态。
|
||||
func resolvedState(for batch: Int64?) -> DroneDockFlightControlState {
|
||||
guard let batch, batch > 0, executionBatch == batch,
|
||||
let state, let value = DroneDockFlightControlState(rawValue: state) else { return .unknown }
|
||||
if value == .returned { return droneInDock == "inside" ? .returned : .unknown }
|
||||
if value == .paused && pauseReason != "manual" { return .unknown }
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP 回执和完整快照共用的指令进度;标识均由服务端回显,不按到包顺序猜测成功。
|
||||
struct DroneDockCommandProgress: Decodable, Equatable, Sendable {
|
||||
/// 服务端唯一指令标识。
|
||||
let commandID: String?
|
||||
/// 本次点击生成的幂等请求标识。
|
||||
let clientRequestID: String?
|
||||
/// 明确对应的安全指令。
|
||||
let command: String?
|
||||
/// pending、succeeded、failed 或 superseded;未知值继续只读核对。
|
||||
let status: String?
|
||||
/// 服务端若提供失败说明则用于本次操作提示。
|
||||
let message: String?
|
||||
|
||||
/// 与后端原始字段对应。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case commandID = "command_id", clientRequestID = "client_request_id", command, status, message
|
||||
}
|
||||
}
|
||||
|
||||
/// 服务端重召唤门禁;客户端仍需验证设备回巢、可用性及操作防重锁。
|
||||
struct DroneDockShootingRestartGate: Decodable, Equatable, Sendable {
|
||||
/// true 才允许进入重召唤校验。
|
||||
let canRestart: Bool?
|
||||
/// 后端诊断原因码。
|
||||
let code: String?
|
||||
/// 后端限制原因,供用户核对。
|
||||
let message: String?
|
||||
|
||||
/// 使用后端原始字段名。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case canRestart = "can_restart", code, message
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,10 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
|
||||
let planeStatus: DroneDockShootingPlaneStatus?
|
||||
/// 执行门禁参与展示及本地模拟开拍校验,不能解除真实飞控禁令。
|
||||
let executeGate: DroneDockShootingExecuteGate?
|
||||
/// 重召唤许可独立于开拍门禁,缺失不视为允许。
|
||||
let restartGate: DroneDockShootingRestartGate?
|
||||
/// 当前批次设备执行状态与逐项权限,不依赖服务端显示文案。
|
||||
let flightControl: DroneDockFlightControl?
|
||||
/// 服务端拍摄阶段和页面提示。
|
||||
let ui: DroneDockShootingUI?
|
||||
/// 完整 data 的格式化 JSON,保留未知字段、空值及原 JSON 类型。
|
||||
@@ -54,6 +58,7 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
|
||||
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
|
||||
case restartGate = "restart_gate", flightControl = "flight_control"
|
||||
case metrics, planeStatus = "plane_status"
|
||||
}
|
||||
|
||||
@@ -79,6 +84,8 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
|
||||
metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? []
|
||||
planeStatus = try container.decodeIfPresent(DroneDockShootingPlaneStatus.self, forKey: .planeStatus)
|
||||
executeGate = try container.decodeIfPresent(DroneDockShootingExecuteGate.self, forKey: .executeGate)
|
||||
restartGate = try container.decodeIfPresent(DroneDockShootingRestartGate.self, forKey: .restartGate)
|
||||
flightControl = try container.decodeIfPresent(DroneDockFlightControl.self, forKey: .flightControl)
|
||||
ui = try container.decodeIfPresent(DroneDockShootingUI.self, forKey: .ui)
|
||||
let raw = try DroneDockHomeJSONValue(from: decoder)
|
||||
let encoder = JSONEncoder()
|
||||
@@ -95,7 +102,7 @@ struct DroneDockShootingTaskIdentity: Decodable, Equatable, Sendable {
|
||||
let orderNumber: String?
|
||||
/// 任务所属景区。
|
||||
let scenicID: Int?
|
||||
/// 订单飞行任务状态:10 待执行、20 执行中、30 成功、40 失败、50 取消、60 待确认。
|
||||
/// 订单飞行任务状态:10 待执行、20 执行中、25 素材上传中、30 成功、40 失败、50 取消、60 待确认。
|
||||
let status: Int?
|
||||
/// 服务端任务状态文案。
|
||||
let statusLabel: String?
|
||||
|
||||
@@ -10,6 +10,7 @@ enum DroneDockShootingSocketMessage {
|
||||
case opened
|
||||
case subscribed(taskID: Int, hasSnapshot: Bool)
|
||||
case snapshot(DroneDockShootingResponse)
|
||||
case subscriptionRejected(code: Int, message: String)
|
||||
case rejected(code: Int, message: String)
|
||||
case unrelated
|
||||
|
||||
@@ -24,9 +25,16 @@ enum DroneDockShootingSocketMessage {
|
||||
guard let root = json as? [String: Any],
|
||||
let code = root["code"] as? Int else { throw APIError.invalidResponse }
|
||||
if code != 100000 {
|
||||
return .rejected(code: code, message: root["msg"] as? String ?? "任务订阅失败")
|
||||
let message = root["msg"] as? String ?? "任务订阅失败"
|
||||
if let body = root["data"] as? [String: Any],
|
||||
body["type"] as? Int == 310, body["subscribed"] as? Bool == false {
|
||||
return .subscriptionRejected(code: code, message: message)
|
||||
}
|
||||
return .rejected(code: code, message: message)
|
||||
}
|
||||
guard let body = root["data"] as? [String: Any] else { throw APIError.invalidResponse }
|
||||
// 链路就绪和 310 已入站仅供诊断,不能替代正式订阅结果,即使误带了订阅字段。
|
||||
if let ack = body["ack"] as? String, ack == "ready" || ack == "received" { return .unrelated }
|
||||
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 }
|
||||
|
||||
@@ -18,6 +18,8 @@ enum DroneDockTaskDisplayPhase: String, Equatable, Sendable {
|
||||
case paused
|
||||
/// 服务端明确正在返航。
|
||||
case returning
|
||||
/// 明确返回机巢,本次拍摄仍为中断结果。
|
||||
case returned
|
||||
/// 服务端明确任务已完成。
|
||||
case completed
|
||||
/// 已确认的任务或航线执行失败。
|
||||
@@ -30,15 +32,15 @@ enum DroneDockTaskDisplayPhase: String, Equatable, Sendable {
|
||||
case readError
|
||||
}
|
||||
|
||||
/// 任务状态区可呈现的动作;开始仅在明确注入本地模拟服务时可用,真实飞控保持禁用。
|
||||
/// 本地状态区的动作,实际执行受操作服务、设备许可和防重复提交门禁共同约束。
|
||||
enum DroneDockTaskDisplayAction: Equatable, Sendable {
|
||||
/// 重新读取同一任务。
|
||||
case refresh
|
||||
/// 开始拍摄动作;真实入口无服务,只有本地模拟可提交验证。
|
||||
/// 同一任务的开始拍摄动作。
|
||||
case start
|
||||
/// 恢复拍摄占位动作,本轮禁用。
|
||||
/// 继续已暂停的任务,包括恢复返航;实际许可由设备状态和操作锁决定。
|
||||
case resume
|
||||
/// 失败后的重新召唤占位动作;尚未接入重新准备流程,始终禁用。
|
||||
/// 设备已回巢且后端门禁允许后的重新召唤。
|
||||
case retry
|
||||
/// 查看已明确完成任务的订单素材。
|
||||
case materials
|
||||
@@ -52,7 +54,7 @@ struct DroneDockTaskPresentation: Equatable, Sendable {
|
||||
let phase: DroneDockTaskDisplayPhase
|
||||
/// 阶段标题。
|
||||
let title: String
|
||||
/// 服务端说明或读取错误,完整文字可由界面展开。
|
||||
/// 本地阶段说明或实际失败原因,完整文字可由界面展开。
|
||||
let message: String
|
||||
/// 当前任务设备的状态文案。
|
||||
let deviceStatus: String
|
||||
@@ -60,7 +62,7 @@ struct DroneDockTaskPresentation: Equatable, Sendable {
|
||||
let action: DroneDockTaskDisplayAction
|
||||
/// 主动作名称,无动作时为 nil。
|
||||
let actionTitle: String?
|
||||
/// 是否可触发动作;真实开始、恢复和重新召唤保持禁用。
|
||||
/// 是否可触发动作;禁用状态仍可保留按钮作为进度提示。
|
||||
let isActionEnabled: Bool
|
||||
/// 主动作下方的真实设备限制说明,未提供时不展示。
|
||||
let actionNote: String?
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import Foundation
|
||||
|
||||
/// 标记完整任务快照实际进入 App 的通道,避免把 HTTP 与 WS 的先后关系混淆。
|
||||
enum DroneDockTaskSnapshotSource: String, Sendable {
|
||||
case http, webSocket = "websocket", unspecified
|
||||
}
|
||||
|
||||
/// 任务诊断摘要保留状态原值和明确身份;完整原始 JSON 仍由原网络日志输出。
|
||||
enum DroneDockTaskTraceFields {
|
||||
/// 把可选值表示为 JSON null,不把缺失的设备证据补成 false 或零。
|
||||
static func value<T>(_ value: T?) -> Any { value.map { $0 as Any } ?? NSNull() }
|
||||
|
||||
/// 对照后端业务阶段、飞控事实、门禁及读数来源,不重写响应对象。
|
||||
static func snapshot(_ snapshot: DroneDockShootingResponse?) -> [String: Any] {
|
||||
guard let snapshot else { return ["snapshot_present": false] }
|
||||
let control = snapshot.flightControl
|
||||
let raw = (try? JSONSerialization.jsonObject(with: Data(snapshot.dataJSON.utf8))) as? [String: Any]
|
||||
let rawControl = raw?["flight_control"] as? [String: Any]
|
||||
return [
|
||||
"snapshot_present": true, "order_flight_task_id": value(snapshot.orderFlightTaskID),
|
||||
"task_id": value(snapshot.task?.id), "oft_id": value(snapshot.orderFlightTask?.id),
|
||||
"execution_batch": value(snapshot.executionBatch), "state_version": value(snapshot.stateVersion),
|
||||
"ui_phase": value(snapshot.ui?.phase), "task_status": value(snapshot.task?.status),
|
||||
"oft_status": value(snapshot.orderFlightTask?.status),
|
||||
"wayline_status": value(snapshot.task?.waylineStatus),
|
||||
"oft_wayline_status": value(snapshot.orderFlightTask?.waylineStatus),
|
||||
"result_code": value(snapshot.orderFlightTask?.resultCode ?? snapshot.task?.resultCode),
|
||||
"plane_id": value(snapshot.currentPlane?.id), "airport_sn": value(snapshot.currentPlane?.snNumber),
|
||||
"work_status": value(snapshot.currentPlane?.workStatus),
|
||||
"flight_control": ["state": value(control?.state),
|
||||
"resolved_state": control?.resolvedState(for: snapshot.executionBatch).rawValue ?? "unknown",
|
||||
"execution_batch": value(control?.executionBatch), "is_airborne": value(control?.isAirborne),
|
||||
"dji_task_status": value(control?.djiTaskStatus),
|
||||
"pause_reason": value(control?.pauseReason), "resume_phase": value(control?.resumePhase),
|
||||
"return_reason": value(control?.returnReason), "drone_in_dock": value(control?.droneInDock),
|
||||
"can_pause": value(control?.canPause), "can_resume": value(control?.canResume),
|
||||
"can_return_home": value(control?.canReturnHome),
|
||||
"evidence": rawControl?["evidence"] ?? NSNull(),
|
||||
"pending_command": progress(control?.pendingCommand)],
|
||||
"can_start": value(snapshot.executeGate?.canExecute), "start_gate_code": value(snapshot.executeGate?.code),
|
||||
"can_restart": value(snapshot.restartGate?.canRestart), "restart_gate_code": value(snapshot.restartGate?.code),
|
||||
"metrics_count": snapshot.metrics.count, "metrics_stale": value(snapshot.metricsStale),
|
||||
"metrics_updated_at": value(snapshot.metricsUpdatedAt),
|
||||
"metrics": raw?["metrics"] ?? NSNull(),
|
||||
"metric_display_values": snapshot.metrics.map { ["key": $0.key, "value": $0.displayText] }
|
||||
]
|
||||
}
|
||||
|
||||
/// 回执和快照共用的指令标识摘要,可与 client_request_id、command_id 逐条对应。
|
||||
static func progress(_ progress: DroneDockCommandProgress?) -> Any {
|
||||
guard let progress else { return NSNull() }
|
||||
return ["command_id": value(progress.commandID), "client_request_id": value(progress.clientRequestID),
|
||||
"command": value(progress.command), "status": value(progress.status), "message": value(progress.message)]
|
||||
}
|
||||
|
||||
/// 召唤回执只摘录身份和阶段,记录是否存在初始前往状态依据。
|
||||
static func summon(_ receipt: DroneDockShootResponse?) -> [String: Any] {
|
||||
guard let text = receipt?.dataJSON,
|
||||
let object = try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] else {
|
||||
return ["receipt_present": receipt != nil, "data_present": false]
|
||||
}
|
||||
var result: [String: Any] = ["receipt_present": true, "data_present": true]
|
||||
for key in ["accepted", "order_flight_task_id", "task_id", "execution_batch", "state_version", "plane_id", "airport_sn", "ui", "flight_control"] {
|
||||
result[key] = object[key] ?? NSNull()
|
||||
}
|
||||
if let task = object["order_flight_task"] as? [String: Any] {
|
||||
result["order_flight_task"] = task.filter { ["id", "order_number", "scenic_id", "status", "wayline_task_id"].contains($0.key) }
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -161,6 +161,10 @@ final class DroneDockShootingRealtimeSession {
|
||||
log("websocket.snapshot_ignored", fields: ["reason": "old_version"])
|
||||
case .invalid: throw APIError.decodeFailed("任务快照身份或结构不一致")
|
||||
}
|
||||
case .subscriptionRejected(let code, let message):
|
||||
// 310 明确拒绝可按错误码处理,不依赖服务端说明的语言或措辞。
|
||||
if code == 100099 { deny(message) }
|
||||
else { fail(message) }
|
||||
case .rejected(let code, let message):
|
||||
if code == 100099, message.contains("无权订阅") || message.contains("飞行任务不存在") {
|
||||
deny(message)
|
||||
|
||||
@@ -54,6 +54,7 @@ final class DroneDockPreparationViewModel {
|
||||
outcomeUnknown: summonOutcomeUnknown, code: shootErrorCode)
|
||||
}
|
||||
|
||||
private let diagnostics: DroneDockTaskDiagnostics
|
||||
private let service: any DroneDockPreparationServing
|
||||
private let planeStatusService: any DroneDockPlaneStatusServing
|
||||
private let taskCreationService: any DroneDockTaskCreating
|
||||
@@ -80,7 +81,9 @@ final class DroneDockPreparationViewModel {
|
||||
taskCreationService: any DroneDockTaskCreating,
|
||||
shootService: any DroneDockShootServing,
|
||||
allowsTaskSubmission: Bool = true,
|
||||
diagnostics: DroneDockTaskDiagnostics = DroneDockTaskDiagnostics(),
|
||||
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
||||
self.diagnostics = diagnostics
|
||||
self.context = context
|
||||
self.order = order
|
||||
self.service = service
|
||||
@@ -91,6 +94,23 @@ final class DroneDockPreparationViewModel {
|
||||
self.currentContext = currentContext
|
||||
}
|
||||
|
||||
/// 准备页会话可与后续任务页入口事件关联,区分重新进入和同一次召唤。
|
||||
var diagnosticSessionID: String { diagnostics.sessionID }
|
||||
|
||||
/// 准备阶段日志只观察现有选择、门禁与请求结果,不发起任何额外请求。
|
||||
func recordPreparationEvent(_ event: String, fields: [String: Any] = [:]) {
|
||||
let summary: [String: Any] = ["source": "preparation", "scenic_id": context.scenicID,
|
||||
"order_number": DroneDockTaskTraceFields.value(order.orderNumber),
|
||||
"spot_id": DroneDockTaskTraceFields.value(selectedSpotID),
|
||||
"air_line_id": DroneDockTaskTraceFields.value(selectedRouteID),
|
||||
"created_task_id": DroneDockTaskTraceFields.value(createdTask?.taskID),
|
||||
"is_creating": isCreatingTask, "is_summoning": isSummoning,
|
||||
"creation_outcome_unknown": taskCreationOutcomeUnknown, "summon_outcome_unknown": summonOutcomeUnknown,
|
||||
"allows_task_submission": allowsTaskSubmission, "primary_action_enabled": isPrimaryActionEnabled]
|
||||
diagnostics.record(event, taskID: createdTask?.taskID ?? 0,
|
||||
fields: summary.merging(fields) { _, new in new })
|
||||
}
|
||||
|
||||
/// 当前阶段只创建待飞任务,不以设备电量或位置作为创建任务条件。
|
||||
var canCreateTask: Bool {
|
||||
guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
|
||||
@@ -139,6 +159,7 @@ final class DroneDockPreparationViewModel {
|
||||
/// 主按钮串接创建与召唤;已有任务跳过创建,成功后的导航由页面处理。
|
||||
@MainActor
|
||||
func prepareAndSummon(onStateChange: @escaping @MainActor () -> Void = {}) async {
|
||||
recordPreparationEvent("preparation.primary_requested")
|
||||
// 禁飞调试在整条链开始前阻断,避免先残留真实待飞任务再拦截召唤。
|
||||
guard allowsTaskSubmission, isPrimaryActionEnabled else { return }
|
||||
primaryActionGeneration &+= 1
|
||||
@@ -180,10 +201,13 @@ final class DroneDockPreparationViewModel {
|
||||
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
|
||||
do {
|
||||
didSendSummon = true
|
||||
recordPreparationEvent("summon.sending")
|
||||
let response = try await shootService.shoot(taskID: taskID)
|
||||
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
|
||||
shootResponse = response
|
||||
DroneDockDiagnostics.event("summon.receipt_accepted", taskID: taskID)
|
||||
recordPreparationEvent("summon.receipt_accepted", fields: ["receipt": DroneDockTaskTraceFields.summon(response),
|
||||
"travel_transition_allowed": response.confirmsTravel(taskID: taskID, orderNumber: order.orderNumber,
|
||||
scenicID: context.scenicID)])
|
||||
hasSubmittedSummon = true
|
||||
summonOutcomeUnknown = false
|
||||
} catch {
|
||||
@@ -191,6 +215,7 @@ final class DroneDockPreparationViewModel {
|
||||
didSendSummon = false
|
||||
}
|
||||
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
|
||||
recordPreparationEvent("summon.failed_or_unknown", fields: ["error": DroneDockDiagnostics.errorFields(error)])
|
||||
if error is DeviceCommandDebugBlockedError {
|
||||
shootErrorMessage = DeviceCommandDebugPolicy.blockedMessage
|
||||
} else if case let APIError.serverCode(code, message) = error {
|
||||
@@ -223,6 +248,7 @@ final class DroneDockPreparationViewModel {
|
||||
/// 点击后先校验最新购买配置,再发送一次创建请求;成功留在准备页供核对。
|
||||
@MainActor
|
||||
func createTask(onStateChange: @escaping @MainActor () -> Void = {}) async {
|
||||
recordPreparationEvent("create.requested", fields: ["allowed": canCreateTask])
|
||||
guard allowsTaskSubmission, canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID,
|
||||
let number = order.orderNumber, let projectID = order.projectID else { return }
|
||||
taskCreationGeneration &+= 1
|
||||
@@ -261,6 +287,7 @@ final class DroneDockPreparationViewModel {
|
||||
}
|
||||
guard acceptsTaskCreation(requestGeneration) else { return }
|
||||
didSendTaskCreation = true
|
||||
recordPreparationEvent("create.sending")
|
||||
let response = try await taskCreationService.createTask(scenicID: context.scenicID,
|
||||
orderNumber: number, spotID: spotID, airLineID: routeID)
|
||||
guard acceptsTaskCreation(requestGeneration) else { return }
|
||||
@@ -269,7 +296,7 @@ final class DroneDockPreparationViewModel {
|
||||
throw APIError.decodeFailed("创建回执与当前订单或项目不一致,请核对任务")
|
||||
}
|
||||
createdTask = response
|
||||
DroneDockDiagnostics.event("create.receipt_accepted", taskID: response.taskID)
|
||||
recordPreparationEvent("create.receipt_accepted", fields: ["receipt_task_id": DroneDockTaskTraceFields.value(response.taskID)])
|
||||
hasCreatedTask = true
|
||||
taskCreationOutcomeUnknown = false
|
||||
} catch {
|
||||
@@ -277,6 +304,7 @@ final class DroneDockPreparationViewModel {
|
||||
didSendTaskCreation = false
|
||||
}
|
||||
guard acceptsTaskCreation(requestGeneration) else { return }
|
||||
recordPreparationEvent("create.failed_or_unknown", fields: ["error": DroneDockDiagnostics.errorFields(error)])
|
||||
if error is DeviceCommandDebugBlockedError {
|
||||
taskCreationErrorMessage = DeviceCommandDebugPolicy.blockedMessage
|
||||
} else if didSendTaskCreation {
|
||||
@@ -580,16 +608,16 @@ final class DroneDockPreparationViewModel {
|
||||
}
|
||||
|
||||
private func markSummonUnknown(reason: String? = nil) {
|
||||
DroneDockDiagnostics.event("summon.outcome_unknown", taskID: createdTask?.taskID)
|
||||
summonOutcomeUnknown = true
|
||||
shootErrorCode = nil
|
||||
shootErrorMessage = (reason.map { "\($0)。" } ?? "") + "召唤结果待核对,请先核对任务状态,勿重复提交"
|
||||
recordPreparationEvent("summon.outcome_unknown")
|
||||
}
|
||||
|
||||
private func markTaskCreationUnknown(reason: String? = nil) {
|
||||
DroneDockDiagnostics.event("taskcreation.outcome_unknown", taskID: createdTask?.taskID)
|
||||
taskCreationOutcomeUnknown = true
|
||||
taskCreationErrorMessage = (reason.map { "\($0)。" } ?? "") + "创建结果待核对,请先查看订单任务,勿重复提交"
|
||||
recordPreparationEvent("taskcreation.outcome_unknown")
|
||||
}
|
||||
|
||||
private static func message(for error: Error) -> String? {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,8 +16,6 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController
|
||||
private let downloadSourceDescription: String?
|
||||
private let downloadIsSimulated: Bool
|
||||
private let taskControllerFactory: (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||
private var taskButton: UIBarButtonItem?
|
||||
|
||||
/// 元数据与媒体分区独立,任务没有素材时也保留其状态。
|
||||
private enum Section: Hashable { case order, filters, summary, task(Int), media(Int), message }
|
||||
@@ -45,16 +43,12 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)? = nil,
|
||||
downloadViewModel: DroneDockMaterialDownloadViewModel? = nil,
|
||||
downloadSourceDescription: String? = nil,
|
||||
downloadIsSimulated: Bool = false,
|
||||
taskControllerFactory: ((Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
|
||||
downloadIsSimulated: Bool = false) {
|
||||
self.viewModel = viewModel
|
||||
self.downloadViewModel = downloadViewModel ?? DroneDockMaterialDownloadViewModel(
|
||||
isContextValid: { [weak viewModel] in viewModel?.acceptsDownloadContext() == true })
|
||||
self.downloadSourceDescription = downloadSourceDescription
|
||||
self.downloadIsSimulated = downloadIsSimulated
|
||||
self.taskControllerFactory = taskControllerFactory ?? { id, order, context in
|
||||
DroneDockShootingTaskEntry.makeController(taskID: id, order: order, context: context)
|
||||
}
|
||||
self.thumbnailProvider = thumbnailProvider
|
||||
self.mediaPreviewControllerFactory = mediaPreviewControllerFactory
|
||||
self.deliveryControllerFactory = deliveryControllerFactory ?? DroneDockDeliveryEntry.makeController
|
||||
@@ -73,11 +67,7 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain, target: self, action: #selector(refreshTapped))
|
||||
refresh.accessibilityLabel = "刷新素材状态"
|
||||
refresh.accessibilityIdentifier = "drone.materials.remote.refresh"
|
||||
let tasks = UIBarButtonItem(title: "查看任务", style: .plain, target: self, action: #selector(viewTasksTapped))
|
||||
tasks.accessibilityIdentifier = "drone.materials.remote.viewTasks"
|
||||
tasks.isEnabled = false
|
||||
taskButton = tasks
|
||||
navigationItem.rightBarButtonItems = [refresh, tasks]
|
||||
navigationItem.rightBarButtonItems = [refresh]
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
@@ -168,8 +158,8 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
return cell
|
||||
case .filter(let id):
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "filter", for: path) as! DroneMaterialFilterCell
|
||||
let title = id.flatMap { id in self.viewModel.spots.first { $0.id == id } }.map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位"
|
||||
cell.apply(title: title, id: id.map(String.init), selected: id == self.displayedSpotID, locked: self.viewModel.detail == nil || self.selectionLocked)
|
||||
cell.apply(title: self.filterTitle(for: id), id: id.map(String.init), selected: id == self.displayedSpotID,
|
||||
locked: self.viewModel.detail == nil || self.selectionLocked, wrapsTitle: true)
|
||||
return cell
|
||||
case .task(let taskID):
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "record", for: path) as! DroneDockMaterialRecordCell
|
||||
@@ -228,8 +218,20 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
guard sections.indices.contains(index) else { return nil }
|
||||
switch sections[index] {
|
||||
case .filters:
|
||||
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
|
||||
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .estimated(104), heightDimension: .absolute(36)), subitems: [item])
|
||||
let maximumWidth = min(200, max(1, environment.container.effectiveContentSize.width - 32))
|
||||
let sizes = dataSource.snapshot().itemIdentifiers(inSection: .filters).compactMap { item -> CGSize? in
|
||||
guard case .filter(let id) = item else { return nil }
|
||||
return DroneMaterialFilterCell.wrappedSize(title: self.filterTitle(for: id), maximumWidth: maximumWidth)
|
||||
}
|
||||
let width = sizes.reduce(0) { $0 + $1.width } + CGFloat(max(0, sizes.count - 1)) * 8
|
||||
let height = sizes.map(\.height).max() ?? 40
|
||||
let group = NSCollectionLayoutGroup.custom(layoutSize: .init(widthDimension: .absolute(max(1, width)), heightDimension: .absolute(height))) { _ in
|
||||
var x: CGFloat = 0
|
||||
return sizes.map { size in
|
||||
defer { x += size.width + 8 }
|
||||
return NSCollectionLayoutGroupCustomItem(frame: CGRect(x: x, y: 0, width: size.width, height: size.height))
|
||||
}
|
||||
}
|
||||
let section = NSCollectionLayoutSection(group: group)
|
||||
section.orthogonalScrollingBehavior = .continuous
|
||||
section.interGroupSpacing = 8
|
||||
@@ -267,7 +269,6 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
|
||||
private func applySnapshot(animated: Bool) {
|
||||
guard dataSource != nil else { return }
|
||||
taskButton?.isEnabled = operation == nil && !selectionLocked && viewModel.canViewRecordedTasks
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
||||
if viewModel.detail != nil {
|
||||
snapshot.appendSections([.order, .filters])
|
||||
@@ -375,7 +376,6 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
|
||||
private func updateDownloadFooter() {
|
||||
navigationItem.rightBarButtonItem?.isEnabled = !selectionLocked
|
||||
taskButton?.isEnabled = operation == nil && !selectionLocked && viewModel.canViewRecordedTasks
|
||||
let model = downloadViewModel
|
||||
let identifier = "drone.materials.remote.download"
|
||||
switch model.phase {
|
||||
@@ -401,31 +401,6 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
}
|
||||
}
|
||||
|
||||
/// 从张工已返回的任务中选择并进入状态页,不创建新任务或调用召唤接口。
|
||||
@objc private func viewTasksTapped() {
|
||||
guard operation == nil, !selectionLocked, viewModel.canViewRecordedTasks,
|
||||
viewModel.acceptsDownloadContext(), presentedViewController == nil else { return }
|
||||
if let task = viewModel.tasks.first, viewModel.tasks.count == 1 {
|
||||
openRecordedTask(id: task.id)
|
||||
return
|
||||
}
|
||||
let sheet = UIAlertController(title: "选择拍摄任务", message: nil, preferredStyle: .actionSheet)
|
||||
for task in viewModel.tasks {
|
||||
let spot = task.spotName.isEmpty ? "拍摄任务" : task.spotName
|
||||
let sequence = task.sequence.map { "第\($0)次拍摄" } ?? "拍摄记录"
|
||||
let title = "\(spot) · \(sequence)" + (task.createdAt.map { " · \($0)" } ?? "")
|
||||
sheet.addAction(UIAlertAction(title: title, style: .default) { [weak self] _ in self?.openRecordedTask(id: task.id) })
|
||||
}
|
||||
sheet.addAction(UIAlertAction(title: "取消", style: .cancel))
|
||||
present(sheet, animated: true)
|
||||
}
|
||||
|
||||
private func openRecordedTask(id: Int) {
|
||||
guard operation == nil, !selectionLocked, viewModel.taskForViewing(id: id) != nil,
|
||||
navigationController?.topViewController === self else { return }
|
||||
navigationController?.pushViewController(taskControllerFactory(id, viewModel.order, viewModel.context), animated: true)
|
||||
}
|
||||
|
||||
private func previewFile(taskID: Int, fileID: Int) {
|
||||
guard operation == nil, let file = task(taskID)?.materials.first(where: { $0.id == fileID }), let url = file.previewURL else { return }
|
||||
preview(url: url, isVideo: file.fileType == 2, title: file.fileName ?? "原素材")
|
||||
@@ -447,6 +422,11 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
DroneDockHomeMetric.usableText(value) ?? fallback
|
||||
}
|
||||
|
||||
private func filterTitle(for id: Int?) -> String {
|
||||
id.flatMap { id in viewModel.spots.first { $0.id == id } }
|
||||
.map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位"
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -140,12 +140,14 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
super.viewWillAppear(animated)
|
||||
isPageVisible = true
|
||||
isApplicationActive = UIApplication.shared.applicationState == .active
|
||||
logPreparationEvent("preparation.page.appeared")
|
||||
refreshPreparation()
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
isPageVisible = false
|
||||
logPreparationEvent("preparation.page.disappeared", fields: ["moving_from_parent": isMovingFromParent])
|
||||
stopPlaneStatusPolling()
|
||||
refreshTask?.cancel()
|
||||
creationTask?.cancel()
|
||||
@@ -183,7 +185,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
|
||||
/// 首次创建并召唤;成功后进入原任务,再次查看不经过创建或召唤接口。
|
||||
private func createSelectedTask() {
|
||||
DroneDockDiagnostics.event("preparation.confirm_tapped", taskID: viewModel.createdTask?.taskID, fields: [
|
||||
logPreparationEvent("preparation.confirm_tapped", fields: [
|
||||
"order_number": viewModel.order.orderNumber as Any? ?? NSNull(),
|
||||
"scenic_id": viewModel.context.scenicID,
|
||||
"spot_id": viewModel.selectedSpotID as Any? ?? NSNull(),
|
||||
@@ -191,12 +193,18 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
"enabled": viewModel.isPrimaryActionEnabled,
|
||||
"blocked": viewModel.isTaskSubmissionBlocked
|
||||
])
|
||||
guard !isRefreshing, !isStartingCreation else { return }
|
||||
guard !isRefreshing, !isStartingCreation else {
|
||||
logPreparationEvent("preparation.confirm_rejected", fields: ["reason": "refresh_or_submission_in_progress"])
|
||||
return
|
||||
}
|
||||
if viewModel.canOpenShootingTask {
|
||||
_ = openShootingTask(automatically: false)
|
||||
return
|
||||
}
|
||||
guard viewModel.isPrimaryActionEnabled else { return }
|
||||
guard viewModel.isPrimaryActionEnabled else {
|
||||
logPreparationEvent("preparation.confirm_rejected", fields: ["reason": "primary_action_disabled"])
|
||||
return
|
||||
}
|
||||
isStartingCreation = true
|
||||
applySnapshot(animated: false)
|
||||
creationTask = Task { @MainActor [weak self] in
|
||||
@@ -204,6 +212,10 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
await self.viewModel.prepareAndSummon { [weak self] in self?.applySnapshot(animated: false) }
|
||||
guard !Task.isCancelled else { return }
|
||||
self.isStartingCreation = false
|
||||
self.logPreparationEvent("preparation.submission_presented", fields: [
|
||||
"has_summon_receipt": self.viewModel.shootResponse != nil,
|
||||
"can_open_task": self.viewModel.canOpenShootingTask,
|
||||
"error_message": self.viewModel.errorMessage as Any? ?? NSNull()])
|
||||
if self.openShootingTask(automatically: true) { return }
|
||||
self.applySnapshot(animated: true) { [weak self] in
|
||||
guard let self,
|
||||
@@ -230,11 +242,23 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask,
|
||||
let taskID = viewModel.createdTask?.taskID,
|
||||
let navigationController, navigationController.topViewController === self,
|
||||
!automatically || (viewModel.shootResponse != nil && automaticallyOpenedTaskID != taskID) else { return false }
|
||||
DroneDockDiagnostics.event("navigation.open_task", taskID: taskID)
|
||||
!automatically || (viewModel.shootResponse != nil && automaticallyOpenedTaskID != taskID) else {
|
||||
logPreparationEvent("navigation.open_task_rejected", fields: ["automatic": automatically,
|
||||
"can_open_task": viewModel.canOpenShootingTask,
|
||||
"is_navigation_top": navigationController?.topViewController === self,
|
||||
"has_summon_receipt": viewModel.shootResponse != nil,
|
||||
"previously_opened_task_id": automaticallyOpenedTaskID as Any? ?? NSNull()])
|
||||
return false
|
||||
}
|
||||
automaticallyOpenedTaskID = taskID
|
||||
let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context)
|
||||
let stack = navigationController.viewControllers
|
||||
let fields: [String: Any] = ["automatic": automatically, "task_id": taskID,
|
||||
"preparation_session_id": viewModel.diagnosticSessionID,
|
||||
"replaces_preparation": stack.count > 1,
|
||||
"navigation_stack_before": stack.map { String(describing: type(of: $0)) }]
|
||||
logPreparationEvent("navigation.open_task", fields: fields)
|
||||
(controller as? DroneDockShootingTaskViewController)?.recordNavigationEntry(source: "preparation", fields: fields)
|
||||
if stack.count > 1 {
|
||||
navigationController.setViewControllers(Array(stack.dropLast()) + [controller], animated: true)
|
||||
} else {
|
||||
@@ -278,6 +302,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
|
||||
@objc private func applicationWillResignActive() {
|
||||
isApplicationActive = false
|
||||
logPreparationEvent("preparation.app.inactive")
|
||||
stopPlaneStatusPolling()
|
||||
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation,
|
||||
isLocalSimulation: simulationRecordsProvider != nil)
|
||||
@@ -285,9 +310,23 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
|
||||
@objc private func applicationDidBecomeActive() {
|
||||
isApplicationActive = true
|
||||
logPreparationEvent("preparation.app.active")
|
||||
startPlaneStatusPolling()
|
||||
}
|
||||
|
||||
/// 准备页 UI 事件沿用业务会话,可与后续任务页的导航记录关联。
|
||||
private func logPreparationEvent(_ name: String, fields: [String: Any] = [:]) {
|
||||
var fields = fields
|
||||
fields["source"] = simulationRecordsProvider == nil ? "preparation_page" : "local_simulation"
|
||||
fields["task_id"] = viewModel.createdTask?.taskID as Any? ?? NSNull()
|
||||
fields["page_visible"] = isPageVisible
|
||||
fields["app_active"] = isApplicationActive
|
||||
fields["refreshing"] = isRefreshing
|
||||
fields["submitting"] = isStartingCreation
|
||||
fields["debug_flight_blocked"] = DeviceCommandDebugPolicy.blocksFlightRequests
|
||||
viewModel.recordPreparationEvent(name, fields: fields)
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, path, item in
|
||||
guard let self else { return nil }
|
||||
|
||||
@@ -29,7 +29,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
private var pollGeneration = 0
|
||||
private var refreshTask: Task<Void, Never>?
|
||||
private var startTask: Task<Void, Never>?
|
||||
private var commandTask: Task<Void, Never>?
|
||||
private var commandTasks: [UUID: Task<Void, Never>] = [:]
|
||||
private var commandAttemptIDs: [DroneDockSafetyCommand: UUID] = [:]
|
||||
private var submittingCommands: Set<DroneDockSafetyCommand> = []
|
||||
private var resummonTask: Task<Void, Never>?
|
||||
private var liveTask: Task<Void, Never>?
|
||||
private var liveParameterTask: Task<Void, Never>?
|
||||
@@ -40,16 +42,19 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
private var isApplicationActive = false
|
||||
private var isRequesting = false
|
||||
private var isStartingAction = false
|
||||
private var isSendingSafetyAction = false
|
||||
private var isSendingSafetyAction: Bool { !submittingCommands.isEmpty }
|
||||
private var isResummoningAction = false
|
||||
private var wasRealtimeLive = false
|
||||
private let coverURL: URL?
|
||||
private var finishedExecutions: Set<String> = []
|
||||
private var stoppedLiveExecutionTitles: [String: String] = [:]
|
||||
private var displayedCompletionIDs: Set<String> = []
|
||||
private var completionNotice: DroneDockRecordingCompletionView?
|
||||
private let countdownDelay: @Sendable () async throws -> Void
|
||||
private var countdownTask: Task<Void, Never>?
|
||||
private var countdownGeneration = 0
|
||||
private var diagnosticStateData: [String: Data] = [:]
|
||||
private var countdownDiagnosticKey: String?
|
||||
private var entrySource = "existing_task_or_direct"
|
||||
|
||||
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
|
||||
init(viewModel: DroneDockShootingTaskViewModel,
|
||||
@@ -83,7 +88,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
hidesBottomBarWhenPushed = true
|
||||
realtimeSession?.onSnapshot = { [weak self] snapshot in
|
||||
guard let self, self.isPageVisible, self.isApplicationActive else { return .invalid }
|
||||
let result = self.viewModel.applyTaskSnapshot(snapshot)
|
||||
let result = self.viewModel.applyTaskSnapshot(snapshot, source: .webSocket)
|
||||
self.applySnapshot()
|
||||
return result
|
||||
}
|
||||
@@ -95,11 +100,17 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 仅记录导航来源与上游诊断会话,不改变任务身份、页面加载或设备操作。
|
||||
func recordNavigationEntry(source: String, fields: [String: Any] = [:]) {
|
||||
entrySource = source
|
||||
logEvent("navigation.task_entry", fields: fields)
|
||||
}
|
||||
|
||||
deinit {
|
||||
pollTask?.cancel()
|
||||
refreshTask?.cancel()
|
||||
startTask?.cancel()
|
||||
commandTask?.cancel()
|
||||
commandTasks.values.forEach { $0.cancel() }
|
||||
resummonTask?.cancel()
|
||||
liveTask?.cancel()
|
||||
liveParameterTask?.cancel()
|
||||
@@ -192,6 +203,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
/// 只按设备可用尺寸调整固定区域,数据、错误和加载状态不会改变它们的高度。
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
defer { recordRenderedState() }
|
||||
let availableHeight = view.bounds.height - view.safeAreaInsets.top - view.safeAreaInsets.bottom
|
||||
let compact = availableHeight < 680
|
||||
let inset = view.safeAreaInsets.bottom
|
||||
@@ -211,8 +223,11 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
statusView.onDetails = { [weak self] in self?.showStatusDetails() }
|
||||
safetyView.onCommand = { [weak self] command in self?.safetyCommandTriggered(command) }
|
||||
feedPlaceholder.onRequest = { [weak self] in self?.refreshLiveIfVisible() }
|
||||
feedPlaceholder.onDiagnosticEvent = { [weak self] event, fields in self?.logEvent(event, fields: fields) }
|
||||
feedPlaceholder.onPlaybackEvent = { [weak self] event, sessionID in
|
||||
guard let self, self.isPageVisible, self.isApplicationActive else { return }
|
||||
guard let self else { return }
|
||||
self.recordPlaybackEvent(event, sessionID: sessionID)
|
||||
guard self.isPageVisible, self.isApplicationActive else { return }
|
||||
self.liveViewModel.receivePlaybackEvent(event, sessionID: sessionID)
|
||||
if self.liveViewModel.playbackSessionID == nil {
|
||||
self.liveParameterTask?.cancel()
|
||||
@@ -230,8 +245,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
override func viewDidAppear(_ animated: Bool) {
|
||||
super.viewDidAppear(animated)
|
||||
isPageVisible = true
|
||||
logEvent("page.appeared")
|
||||
isApplicationActive = UIApplication.shared.applicationState == .active
|
||||
logEvent("page.appeared", fields: ["navigation_stack": navigationController?.viewControllers.map { String(describing: type(of: $0)) } ?? []])
|
||||
refreshTaskIfVisible()
|
||||
refreshLiveIfVisible(automatically: true)
|
||||
}
|
||||
@@ -241,25 +256,30 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
super.viewWillDisappear(animated)
|
||||
isPageVisible = false
|
||||
dismissCompletionNotice()
|
||||
logEvent("page.disappeared")
|
||||
logEvent("page.disappeared", fields: ["moving_from_parent": isMovingFromParent, "being_dismissed": isBeingDismissed])
|
||||
cancelRefresh()
|
||||
stopLive()
|
||||
}
|
||||
|
||||
private func applySnapshot() {
|
||||
guard isViewLoaded else { return }
|
||||
if viewModel.isRecordingFinished { finishedExecutions.insert(viewModel.recordingExecutionID) }
|
||||
let recordingFinished = finishedExecutions.contains(viewModel.recordingExecutionID)
|
||||
if viewModel.shouldStopLiveReception {
|
||||
stoppedLiveExecutionTitles[viewModel.recordingExecutionID] = viewModel.isRecordingFinished
|
||||
? "拍摄已完成" : "无人机已返回机巢"
|
||||
}
|
||||
let stoppedLiveTitle = stoppedLiveExecutionTitles[viewModel.recordingExecutionID]
|
||||
let liveReceptionEnded = stoppedLiveTitle != nil
|
||||
if !viewModel.shouldPresentRecordingCompletion { dismissCompletionNotice() }
|
||||
if recordingFinished, liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil {
|
||||
if liveReceptionEnded, liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil {
|
||||
stopLive()
|
||||
}
|
||||
feedPlaceholder.showRecordingCover(recordingFinished, url: coverURL)
|
||||
feedPlaceholder.showRecordingCover(liveReceptionEnded, url: coverURL,
|
||||
title: stoppedLiveTitle ?? "拍摄已完成")
|
||||
let loading = (viewModel.response == nil && (isRequesting || viewModel.isLoading))
|
||||
|| isStartingAction || viewModel.isStartingShooting
|
||||
|| isSendingSafetyAction || viewModel.isSendingCommand || isResummoningAction || viewModel.isResummoning
|
||||
|| isResummoningAction || viewModel.isResummoning
|
||||
feedPlaceholder.apply(liveViewModel)
|
||||
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive && !recordingFinished)
|
||||
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive && !liveReceptionEnded)
|
||||
taskTitleLabel.text = viewModel.title
|
||||
subtitleLabel.text = viewModel.subtitle + (viewModel.response?.metricsStale == true ? " · 读数已过期" : "")
|
||||
let telemetry = viewModel.telemetry
|
||||
@@ -270,21 +290,25 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
let value = loading && viewModel.response == nil && presentation.phase != .navigating ? DroneDockTaskPresentation(
|
||||
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
|
||||
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : presentation
|
||||
statusView.apply(value, isRefreshing: loading)
|
||||
statusView.apply(value, isRefreshing: loading, isPrimaryActionLoading: value.action == .resume
|
||||
&& (submittingCommands.contains(.resume) || viewModel.isCommandLoading(.resume)))
|
||||
updateArrivalCountdown()
|
||||
safetyView.apply(model: viewModel, isSimulation: simulationRecordsProvider != nil,
|
||||
isInteractive: isPageVisible && isApplicationActive && !loading)
|
||||
isInteractive: isPageVisible && isApplicationActive && !loading,
|
||||
submittingCommands: submittingCommands)
|
||||
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
|
||||
navigationItem.rightBarButtonItems?.forEach { $0.isEnabled = isPageVisible && isApplicationActive && !loading }
|
||||
navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil
|
||||
recordRenderedState()
|
||||
presentCompletionNoticeIfNeeded()
|
||||
refreshLiveIfVisible(automatically: true)
|
||||
}
|
||||
|
||||
/// 倒计时只更新独立秒数标签;网络读取、飞控及后端阶段仍由原有流程驱动。
|
||||
/// 倒计时只更新开拍按钮文案;网络读取、飞控及后端阶段仍由原有流程驱动。
|
||||
private func updateArrivalCountdown() {
|
||||
let seconds = viewModel.countdownRemainingSeconds
|
||||
statusView.updateCountdown(seconds: seconds)
|
||||
recordCountdownState(seconds)
|
||||
guard isPageVisible, isApplicationActive, let seconds, seconds > 0 else {
|
||||
stopArrivalCountdown()
|
||||
return
|
||||
@@ -300,6 +324,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
self.isPageVisible, self.isApplicationActive else { return }
|
||||
let remaining = self.viewModel.countdownRemainingSeconds
|
||||
self.statusView.updateCountdown(seconds: remaining)
|
||||
self.recordCountdownState(remaining)
|
||||
if remaining == nil || remaining == 0 {
|
||||
self.countdownTask = nil
|
||||
return
|
||||
@@ -321,10 +346,15 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
displayedCompletionIDs.insert(id)
|
||||
let notice = DroneDockRecordingCompletionView()
|
||||
completionNotice = notice
|
||||
notice.onLater = { [weak self] in self?.dismissCompletionNotice() }
|
||||
logEvent("ui.completion_notice.shown")
|
||||
notice.onLater = { [weak self] in
|
||||
self?.logEvent("ui.completion_notice.later")
|
||||
self?.dismissCompletionNotice()
|
||||
}
|
||||
notice.onViewMaterials = { [weak self] in
|
||||
guard let self, self.isPageVisible, self.isApplicationActive,
|
||||
self.viewModel.recordingExecutionID == id else { return }
|
||||
self.logEvent("ui.completion_notice.view_materials")
|
||||
self.dismissCompletionNotice()
|
||||
self.openMaterials()
|
||||
}
|
||||
@@ -335,6 +365,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
}
|
||||
|
||||
private func dismissCompletionNotice() {
|
||||
if completionNotice != nil { logEvent("ui.completion_notice.dismissed") }
|
||||
completionNotice?.removeFromSuperview()
|
||||
completionNotice = nil
|
||||
}
|
||||
@@ -352,10 +383,15 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
"enabled": viewModel.presentation.isActionEnabled])
|
||||
guard isPageVisible, isApplicationActive,
|
||||
!isStartingAction, !viewModel.isStartingShooting,
|
||||
!isSendingSafetyAction, !viewModel.isSendingCommand,
|
||||
!isResummoningAction, !viewModel.isResummoning else { return }
|
||||
!isResummoningAction, !viewModel.isResummoning else {
|
||||
logEvent("action.primary.rejected", fields: ["reason": "page_or_submission_guard", "ui": statusView.diagnosticFields])
|
||||
return
|
||||
}
|
||||
let state = viewModel.presentation
|
||||
guard state.isActionEnabled else { return }
|
||||
guard state.isActionEnabled else {
|
||||
logEvent("action.primary.rejected", fields: ["reason": "presentation_action_disabled", "ui": statusView.diagnosticFields])
|
||||
return
|
||||
}
|
||||
switch state.action {
|
||||
case .refresh:
|
||||
refreshTaskIfVisible()
|
||||
@@ -365,7 +401,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
resummonIfAllowed()
|
||||
case .materials:
|
||||
openMaterials()
|
||||
case .resume, .none:
|
||||
case .resume:
|
||||
safetyCommandTriggered(.resume)
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -394,10 +432,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
private func refreshTaskIfVisible(isPolling: Bool = false) {
|
||||
guard isPageVisible, isApplicationActive, viewModel.readAccessError == nil, !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
|
||||
@@ -424,11 +460,10 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
cancelScheduledPoll()
|
||||
guard isPageVisible, isApplicationActive, viewModel.canContinuePolling,
|
||||
realtimeSession?.state != .live,
|
||||
!isRequesting, !isStartingAction, !isSendingSafetyAction, !isResummoningAction else { return }
|
||||
!isRequesting, !isStartingAction, !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 }
|
||||
@@ -438,7 +473,6 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
}
|
||||
|
||||
private func cancelScheduledPoll() {
|
||||
if pollTask != nil { logEvent("poll.cancelled") }
|
||||
pollGeneration &+= 1
|
||||
pollTask?.cancel()
|
||||
pollTask = nil
|
||||
@@ -464,12 +498,13 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
refreshTask = nil
|
||||
startTask?.cancel()
|
||||
startTask = nil
|
||||
commandTask?.cancel()
|
||||
commandTask = nil
|
||||
commandTasks.values.forEach { $0.cancel() }
|
||||
commandTasks.removeAll()
|
||||
commandAttemptIDs.removeAll()
|
||||
submittingCommands.removeAll()
|
||||
resummonTask?.cancel()
|
||||
resummonTask = nil
|
||||
isResummoningAction = false
|
||||
isSendingSafetyAction = false
|
||||
isStartingAction = false
|
||||
isRequesting = false
|
||||
viewModel.invalidate(preservingSnapshot: true)
|
||||
@@ -477,6 +512,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
}
|
||||
|
||||
private func connectionStateChanged(_ state: DroneDockShootingRealtimeSession.State) {
|
||||
logChangedEvent("page.realtime_state", fields: ["state": String(describing: state)])
|
||||
guard isPageVisible, isApplicationActive else { return }
|
||||
switch state {
|
||||
case .live:
|
||||
@@ -564,12 +600,12 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
/// 可见且活跃时自动开启一次;失败可手动重试,不随 shooting/Socket 刷新重复请求。
|
||||
private func refreshLiveIfVisible(automatically: Bool = false, keepingPlayback: Bool = false) {
|
||||
guard viewModel.response != nil, viewModel.readAccessError == nil,
|
||||
!finishedExecutions.contains(viewModel.recordingExecutionID), !viewModel.isRecordingFinished else { return }
|
||||
stoppedLiveExecutionTitles[viewModel.recordingExecutionID] == nil, !viewModel.shouldStopLiveReception else { return }
|
||||
guard !automatically || liveViewModel.loadsAutomatically else { return }
|
||||
guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return }
|
||||
liveParameterTask?.cancel()
|
||||
liveParameterTask = nil
|
||||
logEvent("live.request", fields: ["automatic": automatically])
|
||||
logEvent("live.request", fields: ["automatic": automatically, "keeping_playback": keepingPlayback])
|
||||
liveGeneration &+= 1
|
||||
let generation = liveGeneration
|
||||
liveTask = Task { @MainActor [weak self] in
|
||||
@@ -602,6 +638,10 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
|
||||
/// 离页或进入后台立即释放播放器,使旧图传响应无法恢复播放。
|
||||
private func stopLive() {
|
||||
if liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil {
|
||||
logEvent("live.reception_stopping", fields: ["recording_finished": viewModel.isRecordingFinished,
|
||||
"task_requires_stop": viewModel.shouldStopLiveReception, "ui": feedPlaceholder.diagnosticFields])
|
||||
}
|
||||
liveGeneration &+= 1
|
||||
liveParameterTask?.cancel()
|
||||
liveParameterTask = nil
|
||||
@@ -616,49 +656,62 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) {
|
||||
logEvent("action.safety", fields: ["command": command.rawValue, "enabled": viewModel.canSendCommand(command)])
|
||||
guard allowsControlActions, isPageVisible, isApplicationActive,
|
||||
presentedViewController == nil, !isSendingSafetyAction, !isStartingAction,
|
||||
!isResummoningAction, viewModel.canSendCommand(command) else { return }
|
||||
presentedViewController == nil, !submittingCommands.contains(command), !isStartingAction,
|
||||
!isResummoningAction, viewModel.canSendCommand(command) else {
|
||||
logSafetyRejection(command, stage: "tap")
|
||||
return
|
||||
}
|
||||
if command == .returnHome {
|
||||
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: .cancel) { [weak self] _ in
|
||||
self?.logEvent("action.return_confirmation.cancelled")
|
||||
})
|
||||
alert.addAction(UIAlertAction(title: simulated ? "模拟返航" : "立即返航", style: .destructive) { [weak self] _ in
|
||||
self?.logEvent("action.return_confirmation.confirmed")
|
||||
self?.sendSafetyCommand(command)
|
||||
})
|
||||
logEvent("action.return_confirmation.shown")
|
||||
present(alert, animated: true)
|
||||
} else {
|
||||
sendSafetyCommand(command)
|
||||
}
|
||||
}
|
||||
|
||||
/// 同步锁覆盖异步调度间隙;界面保留旧快照,只有同任务回查成功才更新阶段。
|
||||
/// 同步锁只覆盖同一按钮;不同安全动作可各自等待,设备确认由 ViewModel 和快照处理。
|
||||
private func sendSafetyCommand(_ command: DroneDockSafetyCommand) {
|
||||
guard allowsControlActions, isPageVisible, isApplicationActive,
|
||||
!isSendingSafetyAction, !isStartingAction, !isResummoningAction,
|
||||
viewModel.canSendCommand(command) else { return }
|
||||
!submittingCommands.contains(command), !isStartingAction, !isResummoningAction,
|
||||
viewModel.canSendCommand(command) else {
|
||||
logSafetyRejection(command, stage: "submit")
|
||||
return
|
||||
}
|
||||
cancelPendingReadForAction()
|
||||
let generation = requestGeneration
|
||||
isSendingSafetyAction = true
|
||||
let attemptID = UUID()
|
||||
logEvent("action.safety.submitting", fields: ["command": command.rawValue, "ui_attempt_id": attemptID.uuidString])
|
||||
commandAttemptIDs[command] = attemptID
|
||||
submittingCommands.insert(command)
|
||||
applySnapshot()
|
||||
commandTask = Task { @MainActor [weak self] in
|
||||
commandTasks[attemptID] = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await self.viewModel.sendCommand(command) { [weak self] in self?.applySnapshot() }
|
||||
await self.viewModel.sendCommand(command) { [weak self] in
|
||||
guard let self, self.commandAttemptIDs[command] == attemptID else { return }
|
||||
// ViewModel 已建立本次操作后,加载状态完全交由其管理;后续只读回查不延长动画。
|
||||
self.submittingCommands.remove(command)
|
||||
self.applySnapshot()
|
||||
}
|
||||
self.commandTasks.removeValue(forKey: attemptID)
|
||||
guard self.isPageVisible, self.isApplicationActive,
|
||||
self.requestGeneration == generation, !Task.isCancelled else { return }
|
||||
self.commandTask = nil
|
||||
self.isSendingSafetyAction = false
|
||||
self.commandAttemptIDs[command] == attemptID, !Task.isCancelled else { return }
|
||||
self.commandAttemptIDs.removeValue(forKey: command)
|
||||
self.submittingCommands.remove(command)
|
||||
self.applySnapshot()
|
||||
self.scheduleNextPoll()
|
||||
if let error = self.viewModel.commandErrorMessage {
|
||||
if let error = self.viewModel.commandErrorMessage(for: command) {
|
||||
self.showToast(error)
|
||||
} else if let error = self.viewModel.errorMessage {
|
||||
self.showToast("指令已受理,状态刷新失败:\(error)")
|
||||
} else {
|
||||
self.showToast(self.simulationRecordsProvider != nil
|
||||
? "本地模拟指令已受理,未发送设备指令" : "指令已受理,请等待任务状态更新")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -671,15 +724,17 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
}
|
||||
|
||||
@objc private func refreshTriggered() {
|
||||
logEvent("action.refresh")
|
||||
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else {
|
||||
logEvent("action.refresh.rejected", fields: ["reason": "page_or_read_guard", "read_in_progress": isRequesting || viewModel.isLoading])
|
||||
return
|
||||
}
|
||||
refreshTaskIfVisible()
|
||||
}
|
||||
|
||||
@objc private func applicationWillResignActive() {
|
||||
logEvent("app.inactive")
|
||||
isApplicationActive = false
|
||||
logEvent("app.inactive")
|
||||
cancelRefresh()
|
||||
stopLive()
|
||||
}
|
||||
@@ -695,9 +750,86 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
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)
|
||||
fields["entry_source"] = entrySource
|
||||
fields["page_visible"] = isPageVisible
|
||||
fields["app_active"] = isApplicationActive
|
||||
fields["view_in_window"] = isViewLoaded && view.window != nil
|
||||
fields["debug_flight_blocked"] = DeviceCommandDebugPolicy.blocksFlightRequests
|
||||
fields["debug_live_blocked"] = DeviceCommandDebugPolicy.blocksLiveRequests
|
||||
fields["allows_control_actions"] = allowsControlActions
|
||||
viewModel.recordTaskEvent(name, fields: fields)
|
||||
}
|
||||
|
||||
/// 去重只比较 UI 可观察值,不把快照版本或逐秒计时加入比较。
|
||||
private func logChangedEvent(_ name: String, fields: [String: Any]) {
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: fields, options: [.sortedKeys]),
|
||||
diagnosticStateData[name] != data else { return }
|
||||
diagnosticStateData[name] = data
|
||||
logEvent(name, fields: fields)
|
||||
}
|
||||
|
||||
private func recordRenderedState() {
|
||||
logChangedEvent("ui.render", fields: ["central": statusView.diagnosticFields,
|
||||
"safety": safetyView.diagnosticFields, "page_visible": isPageVisible,
|
||||
"app_active": isApplicationActive, "starting": isStartingAction || viewModel.isStartingShooting,
|
||||
"resummoning": isResummoningAction || viewModel.isResummoning,
|
||||
"submitting_commands": submittingCommands.map(\.rawValue).sorted()])
|
||||
var liveFields = feedPlaceholder.diagnosticFields
|
||||
switch liveViewModel.state {
|
||||
case .restricted: liveFields["state"] = "restricted"
|
||||
case .idle: liveFields["state"] = "idle"
|
||||
case .loading: liveFields["state"] = "loading"
|
||||
case .connecting: liveFields["state"] = "connecting"
|
||||
case .playing: liveFields["state"] = "playing"
|
||||
case .localPreview: liveFields["state"] = "local_preview"
|
||||
case .unavailable(let message): liveFields["state"] = "unavailable"; liveFields["reason"] = message
|
||||
case .failed(let message): liveFields["state"] = "failed"; liveFields["reason"] = message
|
||||
}
|
||||
liveFields["active_role"] = liveViewModel.activeRole as Any? ?? NSNull()
|
||||
liveFields["playback_session"] = liveViewModel.playbackSessionID?.uuidString as Any? ?? NSNull()
|
||||
logChangedEvent("live.render", fields: liveFields)
|
||||
}
|
||||
|
||||
private func recordCountdownState(_ seconds: Int?) {
|
||||
let stage = !isPageVisible || !isApplicationActive || seconds == nil ? "hidden" : seconds == 0 ? "zero" : "running"
|
||||
let key = viewModel.recordingExecutionID + ":" + stage
|
||||
guard countdownDiagnosticKey != key else { return }
|
||||
countdownDiagnosticKey = key
|
||||
logEvent("ui.countdown", fields: ["state": stage, "remaining_seconds": seconds as Any? ?? NSNull(),
|
||||
"execution_id": viewModel.recordingExecutionID])
|
||||
}
|
||||
|
||||
private func recordPlaybackEvent(_ event: DroneDockLivePlaybackEvent, sessionID: UUID) {
|
||||
var fields: [String: Any] = ["playback_session": sessionID.uuidString,
|
||||
"page_session_valid": isPageVisible && isApplicationActive && liveViewModel.playbackSessionID == sessionID,
|
||||
"previous_role": liveViewModel.activeRole as Any? ?? NSNull()]
|
||||
let name: String
|
||||
switch event {
|
||||
case .firstFrame:
|
||||
name = "live.first_frame"
|
||||
fields["role"] = liveViewModel.rtcConfiguration?.role as Any? ?? NSNull()
|
||||
case .sourceChanged(let role):
|
||||
name = "live.source_changed"
|
||||
fields["role"] = role as Any? ?? NSNull()
|
||||
fields["fallback_to_airport"] = liveViewModel.activeRole == "drone" && role == "airport"
|
||||
case .failed(let message): name = "live.receiver.failed"; fields["message"] = message
|
||||
case .expired: name = "live.receiver.expired"
|
||||
}
|
||||
logChangedEvent(name, fields: fields)
|
||||
}
|
||||
|
||||
private func logSafetyRejection(_ command: DroneDockSafetyCommand, stage: String) {
|
||||
var reasons: [String] = []
|
||||
if !allowsControlActions { reasons.append("debug_policy") }
|
||||
if !isPageVisible { reasons.append("page_hidden") }
|
||||
if !isApplicationActive { reasons.append("app_inactive") }
|
||||
if stage == "tap", presentedViewController != nil { reasons.append("modal_presented") }
|
||||
if submittingCommands.contains(command) { reasons.append("same_command_submitting") }
|
||||
if isStartingAction { reasons.append("start_submitting") }
|
||||
if isResummoningAction { reasons.append("resummon_submitting") }
|
||||
if !viewModel.canSendCommand(command) { reasons.append("model_command_not_allowed") }
|
||||
logEvent("action.safety.rejected", fields: ["command": command.rawValue, "stage": stage,
|
||||
"reasons": reasons, "safety": safetyView.diagnosticFields])
|
||||
}
|
||||
|
||||
private var allowsControlActions: Bool {
|
||||
@@ -743,13 +875,11 @@ final class DroneDockSimulationRecordsViewController: BaseViewController {
|
||||
@objc private func close() { dismiss(animated: true) }
|
||||
}
|
||||
|
||||
/// 固定底部的安全控制,只在隔离模拟入口按当前接口提供的指令展示可用操作。
|
||||
/// 固定底部的安全控制,文案来自本地阶段,操作许可统一由任务模型判断。
|
||||
@MainActor
|
||||
private final class DroneDockTaskSafetyView: UIView {
|
||||
/// 将用户选择的白名单指令交给页面,不直接调用任何服务。
|
||||
var onCommand: ((DroneDockSafetyCommand) -> Void)?
|
||||
private var pauseCommand = DroneDockSafetyCommand.pause
|
||||
private var returnCommand = DroneDockSafetyCommand.returnHome
|
||||
private let header = DroneDockStyle.label("安全控制", size: 11, color: DroneDockStyle.secondary)
|
||||
private let pauseButton = DroneShootingTaskSafetyButton(symbol: "pause.circle", color: UIColor(hex: 0xEC982A), filled: true)
|
||||
private let returnButton = DroneShootingTaskSafetyButton(symbol: "arrow.uturn.backward", color: UIColor(hex: 0xD85762), filled: false)
|
||||
@@ -759,6 +889,11 @@ private final class DroneDockTaskSafetyView: UIView {
|
||||
private var buttonGap: Constraint?
|
||||
private var buttonHeight: Constraint?
|
||||
|
||||
/// 两个固定按钮实际显示的标题、字幕、启用和加载状态。
|
||||
var diagnosticFields: [String: Any] {
|
||||
["pause": pauseButton.diagnosticFields, "return_home": returnButton.diagnosticFields]
|
||||
}
|
||||
|
||||
/// 复用安全按钮样式,初始没有状态数据时保持禁用。
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
@@ -799,36 +934,51 @@ private final class DroneDockTaskSafetyView: UIView {
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 保持两列固定布局,暂停/继续与返航/取消由快照中的指令白名单决定。
|
||||
func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool) {
|
||||
let commands = model.availableSafetyCommands
|
||||
/// 两个按钮始终表示暂停与返航;已暂停、返航中和回巢使用本地文案,恢复入口位于中央。
|
||||
func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool,
|
||||
submittingCommands: Set<DroneDockSafetyCommand> = []) {
|
||||
let allowsControls = isSimulation || !DeviceCommandDebugPolicy.blocksFlightRequests
|
||||
pauseCommand = commands.contains(.resume) ? .resume : .pause
|
||||
returnCommand = commands.contains(.cancelReturn) ? .cancelReturn : .returnHome
|
||||
header.text = model.commandOutcomeUnknown ? "安全控制 · 结果待核对"
|
||||
: model.isSendingCommand ? (isSimulation ? "安全控制 · 本地模拟发送中" : "安全控制 · 指令发送中")
|
||||
: isSimulation ? "安全控制 · 本地模拟,不发送设备指令" : "安全控制"
|
||||
for (button, command) in [(pauseButton, pauseCommand), (returnButton, returnCommand)] {
|
||||
let title: String
|
||||
let subtitle: String
|
||||
switch command {
|
||||
case .pause: title = "紧急暂停"; subtitle = "悬停待命"
|
||||
case .resume: title = "继续拍摄"; subtitle = "恢复航线"
|
||||
case .returnHome: title = "立即返航"; subtitle = "中断任务"
|
||||
case .cancelReturn: title = "取消返航"; subtitle = "不恢复已中断任务"
|
||||
let phase = model.presentation.phase
|
||||
var controlState = model.flightControlState
|
||||
if model.response?.flightControl == nil {
|
||||
switch phase {
|
||||
case .paused: controlState = .paused
|
||||
case .returning: controlState = .returning
|
||||
case .returned: controlState = .returned
|
||||
default: break
|
||||
}
|
||||
}
|
||||
header.text = isSimulation ? "安全控制 · 本地模拟,不发送设备指令" : "安全控制"
|
||||
for (button, command) in [(pauseButton, DroneDockSafetyCommand.pause), (returnButton, .returnHome)] {
|
||||
var title = command == .pause ? "紧急暂停" : "立即返航"
|
||||
var subtitle = command == .pause ? "悬停待命" : "中断任务"
|
||||
if controlState == .paused, command == .pause {
|
||||
title = "已暂停"
|
||||
} else if controlState == .returning {
|
||||
if command == .returnHome {
|
||||
title = "返航中"
|
||||
subtitle = "返回机巢"
|
||||
}
|
||||
} else if controlState == .returned {
|
||||
title = command == .pause ? "紧急暂停" : "已返航"
|
||||
subtitle = command == .pause ? "当前未执行任务" : "已返回机巢"
|
||||
} else if controlState == .unknown, model.response?.flightControl != nil {
|
||||
subtitle = "暂不可用"
|
||||
} else if [.loading, .readError, .unknown].contains(phase) {
|
||||
subtitle = "暂不可用"
|
||||
}
|
||||
if model.isCommandOutcomeUnknown(command) {
|
||||
subtitle = "结果待核对"
|
||||
}
|
||||
let loading = submittingCommands.contains(command) || model.isCommandLoading(command)
|
||||
let enabled = allowsControls && isInteractive && model.canSendCommand(command)
|
||||
let detail = model.activeCommand == command ? (isSimulation ? "本地模拟发送中…" : "指令发送中…")
|
||||
: model.commandOutcomeUnknown ? "结果待核对"
|
||||
: !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")
|
||||
button.apply(title: title, subtitle: subtitle, enabled: enabled, isLoading: loading)
|
||||
button.setControlSymbol(command == .pause ? "pause.circle" : "arrow.uturn.backward")
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func pauseTapped() { guard pauseButton.isEnabled else { return }; onCommand?(pauseCommand) }
|
||||
@objc private func returnTapped() { guard returnButton.isEnabled else { return }; onCommand?(returnCommand) }
|
||||
@objc private func pauseTapped() { guard pauseButton.isEnabled else { return }; onCommand?(.pause) }
|
||||
@objc private func returnTapped() { guard returnButton.isEnabled else { return }; onCommand?(.returnHome) }
|
||||
|
||||
/// 高度仅依设备空间切换,不随任务状态、按钮文案或网络响应变化。
|
||||
func configure(compact: Bool) {
|
||||
|
||||
@@ -106,10 +106,13 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
private var hasCreated: Bool
|
||||
private var hasSummoned: Bool
|
||||
private var hasStarted: Bool
|
||||
private var lastCommandProgress: [String: Any]?
|
||||
private var isPaused = false
|
||||
private var isReturning = false
|
||||
private var wasInterrupted = false
|
||||
private var hasFailed: Bool
|
||||
private var executionBatch = 9_001
|
||||
private var stateVersion = 1
|
||||
private var exchanges: [Exchange] = []
|
||||
|
||||
/// 固定当前实例结果,不能用参数切换到真实传输。
|
||||
@@ -191,7 +194,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
}
|
||||
if request.httpMethod == "GET", url.path == "/api/app/airport/plane-status" {
|
||||
guard queryMatches(url, required: ["scenic_id": "128", "live_battery": "1"]) else { throw URLError(.badURL) }
|
||||
let plane: [String: Any] = ["id": 201, "name": "本地模拟无人机", "sn_number": "LOCAL-MOCK-PLANE-201",
|
||||
let plane: [String: Any] = ["id": 201, "name": "本地模拟无人机", "sn_number": "LOCAL-MOCK-DOCK-201",
|
||||
"online_status": 1, "work_status": 1, "work_status_label": "空闲(模拟)",
|
||||
"status_text": "本地模拟 · 电量 95%", "battery_percent": 95,
|
||||
"can_fly": true, "is_receive_order": 1]
|
||||
@@ -230,11 +233,15 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
hasFailed = false
|
||||
hasStarted = false
|
||||
isPaused = false
|
||||
isReturning = false
|
||||
wasInterrupted = false
|
||||
executionBatch += 1
|
||||
}
|
||||
} else if !hasCreated || hasSummoned {
|
||||
return try envelope([:], code: 100099, message: "本地模拟:任务尚未创建或已召唤")
|
||||
}
|
||||
hasSummoned = true
|
||||
stateVersion += 1
|
||||
return try envelope(["order_flight_task": taskData(), "order_flight_task_id": 901,
|
||||
"plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201",
|
||||
"task_uuid": "LOCAL-MOCK-TASK-UUID-901",
|
||||
@@ -262,7 +269,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
if request.httpMethod == "POST", url.path == "/api/app/airport/command" {
|
||||
guard url.query == nil, let body = request.httpBody,
|
||||
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
|
||||
Set(object.keys) == ["id", "command"],
|
||||
Set(object.keys) == ["id", "command", "client_request_id"],
|
||||
let values = try? JSONDecoder().decode(CommandBody.self, from: body),
|
||||
values.id == 901, let command = DroneDockSafetyCommand(rawValue: values.command) else {
|
||||
throw URLError(.badURL)
|
||||
@@ -282,7 +289,17 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
case .returnHome: isReturning = true; wasInterrupted = true; isPaused = false
|
||||
case .cancelReturn: isReturning = false; isPaused = true
|
||||
}
|
||||
return try envelope(["command": command.rawValue, "order_flight_task_id": 901,
|
||||
stateVersion += 1
|
||||
let commandID = "LOCAL-MOCK-COMMAND-\(stateVersion)"
|
||||
lastCommandProgress = ["command_id": commandID, "client_request_id": values.clientRequestID,
|
||||
"command": command.rawValue, "status": "succeeded"]
|
||||
return try envelope(["accepted": true, "device_confirmed": true,
|
||||
"command_id": commandID, "client_request_id": values.clientRequestID,
|
||||
"pending_command": lastCommandProgress ?? [:],
|
||||
"acceptance": command == .returnHome ? "accepted" : "device_confirmed",
|
||||
"command": command.rawValue, "order_flight_task_id": 901,
|
||||
"execution_batch": executionBatch, "state_version": stateVersion,
|
||||
"flight_control": flightControlData(),
|
||||
"airport_sn": "LOCAL-MOCK-DOCK-201", "dji_status": simulatedPhase,
|
||||
"metrics": simulatedMetrics])
|
||||
}
|
||||
@@ -308,6 +325,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
throw URLError(.timedOut)
|
||||
case .success:
|
||||
hasStarted = true
|
||||
stateVersion += 1
|
||||
return try envelope([
|
||||
"task_uuid": "LOCAL-MOCK-TASK-UUID-901", "order_flight_task_id": 901,
|
||||
"order_flight_task": taskData(), "plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201",
|
||||
@@ -355,13 +373,15 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
}
|
||||
let deviceLabel = isReturning ? "返航中" : isPaused ? "悬停中" : hasStarted ? "拍摄中" : "空闲"
|
||||
return ["order_number": "LOCAL-MOCK-ORDER-901", "order_flight_task": taskData(), "task": taskData(),
|
||||
"execution_batch": executionBatch, "state_version": stateVersion, "snapshot_kind": "full",
|
||||
"flight_control": flightControlData(),
|
||||
"scenic": ["id": 128, "name": "本地模拟景区"],
|
||||
"scenic_spot": ["id": 301, "name": "模拟点位"],
|
||||
"air_line": ["id": 401, "name": "模拟航线", "scenic_spot_id": 301],
|
||||
"header": ["order_number": "LOCAL-MOCK-ORDER-901", "title": "模拟点位 · 模拟航线",
|
||||
"tourist_label": "本地模拟,无设备指令", "package_name": "模拟套餐 · 含5次拍摄"],
|
||||
"current_plane": ["id": 201, "sn_number": "LOCAL-MOCK-PLANE-201", "online_status": 1,
|
||||
"work_status": hasStarted ? 2 : 1, "work_status_label": deviceLabel,
|
||||
"current_plane": ["id": 201, "sn_number": "LOCAL-MOCK-DOCK-201", "online_status": 1,
|
||||
"work_status": hasFailed ? 1 : 2, "work_status_label": deviceLabel,
|
||||
"status_text": "本地模拟 · \(deviceLabel) · 电量95%"],
|
||||
"metrics": simulatedMetrics,
|
||||
"plane_status": ["scenic_id": 128, "connected": true, "poll_hint_ms": 5000],
|
||||
@@ -369,12 +389,14 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
"message": hasStarted ? "本地模拟:开拍已受理" : "本地模拟:允许验证开拍请求",
|
||||
"primary_action": canStart ? "start_shoot" : simulatedPhase,
|
||||
"primary_action_label": hasStarted ? "拍摄中" : "开始拍摄"],
|
||||
"restart_gate": ["can_restart": hasFailed, "code": hasFailed ? "ok" : "running"],
|
||||
"ui": ["phase": simulatedPhase, "title": phaseTitle, "commands": commands,
|
||||
"message": wasInterrupted ? phaseTitle : "本地模拟状态回查,未向设备发送指令。"]]
|
||||
}
|
||||
|
||||
private func taskData() -> [String: Any] {
|
||||
var task: [String: Any] = ["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128,
|
||||
"wayline_task_id": executionBatch, "plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201",
|
||||
"status": 20, "status_label": "执行中(模拟)", "wayline_status": 20, "wayline_status_label": "执行中(模拟)"]
|
||||
if hasFailed {
|
||||
task["status"] = 40
|
||||
@@ -385,7 +407,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
} else if wasInterrupted {
|
||||
task["status"] = 40
|
||||
task["status_label"] = "任务已中断(模拟)"
|
||||
task["wayline_status"] = 40
|
||||
task["wayline_status"] = 91
|
||||
task["wayline_status_label"] = "已中断(模拟)"
|
||||
task["result_code"] = "return_home"
|
||||
task["result_message"] = isReturning ? "本地模拟:立即返航中断任务;无人机返航中。"
|
||||
@@ -396,19 +418,34 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
|
||||
private var availableCommands: [DroneDockSafetyCommand] {
|
||||
guard hasSummoned, !hasFailed else { return [] }
|
||||
if isReturning { return [.cancelReturn] }
|
||||
if isReturning { return [isPaused ? .resume : .pause] }
|
||||
if wasInterrupted { return [] }
|
||||
return [isPaused ? .resume : .pause, .returnHome]
|
||||
}
|
||||
|
||||
private var simulatedPhase: String {
|
||||
if hasFailed { return "failed" }
|
||||
if isReturning { return "returning" }
|
||||
if isPaused { return "manual_paused" }
|
||||
if isReturning { return "returning_home" }
|
||||
if wasInterrupted { return "failed" }
|
||||
if isPaused { return "paused" }
|
||||
return hasStarted ? "shooting" : "arrived_pending_start"
|
||||
}
|
||||
|
||||
/// 同一模拟批次的执行状态和权限;回巢仅在显式失败起始场景中提供 inside 证据。
|
||||
private func flightControlData() -> [String: Any] {
|
||||
let state = hasFailed ? "returned" : isPaused ? "paused" : isReturning ? "returning" : "executing"
|
||||
let pauseReason: Any = isPaused ? "manual" : (hasStarted ? NSNull() : "arrival_wait" as Any)
|
||||
return ["state": state, "execution_batch": executionBatch,
|
||||
"is_airborne": !hasFailed, "pause_reason": pauseReason,
|
||||
"pending_command": lastCommandProgress ?? [:],
|
||||
"resume_phase": isReturning ? "returning" : hasStarted ? "shooting" : "arrived_pending_start",
|
||||
"return_reason": wasInterrupted ? "manual" : NSNull(),
|
||||
"drone_in_dock": hasFailed ? "inside" : "outside",
|
||||
"can_pause": availableCommands.contains(.pause),
|
||||
"can_resume": availableCommands.contains(.resume),
|
||||
"can_return_home": availableCommands.contains(.returnHome)]
|
||||
}
|
||||
|
||||
private var simulatedMetrics: [[String: String]] {
|
||||
[["key": "battery", "value": "95%"], ["key": "env_temp", "value": "20.3℃"],
|
||||
["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": "无雨"],
|
||||
@@ -456,6 +493,8 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
private struct CommandBody: Decodable {
|
||||
let id: Int
|
||||
let command: String
|
||||
let clientRequestID: String
|
||||
private enum CodingKeys: String, CodingKey { case id, command, clientRequestID = "client_request_id" }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 暂停、返航及回巢面板,使用本地状态文案及整行主按钮,不显示设备摘要。
|
||||
@MainActor
|
||||
final class DroneDockTaskControlStateView: UIView {
|
||||
/// 用户点击已允许的主操作时交给任务页面执行。
|
||||
var onPrimaryAction: (() -> Void)?
|
||||
/// 当前固定区域使用的排版比例,不通过 transform 缩小点击区域。
|
||||
private(set) var effectiveScale: CGFloat = 1
|
||||
/// 可用高度不足时收紧图标、字号与间距。
|
||||
private(set) var usesCompactLayout = false
|
||||
|
||||
private let content = UIView()
|
||||
private let header = UIView()
|
||||
private let iconBackground = UIView()
|
||||
private let icon = UIImageView()
|
||||
private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold, color: UIColor(hex: 0x101523))
|
||||
private let messageLabel = DroneDockStyle.label(size: 14, color: UIColor(hex: 0x6A79A0))
|
||||
private let actionButton = UIButton(type: .system)
|
||||
private let actionActivityIndicator = UIActivityIndicatorView(style: .medium)
|
||||
private let noteLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private var presentation: DroneDockTaskPresentation?
|
||||
private var identifiersActive = false
|
||||
private var isPrimaryActionLoading = false
|
||||
private var headerHeight: Constraint?
|
||||
private var iconSize: Constraint?
|
||||
private var textLeading: Constraint?
|
||||
private var titleHeight: Constraint?
|
||||
private var messageTop: Constraint?
|
||||
private var messageHeight: Constraint?
|
||||
private var actionTop: Constraint?
|
||||
private var actionHeight: Constraint?
|
||||
private var noteTop: Constraint?
|
||||
private var noteHeight: Constraint?
|
||||
|
||||
/// 创建与任务固定状态区域配合的控制状态视图。
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
setupUI()
|
||||
setupConstraints()
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 文案和动作均由本地展示模型提供,禁用按钮只显示状态且不会触发回调。
|
||||
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false, isPrimaryActionLoading: Bool = false) {
|
||||
self.presentation = presentation
|
||||
self.isPrimaryActionLoading = isPrimaryActionLoading
|
||||
titleLabel.text = presentation.title
|
||||
messageLabel.text = presentation.message
|
||||
noteLabel.text = presentation.actionNote
|
||||
switch presentation.phase {
|
||||
case .paused: icon.image = UIImage(systemName: "pause.fill")
|
||||
case .returning: icon.image = UIImage(systemName: "arrow.uturn.backward")
|
||||
case .returned: icon.image = UIImage(systemName: "house.fill")
|
||||
default: icon.image = UIImage(systemName: "clock")
|
||||
}
|
||||
actionButton.isEnabled = presentation.action != .none && presentation.isActionEnabled && !isRefreshing && !isPrimaryActionLoading
|
||||
actionButton.configuration?.title = presentation.actionTitle
|
||||
let actionSymbol: String? = switch presentation.action {
|
||||
case .resume: "play.fill"
|
||||
case .retry: "paperplane.fill"
|
||||
case .refresh: "arrow.clockwise"
|
||||
default: nil
|
||||
}
|
||||
actionButton.configuration?.image = actionSymbol.flatMap { UIImage(systemName: $0) }
|
||||
if isPrimaryActionLoading { actionActivityIndicator.startAnimating() }
|
||||
else { actionActivityIndicator.stopAnimating() }
|
||||
actionButton.accessibilityValue = isPrimaryActionLoading ? "处理中" : nil
|
||||
setIdentifiersActive(identifiersActive)
|
||||
actionButton.setNeedsUpdateConfiguration()
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
/// 只有可见面板暴露通用标识,状态切换后不会匹配到隐藏的旧按钮。
|
||||
func setIdentifiersActive(_ active: Bool) {
|
||||
identifiersActive = active
|
||||
if !active { actionActivityIndicator.stopAnimating() }
|
||||
titleLabel.accessibilityIdentifier = active ? "drone.task.remote.statusTitle" : nil
|
||||
messageLabel.accessibilityIdentifier = active ? "drone.task.remote.statusMessage" : nil
|
||||
actionButton.accessibilityIdentifier = active
|
||||
? (presentation?.action == .refresh ? "drone.task.remote.refresh" : "drone.task.remote.primary") : nil
|
||||
actionActivityIndicator.accessibilityIdentifier = active ? "drone.task.remote.primary.loading" : nil
|
||||
}
|
||||
|
||||
/// 在固定区域内收紧排版,主按钮始终至少 44 点高。
|
||||
override func layoutSubviews() {
|
||||
updateContentLayout()
|
||||
super.layoutSubviews()
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
accessibilityIdentifier = "drone.task.remote.controlState"
|
||||
backgroundColor = .white
|
||||
addSubview(content)
|
||||
[header, actionButton, noteLabel].forEach(content.addSubview)
|
||||
[iconBackground, titleLabel, messageLabel].forEach(header.addSubview)
|
||||
iconBackground.addSubview(icon)
|
||||
iconBackground.backgroundColor = UIColor(hex: 0xFFF3E0)
|
||||
iconBackground.layer.cornerRadius = 20.5
|
||||
icon.contentMode = .scaleAspectFit
|
||||
icon.tintColor = UIColor(hex: 0xF39819)
|
||||
titleLabel.accessibilityTraits = .header
|
||||
titleLabel.numberOfLines = 1
|
||||
titleLabel.lineBreakMode = .byTruncatingTail
|
||||
messageLabel.numberOfLines = 3
|
||||
messageLabel.lineBreakMode = .byTruncatingTail
|
||||
noteLabel.numberOfLines = 1
|
||||
noteLabel.textAlignment = .center
|
||||
noteLabel.accessibilityIdentifier = "drone.task.remote.controlNote"
|
||||
var configuration = UIButton.Configuration.filled()
|
||||
configuration.imagePadding = 10
|
||||
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 20, weight: .semibold)
|
||||
configuration.background.cornerRadius = 8
|
||||
configuration.cornerStyle = .fixed
|
||||
configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8)
|
||||
actionButton.configuration = configuration
|
||||
actionButton.configurationUpdateHandler = { [weak self] button in
|
||||
guard let self, var configuration = button.configuration else { return }
|
||||
let emphasizesAction = button.isEnabled || self.isPrimaryActionLoading
|
||||
let foreground = emphasizesAction ? UIColor.white : UIColor(hex: 0x929BAE)
|
||||
let font = UIFont.systemFont(ofSize: self.usesCompactLayout ? 16 : 18, weight: .semibold)
|
||||
configuration.background.backgroundColor = emphasizesAction
|
||||
? DroneDockStyle.primary : UIColor(hex: 0xEDF0F5)
|
||||
configuration.baseForegroundColor = foreground
|
||||
configuration.imageColorTransformer = UIConfigurationColorTransformer { _ in foreground }
|
||||
// loading 会禁用按钮;显式设置最终文字色,避免系统禁用态再次把白字变暗。
|
||||
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
|
||||
var result = attributes
|
||||
result.font = font
|
||||
result.foregroundColor = foreground
|
||||
return result
|
||||
}
|
||||
button.configuration = configuration
|
||||
}
|
||||
actionActivityIndicator.color = .white
|
||||
actionActivityIndicator.hidesWhenStopped = true
|
||||
actionActivityIndicator.isUserInteractionEnabled = false
|
||||
actionButton.addSubview(actionActivityIndicator)
|
||||
actionButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
|
||||
}
|
||||
|
||||
private func setupConstraints() {
|
||||
content.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview().inset(18)
|
||||
make.centerY.equalToSuperview()
|
||||
}
|
||||
header.snp.makeConstraints { make in
|
||||
make.top.leading.trailing.equalToSuperview()
|
||||
headerHeight = make.height.equalTo(81).constraint
|
||||
}
|
||||
iconBackground.snp.makeConstraints { make in
|
||||
make.top.leading.equalToSuperview()
|
||||
iconSize = make.size.equalTo(41).constraint
|
||||
}
|
||||
icon.snp.makeConstraints { make in
|
||||
make.center.equalToSuperview()
|
||||
make.size.equalTo(iconBackground.snp.width).multipliedBy(24.0 / 41.0)
|
||||
}
|
||||
titleLabel.snp.makeConstraints { make in
|
||||
make.top.trailing.equalToSuperview()
|
||||
textLeading = make.leading.equalTo(iconBackground.snp.trailing).offset(12).constraint
|
||||
titleHeight = make.height.equalTo(28).constraint
|
||||
}
|
||||
messageLabel.snp.makeConstraints { make in
|
||||
messageTop = make.top.equalTo(titleLabel.snp.bottom).offset(6).constraint
|
||||
make.leading.trailing.equalTo(titleLabel)
|
||||
messageHeight = make.height.equalTo(45).constraint
|
||||
}
|
||||
actionButton.snp.makeConstraints { make in
|
||||
actionTop = make.top.equalTo(header.snp.bottom).offset(16).constraint
|
||||
make.leading.trailing.equalToSuperview()
|
||||
actionHeight = make.height.equalTo(50).constraint
|
||||
}
|
||||
actionActivityIndicator.snp.makeConstraints { make in
|
||||
make.centerY.equalToSuperview()
|
||||
make.trailing.equalToSuperview().inset(14)
|
||||
make.size.equalTo(20)
|
||||
}
|
||||
noteLabel.snp.makeConstraints { make in
|
||||
noteTop = make.top.equalTo(actionButton.snp.bottom).offset(6).constraint
|
||||
make.leading.trailing.bottom.equalToSuperview()
|
||||
noteHeight = make.height.equalTo(16).constraint
|
||||
}
|
||||
}
|
||||
|
||||
private func updateContentLayout() {
|
||||
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
|
||||
let wasCompact = usesCompactLayout
|
||||
usesCompactLayout = bounds.height < 190
|
||||
let extreme = bounds.height < 120
|
||||
let compact = usesCompactLayout
|
||||
let diameter: CGFloat = extreme ? 24 : compact ? 32 : 41
|
||||
let iconGap: CGFloat = extreme ? 8 : compact ? 10 : 12
|
||||
let titleSize: CGFloat = extreme ? 17 : compact ? 20 : 22
|
||||
let messageSize: CGFloat = compact ? 13 : 14
|
||||
let textGap: CGFloat = extreme ? 3 : compact ? 4 : 6
|
||||
let buttonGap: CGFloat = extreme ? 8 : compact ? 12 : 16
|
||||
let buttonHeight: CGFloat = compact ? 44 : 50
|
||||
let available = max(1, bounds.height - (extreme ? 8 : 12))
|
||||
let textWidth = max(1, bounds.width - 36 - diameter - iconGap)
|
||||
titleLabel.font = .systemFont(ofSize: titleSize, weight: .semibold)
|
||||
let title = ceil(titleLabel.font.lineHeight)
|
||||
let paragraph = NSMutableParagraphStyle()
|
||||
paragraph.minimumLineHeight = messageSize * 1.5
|
||||
paragraph.maximumLineHeight = messageSize * 1.5
|
||||
let attributes: [NSAttributedString.Key: Any] = [
|
||||
.font: UIFont.systemFont(ofSize: messageSize),
|
||||
.foregroundColor: UIColor(hex: 0x6A79A0), .paragraphStyle: paragraph
|
||||
]
|
||||
messageLabel.attributedText = NSAttributedString(string: presentation.message, attributes: attributes)
|
||||
let measured = (presentation.message as NSString).boundingRect(
|
||||
with: CGSize(width: textWidth, height: .greatestFiniteMagnitude),
|
||||
options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil).height
|
||||
let hasNote = !extreme && DroneDockHomeMetric.usableText(presentation.actionNote) != nil
|
||||
let note = hasNote ? ceil(noteLabel.font.lineHeight) : 0
|
||||
let noteGap: CGFloat = hasNote ? 6 : 0
|
||||
var lines = extreme || presentation.message.isEmpty ? 0 : 3
|
||||
var body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines)))
|
||||
while max(diameter, title + (lines > 0 ? textGap + body : 0)) + buttonGap + buttonHeight + note + noteGap > available,
|
||||
lines > 0 {
|
||||
lines -= 1
|
||||
body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines)))
|
||||
}
|
||||
messageLabel.numberOfLines = max(1, lines)
|
||||
messageLabel.isHidden = lines == 0
|
||||
noteLabel.isHidden = !hasNote
|
||||
effectiveScale = compact ? 0.8 : 1
|
||||
headerHeight?.update(offset: max(diameter, title + (lines > 0 ? textGap + body : 0)))
|
||||
iconSize?.update(offset: diameter)
|
||||
iconBackground.layer.cornerRadius = diameter / 2
|
||||
textLeading?.update(offset: iconGap)
|
||||
titleHeight?.update(offset: title)
|
||||
messageTop?.update(offset: lines > 0 ? textGap : 0)
|
||||
messageHeight?.update(offset: body)
|
||||
actionTop?.update(offset: buttonGap)
|
||||
actionHeight?.update(offset: buttonHeight)
|
||||
noteTop?.update(offset: noteGap)
|
||||
noteHeight?.update(offset: note)
|
||||
if wasCompact != usesCompactLayout { actionButton.setNeedsUpdateConfiguration() }
|
||||
}
|
||||
|
||||
@objc private func primaryTapped() {
|
||||
guard !isHidden, actionButton.isEnabled else { return }
|
||||
onPrimaryAction?()
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ final class DroneDockTaskLiveView: UIView {
|
||||
var onRequest: (() -> Void)?
|
||||
/// 播放事件附带会话 ID,控制器据此丢弃离页或重连后的旧回调。
|
||||
var onPlaybackEvent: ((DroneDockLivePlaybackEvent, UUID) -> Void)?
|
||||
/// 只上报接收端启动、更新和停止等离散事件;不输出帧数据或解锁旧 SDK 日志。
|
||||
var onDiagnosticEvent: ((String, [String: Any]) -> Void)?
|
||||
|
||||
private let playerLayer = AVPlayerLayer()
|
||||
private let titleLabel = DroneDockStyle.label(size: 15, weight: .medium, color: .white)
|
||||
@@ -31,12 +33,25 @@ final class DroneDockTaskLiveView: UIView {
|
||||
private var labelsCenterY: Constraint?
|
||||
private var isShowingCover = false
|
||||
private var coverURL: URL?
|
||||
private var coverTitle = "拍摄已完成"
|
||||
private let rtcPlayer: any DroneDockLivePlaying
|
||||
private var requestedRTC: [DroneDockVolcLiveConfiguration] = []
|
||||
private var activeRTC: [DroneDockVolcLiveConfiguration] = []
|
||||
private var requestedSessionID: UUID?
|
||||
private var activeSessionID: UUID?
|
||||
|
||||
/// 图传区域实际显示与接收状态;不记录 RTC token 或播放地址。
|
||||
var diagnosticFields: [String: Any] {
|
||||
["playback_active": isPlaybackActive, "showing_cover": isShowingCover,
|
||||
"cover_title": isShowingCover ? coverTitle : "",
|
||||
"badge_visible": !sourceBadge.isHidden, "badge_title": sourceLabel.text ?? "",
|
||||
"display_title": titleLabel.isHidden ? "" : titleLabel.text ?? "",
|
||||
"display_message": messageLabel.isHidden ? "" : messageLabel.text ?? "",
|
||||
"receiver_session": activeSessionID?.uuidString as Any? ?? NSNull(),
|
||||
"receiver_rooms": activeRTC.map { ["role": $0.role, "room_id": $0.roomID] },
|
||||
"local_preview_active": player != nil]
|
||||
}
|
||||
|
||||
/// 保留原任务页图传区域的访问标识,外部负责 16:9 约束。
|
||||
override init(frame: CGRect) {
|
||||
rtcPlayer = DroneDockVolcLivePlayer()
|
||||
@@ -99,11 +114,12 @@ final class DroneDockTaskLiveView: UIView {
|
||||
updatePlayback()
|
||||
}
|
||||
|
||||
/// 录制结束后仅展示静态封面;隐藏实时标记和重试按钮,旧模型不能恢复播放。
|
||||
func showRecordingCover(_ show: Bool, url: URL?) {
|
||||
guard isShowingCover != show || coverURL != url else { return }
|
||||
/// 录制结束或中断回巢后展示静态封面;调用方提供本地标题,避免将中断任务显示为成功。
|
||||
func showRecordingCover(_ show: Bool, url: URL?, title: String = "拍摄已完成") {
|
||||
guard isShowingCover != show || coverURL != url || coverTitle != title else { return }
|
||||
isShowingCover = show
|
||||
coverURL = url
|
||||
coverTitle = title
|
||||
coverView.isHidden = !show
|
||||
coverShade.isHidden = !show
|
||||
coverIcon.isHidden = !show || url != nil
|
||||
@@ -112,13 +128,13 @@ final class DroneDockTaskLiveView: UIView {
|
||||
setPlaybackActive(false)
|
||||
coverView.contentMode = .scaleAspectFill
|
||||
coverView.kf.setImage(with: url)
|
||||
titleLabel.text = "拍摄已完成"
|
||||
titleLabel.text = title
|
||||
titleLabel.isHidden = false
|
||||
messageLabel.text = "拍摄封面 · 实时图传已结束"
|
||||
messageLabel.isHidden = false
|
||||
sourceBadge.isHidden = true
|
||||
requestButton.isHidden = true
|
||||
accessibilityLabel = "拍摄已完成,拍摄封面,实时图传已结束"
|
||||
accessibilityLabel = "\(title),拍摄封面,实时图传已结束"
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
@@ -209,9 +225,13 @@ final class DroneDockTaskLiveView: UIView {
|
||||
if !requestedRTC.isEmpty, let sessionID = requestedSessionID {
|
||||
releasePlayer()
|
||||
guard activeSessionID != sessionID || activeRTC != requestedRTC else { return }
|
||||
if activeSessionID != sessionID { releaseRTC() }
|
||||
let isNewSession = activeSessionID != sessionID
|
||||
if isNewSession { releaseRTC() }
|
||||
activeSessionID = sessionID
|
||||
activeRTC = requestedRTC
|
||||
onDiagnosticEvent?(isNewSession ? "live.receiver.start_requested" : "live.receiver.rooms_updated", [
|
||||
"receiver_session": sessionID.uuidString,
|
||||
"rooms": requestedRTC.map { ["role": $0.role, "room_id": $0.roomID] }])
|
||||
rtcPlayer.start(requestedRTC, in: rtcView) { [weak self] event in
|
||||
guard let self, self.activeSessionID == sessionID else { return }
|
||||
self.onPlaybackEvent?(event, sessionID)
|
||||
@@ -232,16 +252,20 @@ final class DroneDockTaskLiveView: UIView {
|
||||
activeURL = requestedURL
|
||||
playerLayer.player = queue
|
||||
queue.play()
|
||||
onDiagnosticEvent?("live.local_preview.started", ["simulation": true])
|
||||
}
|
||||
|
||||
private func releaseRTC() {
|
||||
guard activeSessionID != nil else { return }
|
||||
guard let sessionID = activeSessionID else { return }
|
||||
onDiagnosticEvent?("live.receiver.stopped", ["receiver_session": sessionID.uuidString,
|
||||
"rooms": activeRTC.map { ["role": $0.role, "room_id": $0.roomID] }])
|
||||
activeSessionID = nil
|
||||
activeRTC = []
|
||||
rtcPlayer.stop()
|
||||
}
|
||||
|
||||
private func releasePlayer() {
|
||||
if player != nil { onDiagnosticEvent?("live.local_preview.stopped", ["simulation": true]) }
|
||||
player?.pause()
|
||||
looper?.disableLooping()
|
||||
player?.removeAllItems()
|
||||
|
||||
@@ -18,13 +18,13 @@ final class DroneDockTaskStatusView: UIView {
|
||||
private let iconView = UIImageView()
|
||||
private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold)
|
||||
private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
|
||||
private let countdownLabel = DroneDockStyle.label(size: 13, weight: .medium, color: DroneDockStyle.primary)
|
||||
private let deviceLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let actionRow = UIView()
|
||||
private let primaryButton = UIButton(type: .system)
|
||||
private let failureView = DroneDockTaskFailureView()
|
||||
private let completedView = DroneDockTaskCompletedView()
|
||||
private let shootingView = DroneDockTaskShootingView()
|
||||
private let controlStateView = DroneDockTaskControlStateView()
|
||||
private var presentation: DroneDockTaskPresentation?
|
||||
private var countdownSeconds: Int?
|
||||
private var contentTop: Constraint?
|
||||
@@ -36,6 +36,35 @@ final class DroneDockTaskStatusView: UIView {
|
||||
private var messageHeight: Constraint?
|
||||
private var deviceHeight: Constraint?
|
||||
|
||||
/// 读取当前可见控件的实际文案和许可,用于对照录屏;不改变布局或任务状态。
|
||||
var diagnosticFields: [String: Any] {
|
||||
func descendants(_ root: UIView) -> [UIView] { [root] + root.subviews.flatMap(descendants) }
|
||||
func isVisible(_ view: UIView) -> Bool {
|
||||
if view === self { return !view.isHidden }
|
||||
return !view.isHidden && (view.superview.map(isVisible) ?? false)
|
||||
}
|
||||
let visible = descendants(self).filter(isVisible)
|
||||
let buttonIDs = ["drone.task.remote.primary", "drone.task.remote.refresh", "drone.task.remote.failureRetry",
|
||||
"drone.task.remote.shooting.indicator"]
|
||||
let button = visible.compactMap { $0 as? UIButton }.first { buttonIDs.contains($0.accessibilityIdentifier ?? "") }
|
||||
?? visible.compactMap { $0 as? UIButton }.first
|
||||
let label = visible.compactMap { $0 as? UILabel }.first {
|
||||
["drone.task.remote.statusTitle", "drone.task.remote.failureTitle"].contains($0.accessibilityIdentifier ?? "")
|
||||
}
|
||||
let message = visible.compactMap { $0 as? UILabel }.first {
|
||||
["drone.task.remote.statusMessage", "drone.task.remote.failureReason"].contains($0.accessibilityIdentifier ?? "")
|
||||
}
|
||||
let countdownState = countdownSeconds == nil ? "hidden" : countdownSeconds == 0 ? "zero" : "running"
|
||||
return ["phase": presentation?.phase.rawValue ?? "uninitialized",
|
||||
"title": label?.text ?? presentation?.title ?? "",
|
||||
"message": message?.text ?? "", "message_visible": message != nil,
|
||||
"action": presentation.map { String(describing: $0.action) } ?? "none",
|
||||
"action_title": button?.configuration?.title ?? button?.title(for: .normal) ?? "",
|
||||
"action_enabled": button?.isEnabled == true && isUserInteractionEnabled,
|
||||
"action_loading": visible.compactMap { $0 as? UIActivityIndicatorView }.contains { $0.isAnimating },
|
||||
"interactive": isUserInteractionEnabled, "countdown": countdownState]
|
||||
}
|
||||
|
||||
/// 创建固定状态槽,完成、失败与进行中使用各自的内容布局。
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
@@ -52,20 +81,29 @@ final class DroneDockTaskStatusView: UIView {
|
||||
}
|
||||
|
||||
/// 更新真实状态与动作许可;刷新期间保留内容,只暂时禁用主操作。
|
||||
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false) {
|
||||
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false, isPrimaryActionLoading: Bool = false) {
|
||||
self.presentation = presentation
|
||||
updateCountdown(seconds: presentation.countdownSeconds)
|
||||
let isFailure = presentation.phase == .failed
|
||||
let isCompleted = [.postShootUploading, .completed].contains(presentation.phase)
|
||||
let isShooting = presentation.phase == .shooting
|
||||
contentStack.isHidden = isFailure || isCompleted || isShooting
|
||||
let isControlState = [.paused, .returning, .returned].contains(presentation.phase)
|
||||
contentStack.isHidden = isFailure || isCompleted || isShooting || isControlState
|
||||
failureView.isHidden = !isFailure
|
||||
completedView.isHidden = !isCompleted
|
||||
shootingView.isHidden = !isShooting
|
||||
controlStateView.isHidden = !isControlState
|
||||
completedView.setIdentifiersActive(isCompleted)
|
||||
shootingView.setIdentifiersActive(isShooting)
|
||||
titleLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusTitle"
|
||||
messageLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusMessage"
|
||||
controlStateView.setIdentifiersActive(isControlState)
|
||||
titleLabel.accessibilityIdentifier = isCompleted || isShooting || isControlState ? nil : "drone.task.remote.statusTitle"
|
||||
messageLabel.accessibilityIdentifier = isCompleted || isShooting || isControlState ? nil : "drone.task.remote.statusMessage"
|
||||
if isControlState {
|
||||
primaryButton.accessibilityIdentifier = nil
|
||||
controlStateView.apply(presentation, isRefreshing: isRefreshing, isPrimaryActionLoading: isPrimaryActionLoading)
|
||||
setNeedsLayout()
|
||||
return
|
||||
}
|
||||
if isShooting {
|
||||
primaryButton.accessibilityIdentifier = nil
|
||||
shootingView.apply(presentation)
|
||||
@@ -91,7 +129,7 @@ final class DroneDockTaskStatusView: UIView {
|
||||
iconView.tintColor = style.color
|
||||
let actionTitle = DroneDockHomeMetric.usableText(presentation.actionTitle)
|
||||
primaryButton.isHidden = presentation.action == .none || actionTitle == nil
|
||||
primaryButton.setTitle(actionTitle, for: .normal)
|
||||
updatePrimaryButtonTitle()
|
||||
primaryButton.isEnabled = presentation.isActionEnabled && !primaryButton.isHidden && !isRefreshing
|
||||
primaryButton.backgroundColor = primaryButton.isEnabled
|
||||
? DroneDockStyle.primary : DroneDockStyle.primary.withAlphaComponent(0.35)
|
||||
@@ -100,19 +138,41 @@ final class DroneDockTaskStatusView: UIView {
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
/// 只刷新已到达阶段的剩余秒数,不变更主操作、服务端阶段或执行任何回调。
|
||||
/// 只刷新开拍按钮中的剩余秒数,不变更操作许可、服务端阶段或执行任何回调。
|
||||
func updateCountdown(seconds: Int?) {
|
||||
let value = presentation?.phase == .ready ? seconds.map { max(0, $0) } : nil
|
||||
let value = presentation?.phase == .ready && presentation?.action == .start
|
||||
? seconds.map { max(0, $0) } : nil
|
||||
guard value != countdownSeconds else { return }
|
||||
let visibilityChanged = (value == nil) != (countdownSeconds == nil)
|
||||
countdownSeconds = value
|
||||
countdownLabel.text = value.map { "自动开拍倒计时:\($0) 秒" }
|
||||
countdownLabel.isHidden = value == nil
|
||||
if visibilityChanged { setNeedsLayout() }
|
||||
updatePrimaryButtonTitle()
|
||||
}
|
||||
|
||||
private func updatePrimaryButtonTitle() {
|
||||
guard let presentation else { return }
|
||||
let title = DroneDockHomeMetric.usableText(presentation.actionTitle)
|
||||
let displayedTitle: String?
|
||||
if presentation.phase == .ready, presentation.action == .start,
|
||||
let title, let countdownSeconds {
|
||||
displayedTitle = "\(title)(\(countdownSeconds)s)"
|
||||
} else {
|
||||
displayedTitle = title
|
||||
}
|
||||
// 秒数直接替换,避免系统按钮的标题过渡暂时保留旧数字。
|
||||
UIView.performWithoutAnimation {
|
||||
primaryButton.setTitle(displayedTitle, for: .normal)
|
||||
primaryButton.layoutIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
/// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。
|
||||
override func layoutSubviews() {
|
||||
if let phase = presentation?.phase, [.paused, .returning, .returned].contains(phase) {
|
||||
super.layoutSubviews()
|
||||
controlStateView.layoutIfNeeded()
|
||||
effectiveScale = controlStateView.effectiveScale
|
||||
usesCompactLayout = controlStateView.usesCompactLayout
|
||||
return
|
||||
}
|
||||
if presentation?.phase == .shooting {
|
||||
super.layoutSubviews()
|
||||
shootingView.layoutIfNeeded()
|
||||
@@ -140,6 +200,9 @@ final class DroneDockTaskStatusView: UIView {
|
||||
|
||||
private func setupUI() {
|
||||
backgroundColor = .white
|
||||
addSubview(controlStateView)
|
||||
controlStateView.isHidden = true
|
||||
controlStateView.onPrimaryAction = { [weak self] in self?.onPrimaryAction?() }
|
||||
addSubview(shootingView)
|
||||
shootingView.isHidden = true
|
||||
addSubview(completedView)
|
||||
@@ -155,7 +218,6 @@ final class DroneDockTaskStatusView: UIView {
|
||||
addSubview(contentStack)
|
||||
contentStack.addArrangedSubview(titleRow)
|
||||
contentStack.addArrangedSubview(messageLabel)
|
||||
contentStack.addArrangedSubview(countdownLabel)
|
||||
contentStack.addArrangedSubview(deviceLabel)
|
||||
contentStack.addArrangedSubview(actionRow)
|
||||
titleRow.addSubview(iconView)
|
||||
@@ -168,16 +230,12 @@ final class DroneDockTaskStatusView: UIView {
|
||||
messageLabel.numberOfLines = 3
|
||||
messageLabel.lineBreakMode = .byTruncatingTail
|
||||
messageLabel.accessibilityIdentifier = "drone.task.remote.statusMessage"
|
||||
countdownLabel.font = .monospacedDigitSystemFont(ofSize: 13, weight: .medium)
|
||||
countdownLabel.numberOfLines = 1
|
||||
countdownLabel.isHidden = true
|
||||
countdownLabel.accessibilityIdentifier = "drone.task.remote.countdown"
|
||||
deviceLabel.numberOfLines = 1
|
||||
deviceLabel.lineBreakMode = .byTruncatingTail
|
||||
deviceLabel.accessibilityIdentifier = "drone.task.remote.deviceStatus"
|
||||
actionRow.addSubview(primaryButton)
|
||||
primaryButton.layer.cornerRadius = 9
|
||||
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
|
||||
primaryButton.titleLabel?.font = .monospacedDigitSystemFont(ofSize: 15, weight: .semibold)
|
||||
primaryButton.titleLabel?.lineBreakMode = .byTruncatingTail
|
||||
primaryButton.setTitleColor(.white, for: .normal)
|
||||
primaryButton.setTitleColor(.white.withAlphaComponent(0.9), for: .disabled)
|
||||
@@ -185,6 +243,7 @@ final class DroneDockTaskStatusView: UIView {
|
||||
}
|
||||
|
||||
private func setupConstraints() {
|
||||
controlStateView.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
shootingView.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
completedView.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
failureView.snp.makeConstraints { make in make.edges.equalToSuperview() }
|
||||
@@ -203,7 +262,6 @@ final class DroneDockTaskStatusView: UIView {
|
||||
make.trailing.centerY.equalToSuperview()
|
||||
}
|
||||
messageLabel.snp.makeConstraints { make in messageHeight = make.height.equalTo(34).priority(999).constraint }
|
||||
countdownLabel.snp.makeConstraints { make in make.height.equalTo(ceil(countdownLabel.font.lineHeight)).priority(999) }
|
||||
deviceLabel.snp.makeConstraints { make in deviceHeight = make.height.equalTo(16).priority(999).constraint }
|
||||
actionRow.snp.makeConstraints { make in make.height.equalTo(44) }
|
||||
primaryButton.snp.makeConstraints { make in
|
||||
@@ -214,9 +272,8 @@ final class DroneDockTaskStatusView: UIView {
|
||||
private func updateContentLayout() {
|
||||
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
|
||||
let isExtreme = bounds.height < 120
|
||||
let hasCountdown = countdownSeconds != nil
|
||||
let horizontalInset: CGFloat = isExtreme ? 12 : 16
|
||||
let verticalInset: CGFloat = isExtreme ? (hasCountdown ? 4 : 6) : 12
|
||||
let verticalInset: CGFloat = isExtreme ? 6 : 12
|
||||
let width = max(1, bounds.width - horizontalInset * 2)
|
||||
let availableHeight = max(1, bounds.height - verticalInset * 2)
|
||||
let message = DroneDockHomeMetric.usableText(presentation.message)
|
||||
@@ -228,20 +285,18 @@ final class DroneDockTaskStatusView: UIView {
|
||||
width: width - 46, lines: 2))
|
||||
let naturalMessage = hasMessage ? Self.textHeight(message, font: .systemFont(ofSize: 14), width: width, lines: 3) : 0
|
||||
let naturalDevice = hasDevice ? UIFont.systemFont(ofSize: 12).lineHeight : 0
|
||||
let countdownTextHeight = hasCountdown ? ceil(countdownLabel.font.lineHeight) : 0
|
||||
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0) + (hasCountdown ? 1 : 0)) * 10
|
||||
let naturalHeight = naturalTitle + naturalMessage + countdownTextHeight + naturalDevice + 44 + naturalGaps
|
||||
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0)) * 10
|
||||
let naturalHeight = naturalTitle + naturalMessage + naturalDevice + 44 + naturalGaps
|
||||
effectiveScale = min(1, max(0.8, availableHeight / max(1, naturalHeight)))
|
||||
usesCompactLayout = bounds.height < 190 || naturalHeight * effectiveScale > availableHeight
|
||||
|
||||
// 先收紧图标和间距;只有不足九成空间时才缩小文字。
|
||||
let fontScale: CGFloat = effectiveScale >= 0.9 ? 1 : effectiveScale / 0.9
|
||||
titleLabel.font = .systemFont(ofSize: isExtreme && hasCountdown ? 17 : max(17, 22 * fontScale), weight: .semibold)
|
||||
titleLabel.font = .systemFont(ofSize: max(17, 22 * fontScale), weight: .semibold)
|
||||
messageLabel.font = .systemFont(ofSize: max(12, 14 * fontScale))
|
||||
deviceLabel.font = .systemFont(ofSize: 12)
|
||||
let icon: CGFloat = isExtreme ? 20 : usesCompactLayout ? 24 : 36 * effectiveScale
|
||||
let gap: CGFloat = isExtreme ? (hasCountdown ? 2 : 4)
|
||||
: hasCountdown && usesCompactLayout ? 6 : max(4, 10 * effectiveScale)
|
||||
let gap: CGFloat = isExtreme ? 4 : max(4, 10 * effectiveScale)
|
||||
let titleGap: CGFloat = usesCompactLayout ? 8 : 10 * effectiveScale
|
||||
titleLabel.numberOfLines = usesCompactLayout ? 1 : 2
|
||||
messageLabel.numberOfLines = usesCompactLayout ? 2 : 3
|
||||
@@ -255,8 +310,8 @@ final class DroneDockTaskStatusView: UIView {
|
||||
width: width, lines: messageLineCount)
|
||||
let deviceTextHeight = deviceLabel.isHidden ? 0 : ceil(deviceLabel.font.lineHeight)
|
||||
var contentHeight: CGFloat {
|
||||
titleHeight + bodyHeight + countdownTextHeight + deviceTextHeight + 44
|
||||
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1) + (hasCountdown ? 1 : 0)) * gap
|
||||
titleHeight + bodyHeight + deviceTextHeight + 44
|
||||
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1)) * gap
|
||||
}
|
||||
while contentHeight > availableHeight && messageLineCount > 1 && !messageLabel.isHidden {
|
||||
messageLineCount -= 1
|
||||
@@ -301,6 +356,7 @@ final class DroneDockTaskStatusView: UIView {
|
||||
case .postShootUploadFailed: ("exclamationmark.circle.fill", DroneDockStyle.warning)
|
||||
case .paused: ("pause.circle.fill", DroneDockStyle.warning)
|
||||
case .returning: ("arrow.uturn.backward.circle.fill", DroneDockStyle.warning)
|
||||
case .returned: ("house.circle.fill", DroneDockStyle.warning)
|
||||
case .completed: ("checkmark.circle.fill", DroneDockStyle.success)
|
||||
case .failed: ("xmark.circle.fill", UIColor(hex: 0xD46B62))
|
||||
case .blocked, .readError: ("exclamationmark.circle.fill", DroneDockStyle.warning)
|
||||
|
||||
@@ -279,6 +279,14 @@ final class DroneShootingTaskSafetyButton: UIButton {
|
||||
private let controlTitleLabel = DroneDockStyle.label(size: 15, weight: .semibold)
|
||||
private let controlSubtitleLabel = DroneDockStyle.label(size: 10)
|
||||
private let controlIconView: UIImageView
|
||||
private let activityIndicator = UIActivityIndicatorView(style: .medium)
|
||||
|
||||
/// 输出实际呈现的控件状态,供页面按变化记录;不推导业务许可。
|
||||
var diagnosticFields: [String: Any] {
|
||||
["title": controlTitleLabel.text ?? "", "subtitle": controlSubtitleLabel.text ?? "",
|
||||
"enabled": isEnabled, "loading": activityIndicator.isAnimating,
|
||||
"accessibility_value": accessibilityValue ?? ""]
|
||||
}
|
||||
|
||||
/// 创建暂停或返航按钮;返回状态只由 ViewModel 决定。
|
||||
init(symbol: String, color: UIColor, filled: Bool) {
|
||||
@@ -292,6 +300,9 @@ final class DroneShootingTaskSafetyButton: UIButton {
|
||||
controlSubtitleLabel.textColor = filled ? UIColor.white.withAlphaComponent(0.85) : DroneDockStyle.secondary
|
||||
controlIconView.tintColor = filled ? .white : color
|
||||
controlIconView.contentMode = .scaleAspectFit
|
||||
activityIndicator.color = filled ? .white : color
|
||||
activityIndicator.hidesWhenStopped = true
|
||||
activityIndicator.isUserInteractionEnabled = false
|
||||
let titles = UIStackView(arrangedSubviews: [controlTitleLabel, controlSubtitleLabel])
|
||||
titles.axis = .vertical
|
||||
titles.spacing = 3
|
||||
@@ -308,6 +319,11 @@ final class DroneShootingTaskSafetyButton: UIButton {
|
||||
make.trailing.lessThanOrEqualToSuperview().offset(-9)
|
||||
}
|
||||
controlIconView.snp.makeConstraints { make in make.size.equalTo(27) }
|
||||
addSubview(activityIndicator)
|
||||
activityIndicator.snp.makeConstraints { make in
|
||||
make.center.equalTo(controlIconView)
|
||||
make.size.equalTo(27)
|
||||
}
|
||||
controlTitleLabel.adjustsFontSizeToFitWidth = true
|
||||
controlTitleLabel.minimumScaleFactor = 0.8
|
||||
controlSubtitleLabel.adjustsFontSizeToFitWidth = true
|
||||
@@ -317,14 +333,18 @@ final class DroneShootingTaskSafetyButton: UIButton {
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 应用语义明确的按钮标题、辅助说明及防重复点击状态。
|
||||
func apply(title: String, subtitle: String, enabled: Bool) {
|
||||
/// 应用独立操作许可和加载状态;加载时仅替换本按钮图标,不改变布局或其他按钮。
|
||||
func apply(title: String, subtitle: String, enabled: Bool, isLoading: Bool = false) {
|
||||
controlTitleLabel.text = title
|
||||
controlSubtitleLabel.text = subtitle
|
||||
isEnabled = enabled
|
||||
alpha = enabled ? 1 : 0.42
|
||||
isEnabled = enabled && !isLoading
|
||||
alpha = enabled || isLoading ? 1 : 0.42
|
||||
controlIconView.alpha = isLoading ? 0 : 1
|
||||
if isLoading { activityIndicator.startAnimating() }
|
||||
else { activityIndicator.stopAnimating() }
|
||||
activityIndicator.accessibilityIdentifier = accessibilityIdentifier.map { "\($0).loading" }
|
||||
accessibilityLabel = title
|
||||
accessibilityValue = subtitle
|
||||
accessibilityValue = isLoading ? "处理中,\(subtitle)" : subtitle
|
||||
}
|
||||
|
||||
/// 切换同一位置的暂停/继续或返航/取消图标,不改变按钮布局。
|
||||
|
||||
Reference in New Issue
Block a user