Change URL protocol to HTTPS and WSS when connecting to port 443

This commit is contained in:
Nick Douma 2022-08-29 17:01:28 +02:00 committed by Alfredo Monclus
parent a599d667e9
commit 89e89ae1b2
2 changed files with 23 additions and 4 deletions

View File

@ -9,6 +9,13 @@ class KlippyRest:
self.port = port
self.api_key = api_key
@property
def endpoint(self):
protocol = "http"
if int(self.port) == 443:
protocol = "https"
return f"{protocol}://{self.ip}:{self.port}"
def get_server_info(self):
return self.send_request("server/info")
@ -22,7 +29,8 @@ class KlippyRest:
return self.send_request("printer/info")
def get_thumbnail_stream(self, thumbnail):
url = f"http://{self.ip}:{self.port}/server/files/gcodes/{thumbnail}"
url = f"{self.endpoint}/server/files/gcodes/{thumbnail}"
response = requests.get(url, stream=True)
if response.status_code == 200:
response.raw.decode_content = True
@ -30,7 +38,7 @@ class KlippyRest:
return False
def send_request(self, method):
url = f"http://{self.ip}:{self.port}/{method}"
url = f"{self.endpoint}/{method}"
logging.debug(f"Sending request to {url}")
headers = {} if self.api_key is False else {"x-api-key": self.api_key}
try:

View File

@ -44,7 +44,18 @@ class KlippyWebsocket(threading.Thread):
self.closing = False
self.ws = None
self._url = f"{host}:{port}"
self.host = host
self.port = port
@property
def _url(self):
return f"{self.host}:{self.port}"
@property
def ws_proto(self):
if int(self.port) == 443:
return "wss"
return "ws"
def initial_connect(self):
# Enable a timeout so that way if moonraker is not running, it will attempt to reconnect
@ -83,7 +94,7 @@ class KlippyWebsocket(threading.Thread):
logging.debug("Unable to get oneshot token")
return False
self.ws_url = f"ws://{self._url}/websocket?token={token}"
self.ws_url = f"{self.ws_proto}://{self._url}/websocket?token={token}"
self.ws = websocket.WebSocketApp(
self.ws_url, on_close=ws_on_close, on_error=ws_on_error, on_message=ws_on_message, on_open=ws_on_open)