feat: 完善机巢任务安全控制与状态诊断

同步新版飞控与 WebSocket 回执合同,完善独立指令等待、暂停继续和返航状态;增加真机诊断并优化倒计时与素材库展示。
This commit is contained in:
2026-11-04 17:34:28 +08:00
parent 1c766ff12f
commit e3979e9e32
44 changed files with 4575 additions and 581 deletions
@@ -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
}
}