remote.py 13 KB

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