device_config.py 20 KB

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