ovos-home-plugin-zigbee2mqtt 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,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: ovos-home-plugin-zigbee2mqtt
3
+ Version: 0.1.0a1
4
+ Summary: Zigbee2MQTT as a brand of ovos-PHAL-plugin-home: Zigbee lights, sensors, buttons and group scenes in the one home, over your own MQTT broker, 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-zigbee2mqtt
9
+ Project-URL: Issues, https://github.com/emkay-voice/ovos-home-plugin-zigbee2mqtt/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
+ Project-URL: Icon, https://raw.githubusercontent.com/emkay-voice/ovos-home-plugin-zigbee2mqtt/main/icon.png
13
+ Keywords: ovos,openvoiceos,plugin,smart-home,zigbee2mqtt,zigbee,mqtt,emkay
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Home Automation
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: ovos-PHAL-plugin-home>=0.2.0
22
+ Requires-Dist: aiomqtt>=2.0
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest; extra == "test"
25
+ Dynamic: license-file
26
+
27
+ # <img src='icon.png' card_color='#FFC135' width='50' height='50' style='vertical-align:bottom'/> ovos-home-plugin-zigbee2mqtt
28
+
29
+ [Zigbee2MQTT](https://www.zigbee2mqtt.io) as one brand of the one home for OpenVoiceOS, [ovos-PHAL-plugin-home](https://github.com/emkay-voice/ovos-PHAL-plugin-home): Zigbee lights, plugs, blinds, radiator valves, sensors and remotes – without the vendors' bridges – and the scenes of Zigbee2MQTT's groups.
30
+
31
+ Made for [Emkay](https://emkay.ai), and works on any OVOS with the home plugin.
32
+
33
+ **All in the house.** The MQTT broker Zigbee2MQTT already uses, in your house. The brand follows the devices' messages as they come.
34
+
35
+ ## Connecting
36
+
37
+ On the control panel's page **Home**, in the form **Connect a brand**: choose Zigbee2MQTT and fill in the broker's address (`192.168.1.5`, or `192.168.1.5:1884` for another port), and its user and password if it has one. They are kept in the house, never in `mycroft.conf`.
38
+
39
+ If Zigbee2MQTT doesn't use the topic `zigbee2mqtt`, put its `base_topic` in the brand's settings.
40
+
41
+ ## Rooms
42
+
43
+ Zigbee2MQTT's own way to structure names is a slash: a device called `Stue/Loftlampe` is *Loftlampe* in the room *Stue*, merged with other brands' rooms of the same name. Devices without a slash get their room on the page **Home**.
44
+
45
+ ## What comes along
46
+
47
+ What each device *exposes*:
48
+
49
+ | Zigbee2MQTT | The home |
50
+ |---|---|
51
+ | light | on/off, brightness, warmth (mired ↔ Kelvin) and colour |
52
+ | switch, plug | on/off (a plug or socket is an outlet) |
53
+ | cover | position |
54
+ | climate (radiator valves) | temperature, the temperature to heat to, heat/auto/off |
55
+ | fan | on/off |
56
+ | temperature, humidity, illuminance, CO2, PM2.5, power, energy, battery | readings |
57
+ | contact, occupancy, water leak, smoke | open/closed, movement, leak, smoke – with events |
58
+ | action (remotes, buttons) | button pressed: press, double, long, released – `brightness_up_hold` is the button *brightness_up*, held |
59
+ | scenes of groups | scenes |
60
+ | availability | when a device goes away and comes back |
61
+
62
+ For a device with more than one light or switch (a 2-gang switch), the first comes along.
63
+
64
+ **Never:** locks, and covers whose description says garage door or gate – opening the house by voice is left to Zigbee2MQTT itself.
65
+
66
+ ## Tested
67
+
68
+ Against a real Mosquitto broker with a stand-in for Zigbee2MQTT that publishes its device list and does what `/set` says: connecting from the page, the home, lights, blinds, changes coming back, and group scenes. The tests run on device lists shaped as Zigbee2MQTT 2.x publishes them. Reports from real Zigbee networks are very welcome in the issues.
69
+
70
+ ## License
71
+
72
+ Apache-2.0. Made by [emkay-voice](https://github.com/emkay-voice), maintained by Andreas Lorensen.
73
+
74
+ The Zigbee2MQTT logo belongs to the Zigbee2MQTT project. It is shown only to say what this plugin works with, taken from [zigbee2mqtt.io](https://github.com/Koenkk/zigbee2mqtt.io); this plugin is not made or endorsed by them.
@@ -0,0 +1,48 @@
1
+ # <img src='icon.png' card_color='#FFC135' width='50' height='50' style='vertical-align:bottom'/> ovos-home-plugin-zigbee2mqtt
2
+
3
+ [Zigbee2MQTT](https://www.zigbee2mqtt.io) as one brand of the one home for OpenVoiceOS, [ovos-PHAL-plugin-home](https://github.com/emkay-voice/ovos-PHAL-plugin-home): Zigbee lights, plugs, blinds, radiator valves, sensors and remotes – without the vendors' bridges – and the scenes of Zigbee2MQTT's groups.
4
+
5
+ Made for [Emkay](https://emkay.ai), and works on any OVOS with the home plugin.
6
+
7
+ **All in the house.** The MQTT broker Zigbee2MQTT already uses, in your house. The brand follows the devices' messages as they come.
8
+
9
+ ## Connecting
10
+
11
+ On the control panel's page **Home**, in the form **Connect a brand**: choose Zigbee2MQTT and fill in the broker's address (`192.168.1.5`, or `192.168.1.5:1884` for another port), and its user and password if it has one. They are kept in the house, never in `mycroft.conf`.
12
+
13
+ If Zigbee2MQTT doesn't use the topic `zigbee2mqtt`, put its `base_topic` in the brand's settings.
14
+
15
+ ## Rooms
16
+
17
+ Zigbee2MQTT's own way to structure names is a slash: a device called `Stue/Loftlampe` is *Loftlampe* in the room *Stue*, merged with other brands' rooms of the same name. Devices without a slash get their room on the page **Home**.
18
+
19
+ ## What comes along
20
+
21
+ What each device *exposes*:
22
+
23
+ | Zigbee2MQTT | The home |
24
+ |---|---|
25
+ | light | on/off, brightness, warmth (mired ↔ Kelvin) and colour |
26
+ | switch, plug | on/off (a plug or socket is an outlet) |
27
+ | cover | position |
28
+ | climate (radiator valves) | temperature, the temperature to heat to, heat/auto/off |
29
+ | fan | on/off |
30
+ | temperature, humidity, illuminance, CO2, PM2.5, power, energy, battery | readings |
31
+ | contact, occupancy, water leak, smoke | open/closed, movement, leak, smoke – with events |
32
+ | action (remotes, buttons) | button pressed: press, double, long, released – `brightness_up_hold` is the button *brightness_up*, held |
33
+ | scenes of groups | scenes |
34
+ | availability | when a device goes away and comes back |
35
+
36
+ For a device with more than one light or switch (a 2-gang switch), the first comes along.
37
+
38
+ **Never:** locks, and covers whose description says garage door or gate – opening the house by voice is left to Zigbee2MQTT itself.
39
+
40
+ ## Tested
41
+
42
+ Against a real Mosquitto broker with a stand-in for Zigbee2MQTT that publishes its device list and does what `/set` says: connecting from the page, the home, lights, blinds, changes coming back, and group scenes. The tests run on device lists shaped as Zigbee2MQTT 2.x publishes them. Reports from real Zigbee networks are very welcome in the issues.
43
+
44
+ ## License
45
+
46
+ Apache-2.0. Made by [emkay-voice](https://github.com/emkay-voice), maintained by Andreas Lorensen.
47
+
48
+ The Zigbee2MQTT logo belongs to the Zigbee2MQTT project. It is shown only to say what this plugin works with, taken from [zigbee2mqtt.io](https://github.com/Koenkk/zigbee2mqtt.io); this plugin is not made or endorsed by them.
@@ -0,0 +1,504 @@
1
+ """ovos-home-plugin-zigbee2mqtt: Zigbee2MQTT as one brand of the home.
2
+
3
+ Zigbee2MQTT's devices become part of the one home (ovos-PHAL-plugin-home),
4
+ read from what each device *exposes*: lights, plugs and switches, blinds,
5
+ radiator thermostats, sensors and buttons. A friendly name with a slash –
6
+ ``Stue/Loftlampe`` – puts the device in a room (Zigbee2MQTT's own way of
7
+ structuring names), and the scenes of Zigbee2MQTT's groups become scenes.
8
+
9
+ It talks to the MQTT broker Zigbee2MQTT already uses, in the house, and
10
+ follows the devices' messages as they come. The broker's address, user and
11
+ password go in the form "Connect a brand" on the control panel's page Home.
12
+
13
+ Locks and garage doors are never part of the home.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import colorsys
19
+ import json
20
+ from typing import Any, AsyncIterator, Callable, Optional
21
+
22
+ from ovos_phal_plugin_home import BrandError, BrandHome, Device, HomeBrand, Result, Room, Scene
23
+ from ovos_utils.log import LOG
24
+
25
+ #: numeric exposes -> the contract's state field
26
+ NUMERIC = {"temperature": "temperature", "humidity": "humidity", "battery": "battery", "power": "power",
27
+ "energy": "energy", "illuminance_lux": "illuminance", "illuminance": "illuminance", "co2": "co2",
28
+ "pm25": "pm25", "voc": "voc"}
29
+ #: binary exposes -> (state field, capability)
30
+ BINARY = {"contact": ("open", "contact"), "occupancy": ("motion", "motion"), "presence": ("motion", "motion"),
31
+ "water_leak": ("leak", "leak"), "smoke": ("smoke", "smoke")}
32
+ #: state field of a binary sensor -> its events (true, false)
33
+ BINARY_EVENTS = {"open": ("contact.opened", "contact.closed"),
34
+ "motion": ("motion.detected", "motion.cleared"),
35
+ "leak": ("leak.detected", "leak.cleared"),
36
+ "smoke": ("smoke.detected", "smoke.cleared")}
37
+ #: words in a device's description that make a cover something that opens the house
38
+ UNSAFE = ("garage", "gate", "door lock")
39
+ HEATING = {"heat": "heat", "off": "off", "auto": "auto"}
40
+
41
+
42
+ def _gamma(c: float) -> float:
43
+ return 1.055 * c ** (1 / 2.4) - 0.055 if c > 0.0031308 else 12.92 * c
44
+
45
+
46
+ def xy_to_hs(x: float, y: float) -> dict:
47
+ if not y:
48
+ return {"h": 0, "s": 0}
49
+ X, Z = x / y, (1 - x - y) / y
50
+ r = X * 3.2406 - 1.5372 - Z * 0.4986
51
+ g = -X * 0.9689 + 1.8758 + Z * 0.0415
52
+ b = X * 0.0557 - 0.2040 + Z * 1.0570
53
+ m = max(r, g, b, 1e-9)
54
+ r, g, b = (_gamma(max(0.0, c / m)) for c in (r, g, b))
55
+ h, s, _ = colorsys.rgb_to_hsv(min(r, 1), min(g, 1), min(b, 1))
56
+ return {"h": round(h * 360), "s": round(s * 100)}
57
+
58
+
59
+ def button_action(action: str) -> tuple[str, str]:
60
+ """Zigbee2MQTT's action ('brightness_up_hold', 'single', 'on') -> (button, action)."""
61
+ for suffix, what in (("_double", "double"), ("double", "double"), ("_hold", "long"), ("hold", "long"),
62
+ ("_long", "long"), ("long", "long"), ("_release", "release"), ("release", "release"),
63
+ ("_click", "press"), ("_press", "press"), ("_single", "press"), ("single", "press")):
64
+ if action.endswith(suffix):
65
+ button = action[: -len(suffix)].rstrip("_")
66
+ return button or "1", what
67
+ return action or "1", "press"
68
+
69
+
70
+ # ---- what a device exposes -> the contract (pure, tested on their own) --------
71
+
72
+ def _features(expose: dict) -> dict[str, dict]:
73
+ return {f.get("name"): f for f in expose.get("features") or []}
74
+
75
+
76
+ def read_device(dev: dict) -> Optional[dict]:
77
+ """How one device of bridge/devices fits the home, or None.
78
+
79
+ {"kind", "capabilities", "props": {property: (field, how)}, "set": {field: property}}
80
+ """
81
+ if dev.get("type") == "Coordinator" or dev.get("disabled") or not dev.get("definition"):
82
+ return None
83
+ desc = " ".join(str((dev.get("definition") or {}).get(k) or "") for k in ("description", "model")).lower()
84
+ exposes = dev["definition"].get("exposes") or []
85
+ kind, caps, props, sets = None, {}, {}, {}
86
+ for e in exposes:
87
+ etype = e.get("type")
88
+ if etype == "lock":
89
+ return None
90
+ if etype in ("light", "switch", "fan") and kind is None:
91
+ f = _features(e)
92
+ if "state" in f:
93
+ prop = f["state"].get("property", "state")
94
+ props[prop] = ("on", {"on": f["state"].get("value_on", "ON")})
95
+ sets["on"] = prop
96
+ caps["on_off"] = {}
97
+ if etype == "light":
98
+ if "brightness" in f:
99
+ props[f["brightness"]["property"]] = ("brightness", {"max": f["brightness"].get("value_max", 254)})
100
+ sets["brightness"] = f["brightness"]["property"]
101
+ caps["brightness"] = {}
102
+ if "color_temp" in f:
103
+ ct = f["color_temp"]
104
+ caps["color_temp"] = {"min": round(1e6 / (ct.get("value_max") or 500)),
105
+ "max": round(1e6 / (ct.get("value_min") or 153))}
106
+ props[ct["property"]] = ("color_temp", {})
107
+ sets["color_temp"] = ct["property"]
108
+ if "color_hs" in f or "color_xy" in f:
109
+ caps["color"] = {}
110
+ props["color"] = ("color", {})
111
+ sets["color"] = "color"
112
+ kind = {"light": "light", "fan": "fan"}.get(etype) or (
113
+ "outlet" if any(w in desc for w in ("plug", "socket", "outlet")) else "switch")
114
+ elif etype == "cover" and kind is None:
115
+ if any(w in desc for w in UNSAFE):
116
+ return None
117
+ f = _features(e)
118
+ if "position" in f:
119
+ props[f["position"]["property"]] = ("position", {})
120
+ sets["position"] = f["position"]["property"]
121
+ caps["position"] = {}
122
+ kind = "blind"
123
+ elif etype == "climate" and kind is None:
124
+ f = _features(e)
125
+ if "local_temperature" in f:
126
+ props[f["local_temperature"]["property"]] = ("temperature", {})
127
+ caps["temperature"] = {}
128
+ sp = f.get("occupied_heating_setpoint") or f.get("current_heating_setpoint")
129
+ if sp:
130
+ props[sp["property"]] = ("target_temperature", {})
131
+ sets["target_temperature"] = sp["property"]
132
+ caps["target_temperature"] = {"min": sp.get("value_min", 5), "max": sp.get("value_max", 30),
133
+ "step": sp.get("value_step", 0.5)}
134
+ if "system_mode" in f:
135
+ modes = [HEATING[v] for v in f["system_mode"].get("values") or [] if v in HEATING]
136
+ if modes:
137
+ props[f["system_mode"]["property"]] = ("heating", {})
138
+ sets["heating"] = f["system_mode"]["property"]
139
+ caps["heating"] = {"modes": modes}
140
+ kind = "climate"
141
+ elif etype == "numeric" and e.get("name") in NUMERIC and e.get("property") not in props:
142
+ field = NUMERIC[e["name"]]
143
+ props[e["property"]] = (field, {})
144
+ caps[field] = {}
145
+ elif etype == "binary" and e.get("name") in BINARY:
146
+ field, cap = BINARY[e["name"]]
147
+ props[e["property"]] = (field, {"true": e.get("value_on", True)})
148
+ caps[cap] = {}
149
+ elif etype == "enum" and e.get("name") == "action":
150
+ caps["button"] = {}
151
+ props[e.get("property", "action")] = ("button", {})
152
+ if not caps:
153
+ return None
154
+ if kind is None:
155
+ kind = "button" if caps.keys() == {"button"} or caps.keys() == {"button", "battery"} else "sensor"
156
+ return {"kind": kind, "capabilities": caps, "props": props, "set": sets}
157
+
158
+
159
+ def state_from(props: dict[str, tuple[str, dict]], payload: dict) -> dict:
160
+ """The contract's state fields in one state message of a device."""
161
+ out: dict[str, Any] = {}
162
+ for prop, value in payload.items():
163
+ if prop not in props:
164
+ continue
165
+ field, how = props[prop]
166
+ if field == "button" or value is None:
167
+ continue
168
+ if field == "on":
169
+ out["on"] = value == how["on"]
170
+ elif field == "brightness":
171
+ out["brightness"] = max(0, min(100, round(float(value) / how.get("max", 254) * 100)))
172
+ elif field == "color_temp":
173
+ if value:
174
+ out["color_temp"] = round(1e6 / float(value))
175
+ elif field == "color":
176
+ if isinstance(value, dict):
177
+ if value.get("hue") is not None and value.get("saturation") is not None:
178
+ out["color"] = {"h": round(value["hue"]), "s": round(value["saturation"])}
179
+ elif value.get("x") is not None and value.get("y") is not None:
180
+ out["color"] = xy_to_hs(value["x"], value["y"])
181
+ elif field == "heating":
182
+ if value in HEATING:
183
+ out["heating"] = HEATING[value]
184
+ elif "true" in how:
185
+ out[field] = value == how["true"] # value_on is the alarm side: open, moving, wet, smoke
186
+ elif isinstance(value, (int, float)):
187
+ out[field] = int(round(value)) if field in ("battery", "position") else round(float(value), 2)
188
+ return out
189
+
190
+
191
+ def split_name(friendly: str) -> tuple[Optional[str], str]:
192
+ """'Stue/Loftlampe' -> ('Stue', 'Loftlampe'); 'loft_lamp' -> (None, 'loft lamp')."""
193
+ room, _, name = friendly.rpartition("/")
194
+ room = room.split("/")[-1].strip() if room else None
195
+ return room or None, name.replace("_", " ").strip() or friendly
196
+
197
+
198
+ def payload_for(dev: dict, values: dict, transition_ms: Optional[int]) -> dict:
199
+ """The /set message for the contract's absolute values on one device."""
200
+ sets, props = dev["set"], dev["props"]
201
+ out: dict[str, Any] = {}
202
+ if values.get("on") is False:
203
+ out[sets["on"]] = "OFF"
204
+ else:
205
+ if values.get("on") and "on" in sets:
206
+ out[sets["on"]] = "ON"
207
+ if "brightness" in values and "brightness" in sets:
208
+ prop = sets["brightness"]
209
+ out[prop] = round(values["brightness"] / 100 * props[prop][1].get("max", 254))
210
+ if "color_temp" in values and "color_temp" in sets:
211
+ out[sets["color_temp"]] = round(1e6 / values["color_temp"])
212
+ if "color" in values and "color" in sets:
213
+ out["color"] = {"hue": values["color"]["h"], "saturation": values["color"]["s"]}
214
+ for field in ("position", "target_temperature", "heating"):
215
+ if field in values and field in sets:
216
+ out[sets[field]] = values[field]
217
+ if transition_ms and dev["kind"] == "light":
218
+ out["transition"] = round(transition_ms / 1000, 2)
219
+ return out
220
+
221
+
222
+ def build_home(devices: list[dict], groups: list[dict]):
223
+ """(home, known): the home Zigbee2MQTT's devices make, and ieee address -> read_device()."""
224
+ rooms: dict[str, Room] = {}
225
+ out, known = [], {}
226
+ for d in devices or []:
227
+ got = read_device(d)
228
+ if not got:
229
+ continue
230
+ ieee, friendly = d["ieee_address"], d.get("friendly_name") or d["ieee_address"]
231
+ room, name = split_name(friendly)
232
+ if room:
233
+ rooms.setdefault(room.lower(), Room(room.lower(), room))
234
+ got["friendly"] = friendly
235
+ known[ieee] = got
236
+ out.append(Device(ieee, name, got["kind"], got["capabilities"], {}, room.lower() if room else None))
237
+ scenes = []
238
+ for g in groups or []:
239
+ room, _ = split_name(g.get("friendly_name") or "")
240
+ gname = (g.get("friendly_name") or "").split("/")[-1]
241
+ rid = (room or gname).lower()
242
+ for s in g.get("scenes") or []:
243
+ scenes.append(Scene(f"{g['id']}:{s['id']}", s.get("name") or f"{gname} {s['id']}",
244
+ rid if rid in rooms else None))
245
+ return BrandHome(list(rooms.values()), out, scenes), known
246
+
247
+
248
+ # ---- talking to the broker ----------------------------------------------------
249
+
250
+ def broker_address(text: str) -> tuple[str, int]:
251
+ """'192.168.1.5', 'mqtt://broker:1884', 'broker:1883' -> (host, port)."""
252
+ text = (text or "").strip().rstrip("/")
253
+ if "://" in text:
254
+ text = text.split("://", 1)[1]
255
+ host, _, port = text.rpartition(":") if text.count(":") == 1 else (text, "", "")
256
+ try:
257
+ return host, int(port) if port else 1883
258
+ except ValueError:
259
+ return text, 1883
260
+
261
+
262
+ class Broker:
263
+ """The MQTT broker, through aiomqtt."""
264
+
265
+ def __init__(self, config: dict):
266
+ self.config = config
267
+ self._client = None
268
+
269
+ async def connect(self) -> None:
270
+ import aiomqtt
271
+ host, port = broker_address(self.config.get("host", ""))
272
+ self._client = aiomqtt.Client(host, int(self.config.get("port") or port),
273
+ username=self.config.get("username") or None,
274
+ password=self.config.get("password") or None)
275
+ await self._client.__aenter__()
276
+
277
+ async def subscribe(self, topic: str) -> None:
278
+ await self._client.subscribe(topic)
279
+
280
+ async def messages(self) -> AsyncIterator[tuple[str, bytes]]:
281
+ async for m in self._client.messages:
282
+ yield str(m.topic), m.payload
283
+
284
+ async def publish(self, topic: str, payload: dict) -> None:
285
+ await self._client.publish(topic, json.dumps(payload))
286
+
287
+ async def close(self) -> None:
288
+ if self._client is not None:
289
+ try:
290
+ await self._client.__aexit__(None, None, None)
291
+ except Exception: # noqa: BLE001 - already gone
292
+ pass
293
+ self._client = None
294
+
295
+
296
+ class Zigbee2MQTTBrand(HomeBrand):
297
+ name = "zigbee2mqtt"
298
+ display_name = "Zigbee2MQTT"
299
+ settings = {"address": "host", "user": "username", "key": "password"}
300
+
301
+ def __init__(self, config: Optional[dict] = None, storage=None,
302
+ broker_factory: Optional[Callable[[dict], Any]] = None):
303
+ super().__init__(config, storage)
304
+ self.base = (self.config.get("base_topic") or "zigbee2mqtt").rstrip("/")
305
+ self._factory = broker_factory or Broker
306
+ self.broker = None
307
+ self.devices_raw: Optional[list] = None
308
+ self.groups_raw: list = []
309
+ self.home = BrandHome()
310
+ self.known: dict[str, dict] = {} # ieee -> read_device()
311
+ self.by_friendly: dict[str, str] = {} # friendly name -> ieee
312
+ self.pending: dict[str, dict] = {} # state that came before the device list
313
+ self._reader: Optional[asyncio.Task] = None
314
+ self._have_devices: Optional[asyncio.Event] = None
315
+
316
+ @property
317
+ def paired(self) -> bool:
318
+ return bool(self.setting("host"))
319
+
320
+ @property
321
+ def hosts(self) -> list[str]:
322
+ return [broker_address(self.setting("host"))[0]] if self.paired else []
323
+
324
+ def broker_config(self) -> dict:
325
+ return {"host": self.setting("host"), "port": self.config.get("port"),
326
+ "username": self.setting("username"), "password": self.setting("password")}
327
+
328
+ async def start(self) -> None:
329
+ if not self.paired:
330
+ return
331
+ self._have_devices = asyncio.Event()
332
+ self.broker = self._factory(self.broker_config())
333
+ await self.broker.connect()
334
+ await self.broker.subscribe(f"{self.base}/#")
335
+ self._reader = asyncio.get_running_loop().create_task(self._read())
336
+ try:
337
+ await asyncio.wait_for(self._have_devices.wait(), float(self.config.get("wait", 10)))
338
+ except asyncio.TimeoutError:
339
+ raise BrandError("unavailable", f"no device list on {self.base}/bridge/devices – is Zigbee2MQTT running?")
340
+
341
+ async def stop(self) -> None:
342
+ if self._reader:
343
+ self._reader.cancel()
344
+ self._reader = None
345
+ if self.broker is not None:
346
+ await self.broker.close()
347
+ self.broker = None
348
+
349
+ async def _read(self) -> None:
350
+ delay = 5
351
+ while True:
352
+ try:
353
+ async for topic, payload in self.broker.messages():
354
+ delay = 5
355
+ self.on_message(topic, payload)
356
+ except asyncio.CancelledError:
357
+ return
358
+ except Exception as e: # noqa: BLE001
359
+ LOG.info(f"zigbee2mqtt brand: lost the broker: {e}")
360
+ for dev in self.home.devices:
361
+ self.update(dev.id, available=False)
362
+ while True:
363
+ await asyncio.sleep(delay)
364
+ try:
365
+ await self.broker.close()
366
+ await self.broker.connect()
367
+ await self.broker.subscribe(f"{self.base}/#")
368
+ break
369
+ except Exception as e: # noqa: BLE001
370
+ LOG.info(f"zigbee2mqtt brand: still no broker: {e}")
371
+ delay = min(delay * 2, 300)
372
+
373
+ # ---- messages ---------------------------------------------------------------
374
+
375
+ def on_message(self, topic: str, payload: bytes) -> None:
376
+ if not topic.startswith(self.base + "/"):
377
+ return
378
+ sub = topic[len(self.base) + 1:]
379
+ try:
380
+ data = json.loads(payload) if payload else None
381
+ except ValueError:
382
+ data = payload.decode("utf-8", "replace") if isinstance(payload, bytes) else payload
383
+ if sub == "bridge/devices":
384
+ self.devices_raw = data or []
385
+ if self._have_devices and not self._have_devices.is_set():
386
+ self._have_devices.set()
387
+ else:
388
+ self.home_changed()
389
+ return
390
+ if sub == "bridge/groups":
391
+ self.groups_raw = data or []
392
+ if self._have_devices and self._have_devices.is_set():
393
+ self.home_changed()
394
+ return
395
+ if sub == "bridge/state":
396
+ online = (data.get("state") if isinstance(data, dict) else data) == "online"
397
+ if not online:
398
+ for dev in self.home.devices:
399
+ self.update(dev.id, available=False)
400
+ return
401
+ if sub.startswith("bridge/"):
402
+ return
403
+ if sub.endswith("/availability"):
404
+ friendly = sub[: -len("/availability")]
405
+ ieee = self.by_friendly.get(friendly)
406
+ if ieee:
407
+ state = data.get("state") if isinstance(data, dict) else data
408
+ self._availability(ieee, state == "online")
409
+ return
410
+ if sub.endswith(("/set", "/get")) or not isinstance(data, dict):
411
+ return
412
+ ieee = self.by_friendly.get(sub)
413
+ if ieee is None:
414
+ self.pending[sub] = {**self.pending.get(sub, {}), **data}
415
+ return
416
+ self._state(ieee, data)
417
+
418
+ def _device(self, did: str) -> Optional[Device]:
419
+ return next((d for d in self.home.devices if d.id == did), None)
420
+
421
+ def _availability(self, ieee: str, online: bool) -> None:
422
+ dev = self._device(ieee)
423
+ if dev is None or dev.available == online:
424
+ return
425
+ dev.available = online
426
+ self.update(ieee, available=online)
427
+ self.event("device.available" if online else "device.unavailable", ieee)
428
+
429
+ def _state(self, ieee: str, data: dict) -> None:
430
+ dev, info = self._device(ieee), self.known.get(ieee)
431
+ if dev is None or info is None:
432
+ return
433
+ new = state_from(info["props"], data)
434
+ changed = {k: v for k, v in new.items() if dev.state.get(k) != v}
435
+ before = dict(dev.state)
436
+ if changed:
437
+ dev.state.update(changed)
438
+ self.update(ieee, changed)
439
+ for field, events in BINARY_EVENTS.items():
440
+ if field in changed and field in before:
441
+ self.event(events[0] if changed[field] else events[1], ieee)
442
+ if "battery" in changed:
443
+ v, was = changed["battery"], before.get("battery")
444
+ if v <= 10 and (was is None or was > 10):
445
+ self.event("battery.low", ieee, {"battery": v})
446
+ action = data.get("action")
447
+ if action and "button" in info["capabilities"]:
448
+ button, what = button_action(str(action))
449
+ self.event("button.pressed", ieee, {"button": button, "action": what})
450
+
451
+ # ---- the home -------------------------------------------------------------
452
+
453
+ async def get_home(self) -> BrandHome:
454
+ if self.devices_raw is None:
455
+ raise BrandError("unavailable", "no device list from Zigbee2MQTT yet")
456
+ old = {d.id: d for d in self.home.devices}
457
+ self.home, self.known = build_home(self.devices_raw, self.groups_raw)
458
+ self.by_friendly = {info["friendly"]: ieee for ieee, info in self.known.items()}
459
+ for dev in self.home.devices:
460
+ if dev.id in old: # keep what we already know across a rebuild
461
+ dev.state, dev.available = old[dev.id].state, old[dev.id].available
462
+ friendly = self.known[dev.id]["friendly"]
463
+ if friendly in self.pending:
464
+ dev.state.update(state_from(self.known[dev.id]["props"], self.pending.pop(friendly)))
465
+ # ask for the state of what can be set; sensors tell when they report
466
+ for ieee, info in self.known.items():
467
+ ask = {prop: "" for prop in info["set"].values() if prop != "color"}
468
+ if ask and ieee not in old:
469
+ try:
470
+ await self.broker.publish(f"{self.base}/{info['friendly']}/get", ask)
471
+ except Exception: # noqa: BLE001 - it comes when the device reports
472
+ pass
473
+ return self.home
474
+
475
+ async def set(self, changes, transition_ms=None):
476
+ results = []
477
+ for did, values in changes.items():
478
+ info = self.known.get(did)
479
+ if info is None:
480
+ results.append(Result(did, False, "unknown_device"))
481
+ continue
482
+ msg = payload_for(info, values, transition_ms)
483
+ if not msg or set(msg) == {"transition"}:
484
+ results.append(Result(did, False, "not_supported"))
485
+ continue
486
+ try:
487
+ await self.broker.publish(f"{self.base}/{info['friendly']}/set", msg)
488
+ results.append(Result(did))
489
+ except Exception as e: # noqa: BLE001
490
+ LOG.error(f"zigbee2mqtt brand: {did}: {e}")
491
+ results.append(Result(did, False, "unavailable"))
492
+ return results
493
+
494
+ async def activate_scene(self, scene_id: str) -> Result:
495
+ group_id, _, scene = scene_id.partition(":")
496
+ group = next((g for g in self.groups_raw if str(g.get("id")) == group_id), None)
497
+ if group is None or not scene:
498
+ return Result(scene_id, False, "unknown_scene")
499
+ try:
500
+ await self.broker.publish(f"{self.base}/{group['friendly_name']}/set", {"scene_recall": int(scene)})
501
+ return Result(scene_id)
502
+ except Exception: # noqa: BLE001
503
+ return Result(scene_id, False, "unavailable")
504
+
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: ovos-home-plugin-zigbee2mqtt
3
+ Version: 0.1.0a1
4
+ Summary: Zigbee2MQTT as a brand of ovos-PHAL-plugin-home: Zigbee lights, sensors, buttons and group scenes in the one home, over your own MQTT broker, 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-zigbee2mqtt
9
+ Project-URL: Issues, https://github.com/emkay-voice/ovos-home-plugin-zigbee2mqtt/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
+ Project-URL: Icon, https://raw.githubusercontent.com/emkay-voice/ovos-home-plugin-zigbee2mqtt/main/icon.png
13
+ Keywords: ovos,openvoiceos,plugin,smart-home,zigbee2mqtt,zigbee,mqtt,emkay
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Home Automation
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: ovos-PHAL-plugin-home>=0.2.0
22
+ Requires-Dist: aiomqtt>=2.0
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest; extra == "test"
25
+ Dynamic: license-file
26
+
27
+ # <img src='icon.png' card_color='#FFC135' width='50' height='50' style='vertical-align:bottom'/> ovos-home-plugin-zigbee2mqtt
28
+
29
+ [Zigbee2MQTT](https://www.zigbee2mqtt.io) as one brand of the one home for OpenVoiceOS, [ovos-PHAL-plugin-home](https://github.com/emkay-voice/ovos-PHAL-plugin-home): Zigbee lights, plugs, blinds, radiator valves, sensors and remotes – without the vendors' bridges – and the scenes of Zigbee2MQTT's groups.
30
+
31
+ Made for [Emkay](https://emkay.ai), and works on any OVOS with the home plugin.
32
+
33
+ **All in the house.** The MQTT broker Zigbee2MQTT already uses, in your house. The brand follows the devices' messages as they come.
34
+
35
+ ## Connecting
36
+
37
+ On the control panel's page **Home**, in the form **Connect a brand**: choose Zigbee2MQTT and fill in the broker's address (`192.168.1.5`, or `192.168.1.5:1884` for another port), and its user and password if it has one. They are kept in the house, never in `mycroft.conf`.
38
+
39
+ If Zigbee2MQTT doesn't use the topic `zigbee2mqtt`, put its `base_topic` in the brand's settings.
40
+
41
+ ## Rooms
42
+
43
+ Zigbee2MQTT's own way to structure names is a slash: a device called `Stue/Loftlampe` is *Loftlampe* in the room *Stue*, merged with other brands' rooms of the same name. Devices without a slash get their room on the page **Home**.
44
+
45
+ ## What comes along
46
+
47
+ What each device *exposes*:
48
+
49
+ | Zigbee2MQTT | The home |
50
+ |---|---|
51
+ | light | on/off, brightness, warmth (mired ↔ Kelvin) and colour |
52
+ | switch, plug | on/off (a plug or socket is an outlet) |
53
+ | cover | position |
54
+ | climate (radiator valves) | temperature, the temperature to heat to, heat/auto/off |
55
+ | fan | on/off |
56
+ | temperature, humidity, illuminance, CO2, PM2.5, power, energy, battery | readings |
57
+ | contact, occupancy, water leak, smoke | open/closed, movement, leak, smoke – with events |
58
+ | action (remotes, buttons) | button pressed: press, double, long, released – `brightness_up_hold` is the button *brightness_up*, held |
59
+ | scenes of groups | scenes |
60
+ | availability | when a device goes away and comes back |
61
+
62
+ For a device with more than one light or switch (a 2-gang switch), the first comes along.
63
+
64
+ **Never:** locks, and covers whose description says garage door or gate – opening the house by voice is left to Zigbee2MQTT itself.
65
+
66
+ ## Tested
67
+
68
+ Against a real Mosquitto broker with a stand-in for Zigbee2MQTT that publishes its device list and does what `/set` says: connecting from the page, the home, lights, blinds, changes coming back, and group scenes. The tests run on device lists shaped as Zigbee2MQTT 2.x publishes them. Reports from real Zigbee networks are very welcome in the issues.
69
+
70
+ ## License
71
+
72
+ Apache-2.0. Made by [emkay-voice](https://github.com/emkay-voice), maintained by Andreas Lorensen.
73
+
74
+ The Zigbee2MQTT logo belongs to the Zigbee2MQTT project. It is shown only to say what this plugin works with, taken from [zigbee2mqtt.io](https://github.com/Koenkk/zigbee2mqtt.io); this plugin is not made or endorsed by them.
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ ovos_home_plugin_zigbee2mqtt/__init__.py
5
+ ovos_home_plugin_zigbee2mqtt.egg-info/PKG-INFO
6
+ ovos_home_plugin_zigbee2mqtt.egg-info/SOURCES.txt
7
+ ovos_home_plugin_zigbee2mqtt.egg-info/dependency_links.txt
8
+ ovos_home_plugin_zigbee2mqtt.egg-info/entry_points.txt
9
+ ovos_home_plugin_zigbee2mqtt.egg-info/requires.txt
10
+ ovos_home_plugin_zigbee2mqtt.egg-info/top_level.txt
11
+ tests/test_brand.py
@@ -0,0 +1,2 @@
1
+ [opm.home]
2
+ zigbee2mqtt = ovos_home_plugin_zigbee2mqtt:Zigbee2MQTTBrand
@@ -0,0 +1,5 @@
1
+ ovos-PHAL-plugin-home>=0.2.0
2
+ aiomqtt>=2.0
3
+
4
+ [test]
5
+ pytest
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ovos-home-plugin-zigbee2mqtt"
7
+ version = "0.1.0a1"
8
+ description = "Zigbee2MQTT as a brand of ovos-PHAL-plugin-home: Zigbee lights, sensors, buttons and group scenes in the one home, over your own MQTT broker, 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", "zigbee2mqtt", "zigbee", "mqtt", "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.2.0", "aiomqtt>=2.0"]
22
+
23
+ [project.optional-dependencies]
24
+ test = ["pytest"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/emkay-voice/ovos-home-plugin-zigbee2mqtt"
28
+ Issues = "https://github.com/emkay-voice/ovos-home-plugin-zigbee2mqtt/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
+ Icon = "https://raw.githubusercontent.com/emkay-voice/ovos-home-plugin-zigbee2mqtt/main/icon.png"
32
+
33
+ [project.entry-points."opm.home"]
34
+ zigbee2mqtt = "ovos_home_plugin_zigbee2mqtt:Zigbee2MQTTBrand"
35
+
36
+ [tool.setuptools]
37
+ packages = ["ovos_home_plugin_zigbee2mqtt"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,178 @@
1
+ """Zigbee2MQTT as a brand: its MQTT messages, through the real manager."""
2
+ import asyncio
3
+ import json
4
+ import threading
5
+ import time
6
+
7
+ import pytest
8
+ from ovos_bus_client.message import Message
9
+
10
+ from devices import DEVICES, GROUPS
11
+ from ovos_home_plugin_zigbee2mqtt import (Zigbee2MQTTBrand, broker_address, build_home, button_action,
12
+ payload_for, split_name)
13
+ from ovos_phal_plugin_home import BrandStorage, HomePlugin
14
+
15
+
16
+ class FakeBroker:
17
+ """A broker with Zigbee2MQTT's retained device list on it."""
18
+
19
+ def __init__(self, config):
20
+ self.config = config
21
+ self.published = []
22
+ self.queue = None
23
+
24
+ async def connect(self):
25
+ self.queue = asyncio.Queue()
26
+
27
+ async def subscribe(self, topic):
28
+ assert topic == "zigbee2mqtt/#"
29
+ self.queue.put_nowait(("zigbee2mqtt/bridge/groups", json.dumps(GROUPS).encode()))
30
+ self.queue.put_nowait(("zigbee2mqtt/Stue/Loftlampe", b'{"state":"ON","brightness":127,"color_temp":370,'
31
+ b'"color":{"x":0.4596,"y":0.4105},"linkquality":80}'))
32
+ self.queue.put_nowait(("zigbee2mqtt/bridge/devices", json.dumps(DEVICES).encode()))
33
+
34
+ async def messages(self):
35
+ while True:
36
+ yield await self.queue.get()
37
+
38
+ async def publish(self, topic, payload):
39
+ self.published.append((topic, payload))
40
+
41
+ async def close(self):
42
+ pass
43
+
44
+
45
+ class Bus:
46
+ def __init__(self):
47
+ self.handlers, self.emitted, self.lock = {}, [], threading.Lock()
48
+
49
+ def on(self, t, h):
50
+ self.handlers.setdefault(t, []).append(h)
51
+
52
+ def once(self, t, h):
53
+ self.on(t, h)
54
+
55
+ def remove(self, t, h):
56
+ pass
57
+
58
+ def emit(self, m):
59
+ json.dumps(m.data)
60
+ with self.lock:
61
+ self.emitted.append(m)
62
+ for h in list(self.handlers.get(m.msg_type, [])):
63
+ h(m)
64
+
65
+ def last(self, t):
66
+ with self.lock:
67
+ return next((m for m in reversed(self.emitted) if m.msg_type == t), None)
68
+
69
+
70
+ def ask(bus, t, data=None):
71
+ bus.emit(Message(t, data or {}))
72
+ return bus.last(t + ".response").data
73
+
74
+
75
+ def wait(check, seconds=3):
76
+ end = time.time() + seconds
77
+ while not check() and time.time() < end:
78
+ time.sleep(0.02)
79
+ return check()
80
+
81
+
82
+ @pytest.fixture
83
+ def home(tmp_path):
84
+ bus = Bus()
85
+ storage = BrandStorage(tmp_path, "zigbee2mqtt")
86
+ storage.set("host", "192.168.1.5")
87
+ brand = Zigbee2MQTTBrand({}, storage, broker_factory=FakeBroker)
88
+ p = HomePlugin(bus=bus, config={"data_dir": str(tmp_path)}, brands={"zigbee2mqtt": brand})
89
+ assert wait(lambda: p.status.get("zigbee2mqtt") == "ok")
90
+ yield bus, brand, p
91
+ p.shutdown()
92
+
93
+
94
+ def send(p, brand, topic, payload):
95
+ p.loop.call_soon_threadsafe(brand.broker.queue.put_nowait, (f"zigbee2mqtt/{topic}", json.dumps(payload).encode()))
96
+
97
+
98
+ def test_names_and_buttons():
99
+ assert split_name("Stue/Loftlampe") == ("Stue", "Loftlampe")
100
+ assert split_name("Hus/Stue/Loftlampe") == ("Stue", "Loftlampe")
101
+ assert split_name("remote_stue") == (None, "remote stue")
102
+ assert button_action("brightness_up_hold") == ("brightness_up", "long")
103
+ assert button_action("single") == ("1", "press") and button_action("toggle") == ("toggle", "press")
104
+ assert button_action("arrow_left_double") == ("arrow_left", "double")
105
+
106
+
107
+ def test_the_broker_as_typed(tmp_path):
108
+ assert broker_address("192.168.1.5") == ("192.168.1.5", 1883)
109
+ assert broker_address("mqtt://broker.local:1884/") == ("broker.local", 1884)
110
+ storage = BrandStorage(tmp_path, "zigbee2mqtt")
111
+ brand = Zigbee2MQTTBrand({}, storage)
112
+ assert not brand.paired
113
+ storage.save({"host": "broker:1884", "username": "z2m", "password": "hemmelig"})
114
+ assert brand.paired and brand.hosts == ["broker"]
115
+ assert brand.broker_config() == {"host": "broker:1884", "port": None, "username": "z2m", "password": "hemmelig"}
116
+
117
+
118
+ def test_what_devices_expose():
119
+ home, known = build_home(DEVICES, GROUPS)
120
+ d = {x.name: x for x in home.devices}
121
+ # the coordinator, the lock and the garage door are left out
122
+ assert set(d) == {"Loftlampe", "kaffemaskine", "Vindue", "remote stue", "Radiator", "Rullegardin"}
123
+ assert d["Loftlampe"].kind == "light" and d["Loftlampe"].room == "stue"
124
+ assert d["Loftlampe"].capabilities["color_temp"] == {"min": 2203, "max": 4000}
125
+ assert set(d["Loftlampe"].capabilities) == {"on_off", "brightness", "color_temp", "color"}
126
+ assert d["kaffemaskine"].kind == "outlet" and set(d["kaffemaskine"].capabilities) == {"on_off", "power"}
127
+ assert set(d["Vindue"].capabilities) == {"battery", "contact"} and d["Vindue"].kind == "sensor"
128
+ assert d["remote stue"].kind == "button" and d["remote stue"].room is None
129
+ assert d["Radiator"].capabilities["heating"] == {"modes": ["heat", "auto", "off"]}
130
+ assert d["Rullegardin"].kind == "blind"
131
+ assert {r.name for r in home.rooms} == {"Stue", "Køkken"}
132
+ assert [(s.id, s.name, s.room) for s in home.scenes] == [("1:3", "Aftenhygge", "stue")]
133
+
134
+
135
+ def test_payloads():
136
+ _, known = build_home(DEVICES, GROUPS)
137
+ lamp = known["0x000b57fffe000001"]
138
+ assert payload_for(lamp, {"on": True, "brightness": 50}, 400) == {"state": "ON", "brightness": 127, "transition": 0.4}
139
+ assert payload_for(lamp, {"on": False}, None) == {"state": "OFF"}
140
+ assert payload_for(lamp, {"color_temp": 2700}, None) == {"color_temp": 370}
141
+ assert payload_for(lamp, {"color": {"h": 0, "s": 100}}, None) == {"color": {"hue": 0, "saturation": 100}}
142
+ rad = known["0xa4c1380000000005"]
143
+ assert payload_for(rad, {"target_temperature": 21.5, "heating": "heat"}, None) == {
144
+ "current_heating_setpoint": 21.5, "system_mode": "heat"}
145
+
146
+
147
+ def test_through_the_manager(home):
148
+ bus, brand, p = home
149
+ got = ask(bus, "ovos.home.get")
150
+ d = {x["name"]: x for x in got["devices"]}
151
+ lamp = d["Loftlampe"]
152
+ # its state came before the device list, and isn't lost
153
+ assert lamp["id"] == "zigbee2mqtt:0x000b57fffe000001" and lamp["room"] == "home:stue"
154
+ assert lamp["state"]["on"] is True and lamp["state"]["brightness"] == 50 and lamp["state"]["color_temp"] == 2703
155
+ assert 25 <= lamp["state"]["color"]["h"] <= 45
156
+ # the state of what can be set is asked for
157
+ assert ("zigbee2mqtt/Stue/Rullegardin/get", {"position": ""}) in brand.broker.published
158
+ r = ask(bus, "ovos.home.set", {"target": {"devices": [lamp["id"]]}, "set": {"brightness": 100}})
159
+ assert r["ok"] and brand.broker.published[-1] == ("zigbee2mqtt/Stue/Loftlampe/set", {"state": "ON", "brightness": 254})
160
+ assert ask(bus, "ovos.home.scene.activate", {"id": "zigbee2mqtt:1:3"})["ok"]
161
+ assert brand.broker.published[-1] == ("zigbee2mqtt/Stue/set", {"scene_recall": 3})
162
+
163
+
164
+ def test_events(home):
165
+ bus, brand, p = home
166
+ ask(bus, "ovos.home.get")
167
+ send(p, brand, "Køkken/Vindue", {"contact": True, "battery": 90})
168
+ assert wait(lambda: ask(bus, "ovos.home.device.get", {"id": "zigbee2mqtt:0x00158d0000000003"})["device"]
169
+ ["state"].get("open") is False)
170
+ send(p, brand, "Køkken/Vindue", {"contact": False, "battery": 9})
171
+ assert wait(lambda: bus.last("ovos.home.event") and bus.last("ovos.home.event").data["type"] == "battery.low")
172
+ types = [m.data["type"] for m in bus.emitted if m.msg_type == "ovos.home.event"]
173
+ assert types == ["contact.opened", "battery.low"]
174
+ send(p, brand, "remote_stue", {"action": "brightness_up_hold", "battery": 80})
175
+ assert wait(lambda: bus.last("ovos.home.event").data["type"] == "button.pressed")
176
+ assert bus.last("ovos.home.event").data["data"] == {"button": "brightness_up", "action": "long"}
177
+ send(p, brand, "Stue/Loftlampe/availability", {"state": "offline"})
178
+ assert wait(lambda: bus.last("ovos.home.event").data["type"] == "device.unavailable")