feat(drone-dock): 添加安全控制接口本地模拟调试

接入 command 请求合同与底部暂停、继续、返航、取消返航交互;支持同任务单次回查、防重复提交及未知结果锁。保留真实指令禁飞拦截,补充隔离测试、模拟回执与截图。
This commit is contained in:
2026-10-30 10:32:31 +08:00
parent b95b251de1
commit 20877b425c
21 changed files with 2668 additions and 43 deletions
@@ -0,0 +1,40 @@
import Foundation
/// 基于既有订单飞行任务发送单次安全指令;禁飞期间仅向本地模拟页面注入。
protocol DroneDockCommandSending: Sendable {
/// 提交任务 ID 和白名单指令,不创建任务、不选机,也不自动重试。
@MainActor
func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse
}
/// 朱工 command 合同适配,真实传输仍受统一 Debug 禁飞策略阻断。
@MainActor
final class DroneDockCommandAPI: DroneDockCommandSending {
private let client: APIClient
/// 注入统一客户端;模拟调试使用完全不转发网络的响应替身。
init(client: APIClient) { self.client = client }
/// 每次仅发送 id 和 command,回执必须对应同一任务及同一指令。
func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse {
try Task.checkCancellation()
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请返回任务页确认") }
let response: DroneDockCommandResponse = try await client.send(APIRequest(
method: .post, path: "/api/app/airport/command",
body: CommandBody(taskID: taskID, command: command.rawValue)
))
guard response.orderFlightTaskID == taskID, response.command == command.rawValue else {
throw APIError.decodeFailed("安全指令回执的任务或指令不一致,请核对原任务状态")
}
return response
}
/// 指令请求只携带任务身份及已确认的指令码。
private struct CommandBody: Encodable {
let taskID: Int
let command: String
/// 朱工请求字段映射,不附加飞机或模拟标志。
private enum CodingKeys: String, CodingKey { case taskID = "id", command }
}
}
@@ -0,0 +1,67 @@
import Foundation
/// 朱工 command 接口明确允许的四类安全指令,不接受服务端未知动作直接透传。
enum DroneDockSafetyCommand: String, CaseIterable, Sendable {
/// 暂停航线并悬停待命。
case pause = "flighttask_pause"
/// 恢复已暂停的航线。
case resume = "flighttask_recovery"
/// 立即返航;服务端会中断当前任务并释放飞行锁。
case returnHome = "return_home"
/// 取消返航,不代表已恢复或重新创建原拍摄任务。
case cancelReturn = "return_home_cancel"
}
/// 指令受理回执;仅保留后端返回的身份、读数与状态,不推断设备已完成动作。
struct DroneDockCommandResponse: Decodable, Equatable, Sendable {
/// 文档要求回显的订单飞行任务 ID。
let orderFlightTaskID: Int?
/// 本次回显的指令码,API 核验其与请求一致。
let command: String?
/// 任务实际锁定的机场标识,客户端不提交或覆盖它。
let airportSN: String?
/// 司空状态允许任意 JSON 类型;null 与缺失都不构成执行成功证据。
let djiStatus: DroneDockHomeJSONValue?
/// 非实时采集的六项读数,不替代 shooting 完整快照。
let metrics: [DroneDockHomeMetric]
/// 完整 data 格式化 JSON,供本地模拟联调查看未知字段与原始类型。
let dataJSON: String
/// 朱工指令回执字段映射。
private enum CodingKeys: String, CodingKey {
case orderFlightTaskID = "order_flight_task_id", command, airportSN = "airport_sn"
case djiStatus = "dji_status", metrics
}
/// 不补造身份、状态或读数,完整 JSON 仍保留实际出现的 null 字段。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
orderFlightTaskID = try container.decodeIfPresent(Int.self, forKey: .orderFlightTaskID)
command = try container.decodeIfPresent(String.self, forKey: .command)
airportSN = try container.decodeIfPresent(String.self, forKey: .airportSN)
djiStatus = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .djiStatus)
metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? []
let raw = try DroneDockHomeJSONValue(from: decoder)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
dataJSON = String(decoding: try encoder.encode(DroneDockCommandJSONSnapshot(value: raw)), as: UTF8.self)
}
}
/// 将现有 JSON 值完整格式化,不更改指令回执的原始值与结构。
private struct DroneDockCommandJSONSnapshot: Encodable {
let value: DroneDockHomeJSONValue
/// 保留字符串、数字、布尔、null 和嵌套对象,不添加业务成功推断。
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch value {
case .object(let object): try container.encode(object.mapValues { DroneDockCommandJSONSnapshot(value: $0) })
case .array(let array): try container.encode(array.map { DroneDockCommandJSONSnapshot(value: $0) })
case .string(let text): try container.encode(text)
case .number(let number): try container.encode(number)
case .bool(let flag): try container.encode(flag)
case .null: try container.encodeNil()
}
}
}
@@ -189,6 +189,26 @@ struct DroneDockShootingUI: Decodable, Equatable, Sendable {
let title: String?
/// 服务端阶段说明,不由 GET 请求成功拼造飞行进度。
let message: String?
/// 服务端实际提供的安全指令;缺失时保持未知,不据阶段文案自行补齐。
let commands: [DroneDockShootingCommand]?
/// 保留既有展示构造方式,新增动作列表默认为未知。
init(phase: String?, title: String?, message: String?, commands: [DroneDockShootingCommand]? = nil) {
self.phase = phase
self.title = title
self.message = message
self.commands = commands
}
}
/// shooting 或 start-shoot 的指令展示项;原始字符串保留,执行时另作白名单校验。
struct DroneDockShootingCommand: Decodable, Equatable, Sendable {
/// 服务端指令码,未知值不应开放动作。
let command: String?
/// 服务端按钮标题。
let label: String?
/// 服务端按钮副标题。
let sub: String?
}
/// 将现有 JSON 值解码结果重新格式化,完整保留 shooting 的未建模字段。
@@ -1,6 +1,6 @@
import Foundation
/// 拍摄任务状态及可选开拍流程,始终复用同一任务;禁飞调试仅为本地模拟注入开拍服务。
/// 拍摄任务状态及可选控制流程,始终复用同一任务;禁飞调试仅为本地模拟注入操作服务。
final class DroneDockShootingTaskViewModel {
/// 页面绑定的账号、景区和门店身份。
let context: DroneDockHomeContext
@@ -24,25 +24,42 @@ final class DroneDockShootingTaskViewModel {
private(set) var hasSubmittedStart = false
/// 同任务开拍回执;受理成功不直接替代 shooting 的完整状态快照。
private(set) var startResponse: DroneDockStartShootResponse?
/// 指令提交及其后单次回查期间锁定控制动作,旧状态继续展示。
private(set) var isSendingCommand = false
/// 当前正在提交或核对的指令;结束后清空。
private(set) var activeCommand: DroneDockSafetyCommand?
/// 最近一次明确受理且身份一致的指令回执,不作为设备已执行的证据。
private(set) var commandResponse: DroneDockCommandResponse?
/// 指令业务拒绝、本地拦截或结果待核对提示。
private(set) var commandErrorMessage: String?
/// 已发但结果不明确时保持锁定,普通读取不能自动解除或重发。
private(set) var commandOutcomeUnknown = false
private let service: any DroneDockShootingServing
private let startService: (any DroneDockStartShooting)?
private let commandService: (any DroneDockCommandSending)?
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private var generation = 0
private var identityInvalidated = false
private var startGeneration = 0
private var didSendStart = false
private var commandGeneration = 0
private var didSendCommand = false
// 回查仍提供的已受理指令分别保留防重锁,避免另一条指令受理覆盖旧锁。
private var pendingAcceptedCommands: Set<DroneDockSafetyCommand> = []
/// 默认只读;只有显式注入开拍服务才提供开拍动作,当前正式入口不注入该服务。
/// 默认只读;仅显式注入模拟操作服务时开放对应动作,当前正式入口不注入。
init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder,
service: any DroneDockShootingServing,
startService: (any DroneDockStartShooting)? = nil,
commandService: (any DroneDockCommandSending)? = nil,
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.taskID = taskID
self.order = order
self.service = service
self.startService = startService
self.commandService = commandService
self.currentContext = currentContext
}
@@ -53,8 +70,9 @@ final class DroneDockShootingTaskViewModel {
}
@MainActor
private func refreshSnapshot(allowWhileStarting: Bool) async {
guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting else { return }
private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false) async {
guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting,
!isSendingCommand || allowWhileCommand else { return }
generation &+= 1
let requestGeneration = generation
isLoading = true
@@ -79,6 +97,7 @@ final class DroneDockShootingTaskViewModel {
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
}
response = value
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
} catch {
guard accepts(requestGeneration) else { return }
errorMessage = error is CancellationError ? nil : error.localizedDescription
@@ -89,6 +108,7 @@ final class DroneDockShootingTaskViewModel {
@MainActor
func invalidate(preservingSnapshot: Bool = false) {
invalidateStartShooting()
invalidateCommand()
generation &+= 1
isLoading = false
if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true }
@@ -96,6 +116,9 @@ final class DroneDockShootingTaskViewModel {
response = nil
startResponse = nil
startErrorMessage = nil
commandResponse = nil
commandErrorMessage = nil
pendingAcceptedCommands.removeAll()
errorMessage = "账号或景区已变化,请返回工作台重新进入"
} else {
if !preservingSnapshot { response = nil }
@@ -106,8 +129,9 @@ final class DroneDockShootingTaskViewModel {
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;默认真实页面保持禁用。
var canStartShooting: Bool {
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && errorMessage == nil
&& !isLoading && !isStartingShooting && !isSendingCommand && errorMessage == nil
&& !hasSubmittedStart && !startOutcomeUnknown
&& !commandOutcomeUnknown && pendingAcceptedCommands.isEmpty
&& resolvedDisplayPhase().0 == .ready
&& response?.executeGate?.canExecute == true
&& response?.executeGate?.primaryAction == "start_shoot"
@@ -180,6 +204,93 @@ final class DroneDockShootingTaskViewModel {
didSendStart = false
}
/// 只识别当前快照明确提供的四种指令,未知值忽略,同一指令只展示一次。
var availableSafetyCommands: [DroneDockSafetyCommand] {
var commands: [DroneDockSafetyCommand] = []
for item in response?.ui?.commands ?? [] {
guard let raw = item.command, let command = DroneDockSafetyCommand(rawValue: raw),
!commands.contains(command) else { continue }
commands.append(command)
}
return commands
}
/// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。
func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool {
commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && !isSendingCommand && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !pendingAcceptedCommands.contains(command)
&& (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID)
&& (response?.currentPlane?.id ?? 0) > 0
&& availableSafetyCommands.contains(command)
}
/// 只提交当前任务的一次指令,受理后单次回查;不轮询、不改派飞机、不自动重试。
@MainActor
func sendCommand(_ command: DroneDockSafetyCommand,
onStateChange: @escaping @MainActor () -> Void = {}) async {
guard canSendCommand(command), let commandService else { return }
guard context.hasSameIdentity(as: currentContext()) else {
identityInvalidated = true
invalidate()
onStateChange()
return
}
guard !Task.isCancelled else { return }
commandGeneration &+= 1
let requestGeneration = commandGeneration
isSendingCommand = true
activeCommand = command
didSendCommand = false
commandResponse = nil
commandErrorMessage = nil
onStateChange()
defer {
if commandGeneration == requestGeneration {
if Task.isCancelled && didSendCommand && commandResponse == nil { markCommandUnknown() }
isSendingCommand = false
activeCommand = nil
didSendCommand = false
onStateChange()
}
}
guard acceptsCommand(requestGeneration) else { return }
do {
didSendCommand = true
let value = try await commandService.sendCommand(taskID: taskID, command: command)
guard acceptsCommand(requestGeneration) else { return }
guard value.orderFlightTaskID == taskID, value.command == command.rawValue else {
throw APIError.decodeFailed("安全指令回执与当前任务或指令不一致,请先核对任务状态")
}
commandResponse = value
pendingAcceptedCommands.insert(command)
commandOutcomeUnknown = false
onStateChange()
guard acceptsCommand(requestGeneration) else { return }
await refreshSnapshot(allowWhileStarting: false, allowWhileCommand: true)
} catch {
if error is DeviceCommandDebugBlockedError, commandGeneration == requestGeneration { didSendCommand = false }
guard acceptsCommand(requestGeneration) else { return }
if error is DeviceCommandDebugBlockedError {
commandErrorMessage = DeviceCommandDebugPolicy.blockedMessage
} else if case APIError.serverCode = error {
commandErrorMessage = error.localizedDescription
} else {
markCommandUnknown(reason: error.localizedDescription)
}
}
}
/// 离页或后台取消控制流程;已发而未受理时保留未知结果锁,忽略迟到回执。
@MainActor
func invalidateCommand() {
if isSendingCommand && didSendCommand && commandResponse == nil { markCommandUnknown() }
commandGeneration &+= 1
isSendingCommand = false
activeCommand = nil
didSendCommand = false
}
/// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。
var title: String {
if let title = usable(response?.header?.title) { return title }
@@ -211,12 +322,13 @@ final class DroneDockShootingTaskViewModel {
?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认"
}
/// 保留服务端阶段说明;未确认的开拍结果明确提示核对,不伪装为正在拍摄。
/// 保留服务端阶段说明;操作结果未知时优先提示核对,不伪装为设备已执行。
var statusMessage: String {
if response == nil {
if let errorMessage { return errorMessage }
if isLoading { return "正在读取当前拍摄任务" }
}
if let commandErrorMessage { return commandErrorMessage }
if resolvedDisplayPhase().0 == .failed { return failureMessage }
if startOutcomeUnknown, let startErrorMessage { return startErrorMessage }
if resolvedDisplayPhase().0 == .ready {
@@ -243,7 +355,7 @@ final class DroneDockShootingTaskViewModel {
let actionTitle: String?
let enabled: Bool
switch phase {
case .ready where hasSubmittedStart || startOutcomeUnknown:
case .ready where hasSubmittedStart || startOutcomeUnknown || commandOutcomeUnknown:
action = .refresh
actionTitle = "刷新状态"
enabled = !identityInvalidated
@@ -271,7 +383,7 @@ final class DroneDockShootingTaskViewModel {
}
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
isActionEnabled: enabled && !isLoading && !isStartingShooting && !identityInvalidated && (errorMessage == nil || action == .refresh),
isActionEnabled: enabled && !isLoading && !isStartingShooting && !isSendingCommand && !identityInvalidated && (errorMessage == nil || action == .refresh),
actionNote: phase == .failed ? retryUnavailableNote : nil)
}
@@ -310,6 +422,22 @@ final class DroneDockShootingTaskViewModel {
return !Task.isCancelled
}
@MainActor
private func acceptsCommand(_ requestGeneration: Int) -> Bool {
guard commandGeneration == requestGeneration else { return false }
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
identityInvalidated = true
invalidate()
return false
}
return !Task.isCancelled
}
private func markCommandUnknown(reason: String? = nil) {
commandOutcomeUnknown = true
commandErrorMessage = (reason.map { "\($0)。" } ?? "") + "安全指令结果待核对,请刷新任务状态,勿重复提交"
}
private func markStartUnknown(reason: String? = nil) {
startOutcomeUnknown = true
startErrorMessage = (reason.map { "\($0)。" } ?? "") + "开始拍摄结果待核对,请刷新任务状态,勿重复提交"
@@ -1,7 +1,7 @@
import SnapKit
import UIKit
/// 拍摄任务页:真实入口只读,本地模拟入口可注入开始拍摄服务验证接口流程。
/// 拍摄任务页:真实入口只读,本地模拟入口可验证开拍与底部安全指令合同。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
@@ -23,11 +23,13 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private let simulationRecordsProvider: (@MainActor () -> String)?
private var refreshTask: Task<Void, Never>?
private var startTask: Task<Void, Never>?
private var commandTask: Task<Void, Never>?
private var requestGeneration = 0
private var isPageVisible = false
private var isApplicationActive = false
private var isRequesting = false
private var isStartingAction = false
private var isSendingSafetyAction = false
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
init(viewModel: DroneDockShootingTaskViewModel,
@@ -51,6 +53,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
deinit {
refreshTask?.cancel()
startTask?.cancel()
commandTask?.cancel()
NotificationCenter.default.removeObserver(self)
}
@@ -156,6 +159,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
override func bindActions() {
statusView.onPrimaryAction = { [weak self] in self?.primaryActionTriggered() }
statusView.onDetails = { [weak self] in self?.showStatusDetails() }
safetyView.onCommand = { [weak self] command in self?.safetyCommandTriggered(command) }
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
@@ -180,6 +184,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func applySnapshot() {
guard isViewLoaded else { return }
let loading = isRequesting || viewModel.isLoading || isStartingAction || viewModel.isStartingShooting
|| isSendingSafetyAction || viewModel.isSendingCommand
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle
let telemetry = viewModel.telemetry
@@ -190,6 +195,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
statusView.apply(value, isRefreshing: loading)
safetyView.apply(model: viewModel, isSimulation: simulationRecordsProvider != nil,
isInteractive: isPageVisible && isApplicationActive && !loading)
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItems?.forEach { $0.isEnabled = isPageVisible && isApplicationActive && !loading }
navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil
@@ -197,7 +204,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func primaryActionTriggered() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting else { return }
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand else { return }
let state = viewModel.presentation
guard state.isActionEnabled else { return }
switch state.action {
@@ -221,6 +229,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
texts.append("刷新失败,当前显示上次数据:\(error)")
}
if let error = viewModel.startErrorMessage { texts.append(error) }
if let error = viewModel.commandErrorMessage { texts.append(error) }
var distinct: [String] = []
for text in texts where !distinct.contains(text) { distinct.append(text) }
let alert = UIAlertController(title: "任务状态详情", message: distinct.joined(separator: "\n\n"), preferredStyle: .alert)
@@ -231,7 +240,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。
private func refreshTaskIfVisible() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting else { return }
!isStartingAction, !viewModel.isStartingShooting,
!isSendingSafetyAction, !viewModel.isSendingCommand else { return }
requestGeneration &+= 1
let generation = requestGeneration
isRequesting = true
@@ -256,6 +266,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
refreshTask = nil
startTask?.cancel()
startTask = nil
commandTask?.cancel()
commandTask = nil
isSendingSafetyAction = false
isStartingAction = false
isRequesting = false
viewModel.invalidate(preservingSnapshot: true)
@@ -264,7 +277,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。
private func startShootingIfAllowed() {
guard !isStartingAction, viewModel.canStartShooting else { return }
guard !isStartingAction, !isSendingSafetyAction, viewModel.canStartShooting else { return }
requestGeneration &+= 1
let generation = requestGeneration
isStartingAction = true
@@ -285,6 +298,51 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
}
/// 仅模拟入口响应安全按钮;返航会中断任务,先明确展示其含义再提交一次。
private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
presentedViewController == nil, !isSendingSafetyAction, !isStartingAction,
!isRequesting, viewModel.canSendCommand(command) else { return }
if command == .returnHome {
let alert = UIAlertController(title: "立即返航(本地模拟)",
message: "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "模拟返航", style: .destructive) { [weak self] _ in
self?.sendSafetyCommand(command)
})
present(alert, animated: true)
} else {
sendSafetyCommand(command)
}
}
/// 同步锁覆盖异步调度间隙;界面保留旧快照,只有同任务回查成功才更新阶段。
private func sendSafetyCommand(_ command: DroneDockSafetyCommand) {
guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive,
!isSendingSafetyAction, !isStartingAction, !isRequesting,
viewModel.canSendCommand(command) else { return }
requestGeneration &+= 1
let generation = requestGeneration
isSendingSafetyAction = true
applySnapshot()
commandTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.sendCommand(command) { [weak self] in self?.applySnapshot() }
guard self.isPageVisible, self.isApplicationActive,
self.requestGeneration == generation, !Task.isCancelled else { return }
self.commandTask = nil
self.isSendingSafetyAction = false
self.applySnapshot()
if let error = self.viewModel.commandErrorMessage {
self.showToast(error)
} else if let error = self.viewModel.errorMessage {
self.showToast("模拟指令已受理,状态刷新失败:\(error)")
} else {
self.showToast("本地模拟指令已受理,未发送设备指令")
}
}
}
/// 模拟入口专用记录页,内容由内存传输提供,不请求后端日志或设备。
@objc private func showSimulationRecords() {
guard let simulationRecordsProvider, presentedViewController == nil else { return }
@@ -349,9 +407,13 @@ 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)
@@ -361,7 +423,7 @@ private final class DroneDockTaskSafetyView: UIView {
private var buttonGap: Constraint?
private var buttonHeight: Constraint?
/// 复用安全按钮样式,按钮始终保留占位与明确的不可用状态。
/// 复用安全按钮样式,初始没有状态数据时保持禁用。
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
@@ -384,6 +446,8 @@ private final class DroneDockTaskSafetyView: UIView {
returnButton.accessibilityIdentifier = "drone.task.remote.return"
pauseButton.apply(title: "紧急暂停", subtitle: "暂不可用", enabled: false)
returnButton.apply(title: "立即返航", subtitle: "暂不可用", enabled: false)
pauseButton.addTarget(self, action: #selector(pauseTapped), for: .touchUpInside)
returnButton.addTarget(self, action: #selector(returnTapped), for: .touchUpInside)
header.snp.makeConstraints { make in
headerTop = make.top.equalToSuperview().offset(10).constraint
make.leading.trailing.equalToSuperview().inset(16)
@@ -399,6 +463,36 @@ 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
pauseCommand = commands.contains(.resume) ? .resume : .pause
returnCommand = commands.contains(.cancelReturn) ? .cancelReturn : .returnHome
header.text = model.commandOutcomeUnknown ? "安全控制 · 结果待核对"
: model.isSendingCommand ? "安全控制 · 本地模拟发送中"
: 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 enabled = isSimulation && isInteractive && model.canSendCommand(command)
let detail = model.activeCommand == command ? "本地模拟发送中…"
: model.commandOutcomeUnknown ? "结果待核对"
: !isSimulation || !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")
}
}
@objc private func pauseTapped() { guard pauseButton.isEnabled else { return }; onCommand?(pauseCommand) }
@objc private func returnTapped() { guard returnButton.isEnabled else { return }; onCommand?(returnCommand) }
/// 高度仅依设备空间切换,不随任务状态、按钮文案或网络响应变化。
func configure(compact: Bool) {
headerTop?.update(offset: compact ? 8 : 10)
@@ -2,18 +2,24 @@ import Foundation
import UIKit
#if DEBUG
/// 独立的准备、召唤与开拍模拟入口;所有请求在内存中处理,不复用账号或真实网络服务。
/// 独立的准备、召唤、开拍及安全控制模拟入口;所有请求在内存中处理,不复用真实网络。
@MainActor
enum DroneDockStartShootSimulation {
/// 显式启动参数选择准备页或任务页,两个入口始终使用隔离的模拟会话。
static func makeController(arguments: [String]) -> UIViewController? {
let startsAtPreparation = arguments.contains("--dock-preparation-mock")
guard startsAtPreparation || arguments.contains("--dock-start-shoot-mock") else { return nil }
let startsAtCommands = arguments.contains("--dock-command-mock")
guard startsAtPreparation || startsAtCommands || arguments.contains("--dock-start-shoot-mock") else { return nil }
let resultArgument = arguments.first { $0.hasPrefix("--dock-start-shoot-result=") }
let result = resultArgument.flatMap {
DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-start-shoot-result=".count)))
} ?? .success
return makeFlow(result: result, startsAtPreparation: startsAtPreparation)
let commandResultArgument = arguments.first { $0.hasPrefix("--dock-command-result=") }
let commandResult = commandResultArgument.flatMap {
DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-command-result=".count)))
} ?? .success
return makeFlow(result: result, startsAtPreparation: startsAtPreparation,
commandResult: commandResult, startsAtCommands: startsAtCommands)
}
/// 从正式准备页进入全新的纯内存模拟,不携带真实订单、账号或设备身份。
@@ -22,8 +28,11 @@ enum DroneDockStartShootSimulation {
}
private static func makeFlow(result: DroneDockStartShootMockResult,
startsAtPreparation: Bool) -> UIViewController? {
let session = DroneDockStartShootMockSession(result: result, requiresPreparation: startsAtPreparation)
startsAtPreparation: Bool,
commandResult: DroneDockStartShootMockResult = .success,
startsAtCommands: Bool = false) -> UIViewController? {
let session = DroneDockStartShootMockSession(result: result, requiresPreparation: startsAtPreparation,
commandResult: commandResult, hasStarted: startsAtCommands && !startsAtPreparation)
let environment = APIEnvironment(baseURL: URL(string: "https://mock.invalid")!,
webSocketURL: URL(string: "wss://mock.invalid/unused")!)
let client = APIClient(environment: environment, session: session)
@@ -35,7 +44,8 @@ enum DroneDockStartShootSimulation {
let taskFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController = { taskID, taskOrder, taskContext in
let model = DroneDockShootingTaskViewModel(context: taskContext, taskID: taskID, order: taskOrder,
service: DroneDockShootingAPI(client: client),
startService: DroneDockStartShootAPI(client: client), currentContext: { context })
startService: DroneDockStartShootAPI(client: client),
commandService: DroneDockCommandAPI(client: client), currentContext: { context })
return DroneDockShootingTaskViewController(viewModel: model,
materialsControllerFactory: { _, _ in
let unavailable = UIViewController()
@@ -65,18 +75,25 @@ private enum DroneDockStartShootMockResult: String {
case timeout
}
/// 无任何网络转发能力的响应替身;仅接受 mock.invalid 上约定的准备、模拟召唤和开拍请求。
/// 无任何网络转发能力的响应替身;仅接受 mock.invalid 上约定的准备、召唤、开拍和安全指令。
private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
private let result: DroneDockStartShootMockResult
private let commandResult: DroneDockStartShootMockResult
private let lock = NSLock()
private var hasCreated: Bool
private var hasSummoned: Bool
private var hasStarted = false
private var hasStarted: Bool
private var isPaused = false
private var isReturning = false
private var wasInterrupted = false
private var exchanges: [Exchange] = []
/// 固定当前实例结果,不能用参数切换到真实传输。
init(result: DroneDockStartShootMockResult, requiresPreparation: Bool) {
init(result: DroneDockStartShootMockResult, requiresPreparation: Bool,
commandResult: DroneDockStartShootMockResult, hasStarted: Bool) {
self.result = result
self.commandResult = commandResult
self.hasStarted = hasStarted
hasCreated = !requiresPreparation
hasSummoned = !requiresPreparation
}
@@ -99,7 +116,8 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
return item
}
let object: [String: Any] = ["source": "local_mock", "description": "纯内存模拟,未调用后端或设备",
"network_sent": false, "scenario": result.rawValue, "records": items]
"network_sent": false, "scenario": result.rawValue,
"command_scenario": commandResult.rawValue, "records": items]
guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) else {
return "本地模拟记录暂不可显示;没有网络请求。"
}
@@ -189,6 +207,34 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") }
return try envelope(shootingData())
}
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"],
let values = try? JSONDecoder().decode(CommandBody.self, from: body),
values.id == 901, let command = DroneDockSafetyCommand(rawValue: values.command) else {
throw URLError(.badURL)
}
guard availableCommands.contains(command) else {
return try envelope([:], code: 100099, message: "本地模拟:当前任务不允许这项指令")
}
switch commandResult {
case .businessFailure:
return try envelope([:], code: 100099, message: "本地模拟:指令被拒绝,未改变任务状态")
case .timeout:
throw URLError(.timedOut)
case .success:
switch command {
case .pause: isPaused = true
case .resume: isPaused = false
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,
"airport_sn": "LOCAL-MOCK-DOCK-201", "dji_status": simulatedPhase,
"metrics": simulatedMetrics])
}
}
guard request.httpMethod == "POST", url.path == "/api/app/airport/start-shoot",
url.query == nil, let body = request.httpBody,
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
@@ -197,6 +243,9 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
throw URLError(.unsupportedURL)
}
guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") }
guard !isPaused, !wasInterrupted else {
return try envelope([:], code: 100099, message: "本地模拟:任务暂停或已中断,不可开始拍摄")
}
guard !hasStarted else {
return try envelope([:], code: 100099, message: "本地模拟:该任务已开始,请读取任务状态")
}
@@ -233,31 +282,76 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
}
private func shootingData() -> [String: Any] {
["order_number": "LOCAL-MOCK-ORDER-901", "order_flight_task": taskData(), "task": taskData(),
let canStart = !hasStarted && !isPaused && !wasInterrupted
let phaseTitle: String
if wasInterrupted {
phaseTitle = isReturning ? "本地模拟:立即返航中断任务;无人机返航中" : "本地模拟:返航已取消,任务仍已中断"
} else if isPaused {
phaseTitle = "拍摄已暂停(模拟)"
} else {
phaseTitle = hasStarted ? "无人机正在拍摄中(模拟)" : "无人机已到达(模拟)"
}
let commands: [[String: String]] = availableCommands.map { command in
switch command {
case .pause: return ["command": command.rawValue, "label": "紧急暂停", "sub": "悬停待命"]
case .resume: return ["command": command.rawValue, "label": "继续拍摄", "sub": "恢复航线"]
case .returnHome: return ["command": command.rawValue, "label": "立即返航", "sub": "中断任务"]
case .cancelReturn: return ["command": command.rawValue, "label": "取消返航", "sub": "不恢复已中断任务"]
}
}
let deviceLabel = isReturning ? "返航中" : isPaused ? "悬停中" : hasStarted ? "拍摄中" : "空闲"
return ["order_number": "LOCAL-MOCK-ORDER-901", "order_flight_task": taskData(), "task": taskData(),
"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": hasStarted ? "拍摄中" : "空闲",
"status_text": hasStarted ? "模拟拍摄中 · 电量95%" : "模拟就绪 · 电量95%"],
"metrics": [["key": "battery", "value": "95%"], ["key": "env_temp", "value": "20.3℃"],
["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": "无雨"],
["key": "signal", "value": "良好"], ["key": "satellite", "value": "36颗"]],
"work_status": hasStarted ? 2 : 1, "work_status_label": deviceLabel,
"status_text": "本地模拟 · \(deviceLabel) · 电量95%"],
"metrics": simulatedMetrics,
"plane_status": ["scenic_id": 128, "connected": true, "poll_hint_ms": 5000],
"execute_gate": ["can_execute": !hasStarted, "code": hasStarted ? "already_started" : "ok",
"execute_gate": ["can_execute": canStart, "code": wasInterrupted ? "return_home" : hasStarted ? "already_started" : "ok",
"message": hasStarted ? "本地模拟:开拍已受理" : "本地模拟:允许验证开拍请求",
"primary_action": hasStarted ? "shooting" : "start_shoot",
"primary_action": canStart ? "start_shoot" : simulatedPhase,
"primary_action_label": hasStarted ? "拍摄中" : "开始拍摄"],
"ui": ["phase": hasStarted ? "shooting" : "arrived_pending_start",
"title": hasStarted ? "无人机正在拍摄中(模拟)" : "无人机已到达(模拟)",
"message": hasStarted ? "本地模拟状态回查:拍摄中,未向设备发送指令。" : "点击开始拍摄,仅验证本地接口流程。"]]
"ui": ["phase": simulatedPhase, "title": phaseTitle, "commands": commands,
"message": wasInterrupted ? phaseTitle : "本地模拟状态回查,未向设备发送指令。"]]
}
private func taskData() -> [String: Any] {
["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128,
var task: [String: Any] = ["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128,
"status": 20, "status_label": "执行中(模拟)", "wayline_status": 20, "wayline_status_label": "执行中(模拟)"]
if wasInterrupted {
task["status"] = 40
task["status_label"] = "任务已中断(模拟)"
task["wayline_status"] = 40
task["wayline_status_label"] = "已中断(模拟)"
task["result_code"] = "return_home"
task["result_message"] = isReturning ? "本地模拟:立即返航中断任务;无人机返航中。"
: "本地模拟:返航已取消,任务仍已中断,不能继续拍摄。"
}
return task
}
private var availableCommands: [DroneDockSafetyCommand] {
guard hasSummoned else { return [] }
if isReturning { return [.cancelReturn] }
if wasInterrupted { return [] }
return [isPaused ? .resume : .pause, .returnHome]
}
private var simulatedPhase: String {
if isReturning { return "returning" }
if wasInterrupted { return "failed" }
if isPaused { return "paused" }
return hasStarted ? "shooting" : "arrived_pending_start"
}
private var simulatedMetrics: [[String: String]] {
[["key": "battery", "value": "95%"], ["key": "env_temp", "value": "20.3℃"],
["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": "无雨"],
["key": "signal", "value": "良好"], ["key": "satellite", "value": "36颗"]]
}
private func envelope(_ data: [String: Any], code: Int = 100000, message: String = "local mock success") throws -> Data {
@@ -296,5 +390,11 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
private struct StartBody: Decodable {
let id: Int
}
/// 模拟指令仍严格匹配正式接口的整数任务 ID 与白名单指令码。
private struct CommandBody: Decodable {
let id: Int
let command: String
}
}
#endif
@@ -326,6 +326,11 @@ final class DroneShootingTaskSafetyButton: UIButton {
accessibilityLabel = title
accessibilityValue = subtitle
}
/// 切换同一位置的暂停/继续或返航/取消图标,不改变按钮布局。
func setControlSymbol(_ symbol: String) {
controlIconView.image = UIImage(systemName: symbol)
}
}
/// 任务本地静帧的全屏放大页,明确标记画面来源。