device_config.py 37 KB

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