device_config.py 38 KB

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