device_config.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. """
  2. Config parser for Tuya Local devices.
  3. """
  4. from base64 import b64decode, b64encode
  5. from fnmatch import fnmatch
  6. import logging
  7. from os import walk
  8. from os.path import join, dirname, splitext, exists
  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. # Allow integers to pass as floats.
  18. if type is float and isinstance(value, int):
  19. return True
  20. if isinstance(value, type):
  21. return True
  22. # Allow values embedded in strings if they can be converted
  23. # But not for bool, as everything can be converted to bool
  24. elif isinstance(value, str) and type is not bool:
  25. try:
  26. type(value)
  27. return True
  28. except ValueError:
  29. return False
  30. return False
  31. def _scale_range(r, s):
  32. "Scale range r by factor s"
  33. if s == 1:
  34. return r
  35. return {"min": r["min"] / s, "max": r["max"] / s}
  36. _unsigned_fmts = {
  37. 1: "B",
  38. 2: "H",
  39. 3: "3s",
  40. 4: "I",
  41. }
  42. _signed_fmts = {
  43. 1: "b",
  44. 2: "h",
  45. 3: "3s",
  46. 4: "i",
  47. }
  48. def _bytes_to_fmt(bytes, signed=False):
  49. "Convert a byte count to an unpack format."
  50. fmt = _signed_fmts if signed else _unsigned_fmts
  51. if bytes in fmt:
  52. return fmt[bytes]
  53. else:
  54. return f"{bytes}s"
  55. class TuyaDeviceConfig:
  56. """Representation of a device config for Tuya Local devices."""
  57. def __init__(self, fname):
  58. """Initialize the device config.
  59. Args:
  60. fname (string): The filename of the yaml config to load."""
  61. _CONFIG_DIR = dirname(config_dir.__file__)
  62. self._fname = fname
  63. filename = join(_CONFIG_DIR, fname)
  64. self._config = load_yaml(filename)
  65. _LOGGER.debug("Loaded device config %s", fname)
  66. @property
  67. def name(self):
  68. """Return the friendly name for this device."""
  69. return self._config["name"]
  70. @property
  71. def config(self):
  72. """Return the config file associated with this device."""
  73. return self._fname
  74. @property
  75. def config_type(self):
  76. """Return the config type associated with this device."""
  77. return splitext(self._fname)[0]
  78. @property
  79. def legacy_type(self):
  80. """Return the legacy conf_type associated with this device."""
  81. return self._config.get("legacy_type", self.config_type)
  82. @property
  83. def primary_entity(self):
  84. """Return the primary type of entity for this device."""
  85. return TuyaEntityConfig(self, self._config["primary_entity"], primary=True)
  86. def secondary_entities(self):
  87. """Iterate through entites for any secondary entites supported."""
  88. for conf in self._config.get("secondary_entities", {}):
  89. yield TuyaEntityConfig(self, conf)
  90. def matches(self, dps):
  91. """Determine if this device matches the provided dps map."""
  92. for d in self.primary_entity.dps():
  93. if (d.id not in dps.keys() and not d.optional) or (
  94. d.id in dps.keys() and not _typematch(d.type, dps[d.id])
  95. ):
  96. return False
  97. for dev in self.secondary_entities():
  98. for d in dev.dps():
  99. if (d.id not in dps.keys() and not d.optional) or (
  100. d.id in dps.keys() and not _typematch(d.type, dps[d.id])
  101. ):
  102. return False
  103. _LOGGER.debug("Matched config for %s", self.name)
  104. return True
  105. def _entity_match_analyse(self, entity, keys, matched, dps):
  106. """
  107. Determine whether this entity can be a match for the dps
  108. Args:
  109. entity - the TuyaEntityConfig to check against
  110. keys - the unmatched keys for the device
  111. matched - the matched keys for the device
  112. dps - the dps values to be matched
  113. Side Effects:
  114. Moves items from keys to matched if they match dps
  115. Return Value:
  116. True if all dps in entity could be matched to dps, False otherwise
  117. """
  118. for d in entity.dps():
  119. if (d.id not in keys and d.id not in matched and not d.optional) or (
  120. (d.id in keys or d.id in matched) and not _typematch(d.type, dps[d.id])
  121. ):
  122. return False
  123. if d.id in keys:
  124. matched.append(d.id)
  125. keys.remove(d.id)
  126. return True
  127. def match_quality(self, dps):
  128. """Determine the match quality for the provided dps map."""
  129. keys = list(dps.keys())
  130. matched = []
  131. if "updated_at" in keys:
  132. keys.remove("updated_at")
  133. total = len(keys)
  134. if not self._entity_match_analyse(self.primary_entity, keys, matched, dps):
  135. return 0
  136. for e in self.secondary_entities():
  137. if not self._entity_match_analyse(e, keys, matched, dps):
  138. return 0
  139. return round((total - len(keys)) * 100 / total)
  140. class TuyaEntityConfig:
  141. """Representation of an entity config for a supported entity."""
  142. def __init__(self, device, config, primary=False):
  143. self._device = device
  144. self._config = config
  145. self._is_primary = primary
  146. @property
  147. def name(self):
  148. """The friendly name for this entity."""
  149. return self._config.get("name")
  150. def unique_id(self, device_uid):
  151. """Return a suitable unique_id for this entity."""
  152. own_name = self.name
  153. if own_name:
  154. return f"{device_uid}-{slugify(own_name)}"
  155. else:
  156. return device_uid
  157. @property
  158. def entity_category(self):
  159. return self._config.get("category")
  160. @property
  161. def deprecated(self):
  162. """Return whether this entitiy is deprecated."""
  163. return "deprecated" in self._config.keys()
  164. @property
  165. def deprecation_message(self):
  166. """Return a deprecation message for this entity"""
  167. replacement = self._config.get(
  168. "deprecated", "nothing, this warning has been raised in error"
  169. )
  170. return (
  171. f"The use of {self.entity} for {self._device.name} is "
  172. f"deprecated and should be replaced by {replacement}."
  173. )
  174. @property
  175. def entity(self):
  176. """The entity type of this entity."""
  177. return self._config["entity"]
  178. @property
  179. def config_id(self):
  180. """The identifier for this entity in the config."""
  181. own_name = self.name
  182. if own_name:
  183. return f"{self.entity}_{slugify(own_name)}"
  184. return self.entity
  185. @property
  186. def device_class(self):
  187. """The device class of this entity."""
  188. return self._config.get("class")
  189. def icon(self, device):
  190. """Return the icon for this device, with state as given."""
  191. icon = self._config.get("icon", None)
  192. priority = self._config.get("icon_priority", 100)
  193. for d in self.dps():
  194. rule = d.icon_rule(device)
  195. if rule and rule["priority"] < priority:
  196. icon = rule["icon"]
  197. priority = rule["priority"]
  198. return icon
  199. @property
  200. def mode(self):
  201. """Return the mode (used by Number entities)."""
  202. return self._config.get("mode")
  203. def dps(self):
  204. """Iterate through the list of dps for this entity."""
  205. for d in self._config["dps"]:
  206. yield TuyaDpsConfig(self, d)
  207. def find_dps(self, name):
  208. """Find a dps with the specified name."""
  209. for d in self.dps():
  210. if d.name == name:
  211. return d
  212. return None
  213. class TuyaDpsConfig:
  214. """Representation of a dps config."""
  215. def __init__(self, entity, config):
  216. self._entity = entity
  217. self._config = config
  218. self.stringify = False
  219. @property
  220. def id(self):
  221. return str(self._config["id"])
  222. @property
  223. def type(self):
  224. t = self._config["type"]
  225. types = {
  226. "boolean": bool,
  227. "integer": int,
  228. "string": str,
  229. "float": float,
  230. "bitfield": int,
  231. "json": str,
  232. "base64": str,
  233. "hex": str,
  234. }
  235. return types.get(t)
  236. @property
  237. def rawtype(self):
  238. return self._config["type"]
  239. @property
  240. def name(self):
  241. return self._config["name"]
  242. @property
  243. def optional(self):
  244. return self._config.get("optional", False)
  245. @property
  246. def force(self):
  247. return self._config.get("force", False)
  248. @property
  249. def format(self):
  250. fmt = self._config.get("format")
  251. if fmt:
  252. unpack_fmt = ">"
  253. ranges = []
  254. names = []
  255. for f in fmt:
  256. name = f.get("name")
  257. b = f.get("bytes", 1)
  258. r = f.get("range")
  259. if r:
  260. mn = r.get("min")
  261. mx = r.get("max")
  262. else:
  263. mn = 0
  264. mx = 256**b - 1
  265. unpack_fmt = unpack_fmt + _bytes_to_fmt(b, mn < 0)
  266. ranges.append({"min": mn, "max": mx})
  267. names.append(name)
  268. _LOGGER.debug(f"format of {unpack_fmt} found")
  269. return {"format": unpack_fmt, "ranges": ranges, "names": names}
  270. return None
  271. def get_value(self, device):
  272. """Return the value of the dps from the given device."""
  273. return self._map_from_dps(device.get_property(self.id), device)
  274. def decoded_value(self, device):
  275. v = self.get_value(device)
  276. if self.rawtype == "hex" and isinstance(v, str):
  277. try:
  278. return bytes.fromhex(v)
  279. except ValueError:
  280. _LOGGER.warning(
  281. f"{device.name} sent invalid hex '{v}' for {self.name}",
  282. )
  283. return None
  284. elif self.rawtype == "base64":
  285. try:
  286. return b64decode(v)
  287. except ValueError:
  288. _LOGGER.warning(
  289. f"{device.name} sent invalid base64 '{v}' for {self.name}",
  290. )
  291. return None
  292. else:
  293. return v
  294. def encode_value(self, v):
  295. if self.rawtype == "hex":
  296. return v.hex()
  297. elif self.rawtype == "base64":
  298. return b64encode(v).decode("utf-8")
  299. else:
  300. return v
  301. def _match(self, matchdata, value):
  302. """Return true val1 matches val2"""
  303. if self.rawtype == "bitfield" and matchdata:
  304. try:
  305. return (int(value) & int(matchdata)) != 0
  306. except (TypeError, ValueError):
  307. return False
  308. else:
  309. return str(value) == str(matchdata)
  310. async def async_set_value(self, device, value):
  311. """Set the value of the dps in the given device to given value."""
  312. if self.readonly:
  313. raise TypeError(f"{self.name} is read only")
  314. if self.invalid_for(value, device):
  315. raise AttributeError(f"{self.name} cannot be set at this time")
  316. settings = self.get_values_to_set(device, value)
  317. await device.async_set_properties(settings)
  318. def values(self, device):
  319. """Return the possible values a dps can take."""
  320. if "mapping" not in self._config.keys():
  321. _LOGGER.debug(
  322. f"No mapping for {self.name}, unable to determine valid values"
  323. )
  324. return None
  325. val = []
  326. for m in self._config["mapping"]:
  327. if "value" in m:
  328. val.append(m["value"])
  329. # If there is mirroring with no value override, include mirrored values
  330. elif "value_mirror" in m:
  331. r_dps = self._entity.find_dps(m["value_mirror"])
  332. val = val + r_dps.values(device)
  333. for c in m.get("conditions", {}):
  334. if "value" in c:
  335. val.append(c["value"])
  336. elif "value_mirror" in c:
  337. r_dps = self._entity.find_dps(c["value_mirror"])
  338. val = val + r_dps.values(device)
  339. cond = self._active_condition(m, device)
  340. if cond and "mapping" in cond:
  341. _LOGGER.debug("Considering conditional mappings")
  342. c_val = []
  343. for m2 in cond["mapping"]:
  344. if "value" in m2:
  345. c_val.append(m2["value"])
  346. elif "value_mirror" in m:
  347. r_dps = self._entity.find_dps(m["value_mirror"])
  348. c_val = c_val + r_dps.values(device)
  349. # if given, the conditional mapping is an override
  350. if c_val:
  351. _LOGGER.debug(f"Overriding {self.name} values {val} with {c_val}")
  352. val = c_val
  353. break
  354. _LOGGER.debug(f"{self.name} values: {val}")
  355. return list(set(val)) if val else None
  356. def default(self):
  357. """Return the default value for a dp."""
  358. if "mapping" not in self._config.keys():
  359. _LOGGER.debug(
  360. f"No mapping for {self.name}, unable to determine default value"
  361. )
  362. return None
  363. for m in self._config["mapping"]:
  364. if m.get("default", False):
  365. return m.get("dps_val", None)
  366. def range(self, device, scaled=True):
  367. """Return the range for this dps if configured."""
  368. scale = self.scale(device) if scaled else 1
  369. mapping = self._find_map_for_dps(device.get_property(self.id))
  370. r = self._config.get("range")
  371. if mapping:
  372. _LOGGER.debug(f"Considering mapping for range of {self.name}")
  373. cond = self._active_condition(mapping, device)
  374. if cond:
  375. r = cond.get("range", r)
  376. if r and "min" in r and "max" in r:
  377. return _scale_range(r, scale)
  378. else:
  379. return None
  380. def scale(self, device):
  381. scale = 1
  382. mapping = self._find_map_for_dps(device.get_property(self.id))
  383. if mapping:
  384. scale = mapping.get("scale", 1)
  385. cond = self._active_condition(mapping, device)
  386. if cond:
  387. scale = cond.get("scale", scale)
  388. return scale
  389. def precision(self, device):
  390. if self.type is int:
  391. scale = self.scale(device)
  392. precision = 0
  393. while scale > 1.0:
  394. scale /= 10.0
  395. precision += 1
  396. return precision
  397. def step(self, device, scaled=True):
  398. step = 1
  399. scale = self.scale(device) if scaled else 1
  400. mapping = self._find_map_for_dps(device.get_property(self.id))
  401. if mapping:
  402. _LOGGER.debug(f"Considering mapping for step of {self.name}")
  403. step = mapping.get("step", 1)
  404. cond = self._active_condition(mapping, device)
  405. if cond:
  406. constraint = mapping.get("constraint")
  407. _LOGGER.debug(f"Considering condition on {constraint}")
  408. step = cond.get("step", step)
  409. if step != 1 or scale != 1:
  410. _LOGGER.debug(f"Step for {self.name} is {step} with scale {scale}")
  411. return step / scale if scaled else step
  412. @property
  413. def readonly(self):
  414. return self._config.get("readonly", False)
  415. def invalid_for(self, value, device):
  416. mapping = self._find_map_for_value(value, device)
  417. if mapping:
  418. cond = self._active_condition(mapping, device)
  419. if cond:
  420. return cond.get("invalid", False)
  421. return False
  422. @property
  423. def hidden(self):
  424. return self._config.get("hidden", False)
  425. @property
  426. def unit(self):
  427. return self._config.get("unit")
  428. @property
  429. def state_class(self):
  430. """The state class of this measurement."""
  431. return self._config.get("class")
  432. def _find_map_for_dps(self, value):
  433. default = None
  434. for m in self._config.get("mapping", {}):
  435. if "dps_val" not in m:
  436. default = m
  437. elif self._match(m["dps_val"], value):
  438. return m
  439. return default
  440. def _correct_type(self, result):
  441. """Convert value to the correct type for this dp."""
  442. if self.type is int:
  443. _LOGGER.debug(f"Rounding {self.name}")
  444. result = int(round(result))
  445. elif self.type is bool:
  446. result = True if result else False
  447. elif self.type is float:
  448. result = float(result)
  449. elif self.type is str:
  450. result = str(result)
  451. if self.stringify:
  452. result = str(result)
  453. return result
  454. def _map_from_dps(self, value, device):
  455. if value is not None and self.type is not str and isinstance(value, str):
  456. try:
  457. value = self.type(value)
  458. self.stringify = True
  459. except ValueError:
  460. self.stringify = False
  461. else:
  462. self.stringify = False
  463. result = value
  464. scale = self.scale(device)
  465. mapping = self._find_map_for_dps(value)
  466. if mapping:
  467. invert = mapping.get("invert", False)
  468. redirect = mapping.get("value_redirect")
  469. mirror = mapping.get("value_mirror")
  470. replaced = "value" in mapping
  471. result = mapping.get("value", result)
  472. cond = self._active_condition(mapping, device)
  473. if cond:
  474. if cond.get("invalid", False):
  475. return None
  476. replaced = replaced or "value" in cond
  477. result = cond.get("value", result)
  478. redirect = cond.get("value_redirect", redirect)
  479. mirror = cond.get("value_mirror", mirror)
  480. for m in cond.get("mapping", {}):
  481. if str(m.get("dps_val")) == str(result):
  482. replaced = "value" in m
  483. result = m.get("value", result)
  484. if redirect:
  485. _LOGGER.debug(f"Redirecting {self.name} to {redirect}")
  486. r_dps = self._entity.find_dps(redirect)
  487. return r_dps.get_value(device)
  488. if mirror:
  489. r_dps = self._entity.find_dps(mirror)
  490. return r_dps.get_value(device)
  491. if invert and isinstance(result, (int, float)):
  492. r = self._config.get("range")
  493. if r and "min" in r and "max" in r:
  494. result = -1 * result + r["min"] + r["max"]
  495. replaced = True
  496. if scale != 1 and isinstance(result, (int, float)):
  497. result = result / scale
  498. replaced = True
  499. if replaced:
  500. _LOGGER.debug(
  501. "%s: Mapped dps %s value from %s to %s",
  502. self._entity._device.name,
  503. self.id,
  504. value,
  505. result,
  506. )
  507. return result
  508. def _find_map_for_value(self, value, device):
  509. default = None
  510. for m in self._config.get("mapping", {}):
  511. if "dps_val" not in m:
  512. default = m
  513. if "value" in m and str(m["value"]) == str(value):
  514. return m
  515. if "value" not in m and "value_mirror" in m:
  516. r_dps = self._entity.find_dps(m["value_mirror"])
  517. if str(r_dps.get_value(device)) == str(value):
  518. return m
  519. for c in m.get("conditions", {}):
  520. if "value" in c and str(c["value"]) == str(value):
  521. c_dp = self._entity.find_dps(m.get("constraint"))
  522. # only consider the condition a match if we can change
  523. # the dp to match, or it already matches
  524. if not c_dp.readonly or device.get_property(c_dp.id) == c.get(
  525. "dps_val"
  526. ):
  527. return m
  528. if "value" not in c and "value_mirror" in c:
  529. r_dps = self._entity.find_dps(c["value_mirror"])
  530. if str(r_dps.get_value(device)) == str(value):
  531. return m
  532. return default
  533. def _active_condition(self, mapping, device, value=None):
  534. constraint = mapping.get("constraint")
  535. conditions = mapping.get("conditions")
  536. c_match = None
  537. if constraint and conditions:
  538. c_dps = self._entity.find_dps(constraint)
  539. c_val = None if c_dps is None else device.get_property(c_dps.id)
  540. for cond in conditions:
  541. if c_val is not None and c_val == cond.get("dps_val"):
  542. c_match = cond
  543. # Case where matching None, need extra checks to ensure we
  544. # are not just defaulting and it is really a match
  545. elif (
  546. c_val is None
  547. and c_dps is not None
  548. and "dps_val" in cond
  549. and cond.get("dps_val") is None
  550. ):
  551. c_match = cond
  552. # when changing, another condition may become active
  553. # return that if it exists over a current condition
  554. if value is not None and value == cond.get("value"):
  555. return cond
  556. return c_match
  557. def get_values_to_set(self, device, value):
  558. """Return the dps values that would be set when setting to value"""
  559. result = value
  560. dps_map = {}
  561. if self.readonly:
  562. return dps_map
  563. mapping = self._find_map_for_value(value, device)
  564. scale = self.scale(device)
  565. if mapping:
  566. replaced = False
  567. redirect = mapping.get("value_redirect")
  568. invert = mapping.get("invert", False)
  569. step = mapping.get("step")
  570. if not isinstance(step, (int, float)):
  571. step = None
  572. if "dps_val" in mapping:
  573. result = mapping["dps_val"]
  574. replaced = True
  575. # Conditions may have side effect of setting another value.
  576. cond = self._active_condition(mapping, device, value)
  577. if cond:
  578. cval = cond.get("value")
  579. if cval is None:
  580. r_dps = cond.get("value_mirror")
  581. if r_dps:
  582. cval = self._entity.find_dps(r_dps).get_value(device)
  583. if cval == value:
  584. c_dps = self._entity.find_dps(mapping["constraint"])
  585. c_val = c_dps._map_from_dps(
  586. cond.get("dps_val", device.get_property(c_dps.id)),
  587. device,
  588. )
  589. dps_map.update(c_dps.get_values_to_set(device, c_val))
  590. # Allow simple conditional mapping overrides
  591. for m in cond.get("mapping", {}):
  592. if m.get("value") == value:
  593. result = m.get("dps_val", result)
  594. step = cond.get("step", step)
  595. redirect = cond.get("value_redirect", redirect)
  596. if redirect:
  597. _LOGGER.debug(f"Redirecting {self.name} to {redirect}")
  598. r_dps = self._entity.find_dps(redirect)
  599. return r_dps.get_values_to_set(device, value)
  600. if scale != 1 and isinstance(result, (int, float)):
  601. _LOGGER.debug(f"Scaling {result} by {scale}")
  602. result = result * scale
  603. remap = self._find_map_for_value(result, device)
  604. if remap and "dps_val" in remap and "dps_val" not in mapping:
  605. result = remap["dps_val"]
  606. replaced = True
  607. if invert:
  608. r = self._config.get("range")
  609. if r and "min" in r and "max" in r:
  610. result = -1 * result + r["min"] + r["max"]
  611. replaced = True
  612. if step and isinstance(result, (int, float)):
  613. _LOGGER.debug(f"Stepping {result} to {step}")
  614. result = step * round(float(result) / step)
  615. remap = self._find_map_for_value(result, device)
  616. if remap and "dps_val" in remap and "dps_val" not in mapping:
  617. result = remap["dps_val"]
  618. replaced = True
  619. if replaced:
  620. _LOGGER.debug(
  621. "%s: Mapped dps %s to %s from %s",
  622. self._entity._device.name,
  623. self.id,
  624. result,
  625. value,
  626. )
  627. r = self.range(device, scaled=False)
  628. if r and isinstance(result, (int, float)):
  629. minimum = r["min"]
  630. maximum = r["max"]
  631. if result < minimum or result > maximum:
  632. # Output scaled values in the error message
  633. r = self.range(device, scaled=True)
  634. minimum = r["min"]
  635. maximum = r["max"]
  636. raise ValueError(
  637. f"{self.name} ({value}) must be between {minimum} and {maximum}"
  638. )
  639. dps_map[self.id] = self._correct_type(result)
  640. return dps_map
  641. def icon_rule(self, device):
  642. mapping = self._find_map_for_dps(device.get_property(self.id))
  643. icon = None
  644. priority = 100
  645. if mapping:
  646. icon = mapping.get("icon", icon)
  647. priority = mapping.get("icon_priority", 10 if icon else 100)
  648. cond = self._active_condition(mapping, device)
  649. if cond and cond.get("icon_priority", 10) < priority:
  650. icon = cond.get("icon", icon)
  651. priority = cond.get("icon_priority", 10 if icon else 100)
  652. return {"priority": priority, "icon": icon}
  653. def available_configs():
  654. """List the available config files."""
  655. _CONFIG_DIR = dirname(config_dir.__file__)
  656. for path, dirs, files in walk(_CONFIG_DIR):
  657. for basename in sorted(files):
  658. if fnmatch(basename, "*.yaml"):
  659. yield basename
  660. def possible_matches(dps):
  661. """Return possible matching configs for a given set of dps values."""
  662. for cfg in available_configs():
  663. parsed = TuyaDeviceConfig(cfg)
  664. if parsed.matches(dps):
  665. yield parsed
  666. def get_config(conf_type):
  667. """
  668. Return a config to use with config_type.
  669. """
  670. _CONFIG_DIR = dirname(config_dir.__file__)
  671. fname = conf_type + ".yaml"
  672. fpath = join(_CONFIG_DIR, fname)
  673. if exists(fpath):
  674. return TuyaDeviceConfig(fname)
  675. else:
  676. return config_for_legacy_use(conf_type)
  677. def config_for_legacy_use(conf_type):
  678. """
  679. Return a config to use with config_type for legacy transition.
  680. Note: as there are two variants for Kogan Socket, this is not guaranteed
  681. to be the correct config for the device, so only use it for looking up
  682. the legacy class during the transition period.
  683. """
  684. for cfg in available_configs():
  685. parsed = TuyaDeviceConfig(cfg)
  686. if parsed.legacy_type == conf_type:
  687. return parsed
  688. return None