device_config.py 37 KB

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