device_config.py 24 KB

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