remote.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. """
  2. Implementation of Tuya remote control devices
  3. Based on broadlink integration for code saving under HA storage
  4. """
  5. import asyncio
  6. from collections import defaultdict
  7. from collections.abc import Iterable
  8. from datetime import timedelta
  9. from itertools import product
  10. import json
  11. import logging
  12. from typing import Any
  13. import voluptuous as vol
  14. from homeassistant.components import persistent_notification
  15. from homeassistant.components.remote import (
  16. ATTR_ALTERNATIVE,
  17. ATTR_DELAY_SECS,
  18. ATTR_DEVICE,
  19. ATTR_NUM_REPEATS,
  20. DEFAULT_DELAY_SECS,
  21. DOMAIN as RM_DOMAIN,
  22. RemoteEntity,
  23. RemoteEntityFeature,
  24. SERVICE_DELETE_COMMAND,
  25. SERVICE_LEARN_COMMAND,
  26. SERVICE_SEND_COMMAND,
  27. )
  28. from homeassistant.const import ATTR_COMMAND
  29. from homeassistant.helpers import config_validation as cv
  30. from homeassistant.helpers.storage import Store
  31. from homeassistant.util import dt as dt_util
  32. from .device import TuyaLocalDevice
  33. from .helpers.config import async_tuya_setup_platform
  34. from .helpers.device_config import TuyaEntityConfig
  35. from .helpers.mixin import TuyaLocalEntity
  36. _LOGGER = logging.getLogger(__name__)
  37. CODE_STORAGE_VERSION = 1
  38. FLAG_STORAGE_VERSION = 1
  39. CODE_SAVE_DELAY = 15
  40. FLAG_SAVE_DELAY = 15
  41. LEARNING_TIMEOUT = timedelta(seconds=30)
  42. # These commands seem to be standard for all devices
  43. CMD_SEND = "send_ir"
  44. CMD_LEARN = "study"
  45. CMD_ENDLEARN = "study_exit"
  46. CMD_STUDYKEY = "study_key"
  47. COMMAND_SCHEMA = vol.Schema(
  48. {
  49. vol.Required(ATTR_COMMAND): vol.All(
  50. cv.ensure_list, [vol.All(cv.string, vol.Length(min=1))], vol.Length(min=1)
  51. ),
  52. },
  53. extra=vol.ALLOW_EXTRA,
  54. )
  55. SERVICE_SEND_SCHEMA = COMMAND_SCHEMA.extend(
  56. {
  57. vol.Optional(ATTR_DEVICE): vol.All(cv.string, vol.Length(min=1)),
  58. vol.Optional(ATTR_DELAY_SECS, default=DEFAULT_DELAY_SECS): vol.Coerce(float),
  59. }
  60. )
  61. SERVICE_LEARN_SCHEMA = COMMAND_SCHEMA.extend(
  62. {
  63. vol.Required(ATTR_DEVICE): vol.All(cv.string, vol.Length(min=1)),
  64. vol.Optional(ATTR_ALTERNATIVE, default=False): cv.boolean,
  65. }
  66. )
  67. SERVICE_DELETE_SCHEMA = COMMAND_SCHEMA.extend(
  68. {
  69. vol.Required(ATTR_DEVICE): vol.All(cv.string, vol.Length(min=1)),
  70. }
  71. )
  72. async def async_setup_entry(hass, config_entry, async_add_entities):
  73. config = {**config_entry.data, **config_entry.options}
  74. await async_tuya_setup_platform(
  75. hass,
  76. async_add_entities,
  77. config,
  78. "remote",
  79. TuyaLocalRemote,
  80. )
  81. class TuyaLocalRemote(TuyaLocalEntity, RemoteEntity):
  82. """Representation of a Tuya Remote entity."""
  83. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  84. """
  85. Initialise the remote device.
  86. Args:
  87. device (TuyaLocalDevice): The device API instance.
  88. config (TuyaEntityConfig): The entity config.
  89. """
  90. super().__init__()
  91. dps_map = self._init_begin(device, config)
  92. self._send_dp = dps_map.pop("send", None)
  93. self._receive_dp = dps_map.pop("receive", None)
  94. # Some remotes split out the control (command) into its own dp and just send raw codes in send
  95. self._control_dp = dps_map.pop("control", None)
  96. self._delay_dp = dps_map.pop("delay", None)
  97. self._type_dp = dps_map.pop("code_type", None)
  98. self._init_end(dps_map)
  99. if self._receive_dp:
  100. self._attr_supported_features |= (
  101. RemoteEntityFeature.LEARN_COMMAND | RemoteEntityFeature.DELETE_COMMAND
  102. )
  103. self._code_storage = Store(
  104. device._hass,
  105. CODE_STORAGE_VERSION,
  106. f"tuya_local_remote_{device.unique_id}_codes",
  107. )
  108. self._flag_storage = Store(
  109. device._hass,
  110. FLAG_STORAGE_VERSION,
  111. f"tuya_local_remote_{device.unique_id}_flags",
  112. )
  113. self._storage_loaded = False
  114. self._codes = {}
  115. self._flags = defaultdict(int)
  116. self._lock = asyncio.Lock()
  117. self._attr_is_on = True
  118. async def _async_load_storage(self):
  119. """Load stored codes and flags from disk."""
  120. self._codes.update(await self._code_storage.async_load() or {})
  121. self._flags.update(await self._flag_storage.async_load() or {})
  122. self._storage_loaded = True
  123. def _extract_codes(self, commands, subdevice=None):
  124. """Extract a list of remote codes.
  125. If the command starts with 'b64:', extract the code from it.
  126. Otherwise use the command and optionally subdevice as keys to extract the
  127. actual command from storage.
  128. The commands are returned in sublists. For toggle commands, the sublist
  129. may contain two codes that must be sent alternately with each call."""
  130. code_list = []
  131. for cmd in commands:
  132. if cmd.startswith("b64:"):
  133. codes = [cmd[4:]]
  134. else:
  135. if subdevice is None:
  136. raise ValueError("device must be specified")
  137. try:
  138. codes = self._codes[subdevice][cmd]
  139. except KeyError as err:
  140. raise ValueError(
  141. f"Command {repr(cmd)} not found for {subdevice}"
  142. ) from err
  143. if isinstance(codes, list):
  144. codes = code[:]
  145. else:
  146. codes = [codes]
  147. for idx, code in enumerate(codes):
  148. try:
  149. codes[idx] = code
  150. except ValueError as err:
  151. raise ValueError(f"Invalid code: {repr(code)}") from err
  152. code_list.append(codes)
  153. return code_list
  154. def _encode_send_code(self, code, delay):
  155. """Encode a remote command into dps values to send."""
  156. # Based on https://github.com/jasonacox/tinytuya/issues/74 and
  157. # the docs it references, there are two kinds of IR devices.
  158. # 1. separate dps for control, code, study,...
  159. # 2. single dp (201) for send_ir, which takes JSON input,
  160. # including control, code, delay, etc, and another for
  161. # study_ir (202) that receives the codes in study mode.
  162. dps = {}
  163. if self._control_dp:
  164. # control and code are sent in seperate dps.
  165. dps = dps | self._control_dp.get_values_to_set(self._device, CMD_SEND)
  166. dps = dps | self._send_dp.get_values_to_set(self._device, code)
  167. if self._delay_dp:
  168. dps = dps | self._delay_dp.get_values_to_set(self._device, delay)
  169. if self._type_dp:
  170. dps = dps | self._type_dp.get_values_to_seet(self._device, 0)
  171. else:
  172. dps = dps | self._send_dp.get_values_to_set(
  173. self._device,
  174. json.dumps(
  175. {
  176. "control": CMD_SEND,
  177. "head": "",
  178. # leading zero means use head, any other leeading character is discarded.
  179. "key1": "1" + code,
  180. "type": 0,
  181. "delay": int(delay),
  182. }
  183. ),
  184. )
  185. return dps
  186. async def async_send_command(self, command: Iterable[str], **kwargs: Any) -> None:
  187. """Send remote commands"""
  188. kwargs[ATTR_COMMAND] = command
  189. kwargs = SERVICE_SEND_SCHEMA(kwargs)
  190. commands = kwargs[ATTR_COMMAND]
  191. subdevice = kwargs.get(ATTR_DEVICE)
  192. repeat = kwargs.get(ATTR_NUM_REPEATS)
  193. delay = kwargs.get(ATTR_DELAY_SECS, DEFAULT_DELAY_SECS) * 1000
  194. service = f"{RM_DOMAIN}.{SERVICE_SEND_COMMAND}"
  195. if not self._storage_loaded:
  196. await self._async_load_storage()
  197. try:
  198. code_list = self._extract_codes(command, subdevice)
  199. except ValueError as err:
  200. _LOGGER.error("Failed to call %s: %s", service, err)
  201. raise
  202. at_least_one_sent = False
  203. for _, codes in product(range(repeat), code_list):
  204. if at_least_one_sent:
  205. await asyncio.sleep(delay)
  206. if len(codes) > 1:
  207. code = codes[self._flags[subdevice]]
  208. else:
  209. code = codes[0]
  210. dps_to_set = self._encode_send_code(code, delay)
  211. await self._device.async_set_properties(dps_to_set)
  212. if len(codes) > 1:
  213. self._flags[subdevice] ^= 1
  214. at_least_one_sent = True
  215. if at_least_one_sent:
  216. self._flag_storage.async_delay_save(self._flags, FLAG_SAVE_DELAY)
  217. async def async_learn_command(self, **kwargs: Any) -> None:
  218. """Learn a list of commands from a remote."""
  219. kwargs = SERVICE_LEARN_SCHEMA(kwargs)
  220. commands = kwargs[ATTR_COMMAND]
  221. subdevice = kwargs[ATTR_DEVICE]
  222. toggle = kwargs[ATTR_ALTERNATIVE]
  223. service = f"{RM_DOMAIN}.{SERVICE_LEARN_COMMAND}"
  224. if not self._storage_loaded:
  225. await self._async_load_storage()
  226. async with self._lock:
  227. should_store = False
  228. for command in commands:
  229. code = await self._async_learn_command(command)
  230. if toggle:
  231. code = [code, await self._async_learn_command(command)]
  232. self._codes.setdefault(subdevice, {}).update({command: code})
  233. should_store = True
  234. if should_store:
  235. await self._code_storage.async_save(self._codes)
  236. async def _async_learn_command(self, command):
  237. """Learn a single command"""
  238. if self._control_dp:
  239. await self._control_dp.async_set_value(self._device, CMD_LEARN)
  240. else:
  241. await self._send_dp.async_set_value(
  242. self._device,
  243. json.dumps({"control": CMD_LEARN}),
  244. )
  245. persistent_notification.async_create(
  246. self._device._hass,
  247. f"Press the '{command}' button.",
  248. title="Learn command",
  249. notification_id="learn_command",
  250. )
  251. try:
  252. start_time = dt_util.utcnow()
  253. while (dt_util.utcnow() - start_time) < LEARNING_TIMEOUT:
  254. await asyncio.sleep(1)
  255. code = self._receive_dp.get_value(self._device)
  256. if code is not None:
  257. return code
  258. raise TimeoutError(
  259. f"No remote code received within {LEARNING_TIMEOUT.total_seconds()} seconds",
  260. )
  261. finally:
  262. persistent_notification.async_dismiss(
  263. self._device._hass, notification_id="learn_command"
  264. )
  265. if self._control_dp:
  266. await self._control_dp.async_set_value(
  267. self._device,
  268. CMD_ENDLEARN,
  269. )
  270. else:
  271. await self._send_dp.async_set_value(
  272. self._device,
  273. json.dumps({"control": CMD_ENDLEARN}),
  274. )
  275. async def async_delete_command(self, **kwargs: Any) -> None:
  276. """Delete a list of commands from a remote."""
  277. kwargs = SERVICE_DELETE_SCHEMA(kwargs)
  278. commands = kwargs[ATTR_COMMAND]
  279. subdevice = kwargs[ATTR_DEVICE]
  280. service = f"{RM_DOMAIN}.{SERVICE_DELETE_COMMAND}"
  281. if not self._storage_loaded:
  282. await self._async_load_storage()
  283. try:
  284. codes = self._codes[subdevice]
  285. except KeyError as err:
  286. err_msg = f"Device not found {repr(subdevice)}"
  287. _LOGGER.error("Failed to call %s. %s", service, err_msg)
  288. raise ValueError(err_msg) from err
  289. cmds_not_found = []
  290. for command in commands:
  291. try:
  292. del codes[command]
  293. except KeyError:
  294. cmds_not_found.append(command)
  295. if cmds_not_found:
  296. if len(cmds_not_found) == 1:
  297. err_msg = f"Command not found: {repr(cmds_not_found[0])}"
  298. else:
  299. err_msg = f"Commands not found: {repr(cmds_not_found)}"
  300. if len(cmds_not_found) == len(commands):
  301. _LOGGER.error("Failed to call %s. %s", service, err_msg)
  302. raise ValueError(err_msg)
  303. _LOGGER.error("Error during %s. %s", service, err_msg)
  304. # Clean up
  305. if not codes:
  306. del self._codes[subdevice]
  307. if self._flags.pop(subdevice, None) is not None:
  308. self._flag_storage.async_delay_save(self._flags, FLAG_SAVE_DELAY)
  309. self._code_storage.async_delay_save(self._codes, CODE_SAVE_DELAY)