device_config.py 26 KB

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