4
0

device_config.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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. @property
  404. def default(self):
  405. """Return the default value for a dp."""
  406. if "mapping" not in self._config.keys():
  407. _LOGGER.debug(
  408. "No mapping for %s, unable to determine default value",
  409. self.name,
  410. )
  411. return None
  412. for m in self._config["mapping"]:
  413. if m.get("default", False):
  414. return m.get("dps_val", None)
  415. def range(self, device, scaled=True):
  416. """Return the range for this dps if configured."""
  417. scale = self.scale(device) if scaled else 1
  418. mapping = self._find_map_for_dps(device.get_property(self.id))
  419. r = self._config.get("range")
  420. if mapping:
  421. _LOGGER.debug("Considering mapping for range of %s", self.name)
  422. cond = self._active_condition(mapping, device)
  423. if cond:
  424. r = cond.get("range", r)
  425. if r and "min" in r and "max" in r:
  426. return _scale_range(r, scale)
  427. else:
  428. return None
  429. def scale(self, device):
  430. scale = 1
  431. mapping = self._find_map_for_dps(device.get_property(self.id))
  432. if mapping:
  433. scale = mapping.get("scale", 1)
  434. cond = self._active_condition(mapping, device)
  435. if cond:
  436. scale = cond.get("scale", scale)
  437. return scale
  438. def precision(self, device):
  439. if self.type is int:
  440. scale = self.scale(device)
  441. precision = 0
  442. while scale > 1.0:
  443. scale /= 10.0
  444. precision += 1
  445. return precision
  446. @property
  447. def suggested_display_precision(self):
  448. return self._config.get("precision")
  449. def step(self, device, scaled=True):
  450. step = 1
  451. scale = self.scale(device) if scaled else 1
  452. mapping = self._find_map_for_dps(device.get_property(self.id))
  453. if mapping:
  454. _LOGGER.debug("Considering mapping for step of %s", self.name)
  455. step = mapping.get("step", 1)
  456. cond = self._active_condition(mapping, device)
  457. if cond:
  458. constraint = mapping.get("constraint", self.name)
  459. _LOGGER.debug("Considering condition on %s", constraint)
  460. step = cond.get("step", step)
  461. if step != 1 or scale != 1:
  462. _LOGGER.debug(
  463. "Step for %s is %s with scale %s",
  464. self.name,
  465. step,
  466. scale,
  467. )
  468. return step / scale if scaled else step
  469. @property
  470. def readonly(self):
  471. return self._config.get("readonly", False)
  472. def invalid_for(self, value, device):
  473. mapping = self._find_map_for_value(value, device)
  474. if mapping:
  475. cond = self._active_condition(mapping, device)
  476. if cond:
  477. return cond.get("invalid", False)
  478. return False
  479. @property
  480. def hidden(self):
  481. return self._config.get("hidden", False)
  482. @property
  483. def unit(self):
  484. return self._config.get("unit")
  485. @property
  486. def state_class(self):
  487. """The state class of this measurement."""
  488. return self._config.get("class")
  489. def _find_map_for_dps(self, value):
  490. default = None
  491. for m in self._config.get("mapping", {}):
  492. if "dps_val" not in m:
  493. default = m
  494. elif self._match(m["dps_val"], value):
  495. return m
  496. return default
  497. def _correct_type(self, result):
  498. """Convert value to the correct type for this dp."""
  499. if self.type is int:
  500. _LOGGER.debug("Rounding %s", self.name)
  501. result = int(round(result))
  502. elif self.type is bool:
  503. result = True if result else False
  504. elif self.type is float:
  505. result = float(result)
  506. elif self.type is str:
  507. result = str(result)
  508. if self.stringify:
  509. result = str(result)
  510. return result
  511. def _map_from_dps(self, val, device):
  512. if val is not None and self.type is not str and isinstance(val, str):
  513. try:
  514. val = self.type(val)
  515. self.stringify = True
  516. except ValueError:
  517. self.stringify = False
  518. else:
  519. self.stringify = False
  520. result = val
  521. scale = self.scale(device)
  522. mapping = self._find_map_for_dps(val)
  523. if mapping:
  524. invert = mapping.get("invert", False)
  525. redirect = mapping.get("value_redirect")
  526. mirror = mapping.get("value_mirror")
  527. replaced = "value" in mapping
  528. result = mapping.get("value", result)
  529. cond = self._active_condition(mapping, device)
  530. if cond:
  531. if cond.get("invalid", False):
  532. return None
  533. replaced = replaced or "value" in cond
  534. result = cond.get("value", result)
  535. redirect = cond.get("value_redirect", redirect)
  536. mirror = cond.get("value_mirror", mirror)
  537. for m in cond.get("mapping", {}):
  538. if str(m.get("dps_val")) == str(result):
  539. replaced = "value" in m
  540. result = m.get("value", result)
  541. if redirect:
  542. _LOGGER.debug("Redirecting %s to %s", self.name, redirect)
  543. r_dps = self._entity.find_dps(redirect)
  544. return r_dps.get_value(device)
  545. if mirror:
  546. r_dps = self._entity.find_dps(mirror)
  547. return r_dps.get_value(device)
  548. if invert and isinstance(result, Number):
  549. r = self._config.get("range")
  550. if r and "min" in r and "max" in r:
  551. result = -1 * result + r["min"] + r["max"]
  552. replaced = True
  553. if scale != 1 and isinstance(result, Number):
  554. result = result / scale
  555. replaced = True
  556. if replaced:
  557. _LOGGER.debug(
  558. "%s: Mapped dps %s value from %s to %s",
  559. self._entity._device.name,
  560. self.id,
  561. val,
  562. result,
  563. )
  564. return result
  565. def _find_map_for_value(self, value, device):
  566. default = None
  567. nearest = None
  568. distance = float("inf")
  569. for m in self._config.get("mapping", {}):
  570. if "dps_val" not in m:
  571. default = m
  572. if "value" in m and str(m["value"]) == str(value):
  573. return m
  574. if (
  575. "value" in m
  576. and isinstance(m["value"], Number)
  577. and isinstance(value, Number)
  578. ):
  579. d = abs(m["value"] - value)
  580. if d < distance:
  581. distance = d
  582. nearest = m
  583. if "value" not in m and "value_mirror" in m:
  584. r_dps = self._entity.find_dps(m["value_mirror"])
  585. if str(r_dps.get_value(device)) == str(value):
  586. return m
  587. for c in m.get("conditions", {}):
  588. if "value" in c and str(c["value"]) == str(value):
  589. c_dp = self._entity.find_dps(m.get("constraint", self.name))
  590. # only consider the condition a match if we can change
  591. # the dp to match, or it already matches
  592. if (c_dp.id != self.id and not c_dp.readonly) or (
  593. _equal_or_in(
  594. device.get_property(c_dp.id),
  595. c.get("dps_val"),
  596. )
  597. ):
  598. return m
  599. if "value" not in c and "value_mirror" in c:
  600. r_dps = self._entity.find_dps(c["value_mirror"])
  601. if str(r_dps.get_value(device)) == str(value):
  602. return m
  603. if nearest:
  604. return nearest
  605. return default
  606. def _active_condition(self, mapping, device, value=None):
  607. constraint = mapping.get("constraint", self.name)
  608. conditions = mapping.get("conditions")
  609. c_match = None
  610. if constraint and conditions:
  611. c_dps = self._entity.find_dps(constraint)
  612. c_val = None if c_dps is None else device.get_property(c_dps.id)
  613. for cond in conditions:
  614. if c_val is not None and (_equal_or_in(c_val, cond.get("dps_val"))):
  615. c_match = cond
  616. # Case where matching None, need extra checks to ensure we
  617. # are not just defaulting and it is really a match
  618. elif (
  619. c_val is None
  620. and c_dps is not None
  621. and "dps_val" in cond
  622. and cond.get("dps_val") is None
  623. ):
  624. c_match = cond
  625. # when changing, another condition may become active
  626. # return that if it exists over a current condition
  627. if value is not None and value == cond.get("value"):
  628. return cond
  629. return c_match
  630. def get_values_to_set(self, device, value):
  631. """Return the dps values that would be set when setting to value"""
  632. result = value
  633. dps_map = {}
  634. if self.readonly:
  635. return dps_map
  636. mapping = self._find_map_for_value(value, device)
  637. scale = self.scale(device)
  638. mask = None
  639. if mapping:
  640. replaced = False
  641. redirect = mapping.get("value_redirect")
  642. invert = mapping.get("invert", False)
  643. mask = mapping.get("mask")
  644. step = mapping.get("step")
  645. if not isinstance(step, Number):
  646. step = None
  647. if "dps_val" in mapping:
  648. result = mapping["dps_val"]
  649. replaced = True
  650. # Conditions may have side effect of setting another value.
  651. cond = self._active_condition(mapping, device, value)
  652. if cond:
  653. cval = cond.get("value")
  654. if cval is None:
  655. r_dps = cond.get("value_mirror")
  656. if r_dps:
  657. cval = self._entity.find_dps(r_dps).get_value(device)
  658. if cval == value:
  659. c_dps = self._entity.find_dps(mapping.get("constraint", self.name))
  660. cond_dpsval = cond.get("dps_val")
  661. single_match = type(cond_dpsval) == str or (
  662. not isinstance(cond_dpsval, Sequence)
  663. )
  664. if c_dps.id != self.id and single_match:
  665. c_val = c_dps._map_from_dps(
  666. cond.get("dps_val", device.get_property(c_dps.id)),
  667. device,
  668. )
  669. dps_map.update(c_dps.get_values_to_set(device, c_val))
  670. # Allow simple conditional mapping overrides
  671. for m in cond.get("mapping", {}):
  672. if m.get("value") == value:
  673. result = m.get("dps_val", result)
  674. step = cond.get("step", step)
  675. redirect = cond.get("value_redirect", redirect)
  676. if redirect:
  677. _LOGGER.debug("Redirecting %s to %s", self.name, redirect)
  678. r_dps = self._entity.find_dps(redirect)
  679. return r_dps.get_values_to_set(device, value)
  680. if scale != 1 and isinstance(result, Number):
  681. _LOGGER.debug("Scaling %s by %s", result, scale)
  682. result = result * scale
  683. remap = self._find_map_for_value(result, device)
  684. if remap and "dps_val" in remap and "dps_val" not in mapping:
  685. result = remap["dps_val"]
  686. replaced = True
  687. if invert:
  688. r = self._config.get("range")
  689. if r and "min" in r and "max" in r:
  690. result = -1 * result + r["min"] + r["max"]
  691. replaced = True
  692. if step and isinstance(result, Number):
  693. _LOGGER.debug("Stepping %s to %s", result, step)
  694. result = step * round(float(result) / step)
  695. remap = self._find_map_for_value(result, device)
  696. if remap and "dps_val" in remap and "dps_val" not in mapping:
  697. result = remap["dps_val"]
  698. replaced = True
  699. if replaced:
  700. _LOGGER.debug(
  701. "%s: Mapped dps %s to %s from %s",
  702. self._entity._device.name,
  703. self.id,
  704. result,
  705. value,
  706. )
  707. r = self.range(device, scaled=False)
  708. if r and isinstance(result, Number):
  709. mn = r["min"]
  710. mx = r["max"]
  711. if result < mn or result > mx:
  712. # Output scaled values in the error message
  713. r = self.range(device, scaled=True)
  714. mn = r["min"]
  715. mx = r["max"]
  716. raise ValueError(f"{self.name} ({value}) must be between {mn} and {mx}")
  717. if mask and isinstance(result, Number):
  718. # Convert to int
  719. length = len(mask)
  720. mask = int(mask, 16)
  721. mask_scale = mask & (1 + ~mask)
  722. current_value = int.from_bytes(self.decoded_value(device), "big")
  723. result = (current_value & ~mask) | (mask & (result * mask_scale))
  724. result = self.encode_value(result.to_bytes(length, "big"))
  725. dps_map[self.id] = self._correct_type(result)
  726. return dps_map
  727. def icon_rule(self, device):
  728. mapping = self._find_map_for_dps(device.get_property(self.id))
  729. icon = None
  730. priority = 100
  731. if mapping:
  732. icon = mapping.get("icon", icon)
  733. priority = mapping.get("icon_priority", 10 if icon else 100)
  734. cond = self._active_condition(mapping, device)
  735. if cond and cond.get("icon_priority", 10) < priority:
  736. icon = cond.get("icon", icon)
  737. priority = cond.get("icon_priority", 10 if icon else 100)
  738. return {"priority": priority, "icon": icon}
  739. def available_configs():
  740. """List the available config files."""
  741. _CONFIG_DIR = dirname(config_dir.__file__)
  742. for path, dirs, files in walk(_CONFIG_DIR):
  743. for basename in sorted(files):
  744. if fnmatch(basename, "*.yaml"):
  745. yield basename
  746. def possible_matches(dps):
  747. """Return possible matching configs for a given set of dps values."""
  748. for cfg in available_configs():
  749. parsed = TuyaDeviceConfig(cfg)
  750. try:
  751. if parsed.matches(dps):
  752. yield parsed
  753. except TypeError:
  754. _LOGGER.error("Parse error in %s", cfg)
  755. def get_config(conf_type):
  756. """
  757. Return a config to use with config_type.
  758. """
  759. _CONFIG_DIR = dirname(config_dir.__file__)
  760. fname = conf_type + ".yaml"
  761. fpath = join(_CONFIG_DIR, fname)
  762. if exists(fpath):
  763. return TuyaDeviceConfig(fname)
  764. else:
  765. return config_for_legacy_use(conf_type)
  766. def config_for_legacy_use(conf_type):
  767. """
  768. Return a config to use with config_type for legacy transition.
  769. Note: as there are two variants for Kogan Socket, this is not guaranteed
  770. to be the correct config for the device, so only use it for looking up
  771. the legacy class during the transition period.
  772. """
  773. for cfg in available_configs():
  774. parsed = TuyaDeviceConfig(cfg)
  775. if parsed.legacy_type == conf_type:
  776. return parsed
  777. return None