device_config.py 28 KB

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