Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helpers to deal with bayesian observations."""
2 
3 from __future__ import annotations
4 
5 from dataclasses import dataclass, field
6 import uuid
7 
8 from homeassistant.const import (
9  CONF_ABOVE,
10  CONF_BELOW,
11  CONF_ENTITY_ID,
12  CONF_PLATFORM,
13  CONF_VALUE_TEMPLATE,
14 )
15 from homeassistant.helpers.template import Template
16 
17 from .const import CONF_P_GIVEN_F, CONF_P_GIVEN_T, CONF_TO_STATE
18 
19 
20 @dataclass
22  """Representation of a sensor or template observation.
23 
24  Either entity_id or value_template should be non-None.
25  """
26 
27  entity_id: str | None
28  platform: str
29  prob_given_true: float
30  prob_given_false: float
31  to_state: str | None
32  above: float | None
33  below: float | None
34  value_template: Template | None
35  observed: bool | None = None
36  multi: bool = False
37  id: uuid.UUID = field(default_factory=uuid.uuid4)
38 
39  def to_dict(self) -> dict[str, str | float | bool | None]:
40  """Represent Class as a Dict for easier serialization."""
41 
42  # Needed because dataclasses asdict() can't serialize Templates and ignores Properties.
43  dic = {
44  CONF_PLATFORM: self.platformplatform,
45  CONF_ENTITY_ID: self.entity_id,
46  CONF_VALUE_TEMPLATE: self.templatetemplate,
47  CONF_TO_STATE: self.to_state,
48  CONF_ABOVE: self.above,
49  CONF_BELOW: self.below,
50  CONF_P_GIVEN_T: self.prob_given_true,
51  CONF_P_GIVEN_F: self.prob_given_false,
52  "observed": self.observed,
53  }
54 
55  for key, value in dic.copy().items():
56  if value is None:
57  del dic[key]
58 
59  return dic
60 
61  def is_mirror(self, other: Observation) -> bool:
62  """Dectects whether given observation is a mirror of this one."""
63  return (
64  self.platformplatform == other.platform
65  and round(self.prob_given_true + other.prob_given_true, 1) == 1
66  and round(self.prob_given_false + other.prob_given_false, 1) == 1
67  )
68 
69  @property
70  def template(self) -> str | None:
71  """Not all observations have templates and we want to get template strings."""
72  if self.value_template is not None:
73  return self.value_template.template
74  return None
dict[str, str|float|bool|None] to_dict(self)
Definition: helpers.py:39
bool is_mirror(self, Observation other)
Definition: helpers.py:61