diff --git a/src/server/main.py b/src/server/main.py index 2203af1..8c4d836 100644 --- a/src/server/main.py +++ b/src/server/main.py @@ -6,14 +6,22 @@ Changes come in via WebAPI so we can make a lightweight desktop client and leave Also allows the TidByt to still have forgeserv.net data without needing to be stood up """ -from fastapi import FastAPI +import logging + +from fastapi import FastAPI, Response + from server.state import AppState, StateManager -app = FastAPI() -state_mgr = StateManager(timeout=10) +app: FastAPI = FastAPI() +logger = logging.getLogger("uvicorn.error") +state_mgr: StateManager = StateManager(timeout=10) +state_mgr.start() @app.post("/") def change_state(new_state: int): - state_mgr.update(AppState(new_state)) - return {"msg": "👍"} + try: + state_mgr.update(AppState(new_state)) + except Exception as e: + logger.warning(f"/change_state ran into an {type(e).__name__}: {str(e)}") + return Response(status_code=200) diff --git a/src/server/pixlet.py b/src/server/pixlet.py index 269ec58..b3b101b 100644 --- a/src/server/pixlet.py +++ b/src/server/pixlet.py @@ -1,26 +1,33 @@ """A Python Wrapper for Pixlet ops""" -import subprocess +import logging from os import getenv from pathlib import Path from platform import machine +from subprocess import PIPE, Popen +from time import sleep +from typing import Tuple from server.renderables import Renderable class PixletHelper: def __init__(self): + self.logger = logging.getLogger("uvicorn.error") self.root_path: Path = Path("./").resolve() self.pixlet: Path = self.root_path.joinpath(f"pixlet.{machine()}").resolve() self.device_id: str = getenv("TIDBYT_DEVICE_ID", "") - def push_to_tidbyt(self, renderable: Renderable) -> None: + def push_to_tidbyt(self, renderable: Renderable) -> bool: """Pushes a renderable to the Tidbyt device Args: renderable (Renderable): The Pixlet Configuration for the given state + + Returns: + bool: True if the process succeeded, False otherwise """ - self.__display(self.__render(renderable)) + return self.__display(self.__render(renderable)) def __render(self, renderable: Renderable) -> Path: """Renders a given PixeltConfiguration (and any template args) to webp @@ -33,19 +40,27 @@ class PixletHelper: """ output_path = self.__prepare_file(renderable) - with subprocess.Popen([self.pixlet, "render", str(output_path)]) as proc: - proc.wait() + with Popen( + [self.pixlet, "render", str(output_path)], stdout=PIPE, stderr=PIPE + ) as proc: + exit_code = proc.wait() + stdout, stderr = self.__get_decoded_out(proc) + if exit_code != 0 and (stdout or stderr): + self.logger.warning(f"__render call failed: {stdout or stderr}") return self.root_path.joinpath("tmp.webp").resolve() - def __display(self, path: Path, attempt=0) -> None: + def __display(self, path: Path, attempt=0) -> bool: """Pushes a given rendered webp file to the pixlet on the same installation id Args: path (Path): The path to the given rendered webp attempt (int, optional): Used to track recursive calls in case pushing fails. Defaults to 0. + + Returns: + bool: True if pushing the rendered path to the Tidbyt succeeded, False otherwise """ - with subprocess.Popen( + with Popen( [ self.pixlet, "push", @@ -53,11 +68,23 @@ class PixletHelper: "automation", self.device_id, str(path), - ] + ], + stdout=PIPE, + stderr=PIPE, ) as proc: exit_code = proc.wait() - if exit_code != 0 and attempt < 5: - self.__display(path, attempt=attempt + 1) + if exit_code == 0: + return True + if attempt < 5: + sleep(3 * (attempt + 1)) + return self.__display(path, attempt=attempt + 1) + else: + stdout, stderr = self.__get_decoded_out(proc) + if exit_code != 0 and (stdout or stderr): + self.logger.warning( + f"__display call failed after 5 attempts: {stdout or stderr}" + ) + return False def __prepare_file(self, renderable: Renderable) -> Path: """Prepares a given pixlet star file. If the file is a template, checks the template keys and prepares the template before writing to the temp path @@ -89,3 +116,14 @@ class PixletHelper: handle.write(data) return output_path + + def __get_decoded_out(self, proc: Popen[bytes]) -> Tuple[str, str]: + """Gets the decoded stdout and stderr from a Popen call + + Returns: + Tuple[str, str]: (stdout, stderr) respectively, decoded as strings. + """ + stdout, stderr = proc.communicate() + stdout = stdout.decode().replace("\n", " ") + stderr = stderr.decode().replace("\n", " ") + return (stdout, stderr) diff --git a/src/server/state.py b/src/server/state.py index 2f1755e..9a49e80 100644 --- a/src/server/state.py +++ b/src/server/state.py @@ -1,14 +1,14 @@ +import logging from pathlib import Path from threading import Thread from time import sleep from typing import Dict +from common.appstate import AppState from server.pixlet import PixletHelper from server.renderables import Renderable from server.renderables.forgeserv import ForgeServ -from common.appstate import AppState - class StateManager: def __init__(self, timeout=1): @@ -17,6 +17,7 @@ class StateManager: Args: timeout (int, optional): How long to wait between iterations (in seconds). Defaults to 1. """ + self.logger = logging.getLogger("uvicorn.error") self.state: AppState = AppState.IDLE self.renderables: Dict[AppState, Renderable] = { AppState.IDLE: ForgeServ(), @@ -36,7 +37,6 @@ class StateManager: self.thread: Thread = None self.stop_thread = False self.__pixlet_helper = PixletHelper() - self.__start() def update(self, new_state: AppState): """Update the Tidbyt's state, returning the prior state @@ -50,7 +50,7 @@ class StateManager: self.state = new_state self.__pixlet_helper.push_to_tidbyt(self.renderables[self.state]) - def __start(self): + def start(self): """Instantiates and starts the worker thread Raises: @@ -60,10 +60,23 @@ class StateManager: raise Exception("Thread has already been initialized!") self.thread = Thread(target=self.__thread_task, daemon=True) self.thread.start() + self.logger.info(f"Started thread with tid={self.thread.ident}") def __thread_task(self): """A looping task that renders and pushes the correct pixlet based on state""" while not self.stop_thread: - if self.renderables[self.state].is_dynamic: - self.__pixlet_helper.push_to_tidbyt(self.renderables[self.state]) - sleep(self.timeout) + try: + if self.renderables[self.state].is_dynamic: + if not self.__pixlet_helper.push_to_tidbyt( + self.renderables[self.state] + ): + self.logger.warning( + f"Failed to push {self.state.name} to TidByt - pausing for {10 * self.timeout} seconds" + ) + sleep(10 * self.timeout) + sleep(self.timeout) + except Exception as e: + self.logger.warning( + f"Thread task ran into an {type(e).__name__}: {str(e)}" + ) + sleep(self.timeout * 2)