mmcli/mmws.py

53 lines
1 KiB
Python

import sys
import json
import threading
import websocket
websocket.enableTrace(True)
class MMws:
"""
Websocket client.
"""
def __init__(self, ws_handler, api, ws_url):
self.api = api
self.ws_url = ws_url
self.ws_handler = ws_handler
self.ws_app = None
self.thread = threading.Thread(target=self._open_websocket)
self.thread.setName("websocket")
self.thread.setDaemon(False)
self.thread.start()
def _open_websocket(self):
def on_open(ws):
print("Opened")
ws.send(json.dumps({
"seq": 1, "action": "authentication_challenge", "data": {"token": self.api._bearer}
}))
def on_message(ws, msg):
print(msg)
self.ws_handler(self, msg)
def on_error(ws, error):
print(error, file=sys.stderr)
sys.exit(1)
self.ws_app = websocket.WebSocketApp(self.ws_url, on_open=on_open, on_message=on_message,
on_close=lambda ws: print("Closed"))
print("Start", flush=True)
self.ws_app.run_forever()
print("Done", flush=True)
def close_websocket(self):
self.ws_app.close()
self.thread.join()