device_config.py 38 KB

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