device_config.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. if "updated_at" in keys:
  74. keys.remove("updated_at")
  75. total = len(keys)
  76. for d in self.primary_entity.dps():
  77. if d.id not in keys or not _typematch(d.type, dps[d.id]):
  78. return 0
  79. keys.remove(d.id)
  80. for dev in self.secondary_entities():
  81. for d in dev.dps():
  82. if d.id not in keys or not _typematch(d.type, dps[d.id]):
  83. return 0
  84. keys.remove(d.id)
  85. return round((total - len(keys)) * 100 / total)
  86. class TuyaEntityConfig:
  87. """Representation of an entity config for a supported entity."""
  88. def __init__(self, device, config):
  89. self._device = device
  90. self._config = config
  91. @property
  92. def name(self):
  93. """The friendly name for this entity."""
  94. return self._config.get("name", self._device.name)
  95. @property
  96. def legacy_class(self):
  97. """Return the legacy device corresponding to this config."""
  98. name = self._config.get("legacy_class", None)
  99. if name is None:
  100. return None
  101. return locate("custom_components.tuya_local" + name)
  102. @property
  103. def entity(self):
  104. """The entity type of this entity."""
  105. return self._config["entity"]
  106. @property
  107. def device_class(self):
  108. """The device class of this entity."""
  109. return self._config.get("class", None)
  110. def dps(self):
  111. """Iterate through the list of dps for this entity."""
  112. for d in self._config["dps"]:
  113. yield TuyaDpsConfig(self, d)
  114. def find_dps(self, name):
  115. """Find a dps with the specified name."""
  116. for d in self.dps():
  117. if d.name == name:
  118. return d
  119. return None
  120. class TuyaDpsConfig:
  121. """Representation of a dps config."""
  122. def __init__(self, entity, config):
  123. self._entity = entity
  124. self._config = config
  125. @property
  126. def id(self):
  127. return str(self._config["id"])
  128. @property
  129. def type(self):
  130. t = self._config["type"]
  131. types = {
  132. "boolean": bool,
  133. "integer": int,
  134. "string": str,
  135. "float": float,
  136. "bitfield": int,
  137. }
  138. return types.get(t, None)
  139. @property
  140. def name(self):
  141. return self._config["name"]
  142. def get_value(self, device):
  143. """Return the value of the dps from the given device."""
  144. return self._map_from_dps(device.get_property(self.id), device)
  145. async def async_set_value(self, device, value):
  146. """Set the value of the dps in the given device to given value."""
  147. if self.readonly:
  148. raise TypeError(f"{self.name} is read only")
  149. await device.async_set_property(self.id, self._map_to_dps(value, device))
  150. @property
  151. def values(self):
  152. """Return the possible values a dps can take."""
  153. if "mapping" not in self._config.keys():
  154. return None
  155. v = []
  156. for map in self._config["mapping"]:
  157. if "value" in map:
  158. v.append(map["value"])
  159. if "conditions" in map:
  160. for c in map["conditions"]:
  161. if "value" in c:
  162. v.append(c["value"])
  163. return list(set(v)) if len(v) > 0 else None
  164. @property
  165. def range(self):
  166. """Return the range for this dps if configured."""
  167. if (
  168. "range" in self._config.keys()
  169. and "min" in self._config["range"].keys()
  170. and "max" in self._config["range"].keys()
  171. ):
  172. return self._config["range"]
  173. else:
  174. return None
  175. @property
  176. def readonly(self):
  177. return "readonly" in self._config.keys() and self._config["readonly"] is True
  178. @property
  179. def hidden(self):
  180. return "hidden" in self._config.keys() and self._config["hidden"] is True
  181. def _map_from_dps(self, value, device):
  182. result = value
  183. replaced = False
  184. default_value = None
  185. scale = 1
  186. if "mapping" in self._config.keys():
  187. for map in self._config["mapping"]:
  188. if "dps_val" not in map:
  189. if "value" in map:
  190. default_value = map["value"]
  191. if "scale" in map:
  192. scale = map["scale"]
  193. elif str(map["dps_val"]) == str(value):
  194. if "value" in map:
  195. result = map["value"]
  196. replaced = True
  197. if "conditions" in map:
  198. cond_dps = self
  199. if "constraint" in map:
  200. cond_dps = self._entity.find_dps(map["constraint"])
  201. for c in map["conditions"]:
  202. if (
  203. "dps_val" in c
  204. and c["dps_val"] == device.get_property(cond_dps.id)
  205. and "value" in c
  206. ):
  207. result = c["value"]
  208. replaced = True
  209. if not replaced and default_value is not None:
  210. result = default_value
  211. replaced = True
  212. if scale != 1 and isinstance(result, (int, float)):
  213. result = result / scale
  214. replaced = True
  215. if replaced:
  216. _LOGGER.debug(
  217. "%s: Mapped dps %s value from %s to %s",
  218. self._entity._device.name,
  219. self.id,
  220. value,
  221. result,
  222. )
  223. return result
  224. def _map_to_dps(self, value, device):
  225. result = value
  226. replaced = False
  227. scale = 1
  228. step = None
  229. if "mapping" in self._config.keys():
  230. for map in self._config["mapping"]:
  231. if (
  232. "value" in map
  233. and "dps_val" in map
  234. and str(map["value"]) == str(value)
  235. ):
  236. result = map["dps_val"]
  237. replaced = True
  238. elif "conditions" in map:
  239. for c in map["conditions"]:
  240. if "value" in c and c["value"] == value:
  241. result = map["dps_val"]
  242. c_dps = self._entity.find_dps(map["constraint"])
  243. device.set_property(c_dps.id, c["dps_val"])
  244. if (
  245. "scale" in map
  246. and "value" not in map
  247. and isinstance(map["scale"], (int, float))
  248. ):
  249. scale = map["scale"]
  250. if (
  251. "step" in map
  252. and "value" not in map
  253. and isinstance(map["step"], (int, float))
  254. ):
  255. step = map["step"]
  256. if scale != 1 and isinstance(result, (int, float)):
  257. result = result / scale
  258. replaced = True
  259. if step is not None and isinstance(result, (int, float)):
  260. result = step * round(float(result) / step)
  261. replaced = True
  262. if self.range is not None:
  263. min = self.range["min"]
  264. max = self.range["max"]
  265. if result < min or result > max:
  266. raise ValueError(
  267. f"Target {self.name} ({value}) must be between {min} and {max}"
  268. )
  269. if replaced:
  270. _LOGGER.debug(
  271. "%s: Mapped dps %s to %s from %s",
  272. self._entity._device.name,
  273. self.id,
  274. result,
  275. value,
  276. )
  277. return result
  278. def available_configs():
  279. """List the available config files."""
  280. _CONFIG_DIR = dirname(config_dir.__file__)
  281. for (path, dirs, files) in walk(_CONFIG_DIR):
  282. for basename in sorted(files):
  283. if fnmatch(basename, "*.yaml"):
  284. yield basename
  285. def possible_matches(dps):
  286. """Return possible matching configs for a given set of dps values."""
  287. for cfg in available_configs():
  288. parsed = TuyaDeviceConfig(cfg)
  289. if parsed.matches(dps):
  290. yield parsed
  291. def config_for_legacy_use(conf_type):
  292. """
  293. Return a config to use with config_type for legacy transition.
  294. Note: as there are two variants for Kogan Socket, this is not guaranteed
  295. to be the correct config for the device, so only use it for looking up
  296. the legacy class during the transition period.
  297. """
  298. for cfg in available_configs():
  299. parsed = TuyaDeviceConfig(cfg)
  300. if parsed.legacy_type == conf_type:
  301. return parsed
  302. return None