RFC: Call services directly (#18720)
* Call services directly * Simplify * Type * Lint * Update name * Fix tests * Catch exceptions in HTTP view * Lint * Handle ServiceNotFound in API endpoints that call services * Type * Don't crash recorder on non-JSON serializable objects
This commit is contained in:
1 parent
53cbb28926
commit
df21dd21f2
30 files changed
+312
-186
No files matched your search
@@ -9,7 +9,9 @@ import json
|
||||
import logging
|
||||
|
||||
from aiohttp import web
|
||||
from aiohttp.web_exceptions import HTTPBadRequest
|
||||
import async_timeout
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.bootstrap import DATA_LOGGING
|
||||
from homeassistant.components.http import HomeAssistantView
|
||||
@@ -21,7 +23,8 @@ from homeassistant.const import (
|
||||
URL_API_TEMPLATE, __version__)
|
||||
import homeassistant.core as ha
|
||||
from homeassistant.auth.permissions.const import POLICY_READ
|
||||
from homeassistant.exceptions import TemplateError, Unauthorized
|
||||
from homeassistant.exceptions import (
|
||||
TemplateError, Unauthorized, ServiceNotFound)
|
||||
from homeassistant.helpers import template
|
||||
from homeassistant.helpers.service import async_get_all_descriptions
|
||||
from homeassistant.helpers.state import AsyncTrackStates
|
||||
@@ -339,8 +342,11 @@ class APIDomainServicesView(HomeAssistantView):
|
||||
"Data should be valid JSON.", HTTP_BAD_REQUEST)
|
||||
|
||||
with AsyncTrackStates(hass) as changed_states:
|
||||
await hass.services.async_call(
|
||||
domain, service, data, True, self.context(request))
|
||||
try:
|
||||
await hass.services.async_call(
|
||||
domain, service, data, True, self.context(request))
|
||||
except (vol.Invalid, ServiceNotFound):
|
||||
raise HTTPBadRequest()
|
||||
|
||||
return self.json(changed_states)
|
||||
|
||||
|
||||
@@ -9,7 +9,9 @@ import json
|
||||
import logging
|
||||
|
||||
from aiohttp import web
|
||||
from aiohttp.web_exceptions import HTTPUnauthorized, HTTPInternalServerError
|
||||
from aiohttp.web_exceptions import (
|
||||
HTTPUnauthorized, HTTPInternalServerError, HTTPBadRequest)
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.http.ban import process_success_login
|
||||
from homeassistant.core import Context, is_callback
|
||||
@@ -114,6 +116,10 @@ def request_handler_factory(view, handler):
|
||||
|
||||
if asyncio.iscoroutine(result):
|
||||
result = await result
|
||||
except vol.Invalid:
|
||||
raise HTTPBadRequest()
|
||||
except exceptions.ServiceNotFound:
|
||||
raise HTTPInternalServerError()
|
||||
except exceptions.Unauthorized:
|
||||
raise HTTPUnauthorized()
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ from homeassistant.core import callback
|
||||
from homeassistant.components.mqtt import (
|
||||
valid_publish_topic, valid_subscribe_topic)
|
||||
from homeassistant.const import (
|
||||
ATTR_SERVICE_DATA, EVENT_CALL_SERVICE, EVENT_SERVICE_EXECUTED,
|
||||
ATTR_SERVICE_DATA, EVENT_CALL_SERVICE,
|
||||
EVENT_STATE_CHANGED, EVENT_TIME_CHANGED, MATCH_ALL)
|
||||
from homeassistant.core import EventOrigin, State
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
@@ -69,16 +69,6 @@ def async_setup(hass, config):
|
||||
):
|
||||
return
|
||||
|
||||
# Filter out all the "event service executed" events because they
|
||||
# are only used internally by core as callbacks for blocking
|
||||
# during the interval while a service is being executed.
|
||||
# They will serve no purpose to the external system,
|
||||
# and thus are unnecessary traffic.
|
||||
# And at any rate it would cause an infinite loop to publish them
|
||||
# because publishing to an MQTT topic itself triggers one.
|
||||
if event.event_type == EVENT_SERVICE_EXECUTED:
|
||||
return
|
||||
|
||||
event_info = {'event_type': event.event_type, 'event_data': event.data}
|
||||
msg = json.dumps(event_info, cls=JSONEncoder)
|
||||
mqtt.async_publish(pub_topic, msg)
|
||||
|
||||
@@ -300,14 +300,24 @@ class Recorder(threading.Thread):
|
||||
time.sleep(CONNECT_RETRY_WAIT)
|
||||
try:
|
||||
with session_scope(session=self.get_session()) as session:
|
||||
dbevent = Events.from_event(event)
|
||||
session.add(dbevent)
|
||||
session.flush()
|
||||
try:
|
||||
dbevent = Events.from_event(event)
|
||||
session.add(dbevent)
|
||||
session.flush()
|
||||
except (TypeError, ValueError):
|
||||
_LOGGER.warning(
|
||||
"Event is not JSON serializable: %s", event)
|
||||
|
||||
if event.event_type == EVENT_STATE_CHANGED:
|
||||
dbstate = States.from_event(event)
|
||||
dbstate.event_id = dbevent.event_id
|
||||
session.add(dbstate)
|
||||
try:
|
||||
dbstate = States.from_event(event)
|
||||
dbstate.event_id = dbevent.event_id
|
||||
session.add(dbstate)
|
||||
except (TypeError, ValueError):
|
||||
_LOGGER.warning(
|
||||
"State is not JSON serializable: %s",
|
||||
event.data.get('new_state'))
|
||||
|
||||
updated = True
|
||||
|
||||
except exc.OperationalError as err:
|
||||
|
||||
@@ -3,7 +3,7 @@ import voluptuous as vol
|
||||
|
||||
from homeassistant.const import MATCH_ALL, EVENT_TIME_CHANGED
|
||||
from homeassistant.core import callback, DOMAIN as HASS_DOMAIN
|
||||
from homeassistant.exceptions import Unauthorized
|
||||
from homeassistant.exceptions import Unauthorized, ServiceNotFound
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.service import async_get_all_descriptions
|
||||
|
||||
@@ -141,10 +141,15 @@ async def handle_call_service(hass, connection, msg):
|
||||
if (msg['domain'] == HASS_DOMAIN and
|
||||
msg['service'] in ['restart', 'stop']):
|
||||
blocking = False
|
||||
await hass.services.async_call(
|
||||
msg['domain'], msg['service'], msg.get('service_data'), blocking,
|
||||
connection.context(msg))
|
||||
connection.send_message(messages.result_message(msg['id']))
|
||||
|
||||
try:
|
||||
await hass.services.async_call(
|
||||
msg['domain'], msg['service'], msg.get('service_data'), blocking,
|
||||
connection.context(msg))
|
||||
connection.send_message(messages.result_message(msg['id']))
|
||||
except ServiceNotFound:
|
||||
connection.send_message(messages.error_message(
|
||||
msg['id'], const.ERR_NOT_FOUND, 'Service not found.'))
|
||||
|
||||
|
||||
@callback
|
||||
|
||||
Reference in new issue
Block a user