diff --git a/tools/rokuHandler.py b/tools/rokuHandler.py index 5f4328c..306a2da 100644 --- a/tools/rokuHandler.py +++ b/tools/rokuHandler.py @@ -48,6 +48,13 @@ COMMANDS = { } class RokuWrapper(): + def _send_msg(self, code: int, msg: object): + try: + content = json.dumps(msg).encode() + self.parent._send(code, content) + except Exception as e: + print(e) + def __init__(self, parent): self.parent = parent @@ -59,22 +66,22 @@ class RokuWrapper(): print(f"Roku client connected to {ROKU_IP}", flush=True) except Exception as e: self.parent.log_error("Failed to create Roku client: %s", e) - return self.parent._send(500, json.dumps({"error": "roku connection failed"}).encode()) + return self._send_msg(500, {"error": "roku connection failed"}) def run_command(self, command: str): if not command: - return self.parent._send(404, json.dumps({"error": "command not given"}).encode()) + return self._send_msg(404, {"error": "command not given"}) command = command.split('/')[0] # If command is not known, nothing to do if command not in COMMANDS: - return self.parent._send(404, json.dumps({"error": "unknown command"}).encode()) + return self._send_msg(404, {"error": f"unknown command. Available commands: {", ".join(COMMANDS.keys())}"}) if hasattr(self.rapp, command): attr = getattr(self.rapp, command) if callable(attr): attr() - return {"result": f"{command} executed"} + return self._send_msg(200, {"result": f"{command} executed"}) # Fallback: send the Roku key name using common API methods key_name = COMMANDS[command] @@ -84,8 +91,8 @@ class RokuWrapper(): fn = getattr(self.rapp, send_fn) try: fn(key_name) - return {"result": f"{command} sent as {key_name} via {send_fn}"} + return self._send_msg(200, {"result": f"{command} sent as {key_name} via {send_fn}"}) except TypeError: continue - self.parent._send(404, json.dumps({"error": "unknown endpoint"}).encode()) + self._send_msg(404, {"error": "unknown endpoint"})