device_config.py 39 KB

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