device_config.py 29 KB

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