simple-ocpp-cs/app/util/websocket_wrapper.py

25 lines
882 B
Python
Raw Normal View History

2024-04-20 17:14:45 +02:00
import logging
2024-03-28 21:23:25 +01:00
from fastapi import WebSocket, WebSocketDisconnect
from websockets import ConnectionClosed
2024-04-20 17:14:45 +02:00
logger = logging.getLogger("gunicorn.access")
2024-03-28 21:23:25 +01:00
# Wrapper to transform a FastAPI websocket to a standard websocket
class WebSocketWrapper():
def __init__(self, websocket: WebSocket):
self._websocket = websocket
async def recv(self) -> str:
try:
2024-04-20 17:14:45 +02:00
text = await self._websocket.receive_text()
logger.info("Message received: {}", text)
2024-03-28 21:23:25 +01:00
return await self._websocket.receive_text()
except WebSocketDisconnect as e:
raise ConnectionClosed(e.code, 'WebSocketWrapper')
async def send(self, msg: str) -> None:
2024-04-20 17:14:45 +02:00
logger.info("Message sent: {}", msg)
2024-03-28 21:23:25 +01:00
await self._websocket.send_text(msg)
async def close(self, code: int, reason: str) -> None:
await self._websocket.close(code)