py-ha-ws-client 0.1__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,95 @@
1
+ Metadata-Version: 2.1
2
+ Name: py_ha_ws_client
3
+ Version: 0.1
4
+ Summary: A Python client to make it easy to connect and consume data from the Home Assistant web socket API.
5
+ Home-page: https://github.com/foxy82/py-ha-ws-client
6
+ Author: foxy82
7
+ Author-email: foxy82.github@gmail.com
8
+ License: Apache 2.0
9
+ Download-URL: https://github.com/foxy82/py-ha-ws-client/archive/0.1.tar.gz
10
+ Keywords: Home Assistant,Websocket
11
+ Platform: UNKNOWN
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Topic :: Software Development :: Build Tools
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+
20
+ # py-ha-ws-client
21
+ A Python client to make it easy to connect and consume data from the [Home Assistant web socket API](https://developers.home-assistant.io/docs/api/websocket/).
22
+
23
+
24
+ ## Example
25
+
26
+ ```
27
+ from time import sleep
28
+ from py_ha_ws_client.client import HomeAssistantWsClient
29
+
30
+ hostname = "<Home Assistant IP>"
31
+ #token = "<from Home Assistant>"
32
+
33
+ client = HomeAssistantWsClient(token, hostname)
34
+ client.connect()
35
+
36
+ while not client.connected():
37
+ sleep(1)
38
+
39
+ # Get all the states as a list
40
+ print("Get all States")
41
+ states = client.get_states()
42
+ print("Print one state as an example")
43
+ print(states[0])
44
+
45
+
46
+ entity_id = "media_player.amplifier"
47
+
48
+ # Define a call back
49
+ def my_callback(entity_id, message):
50
+ print(entity_id, message)
51
+
52
+ # Get the state of a single entity
53
+ state = client.get_state(entity_id)
54
+ print(state)
55
+
56
+ # Register for updates for a specfic entity
57
+ client.subscribe_to_trigger(
58
+ entity_id="media_player.studio_amplifier",
59
+ callback=my_callback,
60
+ )
61
+
62
+ sleep(10)
63
+
64
+ # Send a turn on command
65
+ client.turn_on(
66
+ entity_id=entity_id
67
+ )
68
+
69
+ sleep(10)
70
+
71
+ # Send a change volume command
72
+ client.call_service(
73
+ domain="media_player",
74
+ service="volume_set",
75
+ entity_id=entity_id,
76
+ service_data={
77
+ "volume_level" : "0.50"
78
+ }
79
+ )
80
+
81
+ sleep(10)
82
+
83
+ # Send a turn off command
84
+ client.turn_off(
85
+ entity_id=entity_id
86
+ )
87
+
88
+ sleep(60)
89
+
90
+ ```
91
+
92
+ ## TODO
93
+
94
+ This is a work in progress there are a lot of TODOs in the code.
95
+
@@ -0,0 +1,75 @@
1
+ # py-ha-ws-client
2
+ A Python client to make it easy to connect and consume data from the [Home Assistant web socket API](https://developers.home-assistant.io/docs/api/websocket/).
3
+
4
+
5
+ ## Example
6
+
7
+ ```
8
+ from time import sleep
9
+ from py_ha_ws_client.client import HomeAssistantWsClient
10
+
11
+ hostname = "<Home Assistant IP>"
12
+ #token = "<from Home Assistant>"
13
+
14
+ client = HomeAssistantWsClient(token, hostname)
15
+ client.connect()
16
+
17
+ while not client.connected():
18
+ sleep(1)
19
+
20
+ # Get all the states as a list
21
+ print("Get all States")
22
+ states = client.get_states()
23
+ print("Print one state as an example")
24
+ print(states[0])
25
+
26
+
27
+ entity_id = "media_player.amplifier"
28
+
29
+ # Define a call back
30
+ def my_callback(entity_id, message):
31
+ print(entity_id, message)
32
+
33
+ # Get the state of a single entity
34
+ state = client.get_state(entity_id)
35
+ print(state)
36
+
37
+ # Register for updates for a specfic entity
38
+ client.subscribe_to_trigger(
39
+ entity_id="media_player.studio_amplifier",
40
+ callback=my_callback,
41
+ )
42
+
43
+ sleep(10)
44
+
45
+ # Send a turn on command
46
+ client.turn_on(
47
+ entity_id=entity_id
48
+ )
49
+
50
+ sleep(10)
51
+
52
+ # Send a change volume command
53
+ client.call_service(
54
+ domain="media_player",
55
+ service="volume_set",
56
+ entity_id=entity_id,
57
+ service_data={
58
+ "volume_level" : "0.50"
59
+ }
60
+ )
61
+
62
+ sleep(10)
63
+
64
+ # Send a turn off command
65
+ client.turn_off(
66
+ entity_id=entity_id
67
+ )
68
+
69
+ sleep(60)
70
+
71
+ ```
72
+
73
+ ## TODO
74
+
75
+ This is a work in progress there are a lot of TODOs in the code.
File without changes
@@ -0,0 +1,462 @@
1
+ import abc
2
+ from abc import ABC
3
+ from time import sleep
4
+ from ws4py.client.threadedclient import WebSocketClient
5
+ import logging
6
+ import json
7
+ import threading
8
+ import itertools
9
+
10
+ latest_states = {}
11
+ include_by_default = True
12
+
13
+
14
+ class HomeAssistantWsClient:
15
+
16
+ def __init__(self, token, hostname, port=8123):
17
+ self.logger = logging.getLogger(__name__)
18
+ self.url = f'ws://{hostname}:{port}/api/websocket'
19
+ self.token = token
20
+ self.ws_client = None
21
+ self._reconnection_thread = None
22
+ self._triggers = []
23
+
24
+ def connect(self):
25
+ """
26
+ Connect to the Home Assistant Web Socket API
27
+ :return:
28
+ """
29
+ self._reconnection_thread = threading.Thread(target=self._connect, daemon=True)
30
+ self._reconnection_thread.start()
31
+
32
+ def get_states(self):
33
+ """
34
+ Blocking call to get all states from Home Assistant
35
+ https://developers.home-assistant.io/docs/api/websocket/#fetching-states
36
+ :return:
37
+ """
38
+ if self.ws_client.authenticated:
39
+ callback = BlockingCallback()
40
+ self.ws_client.get_states(callback)
41
+ return callback.get_result()
42
+ else:
43
+ self.logger.warning(f"Can't get states as we aren't connected to home assistant")
44
+
45
+
46
+ def get_state(self, entity_id):
47
+ """
48
+ Blocking call to get a single entities state from Home Assistant
49
+ https://developers.home-assistant.io/docs/api/websocket/#fetching-states
50
+ :return:
51
+ """
52
+ states = self.get_states()
53
+ if states:
54
+ for state in states:
55
+
56
+ if(state.get("entity_id", None) == entity_id):
57
+ return state
58
+ self.logger.warning(f"{entity_id} not found in Home Assistant")
59
+ return None
60
+
61
+
62
+ def get_config(self):
63
+ """
64
+ https://developers.home-assistant.io/docs/api/websocket/#fetching-config
65
+ :return:
66
+ """
67
+ # TODO implement this
68
+ pass
69
+
70
+ def get_services(self):
71
+ """
72
+ https://developers.home-assistant.io/docs/api/websocket/#fetching-services
73
+ :return:
74
+ """
75
+ # TODO implement this
76
+ pass
77
+
78
+ def subscribe_to_events(self, event_type):
79
+ """
80
+ https://developers.home-assistant.io/docs/api/websocket/#subscribe-to-events
81
+ :param event_type:
82
+ :return:
83
+ """
84
+ # TODO implement this
85
+ pass
86
+
87
+ def unsubscribe_from_events(self):
88
+ """
89
+ https://developers.home-assistant.io/docs/api/websocket/#unsubscribing-from-events
90
+ :return:
91
+ """
92
+ # TODO implement this
93
+ pass
94
+
95
+ def fire_an_event(self):
96
+ """
97
+ https://developers.home-assistant.io/docs/api/websocket/#fire-an-event
98
+ :return:
99
+ """
100
+ # TODO implement this
101
+ pass
102
+
103
+ # TODO pass in a trigger not entity_id/from_state/to_state so we can be more flexible
104
+ def subscribe_to_trigger(self, entity_id, callback, from_state=None, to_state=None):
105
+ """
106
+ Subscribe to a trigger
107
+ https://developers.home-assistant.io/docs/api/websocket/#subscribe-to-trigger
108
+ :param entity_id:
109
+ :param callback:
110
+ :param from_state:
111
+ :param to_state:
112
+ :return:
113
+ """
114
+ self._triggers.append(
115
+ Subscription(
116
+ entity_id,
117
+ callback,
118
+ from_state,
119
+ to_state
120
+ )
121
+ )
122
+
123
+ if self.ws_client.authenticated:
124
+ self.ws_client.subscribe_to_trigger(entity_id, callback, from_state, to_state)
125
+
126
+ def unsubscribe_from_trigger(self):
127
+ """
128
+ Need to test this, but I guess this is the same as unsubscribing from an event
129
+ https://developers.home-assistant.io/docs/api/websocket/#unsubscribing-from-events
130
+ :return:
131
+ """
132
+ # TODO implement this
133
+ pass
134
+
135
+ def call_service(self, domain, service, entity_id=None, service_data=None):
136
+ """
137
+ Call a service:
138
+ https://developers.home-assistant.io/docs/api/websocket/#calling-a-service
139
+ :param domain:
140
+ :param service:
141
+ :param entity_id:
142
+ :param service_data:
143
+ :return:
144
+ """
145
+ if self.ws_client.authenticated:
146
+ self.ws_client.call_service(domain, service, entity_id, service_data)
147
+ else:
148
+ self.logger.warning(f"Can't call {domain}.{service} as we aren't connected to home assistant")
149
+
150
+ def validate_config(self):
151
+ """
152
+ https://developers.home-assistant.io/docs/api/websocket/#validate-config
153
+ :return:
154
+ """
155
+ # TODO implement this
156
+ pass
157
+
158
+ def turn_on(self, entity_id):
159
+ if self.ws_client.authenticated:
160
+ self.ws_client.turn_on(entity_id)
161
+ else:
162
+ self.logger.warning(f"Can't turn on {entity_id} as we aren't connected to home assistant")
163
+
164
+ def turn_off(self, entity_id):
165
+ if self.ws_client.authenticated:
166
+ self.ws_client.turn_off(entity_id)
167
+ else:
168
+ self.logger.warning(f"Can't turn off {entity_id} as we aren't connected to home assistant")
169
+
170
+ def _authenticated(self, auth_success):
171
+ if auth_success:
172
+ for trigger in self._triggers:
173
+ self.ws_client.subscribe_to_trigger(
174
+ trigger.entity_id,
175
+ trigger.callback,
176
+ trigger.from_state,
177
+ trigger.to_state
178
+ )
179
+
180
+ def connected(self):
181
+ if self.ws_client is None or self.ws_client.client_terminated:
182
+ return False
183
+ return True
184
+
185
+ def _disconnected(self):
186
+ self.logger.warning("Disconnected will attempt to reconnect.")
187
+ self._reconnection_thread = threading.Thread(target=self._reconnect, daemon=True)
188
+ self._reconnection_thread.start()
189
+
190
+ def _internal_connection(self):
191
+ while not self.connected():
192
+ self.logger.debug("Home Assistant WebSocket - Attempting to connect...")
193
+ self._connect_if_required()
194
+ self.logger.debug(f"Home Assistant WebSocket - connection work? {self.connected()}")
195
+ sleep(5) # Give a moment before reconnecting to ensure the socket has been closed.
196
+
197
+ def _connect(self):
198
+ self.logger.debug("Home Assistant WebSocket - Starting connection thread")
199
+ self._internal_connection()
200
+ self.logger.debug("Home Assistant WebSocket - connection complete - connection thread ending")
201
+
202
+ def _connect_if_required(self):
203
+ if not self.connected():
204
+ try:
205
+ self.ws_client = _HaWsClient(self.url)
206
+ self.ws_client.set_token(self.token)
207
+ self.ws_client.set_disconnect_callback(self._disconnected)
208
+ self.ws_client.set_authenticated_callback(self._authenticated)
209
+ self.ws_client.connect()
210
+ except Exception as e:
211
+ self.logger.info("Error connecting to Home Assistant Websocket", e)
212
+ self.ws_client = None
213
+
214
+ def _reconnect(self):
215
+ self.logger.info("Home Assistant WebSocket - Starting reconnection thread")
216
+ sleep(5) # Give a second before reconnecting to ensure the socket has been closed.
217
+ self._internal_connection()
218
+ self.logger.info("Home Assistant WebSocket - Reconnection complete - reconnection thread ending")
219
+
220
+
221
+ # TODO add pings to ensure connectivity
222
+ class _HaWsClient(WebSocketClient):
223
+ logger = logging.getLogger(__name__)
224
+ authenticated = False
225
+ connected = False
226
+ id_generator = itertools.count(start=1)
227
+ id_to_type = {}
228
+ id_to_entity_id = {}
229
+ id_to_callback = {}
230
+ _entity_id_to_trigger = {}
231
+ reconnection_thread = None
232
+ homeassistant_token = ""
233
+
234
+ def __init__(self, url):
235
+ super().__init__(url)
236
+ self._disconnected_callback = self.do_nothing
237
+ self._authenticated_callback = self.do_nothing
238
+
239
+ def set_token(self, token):
240
+ self.homeassistant_token = token
241
+
242
+ def set_disconnect_callback(self, callback):
243
+ self._disconnected_callback = callback
244
+
245
+ def set_authenticated_callback(self, callback):
246
+ self._authenticated_callback = callback
247
+
248
+ def opened(self):
249
+ self.logger.info("Home Assistant WebSocket Connection Opened")
250
+ self.connected = True
251
+
252
+ def closed(self, code, reason=None):
253
+ self.logger.warning("Home Assistant WebSocket Connection Closed. Code: {} Reason {}".format(code, reason))
254
+ self.connected = False
255
+ self.authenticated = False
256
+
257
+ self.id_to_type.clear()
258
+ self.id_to_entity_id.clear()
259
+ self._entity_id_to_trigger.clear()
260
+
261
+ self._disconnected_callback()
262
+
263
+ def subscribe_to_trigger(self, entity_id, callback, from_state=None, to_state=None):
264
+ self.logger.info(f"Subscribing for trigger for {entity_id} from_state: {from_state}, to_state: {to_state}")
265
+ trigger = {
266
+ "platform": "state",
267
+ "entity_id": entity_id,
268
+ }
269
+ if from_state:
270
+ trigger['from'] = from_state
271
+ if to_state:
272
+ trigger['to'] = to_state
273
+
274
+ payload = {
275
+ "type": "subscribe_trigger",
276
+ "trigger": trigger,
277
+ }
278
+
279
+ message_id = self._send_and_return_message_id(payload, "subscribe_trigger")
280
+ self.id_to_entity_id[message_id] = entity_id
281
+
282
+ self._entity_id_to_trigger[entity_id] = Subscription(entity_id, callback, from_state, to_state)
283
+
284
+ def turn_on(self, entity_id):
285
+ """
286
+ Attempts to turn on a device by guessing the domain from the entity id name
287
+ """
288
+ self.logger.info(f"Turning on {entity_id}")
289
+ split_entity_id = entity_id.split(".")
290
+ if len(split_entity_id) != 2:
291
+ self.logger.error(f"Couldn't get domain from entity_id - is the entity_id correct? {entity_id}")
292
+ else:
293
+ self.call_service(split_entity_id[0], "turn_on", entity_id=entity_id)
294
+
295
+ def turn_off(self, entity_id):
296
+ """
297
+ Attempts to turn off a device by guessing the domain from the entity id name
298
+ """
299
+ self.logger.info(f"Turning off {entity_id}")
300
+ split_entity_id = entity_id.split(".")
301
+ if len(split_entity_id) != 2:
302
+ self.logger.error(f"Couldn't get domain from entity_id - is the entity_id correct? {entity_id}")
303
+ else:
304
+ self.call_service(split_entity_id[0], "turn_off", entity_id=entity_id)
305
+
306
+ def call_service(self, domain, service, entity_id=None, service_data=None):
307
+
308
+ payload = {
309
+ "type": "call_service",
310
+ "domain": domain,
311
+ "service": service,
312
+ }
313
+ if service_data:
314
+ payload["service_data"] = service_data
315
+ if entity_id:
316
+ payload["target"] = {
317
+ "entity_id": entity_id
318
+ }
319
+ return self._send_and_return_message_id(payload, "call_service")
320
+
321
+ def received_message(self, m):
322
+ self.logger.debug("Received message: {}".format(m))
323
+ message_text = m.data.decode(m.encoding)
324
+ message = json.loads(message_text)
325
+ message_type = message.get('type', None)
326
+ if message_type == "auth_required":
327
+ self._do_auth_required()
328
+ elif message_type == "auth_ok":
329
+ self._do_auth_complete()
330
+ elif message_type == "auth_invalid":
331
+ self._do_auth_invalid(message)
332
+ elif message_type == "result":
333
+ self._do_result(message)
334
+ elif message_type == "event":
335
+ self._do_event(message)
336
+ elif message_type == "pong":
337
+ self._do_pong(message)
338
+ else:
339
+ self.logger.warning("Unexpected message: ", message)
340
+
341
+ def _do_auth_required(self):
342
+ self.logger.info("Home Assistant Web Socket Authorisation required")
343
+ payload = {
344
+ 'type': 'auth',
345
+ 'access_token': self.homeassistant_token
346
+ }
347
+ self.logger.debug(f"Sending {payload}")
348
+ self._send(payload)
349
+
350
+ def _do_auth_invalid(self, message):
351
+ self.logger.error("Home Assistant Web Socket Authorisation invalid: {}".format(message))
352
+ self.authenticated = False
353
+ self._authenticated_callback(self.authenticated)
354
+
355
+ def _do_auth_complete(self):
356
+ self.logger.info("Home Assistant Web Socket Authorisation complete")
357
+ self.authenticated = True
358
+ self._authenticated_callback(self.authenticated)
359
+
360
+ def get_states(self, callback):
361
+ payload = {
362
+ 'type': 'get_states'
363
+ }
364
+ message_id = self._send_and_return_message_id(payload, "get_states")
365
+ self.id_to_callback[message_id] = callback
366
+
367
+ # def subscribe_for_updates(self):
368
+ # payload = {
369
+ # "type": "subscribe_events",
370
+ # "event_type": "state_changed"
371
+ # }
372
+ # self._send_with_id(payload, "subscribe")
373
+
374
+ def _do_result(self, message):
375
+ self.logger.debug(self.id_to_type)
376
+ success = message['success']
377
+ if success:
378
+ if 'result' in message:
379
+ message_type = self.id_to_type.pop(message['id'])
380
+ self.logger.debug(f"Got message type {message_type}")
381
+ if message_type == 'subscribe_trigger':
382
+ entity_id = self.id_to_entity_id.get(message['id'])
383
+ self.logger.info(f"Subscribed for {entity_id}")
384
+ elif message_type == 'get_states':
385
+ callback = self.id_to_callback.pop(message['id'])
386
+ if callback is not None:
387
+ callback.set_result(message['result'])
388
+ self.logger.debug(f"Received all states for message id: {message['id']}")
389
+ else:
390
+ self.logger.warning(f"No result in message: {message}")
391
+ else:
392
+ self.logger.error(f"Error code: {message['error']['code']} message: {message['error']['message']}")
393
+
394
+ def _do_event(self, message):
395
+ message_id = message.get('id', -1)
396
+ if message_id in self.id_to_entity_id.keys():
397
+ entity_id = self.id_to_entity_id.get(message['id'])
398
+ self.logger.debug(f"Found entity id {entity_id} in {self.id_to_entity_id}")
399
+ subscription: Subscription = self._entity_id_to_trigger.get(entity_id)
400
+ callback = subscription.callback
401
+ self.logger.debug(f"Found callback {callback} in {self._entity_id_to_trigger}")
402
+ callback(entity_id=entity_id, message=message)
403
+ else:
404
+ self.logger.debug(f"Didn't find message id {message_id} in {self.id_to_entity_id}")
405
+
406
+ def _do_pong(self, message):
407
+ message_id = message['id']
408
+ self.logger.debug(f"Pong received with ID[{message_id}]")
409
+
410
+ def _send_and_return_message_id(self, payload, type_of_call):
411
+ message_id = self._get_next_message_id()
412
+ payload['id'] = message_id
413
+ self.logger.debug(f"Adding {message_id} as type {type_of_call}")
414
+ self.id_to_type[message_id] = type_of_call
415
+ self._send(payload)
416
+ return payload['id']
417
+
418
+ def _get_next_message_id(self):
419
+ return next(self.id_generator)
420
+
421
+ def _send(self, payload):
422
+ json_payload = json.dumps(payload)
423
+ self.logger.debug(f"Sending: {json_payload}")
424
+ self.send(json_payload)
425
+
426
+ def do_nothing(self, *args):
427
+ pass
428
+
429
+
430
+ class Subscription:
431
+ def __init__(self, entity_id, callback, from_state, to_state) -> None:
432
+ self.entity_id = entity_id
433
+ self.callback = callback
434
+ self.from_state = from_state
435
+ self.to_state = to_state
436
+
437
+
438
+ class Callback(ABC):
439
+
440
+ @abc.abstractmethod
441
+ def set_result(self, result):
442
+ pass
443
+
444
+ @abc.abstractmethod
445
+ def get_result(self):
446
+ pass
447
+
448
+
449
+ class BlockingCallback(Callback):
450
+
451
+ def __init__(self, timeout=30):
452
+ self.timeout = timeout
453
+ self.event = threading.Event()
454
+ self.result = None
455
+
456
+ def set_result(self, result):
457
+ self.result = result
458
+ self.event.set()
459
+
460
+ def get_result(self):
461
+ self.event.wait(self.timeout)
462
+ return self.result
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.1
2
+ Name: py-ha-ws-client
3
+ Version: 0.1
4
+ Summary: A Python client to make it easy to connect and consume data from the Home Assistant web socket API.
5
+ Home-page: https://github.com/foxy82/py-ha-ws-client
6
+ Author: foxy82
7
+ Author-email: foxy82.github@gmail.com
8
+ License: Apache 2.0
9
+ Download-URL: https://github.com/foxy82/py-ha-ws-client/archive/0.1.tar.gz
10
+ Keywords: Home Assistant,Websocket
11
+ Platform: UNKNOWN
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Topic :: Software Development :: Build Tools
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+
20
+ # py-ha-ws-client
21
+ A Python client to make it easy to connect and consume data from the [Home Assistant web socket API](https://developers.home-assistant.io/docs/api/websocket/).
22
+
23
+
24
+ ## Example
25
+
26
+ ```
27
+ from time import sleep
28
+ from py_ha_ws_client.client import HomeAssistantWsClient
29
+
30
+ hostname = "<Home Assistant IP>"
31
+ #token = "<from Home Assistant>"
32
+
33
+ client = HomeAssistantWsClient(token, hostname)
34
+ client.connect()
35
+
36
+ while not client.connected():
37
+ sleep(1)
38
+
39
+ # Get all the states as a list
40
+ print("Get all States")
41
+ states = client.get_states()
42
+ print("Print one state as an example")
43
+ print(states[0])
44
+
45
+
46
+ entity_id = "media_player.amplifier"
47
+
48
+ # Define a call back
49
+ def my_callback(entity_id, message):
50
+ print(entity_id, message)
51
+
52
+ # Get the state of a single entity
53
+ state = client.get_state(entity_id)
54
+ print(state)
55
+
56
+ # Register for updates for a specfic entity
57
+ client.subscribe_to_trigger(
58
+ entity_id="media_player.studio_amplifier",
59
+ callback=my_callback,
60
+ )
61
+
62
+ sleep(10)
63
+
64
+ # Send a turn on command
65
+ client.turn_on(
66
+ entity_id=entity_id
67
+ )
68
+
69
+ sleep(10)
70
+
71
+ # Send a change volume command
72
+ client.call_service(
73
+ domain="media_player",
74
+ service="volume_set",
75
+ entity_id=entity_id,
76
+ service_data={
77
+ "volume_level" : "0.50"
78
+ }
79
+ )
80
+
81
+ sleep(10)
82
+
83
+ # Send a turn off command
84
+ client.turn_off(
85
+ entity_id=entity_id
86
+ )
87
+
88
+ sleep(60)
89
+
90
+ ```
91
+
92
+ ## TODO
93
+
94
+ This is a work in progress there are a lot of TODOs in the code.
95
+
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ setup.cfg
4
+ setup.py
5
+ py_ha_ws_client/__init__.py
6
+ py_ha_ws_client/client.py
7
+ py_ha_ws_client.egg-info/PKG-INFO
8
+ py_ha_ws_client.egg-info/SOURCES.txt
9
+ py_ha_ws_client.egg-info/dependency_links.txt
10
+ py_ha_ws_client.egg-info/requires.txt
11
+ py_ha_ws_client.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ ws4py==0.5.1
@@ -0,0 +1 @@
1
+ py_ha_ws_client
@@ -0,0 +1,7 @@
1
+ [metadata]
2
+ description-file = README
3
+
4
+ [egg_info]
5
+ tag_build =
6
+ tag_date = 0
7
+
@@ -0,0 +1,31 @@
1
+ from setuptools import setup
2
+
3
+ version = '0.1'
4
+
5
+ with open("README.md", "rb") as f:
6
+ long_descr = f.read().decode("utf-8")
7
+
8
+ setup(
9
+ name='py_ha_ws_client',
10
+ packages=['py_ha_ws_client'],
11
+ version=version,
12
+ license='Apache 2.0',
13
+ description='A Python client to make it easy to connect and consume data from the Home Assistant web socket API.',
14
+ long_description=long_descr,
15
+ long_description_content_type='text/markdown',
16
+ author='foxy82',
17
+ author_email='foxy82.github@gmail.com',
18
+ url='https://github.com/foxy82/py-ha-ws-client',
19
+ download_url=f'https://github.com/foxy82/py-ha-ws-client/archive/{version}.tar.gz',
20
+ keywords=['Home Assistant', 'Websocket'],
21
+ install_requires=[
22
+ "ws4py==0.5.1"
23
+ ],
24
+ classifiers=[
25
+ 'Development Status :: 4 - Beta',
26
+ 'Intended Audience :: Developers',
27
+ 'Topic :: Software Development :: Build Tools',
28
+ 'License :: OSI Approved :: Apache Software License',
29
+ 'Programming Language :: Python :: 3.10'
30
+ ],
31
+ )