device_config.py 30 KB

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