Files
suixinkan_uikit/suixinkan/Features/DroneDock/Models/DroneDockShootingSocketMessage.swift
T

50 lines
2.5 KiB
Swift

import Foundation
/// HTTP 和 WebSocket 共用的快照接收结果;重复包可证明订阅有效,但旧包不能恢复实时状态。
enum DroneDockSnapshotAcceptance {
case applied, duplicate, outdated, invalid
}
/// 先解析业务码再解析 data,兼容订阅失败时 data=[]。
enum DroneDockShootingSocketMessage {
case subscribed(taskID: Int, hasSnapshot: Bool)
case snapshot(DroneDockShootingResponse)
case rejected(code: Int, message: String)
case unrelated
/// WebSocket 成功码为 0,不使用 HTTP 的 100000 Envelope。
static func decode(_ data: Data) throws -> Self {
guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let code = root["code"] as? Int else { throw APIError.invalidResponse }
if code != 0 {
return .rejected(code: code, message: root["msg"] as? String ?? "任务订阅失败")
}
guard let body = root["data"] as? [String: Any] else { throw APIError.invalidResponse }
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 }
return .subscribed(taskID: id, hasSnapshot: hasSnapshot)
}
guard body["action"] as? String == "app_airport_shooting_updated" else { return .unrelated }
guard let params = body["params"] as? [String: Any] else { throw APIError.invalidResponse }
let value = try JSONDecoder().decode(DroneDockShootingResponse.self,
from: JSONSerialization.data(withJSONObject: params))
guard value.orderFlightTaskID != nil, value.snapshotKind == "full",
let version = value.stateVersion, version > 0,
let batch = value.executionBatch, batch >= 0, value.ui?.phase != nil else {
throw APIError.decodeFailed("任务推送缺少完整快照或版本信息")
}
return .snapshot(value)
}
/// 构造已确认的只读订阅协议,不暴露任意 type 的发送入口。
static func subscribe(taskID: Int, token: String) -> String {
DroneDockDiagnostics.json(["type": 310, "params": ["id": taskID, "socket_token": token]])
}
/// 离页尽力取消订阅;断开连接也会清除服务端 fd 订阅。
static func unsubscribe(taskID: Int) -> String {
DroneDockDiagnostics.json(["type": 311, "params": ["id": taskID]])
}
}