device_config.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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"], primary=True)
  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, primary=False):
  117. self._device = device
  118. self._config = config
  119. self._is_primary = primary
  120. def name(self, base_name):
  121. """The friendly name for this entity."""
  122. own_name = self._config.get("name")
  123. if own_name is None:
  124. return base_name
  125. else:
  126. return base_name + " " + own_name
  127. def unique_id(self, device_uid):
  128. """Return a suitable unique_id for this entity."""
  129. own_name = self._config.get("name")
  130. if own_name:
  131. return f"{device_uid}-{slugify(own_name)}"
  132. else:
  133. return device_uid
  134. @property
  135. def legacy_class(self):
  136. """Return the legacy device corresponding to this config."""
  137. name = self._config.get("legacy_class")
  138. if name is None:
  139. return None
  140. return locate("custom_components.tuya_local" + name)
  141. @property
  142. def entity_category(self):
  143. if self._is_primary:
  144. return None
  145. elif self.entity in ["binary_sensor", "sensor"]:
  146. return "diagnostic"
  147. else:
  148. return "config"
  149. @property
  150. def deprecated(self):
  151. """Return whether this entitiy is deprecated."""
  152. return "deprecated" in self._config.keys()
  153. @property
  154. def deprecation_message(self):
  155. """Return a deprecation message for this entity"""
  156. replacement = self._config.get(
  157. "deprecated", "nothing, this warning has been raised in error"
  158. )
  159. return (
  160. f"The use of {self.entity} for {self._device.name} is "
  161. f"deprecated and should be replaced by {replacement}."
  162. )
  163. @property
  164. def entity(self):
  165. """The entity type of this entity."""
  166. return self._config["entity"]
  167. @property
  168. def config_id(self):
  169. """The identifier for this entitiy in the config."""
  170. own_name = self._config.get("name")
  171. if own_name:
  172. return f"{self.entity}_{slugify(own_name)}"
  173. return self.entity
  174. @property
  175. def device_class(self):
  176. """The device class of this entity."""
  177. return self._config.get("class")
  178. def icon(self, device):
  179. """Return the icon for this device, with state as given."""
  180. icon = self._config.get("icon", None)
  181. priority = self._config.get("icon_priority", 100)
  182. for d in self.dps():
  183. rule = d.icon_rule(device)
  184. if rule and rule["priority"] < priority:
  185. icon = rule["icon"]
  186. priority = rule["priority"]
  187. return icon
  188. @property
  189. def mode(self):
  190. """Return the mode (used by Number entities)."""
  191. return self._config.get("mode")
  192. def dps(self):
  193. """Iterate through the list of dps for this entity."""
  194. for d in self._config["dps"]:
  195. yield TuyaDpsConfig(self, d)
  196. def find_dps(self, name):
  197. """Find a dps with the specified name."""
  198. for d in self.dps():
  199. if d.name == name:
  200. return d
  201. return None
  202. class TuyaDpsConfig:
  203. """Representation of a dps config."""
  204. def __init__(self, entity, config):
  205. self._entity = entity
  206. self._config = config
  207. self.stringify = False
  208. @property
  209. def id(self):
  210. return str(self._config["id"])
  211. @property
  212. def type(self):
  213. t = self._config["type"]
  214. types = {
  215. "boolean": bool,
  216. "integer": int,
  217. "string": str,
  218. "float": float,
  219. "bitfield": int,
  220. }
  221. return types.get(t)
  222. @property
  223. def name(self):
  224. return self._config["name"]
  225. def get_value(self, device):
  226. """Return the value of the dps from the given device."""
  227. return self._map_from_dps(device.get_property(self.id), device)
  228. async def async_set_value(self, device, value):
  229. """Set the value of the dps in the given device to given value."""
  230. if self.readonly:
  231. raise TypeError(f"{self.name} is read only")
  232. if self.invalid_for(value, device):
  233. raise AttributeError(f"{self.name} cannot be set at this time")
  234. settings = self.get_values_to_set(device, value)
  235. await device.async_set_properties(settings)
  236. def values(self, device):
  237. """Return the possible values a dps can take."""
  238. if "mapping" not in self._config.keys():
  239. _LOGGER.debug(
  240. f"No mapping for {self.name}, unable to determine valid values"
  241. )
  242. return None
  243. val = []
  244. for m in self._config["mapping"]:
  245. if "value" in m:
  246. val.append(m["value"])
  247. for c in m.get("conditions", {}):
  248. if "value" in c:
  249. val.append(c["value"])
  250. cond = self._active_condition(m, device)
  251. if cond and "mapping" in cond:
  252. _LOGGER.debug("Considering conditional mappings")
  253. c_val = []
  254. for m2 in cond["mapping"]:
  255. if "value" in m2:
  256. c_val.append(m2["value"])
  257. # if given, the conditional mapping is an override
  258. if c_val:
  259. _LOGGER.debug(f"Overriding {self.name} values {val} with {c_val}")
  260. val = c_val
  261. break
  262. _LOGGER.debug(f"{self.name} values: {val}")
  263. return list(set(val)) if val else None
  264. def range(self, device, scaled=True):
  265. """Return the range for this dps if configured."""
  266. mapping = self._find_map_for_dps(device.get_property(self.id))
  267. scale = 1
  268. if mapping:
  269. _LOGGER.debug(f"Considering mapping for range of {self.name}")
  270. if scaled:
  271. scale = mapping.get("scale", scale)
  272. cond = self._active_condition(mapping, device)
  273. if cond:
  274. constraint = mapping.get("constraint")
  275. if scaled:
  276. scale = mapping.get("scale", scale)
  277. _LOGGER.debug(f"Considering condition on {constraint}")
  278. r = None if cond is None else cond.get("range")
  279. if r and "min" in r and "max" in r:
  280. _LOGGER.info(f"Conditional range returned for {self.name}")
  281. return _scale_range(r, scale)
  282. r = mapping.get("range")
  283. if r and "min" in r and "max" in r:
  284. _LOGGER.info(f"Mapped range returned for {self.name}")
  285. return _scale_range(r, scale)
  286. r = self._config.get("range")
  287. if r and "min" in r and "max" in r:
  288. return _scale_range(r, scale)
  289. else:
  290. return None
  291. def step(self, device, scaled=True):
  292. step = 1
  293. scale = 1
  294. mapping = self._find_map_for_dps(device.get_property(self.id))
  295. if mapping:
  296. _LOGGER.debug(f"Considering mapping for step of {self.name}")
  297. step = mapping.get("step", 1)
  298. scale = mapping.get("scale", 1)
  299. cond = self._active_condition(mapping, device)
  300. if cond:
  301. constraint = mapping.get("constraint")
  302. _LOGGER.debug(f"Considering condition on {constraint}")
  303. step = cond.get("step", step)
  304. scale = cond.get("scale", scale)
  305. if step != 1 or scale != 1:
  306. _LOGGER.info(f"Step for {self.name} is {step} with scale {scale}")
  307. return step / scale if scaled else step
  308. @property
  309. def readonly(self):
  310. return self._config.get("readonly", False)
  311. def invalid_for(self, value, device):
  312. mapping = self._find_map_for_value(value)
  313. if mapping:
  314. cond = self._active_condition(mapping, device)
  315. if cond:
  316. return cond.get("invalid", False)
  317. return False
  318. @property
  319. def hidden(self):
  320. return self._config.get("hidden", False)
  321. @property
  322. def unit(self):
  323. return self._config.get("unit")
  324. @property
  325. def state_class(self):
  326. """The state class of this measurement."""
  327. return self._config.get("class")
  328. def _find_map_for_dps(self, value):
  329. default = None
  330. for m in self._config.get("mapping", {}):
  331. if "dps_val" not in m:
  332. default = m
  333. elif str(m["dps_val"]) == str(value):
  334. return m
  335. return default
  336. def _map_from_dps(self, value, device):
  337. if value is not None and self.type is not str and isinstance(value, str):
  338. try:
  339. value = self.type(value)
  340. self.stringify = True
  341. except ValueError:
  342. self.stringify = False
  343. else:
  344. self.stringify = False
  345. result = value
  346. mapping = self._find_map_for_dps(value)
  347. if mapping:
  348. scale = mapping.get("scale", 1)
  349. if not isinstance(scale, (int, float)):
  350. scale = 1
  351. redirect = mapping.get("value_redirect")
  352. replaced = "value" in mapping
  353. result = mapping.get("value", result)
  354. cond = self._active_condition(mapping, device)
  355. if cond:
  356. if cond.get("invalid", False):
  357. return None
  358. replaced = replaced or "value" in cond
  359. result = cond.get("value", result)
  360. scale = cond.get("scale", scale)
  361. redirect = cond.get("value_redirect", redirect)
  362. for m in cond.get("mapping", {}):
  363. if str(m.get("dps_val")) == str(result):
  364. replaced = "value" in m
  365. result = m.get("value", result)
  366. if redirect:
  367. _LOGGER.debug(f"Redirecting {self.name} to {redirect}")
  368. r_dps = self._entity.find_dps(redirect)
  369. return r_dps.get_value(device)
  370. if scale != 1 and isinstance(result, (int, float)):
  371. result = result / scale
  372. replaced = True
  373. if replaced:
  374. _LOGGER.debug(
  375. "%s: Mapped dps %s value from %s to %s",
  376. self._entity._device.name,
  377. self.id,
  378. value,
  379. result,
  380. )
  381. return result
  382. def _find_map_for_value(self, value):
  383. default = None
  384. for m in self._config.get("mapping", {}):
  385. if "dps_val" not in m:
  386. default = m
  387. if "value" in m and str(m["value"]) == str(value):
  388. return m
  389. for c in m.get("conditions", {}):
  390. if "value" in c and c["value"] == value:
  391. return m
  392. return default
  393. def _active_condition(self, mapping, device, value=None):
  394. constraint = mapping.get("constraint")
  395. conditions = mapping.get("conditions")
  396. c_match = None
  397. if constraint and conditions:
  398. c_dps = self._entity.find_dps(constraint)
  399. c_val = None if c_dps is None else device.get_property(c_dps.id)
  400. for cond in conditions:
  401. if c_val is not None and c_val == cond.get("dps_val"):
  402. c_match = cond
  403. # when changing, another condition may become active
  404. # return that if it exists over a current condition
  405. if value is not None and value == cond.get("value"):
  406. return cond
  407. return c_match
  408. def get_values_to_set(self, device, value):
  409. """Return the dps values that would be set when setting to value"""
  410. result = value
  411. dps_map = {}
  412. mapping = self._find_map_for_value(value)
  413. if mapping:
  414. replaced = False
  415. scale = mapping.get("scale", 1)
  416. redirect = mapping.get("value_redirect")
  417. if not isinstance(scale, (int, float)):
  418. scale = 1
  419. step = mapping.get("step")
  420. if not isinstance(step, (int, float)):
  421. step = None
  422. if "dps_val" in mapping:
  423. result = mapping["dps_val"]
  424. replaced = True
  425. # Conditions may have side effect of setting another value.
  426. cond = self._active_condition(mapping, device, value)
  427. if cond:
  428. if cond.get("value") == value:
  429. c_dps = self._entity.find_dps(mapping["constraint"])
  430. c_val = c_dps._map_from_dps(
  431. cond.get("dps_val", device.get_property(c_dps.id)),
  432. device,
  433. )
  434. dps_map.update(c_dps.get_values_to_set(device, c_val))
  435. # Allow simple conditional mapping overrides
  436. for m in cond.get("mapping", {}):
  437. if m.get("value") == value:
  438. result = m.get("dps_val", result)
  439. scale = cond.get("scale", scale)
  440. step = cond.get("step", step)
  441. redirect = cond.get("value_redirect", redirect)
  442. if redirect:
  443. _LOGGER.debug(f"Redirecting {self.name} to {redirect}")
  444. r_dps = self._entity.find_dps(redirect)
  445. return r_dps.get_values_to_set(device, value)
  446. if scale != 1 and isinstance(result, (int, float)):
  447. _LOGGER.debug(f"Scaling {result} by {scale}")
  448. result = result * scale
  449. remap = self._find_map_for_value(result)
  450. if remap and "dps_val" in remap and "dps_val" not in mapping:
  451. result = remap["dps_val"]
  452. replaced = True
  453. if step and isinstance(result, (int, float)):
  454. _LOGGER.debug(f"Stepping {result} to {step}")
  455. result = step * round(float(result) / step)
  456. remap = self._find_map_for_value(result)
  457. if remap and "dps_val" in remap and "dps_val" not in mapping:
  458. result = remap["dps_val"]
  459. replaced = True
  460. if replaced:
  461. _LOGGER.debug(
  462. "%s: Mapped dps %s to %s from %s",
  463. self._entity._device.name,
  464. self.id,
  465. result,
  466. value,
  467. )
  468. r = self.range(device, scaled=False)
  469. if r:
  470. minimum = r["min"]
  471. maximum = r["max"]
  472. if result < minimum or result > maximum:
  473. # Output scaled values in the error message
  474. r = self.range(device, scaled=True)
  475. minimum = r["min"]
  476. maximum = r["max"]
  477. raise ValueError(
  478. f"{self.name} ({value}) must be between {minimum} and {maximum}"
  479. )
  480. if self.type is int:
  481. _LOGGER.debug(f"Rounding {self.name}")
  482. result = int(round(result))
  483. elif self.type is bool:
  484. result = True if result else False
  485. elif self.type is float:
  486. result = float(result)
  487. elif self.type is str:
  488. result = str(result)
  489. if self.stringify:
  490. result = str(result)
  491. dps_map[self.id] = result
  492. return dps_map
  493. def icon_rule(self, device):
  494. mapping = self._find_map_for_dps(device.get_property(self.id))
  495. icon = None
  496. priority = 100
  497. if mapping:
  498. icon = mapping.get("icon", icon)
  499. priority = mapping.get("icon_priority", 10 if icon else 100)
  500. cond = self._active_condition(mapping, device)
  501. if cond and cond.get("icon_priority", 10) < priority:
  502. icon = cond.get("icon", icon)
  503. priority = cond.get("icon_priority", 10 if icon else 100)
  504. return {"priority": priority, "icon": icon}
  505. def available_configs():
  506. """List the available config files."""
  507. _CONFIG_DIR = dirname(config_dir.__file__)
  508. for (path, dirs, files) in walk(_CONFIG_DIR):
  509. for basename in sorted(files):
  510. if fnmatch(basename, "*.yaml"):
  511. yield basename
  512. def possible_matches(dps):
  513. """Return possible matching configs for a given set of dps values."""
  514. for cfg in available_configs():
  515. parsed = TuyaDeviceConfig(cfg)
  516. if parsed.matches(dps):
  517. yield parsed
  518. def get_config(conf_type):
  519. """
  520. Return a config to use with config_type.
  521. """
  522. _CONFIG_DIR = dirname(config_dir.__file__)
  523. fname = conf_type + ".yaml"
  524. fpath = join(_CONFIG_DIR, fname)
  525. if exists(fpath):
  526. return TuyaDeviceConfig(fname)
  527. else:
  528. return config_for_legacy_use(conf_type)
  529. def config_for_legacy_use(conf_type):
  530. """
  531. Return a config to use with config_type for legacy transition.
  532. Note: as there are two variants for Kogan Socket, this is not guaranteed
  533. to be the correct config for the device, so only use it for looking up
  534. the legacy class during the transition period.
  535. """
  536. for cfg in available_configs():
  537. parsed = TuyaDeviceConfig(cfg)
  538. if parsed.legacy_type == conf_type:
  539. return parsed
  540. return None