device_config.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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 entity, 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. def available(self, device):
  262. """Return whether this entity should be available, with state as given."""
  263. avail_dp = self.find_dps("available")
  264. if avail_dp and device.has_returned_state:
  265. return avail_dp.get_value(device)
  266. return True
  267. class TuyaDpsConfig:
  268. """Representation of a dps config."""
  269. def __init__(self, entity, config):
  270. self._entity = entity
  271. self._config = config
  272. self.stringify = False
  273. @property
  274. def id(self):
  275. return str(self._config["id"])
  276. @property
  277. def type(self):
  278. t = self._config["type"]
  279. types = {
  280. "boolean": bool,
  281. "integer": int,
  282. "string": str,
  283. "float": float,
  284. "bitfield": int,
  285. "json": str,
  286. "base64": str,
  287. "utf16b64": str,
  288. "hex": str,
  289. "unixtime": int,
  290. }
  291. return types.get(t)
  292. @property
  293. def rawtype(self):
  294. return self._config["type"]
  295. @property
  296. def name(self):
  297. return self._config["name"]
  298. @property
  299. def optional(self):
  300. return self._config.get("optional", False)
  301. @property
  302. def persist(self):
  303. return self._config.get("persist", True)
  304. @property
  305. def force(self):
  306. return self._config.get("force", False)
  307. @property
  308. def sensitive(self):
  309. return self._config.get("sensitive", False)
  310. @property
  311. def format(self):
  312. fmt = self._config.get("format")
  313. if fmt:
  314. unpack_fmt = ">"
  315. ranges = []
  316. names = []
  317. for f in fmt:
  318. name = f.get("name")
  319. b = f.get("bytes", 1)
  320. r = f.get("range")
  321. if r:
  322. mn = r.get("min")
  323. mx = r.get("max")
  324. else:
  325. mn = 0
  326. mx = 256**b - 1
  327. unpack_fmt = unpack_fmt + _bytes_to_fmt(b, mn < 0)
  328. ranges.append({"min": mn, "max": mx})
  329. names.append(name)
  330. _LOGGER.debug("format of %s found", unpack_fmt)
  331. return {"format": unpack_fmt, "ranges": ranges, "names": names}
  332. return None
  333. def mask(self, device):
  334. mapping = self._find_map_for_dps(device.get_property(self.id))
  335. if mapping:
  336. mask = mapping.get("mask")
  337. if mask:
  338. return int(mask, 16)
  339. def endianness(self, device):
  340. mapping = self._find_map_for_dps(device.get_property(self.id))
  341. if mapping:
  342. endianness = mapping.get("endianness")
  343. if endianness:
  344. return endianness
  345. return "big"
  346. def get_value(self, device):
  347. """Return the value of the dps from the given device."""
  348. mask = self.mask(device)
  349. bytevalue = self.decoded_value(device)
  350. if mask and isinstance(bytevalue, bytes):
  351. value = int.from_bytes(bytevalue, self.endianness(device))
  352. scale = mask & (1 + ~mask)
  353. return self._map_from_dps((value & mask) // scale, device)
  354. else:
  355. return self._map_from_dps(device.get_property(self.id), device)
  356. def decoded_value(self, device):
  357. v = self._map_from_dps(device.get_property(self.id), device)
  358. if self.rawtype == "hex" and isinstance(v, str):
  359. try:
  360. return bytes.fromhex(v)
  361. except ValueError:
  362. _LOGGER.warning(
  363. "%s sent invalid hex '%s' for %s",
  364. device.name,
  365. v,
  366. self.name,
  367. )
  368. return None
  369. elif self.rawtype == "base64" and isinstance(v, str):
  370. try:
  371. return b64decode(v)
  372. except ValueError:
  373. _LOGGER.warning(
  374. "%s sent invalid base64 '%s' for %s",
  375. device.name,
  376. v,
  377. self.name,
  378. )
  379. return None
  380. else:
  381. return v
  382. def encode_value(self, v):
  383. if self.rawtype == "hex":
  384. return v.hex()
  385. elif self.rawtype == "base64":
  386. return b64encode(v).decode("utf-8")
  387. elif self.rawtype == "unixtime" and isinstance(v, datetime):
  388. return v.timestamp()
  389. else:
  390. return v
  391. def _match(self, matchdata, value):
  392. """Return true val1 matches val2"""
  393. if self.rawtype == "bitfield" and matchdata:
  394. try:
  395. return (int(value) & int(matchdata)) != 0
  396. except (TypeError, ValueError):
  397. return False
  398. else:
  399. return str(value) == str(matchdata)
  400. async def async_set_value(self, device, value):
  401. """Set the value of the dps in the given device to given value."""
  402. if self.readonly:
  403. raise TypeError(f"{self.name} is read only")
  404. if self.invalid_for(value, device):
  405. raise AttributeError(f"{self.name} cannot be set at this time")
  406. settings = self.get_values_to_set(device, value)
  407. await device.async_set_properties(settings)
  408. def should_show_mapping(self, mapping, device):
  409. """Determine if this mapping should be shown in the list of values."""
  410. if "value" not in mapping or mapping.get("hidden", False):
  411. return False
  412. avail_dp = self._entity.find_dps(mapping.get("available"))
  413. return avail_dp.get_value(device) if avail_dp else True
  414. def values(self, device):
  415. """Return the possible values a dps can take."""
  416. if "mapping" not in self._config.keys():
  417. _LOGGER.debug(
  418. "No mapping for dpid %s (%s), unable to determine valid values",
  419. self.id,
  420. self.name,
  421. )
  422. return []
  423. val = []
  424. for m in self._config["mapping"]:
  425. if self.should_show_mapping(m, device):
  426. val.append(m["value"])
  427. # If there is mirroring without override, include mirrored values
  428. elif "value_mirror" in m:
  429. r_dps = self._entity.find_dps(m["value_mirror"])
  430. if r_dps:
  431. val = val + r_dps.values(device)
  432. for c in m.get("conditions", {}):
  433. if self.should_show_mapping(c, device):
  434. val.append(c["value"])
  435. elif "value_mirror" in c:
  436. r_dps = self._entity.find_dps(c["value_mirror"])
  437. if r_dps:
  438. val = val + r_dps.values(device)
  439. cond = self._active_condition(m, device)
  440. if cond and "mapping" in cond:
  441. _LOGGER.debug("Considering conditional mappings")
  442. c_val = []
  443. for m2 in cond["mapping"]:
  444. if self.should_show_mapping(m2, device):
  445. c_val.append(m2["value"])
  446. elif "value_mirror" in m:
  447. r_dps = self._entity.find_dps(m["value_mirror"])
  448. if r_dps:
  449. c_val = c_val + r_dps.values(device)
  450. # if given, the conditional mapping is an override
  451. if c_val:
  452. _LOGGER.debug(
  453. "Overriding %s values %s with %s",
  454. self.name,
  455. val,
  456. c_val,
  457. )
  458. val = c_val
  459. break
  460. _LOGGER.debug("%s values: %s", self.name, val)
  461. return _remove_duplicates(val)
  462. @property
  463. def default(self):
  464. """Return the default value for a dp."""
  465. if "mapping" not in self._config.keys():
  466. _LOGGER.debug(
  467. "No mapping for %s, unable to determine default value",
  468. self.name,
  469. )
  470. return None
  471. for m in self._config["mapping"]:
  472. if m.get("default", False):
  473. return m.get("value", m.get("dps_val", None))
  474. for c in m.get("conditions", {}):
  475. if c.get("default", False):
  476. return c.get("value", m.get("value", m.get("dps_val", None)))
  477. def range(self, device, scaled=True):
  478. """Return the range for this dps if configured."""
  479. scale = self.scale(device) if scaled else 1
  480. mapping = self._find_map_for_dps(device.get_property(self.id))
  481. r = self._config.get("range")
  482. if mapping:
  483. _LOGGER.debug("Considering mapping for range of %s", self.name)
  484. cond = self._active_condition(mapping, device)
  485. if cond:
  486. r = cond.get("range", r)
  487. if r and "min" in r and "max" in r:
  488. return _scale_range(r, scale)
  489. else:
  490. return None
  491. def scale(self, device):
  492. scale = 1
  493. mapping = self._find_map_for_dps(device.get_property(self.id))
  494. if mapping:
  495. scale = mapping.get("scale", 1)
  496. cond = self._active_condition(mapping, device)
  497. if cond:
  498. scale = cond.get("scale", scale)
  499. return scale
  500. def precision(self, device):
  501. if self.type is int:
  502. scale = self.scale(device)
  503. precision = 0
  504. while scale > 1.0:
  505. scale /= 10.0
  506. precision += 1
  507. return precision
  508. @property
  509. def suggested_display_precision(self):
  510. return self._config.get("precision")
  511. def step(self, device, scaled=True):
  512. step = 1
  513. scale = self.scale(device) if scaled else 1
  514. mapping = self._find_map_for_dps(device.get_property(self.id))
  515. if mapping:
  516. _LOGGER.debug("Considering mapping for step of %s", self.name)
  517. step = mapping.get("step", 1)
  518. cond = self._active_condition(mapping, device)
  519. if cond:
  520. constraint = mapping.get("constraint", self.name)
  521. _LOGGER.debug("Considering condition on %s", constraint)
  522. step = cond.get("step", step)
  523. if step != 1 or scale != 1:
  524. _LOGGER.debug(
  525. "Step for %s is %s with scale %s",
  526. self.name,
  527. step,
  528. scale,
  529. )
  530. return step / scale if scaled else step
  531. @property
  532. def readonly(self):
  533. return self._config.get("readonly", False)
  534. def invalid_for(self, value, device):
  535. mapping = self._find_map_for_value(value, device)
  536. if mapping:
  537. cond = self._active_condition(mapping, device)
  538. if cond:
  539. return cond.get("invalid", False)
  540. return False
  541. @property
  542. def hidden(self):
  543. return self._config.get("hidden", False)
  544. @property
  545. def unit(self):
  546. return self._config.get("unit")
  547. @property
  548. def state_class(self):
  549. """The state class of this measurement."""
  550. return self._config.get("class")
  551. def _find_map_for_dps(self, value):
  552. default = None
  553. for m in self._config.get("mapping", {}):
  554. if "dps_val" not in m:
  555. default = m
  556. elif self._match(m["dps_val"], value):
  557. return m
  558. return default
  559. def _correct_type(self, result):
  560. """Convert value to the correct type for this dp."""
  561. if self.type is int:
  562. _LOGGER.debug("Rounding %s", self.name)
  563. result = int(round(result))
  564. elif self.type is bool:
  565. result = True if result else False
  566. elif self.type is float:
  567. result = float(result)
  568. elif self.type is str:
  569. result = str(result)
  570. if self.rawtype == "utf16b64":
  571. result = b64encode(result.encode("utf-16-be")).decode("utf-8")
  572. if self.stringify:
  573. result = str(result)
  574. return result
  575. def _map_from_dps(self, val, device):
  576. if val is not None and self.type is not str and isinstance(val, str):
  577. try:
  578. val = self.type(val)
  579. self.stringify = True
  580. except ValueError:
  581. self.stringify = False
  582. else:
  583. self.stringify = False
  584. # decode utf-16 base64 strings first, so normal strings can be matched
  585. if self.rawtype == "utf16b64" and isinstance(val, str):
  586. try:
  587. val = b64decode(val).decode("utf-16-be")
  588. except ValueError:
  589. _LOGGER.warning("Invalid utf16b64 %s", val)
  590. result = val
  591. scale = self.scale(device)
  592. replaced = False
  593. mapping = self._find_map_for_dps(val)
  594. if mapping:
  595. invert = mapping.get("invert", False)
  596. redirect = mapping.get("value_redirect")
  597. mirror = mapping.get("value_mirror")
  598. replaced = "value" in mapping
  599. result = mapping.get("value", result)
  600. target_range = mapping.get("target_range")
  601. cond = self._active_condition(mapping, device)
  602. if cond:
  603. if cond.get("invalid", False):
  604. return None
  605. replaced = replaced or "value" in cond
  606. result = cond.get("value", result)
  607. redirect = cond.get("value_redirect", redirect)
  608. mirror = cond.get("value_mirror", mirror)
  609. target_range = cond.get("target_range", target_range)
  610. for m in cond.get("mapping", {}):
  611. if str(m.get("dps_val")) == str(result):
  612. replaced = "value" in m
  613. result = m.get("value", result)
  614. if redirect:
  615. _LOGGER.debug("Redirecting %s to %s", self.name, redirect)
  616. r_dps = self._entity.find_dps(redirect)
  617. if r_dps:
  618. return r_dps.get_value(device)
  619. if mirror:
  620. r_dps = self._entity.find_dps(mirror)
  621. if r_dps:
  622. return r_dps.get_value(device)
  623. if invert and isinstance(result, Number):
  624. r = self._config.get("range")
  625. if r and "min" in r and "max" in r:
  626. result = -1 * result + r["min"] + r["max"]
  627. replaced = True
  628. if target_range and isinstance(result, Number):
  629. r = self._config.get("range")
  630. if r and "max" in r and "max" in target_range:
  631. from_min = r.get("min", 0)
  632. from_max = r["max"]
  633. to_min = target_range.get("min", 0)
  634. to_max = target_range["max"]
  635. result = to_min + (
  636. (result - from_min) * (to_max - to_min) / (from_max - from_min)
  637. )
  638. replaced = True
  639. if scale != 1 and isinstance(result, Number):
  640. result = result / scale
  641. replaced = True
  642. if self.rawtype == "unixtime" and isinstance(result, int):
  643. try:
  644. result = datetime.fromtimestamp(result)
  645. replaced = True
  646. except Exception:
  647. _LOGGER.warning("Invalid timestamp %d", result)
  648. if replaced:
  649. _LOGGER.debug(
  650. "%s: Mapped dps %s value from %s to %s",
  651. self._entity._device.name,
  652. self.id,
  653. val,
  654. result,
  655. )
  656. return result
  657. def _find_map_for_value(self, value, device):
  658. default = None
  659. nearest = None
  660. distance = float("inf")
  661. for m in self._config.get("mapping", {}):
  662. if "dps_val" not in m:
  663. default = m
  664. # The following avoids further matching on the above case
  665. # and in the null mapping case, which is intended to be
  666. # a one-way map to prevent the entity showing as unavailable
  667. # when no value is being reported by the device.
  668. if m.get("dps_val") is None:
  669. continue
  670. if "value" in m and str(m["value"]) == str(value):
  671. return m
  672. if (
  673. "value" in m
  674. and isinstance(m["value"], Number)
  675. and isinstance(value, Number)
  676. ):
  677. d = abs(m["value"] - value)
  678. if d < distance:
  679. distance = d
  680. nearest = m
  681. if "value" not in m and "value_mirror" in m:
  682. r_dps = self._entity.find_dps(m["value_mirror"])
  683. if r_dps and str(r_dps.get_value(device)) == str(value):
  684. return m
  685. for c in m.get("conditions", {}):
  686. if "value" in c and str(c["value"]) == str(value):
  687. c_dp = self._entity.find_dps(m.get("constraint", self.name))
  688. # only consider the condition a match if we can change
  689. # the dp to match, or it already matches
  690. if (c_dp and c_dp.id != self.id and not c_dp.readonly) or (
  691. _equal_or_in(
  692. device.get_property(c_dp.id),
  693. c.get("dps_val"),
  694. )
  695. ):
  696. return m
  697. if "value" not in c and "value_mirror" in c:
  698. r_dps = self._entity.find_dps(c["value_mirror"])
  699. if r_dps and str(r_dps.get_value(device)) == str(value):
  700. return m
  701. if nearest:
  702. return nearest
  703. return default
  704. def _active_condition(self, mapping, device, value=None):
  705. constraint = mapping.get("constraint", self.name)
  706. conditions = mapping.get("conditions")
  707. c_match = None
  708. if constraint and conditions:
  709. c_dps = self._entity.find_dps(constraint)
  710. # base64 and hex have to be decoded
  711. c_val = (
  712. None
  713. if c_dps is None
  714. else (
  715. c_dps.get_value(device)
  716. if c_dps.rawtype == "base64" or c_dps.rawtype == "hex"
  717. else device.get_property(c_dps.id)
  718. )
  719. )
  720. for cond in conditions:
  721. if c_val is not None and (_equal_or_in(c_val, cond.get("dps_val"))):
  722. c_match = cond
  723. # Case where matching None, need extra checks to ensure we
  724. # are not just defaulting and it is really a match
  725. elif (
  726. c_val is None
  727. and c_dps is not None
  728. and "dps_val" in cond
  729. and cond.get("dps_val") is None
  730. ):
  731. c_match = cond
  732. # when changing, another condition may become active
  733. # return that if it exists over a current condition
  734. if value is not None and value == cond.get("value"):
  735. return cond
  736. return c_match
  737. def get_values_to_set(self, device, value):
  738. """Return the dps values that would be set when setting to value"""
  739. result = value
  740. dps_map = {}
  741. if self.readonly:
  742. return dps_map
  743. mapping = self._find_map_for_value(value, device)
  744. scale = self.scale(device)
  745. mask = None
  746. if mapping:
  747. replaced = False
  748. redirect = mapping.get("value_redirect")
  749. invert = mapping.get("invert", False)
  750. mask = mapping.get("mask")
  751. endianness = mapping.get("endianness", "big")
  752. target_range = mapping.get("target_range")
  753. step = mapping.get("step")
  754. if not isinstance(step, Number):
  755. step = None
  756. if "dps_val" in mapping and not mapping.get("hidden", False):
  757. result = mapping["dps_val"]
  758. replaced = True
  759. # Conditions may have side effect of setting another value.
  760. cond = self._active_condition(mapping, device, value)
  761. if cond:
  762. cval = cond.get("value")
  763. if cval is None:
  764. r_dps = cond.get("value_mirror")
  765. if r_dps:
  766. mirror = self._entity.find_dps(r_dps)
  767. if mirror:
  768. cval = mirror.get_value(device)
  769. if cval == value:
  770. c_dps = self._entity.find_dps(mapping.get("constraint", self.name))
  771. cond_dpsval = cond.get("dps_val")
  772. single_match = isinstance(cond_dpsval, str) or (
  773. not isinstance(cond_dpsval, Sequence)
  774. )
  775. if c_dps and c_dps.id != self.id and single_match:
  776. c_val = c_dps._map_from_dps(
  777. cond.get("dps_val", device.get_property(c_dps.id)),
  778. device,
  779. )
  780. dps_map.update(c_dps.get_values_to_set(device, c_val))
  781. # Allow simple conditional mapping overrides
  782. for m in cond.get("mapping", {}):
  783. if m.get("value") == value and not m.get("hidden", False):
  784. result = m.get("dps_val", result)
  785. step = cond.get("step", step)
  786. redirect = cond.get("value_redirect", redirect)
  787. target_range = cond.get("target_range", target_range)
  788. if redirect:
  789. _LOGGER.debug("Redirecting %s to %s", self.name, redirect)
  790. r_dps = self._entity.find_dps(redirect)
  791. if r_dps:
  792. return r_dps.get_values_to_set(device, value)
  793. if scale != 1 and isinstance(result, Number):
  794. _LOGGER.debug("Scaling %s by %s", result, scale)
  795. result = result * scale
  796. remap = self._find_map_for_value(result, device)
  797. if (
  798. remap
  799. and "dps_val" in remap
  800. and "dps_val" not in mapping
  801. and not remap.get("hidden", False)
  802. ):
  803. result = remap["dps_val"]
  804. replaced = True
  805. if target_range and isinstance(result, Number):
  806. r = self._config.get("range")
  807. if r and "max" in r and "max" in target_range:
  808. from_min = target_range.get("min", 0)
  809. from_max = target_range["max"]
  810. to_min = r.get("min", 0)
  811. to_max = r["max"]
  812. result = to_min + (
  813. (result - from_min) * (to_max - to_min) / (from_max - from_min)
  814. )
  815. replaced = True
  816. if invert:
  817. r = self._config.get("range")
  818. if r and "min" in r and "max" in r:
  819. result = -1 * result + r["min"] + r["max"]
  820. replaced = True
  821. if step and isinstance(result, Number):
  822. _LOGGER.debug("Stepping %s to %s", result, step)
  823. result = step * round(float(result) / step)
  824. remap = self._find_map_for_value(result, device)
  825. if (
  826. remap
  827. and "dps_val" in remap
  828. and "dps_val" not in mapping
  829. and not remap.get("hidden", False)
  830. ):
  831. result = remap["dps_val"]
  832. replaced = True
  833. if replaced:
  834. _LOGGER.debug(
  835. "%s: Mapped dps %s to %s from %s",
  836. self._entity._device.name,
  837. self.id,
  838. result,
  839. value,
  840. )
  841. r = self.range(device, scaled=False)
  842. if r and isinstance(result, Number):
  843. mn = r[0]
  844. mx = r[1]
  845. if round(result) < mn or round(result) > mx:
  846. # Output scaled values in the error message
  847. r = self.range(device, scaled=True)
  848. mn = r[0]
  849. mx = r[1]
  850. raise ValueError(f"{self.name} ({value}) must be between {mn} and {mx}")
  851. if mask and isinstance(result, Number):
  852. # mask is in hex, 2 digits/characters per byte
  853. length = int(len(mask) / 2)
  854. # Convert to int
  855. mask = int(mask, 16)
  856. mask_scale = mask & (1 + ~mask)
  857. current_value = int.from_bytes(self.decoded_value(device), endianness)
  858. result = (current_value & ~mask) | (mask & int(result * mask_scale))
  859. result = self.encode_value(result.to_bytes(length, endianness))
  860. dps_map[self.id] = self._correct_type(result)
  861. return dps_map
  862. def icon_rule(self, device):
  863. mapping = self._find_map_for_dps(device.get_property(self.id))
  864. icon = None
  865. priority = 100
  866. if mapping:
  867. icon = mapping.get("icon", icon)
  868. priority = mapping.get("icon_priority", 10 if icon else 100)
  869. cond = self._active_condition(mapping, device)
  870. if cond and cond.get("icon_priority", 10) < priority:
  871. icon = cond.get("icon", icon)
  872. priority = cond.get("icon_priority", 10 if icon else 100)
  873. return {"priority": priority, "icon": icon}
  874. def available_configs():
  875. """List the available config files."""
  876. _CONFIG_DIR = dirname(config_dir.__file__)
  877. for path, dirs, files in walk(_CONFIG_DIR):
  878. for basename in sorted(files):
  879. if fnmatch(basename, "*.yaml"):
  880. yield basename
  881. def possible_matches(dps):
  882. """Return possible matching configs for a given set of dps values."""
  883. for cfg in available_configs():
  884. parsed = TuyaDeviceConfig(cfg)
  885. try:
  886. if parsed.matches(dps):
  887. yield parsed
  888. except TypeError:
  889. _LOGGER.error("Parse error in %s", cfg)
  890. def get_config(conf_type):
  891. """
  892. Return a config to use with config_type.
  893. """
  894. _CONFIG_DIR = dirname(config_dir.__file__)
  895. fname = conf_type + ".yaml"
  896. fpath = join(_CONFIG_DIR, fname)
  897. if exists(fpath):
  898. return TuyaDeviceConfig(fname)
  899. else:
  900. return config_for_legacy_use(conf_type)
  901. def config_for_legacy_use(conf_type):
  902. """
  903. Return a config to use with config_type for legacy transition.
  904. Note: as there are two variants for Kogan Socket, this is not guaranteed
  905. to be the correct config for the device, so only use it for looking up
  906. the legacy class during the transition period.
  907. """
  908. for cfg in available_configs():
  909. parsed = TuyaDeviceConfig(cfg)
  910. if parsed.legacy_type == conf_type:
  911. return parsed
  912. return None