From 93db43ea545e57ab1aca87738dd3bb491c60d119 Mon Sep 17 00:00:00 2001 From: Patrick762 Date: Wed, 24 May 2023 15:51:08 +0200 Subject: [PATCH] added 10s status broadcast interval --- README.md | 2 +- streamdeckapi/server.py | 44 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f7ebc0a..3e7ba35 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ # streamdeckapi Stream Deck API Library for Home Assistant Stream Deck Integration -Only compatible with separate [Stream Deck Plugin](https://github.com/Patrick762/streamdeckapi-plugin) +Only compatible with separate [Stream Deck Plugin](https://github.com/Patrick762/streamdeckapi-plugin) or the bundled server. ## Requirements - Python 3.10 or higher diff --git a/streamdeckapi/server.py b/streamdeckapi/server.py index 4d1a51e..2f4e992 100644 --- a/streamdeckapi/server.py +++ b/streamdeckapi/server.py @@ -319,6 +319,30 @@ async def websocket_broadcast(message: str): await connection.send_str(message) +async def broadcast_status(): + """Broadcast the current status of the streamdeck.""" + + # Collect data + data = { + "event": "status", + "args": { + "devices": devices, + "application": application, + "buttons": get_buttons() + } + } + + data_str = encode(data, unpicklable=False) + data_str = ( + data_str.replace('"x_pos"', '"x"') + .replace('"y_pos"', '"y"') + .replace('"platform_version"', '"platformVersion"') + ) + + # Broadcast + await websocket_broadcast(data_str) + + # # Functions # @@ -346,6 +370,8 @@ async def start_server_async(host: str = "0.0.0.0", port: int = PLUGIN_PORT): await site.start() print("Started Stream Deck API server on port", PLUGIN_PORT) + Timer(10, broadcast_status) + def get_position(deck: StreamDeck, key: int) -> SDButtonPosition: """Get the position of a key.""" @@ -479,6 +505,24 @@ def start_ssdp_server(): server.serve_forever() +class Timer: + """Timer class.""" + def __init__(self, interval, callback): + """Init timer.""" + self._interval = interval + self._callback = callback + self._task = asyncio.ensure_future(self._job()) + + async def _job(self): + await asyncio.sleep(self._interval) + await self._callback() + self._task = asyncio.ensure_future(self._job()) + + def cancel(self): + """Cancel timer.""" + self._task.cancel() + + def start(): """Entrypoint.""" init_all()