remote.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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._init_end(dps_map)
  97. self._attr_supported_features = 0
  98. if self._receive_dp:
  99. self._attr_supported_features |= (
  100. RemoteEntityFeature.LEARN_COMMAND | RemoteEntityFeature.DELETE_COMMAND
  101. )
  102. self._code_storage = Store(
  103. device._hass,
  104. CODE_STORAGE_VERSION,
  105. f"tuya_local_remote_{device.unique_id}_codes",
  106. )
  107. self._flag_storage = Store(
  108. device._hass,
  109. FLAG_STORAGE_VERSION,
  110. f"tuya_local_remote_{device.unique_id}_flags",
  111. )
  112. self._storage_loaded = False
  113. self._codes = {}
  114. self._flags = defaultdict(int)
  115. self._lock = asyncio.Lock()
  116. self._attr_is_on = True
  117. async def _async_load_storage(self):
  118. """Load stored codes and flags from disk."""
  119. self._codes.update(await self._code_storage.async_load() or {})
  120. self._flags.update(await self._flag_storage.async_load() or {})
  121. self._storage_loaded = True
  122. def _extract_codes(self, commands, subdevice=None):
  123. """Extract a list of remote codes.
  124. If the command starts with 'b64:', extract the code from it.
  125. Otherwise use the command and optionally subdevice as keys to extract the
  126. actual command from storage.
  127. The commands are returned in sublists. For toggle commands, the sublist
  128. may contain two codes that must be sent alternately with each call."""
  129. code_list = []
  130. for cmd in commands:
  131. if cmd.startswith("b64:"):
  132. codes = [cmd[4:]]
  133. else:
  134. if subdevice is None:
  135. raise ValueError("device must be specified")
  136. try:
  137. codes = self._codes[subdevice][cmd]
  138. except KeyError as err:
  139. raise ValueError(
  140. f"Command {repr(cmd)} not found for {subdevice}"
  141. ) from err
  142. if isinstance(codes, list):
  143. codes = code[:]
  144. else:
  145. codes = [codes]
  146. for idx, code in enumerate(codes):
  147. try:
  148. codes[idx] = code
  149. except ValueError as err:
  150. raise ValueError(f"Invalid code: {repr(code)}") from err
  151. code_list.append(codes)
  152. return code_list
  153. def _encode_send_code(self, code):
  154. """Encode a remote command into dps values to send."""
  155. # Based on https://github.com/jasonacox/tinytuya/issues/74 and
  156. # the docs it references, there are two kinds of IR devices.
  157. # 1. separate dps for control, code, study,...
  158. # 2. single dp (201) for send_ir, which takes JSON input,
  159. # including control, code, delay, etc, and another for
  160. # study_ir (202) that receives the codes in study mode.
  161. dps = {}
  162. if self._control_dp:
  163. # control and code are sent in seperate dps.
  164. dps = dps | self._control_dp.get_values_to_set(self._device, CMD_SEND)
  165. dps = dps | self._send_dp.get_values_to_set(self._device, code)
  166. else:
  167. dps = dps | self._send_dp.get_values_to_set(
  168. self._device,
  169. json.dumps(
  170. {
  171. "control": CMD_SEND,
  172. "head": "",
  173. # leading zero means use head, any other leeading character is discarded.
  174. "key1": "1" + code,
  175. "type": 0,
  176. "delay": 300,
  177. }
  178. ),
  179. )
  180. return dps
  181. async def async_send_command(self, command: Iterable[str], **kwargs: Any) -> None:
  182. """Send remote commands"""
  183. kwargs[ATTR_COMMAND] = command
  184. kwargs = SERVICE_SEND_SCHEMA(kwargs)
  185. commands = kwargs[ATTR_COMMAND]
  186. subdevice = kwargs.get(ATTR_DEVICE)
  187. repeat = kwargs.get(ATTR_NUM_REPEATS)
  188. delay = kwargs.get(ATTR_DELAY_SECS)
  189. service = f"{RM_DOMAIN}.{SERVICE_SEND_COMMAND}"
  190. if not self._storage_loaded:
  191. await self._async_load_storage()
  192. try:
  193. code_list = self._extract_codes(command, subdevice)
  194. except ValueError as err:
  195. _LOGGER.error("Failed to call %s: %s", service, err)
  196. raise
  197. at_least_one_sent = False
  198. for _, codes in product(range(repeat), code_list):
  199. if at_least_one_sent:
  200. await asyncio.sleep(delay)
  201. if len(codes) > 1:
  202. code = codes[self._flags[subdevice]]
  203. else:
  204. code = codes[0]
  205. dps_to_set = self._encode_send_code(code)
  206. await self._device.async_set_properties(dps_to_set)
  207. if len(codes) > 1:
  208. self._flags[subdevice] ^= 1
  209. at_least_one_sent = True
  210. if at_least_one_sent:
  211. self._flag_storage.async_delay_save(self._flags, FLAG_SAVE_DELAY)
  212. async def async_learn_command(self, **kwargs: Any) -> None:
  213. """Learn a list of commands from a remote."""
  214. kwargs = SERVICE_LEARN_SCHEMA(kwargs)
  215. commands = kwargs[ATTR_COMMAND]
  216. subdevice = kwargs[ATTR_DEVICE]
  217. toggle = kwargs[ATTR_ALTERNATIVE]
  218. service = f"{RM_DOMAIN}.{SERVICE_LEARN_COMMAND}"
  219. if not self._storage_loaded:
  220. await self._async_load_storage()
  221. async with self._lock:
  222. should_store = False
  223. for command in commands:
  224. code = await self._async_learn_command(command)
  225. if toggle:
  226. code = [code, await self._async_learn_command(command)]
  227. self._codes.setdefault(subdevice, {}).update({command: code})
  228. should_store = True
  229. if should_store:
  230. await self._code_storage.async_save(self._codes)
  231. async def _async_learn_command(self, command):
  232. """Learn a single command"""
  233. if self._control_dp:
  234. await self._control_dp.async_set_value(self._device, CMD_LEARN)
  235. else:
  236. await self._send_dp.async_set_value(
  237. self._device,
  238. json.dumps({"control": CMD_LEARN}),
  239. )
  240. persistent_notification.async_create(
  241. self._device._hass,
  242. f"Press the '{command}' button.",
  243. title="Learn command",
  244. notification_id="learn_command",
  245. )
  246. try:
  247. start_time = dt_util.utcnow()
  248. while (dt_util.utcnow() - start_time) < LEARNING_TIMEOUT:
  249. await asyncio.sleep(1)
  250. code = self._receive_dp.get_value(self._device)
  251. if code is not None:
  252. return code
  253. raise TimeoutError(
  254. f"No remote code received within {LEARNING_TIMEOUT.total_seconds()} seconds",
  255. )
  256. finally:
  257. persistent_notification.async_dismiss(
  258. self._device._hass, notification_id="learn_command"
  259. )
  260. if self._control_dp:
  261. await self._control_dp.async_set_value(
  262. self._device,
  263. CMD_ENDLEARN,
  264. )
  265. else:
  266. await self._send_dp.async_set_value(
  267. self._device,
  268. json.dumps({"control": CMD_ENDLEARN}),
  269. )
  270. async def async_delete_command(self, **kwargs: Any) -> None:
  271. """Delete a list of commands from a remote."""
  272. kwargs = SERVICE_DELETE_SCHEMA(kwargs)
  273. commands = kwargs[ATTR_COMMAND]
  274. subdevice = kwargs[ATTR_DEVICE]
  275. service = f"{RM_DOMAIN}.{SERVICE_DELETE_COMMAND}"
  276. if not self._storage_loaded:
  277. await self._async_load_storage()
  278. try:
  279. codes = self._codes[subdevice]
  280. except KeyError as err:
  281. err_msg = f"Device not found {repr(subdevice)}"
  282. _LOGGER.error("Failed to call %s. %s", service, err_msg)
  283. raise ValueError(err_msg) from err
  284. cmds_not_found = []
  285. for command in commands:
  286. try:
  287. del codes[command]
  288. except KeyError:
  289. cmds_not_found.append(command)
  290. if cmds_not_found:
  291. if len(cmds_not_found) == 1:
  292. err_msg = f"Command not found: {repr(cmds_not_found[0])}"
  293. else:
  294. err_msg = f"Commands not found: {repr(cmds_not_found)}"
  295. if len(cmds_not_found) == len(commands):
  296. _LOGGER.error("Failed to call %s. %s", service, err_msg)
  297. raise ValueError(err_msg)
  298. _LOGGER.error("Error during %s. %s", service, err_msg)
  299. # Clean up
  300. if not codes:
  301. del self._codes[subdevice]
  302. if self._flags.pop(subdevice, None) is not None:
  303. self._flag_storage.async_delay_save(self._flags, FLAG_SAVE_DELAY)
  304. self._code_storage.async_delay_save(self._codes, CODE_SAVE_DELAY)