text.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """
  2. Setup for different kinds of Tuya text entities
  3. """
  4. import logging
  5. from homeassistant.components.text import TextEntity, TextMode
  6. from homeassistant.components.text.const import (
  7. ATTR_MAX,
  8. ATTR_MIN,
  9. ATTR_MODE,
  10. ATTR_PATTERN,
  11. )
  12. from .device import TuyaLocalDevice
  13. from .entity import TuyaLocalEntity
  14. from .helpers.config import async_tuya_setup_platform
  15. from .helpers.device_config import TuyaEntityConfig
  16. _LOGGER = logging.getLogger(__name__)
  17. async def async_setup_entry(hass, config_entry, async_add_entities):
  18. config = {**config_entry.data, **config_entry.options}
  19. await async_tuya_setup_platform(
  20. hass,
  21. async_add_entities,
  22. config,
  23. "text",
  24. TuyaLocalText,
  25. )
  26. class TuyaLocalText(TuyaLocalEntity, TextEntity):
  27. """Representation of a Tuya Text Entity"""
  28. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  29. """
  30. Initialise the text entity.
  31. Args:
  32. device (TuyaLocalDevice): the device API instance
  33. config (TuyaEntityConfig): the configuration for this entity
  34. """
  35. super().__init__()
  36. dps_map = self._init_begin(device, config)
  37. self._value_dp = dps_map.pop("value")
  38. if self._value_dp is None:
  39. raise AttributeError(f"{config.config_id} is missing value dp")
  40. self._attr_mode = TextMode.PASSWORD if self._value_dp.hidden else TextMode.TEXT
  41. self._extra_info = {ATTR_MODE: self._attr_mode}
  42. range = self._value_dp.range(device, False)
  43. if range:
  44. self._attr_native_min = range[0]
  45. self._attr_native_max = range[1]
  46. self._extra_info[ATTR_MIN] = self._attr_native_min
  47. self._extra_info[ATTR_MAX] = self._attr_native_max
  48. if self._value_dp.rawtype == "hex":
  49. self._attr_pattern = "[0-9a-fA-F]*"
  50. elif self._value_dp.rawtype == "base64":
  51. self._attr_pattern = (
  52. "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"
  53. )
  54. # TODO: general pattern support
  55. if hasattr(self, "_attr_pattern"):
  56. self._extra_info[ATTR_PATTERN] = self._attr_pattern
  57. @property
  58. def native_value(self) -> str | None:
  59. """Return the current value"""
  60. return self._value_dp.get_value(self._device)
  61. async def async_set_value(self, value: str) -> None:
  62. """Set the value"""
  63. await self._value_dp.async_set_value(self._device, value)
  64. @property
  65. def extra_state_attributes(self) -> dict[str, any]:
  66. """As well as extra attributes specified in the config, also return info about the text."""
  67. return TuyaLocalEntity.extra_state_attributes.fget(self) | self._extra_info