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