|
| 1 | +""" |
| 2 | +This module implements the generic actor. |
| 3 | +""" |
| 4 | + |
| 5 | +import typing as T |
| 6 | + |
| 7 | +import copy |
| 8 | + |
| 9 | +import voluptuous as vol |
| 10 | + |
| 11 | +from ... import common |
| 12 | +from .base import ActorBase |
| 13 | + |
| 14 | + |
| 15 | +ALLOWED_VALUE_TYPES = (bool, float, int, str, type(None)) |
| 16 | +ALLOWED_VALUE_TYPES_T = T.Union[ # pylint: disable=invalid-name |
| 17 | + bool, float, int, str, None |
| 18 | +] |
| 19 | +WILDCARD_ATTRIBUTE_VALUE = "*" |
| 20 | + |
| 21 | + |
| 22 | +class Generic2Actor(ActorBase): |
| 23 | + """A configurable, generic actor for Schedy that can control multiple |
| 24 | + attributes at once.""" |
| 25 | + |
| 26 | + name = "generic2" |
| 27 | + config_schema_dict = { |
| 28 | + **ActorBase.config_schema_dict, |
| 29 | + vol.Optional("attributes", default=None): vol.All( |
| 30 | + vol.DefaultTo(list), |
| 31 | + [ |
| 32 | + vol.All( |
| 33 | + vol.DefaultTo(dict), |
| 34 | + {vol.Optional("attribute", default=None): vol.Any(str, None)}, |
| 35 | + ) |
| 36 | + ], |
| 37 | + ), |
| 38 | + vol.Optional("values", default=None): vol.All( |
| 39 | + vol.DefaultTo(list), |
| 40 | + [ |
| 41 | + vol.All( |
| 42 | + vol.DefaultTo(dict), |
| 43 | + { |
| 44 | + vol.Required("value"): vol.All( |
| 45 | + [vol.Any(*ALLOWED_VALUE_TYPES)], vol.Coerce(tuple), |
| 46 | + ), |
| 47 | + vol.Optional("calls", default=None): vol.All( |
| 48 | + vol.DefaultTo(list), |
| 49 | + [ |
| 50 | + vol.All( |
| 51 | + vol.DefaultTo(dict), |
| 52 | + { |
| 53 | + vol.Required("service"): str, |
| 54 | + vol.Optional("data", default=None): vol.All( |
| 55 | + vol.DefaultTo(dict), dict |
| 56 | + ), |
| 57 | + vol.Optional( |
| 58 | + "include_entity_id", default=True |
| 59 | + ): bool, |
| 60 | + }, |
| 61 | + ) |
| 62 | + ], |
| 63 | + ), |
| 64 | + }, |
| 65 | + ) |
| 66 | + ], |
| 67 | + # Sort by number of attributes (descending) for longest prefix matching |
| 68 | + lambda v: sorted(v, key=lambda k: -len(k["value"])), |
| 69 | + ), |
| 70 | + vol.Optional("ignore_case", default=False): bool, |
| 71 | + } |
| 72 | + |
| 73 | + def _find_value_cfg(self, value: T.Tuple) -> T.Any: |
| 74 | + """Returns the config matching given value or ValueError if none found.""" |
| 75 | + for value_cfg in self.cfg["values"]: |
| 76 | + _value = value_cfg["value"] |
| 77 | + if len(_value) != len(value): |
| 78 | + continue |
| 79 | + for idx, attr_value in enumerate(_value): |
| 80 | + if attr_value not in (WILDCARD_ATTRIBUTE_VALUE, value[idx]): |
| 81 | + break |
| 82 | + else: |
| 83 | + return value_cfg |
| 84 | + raise ValueError("No configuration for value {!r}".format(value)) |
| 85 | + |
| 86 | + def _populate_service_data(self, data: T.Dict, fmt: T.Dict[str, T.Any]) -> None: |
| 87 | + """Fills in placeholders in the service data definition.""" |
| 88 | + # pylint: disable=too-many-nested-blocks |
| 89 | + memo = {data} # type: T.Set[T.Union[T.Dict, T.List]] |
| 90 | + while memo: |
| 91 | + obj = memo.pop() |
| 92 | + if isinstance(obj, dict): |
| 93 | + _iter = obj.items() # type: T.Iterable[T.Tuple[T.Any, T.Any]] |
| 94 | + elif isinstance(obj, list): |
| 95 | + _iter = enumerate(obj) |
| 96 | + else: |
| 97 | + continue |
| 98 | + for key, value in _iter: |
| 99 | + if isinstance(value, str): |
| 100 | + try: |
| 101 | + formatted = value.format(fmt) |
| 102 | + # Convert special values to appropriate type |
| 103 | + if formatted == "None": |
| 104 | + obj[key] = None |
| 105 | + elif formatted == "True": |
| 106 | + obj[key] = True |
| 107 | + elif formatted == "False": |
| 108 | + obj[key] = False |
| 109 | + else: |
| 110 | + try: |
| 111 | + _float = float(formatted) |
| 112 | + _int = int(formatted) |
| 113 | + except ValueError: |
| 114 | + # It's a string value |
| 115 | + obj[key] = formatted |
| 116 | + else: |
| 117 | + # It's an int or float |
| 118 | + obj[key] = _int if _float == _int else _float |
| 119 | + except (IndexError, KeyError, ValueError) as err: |
| 120 | + self.log( |
| 121 | + "Couldn't format service data {!r} with values " |
| 122 | + "{!r}: {!r}, omitting data.".format(value, fmt, err), |
| 123 | + level="ERROR", |
| 124 | + ) |
| 125 | + elif isinstance(value, (dict, list)): |
| 126 | + memo.add(value) |
| 127 | + |
| 128 | + def do_send(self) -> None: |
| 129 | + """Executes the configured services for self._wanted_value.""" |
| 130 | + value = self._wanted_value |
| 131 | + # Build formatting data with values of all attributes |
| 132 | + fmt = {"entity_id": self.entity_id} |
| 133 | + for idx in range(len(self.cfg["attributes"])): |
| 134 | + fmt["attr{}".format(idx + 1)] = value[idx] if idx < len(value) else None |
| 135 | + |
| 136 | + for call_cfg in self._find_value_cfg(value)["calls"]: |
| 137 | + service = call_cfg["service"] |
| 138 | + data = copy.deepcopy(call_cfg["data"]) |
| 139 | + self._populate_service_data(data, fmt) |
| 140 | + if call_cfg["include_entity_id"]: |
| 141 | + data.setdefault("entity_id", self.entity_id) |
| 142 | + self.log( |
| 143 | + "Calling service {}, data = {}.".format(repr(service), repr(data)), |
| 144 | + level="DEBUG", |
| 145 | + prefix=common.LOG_PREFIX_OUTGOING, |
| 146 | + ) |
| 147 | + self.app.call_service(service, **data) |
| 148 | + |
| 149 | + def filter_set_value(self, value: T.Tuple) -> T.Any: |
| 150 | + """Checks whether the actor supports this value.""" |
| 151 | + if self.cfg["ignore_case"]: |
| 152 | + value = tuple(v.lower() if isinstance(v, str) else v for v in value) |
| 153 | + try: |
| 154 | + self._find_value_cfg(value) |
| 155 | + except ValueError: |
| 156 | + self.log( |
| 157 | + "Value {!r} is not known by this actor.".format(value), level="ERROR" |
| 158 | + ) |
| 159 | + return None |
| 160 | + return value |
| 161 | + |
| 162 | + def notify_state_changed(self, attrs: dict) -> T.Any: |
| 163 | + """Is called when the entity's state changes.""" |
| 164 | + items = [] |
| 165 | + for attr_cfg in self.cfg["attributes"]: |
| 166 | + attr = attr_cfg["attribute"] |
| 167 | + if attr is None: |
| 168 | + self.log("Ignoring state change (write-only attribute).", level="DEBUG") |
| 169 | + return None |
| 170 | + state = attrs.get(attr) |
| 171 | + self.log( |
| 172 | + "Attribute {!r} is {!r}.".format(attr, state), |
| 173 | + level="DEBUG", |
| 174 | + prefix=common.LOG_PREFIX_INCOMING, |
| 175 | + ) |
| 176 | + if self.cfg["ignore_case"] and isinstance(state, str): |
| 177 | + state = state.lower() |
| 178 | + items.append(state) |
| 179 | + |
| 180 | + tpl = tuple(items) |
| 181 | + # Goes from len(tpl) down to 0 |
| 182 | + for size in range(len(tpl), -1, -1): |
| 183 | + value = tpl[:size] |
| 184 | + try: |
| 185 | + self._find_value_cfg(value) |
| 186 | + except ValueError: |
| 187 | + continue |
| 188 | + return value |
| 189 | + |
| 190 | + self.log( |
| 191 | + "Received state {!r} which is not configured as a value.".format(items), |
| 192 | + level="WARNING", |
| 193 | + ) |
| 194 | + return None |
| 195 | + |
| 196 | + @staticmethod |
| 197 | + def validate_value(value: T.Any) -> T.Any: |
| 198 | + """Converts lists to tuples.""" |
| 199 | + if isinstance(value, list): |
| 200 | + items = tuple(value) |
| 201 | + elif isinstance(value, tuple): |
| 202 | + items = value |
| 203 | + else: |
| 204 | + items = (value,) |
| 205 | + |
| 206 | + for index, item in enumerate(items): |
| 207 | + if not isinstance(item, ALLOWED_VALUE_TYPES): |
| 208 | + raise ValueError( |
| 209 | + "Value {!r} for {}. attribute must be of one of these types: " |
| 210 | + "{}".format(item, index + 1, ALLOWED_VALUE_TYPES) |
| 211 | + ) |
| 212 | + return items |
0 commit comments