device_config.py 35 KB

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