device_config.py 21 KB

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