services.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """Services for Tuya Local integration."""
  2. import asyncio
  3. import logging
  4. import voluptuous as vol
  5. from homeassistant.components import infrared
  6. from homeassistant.components.remote import (
  7. ATTR_DELAY_SECS,
  8. DEFAULT_DELAY_SECS,
  9. )
  10. from homeassistant.components.remote import DOMAIN as REMOTE_DOMAIN
  11. from homeassistant.core import HomeAssistant, ServiceCall
  12. from homeassistant.helpers import config_validation as cv
  13. from homeassistant.helpers import service
  14. from .const import DOMAIN
  15. from .infrared import TuyaRemoteCommand
  16. from .remote import TuyaLocalRemote
  17. REMOTE_SEND_IR_COMMAND_SCHEMA = {
  18. vol.Required("emitter_entity_id"): cv.entity_id,
  19. vol.Required("command"): str,
  20. vol.Optional("device"): str,
  21. }
  22. _LOGGER = logging.getLogger(__name__)
  23. async def async_setup_services(hass: HomeAssistant, entities: list[str]):
  24. """Set up services for the Tuya Local integration."""
  25. if "remote" in entities:
  26. service.async_register_platform_entity_service(
  27. hass,
  28. DOMAIN,
  29. "send_learned_ir_command",
  30. entity_domain=REMOTE_DOMAIN,
  31. schema=REMOTE_SEND_IR_COMMAND_SCHEMA,
  32. func=async_handle_send_ir_command,
  33. )
  34. return True
  35. async def async_handle_send_ir_command(entity, call: ServiceCall):
  36. """Action to send a saved remote command."""
  37. _LOGGER.info("Sending saved remote command: %s", call.data)
  38. if not isinstance(entity, TuyaLocalRemote):
  39. raise ValueError("Entity must be a tuya-local remote")
  40. if not entity._storage_loaded:
  41. await entity._async_load_storage()
  42. emitter = call.data.get("emitter")
  43. device = call.data.get("device")
  44. command = call.data.get("command")
  45. delay = call.data.get(ATTR_DELAY_SECS, DEFAULT_DELAY_SECS)
  46. code_list = entity._extract_codes(
  47. [command], subdevice=device
  48. ) # Validate command and get code
  49. at_least_one_sent = False
  50. for _, codes in code_list:
  51. if at_least_one_sent:
  52. await asyncio.sleep(delay)
  53. if len(codes) > 1:
  54. code = codes[entity._flags[device]]
  55. entity._flags[device] ^= 1
  56. else:
  57. code = codes[0]
  58. if code.startswith("rf:"):
  59. _LOGGER.error("RF emitters are not yet supported by this service")
  60. continue
  61. await infrared.async_send_command(
  62. entity.hass, emitter, cmd=TuyaRemoteCommand(code=code)
  63. )
  64. at_least_one_sent = True