dirigera-bridge 1.0.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 (52) hide show
  1. dirigera_bridge-1.0.0/LICENSE +21 -0
  2. dirigera_bridge-1.0.0/PKG-INFO +532 -0
  3. dirigera_bridge-1.0.0/README.md +497 -0
  4. dirigera_bridge-1.0.0/dirigera_bridge/__init__.py +36 -0
  5. dirigera_bridge-1.0.0/dirigera_bridge/__main__.py +6 -0
  6. dirigera_bridge-1.0.0/dirigera_bridge/config.py +618 -0
  7. dirigera_bridge-1.0.0/dirigera_bridge/core/__init__.py +38 -0
  8. dirigera_bridge-1.0.0/dirigera_bridge/core/discovery_cache.py +445 -0
  9. dirigera_bridge-1.0.0/dirigera_bridge/core/errors.py +202 -0
  10. dirigera_bridge-1.0.0/dirigera_bridge/core/event_bus.py +436 -0
  11. dirigera_bridge-1.0.0/dirigera_bridge/core/lifecycle.py +506 -0
  12. dirigera_bridge-1.0.0/dirigera_bridge/core/metrics.py +307 -0
  13. dirigera_bridge-1.0.0/dirigera_bridge/core/retry.py +394 -0
  14. dirigera_bridge-1.0.0/dirigera_bridge/core/state_cache.py +423 -0
  15. dirigera_bridge-1.0.0/dirigera_bridge/dirigera/__init__.py +45 -0
  16. dirigera_bridge-1.0.0/dirigera_bridge/dirigera/models.py +539 -0
  17. dirigera_bridge-1.0.0/dirigera_bridge/dirigera/rest_client.py +606 -0
  18. dirigera_bridge-1.0.0/dirigera_bridge/dirigera/websocket_client.py +763 -0
  19. dirigera_bridge-1.0.0/dirigera_bridge/factory.py +146 -0
  20. dirigera_bridge-1.0.0/dirigera_bridge/ha/__init__.py +21 -0
  21. dirigera_bridge-1.0.0/dirigera_bridge/ha/ha_client.py +681 -0
  22. dirigera_bridge-1.0.0/dirigera_bridge/main.py +173 -0
  23. dirigera_bridge-1.0.0/dirigera_bridge/mapping/__init__.py +62 -0
  24. dirigera_bridge-1.0.0/dirigera_bridge/mapping/command_mapper.py +566 -0
  25. dirigera_bridge-1.0.0/dirigera_bridge/mapping/device_mapper.py +343 -0
  26. dirigera_bridge-1.0.0/dirigera_bridge/mapping/device_registry.py +395 -0
  27. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/__init__.py +360 -0
  28. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/air_purifier.py +275 -0
  29. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/binary_sensor.py +254 -0
  30. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/blind.py +203 -0
  31. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/button.py +200 -0
  32. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/environment_sensor.py +296 -0
  33. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/gateway.py +393 -0
  34. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/light.py +320 -0
  35. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/outlet.py +321 -0
  36. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/remote.py +213 -0
  37. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/sensor.py +189 -0
  38. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/speaker.py +342 -0
  39. dirigera_bridge-1.0.0/dirigera_bridge/mapping/domains/switch.py +153 -0
  40. dirigera_bridge-1.0.0/dirigera_bridge/mapping/state_mapper.py +1112 -0
  41. dirigera_bridge-1.0.0/dirigera_bridge/orchestrator.py +1029 -0
  42. dirigera_bridge-1.0.0/dirigera_bridge/py.typed +1 -0
  43. dirigera_bridge-1.0.0/dirigera_bridge.egg-info/PKG-INFO +532 -0
  44. dirigera_bridge-1.0.0/dirigera_bridge.egg-info/SOURCES.txt +50 -0
  45. dirigera_bridge-1.0.0/dirigera_bridge.egg-info/dependency_links.txt +1 -0
  46. dirigera_bridge-1.0.0/dirigera_bridge.egg-info/entry_points.txt +2 -0
  47. dirigera_bridge-1.0.0/dirigera_bridge.egg-info/requires.txt +14 -0
  48. dirigera_bridge-1.0.0/dirigera_bridge.egg-info/top_level.txt +1 -0
  49. dirigera_bridge-1.0.0/pyproject.toml +131 -0
  50. dirigera_bridge-1.0.0/setup.cfg +4 -0
  51. dirigera_bridge-1.0.0/tests/test_factory.py +109 -0
  52. dirigera_bridge-1.0.0/tests/test_main.py +421 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dickkouwenhoven
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,532 @@
1
+ Metadata-Version: 2.4
2
+ Name: dirigera_bridge
3
+ Version: 1.0.0
4
+ Summary: A python service that bridges an IKEA Dirigera hub to Home Assistant via MQTT.
5
+ Author-email: Dick Kouwenhoven <dick.kouwenhoven@planet.nl>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/dickkouwenhoven/Dirigera-Bridge
8
+ Project-URL: Repository, https://github.com/dickkouwenhoven/Dirigera-Bridge
9
+ Project-URL: Issues, https://github.com/dickkouwenhoven/Dirigera-Bridge/issues
10
+ Project-URL: Changelog, https://github.com/dickkouwenhoven/Dirigera-Bridge/releases
11
+ Keywords: homeassistant,mqtt,iot,automation,python,smarthome
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Topic :: Home Automation
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Requires-Python: >=3.12
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: aiohttp<4.0,>=3.9
22
+ Requires-Dist: aiomqtt<3.0,>=2.5.1
23
+ Requires-Dist: ha_mqtt_sdk<2.0,>=0.8.4
24
+ Requires-Dist: pydantic<3.0,>=2.13.4
25
+ Requires-Dist: python-dotenv<2.0,>=1.2.3
26
+ Requires-Dist: websockets<17.0,>=16.0
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=9.0.0; extra == "dev"
29
+ Requires-Dist: pytest-cov>=7.0.0; extra == "dev"
30
+ Requires-Dist: pytest-asyncio>=1.0.0; extra == "dev"
31
+ Requires-Dist: ruff>=0.15.0; extra == "dev"
32
+ Requires-Dist: mypy>=2.0.0; extra == "dev"
33
+ Requires-Dist: pre-commit>=4.0.0; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # Dirigera MQTT Bridge
37
+
38
+ A Python service that bridges an **IKEA Dirigera hub** to **Home Assistant** via **MQTT**.
39
+
40
+ The bridge connects to the Dirigera hub over WebSocket (real-time events), forwards device state changes to Home Assistant via MQTT discovery,
41
+ and translates Home Assistant commands back to the Dirigera REST API.
42
+
43
+ ---
44
+
45
+ ## Architecture overview
46
+
47
+ ```
48
+ ┌─────────────────┐ WebSocket ┌─────────────────────────┐
49
+ │ Dirigera Hub │ ◄─────────────────► │ │
50
+ │ (IKEA) │ │ dirigera-mqtt-bridge │
51
+ │ │ ◄── REST (PATCH) ── │ │
52
+ └─────────────────┘ └──────────┬──────────────┘
53
+ │ MQTT
54
+ ▼
55
+ ┌──────────────────┐
56
+ │ Mosquitto │
57
+ │ MQTT Broker │
58
+ └──────────┬───────┘
59
+ │ MQTT discovery
60
+ ▼
61
+ ┌──────────────────┐
62
+ │ Home Assistant │
63
+ └──────────────────┘
64
+ ```
65
+
66
+ ### Four-layer design
67
+
68
+ | Layer | Responsibility |
69
+ |-------------------------|-----------------------------------------------------------------------------------------------------------------------|
70
+ | **Dirigera layer** | WebSocket listener + REST client. Knows nothing about MQTT or HA. |
71
+ | **Mapping layer** | Translates Dirigera device models → HA entities and events → state payloads. Plugin-based — one file per device type. |
72
+ | **MQTT layer** | Owned entirely by the HASDK (`AsyncEntityManager`). No raw aiomqtt calls in application code. |
73
+ | **Orchestration layer** | Wires all layers together. Manages startup, shutdown, reconnect, and event routing. |
74
+
75
+ ---
76
+
77
+ ## Supported devices
78
+
79
+ All device types supported by the Dirigera hub are handled. Devices confirmed from real discovery data:
80
+
81
+ | Dirigera deviceType | HA domain(s) | Example device |
82
+ |---------------------------------|-----------------------------------------------------|-------------------------------|
83
+ | `light` | `light` | TRADFRI bulb GU10 CWS / WS |
84
+ | `outlet` | `switch` + `sensor` ×4 | INSPELNING Smart plug (E2206) |
85
+ | `lightController` | `event` + `sensor` (battery) | Remote Control N2 (E2001) |
86
+ | `motionSensor` | `binary_sensor` + `sensor` (battery) | VALLHORN (E2134) |
87
+ | `lightSensor` | `sensor` (illuminance) | VALLHORN sibling |
88
+ | `waterSensor` | `binary_sensor` + `sensor` (battery) | BADRING (E2202) |
89
+ | `environmentSensor` | `sensor` ×4 | VINDSTYRKA (E2112) |
90
+ | `gateway` | `binary_sensor` ×2 + `sensor` ×7 + `device_tracker` | DIRIGERA Hub |
91
+ | `blind` / `blinds` | `cover` | PRAKTLYSING / KADRILJ |
92
+ | `airPurifier` | `fan` + `sensor` ×2 | STARKVIND (E2007) |
93
+ | `speaker` | `media_player` | SYMFONISK |
94
+ | `switch` | `switch` | Generic switch |
95
+ | `button` / `shortcutController` | `event` + `sensor` (battery) | SOMRIG (E2213) |
96
+
97
+ Multi-deviceType physical devices (e.g. VALLHORN with `motionSensor` + `lightSensor`) are automatically grouped under one physical device in Home Assistant using
98
+ the `relationId` from the Dirigera discovery payload.
99
+
100
+ ---
101
+
102
+ ## Project structure
103
+
104
+ ```
105
+ Dirigera-Bridge/
106
+ ├── .env ← Runtime configuration (never commit)
107
+ ├── .env.example ← Template with descriptions and defaults
108
+ ├── Dockerfile ← Two-stage build (builder + runtime)
109
+ ├── docker-compose.yml ← Service definition
110
+ ├── pyproject.toml ← Package metadata, console script, dev deps
111
+ ├── README.md
112
+ └── dirigera_bridge/
113
+ ├── __init__.py ← Public library API (see "Two ways to use this project")
114
+ ├── __main__.py ← `python -m dirigera_bridge` entry point
115
+ ├── main.py ← CLI/Docker composition root: .env, logging, signals
116
+ ├── factory.py ← build_orchestrator() — the library's composition root
117
+ ├── config.py ← Typed settings from .env
118
+ ├── orchestrator.py ← Service lifecycle + event routing
119
+ ├── core/
120
+ │ ├── errors.py ← Centralised error types
121
+ │ ├── event_bus.py ← Async internal pub/sub
122
+ │ ├── lifecycle.py ← Service state machine
123
+ │ ├── metrics.py ← In-memory counters
124
+ │ ├── retry.py ← Exponential backoff utility
125
+ │ ├── state_cache.py ← Device state deduplication cache
126
+ │ └── discovery_cache.py ← HA entity registration cache
127
+ ├── dirigera/
128
+ │ ├── models.py ← Pydantic models for Dirigera payloads
129
+ │ ├── rest_client.py ← Dirigera REST API (PATCH commands)
130
+ │ └── websocket_client.py ← Dirigera WebSocket event stream
131
+ ├── mapping/
132
+ │ ├── device_registry.py ← Groups logical devices by physical device
133
+ │ ├── device_mapper.py ← Routes DeviceContext → HA entities
134
+ │ ├── state_mapper.py ← Dirigera attribute → HA state payload
135
+ │ ├── command_mapper.py ← HA command → Dirigera REST payload
136
+ │ └── domains/
137
+ │ ├── __init__.py ← Plugin registry + shared helpers
138
+ │ ├── gateway.py
139
+ │ ├── light.py
140
+ │ ├── outlet.py
141
+ │ ├── binary_sensor.py
142
+ │ ├── sensor.py
143
+ │ ├── environment_sensor.py
144
+ │ ├── remote.py
145
+ │ ├── blind.py
146
+ │ ├── switch.py
147
+ │ ├── button.py
148
+ │ ├── air_purifier.py
149
+ │ └── speaker.py
150
+ └── ha/
151
+ └── ha_client.py ← HASDK AsyncEntityManager wrapper
152
+ ```
153
+
154
+ ---
155
+
156
+ ## Two ways to use this project
157
+
158
+ This project ships as a single installable package that serves two different users.
159
+
160
+ **1. As an application** — if you just want your Dirigera hub integrated with Home Assistant and nothing else, run it as-is: `docker compose up -d --build`, or `python -m dirigera_bridge` outside Docker. Everything is configured through `.env`. This is what the [Fully implementing this application](#fully-implementing-this-application) section below walks through end to end.
161
+
162
+ **2. As a library** — if you're bridging more than one hub vendor (say, Dirigera *and* Philips Hue) into the same Home Assistant instance, you don't need to run two unrelated services side by side. Install this package and import its public API directly:
163
+
164
+ ```python
165
+ from dirigera_bridge import Settings, load_settings, build_orchestrator
166
+
167
+ # load_settings() reads .env, or build a Settings instance yourself
168
+ dirigera_settings = load_settings()
169
+ dirigera_orchestrator = build_orchestrator(dirigera_settings)
170
+
171
+ # construct your other vendor's bridge the same way, e.g.:
172
+ # from philips_hue_bridge import build_orchestrator as build_hue_orchestrator
173
+ # hue_orchestrator = build_hue_orchestrator(hue_settings)
174
+
175
+ await dirigera_orchestrator.run()
176
+ # await asyncio.gather(dirigera_orchestrator.run(), hue_orchestrator.run())
177
+ ```
178
+
179
+ The public surface is deliberately small: `Orchestrator`, `Settings`, `load_settings`, and `build_orchestrator`. Everything `build_orchestrator()` constructs — the WebSocket/REST clients, the MQTT client, the mapping layer — is fully self-contained per call. Each `Orchestrator` owns its own MQTT connection, so running several bridges concurrently is just running several `Orchestrator`s side by side; there's no shared connection state to coordinate between vendors.
180
+
181
+ Internal modules (`dirigera_bridge.core`, `dirigera_bridge.mapping`, etc.) are technically importable too, but aren't part of the supported public API — they can change without notice between versions. Build against `dirigera_bridge.__init__`'s exports.
182
+
183
+ ---
184
+
185
+ ## Prerequisites
186
+
187
+ - A machine running Docker and Docker Compose (this project is built and tested for Raspberry Pi 5 / linux/arm64, but the image is portable to any Docker host)
188
+ - An IKEA Dirigera hub on the local network
189
+ - A Dirigera access token (see [Obtaining the Dirigera token](#obtaining-the-dirigera-token))
190
+ - A running MQTT broker — see [Setting up an MQTT broker](#setting-up-an-mqtt-broker) if you don't have one yet
191
+ - Home Assistant running, with its MQTT integration enabled — see [Enabling MQTT in Home Assistant](#enabling-mqtt-in-home-assistant)
192
+ - A Docker bridge network shared by the bridge, the broker, and Home Assistant (this project's `docker-compose.yml` expects one named `iot_network`)
193
+
194
+ ---
195
+
196
+ ## Enabling MQTT in Home Assistant
197
+
198
+ Home Assistant doesn't talk to this bridge directly — everything flows through MQTT, so Home Assistant's own MQTT integration has to be configured first, or nothing this bridge publishes will show up.
199
+
200
+ 1. **Have a broker reachable from Home Assistant.** If you don't have one yet, do the [broker setup](#setting-up-an-mqtt-broker) section below first — Home Assistant's MQTT integration is a client, not a broker; it needs one to connect to.
201
+
202
+ 2. **Add the MQTT integration.**
203
+ - In Home Assistant, go to **Settings → Devices & services**.
204
+ - Click **Add Integration** (bottom right) and select **MQTT**.
205
+ - If you're running the official Mosquitto broker *add-on* inside a Home Assistant OS/Supervised install, Home Assistant can auto-configure this step for you — it generates a broker user/password automatically. If you're running Mosquitto as a **separate Docker container** (the setup this bridge assumes), choose the manual option instead.
206
+
207
+ 3. **Enter your broker's connection details.**
208
+ - **Broker:** the broker's hostname or IP. If Home Assistant and the broker are both Docker containers on the same network, use the broker's *container name* (e.g. `mosquitto`) rather than an IP — container names resolve automatically on a shared Docker bridge network. If Home Assistant lives outside Docker, use the host's IP and the broker's exposed port.
209
+ - **Port:** `1883` for a plain connection (matches this bridge's own `MQTT_PORT` default), or your broker's TLS port if you've enabled TLS.
210
+ - **Username / Password:** the credentials you created for the broker (see the broker setup section — this should be a *separate* MQTT user from the one you give this bridge, so each client's access can be revoked independently).
211
+ - Home Assistant requires the broker to support **MQTT protocol version 5**. The current Mosquitto image (`eclipse-mosquitto:2.x`) supports v5 by default, so this is only a concern with very old broker versions.
212
+ - Submit the form. Home Assistant will test the connection immediately and report an error if it can't reach the broker — double-check the hostname/network and credentials if it fails.
213
+
214
+ 4. **Leave discovery on its default.** Home Assistant listens for MQTT discovery messages on the `homeassistant/` topic prefix by default. This bridge's own `DISCOVERY_PREFIX` setting defaults to `homeassistant` too — leave both at their defaults unless you have a specific reason to change them, and if you do change one, change both to match.
215
+
216
+ 5. **Verify the integration is live.** Go to **Settings → Devices & services** and confirm the **MQTT** tile shows as connected (no error banner). At this point Home Assistant is ready to receive discovery messages — devices won't appear yet until this bridge itself is running and publishing, which the [implementation walkthrough](#fully-implementing-this-application) below covers.
217
+
218
+ 6. **Optional: sanity-check the broker independently of Home Assistant.** From any machine that can reach the broker:
219
+ ```bash
220
+ mosquitto_sub -h <broker-host> -p 1883 -u <user> -P <password> -v -t "homeassistant/#"
221
+ ```
222
+ This subscribes to everything under the discovery prefix. Leave it running, then start this bridge — you should see discovery and state messages appear here as devices come online, which is a faster way to confirm the whole pipeline works than watching the Home Assistant UI alone.
223
+
224
+ ---
225
+
226
+ ## Setting up an MQTT broker
227
+
228
+ If you already have a broker running, skip this section — just make sure you can create a dedicated username/password for this bridge on it. If not, here's a self-contained Mosquitto broker on Docker, matching the network layout `docker-compose.yml` in this repo expects (a shared `iot_network` bridge network, broker reachable by container name).
229
+
230
+ ### 1. Create the config directory
231
+
232
+ ```bash
233
+ mkdir -p ~/mosquitto/config ~/mosquitto/data ~/mosquitto/log
234
+ ```
235
+
236
+ ### 2. Write `mosquitto.conf`
237
+
238
+ ```bash
239
+ cat > ~/mosquitto/config/mosquitto.conf << 'EOF'
240
+ listener 1883
241
+ allow_anonymous false
242
+ password_file /mosquitto/config/passwd
243
+ persistence true
244
+ persistence_location /mosquitto/data/
245
+ log_dest file /mosquitto/log/mosquitto.log
246
+ EOF
247
+ ```
248
+
249
+ Mosquitto 2.x refuses all non-loopback connections unless a listener and an authentication method are both explicitly configured — `allow_anonymous false` plus `password_file` is the minimum needed for this bridge and Home Assistant to authenticate as distinct users.
250
+
251
+ ### 3. Create the Docker network (skip if it already exists)
252
+
253
+ ```bash
254
+ docker network create iot_network
255
+ ```
256
+
257
+ ### 4. Start the broker container
258
+
259
+ ```bash
260
+ docker run -d \
261
+ --name mosquitto \
262
+ --network iot_network \
263
+ --restart always \
264
+ -p 1883:1883 \
265
+ -v ~/mosquitto/config:/mosquitto/config \
266
+ -v ~/mosquitto/data:/mosquitto/data \
267
+ -v ~/mosquitto/log:/mosquitto/log \
268
+ eclipse-mosquitto:2.0
269
+ ```
270
+
271
+ `-p 1883:1883` exposes the broker to the host too (useful for the `mosquitto_sub` sanity check above, or for devices outside Docker); containers on `iot_network` can already reach it by name (`mosquitto`) without this.
272
+
273
+ ### 5. Create broker users
274
+
275
+ Create one user for this bridge and, separately, one for Home Assistant's own MQTT integration — keeping them distinct means you can revoke one client's access without affecting the other.
276
+
277
+ ```bash
278
+ docker exec -it mosquitto mosquitto_passwd -c /mosquitto/config/passwd dirigera_bridge
279
+ docker exec -it mosquitto mosquitto_passwd /mosquitto/config/passwd homeassistant
280
+ ```
281
+
282
+ The first command's `-c` flag *creates* the password file (only use `-c` once — it overwrites any existing file); the second appends a user to the same file. Each command will prompt for a password interactively.
283
+
284
+ ### 6. Restart to pick up the users
285
+
286
+ ```bash
287
+ docker restart mosquitto
288
+ ```
289
+
290
+ ### 7. Verify
291
+
292
+ ```bash
293
+ docker exec -it mosquitto mosquitto_sub -h localhost -p 1883 -u dirigera_bridge -P <password> -t 'test' -C 1 &
294
+ docker exec -it mosquitto mosquitto_pub -h localhost -p 1883 -u dirigera_bridge -P <password> -t 'test' -m 'hello'
295
+ ```
296
+
297
+ If the subscriber prints `hello`, the broker is accepting authenticated connections correctly. Use the `dirigera_bridge` user's credentials as `MQTT_USER`/`MQTT_PASSWORD` in this bridge's `.env`, and the `homeassistant` user's credentials when configuring [Home Assistant's MQTT integration](#enabling-mqtt-in-home-assistant).
298
+
299
+ ---
300
+
301
+ ## Obtaining the Dirigera token
302
+
303
+ The Dirigera hub uses a token-based API. To obtain your token:
304
+
305
+ 1. Install the [dirigera Python library](https://github.com/Leggin/dirigera):
306
+ ```bash
307
+ pip install dirigera
308
+ ```
309
+
310
+ 2. Run the authentication flow:
311
+ ```bash
312
+ python -c "import dirigera; dirigera.create_token('192.168.1.XXX')"
313
+ ```
314
+ Replace `192.168.1.XXX` with your hub's IP address.
315
+
316
+ 3. Follow the on-screen instructions — you will be asked to press the action button on the hub.
317
+
318
+ 4. Copy the token into your `.env` file as `DIRIGERA_TOKEN`.
319
+
320
+ ---
321
+
322
+ ## Fully implementing this application
323
+
324
+ This walks through everything from a bare checkout to a running bridge publishing devices into Home Assistant. It assumes you've already completed [Enabling MQTT in Home Assistant](#enabling-mqtt-in-home-assistant) and [Setting up an MQTT broker](#setting-up-an-mqtt-broker) (or already have both), and that you have your [Dirigera token](#obtaining-the-dirigera-token) in hand.
325
+
326
+ ### 1. Clone the repository
327
+
328
+ ```bash
329
+ git clone https://github.com/dickkouwenhoven/Dirigera-Bridge.git
330
+ cd Dirigera-Bridge
331
+ ```
332
+
333
+ ### 2. Create the shared Docker network (skip if it already exists)
334
+
335
+ ```bash
336
+ docker network create iot_network
337
+ ```
338
+
339
+ If you followed the broker setup above, or already have Home Assistant and Mosquitto running on a shared network, this step is likely already done — `docker network create` fails harmlessly if the network already exists, so it's safe to run either way.
340
+
341
+ ### 3. Configure the environment
342
+
343
+ ```bash
344
+ cp .env.example .env
345
+ ```
346
+
347
+ Edit `.env` and fill in, at minimum, the required values:
348
+
349
+ ```env
350
+ DIRIGERA_IP=192.168.1.XXX # your hub's IP address
351
+ DIRIGERA_TOKEN=your_token_here # from "Obtaining the Dirigera token" above
352
+ MQTT_HOST=mosquitto # the broker's container name, if on the same Docker network
353
+ MQTT_USER=dirigera_bridge # the user you created in the broker setup
354
+ MQTT_PASSWORD=your_broker_password
355
+ ```
356
+
357
+ Everything else in `.env.example` has a working default — see [Configuration reference](#configuration-reference) for the full list, including the MQTT transport-level settings (`MQTT_TLS`, `MQTT_RECONNECT`, `MQTT_RECONNECT_DELAY_MIN`/`MAX`) if your broker setup needs anything beyond the defaults.
358
+
359
+ ### 4. Build and start the bridge
360
+
361
+ ```bash
362
+ docker compose up -d --build
363
+ ```
364
+
365
+ This builds the two-stage image (installing dependencies in a builder layer, then copying only the installed packages and the `dirigera_bridge/` source into a slim runtime layer) and starts the container in the background, attached to `iot_network`.
366
+
367
+ ### 5. Verify it's running
368
+
369
+ ```bash
370
+ docker compose logs -f dirigera-bridge
371
+ ```
372
+
373
+ A successful startup looks like:
374
+
375
+ ```
376
+ INFO dirigera_bridge.main ============================================================
377
+ INFO dirigera_bridge.main dirigera-mqtt-bridge v1.0.0 starting
378
+ INFO dirigera_bridge.main Dirigera hub : 192.168.1.XXX
379
+ INFO dirigera_bridge.main MQTT broker : mosquitto:1883 (client_id=dirigera-bridge)
380
+ INFO dirigera_bridge.orchestrator Orchestrator: startup complete — bridge is RUNNING.
381
+ INFO dirigera_bridge.orchestrator Supported device types: ['airPurifier', 'blind', ...]
382
+ ```
383
+
384
+ If it instead exits immediately with a `CRITICAL Configuration error` line, the message names exactly which `.env` variable is missing or invalid — go back to step 3.
385
+
386
+ ### 6. Confirm devices appear in Home Assistant
387
+
388
+ Go to **Settings → Devices & services → MQTT** in Home Assistant. Within a few seconds of the bridge reaching `RUNNING`, your Dirigera devices should appear as new devices under the MQTT integration, grouped by physical device (a VALLHORN sensor showing as one device with both a motion and illuminance entity, for example — see [Supported devices](#supported-devices)).
389
+
390
+ If nothing appears after a minute:
391
+ - Re-run the [broker sanity check](#setting-up-an-mqtt-broker) (`mosquitto_sub -t "homeassistant/#"`) — if you see messages there but not in Home Assistant, the problem is on the Home Assistant MQTT integration side (check its config against `homeassistant`'s broker credentials, not `dirigera_bridge`'s).
392
+ - If you see nothing at all on the broker, check `docker compose logs -f dirigera-bridge` for connection errors to either the Dirigera hub or the broker — both are logged with a clear error code (see `core/errors.py`'s `ErrorCode` enum for what each one means).
393
+
394
+ ### 7. Ongoing operation
395
+
396
+ - **Updating:** `git pull`, then `docker compose up -d --build` again — Docker Compose rebuilds only what changed.
397
+ - **Stopping cleanly:** `docker compose down` — the bridge handles `SIGTERM` gracefully, marking all entities offline in Home Assistant before exiting (see [Resilience](#resilience)).
398
+ - **Changing configuration:** edit `.env`, then `docker compose restart dirigera-bridge` (no rebuild needed — `.env` is mounted at runtime, not baked into the image).
399
+
400
+ ---
401
+
402
+ ## Adding a new device type
403
+
404
+ The mapping layer is plugin-based. To add support for a new Dirigera device type:
405
+
406
+ 1. Create a new file in `dirigera_bridge/mapping/domains/`, e.g. `my_device.py`
407
+ 2. Implement a mapper function:
408
+ ```python
409
+ def map_my_device(context: DeviceContext, device_info: DeviceInfo) -> List[Entity]: ...
410
+ ```
411
+ 3. Add a `DEVICE_TYPES` dict at the bottom:
412
+ ```python
413
+ DEVICE_TYPES = {
414
+ "myDeviceType": map_my_device,
415
+ }
416
+ ```
417
+ 4. Add the module to `_DOMAIN_MODULES` in `dirigera_bridge/mapping/domains/__init__.py`
418
+ 5. Add state translation to `dirigera_bridge/mapping/state_mapper.py`
419
+ 6. Add command translation to `dirigera_bridge/mapping/command_mapper.py` (if controllable)
420
+
421
+ Nothing else needs to change.
422
+
423
+ ---
424
+
425
+ ## Configuration reference
426
+
427
+ All settings are loaded from `.env` at startup. Invalid or missing required values cause an immediate error with a clear message.
428
+
429
+ | Variable | Required | Default | Description |
430
+ |------------------------------|----------|-------------------|----------------------------------------------------------------|
431
+ | `DIRIGERA_IP` | ✓ | — | IP address of the Dirigera hub |
432
+ | `DIRIGERA_TOKEN` | ✓ | — | Hub access token (secret) |
433
+ | `MQTT_HOST` | ✓ | — | MQTT broker hostname |
434
+ | `MQTT_PORT` | | `1883` | MQTT broker port |
435
+ | `MQTT_USER` | ✓ | — | MQTT username |
436
+ | `MQTT_PASSWORD` | ✓ | — | MQTT password (secret) |
437
+ | `MQTT_CLIENT_ID` | | `dirigera-bridge` | MQTT client identifier |
438
+ | `MQTT_KEEPALIVE` | | `60` | MQTT keepalive interval (seconds) |
439
+ | `MQTT_BASE_TOPIC` | | `dirigera` | Base topic prefix for state/command topics |
440
+ | `MQTT_QOS` | | `1` | MQTT QoS level (0, 1, or 2) |
441
+ | `MQTT_TLS` | | `false` | Use TLS for the MQTT connection |
442
+ | `MQTT_RECONNECT` | | `true` | Let the HASDK auto-reconnect the MQTT transport |
443
+ | `MQTT_RECONNECT_DELAY_MIN` | | `1.0` | Minimum HASDK MQTT reconnect delay (seconds) |
444
+ | `MQTT_RECONNECT_DELAY_MAX` | | `60.0` | Maximum HASDK MQTT reconnect delay (seconds) |
445
+ | `DISCOVERY_PREFIX` | | `homeassistant` | HA MQTT discovery prefix |
446
+ | `LOG_LEVEL` | | `INFO` | Logging level |
447
+ | `METRICS_INTERVAL` | | `300` | Seconds between metrics log snapshots |
448
+ | `WS_PING_INTERVAL` | | `30` | WebSocket keepalive ping interval (seconds) |
449
+ | `WS_PING_TIMEOUT` | | `10` | WebSocket pong timeout (seconds) |
450
+ | `RECONNECT_DELAY_INITIAL` | | `1.0` | Initial Dirigera WebSocket reconnect backoff delay (seconds) |
451
+ | `RECONNECT_DELAY_MAX` | | `60.0` | Maximum Dirigera WebSocket reconnect backoff delay (seconds) |
452
+
453
+ Note the `MQTT_*` reconnect/TLS settings are distinct from `RECONNECT_DELAY_INITIAL`/`RECONNECT_DELAY_MAX` — the former govern the HASDK's MQTT broker connection, the latter govern this bridge's own Dirigera WebSocket connection. They're deliberately named to avoid being confused with each other.
454
+
455
+ ---
456
+
457
+ ## Resilience
458
+
459
+ The bridge is designed to recover automatically from network failures:
460
+
461
+ - **Dirigera WebSocket** — reconnects with exponential backoff (1s → 60s) when the hub connection drops. On reconnect, all devices are re-discovered and state is replayed to HA.
462
+ - **MQTT broker** — reconnects with exponential backoff when the broker is unavailable. Entity registrations are not re-sent if the entity was already registered in the
463
+ - current session (discovery cache).
464
+ - **Availability** — all entities are marked offline in HA when the Dirigera connection drops and marked online again on reconnect.
465
+ - **Shutdown** — `SIGINT` and `SIGTERM` trigger a graceful shutdown: entities are marked offline, connections are closed cleanly, and a final metrics snapshot is logged.
466
+
467
+ ---
468
+
469
+ ## Observability
470
+
471
+ Structured log output goes to stdout and is captured by Docker's json-file logging driver with rotation (10 MB × 5 files).
472
+
473
+ A metrics snapshot is logged every `METRICS_INTERVAL` seconds (default 5 minutes):
474
+
475
+ ```
476
+ INFO dirigera_bridge.orchestrator Metrics snapshot: ws_messages_received=1243 mqtt_messages_published=892 mapping_state_updates=756 ...
477
+ ```
478
+
479
+ To view live logs:
480
+ ```bash
481
+ docker compose logs -f dirigera-bridge
482
+ ```
483
+
484
+ To filter for errors only:
485
+ ```bash
486
+ docker compose logs dirigera-bridge | grep ERROR
487
+ ```
488
+
489
+ ---
490
+
491
+ ## Security notes
492
+
493
+ - The `.env` file contains secrets and must never be committed to version control. Add it to `.gitignore`.
494
+ - The bridge runs as a non-root user (`bridge`, uid 1001) inside the container.
495
+ - The Dirigera token and MQTT password are redacted from all log output.
496
+ - No ports are exposed externally — the bridge communicates only on the internal `iot_network`.
497
+ - SSL certificate verification is disabled for the Dirigera hub connection because the hub uses a self-signed certificate. This is expected and safe for local network communication.
498
+
499
+ ---
500
+
501
+ ## Dependencies
502
+
503
+ | Package | Version | Purpose |
504
+ |------------------------|-----------------|--------------------------------|
505
+ | `websockets` | ≥16.0, <17.0 | Dirigera WebSocket connection |
506
+ | `aiohttp` | ≥3.9, <4.0 | Dirigera REST API |
507
+ | `aiomqtt` | ≥2.5.1, <3.0 | MQTT transport (via HASDK) |
508
+ | `pydantic` | ≥2.13.4, <3.0 | Dirigera payload validation |
509
+ | `python-dotenv` | ≥1.2.3, <2.0 | `.env` file loading |
510
+ | `ha_mqtt_sdk` | ≥0.8.4, <2.0 | HA entity lifecycle via MQTT — published to PyPI, installed like any other dependency |
511
+
512
+ ---
513
+
514
+ ## License
515
+
516
+ This project is licensed under the MIT License, which means you are free to use, copy, modify, merge, publish, distribute, sublicense, and sell this software.
517
+
518
+ See the LICENSE file for the full license text.
519
+
520
+ Attribution
521
+
522
+ You're welcome to use and adapt this code for your own projects. If you do, I would appreciate it if you kept the original author attribution and mentioned dickkouwenhoven as the original author.
523
+
524
+ Attribution is appreciated, but is not a requirement of the MIT License.
525
+
526
+ ---
527
+
528
+ ## Author
529
+
530
+ Dick Kouwenhoven
531
+
532
+ GitHub: https://github.com/dickkouwenhoven/Dirigera-Bridge