HomeAssistant-API 3.0.3.post4__py3-none-any.whl → 3.0.4__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,6 +1,7 @@
1
1
  """Module for interacting with Home Assistant asyncronously."""
2
2
  import asyncio
3
3
  import logging
4
+ from datetime import datetime
4
5
  from posixpath import join
5
6
  from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union, cast
6
7
 
@@ -100,13 +101,23 @@ class RawAsyncClient(RawWrapper, JsonProcessingMixin):
100
101
 
101
102
  async def async_get_entity_histories(
102
103
  self,
103
- *args,
104
- **kwargs,
104
+ entities: Optional[Tuple[AsyncEntity, ...]] = None,
105
+ start_timestamp: Optional[datetime] = None,
106
+ # Defaults to 1 day before. https://developers.home-assistant.io/docs/api/rest/
107
+ end_timestamp: Optional[datetime] = None,
108
+ minimal_state_data: bool = False,
109
+ significant_changes_only: bool = False,
105
110
  ) -> AsyncGenerator[History, None]:
106
111
  """
107
112
  Returns a generator of entity state histories from homeassistant.
108
113
  """
109
- params, url = self.prepare_get_entity_histories_params(*args, **kwargs)
114
+ params, url = self.prepare_get_entity_histories_params(
115
+ entities=entities,
116
+ start_timestamp=start_timestamp,
117
+ end_timestamp=end_timestamp,
118
+ minimal_state_data=minimal_state_data,
119
+ significant_changes_only=significant_changes_only,
120
+ )
110
121
  data = await self.async_request(
111
122
  url,
112
123
  params=self.construct_params(params),
@@ -195,6 +206,14 @@ class RawAsyncClient(RawWrapper, JsonProcessingMixin):
195
206
  )
196
207
  return tuple(services)
197
208
 
209
+ async def async_get_domain(self, domain_id: str) -> Optional[Domain]:
210
+ """Fetchers all services under a particular domain."""
211
+ domains = await self.async_get_domains()
212
+ for domain in domains:
213
+ if domain.domain_id == domain_id:
214
+ return domain
215
+ return None
216
+
198
217
  async def async_trigger_service(
199
218
  self,
200
219
  domain: str,
@@ -2,16 +2,15 @@
2
2
 
3
3
  from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, cast
4
4
 
5
- from pydantic import BaseModel, Field
5
+ from pydantic import Field, validator
6
6
 
7
- from ...models import State
8
- from ...models.domains import ServiceField
7
+ from ...models import ServiceField, State, base
9
8
 
10
9
  if TYPE_CHECKING:
11
10
  from homeassistant_api import Client
12
11
 
13
12
 
14
- class AsyncDomain(BaseModel):
13
+ class AsyncDomain(base.BaseModel):
15
14
  """A class representing the domain that services belong to."""
16
15
 
17
16
  domain_id: str
@@ -30,7 +29,7 @@ class AsyncDomain(BaseModel):
30
29
  }
31
30
  )
32
31
 
33
- def get_service(self, service_id: str):
32
+ def get_service(self, service_id: str) -> Optional["AsyncService"]:
34
33
  """Return a Service with the given service_id, returns None if no such service exists"""
35
34
  return self.services.get(service_id)
36
35
 
@@ -43,16 +42,25 @@ class AsyncDomain(BaseModel):
43
42
  return super().__getattribute__(attr)
44
43
 
45
44
 
46
- class AsyncService(BaseModel):
45
+ class AsyncService(base.BaseModel):
47
46
  """Class representing services from homeassistant"""
48
47
 
49
48
  service_id: str
50
- domain: AsyncDomain
49
+ domain: AsyncDomain = Field(exlude=True, repr=False)
51
50
  name: Optional[str] = None
52
51
  description: Optional[str] = None
53
52
  fields: Optional[Dict[str, ServiceField]] = None
54
53
  target: Optional[Dict[str, dict]] = None
55
54
 
55
+ @classmethod
56
+ @validator("domain")
57
+ def validate_domain(cls, domain: AsyncDomain) -> AsyncDomain:
58
+ """
59
+ Explicitly do nothing to validate the parent domain.
60
+ Elimintates recursive validation errors.
61
+ """
62
+ return domain
63
+
56
64
  async def async_trigger(self, **service_data) -> Tuple[State, ...]:
57
65
  """Triggers the service associated with this object."""
58
66
  data = await self.domain.client.async_trigger_service(
@@ -1,4 +1,5 @@
1
1
  """Module for Entity and entity Group data models"""
2
+ from datetime import datetime
2
3
  from posixpath import join
3
4
  from typing import TYPE_CHECKING, Any, Dict, Optional, cast
4
5
 
@@ -33,7 +34,7 @@ class AsyncEntity(BaseModel):
33
34
 
34
35
  slug: str
35
36
  state: State
36
- group: AsyncGroup
37
+ group: AsyncGroup = Field(exclude=True, repr=False)
37
38
 
38
39
  async def async_get_state(self) -> State:
39
40
  """Asks Home Assistant for the state of the entity and sets it locally"""
@@ -59,13 +60,22 @@ class AsyncEntity(BaseModel):
59
60
  """Constructs the entity_id string from its group and slug"""
60
61
  return self.group.group_id + "." + self.slug
61
62
 
62
- async def async_get_history(self, *args, **kwargs) -> Optional[History]:
63
+ async def async_get_history(
64
+ self,
65
+ start_timestamp: Optional[datetime] = None,
66
+ # Defaults to 1 day before. https://developers.home-assistant.io/docs/api/rest/
67
+ end_timestamp: Optional[datetime] = None,
68
+ minimal_state_data: bool = False,
69
+ significant_changes_only: bool = False,
70
+ ) -> Optional[History]:
63
71
  """Gets the previous `State`'s of the `Entity`."""
64
72
  history: Optional[History] = None
65
73
  async for history in self.group.client.async_get_entity_histories(
66
74
  entities=(self,),
67
- *args,
68
- **kwargs,
75
+ start_timestamp=start_timestamp,
76
+ end_timestamp=end_timestamp,
77
+ minimal_state_data=minimal_state_data,
78
+ significant_changes_only=significant_changes_only,
69
79
  ):
70
80
  break
71
81
  return history
@@ -1,6 +1,6 @@
1
1
  """The Model objects for the entire library."""
2
2
  from .base import BaseModel
3
- from .domains import Domain, Service
3
+ from .domains import Domain, Service, ServiceField
4
4
  from .entity import Entity, Group
5
5
  from .events import Event
6
6
  from .history import History
@@ -10,6 +10,10 @@ from .states import State
10
10
  __all__ = (
11
11
  "Domain",
12
12
  "Service",
13
+ "BaseModel",
14
+ "Domain",
15
+ "Service",
16
+ "ServiceField",
13
17
  "Entity",
14
18
  "Group",
15
19
  "Event",
@@ -1,7 +1,7 @@
1
1
  """File for Service and Domain data models"""
2
2
  from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple
3
3
 
4
- from pydantic import Field
4
+ from pydantic import Field, validator
5
5
 
6
6
  from .base import BaseModel
7
7
  from .states import State
@@ -29,7 +29,7 @@ class Domain(BaseModel):
29
29
  }
30
30
  )
31
31
 
32
- def get_service(self, service_id: str):
32
+ def get_service(self, service_id: str) -> Optional["Service"]:
33
33
  """Return a Service with the given service_id, returns None if no such service exists"""
34
34
  return self.services.get(service_id)
35
35
 
@@ -56,12 +56,21 @@ class Service(BaseModel):
56
56
  """Model representing services from homeassistant"""
57
57
 
58
58
  service_id: str
59
- domain: Domain
59
+ domain: Domain = Field(exlucde=True, repr=False)
60
60
  name: Optional[str] = None
61
61
  description: Optional[str] = None
62
62
  fields: Optional[Dict[str, ServiceField]] = None
63
63
  target: Optional[Dict[str, dict]] = None
64
64
 
65
+ @classmethod
66
+ @validator("domain")
67
+ def validate_domain(cls, domain: Domain) -> Domain:
68
+ """
69
+ Explicitly do nothing to validate the parent domain.
70
+ Elimintates recursive validation errors.
71
+ """
72
+ return domain
73
+
65
74
  def trigger(self, **service_data) -> Tuple[State, ...]:
66
75
  """Triggers the service associated with this object."""
67
76
  return self.domain.client.trigger_service(
@@ -1,5 +1,6 @@
1
1
  """Module for Entity and entity Group data models"""
2
2
 
3
+ from datetime import datetime
3
4
  from posixpath import join
4
5
  from typing import TYPE_CHECKING, Any, Dict, Optional, cast
5
6
 
@@ -25,7 +26,7 @@ class Group(BaseModel):
25
26
  self.entities[entity_slug] = Entity(
26
27
  slug=entity_slug,
27
28
  state=state,
28
- client=self.client,
29
+ group=self,
29
30
  )
30
31
 
31
32
  def get_entity(self, entity_slug: str) -> Optional["Entity"]:
@@ -75,13 +76,22 @@ class Entity(BaseModel):
75
76
  """Constructs the entity_id string from its group and slug"""
76
77
  return (self.group.group_id + "." + self.slug).strip()
77
78
 
78
- def get_history(self, *args, **kwargs) -> History:
79
+ def get_history(
80
+ self,
81
+ start_timestamp: Optional[datetime] = None,
82
+ # Defaults to 1 day before. https://developers.home-assistant.io/docs/api/rest/
83
+ end_timestamp: Optional[datetime] = None,
84
+ minimal_state_data: bool = False,
85
+ significant_changes_only: bool = False,
86
+ ) -> History:
79
87
  """Gets the previous `State`'s of the `Entity`"""
80
88
  history = None
81
89
  for history in self.group.client.get_entity_histories(
82
90
  entities=(self,),
83
- *args,
84
- **kwargs,
91
+ start_timestamp=start_timestamp,
92
+ end_timestamp=end_timestamp,
93
+ minimal_state_data=minimal_state_data,
94
+ significant_changes_only=significant_changes_only,
85
95
  ):
86
96
  break
87
97
  return history
@@ -3,11 +3,17 @@
3
3
  import re
4
4
  from datetime import datetime
5
5
  from posixpath import join
6
- from typing import Dict, Optional, Tuple, Union
6
+ from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
7
+ from urllib.parse import quote as url_quote
7
8
 
8
9
  from .const import DATE_FMT
9
10
  from .models import Entity
10
11
 
12
+ if TYPE_CHECKING:
13
+ from ._async.models.entity import AsyncEntity
14
+ else:
15
+ AsyncEntity = None # pylint: disable=invalid-name
16
+
11
17
 
12
18
  class RawWrapper:
13
19
  """Builds, and makes requests to the API"""
@@ -101,7 +107,7 @@ class RawWrapper:
101
107
 
102
108
  @staticmethod
103
109
  def prepare_get_entity_histories_params(
104
- entities: Optional[Tuple[Entity, ...]] = None,
110
+ entities: Optional[Tuple[Union[Entity, AsyncEntity], ...]] = None,
105
111
  start_timestamp: Optional[datetime] = None,
106
112
  # Defaults to 1 day before. https://developers.home-assistant.io/docs/api/rest/
107
113
  end_timestamp: Optional[datetime] = None,
@@ -114,7 +120,7 @@ class RawWrapper:
114
120
  if entities is not None:
115
121
  params["filter_entity_id"] = ",".join([ent.entity_id for ent in entities])
116
122
  if end_timestamp is not None:
117
- params["end_time"] = end_timestamp.strftime(DATE_FMT)
123
+ params["end_time"] = url_quote(end_timestamp.strftime(DATE_FMT))
118
124
  if minimal_state_data:
119
125
  params["minimal_response"] = None
120
126
  if significant_changes_only:
@@ -122,7 +128,7 @@ class RawWrapper:
122
128
  if start_timestamp is not None:
123
129
  if isinstance(start_timestamp, datetime):
124
130
  formatted_timestamp = start_timestamp.strftime(DATE_FMT)
125
- url = join("history/period", formatted_timestamp)
131
+ url = join("history/period/", formatted_timestamp)
126
132
  else:
127
133
  raise TypeError(f"timestamp needs to be of type {datetime!r}")
128
134
  else:
@@ -143,12 +149,12 @@ class RawWrapper:
143
149
  params.update(entity=filter_entity.entity_id)
144
150
  if end_timestamp is not None:
145
151
  if isinstance(end_timestamp, datetime):
146
- end_timestamp = end_timestamp.strftime(DATE_FMT)
152
+ end_timestamp = url_quote(end_timestamp.strftime(DATE_FMT))
147
153
  params.update(end_time=end_timestamp)
148
154
  if start_timestamp is not None:
149
155
  if isinstance(start_timestamp, datetime):
150
156
  formatted_timestamp = start_timestamp.strftime(DATE_FMT)
151
- url = join("logbook", formatted_timestamp)
157
+ url = join("logbook/", formatted_timestamp)
152
158
  else:
153
159
  url = "logbook"
154
160
  return params, url
@@ -1,6 +1,7 @@
1
1
  """Module for all interaction with homeassistant."""
2
2
 
3
3
  import logging
4
+ from datetime import datetime
4
5
  from posixpath import join
5
6
  from typing import Any, Dict, Generator, List, Optional, Tuple, Union, cast
6
7
 
@@ -100,11 +101,25 @@ class RawClient(RawWrapper, JsonProcessingMixin):
100
101
  for entry in data:
101
102
  yield LogbookEntry.parse_obj(entry)
102
103
 
103
- def get_entity_histories(self, *args, **kwargs) -> Generator[History, None, None]:
104
+ def get_entity_histories(
105
+ self,
106
+ entities: Optional[Tuple[Entity, ...]] = None,
107
+ start_timestamp: Optional[datetime] = None,
108
+ # Defaults to 1 day before. https://developers.home-assistant.io/docs/api/rest/
109
+ end_timestamp: Optional[datetime] = None,
110
+ minimal_state_data: bool = False,
111
+ significant_changes_only: bool = False,
112
+ ) -> Generator[History, None, None]:
104
113
  """
105
114
  Yields entity state histories. See docs on the `History` model.
106
115
  """
107
- params, url = self.prepare_get_entity_histories_params(*args, **kwargs)
116
+ params, url = self.prepare_get_entity_histories_params(
117
+ entities=entities,
118
+ start_timestamp=start_timestamp,
119
+ end_timestamp=end_timestamp,
120
+ minimal_state_data=minimal_state_data,
121
+ significant_changes_only=significant_changes_only,
122
+ )
108
123
  data = self.request(
109
124
  url,
110
125
  params=self.construct_params(params),
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: homeassistant-api
3
- Version: 3.0.3.post4
3
+ Version: 3.0.4
4
4
  Summary: Python Wrapper for Homeassistant's REST API
5
5
  Home-page: https://github.com/GrandMoff100/HomeAssistantAPI
6
6
  License: GPL-3.0-or-later
@@ -14,7 +14,7 @@ Classifier: Programming Language :: Python :: 3.8
14
14
  Classifier: Programming Language :: Python :: 3.9
15
15
  Requires-Dist: aiohttp (>=3.8.1,<4.0.0)
16
16
  Requires-Dist: aiohttp-client-cache (>=0.6.1,<0.7.0)
17
- Requires-Dist: pydantic (>=1.9.0,<2.0.0)
17
+ Requires-Dist: pydantic (<=1.9.0)
18
18
  Requires-Dist: requests (>=2.26.0,<3.0.0)
19
19
  Requires-Dist: requests-cache (>=0.9.2,<0.10.0)
20
20
  Requires-Dist: simplejson (>=3.17.6,<4.0.0)
@@ -1,27 +1,27 @@
1
1
  homeassistant_api/__init__.py,sha256=AH9XX6azCAhlYkvfAKlPpH4PJllEHDZafCw0BFoMe3Y,1063
2
2
  homeassistant_api/_async/__init__.py,sha256=XEF5FPZYe_jT-ivHrAZh90P946aAV3yDMPOmgI7_Oks,319
3
- homeassistant_api/_async/asyncclient.py,sha256=UsSszq48oCy_j3S8hCvPu0CX96OBH283NG1kwOmeGp4,10974
3
+ homeassistant_api/_async/asyncclient.py,sha256=qR_FGaAt0wlhKwcvLcVTK7uAuMMwBUKH7BCuy4pJBpE,11850
4
4
  homeassistant_api/_async/models/__init__.py,sha256=A2C8C-7Pnp7cs5jc6xm12FdSShbEMpNnGeQlRB-mj9Y,255
5
- homeassistant_api/_async/models/domains.py,sha256=G3fcvz_1A4QBk8gr30eFDCpHa-ndGkAisnvwNHEQWCo,2117
6
- homeassistant_api/_async/models/entity.py,sha256=89To595nV9wloVN9G5GCDzspL-qQjDc3wZuBInpX-0A,2307
5
+ homeassistant_api/_async/models/domains.py,sha256=ubiJp0uOh_ZPdp2G8swr8dlZ9ePthR1jXNWzxfCsxHM,2430
6
+ homeassistant_api/_async/models/entity.py,sha256=lDmQ4Q9vAbErRuPPk94_1699UXYlTk6w5su6pcVG7q8,2808
7
7
  homeassistant_api/_async/models/events.py,sha256=bs86N92XMJQXJeVzWGz5YkjXH8zLWDzKO2OscFwd5Gk,792
8
8
  homeassistant_api/client.py,sha256=L9bWMQKPh0fOyW9USli16JjGODEzqSvkNR3eiZiie1E,225
9
9
  homeassistant_api/const.py,sha256=XSNCLYcEsdE5ji2LjpMmfeKdMACPhuRY3nHxhPJXXqA,84
10
10
  homeassistant_api/errors.py,sha256=lH_AQC7yGJujj4fLcFntn_mwlHBG36QFJRJfgWH87tk,2081
11
11
  homeassistant_api/mixins.py,sha256=Ii0t8JD9vncvtErTeo0ng7hK0GZD-Y0H6xBDEQdI1_s,2018
12
- homeassistant_api/models/__init__.py,sha256=3ZX2JOrA4lWB9DTtWuhGzyKaB9WarysCcKHvyiE50Sc,394
12
+ homeassistant_api/models/__init__.py,sha256=x6jKJJofsQcmVknEpbUaf0bq9nS7v0RpiJytjAYYLYM,474
13
13
  homeassistant_api/models/base.py,sha256=-5XsyKSTVzQHtaHNUgLPMAtiSgh_AUfvoyFnSAAtUx4,393
14
- homeassistant_api/models/domains.py,sha256=0TvtRxRzAdwZyDQokfIM9siEjKRlDcK3NZ3DIVqNwFw,2210
15
- homeassistant_api/models/entity.py,sha256=MMrVaIRBlcKJdOAmla-x3p6SeRnqIJq4_xmArooHPPU,2692
14
+ homeassistant_api/models/domains.py,sha256=78Amwtcry-WVR1tvE9NkIMSJggQXs8NI-Od_oQlfwaI,2533
15
+ homeassistant_api/models/entity.py,sha256=BkhgRentgWIypLIs3cs25X2BqL9jwru4k1E1WytHCAY,3151
16
16
  homeassistant_api/models/events.py,sha256=zHB8dNGEkgMlS0pg6NzRstxpjCRYvaz2d9ezM04IlMw,752
17
17
  homeassistant_api/models/history.py,sha256=a5HHV7bw4qeFtOYSqpmun98Kx5yV0DesTmLNi0WLoTo,634
18
18
  homeassistant_api/models/logbook.py,sha256=Op99ux61IQfcD_0UpdFqkKIl6G3j6mcZEhDJPgWoZUc,377
19
19
  homeassistant_api/models/states.py,sha256=60OOGntib5xJndTR6OYR10cZC31dvwPYveNR58rd250,420
20
20
  homeassistant_api/processing.py,sha256=WqworL2RdlvdfoQUfu7t-ISdJjmwYxB3pWvvjnlkCVc,4754
21
21
  homeassistant_api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
- homeassistant_api/rawapi.py,sha256=Hh2k8dP3Gm0hYfVbRAVc0pCurYf-i45MZdcy4SdIps8,5790
23
- homeassistant_api/rawclient.py,sha256=Nar1Fgm5vtpSULaBzqT5iOmnLqX2uoGT_ZoTO3HvGY8,10430
24
- homeassistant_api-3.0.3.post4.dist-info/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
25
- homeassistant_api-3.0.3.post4.dist-info/WHEEL,sha256=DA86_h4QwwzGeRoz62o1svYt5kGEXpoUTuTtwzoTb30,83
26
- homeassistant_api-3.0.3.post4.dist-info/METADATA,sha256=-sRqJzbl6KTHW0KuYgaRhADhoyM1LSjSWn7D32SJBgM,2902
27
- homeassistant_api-3.0.3.post4.dist-info/RECORD,,
22
+ homeassistant_api/rawapi.py,sha256=ScPe4pRy32iwOqpQFplzyZXcS1O4v6-3AhQOoecUS_I,6023
23
+ homeassistant_api/rawclient.py,sha256=JCaH8e8ufDCPYatlBj4yRXcpNcGkfMWPP-0Ow88lbk0,11018
24
+ homeassistant_api-3.0.4.dist-info/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
25
+ homeassistant_api-3.0.4.dist-info/WHEEL,sha256=DA86_h4QwwzGeRoz62o1svYt5kGEXpoUTuTtwzoTb30,83
26
+ homeassistant_api-3.0.4.dist-info/METADATA,sha256=LXCsCos2V2TsDaHgCL7_ha2Mr6YjMYMGe2-3izgE4kI,2889
27
+ homeassistant_api-3.0.4.dist-info/RECORD,,