device_config.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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, splitext
  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", splitext(self.config)[0])
  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 _entity_match_analyse(self, entity, keys, matched, dps):
  71. """
  72. Determine whether this entity can be a match for the dps
  73. Args:
  74. entity - the TuyaEntityConfig to check against
  75. keys - the unmatched keys for the device
  76. matched - the matched keys for the device
  77. dps - the dps values to be matched
  78. Side Effects:
  79. Moves items from keys to matched if they match dps
  80. Return Value:
  81. True if all dps in entity could be matched to dps, False otherwise
  82. """
  83. for d in entity.dps():
  84. if (d.id not in keys and d.id not in matched) or not _typematch(
  85. d.type, dps[d.id]
  86. ):
  87. return False
  88. if d.id in keys:
  89. matched.append(d.id)
  90. keys.remove(d.id)
  91. return True
  92. def match_quality(self, dps):
  93. """Determine the match quality for the provided dps map."""
  94. keys = list(dps.keys())
  95. matched = []
  96. if "updated_at" in keys:
  97. keys.remove("updated_at")
  98. total = len(keys)
  99. if not self._entity_match_analyse(self.primary_entity, keys, matched, dps):
  100. return 0
  101. for e in self.secondary_entities():
  102. if not self._entity_match_analyse(e, keys, matched, dps):
  103. return 0
  104. return round((total - len(keys)) * 100 / total)
  105. class TuyaEntityConfig:
  106. """Representation of an entity config for a supported entity."""
  107. def __init__(self, device, config):
  108. self._device = device
  109. self._config = config
  110. @property
  111. def name(self):
  112. """The friendly name for this entity."""
  113. own_name = self._config.get("name")
  114. if own_name is None:
  115. return self._device.name
  116. else:
  117. return self._device.name + " " + own_name
  118. @property
  119. def legacy_class(self):
  120. """Return the legacy device corresponding to this config."""
  121. name = self._config.get("legacy_class")
  122. if name is None:
  123. return None
  124. return locate("custom_components.tuya_local" + name)
  125. @property
  126. def deprecated(self):
  127. """Return whether this entitiy is deprecated."""
  128. return "deprecated" in self._config.keys()
  129. @property
  130. def deprecation_message(self):
  131. """Return a deprecation message for this entity"""
  132. replacement = self._config.get(
  133. "deprecated", "nothing, this warning has been raised in error"
  134. )
  135. return (
  136. f"The use of {self.entity} for {self._device.name} is "
  137. f"deprecated and should be replaced by {replacement}."
  138. )
  139. @property
  140. def entity(self):
  141. """The entity type of this entity."""
  142. return self._config["entity"]
  143. @property
  144. def device_class(self):
  145. """The device class of this entity."""
  146. return self._config.get("class")
  147. def dps(self):
  148. """Iterate through the list of dps for this entity."""
  149. for d in self._config["dps"]:
  150. yield TuyaDpsConfig(self, d)
  151. def find_dps(self, name):
  152. """Find a dps with the specified name."""
  153. for d in self.dps():
  154. if d.name == name:
  155. return d
  156. return None
  157. class TuyaDpsConfig:
  158. """Representation of a dps config."""
  159. def __init__(self, entity, config):
  160. self._entity = entity
  161. self._config = config
  162. @property
  163. def id(self):
  164. return str(self._config["id"])
  165. @property
  166. def type(self):
  167. t = self._config["type"]
  168. types = {
  169. "boolean": bool,
  170. "integer": int,
  171. "string": str,
  172. "float": float,
  173. "bitfield": int,
  174. }
  175. return types.get(t)
  176. @property
  177. def name(self):
  178. return self._config["name"]
  179. def get_value(self, device):
  180. """Return the value of the dps from the given device."""
  181. return self._map_from_dps(device.get_property(self.id), device)
  182. async def async_set_value(self, device, value):
  183. """Set the value of the dps in the given device to given value."""
  184. if self.readonly:
  185. raise TypeError(f"{self.name} is read only")
  186. await device.async_set_property(self.id, self._map_to_dps(value, device))
  187. @property
  188. def values(self):
  189. """Return the possible values a dps can take."""
  190. if "mapping" not in self._config.keys():
  191. return None
  192. val = []
  193. for m in self._config["mapping"]:
  194. if "value" in m:
  195. val.append(m["value"])
  196. if "conditions" in m:
  197. for c in m["conditions"]:
  198. if "value" in c:
  199. val.append(c["value"])
  200. return list(set(val)) if len(val) > 0 else None
  201. @property
  202. def range(self):
  203. """Return the range for this dps if configured."""
  204. if (
  205. "range" in self._config.keys()
  206. and "min" in self._config["range"].keys()
  207. and "max" in self._config["range"].keys()
  208. ):
  209. return self._config["range"]
  210. else:
  211. return None
  212. def step(self, device):
  213. step = 1
  214. scale = 1
  215. mapping = self._find_map_for_dps(device.get_property(self.id))
  216. if mapping is not None:
  217. step = mapping.get("step", 1)
  218. scale = mapping.get("scale", 1)
  219. return step / scale
  220. @property
  221. def readonly(self):
  222. return "readonly" in self._config.keys() and self._config["readonly"] is True
  223. @property
  224. def hidden(self):
  225. return "hidden" in self._config.keys() and self._config["hidden"] is True
  226. def _find_map_for_dps(self, value):
  227. if "mapping" not in self._config.keys():
  228. return None
  229. default = None
  230. for m in self._config["mapping"]:
  231. if "dps_val" not in m:
  232. default = m
  233. elif str(m["dps_val"]) == str(value):
  234. return m
  235. return default
  236. def _map_from_dps(self, value, device):
  237. result = value
  238. mapping = self._find_map_for_dps(value)
  239. if mapping is not None:
  240. scale = mapping.get("scale", 1)
  241. if not isinstance(scale, (int, float)):
  242. scale = 1
  243. replaced = "value" in mapping
  244. result = mapping.get("value", result)
  245. if "conditions" in mapping:
  246. cond_dps = (
  247. self
  248. if "constraint" not in mapping
  249. else self._entity.find_dps(mapping["constraint"])
  250. )
  251. for c in mapping["conditions"]:
  252. if (
  253. "dps_val" in c
  254. and c["dps_val"] == device.get_property(cond_dps.id)
  255. and "value" in c
  256. ):
  257. result = c["value"]
  258. replaced = True
  259. if scale != 1 and isinstance(result, (int, float)):
  260. result = result / scale
  261. replaced = True
  262. if replaced:
  263. _LOGGER.debug(
  264. "%s: Mapped dps %s value from %s to %s",
  265. self._entity._device.name,
  266. self.id,
  267. value,
  268. result,
  269. )
  270. return result
  271. def _find_map_for_value(self, value):
  272. if "mapping" not in self._config.keys():
  273. return None
  274. default = None
  275. for m in self._config["mapping"]:
  276. if "dps_val" not in m:
  277. default = m
  278. if "value" in m and str(m["value"]) == str(value):
  279. return m
  280. if "conditions" in m:
  281. for c in m["conditions"]:
  282. if "value" in c and c["value"] == value:
  283. return m
  284. return default
  285. def _map_to_dps(self, value, device):
  286. result = value
  287. mapping = self._find_map_for_value(value)
  288. if mapping is not None:
  289. replaced = False
  290. scale = mapping.get("scale", 1)
  291. if not isinstance(scale, (int, float)):
  292. scale = 1
  293. step = mapping.get("step")
  294. if not isinstance(step, (int, float)):
  295. step = None
  296. if "dps_val" in mapping:
  297. result = mapping["dps_val"]
  298. replaced = True
  299. # Conditions may have side effect of setting another value.
  300. if "conditions" in mapping and "constraint" in mapping:
  301. c_dps = self._entity.find_dps(mapping["constraint"])
  302. for c in mapping["conditions"]:
  303. if "value" in c and c["value"] == value:
  304. device.set_property(c_dps.id, c["dps_val"])
  305. if scale != 1 and isinstance(result, (int, float)):
  306. _LOGGER.debug(f"Scaling {result} by {scale}")
  307. result = result * scale
  308. replaced = True
  309. if step is not None and isinstance(result, (int, float)):
  310. _LOGGER.debug(f"Stepping {result} to {step}")
  311. result = step * round(float(result) / step)
  312. replaced = True
  313. if replaced:
  314. _LOGGER.debug(
  315. "%s: Mapped dps %s to %s from %s",
  316. self._entity._device.name,
  317. self.id,
  318. result,
  319. value,
  320. )
  321. if self.range is not None:
  322. minimum = self.range["min"]
  323. maximum = self.range["max"]
  324. if result < minimum or result > maximum:
  325. raise ValueError(
  326. f"Target {self.name} ({value}) must be between "
  327. f"{minimum} and {maximum}"
  328. )
  329. if self.type is int:
  330. _LOGGER.debug(f"Rounding {self.name}")
  331. result = int(round(result))
  332. elif self.type is bool:
  333. result = True if result else False
  334. elif self.type is float:
  335. result = float(result)
  336. elif self.type is str:
  337. result = str(result)
  338. return result
  339. def available_configs():
  340. """List the available config files."""
  341. _CONFIG_DIR = dirname(config_dir.__file__)
  342. for (path, dirs, files) in walk(_CONFIG_DIR):
  343. for basename in sorted(files):
  344. if fnmatch(basename, "*.yaml"):
  345. yield basename
  346. def possible_matches(dps):
  347. """Return possible matching configs for a given set of dps values."""
  348. for cfg in available_configs():
  349. parsed = TuyaDeviceConfig(cfg)
  350. if parsed.matches(dps):
  351. yield parsed
  352. def config_for_legacy_use(conf_type):
  353. """
  354. Return a config to use with config_type for legacy transition.
  355. Note: as there are two variants for Kogan Socket, this is not guaranteed
  356. to be the correct config for the device, so only use it for looking up
  357. the legacy class during the transition period.
  358. """
  359. for cfg in available_configs():
  360. parsed = TuyaDeviceConfig(cfg)
  361. if parsed.legacy_type == conf_type:
  362. return parsed
  363. return None