device_config.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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_dp = keys + matched
  131. for d in entity.dps():
  132. if (d.id not in all_dp and not d.optional) or (
  133. d.id in all_dp 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. @property
  169. def translation_key(self):
  170. """The translation key for this entity."""
  171. return self._config.get("translation_key")
  172. def unique_id(self, device_uid):
  173. """Return a suitable unique_id for this entity."""
  174. return f"{device_uid}-{slugify(self.config_id)}"
  175. @property
  176. def entity_category(self):
  177. return self._config.get("category")
  178. @property
  179. def deprecated(self):
  180. """Return whether this entitiy is deprecated."""
  181. return "deprecated" in self._config.keys()
  182. @property
  183. def deprecation_message(self):
  184. """Return a deprecation message for this entity"""
  185. replacement = self._config.get(
  186. "deprecated", "nothing, this warning has been raised in error"
  187. )
  188. return (
  189. f"The use of {self.entity} for {self._device.name} is "
  190. f"deprecated and should be replaced by {replacement}."
  191. )
  192. @property
  193. def entity(self):
  194. """The entity type of this entity."""
  195. return self._config["entity"]
  196. @property
  197. def config_id(self):
  198. """The identifier for this entity in the config."""
  199. own_name = self.name
  200. if own_name:
  201. return f"{self.entity}_{slugify(own_name)}"
  202. return self.entity
  203. @property
  204. def device_class(self):
  205. """The device class of this entity."""
  206. return self._config.get("class")
  207. def icon(self, device):
  208. """Return the icon for this device, with state as given."""
  209. icon = self._config.get("icon", None)
  210. priority = self._config.get("icon_priority", 100)
  211. for d in self.dps():
  212. rule = d.icon_rule(device)
  213. if rule and rule["priority"] < priority:
  214. icon = rule["icon"]
  215. priority = rule["priority"]
  216. return icon
  217. @property
  218. def mode(self):
  219. """Return the mode (used by Number entities)."""
  220. return self._config.get("mode")
  221. def dps(self):
  222. """Iterate through the list of dps for this entity."""
  223. for d in self._config["dps"]:
  224. yield TuyaDpsConfig(self, d)
  225. def find_dps(self, name):
  226. """Find a dps with the specified name."""
  227. for d in self.dps():
  228. if d.name == name:
  229. return d
  230. return None
  231. class TuyaDpsConfig:
  232. """Representation of a dps config."""
  233. def __init__(self, entity, config):
  234. self._entity = entity
  235. self._config = config
  236. self.stringify = False
  237. @property
  238. def id(self):
  239. return str(self._config["id"])
  240. @property
  241. def type(self):
  242. t = self._config["type"]
  243. types = {
  244. "boolean": bool,
  245. "integer": int,
  246. "string": str,
  247. "float": float,
  248. "bitfield": int,
  249. "json": str,
  250. "base64": str,
  251. "hex": str,
  252. }
  253. return types.get(t)
  254. @property
  255. def rawtype(self):
  256. return self._config["type"]
  257. @property
  258. def name(self):
  259. return self._config["name"]
  260. @property
  261. def optional(self):
  262. return self._config.get("optional", False)
  263. @property
  264. def persist(self):
  265. return self._config.get("persist", True)
  266. @property
  267. def force(self):
  268. return self._config.get("force", False)
  269. @property
  270. def format(self):
  271. fmt = self._config.get("format")
  272. if fmt:
  273. unpack_fmt = ">"
  274. ranges = []
  275. names = []
  276. for f in fmt:
  277. name = f.get("name")
  278. b = f.get("bytes", 1)
  279. r = f.get("range")
  280. if r:
  281. mn = r.get("min")
  282. mx = r.get("max")
  283. else:
  284. mn = 0
  285. mx = 256**b - 1
  286. unpack_fmt = unpack_fmt + _bytes_to_fmt(b, mn < 0)
  287. ranges.append({"min": mn, "max": mx})
  288. names.append(name)
  289. _LOGGER.debug("format of %s found", unpack_fmt)
  290. return {"format": unpack_fmt, "ranges": ranges, "names": names}
  291. return None
  292. def mask(self, device):
  293. mapping = self._find_map_for_dps(device.get_property(self.id))
  294. if mapping:
  295. mask = mapping.get("mask")
  296. if mask:
  297. return int(mask, 16)
  298. def get_value(self, device):
  299. """Return the value of the dps from the given device."""
  300. mask = self.mask(device)
  301. bytevalue = self.decoded_value(device)
  302. if mask and isinstance(bytevalue, bytes):
  303. value = int.from_bytes(bytevalue, "big")
  304. scale = mask & (1 + ~mask)
  305. map_scale = self.scale(device)
  306. return ((value & mask) // scale) / map_scale
  307. else:
  308. return self._map_from_dps(device.get_property(self.id), device)
  309. def decoded_value(self, device):
  310. v = self._map_from_dps(device.get_property(self.id), device)
  311. if self.rawtype == "hex" and isinstance(v, str):
  312. try:
  313. return bytes.fromhex(v)
  314. except ValueError:
  315. _LOGGER.warning(
  316. "%s sent invalid hex '%s' for %s",
  317. device.name,
  318. v,
  319. self.name,
  320. )
  321. return None
  322. elif self.rawtype == "base64" and isinstance(v, str):
  323. try:
  324. return b64decode(v)
  325. except ValueError:
  326. _LOGGER.warning(
  327. "%s sent invalid base64 '%s' for %s",
  328. device.name,
  329. v,
  330. self.name,
  331. )
  332. return None
  333. else:
  334. return v
  335. def encode_value(self, v):
  336. if self.rawtype == "hex":
  337. return v.hex()
  338. elif self.rawtype == "base64":
  339. return b64encode(v).decode("utf-8")
  340. else:
  341. return v
  342. def _match(self, matchdata, value):
  343. """Return true val1 matches val2"""
  344. if self.rawtype == "bitfield" and matchdata:
  345. try:
  346. return (int(value) & int(matchdata)) != 0
  347. except (TypeError, ValueError):
  348. return False
  349. else:
  350. return str(value) == str(matchdata)
  351. async def async_set_value(self, device, value):
  352. """Set the value of the dps in the given device to given value."""
  353. if self.readonly:
  354. raise TypeError(f"{self.name} is read only")
  355. if self.invalid_for(value, device):
  356. raise AttributeError(f"{self.name} cannot be set at this time")
  357. settings = self.get_values_to_set(device, value)
  358. await device.async_set_properties(settings)
  359. def values(self, device):
  360. """Return the possible values a dps can take."""
  361. if "mapping" not in self._config.keys():
  362. _LOGGER.debug(
  363. "No mapping for %s, unable to determine valid values",
  364. self.name,
  365. )
  366. return []
  367. val = []
  368. for m in self._config["mapping"]:
  369. if "value" in m and not m.get("hidden", False):
  370. val.append(m["value"])
  371. # If there is mirroring without override, include mirrored values
  372. elif "value_mirror" in m:
  373. r_dps = self._entity.find_dps(m["value_mirror"])
  374. val = val + r_dps.values(device)
  375. for c in m.get("conditions", {}):
  376. if "value" in c and not c.get("hidden", False):
  377. val.append(c["value"])
  378. elif "value_mirror" in c:
  379. r_dps = self._entity.find_dps(c["value_mirror"])
  380. val = val + r_dps.values(device)
  381. cond = self._active_condition(m, device)
  382. if cond and "mapping" in cond:
  383. _LOGGER.debug("Considering conditional mappings")
  384. c_val = []
  385. for m2 in cond["mapping"]:
  386. if "value" in m2 and not m2.get("hidden", False):
  387. c_val.append(m2["value"])
  388. elif "value_mirror" in m:
  389. r_dps = self._entity.find_dps(m["value_mirror"])
  390. c_val = c_val + r_dps.values(device)
  391. # if given, the conditional mapping is an override
  392. if c_val:
  393. _LOGGER.debug(
  394. "Overriding %s values %s with %s",
  395. self.name,
  396. val,
  397. c_val,
  398. )
  399. val = c_val
  400. break
  401. _LOGGER.debug("%s values: %s", self.name, val)
  402. return list(set(val)) if val else []
  403. def default(self):
  404. """Return the default value for a dp."""
  405. if "mapping" not in self._config.keys():
  406. _LOGGER.debug(
  407. "No mapping for %s, unable to determine default value",
  408. self.name,
  409. )
  410. return None
  411. for m in self._config["mapping"]:
  412. if m.get("default", False):
  413. return m.get("dps_val", None)
  414. def range(self, device, scaled=True):
  415. """Return the range for this dps if configured."""
  416. scale = self.scale(device) if scaled else 1
  417. mapping = self._find_map_for_dps(device.get_property(self.id))
  418. r = self._config.get("range")
  419. if mapping:
  420. _LOGGER.debug("Considering mapping for range of %s", self.name)
  421. cond = self._active_condition(mapping, device)
  422. if cond:
  423. r = cond.get("range", r)
  424. if r and "min" in r and "max" in r:
  425. return _scale_range(r, scale)
  426. else:
  427. return None
  428. def scale(self, device):
  429. scale = 1
  430. mapping = self._find_map_for_dps(device.get_property(self.id))
  431. if mapping:
  432. scale = mapping.get("scale", 1)
  433. cond = self._active_condition(mapping, device)
  434. if cond:
  435. scale = cond.get("scale", scale)
  436. return scale
  437. def precision(self, device):
  438. if self.type is int:
  439. scale = self.scale(device)
  440. precision = 0
  441. while scale > 1.0:
  442. scale /= 10.0
  443. precision += 1
  444. return precision
  445. @property
  446. def suggested_display_precision(self):
  447. return self._config.get("precision")
  448. def step(self, device, scaled=True):
  449. step = 1
  450. scale = self.scale(device) if scaled else 1
  451. mapping = self._find_map_for_dps(device.get_property(self.id))
  452. if mapping:
  453. _LOGGER.debug("Considering mapping for step of %s", self.name)
  454. step = mapping.get("step", 1)
  455. cond = self._active_condition(mapping, device)
  456. if cond:
  457. constraint = mapping.get("constraint", self.name)
  458. _LOGGER.debug("Considering condition on %s", constraint)
  459. step = cond.get("step", step)
  460. if step != 1 or scale != 1:
  461. _LOGGER.debug(
  462. "Step for %s is %s with scale %s",
  463. self.name,
  464. step,
  465. scale,
  466. )
  467. return step / scale if scaled else step
  468. @property
  469. def readonly(self):
  470. return self._config.get("readonly", False)
  471. def invalid_for(self, value, device):
  472. mapping = self._find_map_for_value(value, device)
  473. if mapping:
  474. cond = self._active_condition(mapping, device)
  475. if cond:
  476. return cond.get("invalid", False)
  477. return False
  478. @property
  479. def hidden(self):
  480. return self._config.get("hidden", False)
  481. @property
  482. def unit(self):
  483. return self._config.get("unit")
  484. @property
  485. def state_class(self):
  486. """The state class of this measurement."""
  487. return self._config.get("class")
  488. def _find_map_for_dps(self, value):
  489. default = None
  490. for m in self._config.get("mapping", {}):
  491. if "dps_val" not in m:
  492. default = m
  493. elif self._match(m["dps_val"], value):
  494. return m
  495. return default
  496. def _correct_type(self, result):
  497. """Convert value to the correct type for this dp."""
  498. if self.type is int:
  499. _LOGGER.debug("Rounding %s", self.name)
  500. result = int(round(result))
  501. elif self.type is bool:
  502. result = True if result else False
  503. elif self.type is float:
  504. result = float(result)
  505. elif self.type is str:
  506. result = str(result)
  507. if self.stringify:
  508. result = str(result)
  509. return result
  510. def _map_from_dps(self, val, device):
  511. if val is not None and self.type is not str and isinstance(val, str):
  512. try:
  513. val = self.type(val)
  514. self.stringify = True
  515. except ValueError:
  516. self.stringify = False
  517. else:
  518. self.stringify = False
  519. result = val
  520. scale = self.scale(device)
  521. mapping = self._find_map_for_dps(val)
  522. if mapping:
  523. invert = mapping.get("invert", False)
  524. redirect = mapping.get("value_redirect")
  525. mirror = mapping.get("value_mirror")
  526. replaced = "value" in mapping
  527. result = mapping.get("value", result)
  528. cond = self._active_condition(mapping, device)
  529. if cond:
  530. if cond.get("invalid", False):
  531. return None
  532. replaced = replaced or "value" in cond
  533. result = cond.get("value", result)
  534. redirect = cond.get("value_redirect", redirect)
  535. mirror = cond.get("value_mirror", mirror)
  536. for m in cond.get("mapping", {}):
  537. if str(m.get("dps_val")) == str(result):
  538. replaced = "value" in m
  539. result = m.get("value", result)
  540. if redirect:
  541. _LOGGER.debug("Redirecting %s to %s", self.name, redirect)
  542. r_dps = self._entity.find_dps(redirect)
  543. return r_dps.get_value(device)
  544. if mirror:
  545. r_dps = self._entity.find_dps(mirror)
  546. return r_dps.get_value(device)
  547. if invert and isinstance(result, Number):
  548. r = self._config.get("range")
  549. if r and "min" in r and "max" in r:
  550. result = -1 * result + r["min"] + r["max"]
  551. replaced = True
  552. if scale != 1 and isinstance(result, Number):
  553. result = result / scale
  554. replaced = True
  555. if replaced:
  556. _LOGGER.debug(
  557. "%s: Mapped dps %s value from %s to %s",
  558. self._entity._device.name,
  559. self.id,
  560. val,
  561. result,
  562. )
  563. return result
  564. def _find_map_for_value(self, value, device):
  565. default = None
  566. nearest = None
  567. distance = float("inf")
  568. for m in self._config.get("mapping", {}):
  569. if "dps_val" not in m:
  570. default = m
  571. if "value" in m and str(m["value"]) == str(value):
  572. return m
  573. if (
  574. "value" in m
  575. and isinstance(m["value"], Number)
  576. and isinstance(value, Number)
  577. ):
  578. d = abs(m["value"] - value)
  579. if d < distance:
  580. distance = d
  581. nearest = m
  582. if "value" not in m and "value_mirror" in m:
  583. r_dps = self._entity.find_dps(m["value_mirror"])
  584. if str(r_dps.get_value(device)) == str(value):
  585. return m
  586. for c in m.get("conditions", {}):
  587. if "value" in c and str(c["value"]) == str(value):
  588. c_dp = self._entity.find_dps(m.get("constraint", self.name))
  589. # only consider the condition a match if we can change
  590. # the dp to match, or it already matches
  591. if (c_dp.id != self.id and not c_dp.readonly) or (
  592. _equal_or_in(
  593. device.get_property(c_dp.id),
  594. c.get("dps_val"),
  595. )
  596. ):
  597. return m
  598. if "value" not in c and "value_mirror" in c:
  599. r_dps = self._entity.find_dps(c["value_mirror"])
  600. if str(r_dps.get_value(device)) == str(value):
  601. return m
  602. if nearest:
  603. return nearest
  604. return default
  605. def _active_condition(self, mapping, device, value=None):
  606. constraint = mapping.get("constraint", self.name)
  607. conditions = mapping.get("conditions")
  608. c_match = None
  609. if constraint and conditions:
  610. c_dps = self._entity.find_dps(constraint)
  611. c_val = None if c_dps is None else device.get_property(c_dps.id)
  612. for cond in conditions:
  613. if c_val is not None and (_equal_or_in(c_val, cond.get("dps_val"))):
  614. c_match = cond
  615. # Case where matching None, need extra checks to ensure we
  616. # are not just defaulting and it is really a match
  617. elif (
  618. c_val is None
  619. and c_dps is not None
  620. and "dps_val" in cond
  621. and cond.get("dps_val") is None
  622. ):
  623. c_match = cond
  624. # when changing, another condition may become active
  625. # return that if it exists over a current condition
  626. if value is not None and value == cond.get("value"):
  627. return cond
  628. return c_match
  629. def get_values_to_set(self, device, value):
  630. """Return the dps values that would be set when setting to value"""
  631. result = value
  632. dps_map = {}
  633. if self.readonly:
  634. return dps_map
  635. mapping = self._find_map_for_value(value, device)
  636. scale = self.scale(device)
  637. mask = None
  638. if mapping:
  639. replaced = False
  640. redirect = mapping.get("value_redirect")
  641. invert = mapping.get("invert", False)
  642. mask = mapping.get("mask")
  643. step = mapping.get("step")
  644. if not isinstance(step, Number):
  645. step = None
  646. if "dps_val" in mapping:
  647. result = mapping["dps_val"]
  648. replaced = True
  649. # Conditions may have side effect of setting another value.
  650. cond = self._active_condition(mapping, device, value)
  651. if cond:
  652. cval = cond.get("value")
  653. if cval is None:
  654. r_dps = cond.get("value_mirror")
  655. if r_dps:
  656. cval = self._entity.find_dps(r_dps).get_value(device)
  657. if cval == value:
  658. c_dps = self._entity.find_dps(mapping.get("constraint", self.name))
  659. cond_dpsval = cond.get("dps_val")
  660. single_match = type(cond_dpsval) == str or (
  661. not isinstance(cond_dpsval, Sequence)
  662. )
  663. if c_dps.id != self.id and single_match:
  664. c_val = c_dps._map_from_dps(
  665. cond.get("dps_val", device.get_property(c_dps.id)),
  666. device,
  667. )
  668. dps_map.update(c_dps.get_values_to_set(device, c_val))
  669. # Allow simple conditional mapping overrides
  670. for m in cond.get("mapping", {}):
  671. if m.get("value") == value:
  672. result = m.get("dps_val", result)
  673. step = cond.get("step", step)
  674. redirect = cond.get("value_redirect", redirect)
  675. if redirect:
  676. _LOGGER.debug("Redirecting %s to %s", self.name, redirect)
  677. r_dps = self._entity.find_dps(redirect)
  678. return r_dps.get_values_to_set(device, value)
  679. if scale != 1 and isinstance(result, Number):
  680. _LOGGER.debug("Scaling %s by %s", result, scale)
  681. result = result * scale
  682. remap = self._find_map_for_value(result, device)
  683. if remap and "dps_val" in remap and "dps_val" not in mapping:
  684. result = remap["dps_val"]
  685. replaced = True
  686. if invert:
  687. r = self._config.get("range")
  688. if r and "min" in r and "max" in r:
  689. result = -1 * result + r["min"] + r["max"]
  690. replaced = True
  691. if step and isinstance(result, Number):
  692. _LOGGER.debug("Stepping %s to %s", result, step)
  693. result = step * round(float(result) / step)
  694. remap = self._find_map_for_value(result, device)
  695. if remap and "dps_val" in remap and "dps_val" not in mapping:
  696. result = remap["dps_val"]
  697. replaced = True
  698. if replaced:
  699. _LOGGER.debug(
  700. "%s: Mapped dps %s to %s from %s",
  701. self._entity._device.name,
  702. self.id,
  703. result,
  704. value,
  705. )
  706. r = self.range(device, scaled=False)
  707. if r and isinstance(result, Number):
  708. mn = r["min"]
  709. mx = r["max"]
  710. if result < mn or result > mx:
  711. # Output scaled values in the error message
  712. r = self.range(device, scaled=True)
  713. mn = r["min"]
  714. mx = r["max"]
  715. raise ValueError(f"{self.name} ({value}) must be between {mn} and {mx}")
  716. if mask and isinstance(result, Number):
  717. # Convert to int
  718. length = len(mask)
  719. mask = int(mask, 16)
  720. mask_scale = mask & (1 + ~mask)
  721. current_value = int.from_bytes(self.decoded_value(device), "big")
  722. result = (current_value & ~mask) | (mask & (result * mask_scale))
  723. result = self.encode_value(result.to_bytes(length, "big"))
  724. dps_map[self.id] = self._correct_type(result)
  725. return dps_map
  726. def icon_rule(self, device):
  727. mapping = self._find_map_for_dps(device.get_property(self.id))
  728. icon = None
  729. priority = 100
  730. if mapping:
  731. icon = mapping.get("icon", icon)
  732. priority = mapping.get("icon_priority", 10 if icon else 100)
  733. cond = self._active_condition(mapping, device)
  734. if cond and cond.get("icon_priority", 10) < priority:
  735. icon = cond.get("icon", icon)
  736. priority = cond.get("icon_priority", 10 if icon else 100)
  737. return {"priority": priority, "icon": icon}
  738. def available_configs():
  739. """List the available config files."""
  740. _CONFIG_DIR = dirname(config_dir.__file__)
  741. for path, dirs, files in walk(_CONFIG_DIR):
  742. for basename in sorted(files):
  743. if fnmatch(basename, "*.yaml"):
  744. yield basename
  745. def possible_matches(dps):
  746. """Return possible matching configs for a given set of dps values."""
  747. for cfg in available_configs():
  748. parsed = TuyaDeviceConfig(cfg)
  749. try:
  750. if parsed.matches(dps):
  751. yield parsed
  752. except TypeError:
  753. _LOGGER.error("Parse error in %s", cfg)
  754. def get_config(conf_type):
  755. """
  756. Return a config to use with config_type.
  757. """
  758. _CONFIG_DIR = dirname(config_dir.__file__)
  759. fname = conf_type + ".yaml"
  760. fpath = join(_CONFIG_DIR, fname)
  761. if exists(fpath):
  762. return TuyaDeviceConfig(fname)
  763. else:
  764. return config_for_legacy_use(conf_type)
  765. def config_for_legacy_use(conf_type):
  766. """
  767. Return a config to use with config_type for legacy transition.
  768. Note: as there are two variants for Kogan Socket, this is not guaranteed
  769. to be the correct config for the device, so only use it for looking up
  770. the legacy class during the transition period.
  771. """
  772. for cfg in available_configs():
  773. parsed = TuyaDeviceConfig(cfg)
  774. if parsed.legacy_type == conf_type:
  775. return parsed
  776. return None