clients attempt reconnection after socket close
[ppt-control.git] / ppt_control / ppt_control_obs.py
index aa2e44b7bb72e42a8f7634127404b0dae7102d0f..640d586856b513f2b6c2cce40c900abbce2a927d 100755 (executable)
@@ -4,6 +4,7 @@ import obspython as obs
 import asyncio\r
 import websockets\r
 import threading\r
+import logging, logging.handlers\r
 from time import sleep\r
 \r
 PORT_DEFAULT = 5678\r
@@ -30,12 +31,18 @@ HOTKEY_DESC_LAST = 'Last PowerPoint slide'
 HOTKEY_DESC_BLACK = 'Black PowerPoint slide'\r
 HOTKEY_DESC_WHITE = 'White PowerPoint slide'\r
 \r
+LOG_LEVEL = logging.DEBUG\r
+\r
 global cmd\r
 global attempts\r
+global logger\r
 cmd = ""\r
 hostname = HOSTNAME_DEFAULT\r
 port = PORT_DEFAULT\r
 attempts = 0\r
+logger = None\r
+\r
+logging.basicConfig()\r
 \r
 async def communicate():\r
     async with websockets.connect("ws://%s:%s" % (hostname, port), ping_interval=None) as websocket:\r
@@ -48,24 +55,27 @@ async def communicate():
                     cmd = ""\r
                     await websocket.send('{"action": "%s"}' % cmd_temp)\r
                 except websockets.ConnectionClosed as exc:\r
+                    logger.info("Failed to send command {}: {}".format(cmd_temp, str(exc)))\r
+                    cmd = cmd_temp\r
                     attempts += 1\r
                     if attempts == 4:\r
-                        print("Failed to send command after {} attempts - aborting connection".format(attempts))\r
+                        logger.info("Failed to send command {} after {} attempts - aborting connection".format(cmd_temp, attempts))\r
                         attempts = 0\r
                         cmd = ""\r
-                        raise websockets.exceptions.ConnectionClosedError(1006, "Sending command failed after {} attempts".format(attempts))\r
+                        break\r
             await asyncio.sleep(0.05 + 0.5*attempts**2)\r
 \r
 def run_ws():\r
     while True:\r
+        logger.debug("Attempting to connect")\r
         try:\r
             asyncio.set_event_loop(asyncio.new_event_loop())\r
             asyncio.get_event_loop().run_until_complete(communicate())\r
-        except (OSError, websockets.exceptions.ConnectionClosedError):\r
+        except (OSError, websockets.exceptions.ConnectionClosedError) as e:\r
             # No server available - just keep trying\r
             pass\r
         except Exception as e:\r
-            print("Failed to connect to websocket: {} - {}".format(type(e), e))\r
+            logger.warning("Failed to connect to websocket: {} - {}".format(type(e), e))\r
         finally:\r
             sleep(1)\r
 \r
@@ -79,6 +89,7 @@ def script_load(settings):
     global hotkey_id_last\r
     global hotkey_id_black\r
     global hotkey_id_white\r
+    global logger\r
 \r
     hotkey_id_first = register_and_load_hotkey(settings, HOTKEY_NAME_FIRST, HOTKEY_DESC_FIRST, first_slide)\r
     hotkey_id_prev = register_and_load_hotkey(settings, HOTKEY_NAME_PREV, HOTKEY_DESC_PREV, prev_slide)\r
@@ -87,10 +98,20 @@ def script_load(settings):
     hotkey_id_black = register_and_load_hotkey(settings, HOTKEY_NAME_BLACK, HOTKEY_DESC_BLACK, black)\r
     hotkey_id_white = register_and_load_hotkey(settings, HOTKEY_NAME_WHITE, HOTKEY_DESC_WHITE, white)\r
 \r
+    # Set up logging\r
+    log_formatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-7.7s]  %(message)s")\r
+    logger = logging.getLogger("ppt_control_obs")\r
+    logger.setLevel(LOG_LEVEL)\r
+    logger.propagate = False\r
+    console_handler = logging.StreamHandler()\r
+    console_handler.setFormatter(log_formatter)\r
+    console_handler.setLevel(LOG_LEVEL)\r
+    logger.addHandler(console_handler)\r
+\r
     ws_daemon = threading.Thread(name="ws_daemon", target=run_ws)\r
     ws_daemon.setDaemon(True)\r
     ws_daemon.start()\r
-    print("Started websocket client")\r
+    logger.info("Started websocket client")\r
 \r
 def script_unload():\r
     obs.obs_hotkey_unregister(first_slide)\r