device_config.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. """
  2. Config parser for Tuya Local devices.
  3. """
  4. from fnmatch import fnmatch
  5. import logging
  6. from os import walk
  7. from os.path import join, dirname
  8. from pydoc import locate
  9. from homeassistant.util.yaml import load_yaml
  10. import custom_components.tuya_local.devices as config_dir
  11. _LOGGER = logging.getLogger(__name__)
  12. def _typematch(type, value):
  13. # Workaround annoying legacy of bool being a subclass of int in Python
  14. if type is int and isinstance(value, bool):
  15. return False
  16. if isinstance(value, type):
  17. return True
  18. # Allow values embedded in strings if they can be converted
  19. # But not for bool, as everything can be converted to bool
  20. elif isinstance(value, str) and type is not bool:
  21. try:
  22. type(value)
  23. return True
  24. except ValueError:
  25. return False
  26. return False
  27. class TuyaDeviceConfig:
  28. """Representation of a device config for Tuya Local devices."""
  29. def __init__(self, fname):
  30. """Initialize the device config.
  31. Args:
  32. fname (string): The filename of the yaml config to load."""
  33. _CONFIG_DIR = dirname(config_dir.__file__)
  34. self._fname = fname
  35. filename = join(_CONFIG_DIR, fname)
  36. self._config = load_yaml(filename)
  37. _LOGGER.debug("Loaded device config %s", fname)
  38. @property
  39. def name(self):
  40. """Return the friendly name for this device."""
  41. return self._config["name"]
  42. @property
  43. def config(self):
  44. """Return the config file associated with this device."""
  45. return self._fname
  46. @property
  47. def legacy_type(self):
  48. """Return the legacy conf_type associated with this device."""
  49. return self._config.get("legacy_type", None)
  50. @property
  51. def primary_entity(self):
  52. """Return the primary type of entity for this device."""
  53. return TuyaEntityConfig(self, self._config["primary_entity"])
  54. def secondary_entities(self):
  55. """Iterate through entites for any secondary entites supported."""
  56. if "secondary_entities" in self._config.keys():
  57. for conf in self._config["secondary_entities"]:
  58. yield TuyaEntityConfig(self, conf)
  59. def matches(self, dps):
  60. """Determine if this device matches the provided dps map."""
  61. for d in self.primary_entity.dps():
  62. if d.id not in dps.keys() or not _typematch(d.type, dps[d.id]):
  63. return False
  64. for dev in self.secondary_entities():
  65. for d in dev.dps():
  66. if d.id not in dps.keys() or not _typematch(d.type, dps[d.id]):
  67. return False
  68. _LOGGER.debug("Matched config for %s", self.name)
  69. return True
  70. def match_quality(self, dps):
  71. """Determine the match quality for the provided dps map."""
  72. keys = list(dps.keys())
  73. total = len(keys)
  74. for d in self.primary_entity.dps():
  75. if d.id not in keys or not _typematch(d.type, dps[d.id]):
  76. return 0
  77. keys.remove(d.id)
  78. for dev in self.secondary_entities():
  79. for d in dev.dps():
  80. if d.id not in keys or not _typematch(d.type, dps[d.id]):
  81. return 0
  82. keys.remove(d.id)
  83. return (total - len(keys)) * 100 / total
  84. class TuyaEntityConfig:
  85. """Representation of an entity config for a supported entity."""
  86. def __init__(self, device, config):
  87. self._device = device
  88. self._config = config
  89. @property
  90. def name(self):
  91. """The friendly name for this entity."""
  92. return self._config.get("name", self._device.name)
  93. @property
  94. def legacy_class(self):
  95. """Return the legacy device corresponding to this config."""
  96. name = self._config.get("legacy_class", None)
  97. if name is None:
  98. return None
  99. return locate("custom_components.tuya_local" + name)
  100. @property
  101. def entity(self):
  102. """The entity type of this entity."""
  103. return self._config["entity"]
  104. @property
  105. def device_class(self):
  106. """The device class of this entity."""
  107. return self._config.get("class", None)
  108. def dps(self):
  109. """Iterate through the list of dps for this entity."""
  110. for d in self._config["dps"]:
  111. yield TuyaDpsConfig(self, d)
  112. class TuyaDpsConfig:
  113. """Representation of a dps config."""
  114. def __init__(self, entity, config):
  115. self._entity = entity
  116. self._config = config
  117. @property
  118. def id(self):
  119. return str(self._config["id"])
  120. @property
  121. def type(self):
  122. t = self._config["type"]
  123. types = {
  124. "boolean": bool,
  125. "integer": int,
  126. "string": str,
  127. "float": float,
  128. "bitfield": int,
  129. }
  130. return types.get(t, None)
  131. @property
  132. def name(self):
  133. return self._config["name"]
  134. def get_value(self, device):
  135. """Return the value of the dps from the given device."""
  136. return self.map_from_dps(device.get_property(self.id))
  137. async def async_set_value(self, device, value):
  138. """Set the value of the dps in the given device to given value."""
  139. await device.async_set_property(self.id, self.map_to_dps(value))
  140. @property
  141. def values(self):
  142. """Return the possible values a dps can take."""
  143. if "mapping" not in self._config.keys():
  144. return None
  145. v = []
  146. for map in self._config["mapping"]:
  147. if "value" in map:
  148. v.append(map["value"])
  149. return v if len(v) > 0 else None
  150. @property
  151. def range(self):
  152. """Return the range for this dps if configured."""
  153. if (
  154. "range" in self._config.keys()
  155. and "min" in self._config["range"].keys()
  156. and "max" in self._config["range"].keys()
  157. ):
  158. return self._config["range"]
  159. else:
  160. return None
  161. @property
  162. def isreadonly(self):
  163. return "readonly" in self._config.keys() and self._config["readonly"] is True
  164. def map_from_dps(self, value):
  165. result = value
  166. scale = 1
  167. if "mapping" in self._config.keys():
  168. for map in self._config["mapping"]:
  169. if "value" in map and ("dps_val" not in map or map["dps_val"] == value):
  170. result = map["value"]
  171. _LOGGER.debug(
  172. "%s: Mapped dps %s value from %s to %s",
  173. self._entity._device.name,
  174. self.id,
  175. value,
  176. result,
  177. )
  178. if "scale" in map and "value" not in map:
  179. scale = map["scale"]
  180. return (
  181. result
  182. if scale == 1 or not isinstance(result, (int, float))
  183. else result / scale
  184. )
  185. def map_to_dps(self, value):
  186. result = value
  187. scale = 1
  188. if "mapping" in self._config.keys():
  189. for map in self._config["mapping"]:
  190. if "value" in map and "dps_val" in map and map["value"] == value:
  191. result = map["dps_val"]
  192. _LOGGER.debug(
  193. "%s: Mapped dps %s to %s from %s",
  194. self._entity._device.name,
  195. self.id,
  196. result,
  197. value,
  198. )
  199. if "scale" in map and "value" not in map:
  200. scale = map["scale"]
  201. return (
  202. result
  203. if scale == 1 or not isinstance(result, (int, float))
  204. else result * scale
  205. )
  206. def available_configs():
  207. """List the available config files."""
  208. _CONFIG_DIR = dirname(config_dir.__file__)
  209. for (path, dirs, files) in walk(_CONFIG_DIR):
  210. for basename in sorted(files):
  211. if fnmatch(basename, "*.yaml"):
  212. yield basename
  213. def possible_matches(dps):
  214. """Return possible matching configs for a given set of dps values."""
  215. for cfg in available_configs():
  216. parsed = TuyaDeviceConfig(cfg)
  217. if parsed.matches(dps):
  218. yield parsed
  219. def config_for_legacy_use(conf_type):
  220. """
  221. Return a config to use with config_type for legacy transition.
  222. Note: as there are two variants for Kogan Socket, this is not guaranteed
  223. to be the correct config for the device, so only use it for looking up
  224. the legacy class during the transition period.
  225. """
  226. for cfg in available_configs():
  227. parsed = TuyaDeviceConfig(cfg)
  228. if parsed.legacy_type == conf_type:
  229. return parsed
  230. return None