device_config.py 38 KB

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