device_config.py 27 KB

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