device_config.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. return f"{device_uid}-{slugify(self.config_id)}"
  153. @property
  154. def entity_category(self):
  155. return self._config.get("category")
  156. @property
  157. def deprecated(self):
  158. """Return whether this entitiy is deprecated."""
  159. return "deprecated" in self._config.keys()
  160. @property
  161. def deprecation_message(self):
  162. """Return a deprecation message for this entity"""
  163. replacement = self._config.get(
  164. "deprecated", "nothing, this warning has been raised in error"
  165. )
  166. return (
  167. f"The use of {self.entity} for {self._device.name} is "
  168. f"deprecated and should be replaced by {replacement}."
  169. )
  170. @property
  171. def entity(self):
  172. """The entity type of this entity."""
  173. return self._config["entity"]
  174. @property
  175. def config_id(self):
  176. """The identifier for this entity in the config."""
  177. own_name = self.name
  178. if own_name:
  179. return f"{self.entity}_{slugify(own_name)}"
  180. return self.entity
  181. @property
  182. def device_class(self):
  183. """The device class of this entity."""
  184. return self._config.get("class")
  185. def icon(self, device):
  186. """Return the icon for this device, with state as given."""
  187. icon = self._config.get("icon", None)
  188. priority = self._config.get("icon_priority", 100)
  189. for d in self.dps():
  190. rule = d.icon_rule(device)
  191. if rule and rule["priority"] < priority:
  192. icon = rule["icon"]
  193. priority = rule["priority"]
  194. return icon
  195. @property
  196. def mode(self):
  197. """Return the mode (used by Number entities)."""
  198. return self._config.get("mode")
  199. def dps(self):
  200. """Iterate through the list of dps for this entity."""
  201. for d in self._config["dps"]:
  202. yield TuyaDpsConfig(self, d)
  203. def find_dps(self, name):
  204. """Find a dps with the specified name."""
  205. for d in self.dps():
  206. if d.name == name:
  207. return d
  208. return None
  209. class TuyaDpsConfig:
  210. """Representation of a dps config."""
  211. def __init__(self, entity, config):
  212. self._entity = entity
  213. self._config = config
  214. self.stringify = False
  215. @property
  216. def id(self):
  217. return str(self._config["id"])
  218. @property
  219. def type(self):
  220. t = self._config["type"]
  221. types = {
  222. "boolean": bool,
  223. "integer": int,
  224. "string": str,
  225. "float": float,
  226. "bitfield": int,
  227. "json": str,
  228. "base64": str,
  229. "hex": str,
  230. }
  231. return types.get(t)
  232. @property
  233. def rawtype(self):
  234. return self._config["type"]
  235. @property
  236. def name(self):
  237. return self._config["name"]
  238. @property
  239. def optional(self):
  240. return self._config.get("optional", False)
  241. @property
  242. def force(self):
  243. return self._config.get("force", False)
  244. @property
  245. def format(self):
  246. fmt = self._config.get("format")
  247. if fmt:
  248. unpack_fmt = ">"
  249. ranges = []
  250. names = []
  251. for f in fmt:
  252. name = f.get("name")
  253. b = f.get("bytes", 1)
  254. r = f.get("range")
  255. if r:
  256. mn = r.get("min")
  257. mx = r.get("max")
  258. else:
  259. mn = 0
  260. mx = 256**b - 1
  261. unpack_fmt = unpack_fmt + _bytes_to_fmt(b, mn < 0)
  262. ranges.append({"min": mn, "max": mx})
  263. names.append(name)
  264. _LOGGER.debug(f"format of {unpack_fmt} found")
  265. return {"format": unpack_fmt, "ranges": ranges, "names": names}
  266. return None
  267. def get_value(self, device):
  268. """Return the value of the dps from the given device."""
  269. return self._map_from_dps(device.get_property(self.id), device)
  270. def decoded_value(self, device):
  271. v = self.get_value(device)
  272. if self.rawtype == "hex" and isinstance(v, str):
  273. try:
  274. return bytes.fromhex(v)
  275. except ValueError:
  276. _LOGGER.warning(
  277. f"{device.name} sent invalid hex '{v}' for {self.name}",
  278. )
  279. return None
  280. elif self.rawtype == "base64":
  281. try:
  282. return b64decode(v)
  283. except ValueError:
  284. _LOGGER.warning(
  285. f"{device.name} sent invalid base64 '{v}' for {self.name}",
  286. )
  287. return None
  288. else:
  289. return v
  290. def encode_value(self, v):
  291. if self.rawtype == "hex":
  292. return v.hex()
  293. elif self.rawtype == "base64":
  294. return b64encode(v).decode("utf-8")
  295. else:
  296. return v
  297. def _match(self, matchdata, value):
  298. """Return true val1 matches val2"""
  299. if self.rawtype == "bitfield" and matchdata:
  300. try:
  301. return (int(value) & int(matchdata)) != 0
  302. except (TypeError, ValueError):
  303. return False
  304. else:
  305. return str(value) == str(matchdata)
  306. async def async_set_value(self, device, value):
  307. """Set the value of the dps in the given device to given value."""
  308. if self.readonly:
  309. raise TypeError(f"{self.name} is read only")
  310. if self.invalid_for(value, device):
  311. raise AttributeError(f"{self.name} cannot be set at this time")
  312. settings = self.get_values_to_set(device, value)
  313. await device.async_set_properties(settings)
  314. def values(self, device):
  315. """Return the possible values a dps can take."""
  316. if "mapping" not in self._config.keys():
  317. _LOGGER.debug(
  318. f"No mapping for {self.name}, unable to determine valid values"
  319. )
  320. return None
  321. val = []
  322. for m in self._config["mapping"]:
  323. if "value" in m:
  324. val.append(m["value"])
  325. # If there is mirroring with no value override, include mirrored values
  326. elif "value_mirror" in m:
  327. r_dps = self._entity.find_dps(m["value_mirror"])
  328. val = val + r_dps.values(device)
  329. for c in m.get("conditions", {}):
  330. if "value" in c:
  331. val.append(c["value"])
  332. elif "value_mirror" in c:
  333. r_dps = self._entity.find_dps(c["value_mirror"])
  334. val = val + r_dps.values(device)
  335. cond = self._active_condition(m, device)
  336. if cond and "mapping" in cond:
  337. _LOGGER.debug("Considering conditional mappings")
  338. c_val = []
  339. for m2 in cond["mapping"]:
  340. if "value" in m2:
  341. c_val.append(m2["value"])
  342. elif "value_mirror" in m:
  343. r_dps = self._entity.find_dps(m["value_mirror"])
  344. c_val = c_val + r_dps.values(device)
  345. # if given, the conditional mapping is an override
  346. if c_val:
  347. _LOGGER.debug(f"Overriding {self.name} values {val} with {c_val}")
  348. val = c_val
  349. break
  350. _LOGGER.debug(f"{self.name} values: {val}")
  351. return list(set(val)) if val else None
  352. def default(self):
  353. """Return the default value for a dp."""
  354. if "mapping" not in self._config.keys():
  355. _LOGGER.debug(
  356. f"No mapping for {self.name}, unable to determine default value"
  357. )
  358. return None
  359. for m in self._config["mapping"]:
  360. if m.get("default", False):
  361. return m.get("dps_val", None)
  362. def range(self, device, scaled=True):
  363. """Return the range for this dps if configured."""
  364. scale = self.scale(device) if scaled else 1
  365. mapping = self._find_map_for_dps(device.get_property(self.id))
  366. r = self._config.get("range")
  367. if mapping:
  368. _LOGGER.debug(f"Considering mapping for range of {self.name}")
  369. cond = self._active_condition(mapping, device)
  370. if cond:
  371. r = cond.get("range", r)
  372. if r and "min" in r and "max" in r:
  373. return _scale_range(r, scale)
  374. else:
  375. return None
  376. def scale(self, device):
  377. scale = 1
  378. mapping = self._find_map_for_dps(device.get_property(self.id))
  379. if mapping:
  380. scale = mapping.get("scale", 1)
  381. cond = self._active_condition(mapping, device)
  382. if cond:
  383. scale = cond.get("scale", scale)
  384. return scale
  385. def precision(self, device):
  386. if self.type is int:
  387. scale = self.scale(device)
  388. precision = 0
  389. while scale > 1.0:
  390. scale /= 10.0
  391. precision += 1
  392. return precision
  393. def step(self, device, scaled=True):
  394. step = 1
  395. scale = self.scale(device) if scaled else 1
  396. mapping = self._find_map_for_dps(device.get_property(self.id))
  397. if mapping:
  398. _LOGGER.debug(f"Considering mapping for step of {self.name}")
  399. step = mapping.get("step", 1)
  400. cond = self._active_condition(mapping, device)
  401. if cond:
  402. constraint = mapping.get("constraint")
  403. _LOGGER.debug(f"Considering condition on {constraint}")
  404. step = cond.get("step", step)
  405. if step != 1 or scale != 1:
  406. _LOGGER.debug(f"Step for {self.name} is {step} with scale {scale}")
  407. return step / scale if scaled else step
  408. @property
  409. def readonly(self):
  410. return self._config.get("readonly", False)
  411. def invalid_for(self, value, device):
  412. mapping = self._find_map_for_value(value, device)
  413. if mapping:
  414. cond = self._active_condition(mapping, device)
  415. if cond:
  416. return cond.get("invalid", False)
  417. return False
  418. @property
  419. def hidden(self):
  420. return self._config.get("hidden", False)
  421. @property
  422. def unit(self):
  423. return self._config.get("unit")
  424. @property
  425. def state_class(self):
  426. """The state class of this measurement."""
  427. return self._config.get("class")
  428. def _find_map_for_dps(self, value):
  429. default = None
  430. for m in self._config.get("mapping", {}):
  431. if "dps_val" not in m:
  432. default = m
  433. elif self._match(m["dps_val"], value):
  434. return m
  435. return default
  436. def _correct_type(self, result):
  437. """Convert value to the correct type for this dp."""
  438. if self.type is int:
  439. _LOGGER.debug(f"Rounding {self.name}")
  440. result = int(round(result))
  441. elif self.type is bool:
  442. result = True if result else False
  443. elif self.type is float:
  444. result = float(result)
  445. elif self.type is str:
  446. result = str(result)
  447. if self.stringify:
  448. result = str(result)
  449. return result
  450. def _map_from_dps(self, value, device):
  451. if value is not None and self.type is not str and isinstance(value, str):
  452. try:
  453. value = self.type(value)
  454. self.stringify = True
  455. except ValueError:
  456. self.stringify = False
  457. else:
  458. self.stringify = False
  459. result = value
  460. scale = self.scale(device)
  461. mapping = self._find_map_for_dps(value)
  462. if mapping:
  463. invert = mapping.get("invert", False)
  464. redirect = mapping.get("value_redirect")
  465. mirror = mapping.get("value_mirror")
  466. replaced = "value" in mapping
  467. result = mapping.get("value", result)
  468. cond = self._active_condition(mapping, device)
  469. if cond:
  470. if cond.get("invalid", False):
  471. return None
  472. replaced = replaced or "value" in cond
  473. result = cond.get("value", result)
  474. redirect = cond.get("value_redirect", redirect)
  475. mirror = cond.get("value_mirror", mirror)
  476. for m in cond.get("mapping", {}):
  477. if str(m.get("dps_val")) == str(result):
  478. replaced = "value" in m
  479. result = m.get("value", result)
  480. if redirect:
  481. _LOGGER.debug(f"Redirecting {self.name} to {redirect}")
  482. r_dps = self._entity.find_dps(redirect)
  483. return r_dps.get_value(device)
  484. if mirror:
  485. r_dps = self._entity.find_dps(mirror)
  486. return r_dps.get_value(device)
  487. if invert and isinstance(result, (int, float)):
  488. r = self._config.get("range")
  489. if r and "min" in r and "max" in r:
  490. result = -1 * result + r["min"] + r["max"]
  491. replaced = True
  492. if scale != 1 and isinstance(result, (int, float)):
  493. result = result / scale
  494. replaced = True
  495. if replaced:
  496. _LOGGER.debug(
  497. "%s: Mapped dps %s value from %s to %s",
  498. self._entity._device.name,
  499. self.id,
  500. value,
  501. result,
  502. )
  503. return result
  504. def _find_map_for_value(self, value, device):
  505. default = None
  506. for m in self._config.get("mapping", {}):
  507. if "dps_val" not in m:
  508. default = m
  509. if "value" in m and str(m["value"]) == str(value):
  510. return m
  511. if "value" not in m and "value_mirror" in m:
  512. r_dps = self._entity.find_dps(m["value_mirror"])
  513. if str(r_dps.get_value(device)) == str(value):
  514. return m
  515. for c in m.get("conditions", {}):
  516. if "value" in c and str(c["value"]) == str(value):
  517. c_dp = self._entity.find_dps(m.get("constraint"))
  518. # only consider the condition a match if we can change
  519. # the dp to match, or it already matches
  520. if not c_dp.readonly or device.get_property(c_dp.id) == c.get(
  521. "dps_val"
  522. ):
  523. return m
  524. if "value" not in c and "value_mirror" in c:
  525. r_dps = self._entity.find_dps(c["value_mirror"])
  526. if str(r_dps.get_value(device)) == str(value):
  527. return m
  528. return default
  529. def _active_condition(self, mapping, device, value=None):
  530. constraint = mapping.get("constraint")
  531. conditions = mapping.get("conditions")
  532. c_match = None
  533. if constraint and conditions:
  534. c_dps = self._entity.find_dps(constraint)
  535. c_val = None if c_dps is None else device.get_property(c_dps.id)
  536. for cond in conditions:
  537. if c_val is not None and c_val == cond.get("dps_val"):
  538. c_match = cond
  539. # Case where matching None, need extra checks to ensure we
  540. # are not just defaulting and it is really a match
  541. elif (
  542. c_val is None
  543. and c_dps is not None
  544. and "dps_val" in cond
  545. and cond.get("dps_val") is None
  546. ):
  547. c_match = cond
  548. # when changing, another condition may become active
  549. # return that if it exists over a current condition
  550. if value is not None and value == cond.get("value"):
  551. return cond
  552. return c_match
  553. def get_values_to_set(self, device, value):
  554. """Return the dps values that would be set when setting to value"""
  555. result = value
  556. dps_map = {}
  557. if self.readonly:
  558. return dps_map
  559. mapping = self._find_map_for_value(value, device)
  560. scale = self.scale(device)
  561. if mapping:
  562. replaced = False
  563. redirect = mapping.get("value_redirect")
  564. invert = mapping.get("invert", False)
  565. step = mapping.get("step")
  566. if not isinstance(step, (int, float)):
  567. step = None
  568. if "dps_val" in mapping:
  569. result = mapping["dps_val"]
  570. replaced = True
  571. # Conditions may have side effect of setting another value.
  572. cond = self._active_condition(mapping, device, value)
  573. if cond:
  574. cval = cond.get("value")
  575. if cval is None:
  576. r_dps = cond.get("value_mirror")
  577. if r_dps:
  578. cval = self._entity.find_dps(r_dps).get_value(device)
  579. if cval == value:
  580. c_dps = self._entity.find_dps(mapping["constraint"])
  581. c_val = c_dps._map_from_dps(
  582. cond.get("dps_val", device.get_property(c_dps.id)),
  583. device,
  584. )
  585. dps_map.update(c_dps.get_values_to_set(device, c_val))
  586. # Allow simple conditional mapping overrides
  587. for m in cond.get("mapping", {}):
  588. if m.get("value") == value:
  589. result = m.get("dps_val", result)
  590. step = cond.get("step", step)
  591. redirect = cond.get("value_redirect", redirect)
  592. if redirect:
  593. _LOGGER.debug(f"Redirecting {self.name} to {redirect}")
  594. r_dps = self._entity.find_dps(redirect)
  595. return r_dps.get_values_to_set(device, value)
  596. if scale != 1 and isinstance(result, (int, float)):
  597. _LOGGER.debug(f"Scaling {result} by {scale}")
  598. result = result * scale
  599. remap = self._find_map_for_value(result, device)
  600. if remap and "dps_val" in remap and "dps_val" not in mapping:
  601. result = remap["dps_val"]
  602. replaced = True
  603. if invert:
  604. r = self._config.get("range")
  605. if r and "min" in r and "max" in r:
  606. result = -1 * result + r["min"] + r["max"]
  607. replaced = True
  608. if step and isinstance(result, (int, float)):
  609. _LOGGER.debug(f"Stepping {result} to {step}")
  610. result = step * round(float(result) / step)
  611. remap = self._find_map_for_value(result, device)
  612. if remap and "dps_val" in remap and "dps_val" not in mapping:
  613. result = remap["dps_val"]
  614. replaced = True
  615. if replaced:
  616. _LOGGER.debug(
  617. "%s: Mapped dps %s to %s from %s",
  618. self._entity._device.name,
  619. self.id,
  620. result,
  621. value,
  622. )
  623. r = self.range(device, scaled=False)
  624. if r and isinstance(result, (int, float)):
  625. minimum = r["min"]
  626. maximum = r["max"]
  627. if result < minimum or result > maximum:
  628. # Output scaled values in the error message
  629. r = self.range(device, scaled=True)
  630. minimum = r["min"]
  631. maximum = r["max"]
  632. raise ValueError(
  633. f"{self.name} ({value}) must be between {minimum} and {maximum}"
  634. )
  635. dps_map[self.id] = self._correct_type(result)
  636. return dps_map
  637. def icon_rule(self, device):
  638. mapping = self._find_map_for_dps(device.get_property(self.id))
  639. icon = None
  640. priority = 100
  641. if mapping:
  642. icon = mapping.get("icon", icon)
  643. priority = mapping.get("icon_priority", 10 if icon else 100)
  644. cond = self._active_condition(mapping, device)
  645. if cond and cond.get("icon_priority", 10) < priority:
  646. icon = cond.get("icon", icon)
  647. priority = cond.get("icon_priority", 10 if icon else 100)
  648. return {"priority": priority, "icon": icon}
  649. def available_configs():
  650. """List the available config files."""
  651. _CONFIG_DIR = dirname(config_dir.__file__)
  652. for path, dirs, files in walk(_CONFIG_DIR):
  653. for basename in sorted(files):
  654. if fnmatch(basename, "*.yaml"):
  655. yield basename
  656. def possible_matches(dps):
  657. """Return possible matching configs for a given set of dps values."""
  658. for cfg in available_configs():
  659. parsed = TuyaDeviceConfig(cfg)
  660. if parsed.matches(dps):
  661. yield parsed
  662. def get_config(conf_type):
  663. """
  664. Return a config to use with config_type.
  665. """
  666. _CONFIG_DIR = dirname(config_dir.__file__)
  667. fname = conf_type + ".yaml"
  668. fpath = join(_CONFIG_DIR, fname)
  669. if exists(fpath):
  670. return TuyaDeviceConfig(fname)
  671. else:
  672. return config_for_legacy_use(conf_type)
  673. def config_for_legacy_use(conf_type):
  674. """
  675. Return a config to use with config_type for legacy transition.
  676. Note: as there are two variants for Kogan Socket, this is not guaranteed
  677. to be the correct config for the device, so only use it for looking up
  678. the legacy class during the transition period.
  679. """
  680. for cfg in available_configs():
  681. parsed = TuyaDeviceConfig(cfg)
  682. if parsed.legacy_type == conf_type:
  683. return parsed
  684. return None