device_config.py 36 KB

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