HomeAssistant-API 3.0.3.post5__tar.gz → 4.0.0__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.
Files changed (36) hide show
  1. {HomeAssistant-API-3.0.3.post5 → HomeAssistant-API-4.0.0}/PKG-INFO +10 -5
  2. {HomeAssistant-API-3.0.3.post5 → HomeAssistant-API-4.0.0}/README.md +5 -1
  3. {HomeAssistant-API-3.0.3.post5 → HomeAssistant-API-4.0.0}/homeassistant_api/__init__.py +12 -8
  4. HomeAssistant-API-4.0.0/homeassistant_api/client.py +25 -0
  5. {HomeAssistant-API-3.0.3.post5 → HomeAssistant-API-4.0.0}/homeassistant_api/errors.py +26 -6
  6. {HomeAssistant-API-3.0.3.post5 → HomeAssistant-API-4.0.0}/homeassistant_api/models/__init__.py +5 -1
  7. {HomeAssistant-API-3.0.3.post5 → HomeAssistant-API-4.0.0}/homeassistant_api/models/base.py +8 -1
  8. HomeAssistant-API-4.0.0/homeassistant_api/models/domains.py +118 -0
  9. HomeAssistant-API-4.0.0/homeassistant_api/models/entity.py +124 -0
  10. HomeAssistant-API-4.0.0/homeassistant_api/models/events.py +43 -0
  11. {HomeAssistant-API-3.0.3.post5 → HomeAssistant-API-4.0.0}/homeassistant_api/models/history.py +7 -4
  12. HomeAssistant-API-4.0.0/homeassistant_api/models/logbook.py +26 -0
  13. HomeAssistant-API-4.0.0/homeassistant_api/models/states.py +40 -0
  14. HomeAssistant-API-4.0.0/homeassistant_api/processing.py +134 -0
  15. HomeAssistant-API-3.0.3.post5/homeassistant_api/_async/asyncclient.py → HomeAssistant-API-4.0.0/homeassistant_api/rawasyncclient.py +142 -113
  16. HomeAssistant-API-3.0.3.post5/homeassistant_api/rawapi.py → HomeAssistant-API-4.0.0/homeassistant_api/rawbaseclient.py +38 -46
  17. {HomeAssistant-API-3.0.3.post5 → HomeAssistant-API-4.0.0}/homeassistant_api/rawclient.py +142 -110
  18. {HomeAssistant-API-3.0.3.post5 → HomeAssistant-API-4.0.0}/pyproject.toml +41 -12
  19. HomeAssistant-API-4.0.0/setup.py +35 -0
  20. HomeAssistant-API-3.0.3.post5/homeassistant_api/_async/__init__.py +0 -12
  21. HomeAssistant-API-3.0.3.post5/homeassistant_api/_async/models/__init__.py +0 -6
  22. HomeAssistant-API-3.0.3.post5/homeassistant_api/_async/models/domains.py +0 -67
  23. HomeAssistant-API-3.0.3.post5/homeassistant_api/_async/models/entity.py +0 -81
  24. HomeAssistant-API-3.0.3.post5/homeassistant_api/_async/models/events.py +0 -27
  25. HomeAssistant-API-3.0.3.post5/homeassistant_api/client.py +0 -7
  26. HomeAssistant-API-3.0.3.post5/homeassistant_api/const.py +0 -2
  27. HomeAssistant-API-3.0.3.post5/homeassistant_api/mixins.py +0 -53
  28. HomeAssistant-API-3.0.3.post5/homeassistant_api/models/domains.py +0 -74
  29. HomeAssistant-API-3.0.3.post5/homeassistant_api/models/entity.py +0 -97
  30. HomeAssistant-API-3.0.3.post5/homeassistant_api/models/events.py +0 -28
  31. HomeAssistant-API-3.0.3.post5/homeassistant_api/models/logbook.py +0 -17
  32. HomeAssistant-API-3.0.3.post5/homeassistant_api/models/states.py +0 -16
  33. HomeAssistant-API-3.0.3.post5/homeassistant_api/processing.py +0 -131
  34. HomeAssistant-API-3.0.3.post5/setup.py +0 -38
  35. {HomeAssistant-API-3.0.3.post5 → HomeAssistant-API-4.0.0}/LICENSE +0 -0
  36. {HomeAssistant-API-3.0.3.post5 → HomeAssistant-API-4.0.0}/homeassistant_api/py.typed +0 -0
@@ -1,21 +1,22 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: homeassistant-api
3
- Version: 3.0.3.post5
3
+ Version: 4.0.0
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
7
7
  Author: GrandMoff100
8
8
  Author-email: minecraftcrusher100@gmail.com
9
- Requires-Python: >=3.8,<4.0
9
+ Requires-Python: >=3.7,<4.0.0
10
10
  Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
11
11
  Classifier: Programming Language :: Python :: 3
12
12
  Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.7
13
14
  Classifier: Programming Language :: Python :: 3.8
14
15
  Classifier: Programming Language :: Python :: 3.9
15
16
  Requires-Dist: aiohttp (>=3.8.1,<4.0.0)
16
17
  Requires-Dist: aiohttp-client-cache (>=0.6.1,<0.7.0)
17
- Requires-Dist: pydantic (>=1.9.0,<2.0.0)
18
- Requires-Dist: requests (>=2.26.0,<3.0.0)
18
+ Requires-Dist: pydantic (<=1.9.0)
19
+ Requires-Dist: requests (==2.27.1)
19
20
  Requires-Dist: requests-cache (>=0.9.2,<0.10.0)
20
21
  Requires-Dist: simplejson (>=3.17.6,<4.0.0)
21
22
  Project-URL: Documentation, https://homeassistantapi.readthedocs.io
@@ -24,6 +25,7 @@ Description-Content-Type: text/markdown
24
25
 
25
26
  # HomeassistantAPI
26
27
 
28
+ [![Code Coverage](https://img.shields.io/codecov/c/github/GrandMoff100/HomeAssistantAPI/dev?style=for-the-badge&token=SJFC3HX5R1)](https://codecov.io/gh/GrandMoff100/HomeAssistantAPI)
27
29
  [![PyPI - Downloads](https://img.shields.io/pypi/dm/HomeAssistant-API?style=for-the-badge)](https://pypi.org/project/homeassistant_api)
28
30
  ![GitHub commits since latest release (by date including pre-releases)](https://img.shields.io/github/commits-since/GrandMoff100/HomeassistantAPI/latest/dev?include_prereleases&style=for-the-badge)
29
31
  [![Read the Docs (version)](https://img.shields.io/readthedocs/homeassistantapi?style=for-the-badge)](https://homeassistantapi.readthedocs.io/en/latest/?badge=latest)
@@ -34,6 +36,7 @@ Description-Content-Type: text/markdown
34
36
  ## Python wrapper for Homeassistant's [REST API](https://developers.home-assistant.io/docs/api/rest/)
35
37
 
36
38
  Here is a quick example.
39
+
37
40
  ```py
38
41
  from homeassistant_api import Client
39
42
 
@@ -44,11 +47,13 @@ with Client(
44
47
 
45
48
  light = client.get_domain("light")
46
49
 
47
- light.turn_on(entity_id='light.living_room_lamp')
50
+ light.turn_on(entity_id="light.living_room_lamp")
48
51
  ```
52
+
49
53
  All the methods also support async!
50
54
 
51
55
  ## Documentation
56
+
52
57
  All documentation, API reference, contribution guidelines and pretty much everything else
53
58
  you'd want to know is on our readthedocs site [here](https://homeassistantapi.readthedocs.io)
54
59
 
@@ -1,5 +1,6 @@
1
1
  # HomeassistantAPI
2
2
 
3
+ [![Code Coverage](https://img.shields.io/codecov/c/github/GrandMoff100/HomeAssistantAPI/dev?style=for-the-badge&token=SJFC3HX5R1)](https://codecov.io/gh/GrandMoff100/HomeAssistantAPI)
3
4
  [![PyPI - Downloads](https://img.shields.io/pypi/dm/HomeAssistant-API?style=for-the-badge)](https://pypi.org/project/homeassistant_api)
4
5
  ![GitHub commits since latest release (by date including pre-releases)](https://img.shields.io/github/commits-since/GrandMoff100/HomeassistantAPI/latest/dev?include_prereleases&style=for-the-badge)
5
6
  [![Read the Docs (version)](https://img.shields.io/readthedocs/homeassistantapi?style=for-the-badge)](https://homeassistantapi.readthedocs.io/en/latest/?badge=latest)
@@ -10,6 +11,7 @@
10
11
  ## Python wrapper for Homeassistant's [REST API](https://developers.home-assistant.io/docs/api/rest/)
11
12
 
12
13
  Here is a quick example.
14
+
13
15
  ```py
14
16
  from homeassistant_api import Client
15
17
 
@@ -20,11 +22,13 @@ with Client(
20
22
 
21
23
  light = client.get_domain("light")
22
24
 
23
- light.turn_on(entity_id='light.living_room_lamp')
25
+ light.turn_on(entity_id="light.living_room_lamp")
24
26
  ```
27
+
25
28
  All the methods also support async!
26
29
 
27
30
  ## Documentation
31
+
28
32
  All documentation, API reference, contribution guidelines and pretty much everything else
29
33
  you'd want to know is on our readthedocs site [here](https://homeassistantapi.readthedocs.io)
30
34
 
@@ -1,7 +1,8 @@
1
- """Imports all library stuff for convenience."""
1
+ """Interact with your Homeassistant Instance remotely."""
2
2
 
3
3
 
4
4
  __all__ = (
5
+ "Client",
5
6
  "State",
6
7
  "Service",
7
8
  "History",
@@ -9,15 +10,19 @@ __all__ = (
9
10
  "Event",
10
11
  "Entity",
11
12
  "Domain",
12
- "AsyncService",
13
- "AsyncGroup",
14
- "AsyncEvent",
15
- "AsyncEntity",
16
- "AsyncDomain",
13
+ "Processing",
17
14
  "LogbookEntry",
15
+ "APIConfigurationError",
16
+ "EndpointNotFoundError",
17
+ "HomeassistantAPIError",
18
+ "MalformedDataError",
19
+ "MalformedInputError",
20
+ "MethodNotAllowedError",
21
+ "ParameterMissingError",
22
+ "RequestError",
23
+ "UnauthorizedError",
18
24
  )
19
25
 
20
- from ._async import AsyncDomain, AsyncEntity, AsyncEvent, AsyncGroup, AsyncService
21
26
  from .client import Client
22
27
  from .errors import (
23
28
  APIConfigurationError,
@@ -29,7 +34,6 @@ from .errors import (
29
34
  ParameterMissingError,
30
35
  RequestError,
31
36
  UnauthorizedError,
32
- UnexpectedStatusCodeError,
33
37
  )
34
38
  from .models import Domain, Entity, Event, Group, History, LogbookEntry, Service, State
35
39
  from .processing import Processing
@@ -0,0 +1,25 @@
1
+ """Module containing the primary Client class."""
2
+ from typing import Any
3
+
4
+ from .rawasyncclient import RawAsyncClient
5
+ from .rawclient import RawClient
6
+
7
+
8
+ class Client(RawClient, RawAsyncClient):
9
+ """
10
+ The all-in-one class to interact with Home Assistant!
11
+
12
+ :param api_url: The location of the api endpoint. e.g. :code:`http://localhost:8123/api` Required.
13
+ :param token: The refresh or long lived access token to authenticate your requests. Required.
14
+ :param global_request_kwargs: A dictionary or dict-like object of kwargs to pass to :func:`requests.request` or :meth:`aiohttp.ClientSession.request`. Optional.
15
+ :param cache_session: A :py:class:`requests_cache.CachedSession` object to use for caching requests. Optional.
16
+ :param async_cache_session: A :py:class:`aiohttp_client_cache.CachedSession` object to use for caching requests. Optional.
17
+ """ # pylint: disable=line-too-long
18
+
19
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
20
+ if "cache_session" in kwargs:
21
+ RawClient.__init__(self, *args, **kwargs)
22
+ elif "async_cache_session" in kwargs:
23
+ RawAsyncClient.__init__(self, *args, **kwargs)
24
+ else:
25
+ super().__init__(*args, **kwargs)
@@ -8,8 +8,17 @@ class HomeassistantAPIError(BaseException):
8
8
  class RequestError(HomeassistantAPIError):
9
9
  """Error raised when an issue occurs when requesting to Homeassistant."""
10
10
 
11
- def __init__(self, body: str) -> None:
12
- super().__init__(f"Bad Request: {body}")
11
+
12
+ class RequestTimeoutError(RequestError):
13
+ """Error raised when a request times out."""
14
+
15
+
16
+ class ResponseError(HomeassistantAPIError):
17
+ """Error raised when an issue occurs in a response from Homeassistant."""
18
+
19
+
20
+ class BadTemplateError(HomeassistantAPIError):
21
+ """Error raised when User sends bad template to homeassistant."""
13
22
 
14
23
 
15
24
  class MalformedDataError(HomeassistantAPIError):
@@ -28,12 +37,16 @@ class ParameterMissingError(HomeassistantAPIError):
28
37
  """Error raised when an expected attribute is missing from api response data."""
29
38
 
30
39
 
31
- class UnexpectedStatusCodeError(HomeassistantAPIError):
32
- """Error raised when Home Assistant returns a response with status code that was unexpected."""
40
+ class InternalServerError(HomeassistantAPIError):
41
+ """Error raised when Home Assistant says that it got itself in trouble."""
33
42
 
34
- def __init__(self, code: int, content) -> None:
43
+ def __init__(self, status_code: int, content: str) -> None:
35
44
  super().__init__(
36
- f"Home Assistant return response with an unrecognized status code {code!r}.\n{content}"
45
+ f"Home Assistant returned a response with an error status code {status_code!r}.\n"
46
+ f"{content}\n"
47
+ "If this happened, "
48
+ "please report it at https://github.com/GrandMoff100/HomeAssistantAPI/issues "
49
+ "with the request status code and the request content. Thanks!"
37
50
  )
38
51
 
39
52
 
@@ -62,3 +75,10 @@ class ProcessorNotFoundError(HomeassistantAPIError):
62
75
  """
63
76
  Error raised when a response is encountered that homeassistant_api is not told how to handle.
64
77
  """
78
+
79
+
80
+ class UnexpectedStatusCodeError(ResponseError):
81
+ """Error raised when a response has an unexpected status code."""
82
+
83
+ def __init__(self, status_code: int) -> None:
84
+ super().__init__(f"Response has unexpected status code: {status_code!r}")
@@ -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,14 +1,21 @@
1
1
  """Module for Global Base Model Configuration inheritance."""
2
2
 
3
+ from datetime import datetime
4
+
3
5
  from pydantic import BaseModel as PydanticBaseModel
4
6
 
5
7
 
6
8
  class BaseModel(PydanticBaseModel):
7
9
  """Base model that all Library Models inherit from."""
8
10
 
9
- class Config:
11
+ class Config: # pylint: disable=too-few-public-methods
10
12
  """Pydantic config class for all library models."""
11
13
 
12
14
  arbitrary_types_allowed = True
13
15
  smart_union = True
14
16
  validate_assignment = True
17
+ exclude_none = True
18
+
19
+ json_encoders = {
20
+ datetime: lambda timestamp: timestamp.isoformat(),
21
+ }
@@ -0,0 +1,118 @@
1
+ """File for Service and Domain data models"""
2
+ import gc
3
+ import inspect
4
+ from typing import TYPE_CHECKING, Any, Coroutine, Dict, Optional, Tuple, Union, cast
5
+
6
+ from pydantic import Field
7
+
8
+ from .base import BaseModel
9
+ from .states import State
10
+
11
+ if TYPE_CHECKING:
12
+ from homeassistant_api import Client
13
+
14
+
15
+ class Domain(BaseModel):
16
+ """Model representing the domain that services belong to."""
17
+
18
+ def __init__(self, *args, _client: Optional["Client"] = None, **kwargs) -> None:
19
+ super().__init__(*args, **kwargs)
20
+ if _client is None:
21
+ raise ValueError("No client passed.")
22
+ object.__setattr__(self, "_client", _client)
23
+
24
+ _client: "Client"
25
+ domain_id: str = Field(
26
+ ...,
27
+ description="The name of the domain that services belong to. "
28
+ "(e.g. :code:`frontend` in :code:`frontend.reload_themes`",
29
+ )
30
+ services: Dict[str, "Service"] = Field(
31
+ {},
32
+ description="A dictionary of all services belonging to the domain indexed by their names",
33
+ )
34
+
35
+ @classmethod
36
+ def from_json(cls, json: Dict[str, Any], client: "Client") -> "Domain":
37
+ """Constructs Domain and Service models from json data."""
38
+ if "domain" not in json or "services" not in json:
39
+ raise ValueError(
40
+ "Missing services or attribute attribute in json argument."
41
+ )
42
+ domain = cls(domain_id=cast(str, json.get("domain")), _client=client)
43
+ services = json.get("services")
44
+ assert isinstance(services, dict)
45
+ for service_id, data in services.items():
46
+ domain._add_service(service_id, **data)
47
+ return domain
48
+
49
+ def _add_service(self, service_id: str, **data) -> None:
50
+ """Registers services into a domain to be used or accessed. Used internally."""
51
+ self.services.update(
52
+ {
53
+ service_id: Service(
54
+ service_id=service_id,
55
+ domain=self,
56
+ **data,
57
+ )
58
+ }
59
+ )
60
+
61
+ def get_service(self, service_id: str) -> Optional["Service"]:
62
+ """Return a Service with the given service_id, returns None if no such service exists"""
63
+ return self.services.get(service_id)
64
+
65
+ def __getattr__(self, attr: str):
66
+ """Allows services accessible as attributes"""
67
+ if attr in self.services:
68
+ return self.get_service(attr)
69
+ return super().__getattribute__(attr)
70
+
71
+
72
+ class ServiceField(BaseModel):
73
+ """Model for service parameters/fields."""
74
+
75
+ description: str
76
+ example: Any
77
+ selector: Optional[Dict[str, Any]] = None
78
+ name: Optional[str] = None
79
+ required: Optional[bool] = None
80
+
81
+
82
+ class Service(BaseModel):
83
+ """Model representing services from homeassistant"""
84
+
85
+ service_id: str
86
+ domain: Domain = Field(exclude=True, repr=False)
87
+ name: Optional[str] = None
88
+ description: Optional[str] = None
89
+ fields: Optional[Dict[str, ServiceField]] = None
90
+ target: Optional[Dict[str, Dict[str, Any]]] = None
91
+
92
+ def trigger(self, **service_data) -> Tuple[State, ...]:
93
+ """Triggers the service associated with this object."""
94
+ return self.domain._client.trigger_service(
95
+ self.domain.domain_id,
96
+ self.service_id,
97
+ **service_data,
98
+ )
99
+
100
+ async def async_trigger(self, **service_data) -> Tuple[State, ...]:
101
+ """Triggers the service associated with this object."""
102
+ return await self.domain._client.async_trigger_service(
103
+ self.domain.domain_id,
104
+ self.service_id,
105
+ **service_data,
106
+ )
107
+
108
+ def __call__(
109
+ self, **service_data
110
+ ) -> Union[Tuple[State, ...], Coroutine[Any, Any, Tuple[State, ...]]]:
111
+ """Triggers the service associated with this object."""
112
+ assert (frame := inspect.currentframe()) is not None
113
+ assert (parent_frame := frame.f_back) is not None
114
+ if inspect.iscoroutinefunction(
115
+ caller := gc.get_referrers(parent_frame.f_code)[0]
116
+ ) or inspect.iscoroutine(caller):
117
+ return self.async_trigger(**service_data)
118
+ return self.trigger(**service_data)
@@ -0,0 +1,124 @@
1
+ """Module for Entity and entity Group data models"""
2
+
3
+ from datetime import datetime
4
+ from typing import TYPE_CHECKING, Dict, Optional
5
+
6
+ from pydantic import Field
7
+
8
+ from .base import BaseModel
9
+ from .history import History
10
+ from .states import State
11
+
12
+ if TYPE_CHECKING:
13
+ from homeassistant_api import Client
14
+
15
+
16
+ class Group(BaseModel):
17
+ """Represents the groups that entities belong to."""
18
+
19
+ def __init__(self, *args, _client: Optional["Client"] = None, **kwargs) -> None:
20
+ super().__init__(*args, **kwargs)
21
+ object.__setattr__(self, "_client", _client)
22
+
23
+ group_id: str = Field(
24
+ ...,
25
+ description="A unique string identifying different types/groups of entities.",
26
+ )
27
+ _client: "Client"
28
+ entities: Dict[str, "Entity"] = Field(
29
+ {},
30
+ description="A dictionary of all entities belonging to the group "
31
+ "indexed by their :code:`entity_id`.",
32
+ )
33
+
34
+ def _add_entity(self, slug: str, state: State) -> None:
35
+ """Registers entities to this Group object"""
36
+ self.entities[slug] = Entity(
37
+ slug=slug,
38
+ state=state,
39
+ group=self,
40
+ )
41
+
42
+ def get_entity(self, slug: str) -> Optional["Entity"]:
43
+ """Returns Entity with the given name if it exists. Otherwise returns None"""
44
+ return self.entities.get(slug)
45
+
46
+ def __getattr__(self, key: str):
47
+ if key in self.entities:
48
+ return self.get_entity(key)
49
+ return super().__getattribute__(key)
50
+
51
+
52
+ class Entity(BaseModel):
53
+ """Represents entities inside of homeassistant"""
54
+
55
+ slug: str
56
+ state: State
57
+ group: Group = Field(exclude=True, repr=False)
58
+
59
+ def get_state(self) -> State:
60
+ """Asks Home Assistant for the state of the entity and updates it locally"""
61
+ self.state = self.group._client.get_state(entity_id=self.entity_id)
62
+ return self.state
63
+
64
+ def update_state(self) -> State:
65
+ """
66
+ Tells Home Assistant to set its current local State object.
67
+ (You can modify the local state object yourself.)
68
+ """
69
+ self.state = self.group._client.set_state(self.state)
70
+ return self.state
71
+
72
+ @property
73
+ def entity_id(self) -> str:
74
+ """Constructs the :code:`entity_id` string from its group and slug"""
75
+ return f"{self.group.group_id}.{self.slug}".strip()
76
+
77
+ def get_history(
78
+ self,
79
+ start_timestamp: Optional[datetime] = None,
80
+ # Defaults to 1 day before. https://developers.home-assistant.io/docs/api/rest/
81
+ end_timestamp: Optional[datetime] = None,
82
+ significant_changes_only: bool = False,
83
+ ) -> Optional[History]:
84
+ """Gets the previous :py:class:`State`'s of the :py:class:`Entity`"""
85
+ for history in self.group._client.get_entity_histories(
86
+ entities=(self,),
87
+ start_timestamp=start_timestamp,
88
+ end_timestamp=end_timestamp,
89
+ significant_changes_only=significant_changes_only,
90
+ ):
91
+ return history
92
+ return None
93
+
94
+ async def async_get_state(self) -> State:
95
+ """Asks Home Assistant for the state of the entity and sets it locally"""
96
+ self.state = await self.group._client.async_get_state(
97
+ group_id=self.group.group_id,
98
+ slug=self.slug,
99
+ )
100
+ return self.state
101
+
102
+ async def async_update_state(self) -> State:
103
+ """Tells Home Assistant to set the current local State object."""
104
+ self.state = await self.group._client.async_set_state(self.state)
105
+ return self.state
106
+
107
+ async def async_get_history(
108
+ self,
109
+ start_timestamp: Optional[datetime] = None,
110
+ # Defaults to 1 day before. https://developers.home-assistant.io/docs/api/rest/
111
+ end_timestamp: Optional[datetime] = None,
112
+ significant_changes_only: bool = False,
113
+ ) -> Optional[History]:
114
+ """
115
+ Gets the :py:class:`History` of previous :py:class:`State`'s of the :py:class:`Entity`.
116
+ """
117
+ async for history in self.group._client.async_get_entity_histories(
118
+ entities=(self,),
119
+ start_timestamp=start_timestamp,
120
+ end_timestamp=end_timestamp,
121
+ significant_changes_only=significant_changes_only,
122
+ ):
123
+ return history
124
+ return None
@@ -0,0 +1,43 @@
1
+ """Event Model File"""
2
+
3
+ from typing import TYPE_CHECKING, Any, Dict, Optional
4
+
5
+ from pydantic import Field
6
+
7
+ from .base import BaseModel
8
+
9
+ if TYPE_CHECKING:
10
+ from homeassistant_api import Client
11
+
12
+
13
+ class Event(BaseModel):
14
+ """
15
+ Event class for Home Assistant Event Triggers
16
+
17
+ For attribute information see the Data Science docs on Event models
18
+ https://data.home-assistant.io/docs/events
19
+ """
20
+
21
+ _client: "Client"
22
+ event: str = Field(..., description="The event name/type.")
23
+ listener_count: int = Field(
24
+ ...,
25
+ description="How many listeners are interesting in this event in Home Assistant.",
26
+ )
27
+
28
+ def __init__(self, *args, _client: Optional["Client"] = None, **kwargs) -> None:
29
+ super().__init__(*args, **kwargs)
30
+ object.__setattr__(self, "_client", _client)
31
+
32
+ def fire(self, **event_data) -> Optional[str]:
33
+ """Fires the corresponding event in Home Assistant."""
34
+ return self._client.fire_event(self.event, **event_data)
35
+
36
+ async def async_fire(self, **event_data) -> str:
37
+ """Fires the event type in homeassistant. Ex. `on_startup`"""
38
+ return await self._client.async_fire_event(self.event, **event_data)
39
+
40
+ @classmethod
41
+ def from_json(cls, json: Dict[str, Any], client: "Client") -> "Event":
42
+ """Constructs Event model from json data"""
43
+ return cls(**json, _client=client)
@@ -1,14 +1,18 @@
1
1
  """Module for the History model."""
2
2
  from typing import Tuple
3
3
 
4
+ from pydantic import Field
5
+
4
6
  from .base import BaseModel
5
7
  from .states import State
6
8
 
7
9
 
8
10
  class History(BaseModel):
9
- """Model representing past :code:`State`'s of an entity."""
11
+ """Model representing past :py:class:`State`'s of an entity."""
10
12
 
11
- states: Tuple[State, ...]
13
+ states: Tuple[State, ...] = Field(
14
+ ..., description="A tuple of previous states of an entity."
15
+ )
12
16
 
13
17
  def __init__(self, *args, **kwargs):
14
18
  super().__init__(*args, **kwargs)
@@ -18,6 +22,5 @@ class History(BaseModel):
18
22
  def entity_id(self) -> str:
19
23
  """Returns the shared :code:`entity_id` of states."""
20
24
  entity_ids = [state.entity_id for state in self.states]
21
- result, *others = set(entity_ids)
22
- assert len(others) == 0
25
+ result, *_ = set(entity_ids)
23
26
  return result
@@ -0,0 +1,26 @@
1
+ """Module for the Logbook Entry model."""
2
+ from datetime import datetime
3
+ from typing import Optional
4
+
5
+ from pydantic import Field
6
+
7
+ from .base import BaseModel
8
+
9
+
10
+ class LogbookEntry(BaseModel):
11
+ """Model representing entries in the Logbook."""
12
+
13
+ when: datetime = Field(..., description="When the entry was logged.")
14
+ name: str = Field(..., description="The name of the entry.")
15
+ message: Optional[str] = Field(None, description="Optional message for the entry.")
16
+ entity_id: Optional[str] = Field(None, description="Optional relevant entity_id.")
17
+ state: Optional[str] = Field(
18
+ None, description="The new state information of the entity_id."
19
+ )
20
+ domain: Optional[str] = Field(None, description="When the entry was logged.")
21
+ context_id: Optional[str] = Field(
22
+ None, description="Optional relevant context instead of an entity."
23
+ )
24
+ icon: Optional[str] = Field(
25
+ None, description="An MDI icon associated with the entity_id."
26
+ )
@@ -0,0 +1,40 @@
1
+ """Module for the Entity State model."""
2
+ from datetime import datetime
3
+ from typing import Any, Dict, Optional
4
+
5
+ from pydantic import Field
6
+
7
+ from .base import BaseModel
8
+
9
+
10
+ class Context(BaseModel):
11
+ """Model for entity state contexts."""
12
+
13
+ id: str = Field(max_length=26, description="Unique string identifying the context.")
14
+
15
+
16
+ class State(BaseModel):
17
+ """A model representing a state of an entity."""
18
+
19
+ entity_id: str = Field(..., description="The entity_id this state corresponds to.")
20
+ state: str = Field(
21
+ ..., description="The string representation of the state of the entity."
22
+ )
23
+ attributes: Dict[str, Any] = Field(
24
+ {}, description="A dictionary of extra attributes of the state."
25
+ )
26
+ last_changed: datetime = Field(
27
+ default_factory=datetime.utcnow,
28
+ description="The last time the state was changed.",
29
+ )
30
+ last_updated: Optional[datetime] = Field(
31
+ default_factory=datetime.utcnow, description="The last time the state updated."
32
+ )
33
+ context: Optional[Context] = Field(
34
+ None, description="Provides information about the context of the state."
35
+ )
36
+
37
+ @classmethod
38
+ def from_json(cls, json: Dict[str, Any]) -> "State":
39
+ """Constructs State model from json data"""
40
+ return cls.parse_obj(json)