This commit is contained in:
Paulus Schoutsen committed 2019-07-31 12:25:30 -07:00
1 parent da05dfe708
commit 4de97abc3a
2676 files changed
+163166 -140084

No files matched your search

+37 -27
View File
@@ -11,9 +11,15 @@ from homeassistant.core import callback
from homeassistant.components.http import HomeAssistantView
from .const import (
MAX_PENDING_MSG, CANCELLATION_ERRORS, URL, ERR_UNKNOWN_ERROR,
SIGNAL_WEBSOCKET_CONNECTED, SIGNAL_WEBSOCKET_DISCONNECTED,
DATA_CONNECTIONS, JSON_DUMP)
MAX_PENDING_MSG,
CANCELLATION_ERRORS,
URL,
ERR_UNKNOWN_ERROR,
SIGNAL_WEBSOCKET_CONNECTED,
SIGNAL_WEBSOCKET_DISCONNECTED,
DATA_CONNECTIONS,
JSON_DUMP,
)
from .auth import AuthPhase, auth_required_message
from .error import Disconnect
from .messages import error_message
@@ -28,8 +34,7 @@ class WebsocketAPIView(HomeAssistantView):
async def get(self, request):
"""Handle an incoming websocket connection."""
return await WebSocketHandler(
request.app['hass'], request).async_handle()
return await WebSocketHandler(request.app["hass"], request).async_handle()
class WebSocketHandler:
@@ -43,14 +48,12 @@ class WebSocketHandler:
self._to_write = asyncio.Queue(maxsize=MAX_PENDING_MSG)
self._handle_task = None
self._writer_task = None
self._logger = logging.getLogger(
"{}.connection.{}".format(__name__, id(self)))
self._logger = logging.getLogger("{}.connection.{}".format(__name__, id(self)))
async def _writer(self):
"""Write outgoing messages."""
# Exceptions if Socket disconnected or cancelled by connection handler
with suppress(RuntimeError, ConnectionResetError,
*CANCELLATION_ERRORS):
with suppress(RuntimeError, ConnectionResetError, *CANCELLATION_ERRORS):
while not self.wsock.closed:
message = await self._to_write.get()
if message is None:
@@ -62,11 +65,14 @@ class WebSocketHandler:
else:
await self.wsock.send_json(message, dumps=JSON_DUMP)
except (ValueError, TypeError) as err:
self._logger.error('Unable to serialize to JSON: %s\n%s',
err, message)
await self.wsock.send_json(error_message(
message['id'], ERR_UNKNOWN_ERROR,
'Invalid JSON in response'))
self._logger.error(
"Unable to serialize to JSON: %s\n%s", err, message
)
await self.wsock.send_json(
error_message(
message["id"], ERR_UNKNOWN_ERROR, "Invalid JSON in response"
)
)
@callback
def _send_message(self, message):
@@ -79,8 +85,9 @@ class WebSocketHandler:
try:
self._to_write.put_nowait(message)
except asyncio.QueueFull:
self._logger.error("Client exceeded max pending messages [2]: %s",
MAX_PENDING_MSG)
self._logger.error(
"Client exceeded max pending messages [2]: %s", MAX_PENDING_MSG
)
self._cancel()
@callback
@@ -97,7 +104,7 @@ class WebSocketHandler:
self._logger.debug("Connected")
# Py3.7+
if hasattr(asyncio, 'current_task'):
if hasattr(asyncio, "current_task"):
# pylint: disable=no-member
self._handle_task = asyncio.current_task()
else:
@@ -109,7 +116,8 @@ class WebSocketHandler:
self._cancel()
unsub_stop = self.hass.bus.async_listen(
EVENT_HOMEASSISTANT_STOP, handle_hass_stop)
EVENT_HOMEASSISTANT_STOP, handle_hass_stop
)
self._writer_task = self.hass.async_create_task(self._writer())
@@ -125,29 +133,30 @@ class WebSocketHandler:
with async_timeout.timeout(10):
msg = await wsock.receive()
except asyncio.TimeoutError:
disconnect_warn = \
'Did not receive auth message within 10 seconds'
disconnect_warn = "Did not receive auth message within 10 seconds"
raise Disconnect
if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING):
raise Disconnect
if msg.type != WSMsgType.TEXT:
disconnect_warn = 'Received non-Text message.'
disconnect_warn = "Received non-Text message."
raise Disconnect
try:
msg = msg.json()
except ValueError:
disconnect_warn = 'Received invalid JSON.'
disconnect_warn = "Received invalid JSON."
raise Disconnect
self._logger.debug("Received %s", msg)
connection = await auth.async_handle(msg)
self.hass.data[DATA_CONNECTIONS] = \
self.hass.data[DATA_CONNECTIONS] = (
self.hass.data.get(DATA_CONNECTIONS, 0) + 1
)
self.hass.helpers.dispatcher.async_dispatcher_send(
SIGNAL_WEBSOCKET_CONNECTED)
SIGNAL_WEBSOCKET_CONNECTED
)
# Command phase
while not wsock.closed:
@@ -157,13 +166,13 @@ class WebSocketHandler:
break
elif msg.type != WSMsgType.TEXT:
disconnect_warn = 'Received non-Text message.'
disconnect_warn = "Received non-Text message."
break
try:
msg = msg.json()
except ValueError:
disconnect_warn = 'Received invalid JSON.'
disconnect_warn = "Received invalid JSON."
break
self._logger.debug("Received %s", msg)
@@ -201,6 +210,7 @@ class WebSocketHandler:
if connection is not None:
self.hass.data[DATA_CONNECTIONS] -= 1
self.hass.helpers.dispatcher.async_dispatcher_send(
SIGNAL_WEBSOCKET_DISCONNECTED)
SIGNAL_WEBSOCKET_DISCONNECTED
)
return wsock