device_config.py 35 KB

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