expression.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. # -*- coding: utf-8 -*-
  2. """
  3. Expression Condition - Evaluiert Python-Ausdrücke mit App-Zugriff.
  4. """
  5. from typing import Any, TYPE_CHECKING
  6. from trixy_core.scheduler.condition.base import Condition
  7. if TYPE_CHECKING:
  8. from trixy_core.application import TrixyApplication
  9. class ExpressionCondition(Condition):
  10. """
  11. Evaluiert einen Python-Ausdruck mit Zugriff auf App-Komponenten.
  12. Verfügbare Variablen im Ausdruck:
  13. - app: TrixyApplication Instanz
  14. - satellites: SatelliteManager
  15. - events: EventManager
  16. - plugins: PluginManager
  17. - config: ConfigManager
  18. - scheduler: Scheduler
  19. - context: Aktueller Condition-Kontext
  20. Beispiele:
  21. ```python
  22. # Satellite-Anzahl prüfen
  23. ExpressionCondition("satellites.count > 0")
  24. # Musik-Status prüfen
  25. ExpressionCondition("app.music_player.state == 'stopped'")
  26. # Kombinierte Bedingung
  27. ExpressionCondition(
  28. "satellites.count > 0 and events.listener_count('wakeword') > 0"
  29. )
  30. # Mit Kontext-Variable
  31. ExpressionCondition("context.get('temperature', 0) > 25")
  32. # Satellite in bestimmtem Raum verbunden
  33. ExpressionCondition("satellites.get_by_room('kitchen') is not None")
  34. # Plugin aktiviert
  35. ExpressionCondition("plugins.is_enabled('spotify')")
  36. ```
  37. """
  38. def __init__(
  39. self,
  40. expression: str,
  41. name: str | None = None,
  42. invert: bool = False,
  43. ):
  44. """
  45. Initialisiert die Condition.
  46. Args:
  47. expression: Python-Ausdruck der zu bool evaluiert wird
  48. name: Condition-Name
  49. invert: Ergebnis invertieren
  50. """
  51. super().__init__(name or f"expr:{expression[:30]}", invert)
  52. self._expression = expression
  53. @property
  54. def expression(self) -> str:
  55. """Python-Ausdruck."""
  56. return self._expression
  57. def _build_eval_context(self, context: dict) -> dict[str, Any]:
  58. """
  59. Erstellt den Evaluierungs-Kontext mit App-Zugriff.
  60. Args:
  61. context: Condition-Kontext
  62. Returns:
  63. Dictionary mit allen verfügbaren Variablen
  64. """
  65. eval_ctx: dict[str, Any] = {
  66. # Basis-Kontext
  67. "context": context,
  68. "ctx": context,
  69. # Python builtins (eingeschränkt)
  70. "len": len,
  71. "str": str,
  72. "int": int,
  73. "float": float,
  74. "bool": bool,
  75. "list": list,
  76. "dict": dict,
  77. "set": set,
  78. "tuple": tuple,
  79. "min": min,
  80. "max": max,
  81. "sum": sum,
  82. "abs": abs,
  83. "round": round,
  84. "any": any,
  85. "all": all,
  86. "sorted": sorted,
  87. "reversed": reversed,
  88. "enumerate": enumerate,
  89. "zip": zip,
  90. "range": range,
  91. "isinstance": isinstance,
  92. "hasattr": hasattr,
  93. "getattr": getattr,
  94. "None": None,
  95. "True": True,
  96. "False": False,
  97. }
  98. # App aus Kontext holen
  99. app = context.get("app") or context.get("application")
  100. if app:
  101. eval_ctx["app"] = app
  102. # Manager-Shortcuts
  103. if hasattr(app, "satellite_manager"):
  104. eval_ctx["satellites"] = app.satellite_manager
  105. eval_ctx["satellite_manager"] = app.satellite_manager
  106. if hasattr(app, "event_manager"):
  107. eval_ctx["events"] = app.event_manager
  108. eval_ctx["event_manager"] = app.event_manager
  109. if hasattr(app, "plugin_manager"):
  110. eval_ctx["plugins"] = app.plugin_manager
  111. eval_ctx["plugin_manager"] = app.plugin_manager
  112. if hasattr(app, "config_manager"):
  113. eval_ctx["config"] = app.config_manager
  114. eval_ctx["config_manager"] = app.config_manager
  115. if hasattr(app, "scheduler"):
  116. eval_ctx["scheduler"] = app.scheduler
  117. # Weitere App-Attribute
  118. if hasattr(app, "music_player"):
  119. eval_ctx["music"] = app.music_player
  120. eval_ctx["music_player"] = app.music_player
  121. if hasattr(app, "conversation_manager"):
  122. eval_ctx["conversations"] = app.conversation_manager
  123. if hasattr(app, "wakeword_service"):
  124. eval_ctx["wakeword"] = app.wakeword_service
  125. # Direkte Manager aus Kontext (falls ohne App)
  126. for key in ["satellite_manager", "event_manager", "plugin_manager",
  127. "config_manager", "scheduler"]:
  128. if key in context and key not in eval_ctx:
  129. eval_ctx[key] = context[key]
  130. # Kurznamen
  131. short_name = key.replace("_manager", "s").replace("_", "")
  132. if short_name not in eval_ctx:
  133. eval_ctx[short_name] = context[key]
  134. return eval_ctx
  135. def _evaluate(self, context: dict) -> bool:
  136. """Evaluiert den Ausdruck."""
  137. try:
  138. eval_ctx = self._build_eval_context(context)
  139. # Ausdruck evaluieren
  140. result = eval(self._expression, {"__builtins__": {}}, eval_ctx)
  141. return bool(result)
  142. except Exception as e:
  143. from trixy_core.utils.debug import perror
  144. perror(f"Expression-Fehler '{self._expression}': {e}")
  145. return False
  146. def to_dict(self) -> dict:
  147. """Konvertiert zu Dictionary."""
  148. return {
  149. **self._base_dict(),
  150. "expression": self._expression,
  151. }
  152. @classmethod
  153. def from_dict(cls, data: dict) -> "ExpressionCondition":
  154. """Erstellt Condition aus Dictionary."""
  155. return cls(
  156. expression=data["expression"],
  157. name=data.get("name"),
  158. invert=data.get("invert", False),
  159. )
  160. def __repr__(self) -> str:
  161. return f"ExpressionCondition({self._expression!r})"
  162. class LambdaCondition(Condition):
  163. """
  164. Condition mit Lambda-Funktion.
  165. Für komplexere Logik die nicht in einen Einzeiler passt,
  166. aber trotzdem inline definiert werden soll.
  167. Beispiel:
  168. ```python
  169. LambdaCondition(
  170. lambda ctx: (
  171. ctx.get("satellites", {}).get("count", 0) > 0 and
  172. ctx.get("last_activity") is not None
  173. )
  174. )
  175. ```
  176. """
  177. def __init__(
  178. self,
  179. func: callable,
  180. name: str | None = None,
  181. invert: bool = False,
  182. ):
  183. """
  184. Initialisiert die Condition.
  185. Args:
  186. func: Lambda/Funktion die context → bool mapped
  187. name: Condition-Name
  188. invert: Ergebnis invertieren
  189. """
  190. super().__init__(name or "lambda", invert)
  191. self._func = func
  192. def _evaluate(self, context: dict) -> bool:
  193. """Ruft die Funktion auf."""
  194. try:
  195. result = self._func(context)
  196. return bool(result)
  197. except Exception as e:
  198. from trixy_core.utils.debug import perror
  199. perror(f"Lambda-Fehler: {e}")
  200. return False
  201. def to_dict(self) -> dict:
  202. """Konvertiert zu Dictionary (ohne Funktion)."""
  203. return {
  204. **self._base_dict(),
  205. # Lambda kann nicht serialisiert werden
  206. "func": "<lambda>",
  207. }
  208. # Shortcut-Funktionen für häufige Expressions
  209. def satellites_connected(min_count: int = 1) -> ExpressionCondition:
  210. """Condition: Mindestens X Satellites verbunden."""
  211. return ExpressionCondition(
  212. f"satellites.count >= {min_count}",
  213. name=f"satellites_min_{min_count}",
  214. )
  215. def satellite_in_room(room: str) -> ExpressionCondition:
  216. """Condition: Satellite in bestimmtem Raum verbunden."""
  217. return ExpressionCondition(
  218. f"satellites.get_by_room('{room}') is not None",
  219. name=f"satellite_in_{room}",
  220. )
  221. def plugin_enabled(plugin_name: str) -> ExpressionCondition:
  222. """Condition: Plugin ist aktiviert."""
  223. return ExpressionCondition(
  224. f"plugins.is_enabled('{plugin_name}')",
  225. name=f"plugin_{plugin_name}_enabled",
  226. )
  227. def music_playing() -> ExpressionCondition:
  228. """Condition: Musik wird abgespielt."""
  229. return ExpressionCondition(
  230. "music_player is not None and music_player.is_playing",
  231. name="music_playing",
  232. )
  233. def music_stopped() -> ExpressionCondition:
  234. """Condition: Musik ist gestoppt."""
  235. return ExpressionCondition(
  236. "music_player is None or not music_player.is_playing",
  237. name="music_stopped",
  238. )
  239. def conversation_active() -> ExpressionCondition:
  240. """Condition: Eine Konversation ist aktiv."""
  241. return ExpressionCondition(
  242. "conversations is not None and conversations.has_active_session()",
  243. name="conversation_active",
  244. )
  245. def no_conversation() -> ExpressionCondition:
  246. """Condition: Keine aktive Konversation."""
  247. return ExpressionCondition(
  248. "conversations is None or not conversations.has_active_session()",
  249. name="no_conversation",
  250. )