WS game-state URI

This commit is contained in:
Eden Kirin
2023-03-25 16:14:05 +01:00
parent 245dc75211
commit 8bc8a37edd
3 changed files with 9 additions and 15 deletions

View File

@ -253,17 +253,10 @@ Response body:
### WS Data format ### WS Data format
- json - json
General data format:
```json
{
"command": "command",
"data": {}
}
```
### Game info structure ### Game state structure
Command: `gameInfo` URI: `/game-state`
Data: Data:
```json ```json

View File

@ -3,14 +3,15 @@ import logging
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
import websockets import websockets
from websockets.exceptions import ConnectionClosed
from hopper.models.ws_dto import GameStateDto from hopper.models.ws_dto import GameStateDto
from settings import settings from settings import settings
@asynccontextmanager @asynccontextmanager
async def create_ws_client() -> websockets.WebSocketServerProtocol: async def create_ws_client(path: str) -> websockets.WebSocketServerProtocol:
ws_uri = f"ws://{settings.ws_server.HOST}:{settings.ws_server.PORT}" ws_uri = f"ws://{settings.ws_server.HOST}:{settings.ws_server.PORT}{path}"
async with websockets.connect(uri=ws_uri) as websocket: async with websockets.connect(uri=ws_uri) as websocket:
yield websocket yield websocket
@ -20,7 +21,7 @@ async def ws_send_game_state() -> None:
from hopper.api.dependencies import get_game_engine from hopper.api.dependencies import get_game_engine
try: try:
async with create_ws_client() as websocket: async with create_ws_client("/game-state") as websocket:
engine = get_game_engine() engine = get_game_engine()
game_state = GameStateDto( game_state = GameStateDto(
@ -30,5 +31,5 @@ async def ws_send_game_state() -> None:
layers=engine.get_board_layout().layers, layers=engine.get_board_layout().layers,
) )
await websocket.send(json.dumps(game_state.dict())) await websocket.send(json.dumps(game_state.dict()))
except OSError as ex: except (OSError, ConnectionClosed) as ex:
logging.error(f"Error sending WS state: {ex}") logging.error(f"Error sending WS state: {ex}")

View File

@ -22,7 +22,7 @@ async def ws_handler(websocket: WebSocketServerProtocol):
try: try:
async for message in websocket: async for message in websocket:
logging.debug(f"Received message: {message}") logging.debug(f"Received message on {websocket.path}: {message}")
broadcast_clients = [client for client in connected_clients if client.id != websocket.id] broadcast_clients = [client for client in connected_clients if client.id != websocket.id]
if broadcast_clients: if broadcast_clients:
logging.debug(f"Broadcast message to clients: {broadcast_clients}") logging.debug(f"Broadcast message to clients: {broadcast_clients}")