import asyncio\r
import websockets\r
import threading\r
+import logging, logging.handlers\r
from time import sleep\r
\r
PORT_DEFAULT = 5678\r
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
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
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
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
var preloaded = false;
var preload = [];
-function imageRefresh(id) {
- img = document.getElementById(id);
- var d = new Date;
- var http = img.src;
- if (http.indexOf("?t=") != -1) { http = http.split("?t=")[0]; }
- img.src = http + '?t=' + d.getTime();
-}
-
-function startWebsocket() {
- ws = new WebSocket("ws://" + window.location.host + ":5678/");
- ws.onclose = function(){
- //websocket = null;
- setTimeout(function(){startWebsocket()}, 10000);
- }
- return ws;
-}
-
-var websocket = startWebsocket();
-
var prev = document.querySelector('#prev'),
next = document.querySelector('#next'),
first = document.querySelector('#first'),
slide_label = document.querySelector('#slide_label'),
current = document.querySelector('#current'),
total = document.querySelector('#total'),
- users = document.querySelector('.users'),
+ status_text = document.querySelector('.status_text'),
current_img = document.querySelector('#current_img'),
next_img = document.querySelector('#next_img'),
current_div = document.querySelector('#current_div'),
show_next = document.querySelector('#show_next'),
shortcuts = document.querySelector('#shortcuts');
+
+function startWebsocket() {
+ console.log("Attempting to connect")
+ ws = new WebSocket("ws://" + window.location.host + ":5678/");
+ ws.onmessage = receive_message;
+ ws.onclose = function(){
+ ws = null;
+ setTimeout(function(){websocket = startWebsocket()}, 1000);
+ }
+ if (ws.readyState !== WebSocket.OPEN) {
+ disconnect()
+ }
+ return ws;
+}
+
+var websocket = startWebsocket();
+
prev.onclick = function (event) {
websocket.send(JSON.stringify({action: 'prev'}));
}
}
});
-function sleep(ms) {
- return new Promise(resolve => setTimeout(resolve, ms));
-}
-
function disconnect() {
- document.title = DEFAULT_TITLE;
+ console.log("Disconnecting")
+ document.title = DEFAULT_TITLE;
current_img.src = "/black.jpg";
next_img.src = "/black.jpg";
- users.textContent = "Connection to PowerPoint failed";
-}
-
-function update_current() {
+ status_text.textContent = "Disconnected";
+ total.textContent = "?";
+ current.value = "";
}
-function update_next() {
-}
-
-websocket.onmessage = function (event) {
+function receive_message(event) {
data = JSON.parse(event.data);
switch (data.type) {
case 'state':
if (data.connected == "0" || data.connected == 0) {
- console.log("Disconnected");
disconnect();
break;
+ } else {
+ status_text.textContent = "Connected";
}
var d = new Date;
if (show_current.checked) {
for (let i=1; i<=Number(total.textContent); i++) {
image.src = "/cache/" + i + ".jpg";
preload.push(image);
- console.log("Preloaded " + total.textContent);
- //sleep(0.5)
}
preloaded = true;
}