trying to just redirect ws
This commit is contained in:
1 parent
e6e51be5a5
commit
079f353dbf
8 files changed
+114
-60
No files matched your search
+2
-1
@@ -5,7 +5,7 @@ from fastapi.staticfiles import StaticFiles
|
||||
from src.automations.manager import AutomationManager
|
||||
from src.env import ORIGIN, ROOT_FOLDER
|
||||
|
||||
from .routes import automations, details, ping
|
||||
from .routes import automations, details, ping, socket
|
||||
|
||||
|
||||
def make_app(automation_mgr: AutomationManager) -> FastAPI:
|
||||
@@ -31,4 +31,5 @@ def make_app(automation_mgr: AutomationManager) -> FastAPI:
|
||||
app.include_router(ping.router, prefix="/ping")
|
||||
app.include_router(automations.make_automation_router(automation_mgr), prefix="/automations")
|
||||
app.include_router(details.make_details_router(automation_mgr.hass_config), prefix="/details")
|
||||
app.include_router(socket.router, prefix="/socket")
|
||||
return app
|
||||
@@ -1,6 +1,6 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from src.env import BUILD_VERSION, HASS_URL, HASSIO_TOKEN
|
||||
from src.env import BUILD_VERSION, HASSIO_WS, HASSIO_TOKEN
|
||||
from src.hass_config import HassConfig
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ def make_details_router(hass_config: HassConfig) -> APIRouter:
|
||||
return {
|
||||
"version": BUILD_VERSION,
|
||||
"hassio_token": HASSIO_TOKEN,
|
||||
"hass_url": HASS_URL,
|
||||
"hassio_url": HASSIO_WS,
|
||||
"config": hass_config.get_configuration_path(),
|
||||
"tags": hass_config.get_automation_tags_path(),
|
||||
"autos": hass_config.get_automation_path(),
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import asyncio
|
||||
import json
|
||||
from fastapi import APIRouter, WebSocket
|
||||
from src.ws_redirect import WSRedirector
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.websocket("/api/websocket")
|
||||
async def websocket_endpoint(websocket: WebSocket):
|
||||
async def on_message(ws: WSRedirector, msg: str):
|
||||
await websocket.send_text(msg)
|
||||
|
||||
conn = WSRedirector(
|
||||
on_message=on_message,
|
||||
)
|
||||
|
||||
async def wait_for_data():
|
||||
while True:
|
||||
await conn.send(await websocket.receive_text())
|
||||
|
||||
await websocket.accept()
|
||||
|
||||
await asyncio.gather(
|
||||
conn.start(),
|
||||
wait_for_data(),
|
||||
)
|
||||
+2
-2
@@ -4,7 +4,7 @@ from decouple import Csv, config
|
||||
|
||||
ROOT_FOLDER = Path(__file__).parent.parent.absolute()
|
||||
BUILD_VERSION = config("BUILD_VERSION", "0.0.0")
|
||||
HASSIO_TOKEN = config("HASSIO_TOKEN", "")
|
||||
HASS_URL = config("HASS_URL", "/")
|
||||
HASSIO_TOKEN = config("SUPERVISOR_TOKEN", "")
|
||||
HASSIO_WS = config("HASSIO_WS", "ws://supervisor/core/websocket")
|
||||
LOG_LEVEL = config("LOG_LEVEL", "INFO")
|
||||
ORIGIN = config("ORIGIN", cast=Csv(), default="*")
|
||||
@@ -0,0 +1,70 @@
|
||||
import json
|
||||
import websockets
|
||||
|
||||
from typing import Callable, Coroutine, Optional
|
||||
from http import HTTPStatus
|
||||
|
||||
from websockets.client import ClientConnection
|
||||
from fastapi.exceptions import HTTPException
|
||||
|
||||
from src.logger import logger
|
||||
from src.env import HASSIO_TOKEN, HASSIO_WS
|
||||
|
||||
OnMessage = Callable[[dict], Coroutine]
|
||||
|
||||
|
||||
class WSRedirectorError(HTTPException):
|
||||
def __init__(self, status_code: int) -> None:
|
||||
super().__init__(status_code, detail={"message": str(self.__class__.__name__)})
|
||||
|
||||
|
||||
class WSDisconnectedMessage(WSRedirectorError):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(status_code=HTTPStatus.FAILED_DEPENDENCY)
|
||||
|
||||
|
||||
class WSRedirector:
|
||||
def __init__(
|
||||
self,
|
||||
on_message: OnMessage,
|
||||
token: str = HASSIO_TOKEN,
|
||||
host: str = HASSIO_WS,
|
||||
) -> None:
|
||||
self._host = host
|
||||
self._token = token
|
||||
self._on_message = on_message
|
||||
self._authenticated = False
|
||||
self._client: Optional[ClientConnection] = None
|
||||
self._close: bool = False
|
||||
|
||||
@property
|
||||
def is_closed(self):
|
||||
return self._close
|
||||
|
||||
@property
|
||||
def is_authenticated(self):
|
||||
return self._authenticated
|
||||
|
||||
async def send(self, msg: str):
|
||||
if self._client:
|
||||
return await self._client.send(msg)
|
||||
# else:
|
||||
# raise WSDisconnectedMessage()
|
||||
|
||||
async def start(self):
|
||||
async with websockets.connect(self._host) as websocket:
|
||||
self._client = websocket
|
||||
await websocket.send(json.dumps({"type": "auth", "access_token": self._token}))
|
||||
while not self.is_closed:
|
||||
msg = await websocket.recv()
|
||||
logger.debug(f"WS:MSG: {msg}")
|
||||
await self.process_message(msg)
|
||||
|
||||
async def process_message(self, msg: str):
|
||||
await self._on_message(self, msg)
|
||||
|
||||
def close(self):
|
||||
self._close = True
|
||||
|
||||
def __del__(self):
|
||||
self.close()
|
||||
Reference in new issue
Block a user