Files
suixinkan_uikit/suixinkan/Features/DroneDock/Services/DroneDockShootingSocketTransport.swift
T

60 lines
2.2 KiB
Swift

import Foundation
/// 任务 WebSocket 的隔离传输边界,测试替身不能转发到真实网络。
@MainActor
protocol DroneDockShootingSocketTransport: AnyObject {
/// 发送订阅 JSON。
func send(_ text: String) async throws
/// 等待一条完整消息。
func receive() async throws -> Data
/// 使用原生 Ping/Pong 检查链路,不发送业务或设备指令。
func ping() async throws
/// 关闭连接,离页时尽力发送 311,最多等待一秒。
func close(unsubscribing taskID: Int?)
}
/// Foundation WebSocket 实现;连接生命周期由任务页的实时协调器管理。
@MainActor
final class DroneDockURLSessionShootingSocket: DroneDockShootingSocketTransport {
private let socket: URLSessionWebSocketTask
/// 仅使用环境指定的 wss 地址,无登录 Header、无设备连接。
init(url: URL, session: URLSession = .shared) {
socket = session.webSocketTask(with: url)
socket.resume()
}
deinit { socket.cancel(with: .goingAway, reason: nil) }
func send(_ text: String) async throws { try await socket.send(.string(text)) }
func receive() async throws -> Data {
switch try await socket.receive() {
case .string(let text): return Data(text.utf8)
case .data(let data): return data
@unknown default: throw APIError.invalidResponse
}
}
func ping() async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
socket.sendPing { error in
if let error { continuation.resume(throwing: error) }
else { continuation.resume() }
}
}
}
func close(unsubscribing taskID: Int?) {
guard let taskID else { socket.cancel(with: .goingAway, reason: nil); return }
let socket = socket
socket.send(.string(DroneDockShootingSocketMessage.unsubscribe(taskID: taskID))) { _ in
socket.cancel(with: .normalClosure, reason: nil)
}
Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
socket.cancel(with: .normalClosure, reason: nil)
}
}
}