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

25 lines
849 B
Python
Raw Permalink 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:27:25 +02:00
logger = logging.getLogger("gunicorn.error")
2024-04-20 17:14:45 +02:00
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()
2024-04-20 17:36:35 +02:00
logger.info("Message received: %s", text)
2024-04-20 17:28:43 +02:00
return text
2024-03-28 21:23:25 +01:00
except WebSocketDisconnect as e:
raise ConnectionClosed(e.code, 'WebSocketWrapper')
async def send(self, msg: str) -> None:
2024-04-20 17:36:35 +02:00
logger.info("Message sent: %s", 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)