import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif class GatewayClient { let ws: URLSessionWebSocketTask var sequenceNum: Int? = nil init(gatewayURL: URL) { ws = URLSession.shared.webSocketTask(with: gatewayURL.appending(component: "?v=10&encoding=json")) } func openConnection() async throws { ws.resume() guard case .hello(let helloMessage) = try await getMessage().d else { throw GatewayError.mismatchedOpcode } dump(helloMessage) Timer.scheduledTimer(withTimeInterval: (helloMessage.heartbeat_interval / 1000.0), repeats: true) { } } func getMessage() async throws -> GatewayMessage { let wsMessage = try await ws.receive() guard case .string(let str) = wsMessage else { throw GatewayError.invalidMessage } let json = JSONDecoder() let gwMessage = try json.decode(GatewayMessage.self, from: Data(str.utf8)) sequenceNum = gwMessage.s ?? sequenceNum return gwMessage } } public enum GatewayError: Error { case invalidMessage case invalidOpcode case mismatchedOpcode }