4
0

device_config.py 31 KB

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