feat: 完善机巢模拟调试与素材交付交互
增加禁飞期间的设备指令拦截及本地模拟拍摄流程;适配订单素材库和景区空境库,完善素材筛选、预览与下载;订单交付入口改为方式选择弹窗并复用云端上传。补充单元测试、接口记录和模拟器截图。
This commit is contained in:
@@ -0,0 +1,300 @@
|
||||
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 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)
|
||||
}
|
||||
|
||||
/// 从正式准备页进入全新的纯内存模拟,不携带真实订单、账号或设备身份。
|
||||
static func makePreparationController() -> DroneDockRemotePreparationViewController? {
|
||||
makeFlow(result: .success, startsAtPreparation: true) as? DroneDockRemotePreparationViewController
|
||||
}
|
||||
|
||||
private static func makeFlow(result: DroneDockStartShootMockResult,
|
||||
startsAtPreparation: Bool) -> UIViewController? {
|
||||
let session = DroneDockStartShootMockSession(result: result, requiresPreparation: startsAtPreparation)
|
||||
let environment = APIEnvironment(baseURL: URL(string: "https://mock.invalid")!,
|
||||
webSocketURL: URL(string: "wss://mock.invalid/unused")!)
|
||||
let client = APIClient(environment: environment, session: session)
|
||||
let context = DroneDockHomeContext(userID: "local-start-shoot-mock", accountType: "store_user",
|
||||
scenicID: 128, scenicName: "本地模拟景区", storeID: 38,
|
||||
photographerName: "模拟操作员", token: "local-simulation-only")
|
||||
let orderData = Data(#"{"order_number":"LOCAL-MOCK-ORDER-901","project_id":101,"project_name":"模拟五次套餐","user_phone":"本地模拟游客","shoot_count":5,"shot_count":0,"remaining_count":5}"#.utf8)
|
||||
guard let order = try? JSONDecoder().decode(DroneDockHomeOrder.self, from: orderData) else { return nil }
|
||||
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 })
|
||||
return DroneDockShootingTaskViewController(viewModel: model,
|
||||
materialsControllerFactory: { _, _ in
|
||||
let unavailable = UIViewController()
|
||||
unavailable.title = "本地模拟不连接素材库"
|
||||
unavailable.view.backgroundColor = .systemBackground
|
||||
return unavailable
|
||||
},
|
||||
simulationRecordsProvider: { session.transcriptJSON })
|
||||
}
|
||||
guard startsAtPreparation else { return taskFactory(901, order, context) }
|
||||
let model = DroneDockPreparationViewModel(context: context, order: order,
|
||||
service: DroneDockPreparationAPI(client: client),
|
||||
planeStatusService: DroneDockPlaneStatusAPI(client: client),
|
||||
taskCreationService: DroneDockTaskCreationAPI(client: client),
|
||||
shootService: DroneDockShootAPI(client: client), allowsTaskSubmission: true,
|
||||
currentContext: { context })
|
||||
return DroneDockRemotePreparationViewController(viewModel: model,
|
||||
taskControllerFactory: taskFactory,
|
||||
simulationRecordsProvider: { session.transcriptJSON })
|
||||
}
|
||||
}
|
||||
|
||||
/// 模拟开拍请求的三种结果,不构成真实接口结果或设备执行反馈。
|
||||
private enum DroneDockStartShootMockResult: String {
|
||||
case success
|
||||
case businessFailure = "business-failure"
|
||||
case timeout
|
||||
}
|
||||
|
||||
/// 无任何网络转发能力的响应替身;仅接受 mock.invalid 上约定的准备、模拟召唤和开拍请求。
|
||||
private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
private let result: DroneDockStartShootMockResult
|
||||
private let lock = NSLock()
|
||||
private var hasCreated: Bool
|
||||
private var hasSummoned: Bool
|
||||
private var hasStarted = false
|
||||
private var exchanges: [Exchange] = []
|
||||
|
||||
/// 固定当前实例结果,不能用参数切换到真实传输。
|
||||
init(result: DroneDockStartShootMockResult, requiresPreparation: Bool) {
|
||||
self.result = result
|
||||
hasCreated = !requiresPreparation
|
||||
hasSummoned = !requiresPreparation
|
||||
}
|
||||
|
||||
/// 全部本地请求及完整模拟回执;任务、设备、游客均为虚构测试身份。
|
||||
var transcriptJSON: String {
|
||||
let records = lock.withLock { exchanges }
|
||||
let items: [[String: Any]] = records.map { record in
|
||||
var item: [String: Any] = ["method": record.request.httpMethod ?? "",
|
||||
"path": record.request.url?.path ?? ""]
|
||||
if let query = record.request.url?.query { item["query"] = query }
|
||||
if let body = record.request.httpBody {
|
||||
item["request_body"] = (try? JSONSerialization.jsonObject(with: body)) ?? String(decoding: body, as: UTF8.self)
|
||||
}
|
||||
if let response = record.responseData {
|
||||
item["http_status"] = 200
|
||||
item["response_body"] = (try? JSONSerialization.jsonObject(with: response)) ?? String(decoding: response, as: UTF8.self)
|
||||
}
|
||||
if let error = record.error { item["error"] = error }
|
||||
return item
|
||||
}
|
||||
let object: [String: Any] = ["source": "local_mock", "description": "纯内存模拟,未调用后端或设备",
|
||||
"network_sent": false, "scenario": result.rawValue, "records": items]
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) else {
|
||||
return "本地模拟记录暂不可显示;没有网络请求。"
|
||||
}
|
||||
return String(decoding: data, as: UTF8.self)
|
||||
}
|
||||
|
||||
/// 模拟少量等待后返回内存响应,任何未知请求均在本机失败,绝不回退真实请求。
|
||||
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
|
||||
print("[LOCAL MOCK][Request] \(request.httpMethod ?? "") \(request.url?.absoluteString ?? "") — 不联网")
|
||||
if let body = request.httpBody { print(String(decoding: body, as: UTF8.self)) }
|
||||
do {
|
||||
try Task.checkCancellation()
|
||||
if request.httpMethod == "POST" { try await Task.sleep(nanoseconds: 400_000_000) }
|
||||
try Task.checkCancellation()
|
||||
let data = try lock.withLock { try responseData(for: request) }
|
||||
lock.withLock { exchanges.append(Exchange(request: request, responseData: data, error: nil)) }
|
||||
guard let url = request.url,
|
||||
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) else {
|
||||
throw URLError(.badURL)
|
||||
}
|
||||
print("[LOCAL MOCK][Response] \(String(decoding: data, as: UTF8.self))")
|
||||
return (data, response)
|
||||
} catch {
|
||||
let message = error is CancellationError ? "本地模拟请求取消" : error.localizedDescription
|
||||
lock.withLock { exchanges.append(Exchange(request: request, responseData: nil, error: message)) }
|
||||
print("[LOCAL MOCK][Error] \(message) — 没有网络或设备指令")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func responseData(for request: URLRequest) throws -> Data {
|
||||
guard let url = request.url, url.scheme == "https", url.host == "mock.invalid" else {
|
||||
throw URLError(.unsupportedURL)
|
||||
}
|
||||
if request.httpMethod == "GET", url.path == "/api/yf-handset-app/photog/multi-plane/project-info" {
|
||||
guard queryMatches(url, required: ["scenic_id": "128", "project_id": "101",
|
||||
"order_number": "LOCAL-MOCK-ORDER-901"]) else { throw URLError(.badURL) }
|
||||
var payload = orderData()
|
||||
payload["spot"] = [["scenic_spot_id": 301, "scenic_spot_name": "模拟点位", "available": true,
|
||||
"air_lines": [["air_line_id": 401, "air_line_name": "模拟航线",
|
||||
"available": true, "samples": []]]]]
|
||||
return try envelope(payload)
|
||||
}
|
||||
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",
|
||||
"online_status": 1, "work_status": 1, "work_status_label": "空闲(模拟)",
|
||||
"status_text": "本地模拟 · 电量 95%", "battery_percent": 95,
|
||||
"can_fly": true, "is_receive_order": 1]
|
||||
return try envelope(["scenic_id": 128, "connected": true, "planes": [plane],
|
||||
"recommend": plane, "poll_hint_ms": 30000])
|
||||
}
|
||||
if request.httpMethod == "POST", url.path == "/api/yf-handset-app/photog/multi-plane/tasks/create" {
|
||||
guard url.query == nil, let body = request.httpBody,
|
||||
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
|
||||
Set(object.keys) == ["scenic_id", "order_number", "scenic_spot_id", "air_line_id"],
|
||||
let values = try? JSONDecoder().decode(CreateBody.self, from: body),
|
||||
values.scenicID == 128, values.orderNumber == "LOCAL-MOCK-ORDER-901",
|
||||
values.spotID == 301, values.airLineID == 401 else { throw URLError(.badURL) }
|
||||
guard !hasCreated else { return try envelope([:], code: 100099, message: "本地模拟:任务已经创建") }
|
||||
hasCreated = true
|
||||
var payload = orderData()
|
||||
payload["task_id"] = 901
|
||||
return try envelope(payload)
|
||||
}
|
||||
if request.httpMethod == "POST", url.path == "/api/app/airport/shoot" {
|
||||
guard url.query == nil, let body = request.httpBody,
|
||||
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
|
||||
Set(object.keys) == ["id", "restart"],
|
||||
let values = try? JSONDecoder().decode(ShootBody.self, from: body),
|
||||
values.id == 901, !values.restart else { throw URLError(.badURL) }
|
||||
guard hasCreated, !hasSummoned else {
|
||||
return try envelope([:], code: 100099, message: "本地模拟:任务尚未创建或已召唤")
|
||||
}
|
||||
hasSummoned = true
|
||||
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",
|
||||
"ui": ["phase": "arrived_pending_start", "title": "无人机已到达(模拟)",
|
||||
"message": "本地模拟召唤成功,没有网络或设备指令。"]])
|
||||
}
|
||||
if request.httpMethod == "GET", url.path == "/api/app/airport/shooting" {
|
||||
let query = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
|
||||
guard query.filter({ $0.name == "id" }).map(\.value) == ["901"] else {
|
||||
throw URLError(.badURL)
|
||||
}
|
||||
guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") }
|
||||
return try envelope(shootingData())
|
||||
}
|
||||
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],
|
||||
Set(object.keys) == ["id"],
|
||||
(try? JSONDecoder().decode(StartBody.self, from: body).id) == 901 else {
|
||||
throw URLError(.unsupportedURL)
|
||||
}
|
||||
guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") }
|
||||
guard !hasStarted else {
|
||||
return try envelope([:], code: 100099, message: "本地模拟:该任务已开始,请读取任务状态")
|
||||
}
|
||||
switch result {
|
||||
case .businessFailure:
|
||||
return try envelope([:], code: 100099, message: "本地模拟:电量不足,暂不可开始拍摄")
|
||||
case .timeout:
|
||||
throw URLError(.timedOut)
|
||||
case .success:
|
||||
hasStarted = true
|
||||
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",
|
||||
"ui": ["phase": "shooting", "title": "无人机正在拍摄中(模拟)",
|
||||
"message": "本地模拟开拍回执,不代表真实设备执行。", "primary_action": "shooting",
|
||||
"commands": [["command": "flighttask_pause", "label": "紧急暂停", "sub": "悬停待命"],
|
||||
["command": "return_home", "label": "立即返航", "sub": "中断任务"]]]
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
private func queryMatches(_ url: URL, required: [String: String]) -> Bool {
|
||||
let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
|
||||
return items.count == required.count && required.allSatisfy { key, value in
|
||||
items.filter { $0.name == key }.map(\.value) == [value]
|
||||
}
|
||||
}
|
||||
|
||||
private func orderData() -> [String: Any] {
|
||||
["order_number": "LOCAL-MOCK-ORDER-901", "project_id": 101, "project_name": "模拟五次套餐",
|
||||
"user_phone": "本地模拟游客", "shoot_count": 5, "shot_count": 0, "remaining_count": 5,
|
||||
"shoot_status": "processing", "order_status": 20, "can_create_task": true,
|
||||
"can_upload_film": false, "can_confirm": false, "film_count": 0]
|
||||
}
|
||||
|
||||
private func shootingData() -> [String: Any] {
|
||||
["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颗"]],
|
||||
"plane_status": ["scenic_id": 128, "connected": true, "poll_hint_ms": 5000],
|
||||
"execute_gate": ["can_execute": !hasStarted, "code": hasStarted ? "already_started" : "ok",
|
||||
"message": hasStarted ? "本地模拟:开拍已受理" : "本地模拟:允许验证开拍请求",
|
||||
"primary_action": hasStarted ? "shooting" : "start_shoot",
|
||||
"primary_action_label": hasStarted ? "拍摄中" : "开始拍摄"],
|
||||
"ui": ["phase": hasStarted ? "shooting" : "arrived_pending_start",
|
||||
"title": hasStarted ? "无人机正在拍摄中(模拟)" : "无人机已到达(模拟)",
|
||||
"message": hasStarted ? "本地模拟状态回查:拍摄中,未向设备发送指令。" : "点击开始拍摄,仅验证本地接口流程。"]]
|
||||
}
|
||||
|
||||
private func taskData() -> [String: Any] {
|
||||
["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128,
|
||||
"status": 20, "status_label": "执行中(模拟)", "wayline_status": 20, "wayline_status_label": "执行中(模拟)"]
|
||||
}
|
||||
|
||||
private func envelope(_ data: [String: Any], code: Int = 100000, message: String = "local mock success") throws -> Data {
|
||||
try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, "data": data],
|
||||
options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
|
||||
}
|
||||
|
||||
/// 完整记录每次本地请求结果,数据不落到真实接口或共享会话中。
|
||||
private struct Exchange {
|
||||
let request: URLRequest
|
||||
let responseData: Data?
|
||||
let error: String?
|
||||
}
|
||||
|
||||
/// 创建模拟任务仍验证真实合同的四项身份,不接受其他订单或航线。
|
||||
private struct CreateBody: Decodable {
|
||||
let scenicID: Int
|
||||
let orderNumber: String
|
||||
let spotID: Int
|
||||
let airLineID: Int
|
||||
|
||||
/// 张工任务创建请求字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case scenicID = "scenic_id", orderNumber = "order_number"
|
||||
case spotID = "scenic_spot_id", airLineID = "air_line_id"
|
||||
}
|
||||
}
|
||||
|
||||
/// 召唤只接受同一模拟任务且禁止重启,不产生真实设备操作。
|
||||
private struct ShootBody: Decodable {
|
||||
let id: Int
|
||||
let restart: Bool
|
||||
}
|
||||
|
||||
/// 用强类型解码确认本地开拍请求的 id 为整数。
|
||||
private struct StartBody: Decodable {
|
||||
let id: Int
|
||||
}
|
||||
}
|
||||
#endif
|
||||
Reference in New Issue
Block a user