infrared.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """
  2. Implementation of Tuya infrared control devices
  3. """
  4. import logging
  5. from homeassistant.components.infrared import InfraredCommand, InfraredEntity
  6. from tinytuya.Contrib.IRRemoteControlDevice import IRRemoteControlDevice as IR
  7. from .device import TuyaLocalDevice
  8. from .entity import TuyaLocalEntity
  9. from .helpers.config import async_tuya_setup_platform
  10. from .helpers.device_config import TuyaEntityConfig
  11. _LOGGER = logging.getLogger(__name__)
  12. async def async_setup_entry(hass, entry, async_add_entities):
  13. """Set up the Tuya Local infrared control platform."""
  14. config = {**entry.data, **entry.options}
  15. await async_tuya_setup_platform(
  16. hass,
  17. async_add_entities,
  18. config,
  19. "infrared",
  20. TuyaLocalInfrared,
  21. )
  22. class TuyaLocalInfrared(TuyaLocalEntity, InfraredEntity):
  23. """Representation of a Tuya Local infrared control device."""
  24. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  25. """Initialize the infrared control device."""
  26. super().__init__()
  27. dps_map = self._init_begin(device, config)
  28. self._send_dp = dps_map.pop("send", None)
  29. self._command_dp = dps_map.pop("control", None)
  30. self._type_dp = dps_map.pop("code_type", None)
  31. self._init_end(dps_map)
  32. async def async_send_command(self, command: InfraredCommand) -> None:
  33. """Handle sending an infrared command."""
  34. timings = command.get_raw_timings()
  35. raw = [
  36. interval
  37. for timing in timings
  38. for interval in (timing.high_us, timing.low_us)
  39. ]
  40. tuya_command = IR.pulses_to_base64(raw)
  41. _LOGGER.debug("Sending infrared command: %s", tuya_command)
  42. if self._send_dp:
  43. if self._command_dp:
  44. await self._device.async_set_properties(
  45. self.package_multi_dp_send(tuya_command)
  46. )
  47. else:
  48. await self._send_dp.async_set_value(
  49. self._device,
  50. self.package_single_dp_send(tuya_command),
  51. )
  52. def package_single_dp_send(self, command: str) -> str:
  53. """Package the command for a single DP (usually dp id 201) send."""
  54. json_command = {
  55. "control": "send_ir",
  56. "type": 0,
  57. "head": "",
  58. "key1": "1" + command,
  59. }
  60. return json_command
  61. def package_multi_dp_send(self, command: str) -> dict:
  62. """Package the command for a multi DP send"""
  63. return {
  64. f"{self._command_dp.id}": "send_ir",
  65. f"{self._type_dp.id}": 0,
  66. f"{self._send_dp.id}": command,
  67. }