device_config.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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. cond = self._active_condition(mapping, device)
  530. if cond:
  531. r = cond.get("range", r)
  532. if r and "min" in r and "max" in r:
  533. return _scale_range(r, scale)
  534. else:
  535. return None
  536. def scale(self, device):
  537. scale = 1
  538. mapping = self._find_map_for_dps(device.get_property(self.id), device)
  539. if mapping:
  540. scale = mapping.get("scale", 1)
  541. cond = self._active_condition(mapping, device)
  542. if cond:
  543. scale = cond.get("scale", scale)
  544. return scale
  545. def precision(self, device):
  546. if self.type is int:
  547. scale = self.scale(device)
  548. precision = 0
  549. while scale > 1.0:
  550. scale /= 10.0
  551. precision += 1
  552. return precision
  553. @property
  554. def suggested_display_precision(self):
  555. return self._config.get("precision")
  556. def step(self, device, scaled=True):
  557. step = 1
  558. scale = self.scale(device) if scaled else 1
  559. mapping = self._find_map_for_dps(device.get_property(self.id), device)
  560. if mapping:
  561. step = mapping.get("step", 1)
  562. cond = self._active_condition(mapping, device)
  563. if cond:
  564. step = cond.get("step", step)
  565. if step != 1 or scale != 1:
  566. _LOGGER.debug(
  567. "Step for %s is %s with scale %s",
  568. self.name,
  569. step,
  570. scale,
  571. )
  572. return step / scale if scaled else step
  573. @property
  574. def readonly(self):
  575. return self._config.get("readonly", False)
  576. def invalid_for(self, value, device):
  577. mapping = self._find_map_for_value(value, device)
  578. if mapping:
  579. cond = self._active_condition(mapping, device)
  580. if cond:
  581. return cond.get("invalid", False)
  582. return False
  583. @property
  584. def hidden(self):
  585. return self._config.get("hidden", False)
  586. @property
  587. def unit(self):
  588. return self._config.get("unit")
  589. @property
  590. def state_class(self):
  591. """The state class of this measurement."""
  592. return self._config.get("class")
  593. def _find_map_for_dps(self, value, device):
  594. default = None
  595. for m in self._config.get("mapping", {}):
  596. if not self.mapping_available(m, device) and "conditions" not in m:
  597. continue
  598. if "dps_val" not in m:
  599. default = m
  600. elif self._match(m["dps_val"], value):
  601. return m
  602. return default
  603. def _correct_type(self, result):
  604. """Convert value to the correct type for this dp."""
  605. if self.type is int:
  606. _LOGGER.debug("Rounding %s", self.name)
  607. result = int(round(result))
  608. elif self.type is bool:
  609. result = True if result else False
  610. elif self.type is float:
  611. result = float(result)
  612. elif self.type is str:
  613. result = str(result)
  614. if self.rawtype == "utf16b64":
  615. result = b64encode(result.encode("utf-16-be")).decode("utf-8")
  616. if self.stringify:
  617. result = str(result)
  618. return result
  619. def _map_from_dps(self, val, device):
  620. if val is not None and self.type is not str and isinstance(val, str):
  621. try:
  622. val = self.type(val)
  623. self.stringify = True
  624. except ValueError:
  625. self.stringify = False
  626. else:
  627. self.stringify = False
  628. # decode utf-16 base64 strings first, so normal strings can be matched
  629. if self.rawtype == "utf16b64" and isinstance(val, str):
  630. try:
  631. val = b64decode(val).decode("utf-16-be")
  632. except ValueError:
  633. _LOGGER.warning("Invalid utf16b64 %s", val)
  634. result = val
  635. scale = self.scale(device)
  636. replaced = False
  637. mapping = self._find_map_for_dps(val, device)
  638. if mapping:
  639. invert = mapping.get("invert", False)
  640. redirect = mapping.get("value_redirect")
  641. mirror = mapping.get("value_mirror")
  642. replaced = "value" in mapping
  643. result = mapping.get("value", result)
  644. target_range = mapping.get("target_range")
  645. cond = self._active_condition(mapping, device)
  646. if cond:
  647. if cond.get("invalid", False):
  648. return None
  649. replaced = replaced or "value" in cond
  650. result = cond.get("value", result)
  651. redirect = cond.get("value_redirect", redirect)
  652. mirror = cond.get("value_mirror", mirror)
  653. target_range = cond.get("target_range", target_range)
  654. for m in cond.get("mapping", {}):
  655. if str(m.get("dps_val")) == str(result):
  656. replaced = "value" in m
  657. result = m.get("value", result)
  658. if redirect:
  659. _LOGGER.debug("Redirecting %s to %s", self.name, redirect)
  660. r_dps = self._entity.find_dps(redirect)
  661. if r_dps:
  662. return r_dps.get_value(device)
  663. if mirror:
  664. r_dps = self._entity.find_dps(mirror)
  665. if r_dps:
  666. return r_dps.get_value(device)
  667. if invert and isinstance(result, Number):
  668. r = self._config.get("range")
  669. if r and "min" in r and "max" in r:
  670. result = -1 * result + r["min"] + r["max"]
  671. replaced = True
  672. if target_range and isinstance(result, Number):
  673. r = self._config.get("range")
  674. if r and "max" in r and "max" in target_range:
  675. from_min = r.get("min", 0)
  676. from_max = r["max"]
  677. to_min = target_range.get("min", 0)
  678. to_max = target_range["max"]
  679. result = to_min + (
  680. (result - from_min) * (to_max - to_min) / (from_max - from_min)
  681. )
  682. replaced = True
  683. if scale != 1 and isinstance(result, Number):
  684. result = result / scale
  685. replaced = True
  686. if self.rawtype == "unixtime" and isinstance(result, int):
  687. try:
  688. result = datetime.fromtimestamp(result)
  689. replaced = True
  690. except Exception:
  691. _LOGGER.warning("Invalid timestamp %d", result)
  692. if replaced:
  693. _LOGGER.debug(
  694. "%s: Mapped dps %s value from %s to %s",
  695. self._entity._device.name,
  696. self.id,
  697. val,
  698. result,
  699. )
  700. return result
  701. def _find_map_for_value(self, value, device):
  702. default = None
  703. nearest = None
  704. distance = float("inf")
  705. for m in self._config.get("mapping", {}):
  706. # no reverse mapping of hidden values
  707. ignore = m.get("hidden", False) or not self.mapping_available(m, device)
  708. if "dps_val" not in m and not ignore:
  709. default = m
  710. # The following avoids further matching on the above case
  711. # and in the null mapping case, which is intended to be
  712. # a one-way map to prevent the entity showing as unavailable
  713. # when no value is being reported by the device.
  714. if m.get("dps_val") is None:
  715. ignore = True
  716. if "value" in m and str(m["value"]) == str(value) and not ignore:
  717. return m
  718. if (
  719. "value" in m
  720. and isinstance(m["value"], Number)
  721. and isinstance(value, Number)
  722. and not ignore
  723. ):
  724. d = abs(m["value"] - value)
  725. if d < distance:
  726. distance = d
  727. nearest = m
  728. if "value" not in m and "value_mirror" in m and not ignore:
  729. r_dps = self._entity.find_dps(m["value_mirror"])
  730. if r_dps and str(r_dps.get_value(device)) == str(value):
  731. return m
  732. for c in m.get("conditions", {}):
  733. if c.get("hidden", False) or not self.mapping_available(c, device):
  734. continue
  735. if "value" in c and str(c["value"]) == str(value):
  736. c_dp = self._entity.find_dps(m.get("constraint", self.name))
  737. # only consider the condition a match if we can change
  738. # the dp to match, or it already matches
  739. if (c_dp and c_dp.id != self.id and not c_dp.readonly) or (
  740. _equal_or_in(
  741. device.get_property(c_dp.id),
  742. c.get("dps_val"),
  743. )
  744. ):
  745. return m
  746. if "value" not in c and "value_mirror" in c:
  747. r_dps = self._entity.find_dps(c["value_mirror"])
  748. if r_dps and str(r_dps.get_value(device)) == str(value):
  749. return m
  750. if nearest:
  751. return nearest
  752. return default
  753. def _active_condition(self, mapping, device, value=None):
  754. constraint = mapping.get("constraint", self.name)
  755. conditions = mapping.get("conditions")
  756. c_match = None
  757. if constraint and conditions:
  758. c_dps = self._entity.find_dps(constraint)
  759. # base64 and hex have to be decoded
  760. c_val = (
  761. None
  762. if c_dps is None
  763. else (
  764. c_dps.get_value(device)
  765. if c_dps.rawtype == "base64" or c_dps.rawtype == "hex"
  766. else device.get_property(c_dps.id)
  767. )
  768. )
  769. for cond in conditions:
  770. if not self.mapping_available(cond, device):
  771. continue
  772. if c_val is not None and (_equal_or_in(c_val, cond.get("dps_val"))):
  773. c_match = cond
  774. # Case where matching None, need extra checks to ensure we
  775. # are not just defaulting and it is really a match
  776. elif (
  777. c_val is None
  778. and c_dps is not None
  779. and "dps_val" in cond
  780. and cond.get("dps_val") is None
  781. ):
  782. c_match = cond
  783. # when changing, another condition may become active
  784. # return that if it exists over a current condition
  785. if value is not None and value == cond.get("value"):
  786. return cond
  787. return c_match
  788. def get_values_to_set(self, device, value):
  789. """Return the dps values that would be set when setting to value"""
  790. result = value
  791. dps_map = {}
  792. if self.readonly:
  793. return dps_map
  794. mapping = self._find_map_for_value(value, device)
  795. scale = self.scale(device)
  796. mask = self.mask
  797. if mapping:
  798. replaced = False
  799. redirect = mapping.get("value_redirect")
  800. invert = mapping.get("invert", False)
  801. target_range = mapping.get("target_range")
  802. step = mapping.get("step")
  803. if not isinstance(step, Number):
  804. step = None
  805. if "dps_val" in mapping:
  806. result = mapping["dps_val"]
  807. replaced = True
  808. # Conditions may have side effect of setting another value.
  809. cond = self._active_condition(mapping, device, value)
  810. if cond:
  811. cval = cond.get("value")
  812. if cval is None:
  813. r_dps = cond.get("value_mirror")
  814. if r_dps:
  815. mirror = self._entity.find_dps(r_dps)
  816. if mirror:
  817. cval = mirror.get_value(device)
  818. if cval == value:
  819. c_dps = self._entity.find_dps(mapping.get("constraint", self.name))
  820. cond_dpsval = cond.get("dps_val")
  821. single_match = isinstance(cond_dpsval, str) or (
  822. not isinstance(cond_dpsval, Sequence)
  823. )
  824. if c_dps and c_dps.id != self.id and single_match:
  825. c_val = c_dps._map_from_dps(
  826. cond.get("dps_val", device.get_property(c_dps.id)),
  827. device,
  828. )
  829. dps_map.update(c_dps.get_values_to_set(device, c_val))
  830. # Allow simple conditional mapping overrides
  831. for m in cond.get("mapping", {}):
  832. if m.get("value") == value and not m.get("hidden", False):
  833. result = m.get("dps_val", result)
  834. step = cond.get("step", step)
  835. redirect = cond.get("value_redirect", redirect)
  836. target_range = cond.get("target_range", target_range)
  837. if redirect:
  838. _LOGGER.debug("Redirecting %s to %s", self.name, redirect)
  839. r_dps = self._entity.find_dps(redirect)
  840. if r_dps:
  841. return r_dps.get_values_to_set(device, value)
  842. if scale != 1 and isinstance(result, Number):
  843. _LOGGER.debug("Scaling %s by %s", result, scale)
  844. result = result * scale
  845. remap = self._find_map_for_value(result, device)
  846. if (
  847. remap
  848. and "dps_val" in remap
  849. and "dps_val" not in mapping
  850. and not remap.get("hidden", False)
  851. ):
  852. result = remap["dps_val"]
  853. replaced = True
  854. if target_range and isinstance(result, Number):
  855. r = self._config.get("range")
  856. if r and "max" in r and "max" in target_range:
  857. from_min = target_range.get("min", 0)
  858. from_max = target_range["max"]
  859. to_min = r.get("min", 0)
  860. to_max = r["max"]
  861. result = to_min + (
  862. (result - from_min) * (to_max - to_min) / (from_max - from_min)
  863. )
  864. replaced = True
  865. if invert:
  866. r = self._config.get("range")
  867. if r and "min" in r and "max" in r:
  868. result = -1 * result + r["min"] + r["max"]
  869. replaced = True
  870. if step and isinstance(result, Number):
  871. _LOGGER.debug("Stepping %s to %s", result, step)
  872. result = step * round(float(result) / step)
  873. remap = self._find_map_for_value(result, device)
  874. if (
  875. remap
  876. and "dps_val" in remap
  877. and "dps_val" not in mapping
  878. and not remap.get("hidden", False)
  879. ):
  880. result = remap["dps_val"]
  881. replaced = True
  882. if replaced:
  883. _LOGGER.debug(
  884. "%s: Mapped dps %s to %s from %s",
  885. self._entity._device.name,
  886. self.id,
  887. result,
  888. value,
  889. )
  890. r = self.range(device, scaled=False)
  891. if r and isinstance(result, Number):
  892. mn = r[0]
  893. mx = r[1]
  894. if round(result) < mn or round(result) > mx:
  895. # Output scaled values in the error message
  896. r = self.range(device, scaled=True)
  897. mn = r[0]
  898. mx = r[1]
  899. raise ValueError(f"{self.name} ({value}) must be between {mn} and {mx}")
  900. if mask and isinstance(result, bool):
  901. result = int(result)
  902. if mask and isinstance(result, Number):
  903. # mask is in hex, 2 digits/characters per byte
  904. hex_mask = self._config.get("mask")
  905. length = int(len(hex_mask) / 2)
  906. # Convert to int
  907. endianness = self.endianness
  908. mask_scale = mask & (1 + ~mask)
  909. current_value = int.from_bytes(self.decoded_value(device), endianness)
  910. result = (current_value & ~mask) | (mask & int(result * mask_scale))
  911. result = self.encode_value(result.to_bytes(length, endianness))
  912. dps_map[self.id] = self._correct_type(result)
  913. return dps_map
  914. def icon_rule(self, device):
  915. mapping = self._find_map_for_dps(device.get_property(self.id), device)
  916. icon = None
  917. priority = 100
  918. if mapping:
  919. icon = mapping.get("icon", icon)
  920. priority = mapping.get("icon_priority", 10 if icon else 100)
  921. cond = self._active_condition(mapping, device)
  922. if cond and cond.get("icon_priority", 10) < priority:
  923. icon = cond.get("icon", icon)
  924. priority = cond.get("icon_priority", 10 if icon else 100)
  925. return {"priority": priority, "icon": icon}
  926. def available_configs():
  927. """List the available config files."""
  928. _CONFIG_DIR = dirname(config_dir.__file__)
  929. for direntry in scandir(_CONFIG_DIR):
  930. if direntry.is_file() and fnmatch(direntry.name, "*.yaml"):
  931. yield direntry.name
  932. def possible_matches(dps, product_ids=None):
  933. """Return possible matching configs for a given set of
  934. dps values and product_ids."""
  935. for cfg in available_configs():
  936. parsed = TuyaDeviceConfig(cfg)
  937. try:
  938. if parsed.matches(dps, product_ids):
  939. yield parsed
  940. except TypeError:
  941. _LOGGER.error("Parse error in %s", cfg)
  942. def get_config(conf_type):
  943. """
  944. Return a config to use with config_type.
  945. """
  946. _CONFIG_DIR = dirname(config_dir.__file__)
  947. fname = conf_type + ".yaml"
  948. fpath = join(_CONFIG_DIR, fname)
  949. if exists(fpath):
  950. return TuyaDeviceConfig(fname)
  951. else:
  952. return config_for_legacy_use(conf_type)
  953. def config_for_legacy_use(conf_type):
  954. """
  955. Return a config to use with config_type for legacy transition.
  956. Note: as there are two variants for Kogan Socket, this is not guaranteed
  957. to be the correct config for the device, so only use it for looking up
  958. the legacy class during the transition period.
  959. """
  960. for cfg in available_configs():
  961. parsed = TuyaDeviceConfig(cfg)
  962. if parsed.legacy_type == conf_type:
  963. return parsed
  964. return None