device_config.py 21 KB

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