dirigera-bridge 1.0.0__py3-none-any.whl
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.
- dirigera_bridge/__init__.py +36 -0
- dirigera_bridge/__main__.py +6 -0
- dirigera_bridge/config.py +618 -0
- dirigera_bridge/core/__init__.py +38 -0
- dirigera_bridge/core/discovery_cache.py +445 -0
- dirigera_bridge/core/errors.py +202 -0
- dirigera_bridge/core/event_bus.py +436 -0
- dirigera_bridge/core/lifecycle.py +506 -0
- dirigera_bridge/core/metrics.py +307 -0
- dirigera_bridge/core/retry.py +394 -0
- dirigera_bridge/core/state_cache.py +423 -0
- dirigera_bridge/dirigera/__init__.py +45 -0
- dirigera_bridge/dirigera/models.py +539 -0
- dirigera_bridge/dirigera/rest_client.py +606 -0
- dirigera_bridge/dirigera/websocket_client.py +763 -0
- dirigera_bridge/factory.py +146 -0
- dirigera_bridge/ha/__init__.py +21 -0
- dirigera_bridge/ha/ha_client.py +681 -0
- dirigera_bridge/main.py +173 -0
- dirigera_bridge/mapping/__init__.py +62 -0
- dirigera_bridge/mapping/command_mapper.py +566 -0
- dirigera_bridge/mapping/device_mapper.py +343 -0
- dirigera_bridge/mapping/device_registry.py +395 -0
- dirigera_bridge/mapping/domains/__init__.py +360 -0
- dirigera_bridge/mapping/domains/air_purifier.py +275 -0
- dirigera_bridge/mapping/domains/binary_sensor.py +254 -0
- dirigera_bridge/mapping/domains/blind.py +203 -0
- dirigera_bridge/mapping/domains/button.py +200 -0
- dirigera_bridge/mapping/domains/environment_sensor.py +296 -0
- dirigera_bridge/mapping/domains/gateway.py +393 -0
- dirigera_bridge/mapping/domains/light.py +320 -0
- dirigera_bridge/mapping/domains/outlet.py +321 -0
- dirigera_bridge/mapping/domains/remote.py +213 -0
- dirigera_bridge/mapping/domains/sensor.py +189 -0
- dirigera_bridge/mapping/domains/speaker.py +342 -0
- dirigera_bridge/mapping/domains/switch.py +153 -0
- dirigera_bridge/mapping/state_mapper.py +1112 -0
- dirigera_bridge/orchestrator.py +1029 -0
- dirigera_bridge/py.typed +1 -0
- dirigera_bridge-1.0.0.dist-info/METADATA +532 -0
- dirigera_bridge-1.0.0.dist-info/RECORD +45 -0
- dirigera_bridge-1.0.0.dist-info/WHEEL +5 -0
- dirigera_bridge-1.0.0.dist-info/entry_points.txt +2 -0
- dirigera_bridge-1.0.0.dist-info/licenses/LICENSE +21 -0
- dirigera_bridge-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Dirigera MQTT Bridge.
|
|
3
|
+
|
|
4
|
+
Usable two ways:
|
|
5
|
+
|
|
6
|
+
1. As an application — run `dirigera_bridge` (the console script) or
|
|
7
|
+
`python -m dirigera_bridge`, configured entirely via .env. See
|
|
8
|
+
main.py / README.md for the Docker/CLI deployment.
|
|
9
|
+
|
|
10
|
+
2. As a library — import build_orchestrator() to embed this bridge
|
|
11
|
+
inside a larger application, e.g. one that also wires up other
|
|
12
|
+
vendor bridges (Philips Hue, etc.) alongside this one:
|
|
13
|
+
|
|
14
|
+
from dirigera_bridge import Settings, load_settings, build_orchestrator
|
|
15
|
+
|
|
16
|
+
settings = load_settings() # reads .env, or construct Settings() directly
|
|
17
|
+
orchestrator = build_orchestrator(settings)
|
|
18
|
+
await orchestrator.run()
|
|
19
|
+
|
|
20
|
+
Each build_orchestrator() result is fully self-contained — it
|
|
21
|
+
owns its own MQTT connection — so running several bridges
|
|
22
|
+
concurrently just means running several Orchestrators side by
|
|
23
|
+
side; there's no shared connection state to coordinate between
|
|
24
|
+
them.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from .config import Settings, load_settings
|
|
28
|
+
from .factory import build_orchestrator
|
|
29
|
+
from .orchestrator import Orchestrator
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"Orchestrator",
|
|
33
|
+
"Settings",
|
|
34
|
+
"load_settings",
|
|
35
|
+
"build_orchestrator",
|
|
36
|
+
]
|
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
"""
|
|
2
|
+
config.py
|
|
3
|
+
|
|
4
|
+
Application configuration loader and typed settings.
|
|
5
|
+
|
|
6
|
+
Role & Responsibility:
|
|
7
|
+
Single source of truth for all runtime configuration. Reads
|
|
8
|
+
environment variables (populated from the .env file via
|
|
9
|
+
python-dotenv), validates every value at startup, and exposes
|
|
10
|
+
a single typed Settings object that all other modules import.
|
|
11
|
+
|
|
12
|
+
If any required variable is missing or any value is invalid the
|
|
13
|
+
application raises immediately at startup with a clear error
|
|
14
|
+
message — configuration problems are never discovered at runtime
|
|
15
|
+
mid-operation.
|
|
16
|
+
|
|
17
|
+
What it does:
|
|
18
|
+
- Loads the .env file from the project root using python-dotenv
|
|
19
|
+
- Reads and validates all required and optional environment
|
|
20
|
+
variables
|
|
21
|
+
- Exposes a Settings dataclass with typed fields for every config
|
|
22
|
+
value used in the application
|
|
23
|
+
- Provides a load_settings() factory function that performs the
|
|
24
|
+
full load-and-validate cycle
|
|
25
|
+
- Provides a get_settings() module-level accessor that returns
|
|
26
|
+
the cached singleton — callers never need to pass Settings
|
|
27
|
+
around explicitly
|
|
28
|
+
|
|
29
|
+
Arguments / Configuration:
|
|
30
|
+
All configuration comes from environment variables. Required:
|
|
31
|
+
|
|
32
|
+
DIRIGERA_IP IP address of the Dirigera hub
|
|
33
|
+
DIRIGERA_TOKEN Access token for the Dirigera WebSocket/REST API
|
|
34
|
+
MQTT_HOST Hostname of the MQTT broker (e.g. 'mosquitto')
|
|
35
|
+
MQTT_USER MQTT username
|
|
36
|
+
MQTT_PASSWORD MQTT password
|
|
37
|
+
|
|
38
|
+
Optional (with defaults):
|
|
39
|
+
|
|
40
|
+
MQTT_PORT MQTT broker port (default: 1883)
|
|
41
|
+
MQTT_CLIENT_ID MQTT client identifier (default: 'dirigera-bridge')
|
|
42
|
+
MQTT_KEEPALIVE MQTT keepalive interval in seconds (default: 60)
|
|
43
|
+
MQTT_BASE_TOPIC Base topic prefix for state/command topics (default: 'dirigera')
|
|
44
|
+
MQTT_QOS MQTT QoS level 0, 1, or 2 (default: 1)
|
|
45
|
+
MQTT_TLS Use TLS for the MQTT connection (default: false)
|
|
46
|
+
MQTT_RECONNECT Let the HASDK auto-reconnect the MQTT transport (default: true)
|
|
47
|
+
MQTT_RECONNECT_DELAY_MIN Minimum HADSK MQTT reconnect delay in seconds (default: 1.0)
|
|
48
|
+
MQTT_RECONNECT_DELAY_MAX Maximum HASDK MQTT reconnect deay in seconds (default: 60.0)
|
|
49
|
+
DISCOVERY_PREFIX HA MQTT discovery prefix (default: 'homeassistant')
|
|
50
|
+
LOG_LEVEL Logging level string (default: 'INFO')
|
|
51
|
+
METRICS_INTERVAL Seconds between metrics log snapshots (default: 300)
|
|
52
|
+
WS_PING_INTERVAL Seconds between WebSocket keepalive pings (default: 30)
|
|
53
|
+
WS_PING_TIMEOUT Seconds to wait for a pong reply (default: 10)
|
|
54
|
+
RECONNECT_DELAY_INITIAL First reconnect delay in seconds (default: 1.0)
|
|
55
|
+
RECONNECT_DELAY_MAX Maximum reconnect delay in seconds (default: 60.0)
|
|
56
|
+
|
|
57
|
+
Used by:
|
|
58
|
+
- main.py (calls load_settings() once at startup)
|
|
59
|
+
- app/orchestrator.py (reads settings fields)
|
|
60
|
+
- app/dirigera/websocket_client.py (DIRIGERA_IP, TOKEN, WS_PING_*)
|
|
61
|
+
- app/dirigera/rest_client.py (DIRIGERA_IP, TOKEN)
|
|
62
|
+
- app/ha/ha_client.py (all MQTT_* and DISCOVERY_PREFIX)
|
|
63
|
+
|
|
64
|
+
Not responsible for:
|
|
65
|
+
- Establishing any connections (that is the client modules' job)
|
|
66
|
+
- Watching for config changes at runtime (static at startup)
|
|
67
|
+
- Secrets management beyond reading from environment variables
|
|
68
|
+
- SERVICE_VERSION — that is a hardcoded constant in factory.py, not
|
|
69
|
+
an environment variable, so it cannot be accidentally overridden
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
from __future__ import annotations
|
|
73
|
+
|
|
74
|
+
import logging
|
|
75
|
+
import os
|
|
76
|
+
from dataclasses import dataclass
|
|
77
|
+
|
|
78
|
+
from dotenv import load_dotenv
|
|
79
|
+
|
|
80
|
+
from .core.errors import DirigeraBridgeError, ErrorCode
|
|
81
|
+
|
|
82
|
+
__all__ = [
|
|
83
|
+
"Settings",
|
|
84
|
+
"load_settings",
|
|
85
|
+
"get_settings",
|
|
86
|
+
]
|
|
87
|
+
|
|
88
|
+
logger = logging.getLogger(__name__)
|
|
89
|
+
|
|
90
|
+
# Module-level singleton — populated by load_settings()
|
|
91
|
+
_settings: Settings | None = None
|
|
92
|
+
|
|
93
|
+
# Valid MQTT QoS levels
|
|
94
|
+
_VALID_QOS_LEVELS = {0, 1, 2}
|
|
95
|
+
|
|
96
|
+
# Valid Python logging level strings
|
|
97
|
+
_VALID_LOG_LEVELS = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# ── Settings dataclass ────────────────────────────────────────────────────────
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True)
|
|
104
|
+
class Settings:
|
|
105
|
+
"""
|
|
106
|
+
Typed, immutable application settings.
|
|
107
|
+
|
|
108
|
+
Constructed by load_settings() after reading and validating all
|
|
109
|
+
environment variables. Frozen so no module can accidentally mutate
|
|
110
|
+
configuration at runtime.
|
|
111
|
+
|
|
112
|
+
Fields — Dirigera:
|
|
113
|
+
dirigera_ip (str):
|
|
114
|
+
IP address of the Dirigera hub.
|
|
115
|
+
|
|
116
|
+
dirigera_token (str):
|
|
117
|
+
Access token for Dirigera WebSocket and REST API.
|
|
118
|
+
Never logged — treated as a secret.
|
|
119
|
+
|
|
120
|
+
Fields — MQTT connection:
|
|
121
|
+
mqtt_host (str):
|
|
122
|
+
Hostname or IP of the MQTT broker.
|
|
123
|
+
|
|
124
|
+
mqtt_port (int):
|
|
125
|
+
MQTT broker port. Range: 1-65535. Default: 1883.
|
|
126
|
+
|
|
127
|
+
mqtt_user (str):
|
|
128
|
+
MQTT broker username.
|
|
129
|
+
|
|
130
|
+
mqtt_password (str):
|
|
131
|
+
MQTT broker password. Never logged — treated as a secret.
|
|
132
|
+
|
|
133
|
+
mqtt_client_id (str):
|
|
134
|
+
MQTT client identifier sent to the broker on connect.
|
|
135
|
+
Makes broker-side log filtering easier and ensures the
|
|
136
|
+
broker recognizes reconnecting clients as the same session.
|
|
137
|
+
Default: 'dirigera-bridge'.
|
|
138
|
+
|
|
139
|
+
mqtt_keepalive (int):
|
|
140
|
+
Seconds between MQTT PINGREQ keepalive messages.
|
|
141
|
+
Must be > 0. Default: 60.
|
|
142
|
+
|
|
143
|
+
mqtt_base_topic (str):
|
|
144
|
+
Base topic prefix for all state and command topics owned
|
|
145
|
+
by this bridge (e.g. 'dirigera/light/abc123/state').
|
|
146
|
+
Distinct from discovery_prefix which is controlled by HA.
|
|
147
|
+
Default: 'dirigera'.
|
|
148
|
+
|
|
149
|
+
mqtt_qos (int):
|
|
150
|
+
MQTT Quality of Service level for all publishes and
|
|
151
|
+
subscriptions. 0 = at most once, 1 = at least once,
|
|
152
|
+
2 = exactly once. Default: 1.
|
|
153
|
+
|
|
154
|
+
mqtt_tls (bool):
|
|
155
|
+
Whether the HASDK's MQTT transport connects over TLS.
|
|
156
|
+
Default: False.
|
|
157
|
+
|
|
158
|
+
mqtt_reconnect (bool):
|
|
159
|
+
Whether the HASDK's MQTT transport auto-reconnects on
|
|
160
|
+
connection loss. This is seperate from - and does not
|
|
161
|
+
affect - the bridge's own retry_with_backoff() calls
|
|
162
|
+
around HAClient.connect(); it controls the HASDK's
|
|
163
|
+
internal transport-level behaviour only. Default: True.
|
|
164
|
+
|
|
165
|
+
mqtt_reconnect_delay_min (float):
|
|
166
|
+
Minimum HASDK MQTT reconnect delay in seconds. Distinct
|
|
167
|
+
from reconnect_delay_initial, which governs this
|
|
168
|
+
bridge's own Dirigera WebSocket backoff — the two are
|
|
169
|
+
unrelated layers and are intentionally named
|
|
170
|
+
differently to avoid being confused with each other.
|
|
171
|
+
Minimum: 0.1. Default: 1.0.
|
|
172
|
+
|
|
173
|
+
mqtt_reconnect_delay_max (float):
|
|
174
|
+
Maximum HASDK MQTT reconnect delay in seconds. Distinct
|
|
175
|
+
from reconnect_delay_max (Dirigera WebSocket backoff)
|
|
176
|
+
for the same reason as mqtt_reconnect_delay_min.
|
|
177
|
+
Must be >= mqtt_reconnect_delay_min. Default: 60.0.
|
|
178
|
+
|
|
179
|
+
Fields — Home Assistant:
|
|
180
|
+
discovery_prefix (str):
|
|
181
|
+
Home Assistant MQTT discovery topic prefix. Must match the
|
|
182
|
+
discovery prefix configured in HA. Default: 'homeassistant'.
|
|
183
|
+
|
|
184
|
+
Fields — operational:
|
|
185
|
+
log_level (str):
|
|
186
|
+
Python logging level string. Default: 'INFO'.
|
|
187
|
+
|
|
188
|
+
metrics_interval (int):
|
|
189
|
+
Seconds between periodic metrics log snapshots.
|
|
190
|
+
Minimum: 10. Default: 300 (5 minutes).
|
|
191
|
+
|
|
192
|
+
ws_ping_interval (int):
|
|
193
|
+
Seconds between WebSocket keepalive pings to the hub.
|
|
194
|
+
Minimum: 5. Default: 30.
|
|
195
|
+
|
|
196
|
+
ws_ping_timeout (int):
|
|
197
|
+
Seconds to wait for a pong before declaring the WebSocket
|
|
198
|
+
connection dead. Must be < ws_ping_interval. Default: 10.
|
|
199
|
+
|
|
200
|
+
reconnect_delay_initial (float):
|
|
201
|
+
Initial delay in seconds for exponential backoff on
|
|
202
|
+
reconnect. Minimum: 0.1. Default: 1.0.
|
|
203
|
+
|
|
204
|
+
reconnect_delay_max (float):
|
|
205
|
+
Maximum delay cap in seconds for exponential backoff.
|
|
206
|
+
Must be >= reconnect_delay_initial. Default: 60.0.
|
|
207
|
+
"""
|
|
208
|
+
|
|
209
|
+
# ── Dirigera ──────────────────────────────────────────────────────────
|
|
210
|
+
dirigera_ip: str
|
|
211
|
+
dirigera_token: str # secret — never log raw value
|
|
212
|
+
|
|
213
|
+
# ── MQTT connection ───────────────────────────────────────────────────
|
|
214
|
+
mqtt_host: str
|
|
215
|
+
mqtt_port: int
|
|
216
|
+
mqtt_user: str
|
|
217
|
+
mqtt_password: str # secret — never log raw value
|
|
218
|
+
mqtt_client_id: str
|
|
219
|
+
mqtt_keepalive: int
|
|
220
|
+
mqtt_base_topic: str
|
|
221
|
+
mqtt_qos: int
|
|
222
|
+
mqtt_tls: bool
|
|
223
|
+
mqtt_reconnect: bool
|
|
224
|
+
mqtt_reconnect_delay_min: float
|
|
225
|
+
mqtt_reconnect_delay_max: float
|
|
226
|
+
|
|
227
|
+
# ── Home Assistant ────────────────────────────────────────────────────
|
|
228
|
+
discovery_prefix: str
|
|
229
|
+
|
|
230
|
+
# ── Operational ───────────────────────────────────────────────────────
|
|
231
|
+
log_level: str
|
|
232
|
+
metrics_interval: int
|
|
233
|
+
ws_ping_interval: int
|
|
234
|
+
ws_ping_timeout: int
|
|
235
|
+
reconnect_delay_initial: float
|
|
236
|
+
reconnect_delay_max: float
|
|
237
|
+
|
|
238
|
+
def safe_repr(self) -> str:
|
|
239
|
+
"""
|
|
240
|
+
Return a string representation with secrets redacted.
|
|
241
|
+
|
|
242
|
+
Used for startup logging — never log the raw Settings object
|
|
243
|
+
as it contains the Dirigera token and MQTT password.
|
|
244
|
+
|
|
245
|
+
Returns:
|
|
246
|
+
str: Settings summary with secrets replaced by '***'.
|
|
247
|
+
"""
|
|
248
|
+
|
|
249
|
+
return (
|
|
250
|
+
f"Settings("
|
|
251
|
+
f"dirigera_ip={self.dirigera_ip!r}, "
|
|
252
|
+
f"dirigera_token='***', "
|
|
253
|
+
f"mqtt_host={self.mqtt_host!r}, "
|
|
254
|
+
f"mqtt_port={self.mqtt_port}, "
|
|
255
|
+
f"mqtt_user={self.mqtt_user!r}, "
|
|
256
|
+
f"mqtt_password='***', "
|
|
257
|
+
f"mqtt_client_id={self.mqtt_client_id!r}, "
|
|
258
|
+
f"mqtt_keepalive={self.mqtt_keepalive}, "
|
|
259
|
+
f"mqtt_base_topic={self.mqtt_base_topic!r}, "
|
|
260
|
+
f"mqtt_qos={self.mqtt_qos}, "
|
|
261
|
+
f"mqtt_tls={self.mqtt_tls}, "
|
|
262
|
+
f"mqtt_reconnect={self.mqtt_reconnect}, "
|
|
263
|
+
f"mqtt_reconnect_delay_min={self.mqtt_reconnect_delay_min}, "
|
|
264
|
+
f"mqtt_reconnect_delay_max={self.mqtt_reconnect_delay_max}, "
|
|
265
|
+
f"discovery_prefix={self.discovery_prefix!r}, "
|
|
266
|
+
f"log_level={self.log_level!r}, "
|
|
267
|
+
f"metrics_interval={self.metrics_interval}, "
|
|
268
|
+
f"ws_ping_interval={self.ws_ping_interval}, "
|
|
269
|
+
f"ws_ping_timeout={self.ws_ping_timeout}, "
|
|
270
|
+
f"reconnect_delay_initial={self.reconnect_delay_initial}, "
|
|
271
|
+
f"reconnect_delay_max={self.reconnect_delay_max}"
|
|
272
|
+
f")"
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
# ── Public API ────────────────────────────────────────────────────────────────
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def load_settings(env_file: str | None = None) -> Settings:
|
|
280
|
+
"""
|
|
281
|
+
Load, validate, and cache the application settings.
|
|
282
|
+
|
|
283
|
+
Reads environment variables after loading the .env file.
|
|
284
|
+
Validates every value — including cross-field constraints — and
|
|
285
|
+
raises immediately on any problem so configuration errors surface
|
|
286
|
+
at startup rather than mid-operation.
|
|
287
|
+
|
|
288
|
+
Stores the result as a module-level singleton accessible via
|
|
289
|
+
get_settings(). Calling load_settings() a second time reloads
|
|
290
|
+
and replaces the singleton — useful in tests that inject different
|
|
291
|
+
configuration.
|
|
292
|
+
|
|
293
|
+
Args:
|
|
294
|
+
env_file (str | None): Path to the .env file. If None, looks
|
|
295
|
+
for '.env' in the current working
|
|
296
|
+
directory (standard dotenv behavior).
|
|
297
|
+
|
|
298
|
+
Returns:
|
|
299
|
+
Settings: Fully validated, immutable settings object.
|
|
300
|
+
|
|
301
|
+
Raises:
|
|
302
|
+
DirigeraBridgeError: CONFIG_MISSING_FIELD if a required
|
|
303
|
+
variable is absent or empty.
|
|
304
|
+
DirigeraBridgeError: CONFIG_INVALID_VALUE if any value fails
|
|
305
|
+
type, range, or cross-field validation.
|
|
306
|
+
"""
|
|
307
|
+
|
|
308
|
+
global _settings
|
|
309
|
+
|
|
310
|
+
# ── Load .env file ────────────────────────────────────────────────────
|
|
311
|
+
# override=False (the default) is intentional: environment
|
|
312
|
+
# variables already set — by the shell, Docker's `environment:`
|
|
313
|
+
# block, or a test's monkeypatch — must take priority over
|
|
314
|
+
# whatever is in the .env file on disk. The .env file only fills
|
|
315
|
+
# in values that aren't already set. Using override=True here
|
|
316
|
+
# previously caused a real .env file in the project root to
|
|
317
|
+
# silently clobber test-injected environment variables.
|
|
318
|
+
loaded = load_dotenv(env_file, override=False) if env_file else load_dotenv(override=False)
|
|
319
|
+
|
|
320
|
+
logger.debug(
|
|
321
|
+
"dotenv loaded: %s (env_file=%r)",
|
|
322
|
+
"yes" if loaded else "no file found — using os environment",
|
|
323
|
+
env_file,
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
# ── Required fields ───────────────────────────────────────────────────
|
|
327
|
+
dirigera_ip = _require_str("DIRIGERA_IP")
|
|
328
|
+
dirigera_token = _require_str("DIRIGERA_TOKEN")
|
|
329
|
+
mqtt_host = _require_str("MQTT_HOST")
|
|
330
|
+
mqtt_user = _require_str("MQTT_USER")
|
|
331
|
+
mqtt_password = _require_str("MQTT_PASSWORD")
|
|
332
|
+
|
|
333
|
+
# ── MQTT optional fields ──────────────────────────────────────────────
|
|
334
|
+
mqtt_port = _optional_int("MQTT_PORT", default=1883, min_val=1, max_val=65535)
|
|
335
|
+
mqtt_client_id = _optional_str("MQTT_CLIENT_ID", default="dirigera-bridge")
|
|
336
|
+
mqtt_keepalive = _optional_int("MQTT_KEEPALIVE", default=60, min_val=1)
|
|
337
|
+
mqtt_base_topic = _optional_str("MQTT_BASE_TOPIC", default="dirigera")
|
|
338
|
+
mqtt_qos = _optional_int("MQTT_QOS", default=1, min_val=0, max_val=2)
|
|
339
|
+
mqtt_tls = _optional_bool("MQTT_TLS", default=False)
|
|
340
|
+
mqtt_reconnect = _optional_bool("MQTT_RECONNECT", default=True)
|
|
341
|
+
mqtt_reconnect_delay_min = _optional_float("MQTT_RECONNECT_DELAY_MIN", default=1.0, min_val=0.1)
|
|
342
|
+
mqtt_reconnect_delay_max = _optional_float(
|
|
343
|
+
"MQTT_RECONNECT_DELAY_MAX", default=60.0, min_val=1.0
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
# ── HA optional fields ────────────────────────────────────────────────
|
|
347
|
+
discovery_prefix = _optional_str("DISCOVERY_PREFIX", default="homeassistant")
|
|
348
|
+
|
|
349
|
+
# ── Operational optional fields ───────────────────────────────────────
|
|
350
|
+
log_level = _optional_log_level("LOG_LEVEL", default="INFO")
|
|
351
|
+
metrics_interval = _optional_int("METRICS_INTERVAL", default=300, min_val=10)
|
|
352
|
+
ws_ping_interval = _optional_int("WS_PING_INTERVAL", default=30, min_val=5)
|
|
353
|
+
ws_ping_timeout = _optional_int("WS_PING_TIMEOUT", default=10, min_val=1)
|
|
354
|
+
reconnect_delay_initial = _optional_float("RECONNECT_DELAY_INITIAL", default=1.0, min_val=0.1)
|
|
355
|
+
reconnect_delay_max = _optional_float("RECONNECT_DELAY_MAX", default=60.0, min_val=1.0)
|
|
356
|
+
|
|
357
|
+
# ── Cross-field validation ────────────────────────────────────────────
|
|
358
|
+
if reconnect_delay_max < reconnect_delay_initial:
|
|
359
|
+
raise DirigeraBridgeError(
|
|
360
|
+
ErrorCode.CONFIG_INVALID_VALUE,
|
|
361
|
+
f"RECONNECT_DELAY_MAX ({reconnect_delay_max}) must be >= "
|
|
362
|
+
f"RECONNECT_DELAY_INITIAL ({reconnect_delay_initial})",
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
if ws_ping_timeout >= ws_ping_interval:
|
|
366
|
+
raise DirigeraBridgeError(
|
|
367
|
+
ErrorCode.CONFIG_INVALID_VALUE,
|
|
368
|
+
f"WS_PING_TIMEOUT ({ws_ping_timeout}) must be < WS_PING_INTERVAL ({ws_ping_interval})",
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
if mqtt_keepalive <= ws_ping_timeout:
|
|
372
|
+
raise DirigeraBridgeError(
|
|
373
|
+
ErrorCode.CONFIG_INVALID_VALUE,
|
|
374
|
+
f"MQTT_KEEPALIVE ({mqtt_keepalive}) should be > "
|
|
375
|
+
f"WS_PING_TIMEOUT ({ws_ping_timeout}) to avoid "
|
|
376
|
+
f"premature broker disconnects during WebSocket probes",
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
if mqtt_reconnect_delay_max < mqtt_reconnect_delay_min:
|
|
380
|
+
raise DirigeraBridgeError(
|
|
381
|
+
ErrorCode.CONFIG_INVALID_VALUE,
|
|
382
|
+
f"MQTT_RECONNECT_DELAY_MAX ({mqtt_reconnect_delay_max}) must be >= "
|
|
383
|
+
f"MQTT_RECONNECT_DELAY_MIN ({mqtt_reconnect_delay_min})",
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
# ── Construct and cache ───────────────────────────────────────────────
|
|
387
|
+
_settings = Settings(
|
|
388
|
+
dirigera_ip=dirigera_ip,
|
|
389
|
+
dirigera_token=dirigera_token,
|
|
390
|
+
mqtt_host=mqtt_host,
|
|
391
|
+
mqtt_port=mqtt_port,
|
|
392
|
+
mqtt_user=mqtt_user,
|
|
393
|
+
mqtt_password=mqtt_password,
|
|
394
|
+
mqtt_client_id=mqtt_client_id,
|
|
395
|
+
mqtt_keepalive=mqtt_keepalive,
|
|
396
|
+
mqtt_base_topic=mqtt_base_topic,
|
|
397
|
+
mqtt_qos=mqtt_qos,
|
|
398
|
+
mqtt_tls=mqtt_tls,
|
|
399
|
+
mqtt_reconnect=mqtt_reconnect,
|
|
400
|
+
mqtt_reconnect_delay_min=mqtt_reconnect_delay_min,
|
|
401
|
+
mqtt_reconnect_delay_max=mqtt_reconnect_delay_max,
|
|
402
|
+
discovery_prefix=discovery_prefix,
|
|
403
|
+
log_level=log_level,
|
|
404
|
+
metrics_interval=metrics_interval,
|
|
405
|
+
ws_ping_interval=ws_ping_interval,
|
|
406
|
+
ws_ping_timeout=ws_ping_timeout,
|
|
407
|
+
reconnect_delay_initial=reconnect_delay_initial,
|
|
408
|
+
reconnect_delay_max=reconnect_delay_max,
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
assert _settings is not None
|
|
412
|
+
logger.info("Settings loaded: %s", _settings.safe_repr())
|
|
413
|
+
|
|
414
|
+
return _settings
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def get_settings() -> Settings:
|
|
418
|
+
"""
|
|
419
|
+
Return the cached Settings singleton.
|
|
420
|
+
|
|
421
|
+
Must be called after load_settings() has been called at least once.
|
|
422
|
+
Raises immediately if called before load_settings() so that
|
|
423
|
+
missing startup initialization is caught early and clearly.
|
|
424
|
+
|
|
425
|
+
Returns:
|
|
426
|
+
Settings: The cached settings object.
|
|
427
|
+
|
|
428
|
+
Raises:
|
|
429
|
+
DirigeraBridgeError: LIFECYCLE_STARTUP_FAILED if load_settings()
|
|
430
|
+
has not been called yet.
|
|
431
|
+
"""
|
|
432
|
+
|
|
433
|
+
if _settings is None:
|
|
434
|
+
raise DirigeraBridgeError(
|
|
435
|
+
ErrorCode.LIFECYCLE_STARTUP_FAILED,
|
|
436
|
+
"get_settings() called before load_settings() — "
|
|
437
|
+
"call load_settings() during application startup",
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
return _settings
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
# ── Internal helpers ──────────────────────────────────────────────────────────
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _require_str(key: str) -> str:
|
|
447
|
+
"""
|
|
448
|
+
Read a required environment variable as a non-empty string.
|
|
449
|
+
|
|
450
|
+
Raises:
|
|
451
|
+
DirigeraBridgeError: CONFIG_MISSING_FIELD if absent or empty.
|
|
452
|
+
"""
|
|
453
|
+
|
|
454
|
+
value = os.environ.get(key, "").strip()
|
|
455
|
+
|
|
456
|
+
if not value:
|
|
457
|
+
raise DirigeraBridgeError(
|
|
458
|
+
ErrorCode.CONFIG_MISSING_FIELD,
|
|
459
|
+
f"Required environment variable '{key}' is missing or empty",
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
return value
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
_TRUE_VALUES = {"1", "true", "yes", "on"}
|
|
466
|
+
_FALSE_VALUES = {"0", "false", "no", "off"}
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _optional_bool(key: str, default: bool) -> bool:
|
|
470
|
+
"""
|
|
471
|
+
Read an optional environment variable as a boolean.
|
|
472
|
+
|
|
473
|
+
Accepts (case-insensitive): '1'/'0', 'true'/'false', 'yes'/'no',
|
|
474
|
+
'on'/'off'. Uses default if absent or empty.
|
|
475
|
+
|
|
476
|
+
Raises:
|
|
477
|
+
DirigeraBridgeError: CONFIG_INVALID_VALUE if the value is
|
|
478
|
+
not a recognised boolean string.
|
|
479
|
+
"""
|
|
480
|
+
|
|
481
|
+
raw = os.environ.get(key, "").strip()
|
|
482
|
+
|
|
483
|
+
if not raw:
|
|
484
|
+
return default
|
|
485
|
+
|
|
486
|
+
lowered = raw.lower()
|
|
487
|
+
|
|
488
|
+
if lowered in _TRUE_VALUES:
|
|
489
|
+
return True
|
|
490
|
+
|
|
491
|
+
if lowered in _FALSE_VALUES:
|
|
492
|
+
return False
|
|
493
|
+
|
|
494
|
+
raise DirigeraBridgeError(
|
|
495
|
+
ErrorCode.CONFIG_INVALID_VALUE,
|
|
496
|
+
f"Environment variable '{key}' must be a boolean "
|
|
497
|
+
f"(1/0, true/false, yes/no, on/off), got {raw!r}",
|
|
498
|
+
)
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def _optional_str(key: str, default: str) -> str:
|
|
502
|
+
"""
|
|
503
|
+
Read an optional environment variable as a string.
|
|
504
|
+
|
|
505
|
+
Returns default if absent or empty.
|
|
506
|
+
"""
|
|
507
|
+
|
|
508
|
+
value = os.environ.get(key, "").strip()
|
|
509
|
+
return value if value else default
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _optional_int(
|
|
513
|
+
key: str,
|
|
514
|
+
default: int,
|
|
515
|
+
min_val: int,
|
|
516
|
+
max_val: int | None = None,
|
|
517
|
+
) -> int:
|
|
518
|
+
"""
|
|
519
|
+
Read an optional environment variable as an integer.
|
|
520
|
+
|
|
521
|
+
Uses default if absent or empty. Validates min_val and optional
|
|
522
|
+
max_val.
|
|
523
|
+
|
|
524
|
+
Raises:
|
|
525
|
+
DirigeraBridgeError: CONFIG_INVALID_VALUE if non-parseable
|
|
526
|
+
or out of range.
|
|
527
|
+
"""
|
|
528
|
+
|
|
529
|
+
raw = os.environ.get(key, "").strip()
|
|
530
|
+
|
|
531
|
+
if not raw:
|
|
532
|
+
return default
|
|
533
|
+
|
|
534
|
+
try:
|
|
535
|
+
value = int(raw)
|
|
536
|
+
except ValueError as exc:
|
|
537
|
+
raise DirigeraBridgeError(
|
|
538
|
+
ErrorCode.CONFIG_INVALID_VALUE,
|
|
539
|
+
f"Environment variable '{key}' must be an integer, got {raw!r}",
|
|
540
|
+
) from exc
|
|
541
|
+
|
|
542
|
+
if value < min_val:
|
|
543
|
+
raise DirigeraBridgeError(
|
|
544
|
+
ErrorCode.CONFIG_INVALID_VALUE,
|
|
545
|
+
f"Environment variable '{key}' must be >= {min_val}, got {value}",
|
|
546
|
+
)
|
|
547
|
+
|
|
548
|
+
if max_val is not None and value > max_val:
|
|
549
|
+
raise DirigeraBridgeError(
|
|
550
|
+
ErrorCode.CONFIG_INVALID_VALUE,
|
|
551
|
+
f"Environment variable '{key}' must be <= {max_val}, got {value}",
|
|
552
|
+
)
|
|
553
|
+
|
|
554
|
+
return value
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def _optional_float(
|
|
558
|
+
key: str,
|
|
559
|
+
default: float,
|
|
560
|
+
min_val: float,
|
|
561
|
+
) -> float:
|
|
562
|
+
"""
|
|
563
|
+
Read an optional environment variable as a float.
|
|
564
|
+
|
|
565
|
+
Uses default if absent or empty. Validates min_val only.
|
|
566
|
+
|
|
567
|
+
Raises:
|
|
568
|
+
DirigeraBridgeError: CONFIG_INVALID_VALUE if non-parseable
|
|
569
|
+
or below min_val.
|
|
570
|
+
"""
|
|
571
|
+
|
|
572
|
+
raw = os.environ.get(key, "").strip()
|
|
573
|
+
|
|
574
|
+
if not raw:
|
|
575
|
+
return default
|
|
576
|
+
|
|
577
|
+
try:
|
|
578
|
+
value = float(raw)
|
|
579
|
+
except ValueError as exc:
|
|
580
|
+
raise DirigeraBridgeError(
|
|
581
|
+
ErrorCode.CONFIG_INVALID_VALUE,
|
|
582
|
+
f"Environment variable '{key}' must be a number, got {raw!r}",
|
|
583
|
+
) from exc
|
|
584
|
+
|
|
585
|
+
if value < min_val:
|
|
586
|
+
raise DirigeraBridgeError(
|
|
587
|
+
ErrorCode.CONFIG_INVALID_VALUE,
|
|
588
|
+
f"Environment variable '{key}' must be >= {min_val}, got {value}",
|
|
589
|
+
)
|
|
590
|
+
|
|
591
|
+
return value
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def _optional_log_level(key: str, default: str) -> str:
|
|
595
|
+
"""
|
|
596
|
+
Read an optional environment variable as a logging level string.
|
|
597
|
+
|
|
598
|
+
Valid values: DEBUG, INFO, WARNING, ERROR, CRITICAL (case-insensitive).
|
|
599
|
+
Returns the value uppercased. Uses default if absent or empty.
|
|
600
|
+
|
|
601
|
+
Raises:
|
|
602
|
+
DirigeraBridgeError: CONFIG_INVALID_VALUE if not a valid level.
|
|
603
|
+
"""
|
|
604
|
+
|
|
605
|
+
raw = os.environ.get(key, "").strip()
|
|
606
|
+
|
|
607
|
+
if not raw:
|
|
608
|
+
return default
|
|
609
|
+
|
|
610
|
+
upper = raw.upper()
|
|
611
|
+
|
|
612
|
+
if upper not in _VALID_LOG_LEVELS:
|
|
613
|
+
raise DirigeraBridgeError(
|
|
614
|
+
ErrorCode.CONFIG_INVALID_VALUE,
|
|
615
|
+
f"Environment variable '{key}' must be one of {sorted(_VALID_LOG_LEVELS)}, got {raw!r}",
|
|
616
|
+
)
|
|
617
|
+
|
|
618
|
+
return upper
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""
|
|
2
|
+
app/core — cross-cutting infrastructure.
|
|
3
|
+
|
|
4
|
+
Exports the primary symbols used across the application so callers
|
|
5
|
+
can import from 'app.core' directly rather than from submodules.
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .discovery_cache import DiscoveryCache
|
|
10
|
+
from .errors import DirigeraBridgeError, ErrorCode
|
|
11
|
+
from .event_bus import AsyncEventBus, DirigeraEvent, EventType
|
|
12
|
+
from .lifecycle import LifecycleState, ServiceLifecycle
|
|
13
|
+
from .metrics import MetricName, MetricsStore
|
|
14
|
+
from .retry import RetryConfig, retry_with_backoff
|
|
15
|
+
from .state_cache import StateCache
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
# Discovery Cache
|
|
19
|
+
"DiscoveryCache",
|
|
20
|
+
# Errors
|
|
21
|
+
"DirigeraBridgeError",
|
|
22
|
+
"ErrorCode",
|
|
23
|
+
# Event Bus
|
|
24
|
+
"AsyncEventBus",
|
|
25
|
+
"DirigeraEvent",
|
|
26
|
+
"EventType",
|
|
27
|
+
# Lifecycle
|
|
28
|
+
"ServiceLifecycle",
|
|
29
|
+
"LifecycleState",
|
|
30
|
+
# Metrics
|
|
31
|
+
"MetricsStore",
|
|
32
|
+
"MetricName",
|
|
33
|
+
# Retry
|
|
34
|
+
"RetryConfig",
|
|
35
|
+
"retry_with_backoff",
|
|
36
|
+
# State Cache
|
|
37
|
+
"StateCache",
|
|
38
|
+
]
|