ovos-home-plugin-dirigera 0.1.0a1__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: ovos-home-plugin-dirigera
3
+ Version: 0.1.0a1
4
+ Summary: IKEA DIRIGERA as a brand of ovos-PHAL-plugin-home: IKEA lights, outlets, blinds, air purifiers, sensors, remotes, rooms and scenes in the one home - paired with the hub's button, all in the house. Made for Emkay.
5
+ Author: emkay-voice
6
+ Maintainer: Andreas Lorensen
7
+ License: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/emkay-voice/ovos-home-plugin-dirigera
9
+ Project-URL: Issues, https://github.com/emkay-voice/ovos-home-plugin-dirigera/issues
10
+ Project-URL: Contract, https://github.com/emkay-voice/ovos-PHAL-plugin-home/blob/main/SPEC.md
11
+ Project-URL: Emkay, https://github.com/emkay-voice/emkay
12
+ Keywords: ovos,openvoiceos,plugin,smart-home,ikea,dirigera,tradfri,emkay
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Home Automation
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: ovos-PHAL-plugin-home>=0.1.0a2
21
+ Requires-Dist: dirigera>=1.2
22
+ Requires-Dist: zeroconf
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest; extra == "test"
25
+ Dynamic: license-file
26
+
27
+ # ovos-home-plugin-dirigera
28
+
29
+ IKEA's [DIRIGERA](https://www.ikea.com/) hub as one brand of the one home for OpenVoiceOS, [ovos-PHAL-plugin-home](https://github.com/emkay-voice/ovos-PHAL-plugin-home): IKEA lights, outlets, blinds, air purifiers, sensors and remotes, with the rooms and scenes from the IKEA Home smart app.
30
+
31
+ Made for [Emkay](https://emkay.ai), and works on any OVOS with the home plugin.
32
+
33
+ **All in the house.** DIRIGERA needs no internet connection, and nothing here leaves the LAN: the hub is the one host the brand talks to.
34
+
35
+ ## Pairing
36
+
37
+ In the control panel's page **Home**, under Brands: **Find and pair**. The house finds the hub on the network (mDNS), says *press the button on the hub now*, and keeps the token it gets – readable only by the user OVOS runs as, never in `mycroft.conf`. Without the panel:
38
+
39
+ ```json
40
+ "PHAL": {
41
+ "ovos-PHAL-plugin-home": {
42
+ "brands": {
43
+ "dirigera": {"host": "192.168.1.50"}
44
+ }
45
+ }
46
+ }
47
+ ```
48
+
49
+ and send `ovos.home.brand.pair` `{"brand": "dirigera", "hub": "192.168.1.50"}`, then press the button.
50
+
51
+ ## What comes along
52
+
53
+ | DIRIGERA | The home |
54
+ |---|---|
55
+ | lights | on/off, brightness, warmth and colour as the lamp can |
56
+ | outlets | on/off, with power and energy where the outlet measures them (INSPELNING) |
57
+ | blinds | by position (FYRTUR, KADRILJ, PRAKTLYSING …) |
58
+ | air purifiers | on/off and auto/low/medium/high, with PM2.5 (STARKVIND) |
59
+ | environment sensors | temperature, humidity, PM2.5, CO₂, VOC (VINDSTYRKA, ALPSTUGA) |
60
+ | door/window, motion, water sensors | readings and events: a door opened, someone moved, **water** (PARASOLL, VALLHORN, BADRING) |
61
+ | remotes | buttons: pressed, double, long (STYRBAR, RODRET, SOMRIG) |
62
+ | rooms and scenes | from the IKEA Home smart app |
63
+
64
+ ## Good to know
65
+
66
+ - DIRIGERA's local API isn't documented by IKEA. It is the one the community has worked out, spoken here through the [`dirigera`](https://github.com/Leggin/dirigera) library. A firmware update could change it.
67
+ - **Tested** against JSON as dumped from real hubs, not yet against a hub of our own. If you have a DIRIGERA, reports are very welcome in the issues – especially about blinds (which way is up) and remotes.
68
+
69
+ ## License
70
+
71
+ Apache-2.0
@@ -0,0 +1,45 @@
1
+ # ovos-home-plugin-dirigera
2
+
3
+ IKEA's [DIRIGERA](https://www.ikea.com/) hub as one brand of the one home for OpenVoiceOS, [ovos-PHAL-plugin-home](https://github.com/emkay-voice/ovos-PHAL-plugin-home): IKEA lights, outlets, blinds, air purifiers, sensors and remotes, with the rooms and scenes from the IKEA Home smart app.
4
+
5
+ Made for [Emkay](https://emkay.ai), and works on any OVOS with the home plugin.
6
+
7
+ **All in the house.** DIRIGERA needs no internet connection, and nothing here leaves the LAN: the hub is the one host the brand talks to.
8
+
9
+ ## Pairing
10
+
11
+ In the control panel's page **Home**, under Brands: **Find and pair**. The house finds the hub on the network (mDNS), says *press the button on the hub now*, and keeps the token it gets – readable only by the user OVOS runs as, never in `mycroft.conf`. Without the panel:
12
+
13
+ ```json
14
+ "PHAL": {
15
+ "ovos-PHAL-plugin-home": {
16
+ "brands": {
17
+ "dirigera": {"host": "192.168.1.50"}
18
+ }
19
+ }
20
+ }
21
+ ```
22
+
23
+ and send `ovos.home.brand.pair` `{"brand": "dirigera", "hub": "192.168.1.50"}`, then press the button.
24
+
25
+ ## What comes along
26
+
27
+ | DIRIGERA | The home |
28
+ |---|---|
29
+ | lights | on/off, brightness, warmth and colour as the lamp can |
30
+ | outlets | on/off, with power and energy where the outlet measures them (INSPELNING) |
31
+ | blinds | by position (FYRTUR, KADRILJ, PRAKTLYSING …) |
32
+ | air purifiers | on/off and auto/low/medium/high, with PM2.5 (STARKVIND) |
33
+ | environment sensors | temperature, humidity, PM2.5, CO₂, VOC (VINDSTYRKA, ALPSTUGA) |
34
+ | door/window, motion, water sensors | readings and events: a door opened, someone moved, **water** (PARASOLL, VALLHORN, BADRING) |
35
+ | remotes | buttons: pressed, double, long (STYRBAR, RODRET, SOMRIG) |
36
+ | rooms and scenes | from the IKEA Home smart app |
37
+
38
+ ## Good to know
39
+
40
+ - DIRIGERA's local API isn't documented by IKEA. It is the one the community has worked out, spoken here through the [`dirigera`](https://github.com/Leggin/dirigera) library. A firmware update could change it.
41
+ - **Tested** against JSON as dumped from real hubs, not yet against a hub of our own. If you have a DIRIGERA, reports are very welcome in the issues – especially about blinds (which way is up) and remotes.
42
+
43
+ ## License
44
+
45
+ Apache-2.0
@@ -0,0 +1,383 @@
1
+ """ovos-home-plugin-dirigera: IKEA's DIRIGERA hub as a brand of the home.
2
+
3
+ IKEA lights, outlets, blinds, air purifiers, sensors and remotes, with the
4
+ rooms and scenes from the IKEA Home smart app, in the one home of
5
+ ovos-PHAL-plugin-home – all in the house: DIRIGERA needs no internet, and
6
+ nothing here leaves the LAN.
7
+
8
+ DIRIGERA's local API isn't documented by IKEA; it is the one the community
9
+ has worked out and the `dirigera` library speaks (REST on port 8443 and a
10
+ websocket for events). A firmware update could change it.
11
+
12
+ Pairing is the hub's own: the house finds the hub on the network, says
13
+ "press the button on the hub", and keeps the token it gets.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import json
19
+ import time
20
+ from typing import Any, Callable, Optional
21
+
22
+ from ovos_phal_plugin_home import BrandError, BrandHome, Device, FoundHub, HomeBrand, Result, Room, Scene
23
+ from ovos_utils.log import LOG
24
+
25
+ #: how long pairing waits for the button
26
+ PAIR_SECONDS = 90
27
+
28
+
29
+ def _pct(v) -> Optional[int]:
30
+ try:
31
+ return int(round(float(v)))
32
+ except (TypeError, ValueError):
33
+ return None
34
+
35
+
36
+ def to_device(raw: dict) -> Optional[Device]:
37
+ """A DIRIGERA device as the contract wants it, or None for what isn't one."""
38
+ t = raw.get("deviceType") or raw.get("type")
39
+ a = raw.get("attributes", {}) or {}
40
+ can = set((raw.get("capabilities") or {}).get("canReceive") or [])
41
+ name = a.get("customName") or a.get("model") or raw.get("id")
42
+ room = (raw.get("room") or {}).get("id")
43
+ caps: dict[str, dict] = {}
44
+ state: dict[str, Any] = {}
45
+ kind = None
46
+ if t == "light":
47
+ kind = "light"
48
+ caps["on_off"] = {}
49
+ state["on"] = bool(a.get("isOn"))
50
+ if "lightLevel" in can or "lightLevel" in a:
51
+ caps["brightness"] = {}
52
+ if a.get("lightLevel") is not None:
53
+ state["brightness"] = _pct(a["lightLevel"])
54
+ if "colorTemperature" in can:
55
+ lo, hi = a.get("colorTemperatureMax"), a.get("colorTemperatureMin") # IKEA has them reversed
56
+ if lo and hi:
57
+ lo, hi = sorted((int(lo), int(hi)))
58
+ caps["color_temp"] = {"min": lo or 2200, "max": hi or 4000}
59
+ if a.get("colorTemperature"):
60
+ state["color_temp"] = int(a["colorTemperature"])
61
+ if "colorHue" in can:
62
+ caps["color"] = {}
63
+ if a.get("colorHue") is not None:
64
+ state["color"] = {"h": _pct(a["colorHue"]), "s": _pct(float(a.get("colorSaturation", 0)) * 100)}
65
+ elif t == "outlet":
66
+ kind = "outlet"
67
+ caps["on_off"] = {}
68
+ state["on"] = bool(a.get("isOn"))
69
+ if a.get("currentActivePower") is not None:
70
+ caps["power"] = {}
71
+ state["power"] = round(float(a["currentActivePower"]), 1)
72
+ if a.get("totalEnergyConsumed") is not None:
73
+ caps["energy"] = {}
74
+ state["energy"] = round(float(a["totalEnergyConsumed"]), 2)
75
+ elif t == "blinds":
76
+ kind = "blind"
77
+ caps["position"] = {}
78
+ level = a.get("blindsCurrentLevel")
79
+ if level is not None:
80
+ state["position"] = 100 - _pct(level) # IKEA: 0 = up (open), 100 = down
81
+ elif t == "airPurifier":
82
+ kind = "air_purifier"
83
+ caps["on_off"] = {}
84
+ caps["mode"] = {"modes": ["auto", "low", "medium", "high"]}
85
+ mode = a.get("fanMode")
86
+ state["on"] = mode not in (None, "off")
87
+ if mode and mode != "off":
88
+ state["mode"] = mode
89
+ if a.get("currentPM25") is not None:
90
+ caps["pm25"] = {}
91
+ state["pm25"] = a["currentPM25"]
92
+ elif t in ("environmentSensor", "openCloseSensor", "motionSensor", "waterSensor",
93
+ "lightSensor", "occupancySensor"):
94
+ kind = "sensor"
95
+ for src, cap, field in (("currentTemperature", "temperature", "temperature"),
96
+ ("currentRH", "humidity", "humidity"),
97
+ ("currentPM25", "pm25", "pm25"),
98
+ ("currentCO2", "co2", "co2"),
99
+ ("vocIndex", "voc", "voc"),
100
+ ("illuminance", "illuminance", "illuminance")):
101
+ if a.get(src) is not None:
102
+ caps[cap] = {}
103
+ state[field] = a[src]
104
+ if "isOpen" in a:
105
+ caps["contact"] = {}
106
+ state["open"] = bool(a["isOpen"])
107
+ if "isDetected" in a:
108
+ caps["motion"] = {}
109
+ state["motion"] = bool(a["isDetected"])
110
+ if "waterLeakDetected" in a:
111
+ caps["leak"] = {}
112
+ state["leak"] = bool(a["waterLeakDetected"])
113
+ elif t == "controller":
114
+ kind = "button"
115
+ caps["button"] = {}
116
+ if kind is None:
117
+ return None
118
+ if a.get("batteryPercentage") is not None:
119
+ caps["battery"] = {}
120
+ state["battery"] = a["batteryPercentage"]
121
+ return Device(raw["id"], name, kind, caps, state, room, bool(raw.get("isReachable", True)))
122
+
123
+
124
+ #: attribute DIRIGERA reports -> (state field, how to read it)
125
+ CHANGES: dict[str, tuple[str, Callable]] = {
126
+ "isOn": ("on", bool), "lightLevel": ("brightness", _pct), "colorTemperature": ("color_temp", int),
127
+ "currentActivePower": ("power", lambda v: round(float(v), 1)),
128
+ "totalEnergyConsumed": ("energy", lambda v: round(float(v), 2)),
129
+ "blindsCurrentLevel": ("position", lambda v: 100 - _pct(v)),
130
+ "currentTemperature": ("temperature", float), "currentRH": ("humidity", float),
131
+ "currentPM25": ("pm25", float), "currentCO2": ("co2", float), "vocIndex": ("voc", float),
132
+ "illuminance": ("illuminance", float), "isOpen": ("open", bool), "isDetected": ("motion", bool),
133
+ "waterLeakDetected": ("leak", bool), "batteryPercentage": ("battery", float),
134
+ }
135
+ #: state field turning true/false -> events
136
+ EVENTS = {"open": ("contact.opened", "contact.closed"), "motion": ("motion.detected", "motion.cleared"),
137
+ "leak": ("leak.detected", "leak.cleared")}
138
+ PRESS = {"singlePress": "press", "doublePress": "double", "longPress": "long", "release": "release"}
139
+
140
+
141
+ def patches(dev: Device, values: dict, transition_ms: Optional[int]) -> list[dict]:
142
+ """DIRIGERA's PATCH bodies for the contract's values, one attribute each."""
143
+ out = []
144
+ extra = {"transitionTime": int(transition_ms)} if transition_ms else {}
145
+ if dev.kind == "air_purifier":
146
+ if values.get("on") is False:
147
+ return [{"attributes": {"fanMode": "off"}}]
148
+ mode = values.get("mode") or (dev.state.get("mode") or "auto" if values.get("on") else None)
149
+ return [{"attributes": {"fanMode": mode}}] if mode else []
150
+ if "brightness" in values:
151
+ out.append({"attributes": {"lightLevel": max(1, int(values["brightness"]))}, **extra})
152
+ if "color_temp" in values:
153
+ out.append({"attributes": {"colorTemperature": int(values["color_temp"])}, **extra})
154
+ if "color" in values:
155
+ out.append({"attributes": {"colorHue": values["color"]["h"],
156
+ "colorSaturation": round(values["color"]["s"] / 100, 2)}, **extra})
157
+ if "position" in values:
158
+ out.append({"attributes": {"blindsTargetLevel": 100 - int(values["position"])}})
159
+ if "on" in values:
160
+ on = {"attributes": {"isOn": bool(values["on"])}}
161
+ # on first, so a dimmed lamp comes on at its new level; off last
162
+ out = [on, *out] if values["on"] else [*out, on]
163
+ return out
164
+
165
+
166
+ class DirigeraBrand(HomeBrand):
167
+ name = "dirigera"
168
+ display_name = "IKEA DIRIGERA"
169
+ pairs = True
170
+
171
+ def __init__(self, config: Optional[dict] = None, storage=None, hub_factory=None):
172
+ super().__init__(config, storage)
173
+ self._factory = hub_factory or self._real_hub
174
+ self.hub = None
175
+ self.devices: dict[str, Device] = {}
176
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
177
+
178
+ # ---- pairing ------------------------------------------------------------
179
+
180
+ @property
181
+ def host(self) -> str:
182
+ return self.config.get("host") or (self.storage.get("host") if self.storage else "") or ""
183
+
184
+ @property
185
+ def token(self) -> str:
186
+ return self.config.get("token") or (self.storage.get("token") if self.storage else "") or ""
187
+
188
+ @property
189
+ def paired(self) -> bool:
190
+ return bool(self.host and self.token)
191
+
192
+ @property
193
+ def hosts(self) -> list[str]:
194
+ return [self.host] if self.host else []
195
+
196
+ @staticmethod
197
+ def _real_hub(token, host):
198
+ from dirigera import Hub
199
+ return Hub(token=token, ip_address=host)
200
+
201
+ async def discover(self) -> list[FoundHub]:
202
+ if self.config.get("host"):
203
+ return [FoundHub(self.config["host"], "DIRIGERA", self.config["host"], self.paired)]
204
+ return await asyncio.get_running_loop().run_in_executor(None, self._browse)
205
+
206
+ def _browse(self) -> list[FoundHub]:
207
+ """DIRIGERA announces itself on mDNS as _ihsp._tcp."""
208
+ try:
209
+ from zeroconf import ServiceBrowser, Zeroconf
210
+ except ImportError:
211
+ return []
212
+ found: dict[str, FoundHub] = {}
213
+
214
+ class Listener:
215
+ def add_service(self, zc, type_, name):
216
+ info = zc.get_service_info(type_, name, 3000)
217
+ if info and info.parsed_addresses():
218
+ host = info.parsed_addresses()[0]
219
+ found[host] = FoundHub(host, name.split(".")[0], host)
220
+
221
+ def update_service(self, *a):
222
+ pass
223
+
224
+ def remove_service(self, *a):
225
+ pass
226
+
227
+ zc = Zeroconf()
228
+ try:
229
+ ServiceBrowser(zc, "_ihsp._tcp.local.", Listener())
230
+ time.sleep(4)
231
+ finally:
232
+ zc.close()
233
+ for hub in found.values():
234
+ hub.paired = hub.host == self.host and bool(self.token)
235
+ return list(found.values())
236
+
237
+ async def pair(self, hub_id: str, progress: Callable[[str], None]) -> None:
238
+ from dirigera.hub.auth import ALPHABET, CODE_LENGTH, get_token, random_code, send_challenge
239
+ loop = asyncio.get_running_loop()
240
+ verifier = random_code(ALPHABET, CODE_LENGTH)
241
+ code = await loop.run_in_executor(None, send_challenge, hub_id, verifier)
242
+ progress("press_button")
243
+ end = time.monotonic() + PAIR_SECONDS
244
+ while time.monotonic() < end:
245
+ await asyncio.sleep(2)
246
+ try:
247
+ token = await loop.run_in_executor(None, get_token, hub_id, code, verifier)
248
+ except Exception: # noqa: BLE001 - not pressed yet
249
+ continue
250
+ self.storage.set("host", hub_id)
251
+ self.storage.set("token", token)
252
+ return
253
+ raise BrandError("timeout", "the button on the hub wasn't pressed")
254
+
255
+ async def unpair(self, hub_id: str) -> None:
256
+ await self.stop()
257
+ if self.storage:
258
+ self.storage.delete("token")
259
+ self.storage.delete("host")
260
+ self.hub = None
261
+
262
+ # ---- the hub ------------------------------------------------------------
263
+
264
+ async def _in_thread(self, fn, *args):
265
+ return await asyncio.get_running_loop().run_in_executor(None, fn, *args)
266
+
267
+ async def start(self) -> None:
268
+ self._loop = asyncio.get_running_loop()
269
+ if not self.paired:
270
+ return
271
+ self.hub = self._factory(self.token, self.host)
272
+ listen = getattr(self.hub, "create_event_listener", None)
273
+ if listen:
274
+ import threading
275
+ threading.Thread(target=lambda: listen(on_message=self._on_message, reconnect=True),
276
+ name="dirigera-events", daemon=True).start()
277
+
278
+ async def stop(self) -> None:
279
+ stop = getattr(self.hub, "stop_event_listener", None)
280
+ if stop:
281
+ try:
282
+ stop()
283
+ except Exception: # noqa: BLE001
284
+ pass
285
+
286
+ async def get_home(self) -> BrandHome:
287
+ if self.hub is None:
288
+ raise BrandError("unavailable", "not paired with a DIRIGERA hub")
289
+ raw_devices = await self._in_thread(self.hub.get, "/devices")
290
+ raw_scenes = await self._in_thread(self.hub.get, "/scenes")
291
+ rooms: dict[str, Room] = {}
292
+ devices = []
293
+ for raw in raw_devices or []:
294
+ if raw.get("isHidden"):
295
+ continue
296
+ dev = to_device(raw)
297
+ if dev is None:
298
+ continue
299
+ devices.append(dev)
300
+ r = raw.get("room") or {}
301
+ if r.get("id"):
302
+ rooms.setdefault(r["id"], Room(r["id"], r.get("name") or r["id"]))
303
+ scenes = [Scene(s["id"], (s.get("info") or {}).get("name") or s["id"])
304
+ for s in raw_scenes or [] if s.get("type", "userScene") == "userScene"]
305
+ self.devices = {d.id: d for d in devices}
306
+ return BrandHome(list(rooms.values()), devices, scenes)
307
+
308
+ async def set(self, changes, transition_ms=None):
309
+ results = []
310
+ for did, values in changes.items():
311
+ dev = self.devices.get(did)
312
+ if dev is None:
313
+ results.append(Result(did, False, "unknown_device"))
314
+ continue
315
+ try:
316
+ for body in patches(dev, values, transition_ms):
317
+ await self._in_thread(self.hub.patch, f"/devices/{did}", [body])
318
+ results.append(Result(did))
319
+ except Exception as e: # noqa: BLE001
320
+ LOG.error(f"dirigera: {did}: {e}")
321
+ results.append(Result(did, False, "brand_error"))
322
+ return results
323
+
324
+ async def activate_scene(self, scene_id: str) -> Result:
325
+ try:
326
+ await self._in_thread(self.hub.post, f"/scenes/{scene_id}/trigger")
327
+ return Result(scene_id)
328
+ except Exception as e: # noqa: BLE001
329
+ LOG.error(f"dirigera: scene {scene_id}: {e}")
330
+ return Result(scene_id, False, "brand_error")
331
+
332
+ # ---- events (the hub's websocket, in its own thread) -----------------------
333
+
334
+ def _on_message(self, ws, message) -> None:
335
+ try:
336
+ msg = json.loads(message) if isinstance(message, str) else message
337
+ except ValueError:
338
+ return
339
+ self.handle(msg)
340
+
341
+ def handle(self, msg: dict) -> None:
342
+ kind, data = msg.get("type"), msg.get("data") or {}
343
+ did = data.get("id")
344
+ if kind in ("deviceAdded", "deviceRemoved", "sceneCreated", "sceneDeleted", "sceneUpdated"):
345
+ self.home_changed()
346
+ return
347
+ if kind == "remotePressEvent" and did:
348
+ action = PRESS.get(data.get("clickPattern", ""), "press")
349
+ self.event("button.pressed", did, {"button": str(data.get("buttonIndex", "1")), "action": action})
350
+ return
351
+ if kind != "deviceStateChanged" or did not in self.devices:
352
+ return
353
+ dev = self.devices[did]
354
+ attrs = data.get("attributes") or {}
355
+ changed: dict[str, Any] = {}
356
+ for src, (field, read) in CHANGES.items():
357
+ if src in attrs and attrs[src] is not None:
358
+ try:
359
+ changed[field] = read(attrs[src])
360
+ except (TypeError, ValueError):
361
+ pass
362
+ if "fanMode" in attrs:
363
+ changed["on"] = attrs["fanMode"] != "off"
364
+ if attrs["fanMode"] != "off":
365
+ changed["mode"] = attrs["fanMode"]
366
+ if "customName" in attrs or ("room" in data and (data["room"] or {}).get("id") != dev.room):
367
+ self.home_changed()
368
+ reachable = data.get("isReachable")
369
+ before = dict(dev.state)
370
+ dev.state.update(changed)
371
+ if changed or reachable is not None:
372
+ self.update(did, changed or None, reachable)
373
+ if reachable is False and dev.available:
374
+ dev.available = False
375
+ self.event("device.unavailable", did)
376
+ elif reachable is True and not dev.available:
377
+ dev.available = True
378
+ self.event("device.available", did)
379
+ for field, (on_event, off_event) in EVENTS.items():
380
+ if field in changed and before.get(field) != changed[field]:
381
+ self.event(on_event if changed[field] else off_event, did)
382
+ if "battery" in changed and changed["battery"] <= 10 < (before.get("battery") or 100):
383
+ self.event("battery.low", did, {"battery": changed["battery"]})
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: ovos-home-plugin-dirigera
3
+ Version: 0.1.0a1
4
+ Summary: IKEA DIRIGERA as a brand of ovos-PHAL-plugin-home: IKEA lights, outlets, blinds, air purifiers, sensors, remotes, rooms and scenes in the one home - paired with the hub's button, all in the house. Made for Emkay.
5
+ Author: emkay-voice
6
+ Maintainer: Andreas Lorensen
7
+ License: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/emkay-voice/ovos-home-plugin-dirigera
9
+ Project-URL: Issues, https://github.com/emkay-voice/ovos-home-plugin-dirigera/issues
10
+ Project-URL: Contract, https://github.com/emkay-voice/ovos-PHAL-plugin-home/blob/main/SPEC.md
11
+ Project-URL: Emkay, https://github.com/emkay-voice/emkay
12
+ Keywords: ovos,openvoiceos,plugin,smart-home,ikea,dirigera,tradfri,emkay
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Home Automation
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: ovos-PHAL-plugin-home>=0.1.0a2
21
+ Requires-Dist: dirigera>=1.2
22
+ Requires-Dist: zeroconf
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest; extra == "test"
25
+ Dynamic: license-file
26
+
27
+ # ovos-home-plugin-dirigera
28
+
29
+ IKEA's [DIRIGERA](https://www.ikea.com/) hub as one brand of the one home for OpenVoiceOS, [ovos-PHAL-plugin-home](https://github.com/emkay-voice/ovos-PHAL-plugin-home): IKEA lights, outlets, blinds, air purifiers, sensors and remotes, with the rooms and scenes from the IKEA Home smart app.
30
+
31
+ Made for [Emkay](https://emkay.ai), and works on any OVOS with the home plugin.
32
+
33
+ **All in the house.** DIRIGERA needs no internet connection, and nothing here leaves the LAN: the hub is the one host the brand talks to.
34
+
35
+ ## Pairing
36
+
37
+ In the control panel's page **Home**, under Brands: **Find and pair**. The house finds the hub on the network (mDNS), says *press the button on the hub now*, and keeps the token it gets – readable only by the user OVOS runs as, never in `mycroft.conf`. Without the panel:
38
+
39
+ ```json
40
+ "PHAL": {
41
+ "ovos-PHAL-plugin-home": {
42
+ "brands": {
43
+ "dirigera": {"host": "192.168.1.50"}
44
+ }
45
+ }
46
+ }
47
+ ```
48
+
49
+ and send `ovos.home.brand.pair` `{"brand": "dirigera", "hub": "192.168.1.50"}`, then press the button.
50
+
51
+ ## What comes along
52
+
53
+ | DIRIGERA | The home |
54
+ |---|---|
55
+ | lights | on/off, brightness, warmth and colour as the lamp can |
56
+ | outlets | on/off, with power and energy where the outlet measures them (INSPELNING) |
57
+ | blinds | by position (FYRTUR, KADRILJ, PRAKTLYSING …) |
58
+ | air purifiers | on/off and auto/low/medium/high, with PM2.5 (STARKVIND) |
59
+ | environment sensors | temperature, humidity, PM2.5, CO₂, VOC (VINDSTYRKA, ALPSTUGA) |
60
+ | door/window, motion, water sensors | readings and events: a door opened, someone moved, **water** (PARASOLL, VALLHORN, BADRING) |
61
+ | remotes | buttons: pressed, double, long (STYRBAR, RODRET, SOMRIG) |
62
+ | rooms and scenes | from the IKEA Home smart app |
63
+
64
+ ## Good to know
65
+
66
+ - DIRIGERA's local API isn't documented by IKEA. It is the one the community has worked out, spoken here through the [`dirigera`](https://github.com/Leggin/dirigera) library. A firmware update could change it.
67
+ - **Tested** against JSON as dumped from real hubs, not yet against a hub of our own. If you have a DIRIGERA, reports are very welcome in the issues – especially about blinds (which way is up) and remotes.
68
+
69
+ ## License
70
+
71
+ Apache-2.0
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ ovos_home_plugin_dirigera/__init__.py
5
+ ovos_home_plugin_dirigera.egg-info/PKG-INFO
6
+ ovos_home_plugin_dirigera.egg-info/SOURCES.txt
7
+ ovos_home_plugin_dirigera.egg-info/dependency_links.txt
8
+ ovos_home_plugin_dirigera.egg-info/entry_points.txt
9
+ ovos_home_plugin_dirigera.egg-info/requires.txt
10
+ ovos_home_plugin_dirigera.egg-info/top_level.txt
11
+ tests/test_brand.py
@@ -0,0 +1,2 @@
1
+ [opm.home]
2
+ dirigera = ovos_home_plugin_dirigera:DirigeraBrand
@@ -0,0 +1,6 @@
1
+ ovos-PHAL-plugin-home>=0.1.0a2
2
+ dirigera>=1.2
3
+ zeroconf
4
+
5
+ [test]
6
+ pytest
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ovos-home-plugin-dirigera"
7
+ version = "0.1.0a1"
8
+ description = "IKEA DIRIGERA as a brand of ovos-PHAL-plugin-home: IKEA lights, outlets, blinds, air purifiers, sensors, remotes, rooms and scenes in the one home - paired with the hub's button, all in the house. Made for Emkay."
9
+ readme = "README.md"
10
+ license = {text = "Apache-2.0"}
11
+ authors = [{name = "emkay-voice"}]
12
+ maintainers = [{name = "Andreas Lorensen"}]
13
+ requires-python = ">=3.10"
14
+ keywords = ["ovos", "openvoiceos", "plugin", "smart-home", "ikea", "dirigera", "tradfri", "emkay"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Home Automation",
20
+ ]
21
+ dependencies = ["ovos-PHAL-plugin-home>=0.1.0a2", "dirigera>=1.2", "zeroconf"]
22
+
23
+ [project.optional-dependencies]
24
+ test = ["pytest"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/emkay-voice/ovos-home-plugin-dirigera"
28
+ Issues = "https://github.com/emkay-voice/ovos-home-plugin-dirigera/issues"
29
+ Contract = "https://github.com/emkay-voice/ovos-PHAL-plugin-home/blob/main/SPEC.md"
30
+ Emkay = "https://github.com/emkay-voice/emkay"
31
+
32
+ [project.entry-points."opm.home"]
33
+ dirigera = "ovos_home_plugin_dirigera:DirigeraBrand"
34
+
35
+ [tool.setuptools]
36
+ packages = ["ovos_home_plugin_dirigera"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,196 @@
1
+ """DIRIGERA as a brand: the hub's JSON, as dumped from real hubs, through the real manager."""
2
+ import json
3
+ import threading
4
+ import time
5
+
6
+ import pytest
7
+ from ovos_bus_client.message import Message
8
+
9
+ from ovos_home_plugin_dirigera import DirigeraBrand, patches, to_device
10
+ from ovos_phal_plugin_home import BrandStorage, HomePlugin
11
+
12
+ ROOM = {"id": "r-stue", "name": "Stue", "color": "ikea_green_no_65", "icon": "rooms_sofa"}
13
+ DEVICES = [
14
+ {"id": "l1", "type": "light", "deviceType": "light", "isReachable": True, "isHidden": False, "room": ROOM,
15
+ "attributes": {"customName": "Loftlampe", "isOn": True, "lightLevel": 80, "colorTemperature": 2700,
16
+ "colorTemperatureMin": 4000, "colorTemperatureMax": 2202, "colorMode": "temperature"},
17
+ "capabilities": {"canSend": [], "canReceive": ["customName", "isOn", "lightLevel", "colorTemperature"]}},
18
+ {"id": "l2", "type": "light", "deviceType": "light", "isReachable": True, "room": ROOM,
19
+ "attributes": {"customName": "Lyskæde", "isOn": False, "lightLevel": 50, "colorHue": 120, "colorSaturation": 0.5},
20
+ "capabilities": {"canReceive": ["isOn", "lightLevel", "colorHue", "colorSaturation"]}},
21
+ {"id": "o1", "type": "outlet", "deviceType": "outlet", "isReachable": True, "room": {"id": "r-kok", "name": "Køkken"},
22
+ "attributes": {"customName": "Kaffe", "isOn": False, "currentActivePower": 0.4, "totalEnergyConsumed": 12.25},
23
+ "capabilities": {"canReceive": ["isOn"]}},
24
+ {"id": "b1", "type": "blinds", "deviceType": "blinds", "isReachable": True, "room": ROOM,
25
+ "attributes": {"customName": "Rullegardin", "blindsCurrentLevel": 0, "batteryPercentage": 77},
26
+ "capabilities": {"canReceive": ["blindsTargetLevel"]}},
27
+ {"id": "p1", "type": "airPurifier", "deviceType": "airPurifier", "isReachable": True, "room": ROOM,
28
+ "attributes": {"customName": "STARKVIND", "fanMode": "auto", "currentPM25": 4},
29
+ "capabilities": {"canReceive": ["fanMode"]}},
30
+ {"id": "s1", "type": "sensor", "deviceType": "environmentSensor", "isReachable": True, "room": ROOM,
31
+ "attributes": {"customName": "VINDSTYRKA", "currentTemperature": 21.5, "currentRH": 41, "currentPM25": 3, "vocIndex": 95}},
32
+ {"id": "s2", "type": "sensor", "deviceType": "openCloseSensor", "isReachable": True, "room": {"id": "r-entre", "name": "Entré"},
33
+ "attributes": {"customName": "Hoveddør", "isOpen": False, "batteryPercentage": 90}},
34
+ {"id": "s3", "type": "sensor", "deviceType": "waterSensor", "isReachable": True, "room": {"id": "r-bad", "name": "Bad"},
35
+ "attributes": {"customName": "BADRING", "waterLeakDetected": False, "batteryPercentage": 100}},
36
+ {"id": "c1", "type": "controller", "deviceType": "controller", "isReachable": True, "room": ROOM,
37
+ "attributes": {"customName": "STYRBAR", "batteryPercentage": 60}},
38
+ {"id": "g1", "type": "gateway", "deviceType": "gateway", "attributes": {"customName": "DIRIGERA"}},
39
+ {"id": "h1", "type": "light", "deviceType": "light", "isHidden": True, "attributes": {"customName": "Skjult", "isOn": False}},
40
+ ]
41
+ SCENES = [{"id": "sc1", "type": "userScene", "info": {"name": "Godnat", "icon": "scenes_night"}},
42
+ {"id": "sc2", "type": "wakeUpScene", "info": {"name": "Wake"}}]
43
+
44
+
45
+ class FakeHub:
46
+ def __init__(self, token, host):
47
+ assert (token, host) == ("tok", "192.168.1.50")
48
+ self.patched, self.posted = [], []
49
+
50
+ def get(self, route):
51
+ return {"/devices": DEVICES, "/scenes": SCENES}[route]
52
+
53
+ def patch(self, route, data):
54
+ self.patched.append((route, data))
55
+ return ""
56
+
57
+ def post(self, route, data=None):
58
+ self.posted.append(route)
59
+ return {}
60
+
61
+
62
+ class Bus:
63
+ def __init__(self):
64
+ self.handlers, self.emitted, self.lock = {}, [], threading.Lock()
65
+
66
+ def on(self, t, h):
67
+ self.handlers.setdefault(t, []).append(h)
68
+
69
+ def once(self, t, h):
70
+ self.on(t, h)
71
+
72
+ def remove(self, t, h):
73
+ pass
74
+
75
+ def emit(self, m):
76
+ json.dumps(m.data)
77
+ with self.lock:
78
+ self.emitted.append(m)
79
+ for h in list(self.handlers.get(m.msg_type, [])):
80
+ h(m)
81
+
82
+ def last(self, t):
83
+ with self.lock:
84
+ return next((m for m in reversed(self.emitted) if m.msg_type == t), None)
85
+
86
+
87
+ def ask(bus, t, data=None):
88
+ bus.emit(Message(t, data or {}))
89
+ return bus.last(t + ".response").data
90
+
91
+
92
+ @pytest.fixture
93
+ def home(tmp_path):
94
+ bus = Bus()
95
+ storage = BrandStorage(tmp_path, "dirigera")
96
+ storage.set("host", "192.168.1.50")
97
+ storage.set("token", "tok")
98
+ brand = DirigeraBrand({}, storage, hub_factory=FakeHub)
99
+ p = HomePlugin(bus=bus, config={"data_dir": str(tmp_path)}, brands={"dirigera": brand})
100
+ end = time.time() + 3
101
+ while p.status.get("dirigera") != "ok" and time.time() < end:
102
+ time.sleep(0.02)
103
+ yield bus, brand
104
+ p.shutdown()
105
+
106
+
107
+ def test_devices_as_the_contract_wants_them():
108
+ lamp = to_device(DEVICES[0])
109
+ assert lamp.kind == "light" and lamp.capabilities["color_temp"] == {"min": 2202, "max": 4000}
110
+ assert lamp.state == {"on": True, "brightness": 80, "color_temp": 2700}
111
+ assert to_device(DEVICES[1]).state["color"] == {"h": 120, "s": 50}
112
+ assert to_device(DEVICES[3]).state == {"position": 100, "battery": 77}, "IKEA level 0 is up: open"
113
+ purifier = to_device(DEVICES[4])
114
+ assert purifier.state == {"on": True, "mode": "auto", "pm25": 4}
115
+ env = to_device(DEVICES[5])
116
+ assert set(env.capabilities) == {"temperature", "humidity", "pm25", "voc"}
117
+ assert to_device(DEVICES[9]) is None, "the hub itself is not a device"
118
+
119
+
120
+ def test_patches():
121
+ lamp, blind, purifier = to_device(DEVICES[0]), to_device(DEVICES[3]), to_device(DEVICES[4])
122
+ assert patches(lamp, {"on": True, "brightness": 30}, 400) == [
123
+ {"attributes": {"isOn": True}}, {"attributes": {"lightLevel": 30}, "transitionTime": 400}]
124
+ assert patches(lamp, {"on": False}, None) == [{"attributes": {"isOn": False}}]
125
+ assert patches(blind, {"position": 0}, None) == [{"attributes": {"blindsTargetLevel": 100}}]
126
+ assert patches(purifier, {"on": False}, None) == [{"attributes": {"fanMode": "off"}}]
127
+ assert patches(purifier, {"mode": "high"}, None) == [{"attributes": {"fanMode": "high"}}]
128
+
129
+
130
+ def test_the_home_from_the_hub(home):
131
+ bus, brand = home
132
+ got = ask(bus, "ovos.home.get")
133
+ assert {d["name"] for d in got["devices"]} == {"Loftlampe", "Lyskæde", "Kaffe", "Rullegardin", "STARKVIND",
134
+ "VINDSTYRKA", "Hoveddør", "BADRING", "STYRBAR"}
135
+ assert [s["name"] for s in got["scenes"]] == ["Godnat"]
136
+ assert {r["name"] for r in got["rooms"]} == {"Stue", "Køkken", "Entré", "Bad"}
137
+ assert got["brands"][0]["hosts"] == ["192.168.1.50"]
138
+
139
+
140
+ def test_set_and_scene(home):
141
+ bus, brand = home
142
+ r = ask(bus, "ovos.home.set", {"target": {"rooms": ["home:stue"], "kind": "light"}, "set": {"on": False}})
143
+ assert r["ok"]
144
+ assert sorted(x[0] for x in brand.hub.patched) == ["/devices/l1", "/devices/l2"]
145
+ assert ask(bus, "ovos.home.scene.activate", {"id": "dirigera:sc1"})["ok"]
146
+ assert brand.hub.posted == ["/scenes/sc1/trigger"]
147
+
148
+
149
+ def test_events_from_the_websocket(home):
150
+ bus, brand = home
151
+ brand.handle({"type": "deviceStateChanged", "data": {"id": "s3", "attributes": {"waterLeakDetected": True}}})
152
+ ev = bus.last("ovos.home.event").data
153
+ assert (ev["type"], ev["announce"], ev["room"]) == ("leak.detected", True, "home:bad")
154
+ brand.handle({"type": "deviceStateChanged", "data": {"id": "l1", "attributes": {"lightLevel": 20}}})
155
+ assert ask(bus, "ovos.home.device.get", {"id": "dirigera:l1"})["device"]["state"]["brightness"] == 20
156
+ brand.handle({"type": "remotePressEvent", "data": {"id": "c1", "clickPattern": "doublePress"}})
157
+ assert bus.last("ovos.home.event").data["data"]["action"] == "double"
158
+ brand.handle({"type": "deviceStateChanged", "data": {"id": "s2", "isReachable": False}})
159
+ assert bus.last("ovos.home.event").data["type"] == "device.unavailable"
160
+
161
+
162
+ def test_not_paired_says_so(tmp_path):
163
+ bus = Bus()
164
+ brand = DirigeraBrand({}, BrandStorage(tmp_path, "dirigera"), hub_factory=FakeHub)
165
+ p = HomePlugin(bus=bus, config={"data_dir": str(tmp_path)}, brands={"dirigera": brand})
166
+ time.sleep(0.3)
167
+ assert p.status["dirigera"] == "not_paired"
168
+ row = ask(bus, "ovos.home.panel.brands")["items"][0]
169
+ assert row["can_pair"] and not row["can_unpair"]
170
+ p.shutdown()
171
+
172
+
173
+ def test_pairing_waits_for_the_button(tmp_path, monkeypatch):
174
+ import dirigera.hub.auth as auth
175
+ pressed = {"n": 0}
176
+ monkeypatch.setattr(auth, "send_challenge", lambda host, verifier: "code")
177
+
178
+ def token(host, code, verifier):
179
+ pressed["n"] += 1
180
+ if pressed["n"] < 2:
181
+ raise RuntimeError("not yet")
182
+ return "tok"
183
+ monkeypatch.setattr(auth, "get_token", token)
184
+ import ovos_home_plugin_dirigera as m
185
+ real_sleep = m.asyncio.sleep
186
+ monkeypatch.setattr(m.asyncio, "sleep", lambda s: real_sleep(0))
187
+ bus = Bus()
188
+ brand = DirigeraBrand({}, BrandStorage(tmp_path, "dirigera"), hub_factory=FakeHub)
189
+ p = HomePlugin(bus=bus, config={"data_dir": str(tmp_path)}, brands={"dirigera": brand})
190
+ assert ask(bus, "ovos.home.brand.pair", {"brand": "dirigera", "hub": "192.168.1.50"})["ok"]
191
+ end = time.time() + 3
192
+ while p.status.get("dirigera") != "ok" and time.time() < end:
193
+ time.sleep(0.02)
194
+ statuses = [m.data["status"] for m in bus.emitted if m.msg_type == "ovos.home.brand.pair.status"]
195
+ assert statuses == ["press_button", "paired"] and p.status["dirigera"] == "ok"
196
+ p.shutdown()