From 00de971a0d811da82683db7d878e7c894f9a282a Mon Sep 17 00:00:00 2001 From: Alone Date: Fri, 13 Sep 2024 12:49:14 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=95=B9=20add=20`learn=5Fcommand`=20for=20?= =?UTF-8?q?remote=20(#276)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- custom_components/xiaomi_miot/remote.py | 32 +++++++++++++++++++------ 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/custom_components/xiaomi_miot/remote.py b/custom_components/xiaomi_miot/remote.py index 7789c4b2a..9e6e6e7b5 100644 --- a/custom_components/xiaomi_miot/remote.py +++ b/custom_components/xiaomi_miot/remote.py @@ -1,5 +1,6 @@ """Support remote entity for Xiaomi Miot.""" import logging +import asyncio import time from functools import partial @@ -7,7 +8,7 @@ CONF_HOST, CONF_TOKEN, ) -from homeassistant.components import remote +from homeassistant.components import remote, persistent_notification from homeassistant.components.remote import ( DOMAIN as ENTITY_DOMAIN, RemoteEntity, @@ -174,15 +175,32 @@ async def async_send_command(self, command, **kwargs): partial(self.send_remote_command, command, **kwargs) ) - def learn_command(self, **kwargs): + async def async_learn_command(self, **kwargs): """Learn a command from a device.""" + timeout = int(kwargs.get(remote.ATTR_TIMEOUT) or 30) + res = {} try: - key = int(kwargs.get(remote.ATTR_DEVICE)) - return self._device.learn(key) + key = int(kwargs.get(remote.ATTR_DEVICE, 999999)) + for idx in range(timeout): + if idx == 0: + await self.hass.async_add_executor_job(self._device.learn, key) + await asyncio.sleep(1) + res = await self.hass.async_add_executor_job(self._device.read, key) + if isinstance(res, dict) and res.get('code'): + break except (TypeError, ValueError, DeviceException) as exc: - self.logger.warning('%s: Learn command failed: %s, the device ID is used to store command ' - 'and must between 1 and 1000000.', self.name_model, exc) - return False + res = {'error': f'{exc}'} + self.logger.warning( + '%s: Learn command failed, the device ID must between 1 and 1000000. %s', + self.name_model, exc, + ) + persistent_notification.async_create( + self.hass, + f'{res}', + 'Remote learn result', + f'{DOMAIN}-remote-learn', + ) + return res def delete_command(self, **kwargs): """Delete commands from the database."""