HomeAssistant-API 2.4.0.post2__py3-none-any.whl → 3.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- homeassistant_api/__init__.py +17 -10
- homeassistant_api/_async/__init__.py +3 -2
- homeassistant_api/_async/asyncclient.py +206 -209
- homeassistant_api/_async/models/__init__.py +2 -2
- homeassistant_api/_async/models/domains.py +21 -33
- homeassistant_api/_async/models/entity.py +49 -40
- homeassistant_api/_async/models/events.py +19 -18
- homeassistant_api/client.py +5 -268
- homeassistant_api/const.py +2 -0
- homeassistant_api/errors.py +10 -2
- homeassistant_api/mixins.py +53 -0
- homeassistant_api/models/__init__.py +6 -3
- homeassistant_api/models/base.py +9 -25
- homeassistant_api/models/domains.py +47 -53
- homeassistant_api/models/entity.py +59 -47
- homeassistant_api/models/events.py +19 -21
- homeassistant_api/models/history.py +23 -0
- homeassistant_api/models/logbook.py +17 -0
- homeassistant_api/models/states.py +12 -19
- homeassistant_api/processing.py +68 -54
- homeassistant_api/rawapi.py +129 -43
- homeassistant_api/rawclient.py +279 -0
- homeassistant_api-3.0.2.dist-info/LICENSE +674 -0
- homeassistant_api-3.0.2.dist-info/METADATA +68 -0
- homeassistant_api-3.0.2.dist-info/RECORD +26 -0
- {HomeAssistant_API-2.4.0.post2.dist-info → homeassistant_api-3.0.2.dist-info}/WHEEL +1 -2
- HomeAssistant_API-2.4.0.post2.dist-info/LICENSE +0 -21
- HomeAssistant_API-2.4.0.post2.dist-info/METADATA +0 -70
- HomeAssistant_API-2.4.0.post2.dist-info/RECORD +0 -23
- HomeAssistant_API-2.4.0.post2.dist-info/top_level.txt +0 -1
- homeassistant_api/_async/models/states.py +0 -8
homeassistant_api/__init__.py
CHANGED
|
@@ -1,18 +1,25 @@
|
|
|
1
|
-
|
|
2
|
-
from .
|
|
3
|
-
from .
|
|
1
|
+
"""Imports all library stuff for convenience."""
|
|
2
|
+
from ._async import AsyncDomain, AsyncEntity, AsyncEvent, AsyncGroup, AsyncService
|
|
3
|
+
from .client import Client
|
|
4
4
|
from .errors import (
|
|
5
|
+
APIConfigurationError,
|
|
6
|
+
EndpointNotFoundError,
|
|
5
7
|
HomeassistantAPIError,
|
|
6
|
-
RequestError,
|
|
7
8
|
MalformedDataError,
|
|
8
9
|
MalformedInputError,
|
|
9
|
-
|
|
10
|
+
MethodNotAllowedError,
|
|
10
11
|
ParameterMissingError,
|
|
11
|
-
|
|
12
|
+
RequestError,
|
|
12
13
|
UnauthorizedError,
|
|
13
|
-
|
|
14
|
-
MethodNotAllowedError
|
|
14
|
+
UnexpectedStatusCodeError,
|
|
15
15
|
)
|
|
16
|
+
from .models import Domain, Entity, Event, Group, History, Service, State
|
|
17
|
+
from .processing import Processing
|
|
16
18
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
+
Domain.update_forward_refs(**locals())
|
|
20
|
+
Entity.update_forward_refs(**locals())
|
|
21
|
+
Event.update_forward_refs(**locals())
|
|
22
|
+
Group.update_forward_refs(**locals())
|
|
23
|
+
History.update_forward_refs(**locals())
|
|
24
|
+
Service.update_forward_refs(**locals())
|
|
25
|
+
State.update_forward_refs(**locals())
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
from
|
|
2
|
-
from .
|
|
1
|
+
"""Imports objects from the async sub-module for convenience."""
|
|
2
|
+
from .asyncclient import RawAsyncClient
|
|
3
|
+
from .models import AsyncDomain, AsyncEntity, AsyncEvent, AsyncGroup, AsyncService
|
|
@@ -1,283 +1,280 @@
|
|
|
1
|
-
|
|
1
|
+
"""Module for interacting with Home Assistant asyncronously."""
|
|
2
2
|
import asyncio
|
|
3
|
+
from os.path import join
|
|
4
|
+
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union, cast
|
|
3
5
|
|
|
4
|
-
|
|
5
|
-
from
|
|
6
|
-
from datetime import datetime
|
|
7
|
-
|
|
8
|
-
from .models import (
|
|
9
|
-
AsyncDomain,
|
|
10
|
-
AsyncGroup,
|
|
11
|
-
AsyncEntity,
|
|
12
|
-
AsyncState,
|
|
13
|
-
AsyncEvent
|
|
14
|
-
)
|
|
15
|
-
|
|
16
|
-
from ..models import JsonModel
|
|
17
|
-
from ..client import Client, RawClient
|
|
18
|
-
from ..errors import (
|
|
19
|
-
APIConfigurationError,
|
|
20
|
-
RequestError,
|
|
21
|
-
MalformedDataError
|
|
22
|
-
)
|
|
6
|
+
import aiohttp
|
|
7
|
+
from aiohttp_client_cache import CachedSession
|
|
23
8
|
|
|
9
|
+
from ..errors import APIConfigurationError, MalformedDataError, RequestError
|
|
10
|
+
from ..mixins import JsonProcessingMixin
|
|
11
|
+
from ..models import Domain, Event, History, LogbookEntry, State
|
|
24
12
|
from ..processing import Processing
|
|
13
|
+
from ..rawapi import RawWrapper
|
|
14
|
+
from .models import AsyncEntity, AsyncGroup
|
|
25
15
|
|
|
26
16
|
|
|
27
|
-
class
|
|
17
|
+
class RawAsyncClient(RawWrapper, JsonProcessingMixin):
|
|
28
18
|
"""
|
|
29
19
|
The async equivalent of :class:`Client`
|
|
30
20
|
|
|
31
21
|
:param api_url: The location of the api endpoint. e.g. :code:`http://localhost:8123/api` Required.
|
|
32
22
|
:param token: The refresh or long lived access token to authenticate your requests. Required.
|
|
33
23
|
:param global_request_kwargs: A dictionary or dict-like object of kwargs to pass to :func:`requests.request` or :meth:`aiohttp.ClientSession.request`. Optional.
|
|
34
|
-
"""
|
|
35
|
-
|
|
36
|
-
def __init__(self, *args, global_request_kwargs: dict = None, **kwargs):
|
|
37
|
-
super(RawClient, self).__init__(*args, **kwargs)
|
|
38
|
-
if global_request_kwargs:
|
|
39
|
-
self.global_request_kwargs.update(global_request_kwargs)
|
|
24
|
+
""" # pylint: disable=line-too-long
|
|
40
25
|
|
|
41
|
-
|
|
42
|
-
return f'<AsyncClient of "{self.api_url[:20]}">'
|
|
26
|
+
_async_session: Optional[CachedSession] = None
|
|
43
27
|
|
|
44
28
|
async def __aenter__(self):
|
|
45
|
-
|
|
46
|
-
await self.
|
|
29
|
+
self._async_session = CachedSession(expire_after=30)
|
|
30
|
+
await self._async_session.__aenter__()
|
|
31
|
+
await self.async_check_api_running()
|
|
47
32
|
return self
|
|
48
33
|
|
|
49
|
-
async def __aexit__(self, cls, obj,
|
|
50
|
-
|
|
34
|
+
async def __aexit__(self, cls, obj, traceback):
|
|
35
|
+
await self._async_session.__aexit__(cls, obj, traceback)
|
|
51
36
|
|
|
52
37
|
# Very important request function
|
|
53
|
-
async def
|
|
38
|
+
async def async_request(
|
|
54
39
|
self,
|
|
55
|
-
path,
|
|
56
|
-
method=
|
|
57
|
-
headers:
|
|
58
|
-
**kwargs
|
|
59
|
-
) -> Union[
|
|
40
|
+
path: str,
|
|
41
|
+
method: str = "GET",
|
|
42
|
+
headers: Optional[Dict[str, str]] = None,
|
|
43
|
+
**kwargs,
|
|
44
|
+
) -> Union[Dict[str, Any], List[Dict[str, Any]], str]:
|
|
60
45
|
"""Base method for making requests to the api"""
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
headers=headers,
|
|
73
|
-
**kwargs,
|
|
74
|
-
**self.global_request_kwargs
|
|
46
|
+
try:
|
|
47
|
+
if self.global_request_kwargs is not None:
|
|
48
|
+
kwargs.update(self.global_request_kwargs)
|
|
49
|
+
if self._async_session is not None:
|
|
50
|
+
return await self.async_response_logic(
|
|
51
|
+
await self._async_session.request(
|
|
52
|
+
method,
|
|
53
|
+
self.endpoint(path),
|
|
54
|
+
headers=self.prepare_headers(headers),
|
|
55
|
+
**kwargs,
|
|
56
|
+
)
|
|
75
57
|
)
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
"""Constructs State model from json data"""
|
|
93
|
-
return AsyncState(**json)
|
|
94
|
-
|
|
95
|
-
def process_event_json(self, json: dict) -> AsyncEvent:
|
|
96
|
-
"""Constructs Event model from json data"""
|
|
97
|
-
return AsyncEvent(**json, client=self)
|
|
58
|
+
async with aiohttp.request(
|
|
59
|
+
method,
|
|
60
|
+
self.endpoint(path),
|
|
61
|
+
headers=self.prepare_headers(headers),
|
|
62
|
+
**kwargs,
|
|
63
|
+
) as resp:
|
|
64
|
+
return await self.async_response_logic(resp)
|
|
65
|
+
except asyncio.exceptions.TimeoutError as err:
|
|
66
|
+
raise RequestError(
|
|
67
|
+
f'Home Assistant did not respond in time (timeout: {kwargs.get("timeout", 300)} sec)'
|
|
68
|
+
) from err
|
|
69
|
+
|
|
70
|
+
@staticmethod
|
|
71
|
+
async def async_response_logic(response):
|
|
72
|
+
"""Processes custom mimetype content asyncronously."""
|
|
73
|
+
return await Processing(response=response).process()
|
|
98
74
|
|
|
99
75
|
# API information methods
|
|
100
|
-
async def
|
|
76
|
+
async def async_api_error_log(self) -> str:
|
|
101
77
|
"""Returns the server error log as a string"""
|
|
102
|
-
return await self.
|
|
78
|
+
return cast(str, await self.async_request("error_log"))
|
|
103
79
|
|
|
104
|
-
async def
|
|
80
|
+
async def async_api_config(self) -> Dict[str, Any]:
|
|
105
81
|
"""Returns the yaml configuration of homeassistant"""
|
|
106
|
-
return await self.
|
|
82
|
+
return cast(Dict[str, Any], await self.async_request("config"))
|
|
107
83
|
|
|
108
|
-
async def
|
|
84
|
+
async def async_logbook_entries(
|
|
109
85
|
self,
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
86
|
+
*args,
|
|
87
|
+
**kwargs,
|
|
88
|
+
) -> AsyncGenerator[LogbookEntry, None]:
|
|
89
|
+
"""Returns a list of logbook entries from homeassistant."""
|
|
90
|
+
params, url = self.prepare_get_logbook_entry_params(*args, **kwargs)
|
|
91
|
+
data = await self.async_request(url, params=params)
|
|
92
|
+
for entry in data:
|
|
93
|
+
yield LogbookEntry.parse_obj(entry)
|
|
94
|
+
|
|
95
|
+
async def async_get_entity_histories(
|
|
117
96
|
self,
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
97
|
+
*args,
|
|
98
|
+
**kwargs,
|
|
99
|
+
) -> AsyncGenerator[History, None]:
|
|
100
|
+
"""
|
|
101
|
+
Returns a generator of entity state histories from homeassistant.
|
|
102
|
+
"""
|
|
103
|
+
params, url = self.prepare_get_entity_histories_params(*args, **kwargs)
|
|
104
|
+
data = await self.async_request(
|
|
105
|
+
url,
|
|
106
|
+
params=self.construct_params(params),
|
|
107
|
+
)
|
|
108
|
+
for states in data:
|
|
109
|
+
yield History.parse_obj({"states": states})
|
|
110
|
+
|
|
111
|
+
async def async_get_rendered_template(self, template: str):
|
|
112
|
+
"""Renders a given Jinja2 template string with Home Assistant context data."""
|
|
113
|
+
return await self.async_request(
|
|
114
|
+
"template",
|
|
115
|
+
json=dict(template=template),
|
|
116
|
+
return_text=True,
|
|
117
|
+
method="POST",
|
|
130
118
|
)
|
|
131
119
|
|
|
132
|
-
async def
|
|
133
|
-
return await self.request('template', json=dict(template=template), return_text=True, method='POST')
|
|
134
|
-
|
|
135
|
-
async def get_discovery_info(self) -> dict:
|
|
120
|
+
async def async_get_discovery_info(self) -> Dict[str, Any]:
|
|
136
121
|
"""Returns a dictionary of discovery info such as internal_url and version"""
|
|
137
|
-
return await self.
|
|
122
|
+
return cast(Dict[str, Any], await self.async_request("discovery_info"))
|
|
138
123
|
|
|
139
124
|
# API check methods
|
|
140
|
-
async def
|
|
141
|
-
"""Asks
|
|
142
|
-
res = await self.
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
125
|
+
async def async_check_api_config(self) -> bool:
|
|
126
|
+
"""Asks Home Assistant to validate its configuration file"""
|
|
127
|
+
res = await self.async_request("config/core/check_config", method="POST")
|
|
128
|
+
res = cast(Dict[Any, Any], res)
|
|
129
|
+
valid = {"valid": True, "invalid": False}.get(
|
|
130
|
+
cast(
|
|
131
|
+
str,
|
|
132
|
+
res["result"],
|
|
133
|
+
),
|
|
134
|
+
False,
|
|
135
|
+
)
|
|
136
|
+
if valid is False:
|
|
137
|
+
raise APIConfigurationError(res["errors"])
|
|
146
138
|
return valid
|
|
147
139
|
|
|
148
|
-
async def
|
|
149
|
-
"""Asks
|
|
150
|
-
res = await self.
|
|
151
|
-
if res.get(
|
|
140
|
+
async def async_check_api_running(self) -> bool:
|
|
141
|
+
"""Asks Home Assistant if its running"""
|
|
142
|
+
res = cast(Dict[Any, Any], await self.async_request(""))
|
|
143
|
+
if res.get("message", None) == "API running.":
|
|
152
144
|
return True
|
|
153
|
-
|
|
154
|
-
raise MalformedDataError('Server response did not return message attribute')
|
|
155
|
-
|
|
156
|
-
async def malformed_id(self, entity_id: str) -> bool:
|
|
157
|
-
"""Checks whether or not a given entity_id is formatted correctly"""
|
|
158
|
-
checks = [
|
|
159
|
-
' ' in entity_id,
|
|
160
|
-
'.' not in entity_id,
|
|
161
|
-
'-' in entity_id,
|
|
162
|
-
entity_id.lower() == entity_id
|
|
163
|
-
]
|
|
164
|
-
return True in checks
|
|
145
|
+
raise MalformedDataError("Server response did not return message attribute")
|
|
165
146
|
|
|
166
147
|
# Entity methods
|
|
167
|
-
async def
|
|
148
|
+
async def async_get_entities(self) -> Tuple[AsyncGroup, ...]:
|
|
168
149
|
"""Fetches all entities from the api"""
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
return cls[group_id]
|
|
175
|
-
entities = GroupDict()
|
|
176
|
-
for state in await self.get_states():
|
|
177
|
-
group_id, entity_slug = state.entity_id.split('.')
|
|
150
|
+
entities: Dict[str, AsyncGroup] = {}
|
|
151
|
+
for state in await self.async_get_states():
|
|
152
|
+
group_id, entity_slug = state.entity_id.split(".")
|
|
153
|
+
if group_id not in entities:
|
|
154
|
+
entities[group_id] = AsyncGroup(group_id=group_id, client=self)
|
|
178
155
|
entities[group_id].add_entity(entity_slug, state)
|
|
179
|
-
return
|
|
156
|
+
return tuple(entities.values())
|
|
180
157
|
|
|
181
|
-
async def
|
|
158
|
+
async def async_get_entity(
|
|
182
159
|
self,
|
|
183
160
|
group_id: str = None,
|
|
184
161
|
entity_slug: str = None,
|
|
185
|
-
entity_id: str = None
|
|
186
|
-
) -> AsyncEntity:
|
|
162
|
+
entity_id: str = None,
|
|
163
|
+
) -> Optional[AsyncEntity]:
|
|
187
164
|
"""Returns a Entity model for an entity_id"""
|
|
188
165
|
if group_id is not None and entity_slug is not None:
|
|
189
|
-
state = await self.
|
|
166
|
+
state = await self.async_get_state(group=group_id, slug=entity_slug)
|
|
190
167
|
elif entity_id is not None:
|
|
191
|
-
state = await self.
|
|
168
|
+
state = await self.async_get_state(entity_id=entity_id)
|
|
192
169
|
else:
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
)
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
170
|
+
help_msg = (
|
|
171
|
+
"Use keyword arguments to pass entity_id. "
|
|
172
|
+
"Or you can pass the entity_group and entity_slug instead."
|
|
173
|
+
)
|
|
174
|
+
raise ValueError(
|
|
175
|
+
f"Neither group and slug or entity_id provided. {help_msg}"
|
|
176
|
+
)
|
|
177
|
+
group_id, entity_slug = state.entity_id.split(".")
|
|
178
|
+
group = AsyncGroup(group_id=cast(str, group_id), client=self)
|
|
179
|
+
group.add_entity(cast(str, entity_slug), state)
|
|
180
|
+
return group.get_entity(cast(str, entity_slug))
|
|
201
181
|
|
|
202
182
|
# Services and domain methods
|
|
203
|
-
async def
|
|
183
|
+
async def async_get_domains(self) -> Tuple[Domain, ...]:
|
|
204
184
|
"""Fetches all Services from the api"""
|
|
205
|
-
|
|
206
|
-
services =
|
|
207
|
-
|
|
208
|
-
|
|
185
|
+
data = await self.async_request("services")
|
|
186
|
+
services = map(
|
|
187
|
+
self.process_services_json,
|
|
188
|
+
cast(Tuple[Dict[str, Any], ...], data),
|
|
189
|
+
)
|
|
190
|
+
return tuple(services)
|
|
209
191
|
|
|
210
|
-
async def
|
|
192
|
+
async def async_trigger_service(
|
|
211
193
|
self,
|
|
212
194
|
domain: str,
|
|
213
195
|
service: str,
|
|
214
|
-
**service_data
|
|
215
|
-
) -> List[
|
|
216
|
-
"""Tells
|
|
217
|
-
data = await self.
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
service
|
|
222
|
-
),
|
|
223
|
-
method='POST',
|
|
224
|
-
json=service_data
|
|
196
|
+
**service_data,
|
|
197
|
+
) -> List[State]:
|
|
198
|
+
"""Tells Home Assistant to trigger a service, returns stats changed while being called"""
|
|
199
|
+
data = await self.async_request(
|
|
200
|
+
join("services", domain, service),
|
|
201
|
+
method="POST",
|
|
202
|
+
json=service_data,
|
|
225
203
|
)
|
|
226
204
|
return [
|
|
227
205
|
self.process_state_json(state_data)
|
|
228
|
-
for state_data in data
|
|
206
|
+
for state_data in cast(List[Dict[Any, Any]], data)
|
|
229
207
|
]
|
|
230
208
|
|
|
231
209
|
# EntityState methods
|
|
232
|
-
async def
|
|
210
|
+
async def async_get_state( # pylint: disable=duplicate-code
|
|
211
|
+
self,
|
|
212
|
+
*,
|
|
213
|
+
entity_id: Optional[str] = None,
|
|
214
|
+
group: Optional[str] = None,
|
|
215
|
+
slug: Optional[str] = None,
|
|
216
|
+
) -> State:
|
|
233
217
|
"""Fetches the state of the entity specified"""
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
218
|
+
target_entity_id = self.prepare_entity_id(
|
|
219
|
+
group=group,
|
|
220
|
+
slug=slug,
|
|
221
|
+
entity_id=entity_id,
|
|
222
|
+
)
|
|
223
|
+
data = await self.async_request(join("states", target_entity_id))
|
|
224
|
+
return self.process_state_json(cast(Dict[Any, Any], data))
|
|
240
225
|
|
|
241
|
-
async def
|
|
226
|
+
async def async_set_state( # pylint: disable=duplicate-code
|
|
227
|
+
self,
|
|
228
|
+
state: str,
|
|
229
|
+
*,
|
|
230
|
+
entity_id: Optional[str] = None,
|
|
231
|
+
group: Optional[str] = None,
|
|
232
|
+
slug: Optional[str] = None,
|
|
233
|
+
**payload,
|
|
234
|
+
) -> State:
|
|
242
235
|
"""Sets the state of the entity given (does not have to be a real entity) and returns the updated state"""
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
elif entity_id is None:
|
|
249
|
-
raise ValueError('Neither group and slug or entity_id provided.')
|
|
250
|
-
if state is None:
|
|
251
|
-
raise ValueError('required parameter "state" is missing')
|
|
236
|
+
target_entity_id = self.prepare_entity_id(
|
|
237
|
+
group=group,
|
|
238
|
+
slug=slug,
|
|
239
|
+
entity_id=entity_id,
|
|
240
|
+
)
|
|
252
241
|
payload.update(state=state)
|
|
253
|
-
data = await self.
|
|
254
|
-
|
|
255
|
-
method=
|
|
256
|
-
json=payload
|
|
242
|
+
data = await self.async_request(
|
|
243
|
+
join("states", target_entity_id),
|
|
244
|
+
method="POST",
|
|
245
|
+
json=payload,
|
|
257
246
|
)
|
|
258
|
-
return self.process_state_json(data)
|
|
247
|
+
return self.process_state_json(cast(Dict[Any, Any], data))
|
|
259
248
|
|
|
260
|
-
async def
|
|
261
|
-
"""Gets the states of all
|
|
262
|
-
data = await self.
|
|
263
|
-
return [
|
|
249
|
+
async def async_get_states(self) -> List[State]:
|
|
250
|
+
"""Gets the states of all entities within homeassistant"""
|
|
251
|
+
data = await self.async_request("states")
|
|
252
|
+
return [
|
|
253
|
+
self.process_state_json(state_data)
|
|
254
|
+
for state_data in cast(List[Dict[Any, Any]], data)
|
|
255
|
+
]
|
|
264
256
|
|
|
265
257
|
# Event methods
|
|
266
|
-
async def
|
|
258
|
+
async def async_get_events(self) -> Tuple[Event, ...]:
|
|
267
259
|
"""Gets the Events that happen within homeassistant"""
|
|
268
|
-
data = await self.
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
260
|
+
data = await self.async_request("events")
|
|
261
|
+
if not isinstance(data, list):
|
|
262
|
+
events = map(
|
|
263
|
+
self.process_event_json,
|
|
264
|
+
cast(List[Dict[Any, Any]], data),
|
|
265
|
+
)
|
|
266
|
+
return tuple(events)
|
|
267
|
+
raise TypeError("Received JSON data is not a list of events.")
|
|
268
|
+
|
|
269
|
+
async def async_fire_event(self, event_type: str, **event_data) -> str:
|
|
274
270
|
"""Fires a given event_type within homeassistant. Must be an existing event_type."""
|
|
275
|
-
data = await self.
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
),
|
|
280
|
-
method='POST',
|
|
281
|
-
json=event_data
|
|
271
|
+
data = await self.async_request(
|
|
272
|
+
join("events", event_type),
|
|
273
|
+
method="POST",
|
|
274
|
+
json=event_data,
|
|
282
275
|
)
|
|
283
|
-
|
|
276
|
+
if not isinstance(data, dict):
|
|
277
|
+
raise TypeError(
|
|
278
|
+
f"Invalid return type from API. Expected {dict!r} got {type(data)!r}"
|
|
279
|
+
)
|
|
280
|
+
return data.get("message", "No message provided")
|
|
@@ -1,29 +1,24 @@
|
|
|
1
1
|
"""File for Service and Domain data models"""
|
|
2
2
|
|
|
3
|
-
from
|
|
4
|
-
from typing import List
|
|
3
|
+
from typing import Any, Dict, Tuple, cast
|
|
5
4
|
|
|
6
|
-
from ...models import Domain, Service
|
|
7
|
-
from .states import AsyncState
|
|
5
|
+
from ...models import Domain, Service, State
|
|
8
6
|
|
|
9
7
|
|
|
10
8
|
class AsyncDomain(Domain):
|
|
11
9
|
"""A class representing the domain that services belong to."""
|
|
12
10
|
|
|
13
|
-
async def __new__(cls):
|
|
14
|
-
return cls
|
|
15
|
-
|
|
16
|
-
async def __init__(*args, **kwargs):
|
|
17
|
-
super().__init__(*args, **kwargs)
|
|
18
|
-
|
|
19
|
-
def __repr__(self):
|
|
20
|
-
return f'<AsyncDomain {self.domain_id}>'
|
|
21
|
-
|
|
22
11
|
def add_service(self, service_id: str, **data) -> None:
|
|
23
12
|
"""Registers services into a domain to be used or accessed"""
|
|
24
|
-
self.services.update(
|
|
25
|
-
|
|
26
|
-
|
|
13
|
+
self.services.update(
|
|
14
|
+
{
|
|
15
|
+
service_id: AsyncService(
|
|
16
|
+
service_id=service_id,
|
|
17
|
+
client=self,
|
|
18
|
+
**data,
|
|
19
|
+
)
|
|
20
|
+
}
|
|
21
|
+
)
|
|
27
22
|
|
|
28
23
|
def get_service(self, service_id: str):
|
|
29
24
|
"""Return a Service with the given service_id, returns None if no such service exists"""
|
|
@@ -33,22 +28,15 @@ class AsyncDomain(Domain):
|
|
|
33
28
|
class AsyncService(Service):
|
|
34
29
|
"""Class representing services from homeassistant"""
|
|
35
30
|
|
|
36
|
-
def
|
|
37
|
-
return f'<AsyncService {self.id} domain="{self.domain.domain_id}">'
|
|
38
|
-
|
|
39
|
-
async def trigger(self, **service_data) -> List[AsyncState]:
|
|
31
|
+
async def async_trigger(self, **service_data) -> Tuple[State, ...]:
|
|
40
32
|
"""Triggers the service associated with this object."""
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
json=service_data
|
|
33
|
+
data = await self.domain.client.async_trigger_service(
|
|
34
|
+
self.domain.domain_id,
|
|
35
|
+
self.service_id,
|
|
36
|
+
**service_data,
|
|
37
|
+
)
|
|
38
|
+
states = map(
|
|
39
|
+
self.domain.client.process_state_json,
|
|
40
|
+
cast(Tuple[Dict[str, Any]], data),
|
|
50
41
|
)
|
|
51
|
-
return
|
|
52
|
-
self.domain.client.process_state_json(state_data)
|
|
53
|
-
for state_data in data
|
|
54
|
-
]
|
|
42
|
+
return tuple(states)
|