Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """WebSocket based API for Home Assistant."""
2 
3 from __future__ import annotations
4 
5 from typing import Final, cast
6 
7 from homeassistant.core import HomeAssistant, callback
8 from homeassistant.helpers import config_validation as cv
9 from homeassistant.helpers.typing import ConfigType, VolSchemaType
10 from homeassistant.loader import bind_hass
11 
12 from . import commands, connection, const, decorators, http, messages # noqa: F401
13 from .connection import ActiveConnection, current_connection # noqa: F401
14 from .const import ( # noqa: F401
15  ERR_HOME_ASSISTANT_ERROR,
16  ERR_INVALID_FORMAT,
17  ERR_NOT_ALLOWED,
18  ERR_NOT_FOUND,
19  ERR_NOT_SUPPORTED,
20  ERR_SERVICE_VALIDATION_ERROR,
21  ERR_TEMPLATE_ERROR,
22  ERR_TIMEOUT,
23  ERR_UNAUTHORIZED,
24  ERR_UNKNOWN_COMMAND,
25  ERR_UNKNOWN_ERROR,
26  TYPE_RESULT,
27  AsyncWebSocketCommandHandler,
28  WebSocketCommandHandler,
29 )
30 from .decorators import ( # noqa: F401
31  async_response,
32  require_admin,
33  websocket_command,
34  ws_require_user,
35 )
36 from .messages import ( # noqa: F401
37  BASE_COMMAND_MESSAGE_SCHEMA,
38  error_message,
39  event_message,
40  result_message,
41 )
42 
43 DOMAIN: Final = const.DOMAIN
44 
45 DEPENDENCIES: Final[tuple[str]] = ("http",)
46 
47 CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)
48 
49 
50 @bind_hass
51 @callback
53  hass: HomeAssistant,
54  command_or_handler: str | const.WebSocketCommandHandler,
55  handler: const.WebSocketCommandHandler | None = None,
56  schema: VolSchemaType | None = None,
57 ) -> None:
58  """Register a websocket command."""
59  if handler is None:
60  handler = cast(const.WebSocketCommandHandler, command_or_handler)
61  command = handler._ws_command # type: ignore[attr-defined] # noqa: SLF001
62  schema = handler._ws_schema # type: ignore[attr-defined] # noqa: SLF001
63  else:
64  command = command_or_handler
65  if (handlers := hass.data.get(DOMAIN)) is None:
66  handlers = hass.data[DOMAIN] = {}
67  handlers[command] = (handler, schema)
68 
69 
70 async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
71  """Initialize the websocket API."""
72  hass.http.register_view(http.WebsocketAPIView())
73  commands.async_register_commands(hass, async_register_command)
74  return True
None async_register_command(HomeAssistant hass, str|const .WebSocketCommandHandler command_or_handler, const .WebSocketCommandHandler|None handler=None, VolSchemaType|None schema=None)
Definition: __init__.py:57
bool async_setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:70