device_config.py 43 KB

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