device_config.py 22 KB

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