~johnhamelink/mopidy-swift

9eea9c27de023b7667e3a801eb2782b53e980429 — John Hamelink 9 months ago 49fffdd
Began to sketch out websocket implementation
M Sources/mopidy-swift/mopidy_swift.swift => Sources/mopidy-swift/mopidy_swift.swift +43 -2
@@ 1,3 1,44 @@
struct mopidy_swift {
    var text = "Hello, World!"
import Foundation
import Starscream

enum JSONRPCMethod: String, Codable {
    case getCurrentTrack = "core.playback.get_current_track"
}

struct JSONRPCRequest: Codable {
    var jsonrpc: String = "2.0"
    var id: Int
    var method: JSONRPCMethod
}

class MopidySwift: WebSocketDelegate {

    var socket: WebSocket? = nil
    static let shared = MopidySwift()

    static func connect() throws -> MopidySwift {
        var request = URLRequest(url: URL(string: "http://localhost:6680/mopidy/ws")!)
        request.timeoutInterval = 5
        shared.socket = WebSocket(request: request)
        shared.socket!.delegate = shared
        shared.socket!.connect()

        return shared
    }

    func didReceive(event: WebSocketEvent, client: WebSocket) {
        switch event {
        case .text(let string):
            print("Recieved: \(string)")
        default:
            print("Received an event we don't handle yet (\(event))")
        }
    }

    func getCurrentTrack() {
        let json = """
          {"jsonrpc":"2.0","id":1,"method":"core.playback.get_current_track"}
          """
        MopidySwift.shared.socket?.write(string: json)
    }
}

M Tests/mopidy-swiftTests/mopidy_swiftTests.swift => Tests/mopidy-swiftTests/mopidy_swiftTests.swift +9 -1
@@ 6,7 6,15 @@ final class mopidy_swiftTests: XCTestCase {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct
        // results.
        XCTAssertEqual(mopidy_swift().text, "Hello, World!")

        do {
            let client = try MopidySwift.connect()
            client.getCurrentTrack()
        } catch {
            print(error)
        }

        //XCTAssertEqual(mopidy_swift().text, "Hello, World!")
    }

    static var allTests = [