services.py 2.2 KB

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