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
@@ -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