device_config.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. if self.invalid_for(value, device):
  187. raise AttributeError(f"{self.name} cannot be set at this time")
  188. settings = self.get_values_to_set(device, value)
  189. await device.async_set_properties(settings)
  190. @property
  191. def values(self):
  192. """Return the possible values a dps can take."""
  193. if "mapping" not in self._config.keys():
  194. return None
  195. val = []
  196. for m in self._config["mapping"]:
  197. if "value" in m:
  198. val.append(m["value"])
  199. if "conditions" in m:
  200. for c in m["conditions"]:
  201. if "value" in c:
  202. val.append(c["value"])
  203. return list(set(val)) if len(val) > 0 else None
  204. def range(self, device):
  205. """Return the range for this dps if configured."""
  206. mapping = self._find_map_for_dps(device.get_property(self.id))
  207. if mapping is not None:
  208. _LOGGER.debug(f"Considering mapping for range of {self.name}")
  209. cond = self._active_condition(mapping, device)
  210. if cond is not None:
  211. constraint = mapping.get("constraint")
  212. _LOGGER.debug(f"Considering condition on {constraint}")
  213. r = None if cond is None else cond.get("range")
  214. if r is not None and "min" in r and "max" in r:
  215. _LOGGER.info(f"Conditional range returned for {self.name}")
  216. return r
  217. r = mapping.get("range")
  218. if r is not None and "min" in r and "max" in r:
  219. _LOGGER.info(f"Mapped range returned for {self.name}")
  220. return r
  221. r = self._config.get("range")
  222. if r is not None and "min" in r and "max" in r:
  223. return r
  224. else:
  225. return None
  226. def step(self, device):
  227. step = 1
  228. scale = 1
  229. mapping = self._find_map_for_dps(device.get_property(self.id))
  230. if mapping is not None:
  231. _LOGGER.debug(f"Considering mapping for step of {self.name}")
  232. step = mapping.get("step", 1)
  233. scale = mapping.get("scale", 1)
  234. cond = self._active_condition(mapping, device)
  235. if cond is not None:
  236. constraint = mapping.get("constraint")
  237. _LOGGER.debug(f"Considering condition on {constraint}")
  238. step = cond.get("step", step)
  239. scale = cond.get("scale", scale)
  240. if step != 1 or scale != 1:
  241. _LOGGER.info(f"Step for {self.name} is {step} with scale {scale}")
  242. return step / scale
  243. @property
  244. def readonly(self):
  245. return self._config.get("readonly", False)
  246. @property
  247. def stringify(self):
  248. return self._config.get("stringify", False)
  249. def invalid_for(self, value, device):
  250. mapping = self._find_map_for_value(value)
  251. if mapping is not None:
  252. cond = self._active_condition(mapping, device)
  253. if cond is not None:
  254. return cond.get("invalid", False)
  255. return False
  256. @property
  257. def hidden(self):
  258. return self._config.get("hidden", False)
  259. def _find_map_for_dps(self, value):
  260. if "mapping" not in self._config.keys():
  261. return None
  262. default = None
  263. for m in self._config["mapping"]:
  264. if "dps_val" not in m:
  265. default = m
  266. elif str(m["dps_val"]) == str(value):
  267. return m
  268. return default
  269. def _map_from_dps(self, value, device):
  270. # For stringified dps, convert to desired type if possible
  271. if self.stringify and value is not None:
  272. try:
  273. value = self.type(value)
  274. except ValueError:
  275. pass
  276. result = value
  277. mapping = self._find_map_for_dps(value)
  278. if mapping is not None:
  279. scale = mapping.get("scale", 1)
  280. if not isinstance(scale, (int, float)):
  281. scale = 1
  282. redirect = mapping.get("value-redirect")
  283. replaced = "value" in mapping
  284. result = mapping.get("value", result)
  285. cond = self._active_condition(mapping, device)
  286. if cond is not None:
  287. if cond.get("invalid", False):
  288. return None
  289. replaced = replaced or "value" in cond
  290. result = cond.get("value", result)
  291. scale = cond.get("scale", scale)
  292. redirect = cond.get("value-redirect", redirect)
  293. if "mapping" in cond:
  294. for m in cond["mapping"]:
  295. if str(m.get("dps_val")) == str(result):
  296. replaced = "value" in m
  297. result = m.get("value", result)
  298. if redirect is not None:
  299. _LOGGER.debug(f"Redirecting {self.name} to {redirect}")
  300. r_dps = self._entity.find_dps(redirect)
  301. return r_dps.get_value(device)
  302. if scale != 1 and isinstance(result, (int, float)):
  303. result = result / scale
  304. replaced = True
  305. if replaced:
  306. _LOGGER.debug(
  307. "%s: Mapped dps %s value from %s to %s",
  308. self._entity._device.name,
  309. self.id,
  310. value,
  311. result,
  312. )
  313. return result
  314. def _find_map_for_value(self, value):
  315. if "mapping" not in self._config.keys():
  316. return None
  317. default = None
  318. for m in self._config["mapping"]:
  319. if "dps_val" not in m:
  320. default = m
  321. if "value" in m and str(m["value"]) == str(value):
  322. return m
  323. if "conditions" in m:
  324. for c in m["conditions"]:
  325. if "value" in c and c["value"] == value:
  326. return m
  327. return default
  328. def _active_condition(self, mapping, device):
  329. constraint = mapping.get("constraint")
  330. conditions = mapping.get("conditions")
  331. if constraint is not None and conditions is not None:
  332. c_dps = self._entity.find_dps(constraint)
  333. c_val = None if c_dps is None else device.get_property(c_dps.id)
  334. if c_val is not None:
  335. for cond in conditions:
  336. if c_val == cond.get("dps_val"):
  337. return cond
  338. return None
  339. def get_values_to_set(self, device, value):
  340. """Return the dps values that would be set when setting to value"""
  341. result = value
  342. dps_map = {}
  343. mapping = self._find_map_for_value(value)
  344. if mapping is not None:
  345. replaced = False
  346. scale = mapping.get("scale", 1)
  347. redirect = mapping.get("value-redirect")
  348. if not isinstance(scale, (int, float)):
  349. scale = 1
  350. step = mapping.get("step")
  351. if not isinstance(step, (int, float)):
  352. step = None
  353. if "dps_val" in mapping:
  354. result = mapping["dps_val"]
  355. replaced = True
  356. # Conditions may have side effect of setting another value.
  357. cond = self._active_condition(mapping, device)
  358. if cond is not None:
  359. if cond.get("value") == value:
  360. c_dps = self._entity.find_dps(mapping["constraint"])
  361. dps_map.update(c_dps.get_values_to_set(device, cond["dps_val"]))
  362. scale = cond.get("scale", scale)
  363. step = cond.get("step", step)
  364. redirect = cond.get("value-redirect", redirect)
  365. if redirect is not None:
  366. _LOGGER.debug(f"Redirecting {self.name} to {redirect}")
  367. r_dps = self._entity.find_dps(redirect)
  368. return r_dps.get_values_to_set(device, value)
  369. if scale != 1 and isinstance(result, (int, float)):
  370. _LOGGER.debug(f"Scaling {result} by {scale}")
  371. result = result * scale
  372. replaced = True
  373. if step is not None and isinstance(result, (int, float)):
  374. _LOGGER.debug(f"Stepping {result} to {step}")
  375. result = step * round(float(result) / step)
  376. replaced = True
  377. if replaced:
  378. _LOGGER.debug(
  379. "%s: Mapped dps %s to %s from %s",
  380. self._entity._device.name,
  381. self.id,
  382. result,
  383. value,
  384. )
  385. r = self.range(device)
  386. if r is not None:
  387. minimum = r["min"]
  388. maximum = r["max"]
  389. if result < minimum or result > maximum:
  390. raise ValueError(
  391. f"{self.name} ({value}) must be between {minimum} and {maximum}"
  392. )
  393. if self.type is int:
  394. _LOGGER.debug(f"Rounding {self.name}")
  395. result = int(round(result))
  396. elif self.type is bool:
  397. result = True if result else False
  398. elif self.type is float:
  399. result = float(result)
  400. elif self.type is str:
  401. result = str(result)
  402. if self.stringify:
  403. result = str(result)
  404. dps_map[self.id] = result
  405. return dps_map
  406. def available_configs():
  407. """List the available config files."""
  408. _CONFIG_DIR = dirname(config_dir.__file__)
  409. for (path, dirs, files) in walk(_CONFIG_DIR):
  410. for basename in sorted(files):
  411. if fnmatch(basename, "*.yaml"):
  412. yield basename
  413. def possible_matches(dps):
  414. """Return possible matching configs for a given set of dps values."""
  415. for cfg in available_configs():
  416. parsed = TuyaDeviceConfig(cfg)
  417. if parsed.matches(dps):
  418. yield parsed
  419. def config_for_legacy_use(conf_type):
  420. """
  421. Return a config to use with config_type for legacy transition.
  422. Note: as there are two variants for Kogan Socket, this is not guaranteed
  423. to be the correct config for the device, so only use it for looking up
  424. the legacy class during the transition period.
  425. """
  426. for cfg in available_configs():
  427. parsed = TuyaDeviceConfig(cfg)
  428. if parsed.legacy_type == conf_type:
  429. return parsed
  430. return None