device_config.py 26 KB

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