device_config.py 34 KB

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