hass-maestro 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. hass_maestro-0.1.0/.github/workflows/ci.yml +32 -0
  2. hass_maestro-0.1.0/.github/workflows/release.yml +48 -0
  3. hass_maestro-0.1.0/.gitignore +73 -0
  4. hass_maestro-0.1.0/.python-version +1 -0
  5. hass_maestro-0.1.0/AGENTS.md +349 -0
  6. hass_maestro-0.1.0/LICENSE +25 -0
  7. hass_maestro-0.1.0/PKG-INFO +965 -0
  8. hass_maestro-0.1.0/README.md +932 -0
  9. hass_maestro-0.1.0/maestro/__init__.py +18 -0
  10. hass_maestro-0.1.0/maestro/_app.py +170 -0
  11. hass_maestro-0.1.0/maestro/_cli/__init__.py +3 -0
  12. hass_maestro-0.1.0/maestro/_cli/init.py +76 -0
  13. hass_maestro-0.1.0/maestro/_cli/main.py +48 -0
  14. hass_maestro-0.1.0/maestro/_cli/templates/AGENTS.md.tmpl +80 -0
  15. hass_maestro-0.1.0/maestro/_cli/templates/Dockerfile.tmpl +20 -0
  16. hass_maestro-0.1.0/maestro/_cli/templates/README.md.tmpl +43 -0
  17. hass_maestro-0.1.0/maestro/_cli/templates/app.py.tmpl +59 -0
  18. hass_maestro-0.1.0/maestro/_cli/templates/docker-compose.yml.tmpl +31 -0
  19. hass_maestro-0.1.0/maestro/_cli/templates/env.tmpl +18 -0
  20. hass_maestro-0.1.0/maestro/_cli/templates/gitignore.tmpl +17 -0
  21. hass_maestro-0.1.0/maestro/_cli/templates/justfile.tmpl +41 -0
  22. hass_maestro-0.1.0/maestro/_cli/templates/pyproject.toml.tmpl +85 -0
  23. hass_maestro-0.1.0/maestro/_cli/templates/redis.conf.tmpl +17 -0
  24. hass_maestro-0.1.0/maestro/_cli/templates/scripts_example.py.tmpl +27 -0
  25. hass_maestro-0.1.0/maestro/_cli/templates/scripts_tests_test_example.py.tmpl +25 -0
  26. hass_maestro-0.1.0/maestro/_config.py +54 -0
  27. hass_maestro-0.1.0/maestro/_handlers/__init__.py +0 -0
  28. hass_maestro-0.1.0/maestro/_handlers/event_fired.py +16 -0
  29. hass_maestro-0.1.0/maestro/_handlers/hass_shutdown.py +8 -0
  30. hass_maestro-0.1.0/maestro/_handlers/hass_startup.py +8 -0
  31. hass_maestro-0.1.0/maestro/_handlers/notif_action.py +24 -0
  32. hass_maestro-0.1.0/maestro/_handlers/state_changed.py +100 -0
  33. hass_maestro-0.1.0/maestro/_handlers/types.py +72 -0
  34. hass_maestro-0.1.0/maestro/domains/__init__.py +68 -0
  35. hass_maestro-0.1.0/maestro/domains/_binary_sensor.py +11 -0
  36. hass_maestro-0.1.0/maestro/domains/_button.py +10 -0
  37. hass_maestro-0.1.0/maestro/domains/_calendar.py +48 -0
  38. hass_maestro-0.1.0/maestro/domains/_climate.py +35 -0
  39. hass_maestro-0.1.0/maestro/domains/_cover.py +19 -0
  40. hass_maestro-0.1.0/maestro/domains/_device_tracker.py +11 -0
  41. hass_maestro-0.1.0/maestro/domains/_entity.py +174 -0
  42. hass_maestro-0.1.0/maestro/domains/_event.py +7 -0
  43. hass_maestro-0.1.0/maestro/domains/_fan.py +26 -0
  44. hass_maestro-0.1.0/maestro/domains/_humidifier.py +19 -0
  45. hass_maestro-0.1.0/maestro/domains/_input_boolean.py +19 -0
  46. hass_maestro-0.1.0/maestro/domains/_input_datetime.py +27 -0
  47. hass_maestro-0.1.0/maestro/domains/_input_number.py +15 -0
  48. hass_maestro-0.1.0/maestro/domains/_input_select.py +24 -0
  49. hass_maestro-0.1.0/maestro/domains/_input_text.py +9 -0
  50. hass_maestro-0.1.0/maestro/domains/_light.py +28 -0
  51. hass_maestro-0.1.0/maestro/domains/_lock.py +13 -0
  52. hass_maestro-0.1.0/maestro/domains/_maestro.py +6 -0
  53. hass_maestro-0.1.0/maestro/domains/_media_player.py +67 -0
  54. hass_maestro-0.1.0/maestro/domains/_notify.py +7 -0
  55. hass_maestro-0.1.0/maestro/domains/_number.py +10 -0
  56. hass_maestro-0.1.0/maestro/domains/_person.py +25 -0
  57. hass_maestro-0.1.0/maestro/domains/_select.py +22 -0
  58. hass_maestro-0.1.0/maestro/domains/_sensor.py +7 -0
  59. hass_maestro-0.1.0/maestro/domains/_sun.py +25 -0
  60. hass_maestro-0.1.0/maestro/domains/_switch.py +20 -0
  61. hass_maestro-0.1.0/maestro/domains/_update.py +20 -0
  62. hass_maestro-0.1.0/maestro/domains/_weather.py +23 -0
  63. hass_maestro-0.1.0/maestro/domains/_zone.py +7 -0
  64. hass_maestro-0.1.0/maestro/exceptions.py +75 -0
  65. hass_maestro-0.1.0/maestro/integrations/__init__.py +29 -0
  66. hass_maestro-0.1.0/maestro/integrations/_home_assistant/__init__.py +0 -0
  67. hass_maestro-0.1.0/maestro/integrations/_home_assistant/client.py +273 -0
  68. hass_maestro-0.1.0/maestro/integrations/_home_assistant/domain.py +37 -0
  69. hass_maestro-0.1.0/maestro/integrations/_home_assistant/types.py +168 -0
  70. hass_maestro-0.1.0/maestro/integrations/_home_assistant/websocket_client.py +147 -0
  71. hass_maestro-0.1.0/maestro/integrations/_home_assistant/websocket_manager.py +189 -0
  72. hass_maestro-0.1.0/maestro/integrations/_redis.py +177 -0
  73. hass_maestro-0.1.0/maestro/integrations/_state_manager.py +323 -0
  74. hass_maestro-0.1.0/maestro/py.typed +0 -0
  75. hass_maestro-0.1.0/maestro/registry/README.md +47 -0
  76. hass_maestro-0.1.0/maestro/registry/__init__.py +5 -0
  77. hass_maestro-0.1.0/maestro/registry/_registry_manager.py +306 -0
  78. hass_maestro-0.1.0/maestro/testing/__init__.py +7 -0
  79. hass_maestro-0.1.0/maestro/testing/_context.py +44 -0
  80. hass_maestro-0.1.0/maestro/testing/_fixtures.py +42 -0
  81. hass_maestro-0.1.0/maestro/testing/_maestro_test.py +401 -0
  82. hass_maestro-0.1.0/maestro/testing/_mocks.py +401 -0
  83. hass_maestro-0.1.0/maestro/testing/tests/__init__.py +0 -0
  84. hass_maestro-0.1.0/maestro/testing/tests/test_action_calls.py +115 -0
  85. hass_maestro-0.1.0/maestro/testing/tests/test_action_response.py +68 -0
  86. hass_maestro-0.1.0/maestro/testing/tests/test_app_construction.py +79 -0
  87. hass_maestro-0.1.0/maestro/testing/tests/test_cli_init.py +85 -0
  88. hass_maestro-0.1.0/maestro/testing/tests/test_database.py +30 -0
  89. hass_maestro-0.1.0/maestro/testing/tests/test_entity_integration.py +58 -0
  90. hass_maestro-0.1.0/maestro/testing/tests/test_entity_state.py +116 -0
  91. hass_maestro-0.1.0/maestro/testing/tests/test_fired_events.py +57 -0
  92. hass_maestro-0.1.0/maestro/testing/tests/test_handlers.py +113 -0
  93. hass_maestro-0.1.0/maestro/testing/tests/test_job_scheduling.py +135 -0
  94. hass_maestro-0.1.0/maestro/testing/tests/test_registry_generation.py +139 -0
  95. hass_maestro-0.1.0/maestro/testing/tests/test_state_manager.py +231 -0
  96. hass_maestro-0.1.0/maestro/triggers/__init__.py +20 -0
  97. hass_maestro-0.1.0/maestro/triggers/_cron.py +132 -0
  98. hass_maestro-0.1.0/maestro/triggers/_event_fired.py +85 -0
  99. hass_maestro-0.1.0/maestro/triggers/_hass.py +63 -0
  100. hass_maestro-0.1.0/maestro/triggers/_maestro.py +68 -0
  101. hass_maestro-0.1.0/maestro/triggers/_notif_action.py +63 -0
  102. hass_maestro-0.1.0/maestro/triggers/_state_change.py +74 -0
  103. hass_maestro-0.1.0/maestro/triggers/_sun.py +138 -0
  104. hass_maestro-0.1.0/maestro/triggers/_trigger_manager.py +181 -0
  105. hass_maestro-0.1.0/maestro/triggers/_types.py +119 -0
  106. hass_maestro-0.1.0/maestro/utils/__init__.py +21 -0
  107. hass_maestro-0.1.0/maestro/utils/_dates.py +96 -0
  108. hass_maestro-0.1.0/maestro/utils/_internal.py +113 -0
  109. hass_maestro-0.1.0/maestro/utils/_logging.py +52 -0
  110. hass_maestro-0.1.0/maestro/utils/_push.py +127 -0
  111. hass_maestro-0.1.0/maestro/utils/_scheduler.py +78 -0
  112. hass_maestro-0.1.0/pyproject.toml +127 -0
  113. hass_maestro-0.1.0/uv.lock +1030 -0
@@ -0,0 +1,32 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ workflow_call:
8
+
9
+ jobs:
10
+ checks:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+
15
+ - uses: astral-sh/setup-uv@v5
16
+ with:
17
+ enable-cache: true
18
+
19
+ - name: Install dependencies
20
+ run: uv sync
21
+
22
+ - name: Lint
23
+ run: uv run ruff check maestro
24
+
25
+ - name: Format check
26
+ run: uv run ruff format --check maestro
27
+
28
+ - name: Type check
29
+ run: uv run mypy maestro
30
+
31
+ - name: Test
32
+ run: uv run pytest maestro
@@ -0,0 +1,48 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+
7
+ jobs:
8
+ checks:
9
+ uses: ./.github/workflows/ci.yml
10
+
11
+ build:
12
+ needs: checks
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - uses: astral-sh/setup-uv@v5
18
+
19
+ - name: Verify tag matches project version
20
+ run: |
21
+ TAG_VERSION="${GITHUB_REF_NAME#v}"
22
+ PROJECT_VERSION="$(uv version --short)"
23
+ if [ "$TAG_VERSION" != "$PROJECT_VERSION" ]; then
24
+ echo "Tag version ($TAG_VERSION) does not match pyproject.toml version ($PROJECT_VERSION)"
25
+ exit 1
26
+ fi
27
+
28
+ - name: Build distributions
29
+ run: uv build
30
+
31
+ - uses: actions/upload-artifact@v4
32
+ with:
33
+ name: dist
34
+ path: dist/
35
+
36
+ publish:
37
+ needs: build
38
+ runs-on: ubuntu-latest
39
+ environment: pypi
40
+ permissions:
41
+ id-token: write
42
+ steps:
43
+ - uses: actions/download-artifact@v4
44
+ with:
45
+ name: dist
46
+ path: dist/
47
+
48
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,73 @@
1
+ # Virtual environments
2
+ venv/
3
+ .venv/
4
+ env/
5
+ .env/
6
+ ENV/
7
+ env.bak/
8
+ venv.bak/
9
+
10
+ # Python
11
+ __pycache__/
12
+ *.py[cod]
13
+ *$py.class
14
+ *.so
15
+ .Python
16
+ build/
17
+ develop-eggs/
18
+ dist/
19
+ downloads/
20
+ eggs/
21
+ .eggs/
22
+ lib/
23
+ lib64/
24
+ parts/
25
+ sdist/
26
+ var/
27
+ wheels/
28
+ pip-wheel-metadata/
29
+ share/python-wheels/
30
+ *.egg-info/
31
+ .installed.cfg
32
+ *.egg
33
+ MANIFEST
34
+ .mypy_cache
35
+ .pytest_cache
36
+
37
+ # Flask
38
+ instance/
39
+ .webassets-cache
40
+
41
+ # Environment variables
42
+ .env
43
+ .env.local
44
+ .env.production
45
+
46
+ # Docker
47
+ .dockerignore
48
+
49
+ # IDE
50
+ .vscode/
51
+ .idea/
52
+ *.swp
53
+ *.swo
54
+ *~
55
+
56
+ # OS
57
+ .DS_Store
58
+ .DS_Store?
59
+ ._*
60
+ .Spotlight-V100
61
+ .Trashes
62
+ ehthumbs.db
63
+ Thumbs.db
64
+
65
+ # Logs
66
+ *.log
67
+ logs/
68
+
69
+ .cache
70
+ TODO.txt
71
+
72
+ .opencode/
73
+ dist/
@@ -0,0 +1 @@
1
+ 3.14
@@ -0,0 +1,349 @@
1
+ # Maestro (hass-maestro)
2
+
3
+ Strongly-typed Python automation framework for Home Assistant, packaged as an installable library (PyPI name `hass-maestro`, import name `maestro`). Flask + SQLAlchemy + Redis + APScheduler + structlog. Python 3.14+. Users install the package, write a small `app.py` that constructs `MaestroApp`, and keep their automations, entity registry, and custom domains in their own project. The reference consumer is [maestro](https://github.com/papa-marsh/maestro).
4
+
5
+ ## Project Structure
6
+
7
+ ```
8
+ maestro/ # The library package
9
+ __init__.py # Public surface: MaestroApp, get_app, get_config, db, __version__
10
+ _app.py # MaestroApp (Flask subclass); all initialization in its constructor
11
+ _cli/ # `hass-maestro` CLI; the init command scaffolds user projects from templates/
12
+ _config.py # MaestroConfig frozen dataclass + get_config()/register_config()
13
+ _handlers/ # WebSocket event handler functions (state_changed, event_fired, etc.)
14
+ exceptions.py # Public exception hierarchy (maestro.exceptions)
15
+ domains/ # Entity domain classes (Light, Switch, Climate, etc.)
16
+ integrations/ # External service clients (HA REST, WebSocket, Redis, StateManager)
17
+ triggers/ # Decorator-based trigger system (state_change, cron, sun, etc.)
18
+ registry/ # RegistryManager: generates entity modules into the user's project
19
+ testing/ # Test framework (MaestroTest, mocks, fixtures; ships as a pytest plugin)
20
+ tests/ # The library's own test suite
21
+ utils/ # Shared utilities (logging, dates, push notifs, scheduler)
22
+ ```
23
+
24
+ Modules and subpackages prefixed with `_` are internal. Everything a consumer may use is re-exported from a top-level package (`maestro`, `maestro.domains`, `maestro.exceptions`, `maestro.integrations`, `maestro.triggers`, `maestro.registry`, `maestro.utils`, `maestro.testing`).
25
+
26
+ ### The consumer model
27
+
28
+ Nothing in this repo is deployed directly. A user project looks like:
29
+
30
+ ```
31
+ their-project/
32
+ app.py # constructs MaestroApp; served by gunicorn as "app:app"
33
+ scripts/ # automation modules, loaded at startup
34
+ registry/ # generated by RegistryManager, imported as `from registry import ...`
35
+ custom_domains/ # optional Entity subclass extensions
36
+ ```
37
+
38
+ The constructor puts the project root on `sys.path`, so `scripts`, `registry`, and `custom_domains` are top-level packages named after their directories (all three names are configurable). Script modules import as `scripts.family.bedroom` (package-scoped, single module identity).
39
+
40
+ `hass-maestro init <dir>` scaffolds this layout as a ready-to-run project, including an example script + test, `.env`/`.env.example`, and a Docker deployment stack (app + redis + postgres).
41
+
42
+ ### The CLI (`_cli/`)
43
+
44
+ The `hass-maestro` console script (declared in `[project.scripts]`) dispatches argparse subcommands from `_cli/main.py`. The `init` command renders `_cli/templates/*.tmpl` files into the target directory using `string.Template` (`$project_name`, `$timezone`); literal dollar signs in templates must be escaped as `$$`. Templates ship as package data (hatchling includes non-Python package files by default). Because templates embody the consumer-facing API, changes to either should be verified by scaffolding a project and running its full toolchain (`uv run pytest / ruff check / ruff format --check / mypy .`) with the `[tool.uv.sources]` entry pointed at the local checkout. The CLI is exempt from the `T20` no-print rule.
45
+
46
+ ## Build / Lint / Test Commands
47
+
48
+ ```bash
49
+ uv sync # Install dependencies (creates .venv)
50
+
51
+ uv run ruff check maestro # Lint
52
+ uv run ruff check --fix maestro # Lint and auto-fix
53
+ uv run ruff format maestro # Format
54
+
55
+ uv run mypy maestro # Type check (strict mode)
56
+
57
+ uv run pytest maestro # Run all tests
58
+ uv run pytest maestro/testing/tests/test_entity_state.py::test_set_and_get_state
59
+ uv run pytest maestro -k "test_action"
60
+
61
+ uv add <package> # Runtime dependency
62
+ uv add --group dev <package> # Dev-only dependency
63
+ ```
64
+
65
+ Tests need no Redis, database, or Home Assistant connection. The `mt` fixture auto-registers via the `pytest11` entry point declared in pyproject (there is no conftest.py).
66
+
67
+ ## How Maestro Works
68
+
69
+ ### Lifecycle: everything happens in the constructor
70
+
71
+ There are no import-time singletons or side effects anywhere in the library. Importing `maestro` is inert. `MaestroApp.__init__` runs the full bootstrap:
72
+
73
+ 1. Builds a `MaestroConfig` from flat constructor kwargs and registers it globally (`register_config`)
74
+ 2. Registers itself as the current app -- `get_app()` returns it; a second construction raises `MaestroAlreadyConstructedError`
75
+ 3. Configures structlog logging (skippable via `configure_logging=False`)
76
+ 4. `db.init_app(self)` only if `db_url` was provided -- the database is fully optional
77
+ 5. Puts project directory parents on `sys.path`; imports the custom domains package if configured
78
+ 6. `load_script_modules(scripts_dir)` imports every user module, firing trigger decorator registration
79
+ 7. If `background_services=True` (default): starts the APScheduler `BackgroundScheduler` (Redis-backed job store), registers cron/sun jobs, starts `WebSocketManager` in a daemon thread, fires `MaestroEvent.STARTUP` triggers, and registers atexit shutdown handlers. If `False`: creates an idle in-memory scheduler only (REPL/shell use).
80
+
81
+ `db = SQLAlchemy()` is created at module level in `maestro/__init__.py` -- this is deliberately the one module-level object, because user model files need `class X(db.Model)` to work before the app exists. Creating the extension object is side-effect-free; it only binds to an app in step 4.
82
+
83
+ ### Configuration access
84
+
85
+ `MaestroConfig` is a frozen dataclass registered at construction. Library code reads it at call time via `get_config()` -- never at import time (no module-level constants derived from config, no config-valued default parameters, no eager class attributes). `get_config()` before construction raises `MaestroNotConstructedError`. In tests, the pytest plugin's `pytest_configure` hook registers a default config.
86
+
87
+ When adding code that needs config, follow this rule strictly: read `get_config()` inside the function or method that uses the value. For default parameters that should fall back to config, use the `_UnsetType` sentinel pattern (see `utils/_push.py`).
88
+
89
+ ### Event Flow: WebSocket to User Script
90
+
91
+ 1. **WebSocket** receives raw JSON from HA in a dedicated daemon thread with its own asyncio event loop
92
+ 2. **`WebSocketManager._handle_event()`** classifies the event type, generates a process ID for log correlation, constructs a `WebSocketEvent` dataclass
93
+ 3. **Handler dispatch** via `EventType` registry -- known events (`state_changed`, `ios.notification_action_fired`, etc.) get dedicated handlers; unknown events go to a default `event_fired` handler
94
+ 4. **Handler** (e.g., `handle_state_changed`) parses event data into typed dataclasses (`StateChangeEvent`), caches new state via `StateManager`, and fires matching triggers
95
+ 5. **`TriggerManager.fire_triggers()`** looks up registered functions by registry key (entity ID, event type, etc.), applies filters (from_state/to_state, user_id, etc.), and dispatches via `invoke_funcs_threaded()`
96
+ 6. **Thread-per-trigger**: Each matching function runs in its own daemon thread with its own Flask `app_context()` (synchronous in tests via `invoke_funcs_sync()`)
97
+ 7. **User script** executes, reading state via `Entity.state` / `EntityAttribute` (cache-through to Redis) and calling actions via `Entity.perform_action()` (REST API)
98
+
99
+ ### State Management (`integrations/_state_manager.py`)
100
+
101
+ `StateManager` is the central orchestrator, owning both a `HomeAssistantClient` (REST) and a `RedisClient` (cache). Key patterns:
102
+
103
+ - **Cache-through reads**: All state reads check Redis first; HA REST API is the fallback, which also populates the cache as a side effect
104
+ - **Event-driven cache writes**: WebSocket `state_changed` events trigger immediate cache updates via `cache_entity()`, which overwrites all state + attributes and deletes stale attribute keys
105
+ - **Type-preserving serialization**: Redis stores `{value, type}` JSON pairs so `int`, `float`, `bool`, `datetime`, `dict`, `list`, and `str` all round-trip correctly
106
+ - **Distributed locking**: Entity mutation operations (`patch_hass_entity`, `post_hass_entity`) acquire Redis locks to prevent concurrent modifications
107
+ - **Reconnection-aware sync**: If the WebSocket was disconnected for >30 minutes, a full REST API state sync runs on reconnect
108
+
109
+ In test mode, `StateManager.__init__()` auto-detects `test_mode_active()` and transparently swaps in `MockHomeAssistantClient` and `MockRedisClient`.
110
+
111
+ ### Redis keys (`integrations/_redis.py`)
112
+
113
+ Every maestro key is namespaced under the configurable `redis_key_prefix` (default `maestro`), enabling shared Redis instances and multiple maestro deployments per Redis. `RedisClient.build_key()` is the single choke point -- all keys, lock names, and SCAN patterns must go through it. Key shape: `maestro:STATE:domain:entity[:attribute]`, plus `REGISTERED:` (registry tracking) and `ENTITY_LOCK:` (distributed locks) prefixes. The APScheduler job store writes its own keys, passed explicitly as `{prefix}:apscheduler.jobs` / `{prefix}:apscheduler.run_times` in `_app.py`. Values are JSON-encoded with type metadata for lossless round-trips. Uses `SCAN` (not `KEYS`) for pattern matching. `StateId.cache_key` is a lazy property so IDs can be constructed before config exists.
114
+
115
+ ### Trigger System (`triggers/`)
116
+
117
+ #### Registration
118
+
119
+ Trigger decorators (`@state_change_trigger`, `@cron_trigger`, etc.) register functions into a class-level `_registry` at import time of the decorated module. The registry is a nested dict: `TriggerType -> registry_key -> list[TriggerRegistryEntry]`. `load_script_modules()` imports all user scripts during construction, which executes decorator applications and populates the registry.
120
+
121
+ #### Decorator Pattern
122
+
123
+ All trigger decorators follow a three-layer structure:
124
+ 1. **Outer function** -- receives configuration (entity IDs, cron fields, etc.)
125
+ 2. **`decorator(func)`** -- builds a `TriggerRegistryEntry`, calls `XxxTriggerManager.register_function()`, returns wrapper
126
+ 3. **`wrapper(*args)`** -- `@wraps(func)` proxy called at runtime; wrappers that need the app use `get_app()`
127
+
128
+ #### Optional Parameter Injection
129
+
130
+ `_invoke_func_with_param_handling()` uses `inspect.signature()` to match the decorated function's parameter names to available runtime params. This allows trigger functions to optionally accept context parameters or take no parameters at all:
131
+
132
+ ```python
133
+ # Both are valid:
134
+ @state_change_trigger(switch.motion, to_state=ON)
135
+ def with_context(state_change: StateChangeEvent) -> None: ...
136
+
137
+ @state_change_trigger(switch.motion, to_state=ON)
138
+ def without_context() -> None: ...
139
+ ```
140
+
141
+ #### Trigger Types
142
+
143
+ | Type | Registry Key | Filtering | Execution |
144
+ |------|-------------|-----------|-----------|
145
+ | `state_change` | entity ID | `from_state`, `to_state` exact match (None = wildcard) | Thread-per-trigger via `invoke_funcs_threaded` |
146
+ | `cron` | APScheduler `CronTrigger` object | None (APScheduler handles scheduling) | APScheduler's thread pool |
147
+ | `sun` | APScheduler `DateTrigger` object | None (self-rescheduling after each fire) | APScheduler's thread pool |
148
+ | `event_fired` | event type string | `user_id`, `**event_data` key-value match | Thread-per-trigger |
149
+ | `notif_action` | action name string | `device_id` | Thread-per-trigger |
150
+ | `maestro` | `MaestroEvent` enum | None | Threaded for STARTUP, synchronous for SHUTDOWN |
151
+ | `hass` | `HassEvent` enum | None | Thread-per-trigger |
152
+
153
+ Sun triggers are self-perpetuating: each fire computes the next solar event time from the `sun.sun` entity (a module-level `Sun("sun.sun")` singleton in `triggers/_sun.py`; the solar attributes are built into the `Sun` domain class) and schedules itself again, with a 20-hour guard to prevent rescheduling loops.
154
+
155
+ #### Test Registry
156
+
157
+ A separate `_test_registry` overlays the production `_registry`. Event-driven triggers use `get_registry(registry_union=True)` so both test-registered and production-registered triggers fire in tests.
158
+
159
+ ### Entity System (`domains/`)
160
+
161
+ #### Entity Base Class (`_entity.py`)
162
+
163
+ `Entity` is an ABC that all domain classes inherit from. Core behavior:
164
+
165
+ - **`state` property**: Reads from `StateManager.get_entity_state()` (cache-through). Setter is guarded by `allow_set_state` (only `True` for input_* domains and maestro).
166
+ - **`perform_action(action, **kwargs)`**: Calls `StateManager.hass_client.perform_action()`. Uses `@overload` with `Literal` for polymorphic return types (`response_expected=True` returns a dict).
167
+ - **`update(state, **attributes)`**: Delegates to `StateManager.patch_hass_entity()` for atomic read-modify-write.
168
+ - **Equality**: Uses identity comparison (`self is other`). Comparing an Entity to a non-Entity raises `TypeError` with a helpful hint ("Did you mean entity.state?").
169
+ - **Laziness**: Construction is side-effect-free; the `StateManager` is built on first state access. Entities are safe to instantiate at import time (registry modules do exactly this).
170
+
171
+ Constants: `ON`, `OFF`, `HOME`, `AWAY`, `UNAVAILABLE`, `UNKNOWN`.
172
+
173
+ #### EntityAttribute Descriptor (`_entity.py`)
174
+
175
+ A Python descriptor using PEP 695 generics (`EntityAttribute[T]`) constrained to `str | int | float | dict | list | bool | datetime`. Every attribute access is **live** -- it calls `StateManager.get_attribute_state()` each time (no local caching). Assignment delegates to `Entity.update()`.
176
+
177
+ #### Domain Subclasses
178
+
179
+ Each domain (Light, Switch, Climate, Cover, Lock, Fan, MediaPlayer, etc.) subclasses Entity, sets `domain = Domain.XXX`, and defines action methods that call `self.perform_action()`. Most set `allow_set_state = False`.
180
+
181
+ #### Custom Domain Subclasses (user project)
182
+
183
+ Users extend built-in domain classes in their own custom domains package (`custom_domains_dir` config). Maestro imports the package during construction, before registry modules and scripts load. User code imports custom classes directly (`from custom_domains import Thermostat`) -- the library never imports user code into its own namespace. Custom domain modules import their parent classes from the package (`from maestro.domains import Climate`) and export via `__all__` in the package `__init__.py`.
184
+
185
+ ### Entity Registry (`registry/`)
186
+
187
+ `RegistryManager` generates Python modules into the user project's `registry_dir` from Home Assistant entity data. Each domain gets a file (e.g., `registry/light.py`) containing a class per entity (subclassing its domain class, with `EntityAttribute` descriptors) and a module-level instance:
188
+
189
+ ```python
190
+ class LightMultiColorBulb(Light):
191
+ brightness = EntityAttribute(int)
192
+ rgb_color = EntityAttribute(list)
193
+ multi_color_bulb = LightMultiColorBulb("light.multi_color_bulb")
194
+ ```
195
+
196
+ Generation is line-format-sensitive: `_parse_module_entries` parses the generated files with regexes, so the writer and parser must stay in sync. When an entity's parent class was changed to a custom domain subclass, updates and prunes preserve it. `_build_import_strings` splits parent imports between `maestro.domains` (checked via `hasattr`) and the user's custom domains package; custom parents without a configured `custom_domains_dir` raise `CustomDomainsNotConfiguredError`.
197
+
198
+ `upsert_entity` is rate-limited via `REGISTERED:` Redis keys (one refresh per entity per day unless forced). `prune()` removes entries for entities no longer in HA, deleting emptied modules and clearing their Redis keys; it refuses to remove more than 25% of the registry unless `force=True`.
199
+
200
+ `EntityId.resolve_entity()` dynamically imports `{registry_package}.{domain}` to map an ID string back to its registered instance.
201
+
202
+ ### WebSocket System (`integrations/_home_assistant/`)
203
+
204
+ - **`WebSocketClient`**: Async aiohttp-based client. Connects, authenticates with a long-lived token, subscribes to all HA events, and runs a listener loop that invokes a callback per event.
205
+ - **`WebSocketManager`**: Lifecycle orchestrator running in a daemon thread with its own asyncio event loop. Handles reconnection with linear backoff (2s increments, max 30s), state sync on reconnect, and event routing to handlers.
206
+
207
+ ### Utilities (`utils/`)
208
+
209
+ - **Logging** (`_logging.py`): `LoggerProxy` singleton bound to `log`. Every log line carries a `process_id` context variable for correlating event processing chains across threads. Always use structured key-value arguments, never string interpolation.
210
+ - **Dates** (`_dates.py`): `local_now()`, `resolve_timestamp()`, `format_duration()`, `IntervalSeconds` IntEnum for TTL constants.
211
+ - **Scheduler** (`_scheduler.py`): `JobScheduler` wraps APScheduler for one-shot scheduled jobs. Uses `get_app().scheduler` in production; auto-redirects to `MockJobScheduler` in tests.
212
+ - **Push** (`_push.py`): `Notif` class for iOS push notifications via HA. Supports priorities, actionable buttons, custom sounds, grouping/tagging. Sound/url defaults come from config at call time via the `_UnsetType` sentinel.
213
+ - **Internal** (`_internal.py`): `load_script_modules`, `import_custom_domains`, `configure_logging`, `test_mode_active`. Not part of the public API.
214
+
215
+ ### Testing Framework (`testing/`)
216
+
217
+ - **`MaestroTest`** (`_maestro_test.py`): The primary test interface, injected as the `mt` fixture. Provides methods for state setup, trigger simulation, action assertions, entity assertions, job scheduler assertions, and time mocking (via freezegun, imported lazily so the plugin loads without it).
218
+ - **Mocks** (`_mocks.py`): `MockHomeAssistantClient` (in-memory entity store + action call recording), `MockRedisClient` (in-memory dict), `MockJobScheduler` (stores jobs without executing). All extend real client classes with `@override`.
219
+ - **Context** (`_context.py`): Per-test global singletons (`_test_state_manager`, `_test_job_scheduler`) with lazy init and full reset between tests.
220
+ - **Fixtures** (`_fixtures.py`): Registered as a pytest plugin via the `pytest11` entry point, so consumers get the `mt` fixture with zero conftest wiring. `pytest_configure` registers a default `MaestroConfig`. The `mt` fixture creates a lightweight Flask app (never a `MaestroApp`) with in-memory SQLite, yields a `MaestroTest` instance, then tears down DB and resets test context.
221
+
222
+ Tests never construct `MaestroApp` (except the dedicated construction tests, which restore the singleton state afterward). Test-mode detection (`"pytest" in sys.modules`) inside `StateManager`, `invoke_funcs_threaded`, and `JobScheduler` makes execution synchronous and mock-backed automatically.
223
+
224
+ ## Code Style
225
+
226
+ ### Formatting
227
+
228
+ - **Line length**: 100 characters (configured in `pyproject.toml`)
229
+ - **Formatter**: Ruff (`ruff format`), applied on save
230
+ - **Final newline**: Always required
231
+ - **No print statements**: Enforced by ruff rule `T20` -- use `log` instead
232
+ - **No `os.path`**: Enforced by ruff rule `PTH` -- use `pathlib`
233
+
234
+ ### Imports
235
+
236
+ Three groups separated by blank lines, each alphabetically sorted (enforced by ruff isort):
237
+
238
+ ```python
239
+ import re # 1. stdlib
240
+ from collections.abc import Callable
241
+ from typing import TYPE_CHECKING, Any, ClassVar, final
242
+
243
+ from apscheduler.triggers.cron import CronTrigger # 2. third-party
244
+
245
+ from maestro.triggers._types import TriggerFuncParamsT # 3. local
246
+ from maestro.utils._logging import log
247
+ ```
248
+
249
+ Use `TYPE_CHECKING` guard to avoid circular imports. Use `# type:ignore[import-untyped]` on untyped third-party imports.
250
+
251
+ ### Type Annotations
252
+
253
+ - **Every function must have full type annotations** including return type (enforced by mypy `disallow_untyped_defs`)
254
+ - Always annotate `-> None` for void functions
255
+ - Use `X | None` instead of `Optional[X]`
256
+ - Use `collections.abc.Callable` / `collections.abc.Mapping` instead of `typing.Callable` / `typing.Mapping`
257
+ - Use Python 3.12+ generic syntax: `class Entity[T]:`
258
+ - Use `TypedDict` for structured parameter dicts
259
+ - Use `@overload` with `Literal` for polymorphic return types
260
+ - Use `@override` on overridden methods (especially in mocks)
261
+ - Type aliases use PascalCase with `T` suffix: `CachedValueT`, `TriggerFuncParamsT`
262
+ - The package ships `py.typed`; strict typing is part of the public contract
263
+
264
+ ### Naming Conventions
265
+
266
+ | Kind | Convention | Examples |
267
+ |---|---|---|
268
+ | Functions/methods | `snake_case` | `fire_triggers`, `get_entity_state` |
269
+ | Private methods | `_snake_case` | `_initialize_db`, `_run_event_loop` |
270
+ | Unused params | `_prefixed` | `_event: WebSocketEvent`, `_logger` |
271
+ | Classes | `PascalCase` | `StateManager`, `MaestroTest` |
272
+ | Manager classes | `XxxManager` suffix | `TriggerManager`, `RegistryManager` |
273
+ | Mock classes | `MockXxx` prefix | `MockHomeAssistantClient` |
274
+ | Constants | `SCREAMING_SNAKE_CASE` | `ON`, `OFF`, `HOME`, `SCHEDULER_JOB_PREFIX` |
275
+ | Enums | `PascalCase` class, `SCREAMING_SNAKE_CASE` members | `TriggerType.STATE_CHANGE` |
276
+ | Type aliases | `PascalCaseT` | `CachedValueT`, `RegistryT` |
277
+
278
+ ### Enums
279
+
280
+ Use `StrEnum` with `auto()` for string enums (produces lowercase values). Use `IntEnum` for numeric constants:
281
+
282
+ ```python
283
+ class Domain(StrEnum):
284
+ LIGHT = auto() # "light"
285
+ MEDIA_PLAYER = auto() # "media_player"
286
+ ```
287
+
288
+ ### Custom String Types
289
+
290
+ Subclass `str` with `__new__` for validated identifiers (not `NewType`):
291
+
292
+ ```python
293
+ class StateId(str):
294
+ def __new__(cls, value: str) -> "StateId":
295
+ if not re.match(cls.entity_pattern, value):
296
+ raise ValueError(f"Invalid format: {value}")
297
+ return str.__new__(cls, value)
298
+ ```
299
+
300
+ ### Error Handling
301
+
302
+ - Custom exception hierarchy in `maestro/exceptions.py` with compact `class XxxError(BaseError): ...` syntax
303
+ - Always chain exceptions with `from e`: `raise MalformedResponseError("msg") from e`
304
+ - Use `contextlib.suppress(XxxError)` instead of bare `try/except` for expected exceptions
305
+ - Use `log.exception(...)` at thread/background-task boundaries for unexpected errors
306
+
307
+ ### Logging
308
+
309
+ Single `log` instance imported everywhere from `maestro.utils.logging`. Always use structured key-value arguments -- never string interpolation in log messages:
310
+
311
+ ```python
312
+ from maestro.utils._logging import log
313
+
314
+ log.info("Registered trigger", function_name=func.__name__, trigger_type=trigger_type)
315
+ log.exception("Failed to load module", module=module_name)
316
+ ```
317
+
318
+ ### Docstrings
319
+
320
+ Short imperative sentences. No Google/numpy `Args:`/`Returns:` sections. Multi-line only when explaining complex behavior. Use `# MARK:` comments to organize logical groups of methods within large classes.
321
+
322
+ ### Dataclasses
323
+
324
+ Use `@dataclass` for value/data transfer objects. Use `__post_init__` for data sanitization.
325
+
326
+ ## Testing Conventions
327
+
328
+ - **Framework**: pytest with the `mt` fixture (auto-registered plugin)
329
+ - **Test files**: Named `test_*.py`, module-level docstring describing scope
330
+ - **Test functions**: Named `test_*`, short one-line docstrings, return type `-> None`
331
+ - **No test classes** -- all tests are module-level functions
332
+ - **First parameter**: Always `mt: MaestroTest` (provides clean test context per test)
333
+ - **Pattern**: Setup state -> trigger action -> assert results
334
+
335
+ ```python
336
+ def test_motion_turns_on_light(mt: MaestroTest) -> None:
337
+ """Test that motion sensor triggers bedroom light"""
338
+ mt.set_state(switch.motion_sensor, OFF)
339
+ mt.trigger_state_change(switch.motion_sensor, old=OFF, new=ON)
340
+ mt.assert_action_called("light", "turn_on", entity_id="light.bedroom")
341
+ ```
342
+
343
+ ## Public API Discipline
344
+
345
+ The public API is exactly what the top-level packages re-export: consumers import from `maestro`, `maestro.domains`, `maestro.exceptions`, `maestro.integrations`, `maestro.triggers`, `maestro.registry`, `maestro.utils`, and `maestro.testing` -- never from submodules. Everything else is internal and carries an `_` prefix (modules like `utils/_dates.py`, whole packages like `_handlers/`).
346
+
347
+ - Public packages re-export via `__init__.py` with `__all__` lists using `ClassName.__name__` references (quote the name for string constants and non-class symbols -- `X.__name__` on a string constant silently inserts its value).
348
+ - Library-internal code imports directly from the underscored modules (`from maestro.utils._logging import log`), not from package `__init__` files, to avoid import cycles.
349
+ - When adding a public symbol, define it in an internal module and re-export it from the owning top-level package. When adding an internal module, prefix it with `_`.
@@ -0,0 +1,25 @@
1
+ Creative Commons Attribution-NonCommercial 4.0 International Public License
2
+
3
+ Copyright (c) 2025 Marshall
4
+
5
+ This work is licensed under the Creative Commons Attribution-NonCommercial 4.0
6
+ International License. To view a copy of this license, visit
7
+ http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
8
+ Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
9
+
10
+ You are free to:
11
+ - Share — copy and redistribute the material in any medium or format
12
+ - Adapt — remix, transform, and build upon the material
13
+
14
+ Under the following terms:
15
+ - Attribution — You must give appropriate credit, provide a link to the license,
16
+ and indicate if changes were made. You may do so in any reasonable manner,
17
+ but not in any way that suggests the licensor endorses you or your use.
18
+ - NonCommercial — You may not use the material for commercial purposes.
19
+
20
+ No additional restrictions — You may not apply legal terms or technological
21
+ measures that legally restrict others from doing anything the license permits.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.