device_config.py 36 KB

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