2023-02-09 01:19:23 +00:00
|
|
|
//
|
2023-05-24 17:35:51 +00:00
|
|
|
// MoonrakerSocketManager.swift
|
2023-02-09 01:19:23 +00:00
|
|
|
// KlipperMon
|
|
|
|
//
|
|
|
|
// Created by maddiefuzz on 2/7/23.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import Network
|
2023-03-20 23:58:40 +00:00
|
|
|
import AppKit
|
2023-02-09 05:29:15 +00:00
|
|
|
import Starscream
|
2023-02-09 01:19:23 +00:00
|
|
|
|
2023-02-23 01:14:11 +00:00
|
|
|
|
2023-04-05 17:49:05 +00:00
|
|
|
class MoonrakerSocketManager: ObservableObject, WebSocketDelegate {
|
2023-02-21 05:35:54 +00:00
|
|
|
let WEBSOCKET_TIMEOUT_INTERVAL: TimeInterval = 60.0
|
|
|
|
|
|
|
|
// Websocket JSON-RPC published data
|
|
|
|
@Published var state: String
|
|
|
|
@Published var progress: Double
|
|
|
|
@Published var extruderTemperature: Double
|
|
|
|
@Published var bedTemperature: Double
|
2023-02-09 05:29:15 +00:00
|
|
|
|
2023-02-21 05:35:54 +00:00
|
|
|
// Active connection published data
|
|
|
|
@Published var isConnected = false
|
|
|
|
@Published var socketHost: String
|
|
|
|
@Published var socketPort: String
|
2023-02-09 05:29:15 +00:00
|
|
|
|
2023-03-24 18:42:17 +00:00
|
|
|
// Published NWConnection for listing connection information
|
|
|
|
@Published var connection: NWConnection?
|
2023-05-28 02:29:05 +00:00
|
|
|
@Published var friendlyHostname: String = ""
|
2023-03-24 18:42:17 +00:00
|
|
|
|
2023-06-07 19:47:26 +00:00
|
|
|
var notification = UserNotificationHandler.shared
|
|
|
|
|
2023-03-24 18:42:17 +00:00
|
|
|
private var socket: WebSocket?
|
|
|
|
private var lastPingDate = Date()
|
2023-05-24 17:35:51 +00:00
|
|
|
private var starscreamEngine: Engine
|
2023-02-09 01:19:23 +00:00
|
|
|
|
2023-02-21 05:35:54 +00:00
|
|
|
|
2023-03-21 00:31:18 +00:00
|
|
|
// MARK: PRM init()
|
2023-05-24 17:35:51 +00:00
|
|
|
init(starscreamEngine: Engine = WSEngine(transport: TCPTransport())) {
|
2023-02-21 05:35:54 +00:00
|
|
|
state = ""
|
|
|
|
progress = 0.0
|
|
|
|
extruderTemperature = 0.0
|
|
|
|
bedTemperature = 0.0
|
|
|
|
socketHost = ""
|
|
|
|
socketPort = ""
|
2023-03-20 23:58:40 +00:00
|
|
|
|
2023-05-24 17:35:51 +00:00
|
|
|
self.starscreamEngine = starscreamEngine
|
|
|
|
|
2023-03-21 00:31:18 +00:00
|
|
|
// Set up sleep/wake notification observers
|
2023-03-20 23:58:40 +00:00
|
|
|
let center = NSWorkspace.shared.notificationCenter;
|
|
|
|
let mainQueue = OperationQueue.main
|
|
|
|
|
|
|
|
center.addObserver(forName: NSWorkspace.screensDidWakeNotification, object: nil, queue: mainQueue) { notification in
|
|
|
|
self.screenChangedSleepState(notification)
|
|
|
|
}
|
|
|
|
|
|
|
|
center.addObserver(forName: NSWorkspace.screensDidSleepNotification, object: nil, queue: mainQueue) { notification in
|
|
|
|
self.screenChangedSleepState(notification)
|
|
|
|
}
|
2023-02-09 05:29:15 +00:00
|
|
|
}
|
|
|
|
|
2023-02-21 05:35:54 +00:00
|
|
|
// Called from the UI with an endpoint.
|
2023-02-09 06:35:26 +00:00
|
|
|
// Momentarily connect/disconnects from the endpoint to retrieve the host/port
|
|
|
|
// calls private function openWebsocket to process the host/port
|
2023-03-21 00:31:18 +00:00
|
|
|
func connectToBonjourEndpoint(_ endpoint: NWEndpoint) {
|
2023-02-21 05:35:54 +00:00
|
|
|
// Debug stuff
|
|
|
|
endpoint.txtRecord?.forEach({ (key: String, value: NWTXTRecord.Entry) in
|
|
|
|
print("\(key): \(value)")
|
|
|
|
})
|
|
|
|
|
2023-06-07 19:47:26 +00:00
|
|
|
// if isConnected == true {
|
|
|
|
// connection?.cancel()
|
|
|
|
// socket?.disconnect()
|
|
|
|
// }
|
|
|
|
//
|
2023-06-27 22:41:22 +00:00
|
|
|
if connection == nil || connection?.state == .cancelled {
|
2023-03-24 18:42:17 +00:00
|
|
|
connection = NWConnection(to: endpoint, using: .tcp)
|
|
|
|
}
|
|
|
|
|
|
|
|
connection?.stateUpdateHandler = { [self] state in
|
2023-02-09 05:29:15 +00:00
|
|
|
switch state {
|
|
|
|
case .ready:
|
2023-03-24 18:42:17 +00:00
|
|
|
if let innerEndpoint = connection?.currentPath?.remoteEndpoint, case .hostPort(let host, let port) = innerEndpoint {
|
2023-02-21 05:35:54 +00:00
|
|
|
let hostPortDebugOutput = "Connected to \(host):\(port)"
|
|
|
|
|
|
|
|
print(hostPortDebugOutput)
|
|
|
|
|
2023-02-09 05:29:15 +00:00
|
|
|
let hostString = "\(host)"
|
2023-02-21 05:35:54 +00:00
|
|
|
let regex = try! Regex("%(.+)")
|
2023-02-09 05:29:15 +00:00
|
|
|
let match = hostString.firstMatch(of: regex)
|
2023-05-24 17:35:51 +00:00
|
|
|
|
|
|
|
let sanitizedHost = hostString.replacingOccurrences(of: match?.0 ?? "", with: "")
|
2023-02-09 05:29:15 +00:00
|
|
|
|
|
|
|
print("[sanitized] Resolved \(sanitizedHost):\(port)")
|
2023-02-21 05:35:54 +00:00
|
|
|
|
2023-03-24 18:42:17 +00:00
|
|
|
connection?.cancel()
|
2023-03-21 00:31:18 +00:00
|
|
|
|
|
|
|
DispatchQueue.main.async {
|
2023-06-07 19:47:26 +00:00
|
|
|
self.friendlyHostname = endpoint.toFriendlyString()
|
2023-03-21 00:31:18 +00:00
|
|
|
self.socketHost = sanitizedHost
|
|
|
|
self.socketPort = "\(port)"
|
|
|
|
self.openWebsocket()
|
|
|
|
}
|
2023-02-09 05:29:15 +00:00
|
|
|
}
|
|
|
|
default:
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2023-03-24 18:42:17 +00:00
|
|
|
connection?.start(queue: .global())
|
|
|
|
}
|
|
|
|
|
|
|
|
func disconnect() {
|
2023-05-28 02:29:05 +00:00
|
|
|
print("disconnect() called")
|
2023-06-27 22:41:22 +00:00
|
|
|
self.isConnected = false
|
2023-03-24 18:42:17 +00:00
|
|
|
socket?.disconnect()
|
2023-06-27 22:41:22 +00:00
|
|
|
socket = nil
|
2023-02-09 01:19:23 +00:00
|
|
|
}
|
2023-06-07 19:47:26 +00:00
|
|
|
|
2023-02-09 01:19:23 +00:00
|
|
|
|
2023-03-21 00:31:18 +00:00
|
|
|
// MARK: Private functions
|
2023-02-21 05:35:54 +00:00
|
|
|
|
2023-02-09 06:35:26 +00:00
|
|
|
// Opens the websocket connection
|
2023-06-27 22:41:22 +00:00
|
|
|
func openWebsocket() {
|
2023-05-28 02:29:05 +00:00
|
|
|
// Exit function if there is no server to connect to
|
|
|
|
if socketHost.isEmpty || socketPort.isEmpty {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-06-27 22:41:22 +00:00
|
|
|
if socket != nil {
|
|
|
|
socket!.connect()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-05-28 02:29:05 +00:00
|
|
|
lastPingDate = Date.now
|
|
|
|
|
2023-06-27 22:41:22 +00:00
|
|
|
var request = URLRequest(url: URL(string: "ws://\(socketHost):\(socketPort)/websocket")!)
|
2023-05-28 02:29:05 +00:00
|
|
|
request.timeoutInterval = 30
|
2023-05-24 17:35:51 +00:00
|
|
|
socket = WebSocket(request: request, engine: starscreamEngine)
|
2023-02-21 05:35:54 +00:00
|
|
|
socket!.delegate = self
|
2023-05-24 17:35:51 +00:00
|
|
|
print("About to connect to WebSocket at: \(request.debugDescription)")
|
2023-02-21 05:35:54 +00:00
|
|
|
socket!.connect()
|
2023-03-21 00:31:18 +00:00
|
|
|
}
|
|
|
|
|
2023-05-28 02:29:05 +00:00
|
|
|
// TODO: This may not work properly when already connected to the socket
|
2023-03-21 00:31:18 +00:00
|
|
|
private func reconnectWebsocket() {
|
|
|
|
if socket == nil {
|
2023-05-28 02:29:05 +00:00
|
|
|
print("Socket doesn't exist. Fail-safe triggered.")
|
2023-03-21 00:31:18 +00:00
|
|
|
return
|
|
|
|
}
|
2023-02-21 05:35:54 +00:00
|
|
|
|
2023-03-21 00:31:18 +00:00
|
|
|
socket!.disconnect()
|
|
|
|
self.openWebsocket()
|
|
|
|
}
|
|
|
|
|
2023-05-24 17:35:51 +00:00
|
|
|
// MARK: Callbacks
|
2023-03-21 00:31:18 +00:00
|
|
|
func screenChangedSleepState(_ notification: Notification) {
|
|
|
|
switch(notification.name) {
|
|
|
|
case NSWorkspace.screensDidSleepNotification:
|
2023-05-28 02:29:05 +00:00
|
|
|
print("Screen slept. Disconnecting..")
|
2023-06-27 22:41:22 +00:00
|
|
|
self.disconnect()
|
|
|
|
//socket?.disconnect()
|
2023-03-21 00:31:18 +00:00
|
|
|
case NSWorkspace.screensDidWakeNotification:
|
2023-05-28 02:29:05 +00:00
|
|
|
print("Screen awoke. Opening websocket..")
|
2023-03-21 00:31:18 +00:00
|
|
|
self.openWebsocket()
|
|
|
|
default:
|
|
|
|
return
|
2023-02-09 06:35:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-21 05:35:54 +00:00
|
|
|
func didReceive(event: Starscream.WebSocketEvent, client: Starscream.WebSocket) {
|
|
|
|
switch event {
|
|
|
|
case .connected(let headers):
|
|
|
|
isConnected = true
|
|
|
|
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("[send] json-rpc printer.objects.subscribe query")
|
|
|
|
})
|
|
|
|
case .disconnected(let reason, let code):
|
|
|
|
isConnected = false
|
|
|
|
print("websocket is disconnected: \(reason) with code: \(code)")
|
|
|
|
case .text(let string):
|
|
|
|
// Check for initial RPC response
|
|
|
|
let statusResponse = try? JSONDecoder().decode(jsonRpcResponse.self, from: Data(string.utf8))
|
|
|
|
if let statusResponseSafe = statusResponse {
|
|
|
|
self.parse_response(statusResponseSafe)
|
2023-02-09 01:19:23 +00:00
|
|
|
}
|
2023-02-21 05:35:54 +00:00
|
|
|
// Check for RPC updates
|
|
|
|
if let updateResponse = try? JSONDecoder().decode(jsonRpcUpdate.self, from: Data(string.utf8)) {
|
|
|
|
self.parse_update(updateResponse)
|
|
|
|
}
|
|
|
|
case .binary(let data):
|
|
|
|
print("Received data: \(data.count)")
|
|
|
|
case .ping(_):
|
|
|
|
print("PING! \(Date())")
|
|
|
|
// TODO: There's probably a better way to do this
|
|
|
|
if(lastPingDate.addingTimeInterval(WEBSOCKET_TIMEOUT_INTERVAL) < Date.now) {
|
|
|
|
print("Forcing reconnection of websocket..")
|
|
|
|
self.reconnectWebsocket()
|
|
|
|
}
|
|
|
|
lastPingDate = Date()
|
|
|
|
break
|
|
|
|
case .pong(_):
|
|
|
|
print("PONG!")
|
|
|
|
break
|
|
|
|
case .viabilityChanged(_):
|
|
|
|
break
|
|
|
|
case .reconnectSuggested(_):
|
|
|
|
break
|
|
|
|
case .cancelled:
|
|
|
|
isConnected = false
|
|
|
|
case .error(let error):
|
|
|
|
isConnected = false
|
|
|
|
print("[error] Starscream: \(error.debugDescription)")
|
2023-06-27 22:41:22 +00:00
|
|
|
switch(error) {
|
|
|
|
case .some(HTTPUpgradeError.notAnUpgrade(200)):
|
|
|
|
print("[debug] Starscream: Forcing disconnect and reconnect..")
|
|
|
|
self.socket?.forceDisconnect()
|
|
|
|
self.socket = nil
|
|
|
|
self.openWebsocket()
|
|
|
|
default:
|
|
|
|
break
|
|
|
|
}
|
2023-02-09 01:19:23 +00:00
|
|
|
}
|
|
|
|
}
|
2023-02-21 05:35:54 +00:00
|
|
|
|
2023-03-21 00:31:18 +00:00
|
|
|
// MARK: JSON-RPC Parsing
|
|
|
|
// Parse a JSON-RPC query-response message
|
|
|
|
func parse_response(_ response: jsonRpcResponse) {
|
|
|
|
state = response.result.status.print_stats?.state ?? ""
|
2023-06-07 19:47:26 +00:00
|
|
|
|
|
|
|
|
2023-03-21 00:31:18 +00:00
|
|
|
progress = response.result.status.virtual_sdcard?.progress ?? 0.0
|
|
|
|
extruderTemperature = response.result.status.extruder?.temperature ?? 0.0
|
|
|
|
bedTemperature = response.result.status.heater_bed?.temperature ?? 0.0
|
|
|
|
}
|
|
|
|
|
|
|
|
// Parse a JSON-RPC update message
|
|
|
|
func parse_update(_ update: jsonRpcUpdate) {
|
|
|
|
if let newState = update.params.status?.print_stats?.state {
|
2023-06-07 19:47:26 +00:00
|
|
|
print("Printer state: \(newState)")
|
|
|
|
// Issue a notification when state changes from printing to complete
|
|
|
|
// TODO: Handle this better
|
|
|
|
if newState == "complete" && state == "printing" {
|
|
|
|
notification.sendNotification(.printComplete)
|
|
|
|
}
|
2023-03-21 00:31:18 +00:00
|
|
|
state = newState
|
|
|
|
}
|
|
|
|
if let newProgress = update.params.status?.virtual_sdcard?.progress {
|
|
|
|
progress = newProgress
|
|
|
|
}
|
|
|
|
if let newExtruderTemp = update.params.status?.extruder?.temperature {
|
|
|
|
extruderTemperature = newExtruderTemp
|
|
|
|
}
|
|
|
|
if let newBedTemp = update.params.status?.heater_bed?.temperature {
|
|
|
|
bedTemperature = newBedTemp
|
|
|
|
}
|
|
|
|
}
|
2023-02-09 01:19:23 +00:00
|
|
|
}
|
2023-03-24 18:42:17 +00:00
|
|
|
|
|
|
|
// Properly formatted JSON-RPC Request for use with Starscream
|
|
|
|
// MARK: JSON-RPC Request Codable
|
|
|
|
struct JsonRpcRequest: Codable {
|
|
|
|
var jsonrpc = "2.0"
|
|
|
|
let method: String
|
|
|
|
let params: [String: [String: String?]]
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|