device_config.py 28 KB

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