device_config.py 32 KB

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