device_config.py 34 KB

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