device_config.py 20 KB

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