device_config.py 41 KB

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