import Foundation /// 基于既有订单飞行任务发送单次安全指令;测试使用独立的本地模拟服务。 protocol DroneDockCommandSending: Sendable { /// 提交任务 ID 和白名单指令,不创建任务、不选机,也不自动重试。 @MainActor func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse } /// 朱工 command 合同适配,校验任务身份及幂等指令回执。 @MainActor final class DroneDockCommandAPI: DroneDockCommandSending { private let client: APIClient /// 注入统一客户端;模拟调试使用完全不转发网络的响应替身。 init(client: APIClient) { self.client = client } /// 每次点击使用独立幂等键,回执必须对应同一任务、指令及请求。 func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse { try Task.checkCancellation() 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, clientRequestID: clientRequestID) )) 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 } /// 指令请求只携带任务身份及已确认的指令码。 private struct CommandBody: Encodable { let taskID: Int let command: String let clientRequestID: String /// 朱工请求字段映射,不附加飞机或模拟标志。 private enum CodingKeys: String, CodingKey { case taskID = "id", command, clientRequestID = "client_request_id" } } }