device_config.py 34 KB

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