HomeAssistant-API 2.4.0.post1__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.
@@ -1,7 +1,25 @@
1
- from .client import Client, RawClient
2
- from .models import Group, Entity, Domain, Service, State, Event
1
+ """Imports all library stuff for convenience."""
2
+ from ._async import AsyncDomain, AsyncEntity, AsyncEvent, AsyncGroup, AsyncService
3
+ from .client import Client
4
+ from .errors import (
5
+ APIConfigurationError,
6
+ EndpointNotFoundError,
7
+ HomeassistantAPIError,
8
+ MalformedDataError,
9
+ MalformedInputError,
10
+ MethodNotAllowedError,
11
+ ParameterMissingError,
12
+ RequestError,
13
+ UnauthorizedError,
14
+ UnexpectedStatusCodeError,
15
+ )
16
+ from .models import Domain, Entity, Event, Group, History, Service, State
3
17
  from .processing import Processing
4
18
 
5
-
6
- __version__ = '2.4.0.post1'
7
- __name__ = 'Homeassistant API'
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 .asyncclient import AsyncClient
2
- from .models import AsyncDomain, AsyncService, AsyncGroup, AsyncEntity, AsyncState, AsyncEvent
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
- import aiohttp
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
- 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
- )
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 AsyncClient(Client):
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
- def __repr__(self) -> str:
42
- return f'<AsyncClient of "{self.api_url[:20]}">'
28
+ _async_session: Optional[CachedSession] = None
43
29
 
44
30
  async def __aenter__(self):
45
- await self.check_api_running()
46
- await self.check_api_config()
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, tb):
50
- pass
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 request(
40
+ async def async_request(
54
41
  self,
55
- path,
56
- method='GET',
57
- headers: dict = None,
58
- **kwargs
59
- ) -> Union[dict, list, str]:
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
- if headers is None:
62
- headers = {}
63
- if isinstance(headers, dict):
64
- headers.update(self._headers)
65
- else:
66
- raise ValueError(f'headers must be dict or dict subclass, not type {type(headers).__name__!r}')
67
- async with aiohttp.ClientSession() as session:
68
- try:
69
- resp = await session.request(
70
- method,
71
- self.endpoint(path),
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
- except asyncio.exceptions.TimeoutError:
77
- raise RequestError(f'Homeassistant did not respond in time (timeout: {kwargs.get("timeout", 300)} sec)')
78
- return await self.response_logic(resp)
79
-
80
- async def response_logic(self, response):
81
- return await Processing(response).process(_async=True)
82
-
83
- # Response processing methods
84
- def process_services_json(self, json: dict) -> AsyncDomain:
85
- """Constructs Domain and Service models from json data"""
86
- domain = AsyncDomain(json.get('domain'), self)
87
- for service_id, data in json.get('services').items():
88
- domain.add_service(service_id, **data)
89
- return domain
90
-
91
- def process_state_json(self, json: dict) -> AsyncState:
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 api_error_log(self) -> str:
78
+ async def async_api_error_log(self) -> str:
101
79
  """Returns the server error log as a string"""
102
- return await self.request('error_log', return_text=True)
80
+ return cast(str, await self.async_request("error_log"))
103
81
 
104
- async def api_config(self) -> dict:
82
+ async def async_api_config(self) -> Dict[str, Any]:
105
83
  """Returns the yaml configuration of homeassistant"""
106
- return await self.request('config')
84
+ return cast(Dict[str, Any], await self.async_request("config"))
107
85
 
108
- async def logbook_entries(
86
+ async def async_logbook_entries(
109
87
  self,
110
88
  filter_entity: AsyncEntity = None,
111
- timestamp: Union[str, datetime] = None, # Defaults to 1 day before
112
- end_timestamp: Union[str, datetime] = None
113
- ) -> dict:
114
- return await super().logbook_entries(filter_entity, timestamp, end_timestamp)
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 get_history(
111
+ async def async_get_entity_histories(
117
112
  self,
118
- entities: Tuple[AsyncEntity] = None,
119
- timestamp: datetime = None, # Defaults to 1 day before
120
- end_timestamp: datetime = None,
121
- minimal_state_data=False,
122
- significant_changes_only=False
123
- ) -> Union[dict, list, str]:
124
- return await super().get_history(
125
- entities,
126
- timestamp,
127
- end_timestamp,
128
- minimal_state_data,
129
- significant_changes_only
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 get_rendered_template(self, template: str):
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.request('discovery_info')
138
+ return cast(Dict[str, Any], await self.async_request("discovery_info"))
138
139
 
139
140
  # API check methods
140
- async def check_api_config(self) -> True:
141
- """Asks homeassistant to validate its configuration file"""
142
- res = await self.request('config/core/check_config', method='POST')
143
- valid = {'valid': True, 'invalid': False}.get(res['result'], None)
144
- if not valid:
145
- raise APIConfigurationError(res['errors'])
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 check_api_running(self) -> True:
149
- """Asks homeassistant if its running"""
150
- res = await self.request('')
151
- if res.get('message', None) == 'API running.':
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
- else:
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 get_entities(self) -> JsonModel:
164
+ async def async_get_entities(self) -> Tuple[AsyncGroup, ...]:
168
165
  """Fetches all entities from the api"""
169
- class GroupDict(dict):
170
- """dict subclass for constructing dynamic default Group models"""
171
- def __missing__(cls, group_id: str):
172
- """Allows for dynamic default values in a dictionary"""
173
- cls[group_id] = AsyncGroup(group_id, self)
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 JsonModel(entities)
172
+ return tuple(entities.values())
180
173
 
181
- async def get_entity(
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.get_state(group=group_id, slug=entity_slug)
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.get_state(entity_id=entity_id)
184
+ state = await self.async_get_state(entity_id=entity_id)
192
185
  else:
193
- raise ValueError('Neither group and slug or entity_id provided. {help_msg}'.format(
194
- help_msg='Use keyword arguments to pass entity_id. Or you can pass the entity_group and entity_slug '
195
- 'instead '
196
- ))
197
- group_id, entity_slug = state.entity_id.split('.')
198
- group = AsyncGroup(group_id, self)
199
- group.add_entity(entity_slug, state)
200
- return group.get_entity(entity_slug)
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 get_domains(self) -> JsonModel:
199
+ async def async_get_domains(self) -> Tuple[Domain, ...]:
204
200
  """Fetches all Services from the api"""
205
- services = await self.request('services')
206
- services = [self.process_services_json(data) for data in services]
207
- services = {service.domain_id: service for service in services}
208
- return JsonModel(services)
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 trigger_service(
208
+ async def async_trigger_service(
211
209
  self,
212
210
  domain: str,
213
211
  service: str,
214
- **service_data
215
- ) -> List[AsyncState]:
216
- """Tells homeassistant to trigger a service, returns stats changed while being called"""
217
- data = await self.request(
218
- path(
219
- 'services',
220
- domain,
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 get_state(self, entity_id: str = None, group: str = None, slug: str = None) -> AsyncState:
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
- if group is not None and slug is not None:
235
- entity_id = group + '.' + slug
236
- elif entity_id is None:
237
- raise ValueError('Neither group and slug or entity_id provided.')
238
- data = await self.request(path('states', entity_id))
239
- return self.process_state_json(data)
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 set_state(self, entity_id: str = None, state: str = None, group: str = None, slug: str = None, **payload) -> AsyncState:
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
- if group is None or slug is None:
244
- raise ValueError('To use group or slug you need to pass both not just one.'
245
- 'Make sure you are using keyword arguments.')
246
- if group is not None and slug is not None:
247
- entity_id = group + '.' + slug
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.request(
254
- path('states', entity_id),
255
- method='POST',
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 get_states(self) -> List[AsyncState]:
261
- """Gets the states of all entitites within homeassistant"""
262
- data = await self.request('states')
263
- return [self.process_state_json(state_data) for state_data in data]
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 get_events(self) -> JsonModel:
274
+ async def async_get_events(self) -> Tuple[Event, ...]:
267
275
  """Gets the Events that happen within homeassistant"""
268
- data = await self.request('events')
269
- events = [self.process_event_json(event_info) for event_info in data]
270
- events = {evt.event_type: evt for evt in events}
271
- return JsonModel(events)
272
-
273
- async def fire_event(self, event_type: str, **event_data) -> str:
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.request(
276
- path(
277
- 'events',
278
- event_type
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
- return data.get('message', 'No message provided')
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,4 +1,4 @@
1
+ """The async Models for the entire library."""
1
2
  from .domains import AsyncDomain, AsyncService
2
- from .entity import AsyncGroup, AsyncEntity
3
- from .states import AsyncState
3
+ from .entity import AsyncEntity, AsyncGroup
4
4
  from .events import AsyncEvent
@@ -1,29 +1,24 @@
1
1
  """File for Service and Domain data models"""
2
2
 
3
- from os.path import join as path
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
- service_id: AsyncService(service_id, self, **data)
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 __repr__(self):
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
- data = await self.domain.client.request(
43
- path(
44
- 'services',
45
- self.domain.domain_id,
46
- self.id
47
- ),
48
- method='POST',
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)