diff --git a/build/requirements.txt b/build/requirements.txt index 6f7f474..2c2704c 100644 --- a/build/requirements.txt +++ b/build/requirements.txt @@ -4,4 +4,5 @@ mutagen sounddevice autopep8 setproctitle -pyttsx3 \ No newline at end of file +pyttsx3 +websockets \ No newline at end of file diff --git a/server.py b/server.py index b108652..0cb4187 100644 --- a/server.py +++ b/server.py @@ -30,6 +30,7 @@ import config from typing import Dict, List from helpers.state_manager import StateManager from helpers.logging_manager import LoggingManager +from websocket_server import WebsocketServer setproctitle.setproctitle("BAPSicle - Server") @@ -38,6 +39,7 @@ default_state = { "server_name": "URY BAPSicle", "host": "localhost", "port": 13500, + "ws_port": 13501, "num_channels": 3 } @@ -360,6 +362,9 @@ def startServer(): ) channel_p[channel].start() + websockets_server = multiprocessing.Process(target=WebsocketServer, args=[channel_to_q, state]) + websockets_server.start() + if not isMacOS(): # Temporary RIP. diff --git a/websocket_server.py b/websocket_server.py new file mode 100644 index 0000000..d744f21 --- /dev/null +++ b/websocket_server.py @@ -0,0 +1,57 @@ +import asyncio +import websockets +import json + +baps_clients = set() +channel_to_q = None + + +async def websocket_handler(websocket, path): + baps_clients.add(websocket) + await websocket.send(json.dumps({"message": "Hello"})) + print("New Client: {}".format(websocket)) + + try: + async for message in websocket: + data = json.loads(message) + channel = int(data["channel"]) + if "command" in data.keys(): + if data["command"] == "PLAY": + channel_to_q[channel].put("PLAY") + elif data["command"] == "PAUSE": + channel_to_q[channel].put("PAUSE") + elif data["command"] == "UNPAUSE": + channel_to_q[channel].put("UNPAUSE") + elif data["command"] == "STOP": + channel_to_q[channel].put("STOP") + elif data["command"] == "SEEK": + channel_to_q[channel].put("SEEK:" + str(data["time"])) + elif data["command"] == "LOAD": + pass + + asyncio.wait([await conn.send(message) for conn in baps_clients]) + + except websockets.exceptions.ConnectionClosedError: + print("RIP {}".format(websocket)) + + except Exception as e: + print(e) + + finally: + baps_clients.remove(websocket) + + +class WebsocketServer: + + def __init__(self, in_q, state): + global channel_to_q + channel_to_q = in_q + + websocket_server = websockets.serve(websocket_handler, state.state["host"], state.state["ws_port"]) + + asyncio.get_event_loop().run_until_complete(websocket_server) + asyncio.get_event_loop().run_forever() + + +if __name__ == "__main__": + print("Don't do this")