Skip to content

Commit

Permalink
fix websocket reconnect
Browse files Browse the repository at this point in the history
  • Loading branch information
nlef committed Nov 4, 2024
1 parent 50a36c5 commit 0e6f945
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 28 deletions.
7 changes: 7 additions & 0 deletions bot/klippy.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,13 @@ async def set_connected(self, new_value: bool) -> None:
def macros(self) -> List[str]:
return self._get_marco_list()

async def get_macros_force(self):
try:
await self._update_printer_objects()
except Exception as e:
logger.error(e)
return self._get_marco_list()

@property
def macros_all(self) -> List[str]:
return self._get_full_marco_list()
Expand Down
2 changes: 1 addition & 1 deletion bot/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,7 +1090,7 @@ async def greeting_message(bot: telegram.Bot) -> None:
disable_notification=notifier.silent_status,
)

await bot.set_my_commands(commands=prepare_commands_list(klippy.macros, configWrap.telegram_ui.include_macros_in_command_list))
await bot.set_my_commands(commands=prepare_commands_list(await klippy.get_macros_force(), configWrap.telegram_ui.include_macros_in_command_list))
await klippy.add_bot_announcements_feed()
await check_unfinished_lapses(bot)

Expand Down
53 changes: 27 additions & 26 deletions bot/websocket_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
import random
import ssl
import time
from typing import Dict

from apscheduler.schedulers.base import BaseScheduler # type: ignore
import orjson
import websockets
from websockets.asyncio.client import ClientConnection, connect
from websockets.protocol import State

Expand Down Expand Up @@ -43,7 +43,11 @@ def __init__(
self._host: str = config.bot_config.host
self._port = config.bot_config.port
self._protocol: str = "wss" if config.bot_config.ssl else "ws"
self._ssl_opt: Dict = {} if config.bot_config.ssl_validate else {"cert_reqs": ssl.CERT_NONE, "check_hostname": False}
self._ssl_context = ssl.create_default_context() if config.bot_config.ssl else None
if config.bot_config.ssl_validate is False and self._ssl_context is not None:
self._ssl_context.verify_mode = ssl.CERT_NONE
self._ssl_context.check_hostname = False

self._klippy: Klippy = klippy
self._notifier: Notifier = notifier
self._timelapse: Timelapse = timelapse
Expand All @@ -57,25 +61,9 @@ def __init__(
if logging_handler:
logger.addHandler(logging_handler)

# # Todo: add port + protocol + ssl_validate
# self.websocket = websocket.WebSocketApp(
# f"{self._protocol}://{self._host}:{self._port}/websocket{self._klippy.one_shot_token}",
# on_message=self.websocket_to_message,
# on_open=self.on_open,
# on_error=self.on_error,
# on_close=self.on_close,
# )

# @staticmethod
# def on_close(_, close_status_code, close_msg):
# logger.info("WebSocket closed")
# if close_status_code or close_msg:
# logger.error("WebSocket close status code: %s", str(close_status_code))
# logger.error("WebSocket close message: %s", str(close_msg))
#
# @staticmethod
# def on_error(_, error):
# logger.error(error)
@staticmethod
def on_error(error):
logger.error(error)

@property
def _my_id(self) -> int:
Expand Down Expand Up @@ -441,8 +429,21 @@ def parselog(self):
print("lalal")

async def run_forever_async(self):
# Todo: ssl context?!
self._ws = await connect(f"{self._protocol}://{self._host}:{self._port}/websocket{ await self._klippy.get_one_shot_token()}")
self._scheduler.add_job(self.reshedule, "interval", seconds=2, id="ws_reschedule", replace_existing=True)
async for message in self._ws:
await self.websocket_to_message(message)
# Todo: use headers instead of inline token
async for websocket in connect(
uri=f"{self._protocol}://{self._host}:{self._port}/websocket{await self._klippy.get_one_shot_token()}",
process_exception=self.on_error,
open_timeout=5.0,
close_timeout=5.0,
max_queue=1024,
logger=logger,
ssl=self._ssl_context,
):
try:
self._ws = websocket
self._scheduler.add_job(self.reshedule, "interval", seconds=2, id="ws_reschedule", replace_existing=True)
async for message in self._ws:
await self.websocket_to_message(message)
except websockets.ConnectionClosed:
self._scheduler.remove_job("ws_reschedule")
continue
4 changes: 3 additions & 1 deletion scripts/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
anyio==4.6.2.post1
emoji==2.14.0
ffmpegcv==0.3.15
idna==3.10
orjson==3.10.7
orjson==3.10.11
Pillow==11.0.0 ; python_version>='3.10'
Pillow==10.4.0 ; python_version<='3.9'
psutil==6.1.0
python-telegram-bot[socks,http2,rate-limiter,callback-data,job-queue]==21.6
tzlocal==2.1
uvloop==0.20.0 ; platform_system != "Windows"
Expand Down

0 comments on commit 0e6f945

Please sign in to comment.