Websocket request implementation
This commit is contained in:
parent
ee2583172a
commit
ab849a721b
@ -8,14 +8,6 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import AppKit
|
import AppKit
|
||||||
|
|
||||||
struct KlipperMenuBarButtonStyle: ButtonStyle {
|
|
||||||
func makeBody(configuration: Configuration) -> some View {
|
|
||||||
configuration.label
|
|
||||||
.padding()
|
|
||||||
.foregroundColor(.white)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct KlipperMonMenuBarExtraView: View {
|
struct KlipperMonMenuBarExtraView: View {
|
||||||
let DANGERTEMP = 40.0
|
let DANGERTEMP = 40.0
|
||||||
|
|
||||||
|
@ -9,21 +9,39 @@ import Foundation
|
|||||||
import Network
|
import Network
|
||||||
import Starscream
|
import Starscream
|
||||||
|
|
||||||
struct JsonRpcRequest: Encodable {
|
struct JsonRpcRequest: Codable {
|
||||||
let jsonrpc = "2.0"
|
var jsonrpc = "2.0"
|
||||||
let method: String
|
let method: String
|
||||||
let params: [String: String]
|
let params: [String: [String: String?]]
|
||||||
//let id = UUID()
|
var id = 1
|
||||||
|
|
||||||
|
func encode(to encoder: Encoder) throws {
|
||||||
|
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||||
|
try container.encode(jsonrpc, forKey: .jsonrpc)
|
||||||
|
try container.encode(method, forKey: .method)
|
||||||
|
try container.encode(params, forKey: .params)
|
||||||
|
try container.encode(id, forKey: .id)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class PrinterRequestManager: ObservableObject, WebSocketDelegate {
|
class PrinterRequestManager: ObservableObject, WebSocketDelegate {
|
||||||
func didReceive(event: Starscream.WebSocketEvent, client: Starscream.WebSocket) {
|
func didReceive(event: Starscream.WebSocketEvent, client: Starscream.WebSocket) {
|
||||||
switch event {
|
switch event {
|
||||||
case .connected(let headers):
|
case .connected(let headers):
|
||||||
//isConnected = true
|
|
||||||
print("websocket is connected: \(headers)")
|
print("websocket is connected: \(headers)")
|
||||||
|
let jsonRpcRequest = JsonRpcRequest(method: "printer.objects.subscribe",
|
||||||
|
params: ["objects":
|
||||||
|
["extruder": nil,
|
||||||
|
"virtual_sdcard": nil,
|
||||||
|
"heater_bed": nil,
|
||||||
|
"print_stats": nil]
|
||||||
|
])
|
||||||
|
|
||||||
|
print(String(data: try! JSONEncoder().encode(jsonRpcRequest), encoding: .utf8)!)
|
||||||
|
socket.write(data: try! JSONEncoder().encode(jsonRpcRequest), completion: {
|
||||||
|
print("Data transferred.")
|
||||||
|
})
|
||||||
case .disconnected(let reason, let code):
|
case .disconnected(let reason, let code):
|
||||||
//isConnected = false
|
|
||||||
print("websocket is disconnected: \(reason) with code: \(code)")
|
print("websocket is disconnected: \(reason) with code: \(code)")
|
||||||
case .text(let string):
|
case .text(let string):
|
||||||
print("Received text: \(string)")
|
print("Received text: \(string)")
|
||||||
@ -38,12 +56,9 @@ class PrinterRequestManager: ObservableObject, WebSocketDelegate {
|
|||||||
case .reconnectSuggested(_):
|
case .reconnectSuggested(_):
|
||||||
break
|
break
|
||||||
case .cancelled:
|
case .cancelled:
|
||||||
//isConnected = false
|
|
||||||
break
|
break
|
||||||
case .error(let error):
|
case .error(let error):
|
||||||
print("[error] Starscream: \(error.debugDescription)")
|
print("[error] Starscream: \(error.debugDescription)")
|
||||||
//isConnected = false
|
|
||||||
//handleError(error)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,30 +81,15 @@ class PrinterRequestManager: ObservableObject, WebSocketDelegate {
|
|||||||
static let shared = PrinterRequestManager()
|
static let shared = PrinterRequestManager()
|
||||||
|
|
||||||
private init() {
|
private init() {
|
||||||
// MARK: Starscream shit
|
// MARK: Bonjour browser initialization at instantiation
|
||||||
//
|
|
||||||
//
|
|
||||||
print("init PRM..")
|
|
||||||
// var request = URLRequest(url: URL(string: "http://10.0.21.39:7125/websocket")!)
|
|
||||||
// request.timeoutInterval = 5
|
|
||||||
// socket = WebSocket(request: request)
|
|
||||||
// socket.delegate = self
|
|
||||||
//socket.connect()
|
|
||||||
|
|
||||||
//let data = try! JSONEncoder().encode(JsonRpcRequest(method: "printer.objects.list", params: [:]))
|
|
||||||
//socket.write(data: data)
|
|
||||||
|
|
||||||
// MARK: NWBrowser shit
|
|
||||||
//
|
|
||||||
//
|
|
||||||
nwBrowser.browseResultsChangedHandler = { (newResults, changes) in
|
nwBrowser.browseResultsChangedHandler = { (newResults, changes) in
|
||||||
print("[update] Results changed.")
|
print("[update] Results changed.")
|
||||||
newResults.forEach { result in
|
newResults.forEach { result in
|
||||||
print(result)
|
print(result)
|
||||||
self.nwBrowserDiscoveredItems.append(result.endpoint)
|
self.nwBrowserDiscoveredItems.append(result.endpoint)
|
||||||
}
|
}
|
||||||
//self.nwBrowserDiscoveredItems.append(newResults.description)
|
|
||||||
}
|
}
|
||||||
|
// State update handler
|
||||||
nwBrowser.stateUpdateHandler = { newState in
|
nwBrowser.stateUpdateHandler = { newState in
|
||||||
switch newState {
|
switch newState {
|
||||||
case .failed(let error):
|
case .failed(let error):
|
||||||
@ -105,20 +105,13 @@ class PrinterRequestManager: ObservableObject, WebSocketDelegate {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Start up the bonjour browser, get results and process them in the update handler
|
||||||
nwBrowser.start(queue: DispatchQueue.main)
|
nwBrowser.start(queue: DispatchQueue.main)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func openWebsocket() {
|
// Called from the UI, providing an endpoint.
|
||||||
if let host = socketHost, let port = socketPort {
|
// Momentarily connect/disconnects from the endpoint to retrieve the host/port
|
||||||
//let fullUrlString = "http://\(socketHost):\(socketPort)/websocket"
|
// calls private function openWebsocket to process the host/port
|
||||||
var request = URLRequest(url: URL(string: "http://\(host):\(port)/websocket")!)
|
|
||||||
request.timeoutInterval = 5
|
|
||||||
socket = WebSocket(request: request)
|
|
||||||
socket.delegate = self
|
|
||||||
socket.connect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func resolveBonjourHost(_ endpoint: NWEndpoint) {
|
func resolveBonjourHost(_ endpoint: NWEndpoint) {
|
||||||
connection = NWConnection(to: endpoint, using: .tcp)
|
connection = NWConnection(to: endpoint, using: .tcp)
|
||||||
connection.stateUpdateHandler = { [self] state in
|
connection.stateUpdateHandler = { [self] state in
|
||||||
@ -142,13 +135,23 @@ class PrinterRequestManager: ObservableObject, WebSocketDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
connection.start(queue: .global())
|
connection.start(queue: .global())
|
||||||
//connection.cancel()
|
|
||||||
|
|
||||||
//self.openWebsocket()
|
|
||||||
}
|
}
|
||||||
// NWConnection shit
|
|
||||||
//connection = NWConnection(
|
|
||||||
|
|
||||||
|
// Opens the websocket connection
|
||||||
|
// TODO: host and port should be function arguments probably maybe
|
||||||
|
private func openWebsocket() {
|
||||||
|
if let host = socketHost, let port = socketPort {
|
||||||
|
//let fullUrlString = "http://\(socketHost):\(socketPort)/websocket"
|
||||||
|
var request = URLRequest(url: URL(string: "http://\(host):\(port)/websocket")!)
|
||||||
|
request.timeoutInterval = 5
|
||||||
|
socket = WebSocket(request: request)
|
||||||
|
socket.delegate = self
|
||||||
|
socket.connect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Old REST way to do it
|
||||||
|
// TODO: Stop using this.
|
||||||
func queryPrinterStats() async {
|
func queryPrinterStats() async {
|
||||||
guard let url = URL(string: "http://10.0.21.39/printer/objects/query?extruder&virtual_sdcard&print_stats&heater_bed") else {
|
guard let url = URL(string: "http://10.0.21.39/printer/objects/query?extruder&virtual_sdcard&print_stats&heater_bed") else {
|
||||||
fatalError("Missing URL")
|
fatalError("Missing URL")
|
||||||
@ -165,7 +168,6 @@ class PrinterRequestManager: ObservableObject, WebSocketDelegate {
|
|||||||
let decoder = JSONDecoder()
|
let decoder = JSONDecoder()
|
||||||
printerObjectsQuery = try decoder.decode(PrinterObjectsQuery.self, from: data)
|
printerObjectsQuery = try decoder.decode(PrinterObjectsQuery.self, from: data)
|
||||||
printerCommsOkay = true
|
printerCommsOkay = true
|
||||||
//return printerObjectsQuery.result.status.extruder.temperature
|
|
||||||
} catch {
|
} catch {
|
||||||
print("Exception thrown: \(error)")
|
print("Exception thrown: \(error)")
|
||||||
printerCommsOkay = false
|
printerCommsOkay = false
|
||||||
|
Loading…
Reference in New Issue
Block a user