Skip to content

Commit

Permalink
👌 add response for services
Browse files Browse the repository at this point in the history
  • Loading branch information
al-one committed Aug 11, 2023
1 parent 8ea4fa8 commit 059e028
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 12 deletions.
41 changes: 29 additions & 12 deletions custom_components/xiaomi_miot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
vol.Required('method'): cv.string,
vol.Optional('params', default=[]): cv.ensure_list,
vol.Optional('throw', default=False): cv.boolean,
vol.Optional('return_result', default=True): cv.boolean,
},
),
},
Expand Down Expand Up @@ -385,7 +386,8 @@ def init_integration_data(hass):


def bind_services_to_entries(hass, services):
async def async_service_handler(service):
async def async_service_handler(service) -> ServiceResponse:
result = None
method = services.get(service.service)
fun = method['method']
params = {
Expand Down Expand Up @@ -416,14 +418,21 @@ async def async_service_handler(service):
if not hasattr(ent, fun):
_LOGGER.warning('Call service failed: Entity %s have no method: %s', ent.entity_id, fun)
continue
await getattr(ent, fun)(**params)
result = await getattr(ent, fun)(**params)
update_tasks.append(ent.async_update_ha_state(True))
if update_tasks:
await asyncio.gather(*update_tasks)
if not isinstance(result, dict):
result = {'result': result}
return result

for srv, obj in services.items():
schema = obj.get('schema', XIAOMI_MIIO_SERVICE_SCHEMA)
hass.services.async_register(DOMAIN, srv, async_service_handler, schema=schema)
kws = {
'schema': obj.get('schema', XIAOMI_MIIO_SERVICE_SCHEMA),
}
if SupportsResponse:
kws['supports_response'] = SupportsResponse.OPTIONAL
hass.services.async_register(DOMAIN, srv, async_service_handler, **kws)


async def async_reload_integration_config(hass, config):
Expand All @@ -449,7 +458,7 @@ async def async_reload_integration_config(hass, config):

async def async_setup_component_services(hass):

async def async_get_token(call):
async def async_get_token(call) -> ServiceResponse:
nam = call.data.get('name')
kwd = f'{nam}'.strip().lower()
cnt = 0
Expand Down Expand Up @@ -482,13 +491,19 @@ async def async_get_token(call):
persistent_notification.async_create(
hass, msg, 'Miot device', f'{DOMAIN}-debug',
)
return lst
return {
'list': lst,
}

hass.services.async_register(
DOMAIN, 'get_token', async_get_token,
schema=XIAOMI_MIIO_SERVICE_SCHEMA.extend({
kws = {
'schema': XIAOMI_MIIO_SERVICE_SCHEMA.extend({
vol.Required('name', default=''): cv.string,
}),
}
if SupportsResponse:
kws['supports_response'] = SupportsResponse.OPTIONAL,
hass.services.async_register(
DOMAIN, 'get_token', async_get_token, **kws,
)

async def async_renew_devices(call):
Expand Down Expand Up @@ -960,16 +975,18 @@ def send_miio_command(self, method, params=None, **kwargs):
'params': params,
'result': result,
})
ret = result == self._success_result
if not ret:
self.logger.info('%s: Send miio command: %s(%s) failed, result: %s', self.name_model, method, params, result)
if kwargs.get('throw'):
persistent_notification.create(
self.hass,
f'{result}',
'Miio command result',
f'{DOMAIN}-debug',
)
ret = result == self._success_result
if kwargs.get('return_result'):
return result
elif not ret:
self.logger.info('%s: Send miio command: %s(%s) failed, result: %s', self.name_model, method, params, result)
return ret

def send_command(self, method, params=None, **kwargs):
Expand Down
9 changes: 9 additions & 0 deletions custom_components/xiaomi_miot/core/const.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from __future__ import annotations
from enum import Enum

from .device_customizes import DEVICE_CUSTOMIZES # noqa
from .miot_local_devices import MIOT_LOCAL_MODELS # noqa
from .translation_languages import TRANSLATION_LANGUAGES # noqa
from homeassistant.util.json import JsonObjectType

DOMAIN = 'xiaomi_miot'
DEFAULT_NAME = 'Xiaomi Miot'
Expand Down Expand Up @@ -81,3 +83,10 @@ class EntityCategory(Enum):
SUPPORTED_DOMAINS.append(DOMAIN_TEXT)
except (ModuleNotFoundError, ImportError):
DOMAIN_TEXT = None

try:
# hass 2023.7
from homeassistant.core import ServiceResponse, SupportsResponse
except (ModuleNotFoundError, ImportError):
SupportsResponse = None
ServiceResponse = JsonObjectType | None

0 comments on commit 059e028

Please sign in to comment.