device_config.py 37 KB

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