device_config.py 34 KB

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