state.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # -*- coding: utf-8 -*-
  2. """
  3. State Conditions - Zustandsbasierte Bedingungen.
  4. """
  5. from typing import Any
  6. from trixy_core.scheduler.condition.base import Condition
  7. class StateCondition(Condition):
  8. """
  9. Prüft ob System/Komponente in bestimmtem Zustand ist.
  10. Beispiel:
  11. - StateCondition("satellite_kitchen", "connected")
  12. - StateCondition("system_mode", ["active", "standby"])
  13. """
  14. def __init__(
  15. self,
  16. state_key: str,
  17. expected_state: str | list[str],
  18. name: str | None = None,
  19. invert: bool = False,
  20. ):
  21. """
  22. Initialisiert die Condition.
  23. Args:
  24. state_key: Schlüssel für Zustand im Kontext
  25. expected_state: Erwarteter Zustand oder Liste
  26. name: Condition-Name
  27. invert: Ergebnis invertieren
  28. """
  29. super().__init__(name, invert)
  30. self._state_key = state_key
  31. if isinstance(expected_state, str):
  32. self._expected_states = [expected_state]
  33. else:
  34. self._expected_states = list(expected_state)
  35. @property
  36. def state_key(self) -> str:
  37. """Zustands-Schlüssel."""
  38. return self._state_key
  39. @property
  40. def expected_states(self) -> list[str]:
  41. """Erwartete Zustände."""
  42. return list(self._expected_states)
  43. def _evaluate(self, context: dict) -> bool:
  44. """Prüft ob Zustand erwartet ist."""
  45. current_state = context.get(self._state_key)
  46. if current_state is None:
  47. return False
  48. # String-Vergleich (case-insensitive)
  49. current_str = str(current_state).lower()
  50. return any(
  51. s.lower() == current_str
  52. for s in self._expected_states
  53. )
  54. def to_dict(self) -> dict:
  55. """Konvertiert zu Dictionary."""
  56. return {
  57. **self._base_dict(),
  58. "state_key": self._state_key,
  59. "expected_states": self._expected_states,
  60. }
  61. @classmethod
  62. def from_dict(cls, data: dict) -> "StateCondition":
  63. """Erstellt Condition aus Dictionary."""
  64. return cls(
  65. state_key=data["state_key"],
  66. expected_state=data["expected_states"],
  67. name=data.get("name"),
  68. invert=data.get("invert", False),
  69. )
  70. class BooleanCondition(Condition):
  71. """
  72. Prüft ob Boolean-Flag gesetzt ist.
  73. Beispiel:
  74. - BooleanCondition("is_home") - Nur wenn zu Hause
  75. - BooleanCondition("debug_mode", expected=False) - Nur wenn kein Debug
  76. """
  77. def __init__(
  78. self,
  79. flag_key: str,
  80. expected: bool = True,
  81. name: str | None = None,
  82. invert: bool = False,
  83. ):
  84. """
  85. Initialisiert die Condition.
  86. Args:
  87. flag_key: Schlüssel für Flag im Kontext
  88. expected: Erwarteter Wert (default: True)
  89. name: Condition-Name
  90. invert: Ergebnis invertieren
  91. """
  92. super().__init__(name, invert)
  93. self._flag_key = flag_key
  94. self._expected = expected
  95. @property
  96. def flag_key(self) -> str:
  97. """Flag-Schlüssel."""
  98. return self._flag_key
  99. @property
  100. def expected(self) -> bool:
  101. """Erwarteter Wert."""
  102. return self._expected
  103. def _evaluate(self, context: dict) -> bool:
  104. """Prüft ob Flag erwartet ist."""
  105. value = context.get(self._flag_key)
  106. # None behandeln
  107. if value is None:
  108. return not self._expected
  109. # Boolean konvertieren
  110. if isinstance(value, bool):
  111. return value == self._expected
  112. elif isinstance(value, str):
  113. truthy = value.lower() in ("true", "1", "yes", "on")
  114. return truthy == self._expected
  115. elif isinstance(value, (int, float)):
  116. return bool(value) == self._expected
  117. return False
  118. def to_dict(self) -> dict:
  119. """Konvertiert zu Dictionary."""
  120. return {
  121. **self._base_dict(),
  122. "flag_key": self._flag_key,
  123. "expected": self._expected,
  124. }
  125. @classmethod
  126. def from_dict(cls, data: dict) -> "BooleanCondition":
  127. """Erstellt Condition aus Dictionary."""
  128. return cls(
  129. flag_key=data["flag_key"],
  130. expected=data.get("expected", True),
  131. name=data.get("name"),
  132. invert=data.get("invert", False),
  133. )
  134. class ExistsCondition(Condition):
  135. """
  136. Prüft ob Schlüssel im Kontext existiert.
  137. Beispiel:
  138. - ExistsCondition("user_preferences")
  139. - ExistsCondition("error_message", exists=False)
  140. """
  141. def __init__(
  142. self,
  143. key: str,
  144. exists: bool = True,
  145. allow_none: bool = False,
  146. name: str | None = None,
  147. invert: bool = False,
  148. ):
  149. """
  150. Initialisiert die Condition.
  151. Args:
  152. key: Schlüssel im Kontext
  153. exists: Soll existieren (True) oder nicht (False)
  154. allow_none: None als existent zählen
  155. name: Condition-Name
  156. invert: Ergebnis invertieren
  157. """
  158. super().__init__(name, invert)
  159. self._key = key
  160. self._exists = exists
  161. self._allow_none = allow_none
  162. @property
  163. def key(self) -> str:
  164. """Schlüssel."""
  165. return self._key
  166. def _evaluate(self, context: dict) -> bool:
  167. """Prüft ob Schlüssel existiert."""
  168. key_exists = self._key in context
  169. if key_exists and not self._allow_none:
  170. key_exists = context[self._key] is not None
  171. return key_exists == self._exists
  172. def to_dict(self) -> dict:
  173. """Konvertiert zu Dictionary."""
  174. return {
  175. **self._base_dict(),
  176. "key": self._key,
  177. "exists": self._exists,
  178. "allow_none": self._allow_none,
  179. }
  180. @classmethod
  181. def from_dict(cls, data: dict) -> "ExistsCondition":
  182. """Erstellt Condition aus Dictionary."""
  183. return cls(
  184. key=data["key"],
  185. exists=data.get("exists", True),
  186. allow_none=data.get("allow_none", False),
  187. name=data.get("name"),
  188. invert=data.get("invert", False),
  189. )