Skip to content

Commit

Permalink
blah
Browse files Browse the repository at this point in the history
  • Loading branch information
glennerichall committed Feb 18, 2024
1 parent dee3463 commit 0219ab6
Show file tree
Hide file tree
Showing 5 changed files with 100 additions and 72 deletions.
9 changes: 4 additions & 5 deletions octoprint_zupfe/backend/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,14 @@ def set_octo_id(self, octo_id, api_key):
for key, value in self._original_urls.items():
self._urls_with_id[key] = value.replace(':uuid', str(self.octo_id))

def connect_wss(self, on_message, on_open=None, on_close=None, on_error=None):
def init_wss(self, on_message, on_open=None, on_close=None, on_error=None):
self._ws = WebSocketClient(self._backend_ws_url,
self.octo_id,
self.api_key,
on_message,
on_open=on_open,
on_error=on_error,
on_close=on_close)

def connect_ws(self):
logger.debug('Connecting to ' + self._backend_ws_url)
self._ws.connect()
self._ws.connect(self.octo_id, self.api_key, )
return self._ws

3 changes: 2 additions & 1 deletion octoprint_zupfe/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,4 +292,5 @@ async def on_request_stop_temperatures():
plugin.worker.submit_coroutines(handler())
else:
plugin.logger.debug("Command does not exist: " + str(message.command))
reject('Unknown request ' + str(message.command))
if message.is_command:
reject('Unknown request ' + str(message.command))
3 changes: 2 additions & 1 deletion octoprint_zupfe/loops/polling_thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ def start(self):
thread = threading.Thread(target=self.poll)
self._thread = thread

# daemon mode is mandatory so threads get killed when server shuts down
# daemon mode is mandatory so threads get killed when server shuts down const client = this.createClient(ws, req);

thread.daemon = True
thread.start()

Expand Down
98 changes: 57 additions & 41 deletions octoprint_zupfe/startup.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import asyncio

from .commands import handle_message
from octoprint_zupfe.loops.snapshots import snapshots_daily_push_loop
from .worker import AsyncTaskWorker
Expand Down Expand Up @@ -38,46 +40,60 @@ async def initialize_backend(plugin):
await plugin.backend.init()
plugin.frontend.emitInitialized()

octo_id = plugin.settings.get('octoprint_id', None)
api_key = plugin.settings.get('api_key', None)

uuid_valid = False
while not uuid_valid:
if octo_id is None:
plugin.logger.debug('No octoid, asking for a new one')
instance = await plugin.actions.new_octo_id()
plugin.logger.debug('Got a new octoid')
octo_id = instance['uuid']
api_key = instance['apiKey']
plugin.settings.save_if_updated('octoprint_id', octo_id)
plugin.settings.save_if_updated('api_key', api_key)
plugin.settings.save_if_updated('linked', False)
else:
plugin.backend.set_octo_id(octo_id, api_key)

plugin.logger.debug('Checking validity of octoid and api key')
uuid_valid = await plugin.actions.check_uuid()

if not uuid_valid:
plugin.logger.debug('Octoid not found on backend or api key is invalid, flushing octoid')
octo_id = None
api_key = None
else:
plugin.logger.debug('Octoid is valid')

# must transmit api key because:
# jinja may not have access to value when rendering wizard
# self.settings.settings.plugins.zupfe.api_key in zupfe.js does not seem to get settings everytime
plugin.frontend.emitApiKey(api_key)
async def validate_api_key():
octo_id = plugin.settings.get('octoprint_id', None)
api_key = plugin.settings.get('api_key', None)

uuid_valid = False
while not uuid_valid:
if octo_id is None:
plugin.logger.debug('No octoid, asking for a new one')
instance = await plugin.actions.new_octo_id()
plugin.logger.debug('Got a new octoid')
octo_id = instance['uuid']
api_key = instance['apiKey']
plugin.settings.save_if_updated('octoprint_id', octo_id)
plugin.settings.save_if_updated('api_key', api_key)
plugin.settings.save_if_updated('linked', False)
else:
plugin.backend.set_octo_id(octo_id, api_key)

plugin.logger.debug('Checking validity of octoid and api key')
uuid_valid = await plugin.actions.check_uuid()

if not uuid_valid:
plugin.logger.debug('Octoid not found on backend or api key is invalid, flushing octoid')
octo_id = None
api_key = None
else:
plugin.logger.debug('Octoid is valid')

# must transmit api key because:
# jinja may not have access to value when rendering wizard
# self.settings.settings.plugins.zupfe.api_key in zupfe.js does not seem to get settings everytime
plugin.frontend.emitApiKey(api_key)

async def on_close():
plugin.frontend.emitBackendDisconnected()
await validate_api_key()
await asyncio.sleep(1)
connect_ws()

def connect_ws():
try:
plugin.logger.debug('Connecting to websocket')
plugin.backend.connect_ws()
except Exception as e:
plugin.logger.error(str(e))


plugin.backend.init_wss(
on_message=lambda message, reply, reject, transport:
handle_message(plugin, message, reply, reject, transport),
on_close=lambda: plugin.worker.submit_coroutines(on_close()),
on_open=lambda: plugin.worker.submit_coroutines(on_connected(plugin)))

await validate_api_key()
connect_ws()

try:

plugin.logger.debug('Connecting to websocket')
plugin.backend.connect_wss(
on_message=lambda message, reply, reject, transport:
handle_message(plugin, message, reply, reject, transport),
on_close=plugin.frontend.emitBackendDisconnected,
on_error=plugin.frontend.emitBackendDisconnected,
on_open=lambda: plugin.worker.submit_coroutines(on_connected(plugin)))
except Exception as e:
plugin.logger.error(str(e))
59 changes: 35 additions & 24 deletions octoprint_zupfe/transport/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,20 +37,21 @@ def send_binary(self, message):


class WebSocketClient:
def __init__(self, backend_ws_url, octo_id, api_key, on_message,
def __init__(self, backend_ws_url, on_message,
on_open=None, on_close=None, on_error=None):
headers = {
'x-printer-uuid': octo_id,
'x-api-key': api_key
}

self._api_key = None
self._octo_id = None

# Create a custom SSL context that allows self-signed certificates
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
# websocket.enableTrace(True)

self._backend_ws_url = backend_ws_url
self._close_callbacks = []
self._thread = threading.Thread(target=self._run_forever)
self._thread = None

self._connected = False
self._connection_future = None
Expand All @@ -63,12 +64,7 @@ def __init__(self, backend_ws_url, octo_id, api_key, on_message,

self._uuid = str(uuid.uuid4())

self._ws = websocket.WebSocketApp(backend_ws_url,
header=headers,
on_open=self._on_open,
on_message=self._on_message,
on_error=self._on_error,
on_close=self._on_close)


@property
def uuid(self):
Expand Down Expand Up @@ -137,24 +133,39 @@ def _on_open(self, wssapp):
if self._on_open_callback is not None:
self._on_open_callback()

def _run_forever(self, retry_interval=1):
while not self._closed:
try:
self._ws.run_forever(skip_utf8_validation=True, sslopt={"cert_reqs": ssl.CERT_NONE})
if self._connected:
self._ws.close()
self._on_close(None, None, None)
def _run_ws(self):
try:
headers = {
'x-printer-uuid': self._octo_id,
'x-api-key': self._api_key
}

self._ws = websocket.WebSocketApp(self._backend_ws_url,
header=headers,
on_open=self._on_open,
on_message=self._on_message,
on_error=self._on_error,
on_close=self._on_close)

self._ws.run_forever(skip_utf8_validation=True, sslopt={"cert_reqs": ssl.CERT_NONE})

if self._connected:
self._ws.close()
self._on_close(None, None, None)

self._connected = False

self._connected = False
time.sleep(retry_interval)
except websocket.WebSocketException as e:
pass
except websocket.WebSocketException as e:
pass

def close(self):
self._closed = True

def connect(self):
def connect(self, octo_id, api_key):
self._api_key = api_key
self._octo_id = octo_id
self._closed = False
self._thread = threading.Thread(target=self._run_ws)
self._thread.start()

def on_close(self, callback):
Expand Down

0 comments on commit 0219ab6

Please sign in to comment.