device_config.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. for conf in self._config.get("secondary_entities", {}):
  57. yield TuyaEntityConfig(self, conf)
  58. def matches(self, dps):
  59. """Determine if this device matches the provided dps map."""
  60. for d in self.primary_entity.dps():
  61. if d.id not in dps.keys() or not _typematch(d.type, dps[d.id]):
  62. return False
  63. for dev in self.secondary_entities():
  64. for d in dev.dps():
  65. if d.id not in dps.keys() or not _typematch(d.type, dps[d.id]):
  66. return False
  67. _LOGGER.debug("Matched config for %s", self.name)
  68. return True
  69. def _entity_match_analyse(self, entity, keys, matched, dps):
  70. """
  71. Determine whether this entity can be a match for the dps
  72. Args:
  73. entity - the TuyaEntityConfig to check against
  74. keys - the unmatched keys for the device
  75. matched - the matched keys for the device
  76. dps - the dps values to be matched
  77. Side Effects:
  78. Moves items from keys to matched if they match dps
  79. Return Value:
  80. True if all dps in entity could be matched to dps, False otherwise
  81. """
  82. for d in entity.dps():
  83. if (d.id not in keys and d.id not in matched) or not _typematch(
  84. d.type, dps[d.id]
  85. ):
  86. return False
  87. if d.id in keys:
  88. matched.append(d.id)
  89. keys.remove(d.id)
  90. return True
  91. def match_quality(self, dps):
  92. """Determine the match quality for the provided dps map."""
  93. keys = list(dps.keys())
  94. matched = []
  95. if "updated_at" in keys:
  96. keys.remove("updated_at")
  97. total = len(keys)
  98. if not self._entity_match_analyse(self.primary_entity, keys, matched, dps):
  99. return 0
  100. for e in self.secondary_entities():
  101. if not self._entity_match_analyse(e, keys, matched, dps):
  102. return 0
  103. return round((total - len(keys)) * 100 / total)
  104. class TuyaEntityConfig:
  105. """Representation of an entity config for a supported entity."""
  106. def __init__(self, device, config):
  107. self._device = device
  108. self._config = config
  109. @property
  110. def name(self):
  111. """The friendly name for this entity."""
  112. own_name = self._config.get("name")
  113. if own_name is None:
  114. return self._device.name
  115. else:
  116. return self._device.name + " " + own_name
  117. @property
  118. def legacy_class(self):
  119. """Return the legacy device corresponding to this config."""
  120. name = self._config.get("legacy_class")
  121. if name is None:
  122. return None
  123. return locate("custom_components.tuya_local" + name)
  124. @property
  125. def deprecated(self):
  126. """Return whether this entitiy is deprecated."""
  127. return "deprecated" in self._config.keys()
  128. @property
  129. def deprecation_message(self):
  130. """Return a deprecation message for this entity"""
  131. replacement = self._config.get(
  132. "deprecated", "nothing, this warning has been raised in error"
  133. )
  134. return (
  135. f"The use of {self.entity} for {self._device.name} is "
  136. f"deprecated and should be replaced by {replacement}."
  137. )
  138. @property
  139. def entity(self):
  140. """The entity type of this entity."""
  141. return self._config["entity"]
  142. @property
  143. def device_class(self):
  144. """The device class of this entity."""
  145. return self._config.get("class")
  146. def icon(self, device):
  147. """Return the icon for this device, with state as given."""
  148. icon = self._config.get("icon", None)
  149. priority = self._config.get("icon_priority", 100)
  150. for d in self.dps():
  151. rule = d.icon_rule(device)
  152. if rule and rule["priority"] < priority:
  153. icon = rule["icon"]
  154. priority = rule["priority"]
  155. return icon
  156. def dps(self):
  157. """Iterate through the list of dps for this entity."""
  158. for d in self._config["dps"]:
  159. yield TuyaDpsConfig(self, d)
  160. def find_dps(self, name):
  161. """Find a dps with the specified name."""
  162. for d in self.dps():
  163. if d.name == name:
  164. return d
  165. return None
  166. class TuyaDpsConfig:
  167. """Representation of a dps config."""
  168. def __init__(self, entity, config):
  169. self._entity = entity
  170. self._config = config
  171. @property
  172. def id(self):
  173. return str(self._config["id"])
  174. @property
  175. def type(self):
  176. t = self._config["type"]
  177. types = {
  178. "boolean": bool,
  179. "integer": int,
  180. "string": str,
  181. "float": float,
  182. "bitfield": int,
  183. }
  184. return types.get(t)
  185. @property
  186. def name(self):
  187. return self._config["name"]
  188. def get_value(self, device):
  189. """Return the value of the dps from the given device."""
  190. return self._map_from_dps(device.get_property(self.id), device)
  191. async def async_set_value(self, device, value):
  192. """Set the value of the dps in the given device to given value."""
  193. if self.readonly:
  194. raise TypeError(f"{self.name} is read only")
  195. if self.invalid_for(value, device):
  196. raise AttributeError(f"{self.name} cannot be set at this time")
  197. settings = self.get_values_to_set(device, value)
  198. await device.async_set_properties(settings)
  199. @property
  200. def values(self):
  201. """Return the possible values a dps can take."""
  202. if "mapping" not in self._config.keys():
  203. return None
  204. val = []
  205. for m in self._config["mapping"]:
  206. if "value" in m:
  207. val.append(m["value"])
  208. for c in m.get("conditions", {}):
  209. if "value" in c:
  210. val.append(c["value"])
  211. return list(set(val)) if len(val) > 0 else None
  212. def range(self, device):
  213. """Return the range for this dps if configured."""
  214. mapping = self._find_map_for_dps(device.get_property(self.id))
  215. if mapping is not None:
  216. _LOGGER.debug(f"Considering mapping for range of {self.name}")
  217. cond = self._active_condition(mapping, device)
  218. if cond is not None:
  219. constraint = mapping.get("constraint")
  220. _LOGGER.debug(f"Considering condition on {constraint}")
  221. r = None if cond is None else cond.get("range")
  222. if r is not None and "min" in r and "max" in r:
  223. _LOGGER.info(f"Conditional range returned for {self.name}")
  224. return r
  225. r = mapping.get("range")
  226. if r is not None and "min" in r and "max" in r:
  227. _LOGGER.info(f"Mapped range returned for {self.name}")
  228. return r
  229. r = self._config.get("range")
  230. if r is not None and "min" in r and "max" in r:
  231. return r
  232. else:
  233. return None
  234. def step(self, device):
  235. step = 1
  236. scale = 1
  237. mapping = self._find_map_for_dps(device.get_property(self.id))
  238. if mapping is not None:
  239. _LOGGER.debug(f"Considering mapping for step of {self.name}")
  240. step = mapping.get("step", 1)
  241. scale = mapping.get("scale", 1)
  242. cond = self._active_condition(mapping, device)
  243. if cond is not None:
  244. constraint = mapping.get("constraint")
  245. _LOGGER.debug(f"Considering condition on {constraint}")
  246. step = cond.get("step", step)
  247. scale = cond.get("scale", scale)
  248. if step != 1 or scale != 1:
  249. _LOGGER.info(f"Step for {self.name} is {step} with scale {scale}")
  250. return step / scale
  251. @property
  252. def readonly(self):
  253. return self._config.get("readonly", False)
  254. @property
  255. def stringify(self):
  256. return self._config.get("stringify", False)
  257. def invalid_for(self, value, device):
  258. mapping = self._find_map_for_value(value)
  259. if mapping is not None:
  260. cond = self._active_condition(mapping, device)
  261. if cond is not None:
  262. return cond.get("invalid", False)
  263. return False
  264. @property
  265. def hidden(self):
  266. return self._config.get("hidden", False)
  267. def _find_map_for_dps(self, value):
  268. default = None
  269. for m in self._config.get("mapping", {}):
  270. if "dps_val" not in m:
  271. default = m
  272. elif str(m["dps_val"]) == str(value):
  273. return m
  274. return default
  275. def _map_from_dps(self, value, device):
  276. # For stringified dps, convert to desired type if possible
  277. if self.stringify and value is not None:
  278. try:
  279. value = self.type(value)
  280. except ValueError:
  281. pass
  282. result = value
  283. mapping = self._find_map_for_dps(value)
  284. if mapping is not None:
  285. scale = mapping.get("scale", 1)
  286. if not isinstance(scale, (int, float)):
  287. scale = 1
  288. redirect = mapping.get("value-redirect")
  289. replaced = "value" in mapping
  290. result = mapping.get("value", result)
  291. cond = self._active_condition(mapping, device)
  292. if cond is not None:
  293. if cond.get("invalid", False):
  294. return None
  295. replaced = replaced or "value" in cond
  296. result = cond.get("value", result)
  297. scale = cond.get("scale", scale)
  298. redirect = cond.get("value-redirect", redirect)
  299. for m in cond.get("mapping", {}):
  300. if str(m.get("dps_val")) == str(result):
  301. replaced = "value" in m
  302. result = m.get("value", result)
  303. if redirect is not None:
  304. _LOGGER.debug(f"Redirecting {self.name} to {redirect}")
  305. r_dps = self._entity.find_dps(redirect)
  306. return r_dps.get_value(device)
  307. if scale != 1 and isinstance(result, (int, float)):
  308. result = result / scale
  309. replaced = True
  310. if replaced:
  311. _LOGGER.debug(
  312. "%s: Mapped dps %s value from %s to %s",
  313. self._entity._device.name,
  314. self.id,
  315. value,
  316. result,
  317. )
  318. return result
  319. def _find_map_for_value(self, value):
  320. default = None
  321. for m in self._config.get("mapping", {}):
  322. if "dps_val" not in m:
  323. default = m
  324. if "value" in m and str(m["value"]) == str(value):
  325. return m
  326. for c in m.get("conditions", {}):
  327. if "value" in c and c["value"] == value:
  328. return m
  329. return default
  330. def _active_condition(self, mapping, device):
  331. constraint = mapping.get("constraint")
  332. conditions = mapping.get("conditions")
  333. if constraint is not None and conditions is not None:
  334. c_dps = self._entity.find_dps(constraint)
  335. c_val = None if c_dps is None else device.get_property(c_dps.id)
  336. if c_val is not None:
  337. for cond in conditions:
  338. if c_val == cond.get("dps_val"):
  339. return cond
  340. return None
  341. def get_values_to_set(self, device, value):
  342. """Return the dps values that would be set when setting to value"""
  343. result = value
  344. dps_map = {}
  345. mapping = self._find_map_for_value(value)
  346. if mapping is not None:
  347. replaced = False
  348. scale = mapping.get("scale", 1)
  349. redirect = mapping.get("value-redirect")
  350. if not isinstance(scale, (int, float)):
  351. scale = 1
  352. step = mapping.get("step")
  353. if not isinstance(step, (int, float)):
  354. step = None
  355. if "dps_val" in mapping:
  356. result = mapping["dps_val"]
  357. replaced = True
  358. # Conditions may have side effect of setting another value.
  359. cond = self._active_condition(mapping, device)
  360. if cond is not None:
  361. if cond.get("value") == value:
  362. c_dps = self._entity.find_dps(mapping["constraint"])
  363. dps_map.update(c_dps.get_values_to_set(device, cond["dps_val"]))
  364. scale = cond.get("scale", scale)
  365. step = cond.get("step", step)
  366. redirect = cond.get("value-redirect", redirect)
  367. if redirect is not None:
  368. _LOGGER.debug(f"Redirecting {self.name} to {redirect}")
  369. r_dps = self._entity.find_dps(redirect)
  370. return r_dps.get_values_to_set(device, value)
  371. if scale != 1 and isinstance(result, (int, float)):
  372. _LOGGER.debug(f"Scaling {result} by {scale}")
  373. result = result * scale
  374. replaced = True
  375. if step is not None and isinstance(result, (int, float)):
  376. _LOGGER.debug(f"Stepping {result} to {step}")
  377. result = step * round(float(result) / step)
  378. replaced = True
  379. if replaced:
  380. _LOGGER.debug(
  381. "%s: Mapped dps %s to %s from %s",
  382. self._entity._device.name,
  383. self.id,
  384. result,
  385. value,
  386. )
  387. r = self.range(device)
  388. if r is not None:
  389. minimum = r["min"]
  390. maximum = r["max"]
  391. if result < minimum or result > maximum:
  392. raise ValueError(
  393. f"{self.name} ({value}) must be between {minimum} and {maximum}"
  394. )
  395. if self.type is int:
  396. _LOGGER.debug(f"Rounding {self.name}")
  397. result = int(round(result))
  398. elif self.type is bool:
  399. result = True if result else False
  400. elif self.type is float:
  401. result = float(result)
  402. elif self.type is str:
  403. result = str(result)
  404. if self.stringify:
  405. result = str(result)
  406. dps_map[self.id] = result
  407. return dps_map
  408. def icon_rule(self, device):
  409. mapping = self._find_map_for_dps(device.get_property(self.id))
  410. icon = None
  411. priority = 100
  412. if mapping:
  413. icon = mapping.get("icon", icon)
  414. priority = mapping.get("icon_priority", 10 if icon else 100)
  415. cond = self._active_condition(mapping, device)
  416. if cond and cond.get("icon_priority", 10) < priority:
  417. icon = cond.get("icon", icon)
  418. priority = cond.get("icon_priority", 10 if icon else 100)
  419. return {"priority": priority, "icon": icon}
  420. def available_configs():
  421. """List the available config files."""
  422. _CONFIG_DIR = dirname(config_dir.__file__)
  423. for (path, dirs, files) in walk(_CONFIG_DIR):
  424. for basename in sorted(files):
  425. if fnmatch(basename, "*.yaml"):
  426. yield basename
  427. def possible_matches(dps):
  428. """Return possible matching configs for a given set of dps values."""
  429. for cfg in available_configs():
  430. parsed = TuyaDeviceConfig(cfg)
  431. if parsed.matches(dps):
  432. yield parsed
  433. def config_for_legacy_use(conf_type):
  434. """
  435. Return a config to use with config_type for legacy transition.
  436. Note: as there are two variants for Kogan Socket, this is not guaranteed
  437. to be the correct config for the device, so only use it for looking up
  438. the legacy class during the transition period.
  439. """
  440. for cfg in available_configs():
  441. parsed = TuyaDeviceConfig(cfg)
  442. if parsed.legacy_type == conf_type:
  443. return parsed
  444. return None