4
0

device_config.py 19 KB

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