HomeAssistant-API 3.0.4__py3-none-any.whl → 4.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,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
@@ -1,7 +1,25 @@
1
1
  """Module containing the primary Client class."""
2
- from ._async import RawAsyncClient
2
+ from typing import Any
3
+
4
+ from .rawasyncclient import RawAsyncClient
3
5
  from .rawclient import RawClient
4
6
 
5
7
 
6
8
  class Client(RawClient, RawAsyncClient):
7
- """The all-in-one class to interact with Home Assistant!"""
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,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
+ }
@@ -1,7 +1,9 @@
1
1
  """File for Service and Domain data models"""
2
- from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple
2
+ import gc
3
+ import inspect
4
+ from typing import TYPE_CHECKING, Any, Coroutine, Dict, Optional, Tuple, Union, cast
3
5
 
4
- from pydantic import Field, validator
6
+ from pydantic import Field
5
7
 
6
8
  from .base import BaseModel
7
9
  from .states import State
@@ -13,12 +15,39 @@ if TYPE_CHECKING:
13
15
  class Domain(BaseModel):
14
16
  """Model representing the domain that services belong to."""
15
17
 
16
- domain_id: str
17
- client: "Client" = Field(exclude=True, repr=False)
18
- services: Dict[str, "Service"] = {}
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
+ )
19
34
 
20
- def add_service(self, service_id: str, **data) -> None:
21
- """Registers services into a domain to be used or accessed"""
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."""
22
51
  self.services.update(
23
52
  {
24
53
  service_id: Service(
@@ -35,8 +64,6 @@ class Domain(BaseModel):
35
64
 
36
65
  def __getattr__(self, attr: str):
37
66
  """Allows services accessible as attributes"""
38
- if attr in self.__dict__:
39
- return super().__getattribute__(attr)
40
67
  if attr in self.services:
41
68
  return self.get_service(attr)
42
69
  return super().__getattribute__(attr)
@@ -56,28 +83,36 @@ class Service(BaseModel):
56
83
  """Model representing services from homeassistant"""
57
84
 
58
85
  service_id: str
59
- domain: Domain = Field(exlucde=True, repr=False)
86
+ domain: Domain = Field(exclude=True, repr=False)
60
87
  name: Optional[str] = None
61
88
  description: Optional[str] = None
62
89
  fields: Optional[Dict[str, ServiceField]] = None
63
- target: Optional[Dict[str, dict]] = None
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
90
+ target: Optional[Dict[str, Dict[str, Any]]] = None
73
91
 
74
92
  def trigger(self, **service_data) -> Tuple[State, ...]:
75
93
  """Triggers the service associated with this object."""
76
- return self.domain.client.trigger_service(
94
+ return self.domain._client.trigger_service(
77
95
  self.domain.domain_id,
78
96
  self.service_id,
79
97
  **service_data,
80
98
  )
81
99
 
82
- def __call__(self, **service_data) -> Tuple[State, ...]:
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)
83
118
  return self.trigger(**service_data)
@@ -1,8 +1,7 @@
1
1
  """Module for Entity and entity Group data models"""
2
2
 
3
3
  from datetime import datetime
4
- from posixpath import join
5
- from typing import TYPE_CHECKING, Any, Dict, Optional, cast
4
+ from typing import TYPE_CHECKING, Dict, Optional
6
5
 
7
6
  from pydantic import Field
8
7
 
@@ -17,28 +16,37 @@ if TYPE_CHECKING:
17
16
  class Group(BaseModel):
18
17
  """Represents the groups that entities belong to."""
19
18
 
20
- group_id: str
21
- client: "Client" = Field(exclude=True, repr=False)
22
- entities: Dict[str, "Entity"] = {}
23
-
24
- def add_entity(self, entity_slug: str, state: State) -> None:
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:
25
35
  """Registers entities to this Group object"""
26
- self.entities[entity_slug] = Entity(
27
- slug=entity_slug,
36
+ self.entities[slug] = Entity(
37
+ slug=slug,
28
38
  state=state,
29
39
  group=self,
30
40
  )
31
41
 
32
- def get_entity(self, entity_slug: str) -> Optional["Entity"]:
42
+ def get_entity(self, slug: str) -> Optional["Entity"]:
33
43
  """Returns Entity with the given name if it exists. Otherwise returns None"""
34
- return self.entities.get(entity_slug)
44
+ return self.entities.get(slug)
35
45
 
36
46
  def __getattr__(self, key: str):
37
47
  if key in self.entities:
38
48
  return self.get_entity(key)
39
- return super(object, self).__getattribute__( # type: ignore[misc] # pylint: disable=bad-super-call
40
- key
41
- )
49
+ return super().__getattribute__(key)
42
50
 
43
51
 
44
52
  class Entity(BaseModel):
@@ -46,52 +54,71 @@ class Entity(BaseModel):
46
54
 
47
55
  slug: str
48
56
  state: State
49
- group: Group
57
+ group: Group = Field(exclude=True, repr=False)
50
58
 
51
59
  def get_state(self) -> State:
52
- """Asks Home Assistant for the state of the entity and caches it locally"""
53
- state_data = self.group.client.request(join("states", self.entity_id))
54
- self.state = self.group.client.process_state_json(
55
- cast(Dict[str, Any], state_data)
56
- )
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)
57
62
  return self.state
58
63
 
59
- def set_state(self, state: State) -> State:
64
+ def update_state(self) -> State:
60
65
  """
61
- Tells Home Assistant to set the given State object.
62
- (You can construct the state object yourself.)
66
+ Tells Home Assistant to set its current local State object.
67
+ (You can modify the local state object yourself.)
63
68
  """
64
- state_data = self.group.client.request(
65
- join("states", self.group.group_id + "." + self.slug),
66
- method="POST",
67
- json=state,
68
- )
69
- self.state = self.group.client.process_state_json(
70
- cast(Dict[str, Any], state_data)
71
- )
69
+ self.state = self.group._client.set_state(self.state)
72
70
  return self.state
73
71
 
74
72
  @property
75
73
  def entity_id(self) -> str:
76
- """Constructs the entity_id string from its group and slug"""
77
- return (self.group.group_id + "." + self.slug).strip()
74
+ """Constructs the :code:`entity_id` string from its group and slug"""
75
+ return f"{self.group.group_id}.{self.slug}".strip()
78
76
 
79
77
  def get_history(
80
78
  self,
81
79
  start_timestamp: Optional[datetime] = None,
82
80
  # Defaults to 1 day before. https://developers.home-assistant.io/docs/api/rest/
83
81
  end_timestamp: Optional[datetime] = None,
84
- minimal_state_data: bool = False,
85
82
  significant_changes_only: bool = False,
86
- ) -> History:
87
- """Gets the previous `State`'s of the `Entity`"""
88
- history = None
89
- for history in self.group.client.get_entity_histories(
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(
90
118
  entities=(self,),
91
119
  start_timestamp=start_timestamp,
92
120
  end_timestamp=end_timestamp,
93
- minimal_state_data=minimal_state_data,
94
121
  significant_changes_only=significant_changes_only,
95
122
  ):
96
- break
97
- return history
123
+ return history
124
+ return None
@@ -1,6 +1,6 @@
1
1
  """Event Model File"""
2
2
 
3
- from typing import TYPE_CHECKING, Dict, cast
3
+ from typing import TYPE_CHECKING, Any, Dict, Optional
4
4
 
5
5
  from pydantic import Field
6
6
 
@@ -18,11 +18,26 @@ class Event(BaseModel):
18
18
  https://data.home-assistant.io/docs/events
19
19
  """
20
20
 
21
- event_type: str
22
- listener_count: int
23
- client: "Client" = Field(exclude=True, repr=False)
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
+ )
24
27
 
25
- def fire(self, **event_data) -> str:
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]:
26
33
  """Fires the corresponding event in Home Assistant."""
27
- data = self.client.fire_event(self.event_type, **event_data)
28
- return cast(Dict[str, str], data).get("message", "No message provided")
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
@@ -2,16 +2,25 @@
2
2
  from datetime import datetime
3
3
  from typing import Optional
4
4
 
5
+ from pydantic import Field
6
+
5
7
  from .base import BaseModel
6
8
 
7
9
 
8
10
  class LogbookEntry(BaseModel):
9
- """Model representing"""
11
+ """Model representing entries in the Logbook."""
10
12
 
11
- when: datetime
12
- name: str
13
- entity_id: str
14
- state: Optional[str] = None
15
- domain: Optional[str] = None
16
- context_id: Optional[str] = None
17
- icon: Optional[str] = None
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
+ )
@@ -2,15 +2,39 @@
2
2
  from datetime import datetime
3
3
  from typing import Any, Dict, Optional
4
4
 
5
+ from pydantic import Field
6
+
5
7
  from .base import BaseModel
6
8
 
7
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
+
8
16
  class State(BaseModel):
9
17
  """A model representing a state of an entity."""
10
18
 
11
- entity_id: str
12
- state: str
13
- attributes: Dict[str, Any] = {}
14
- last_changed: Optional[datetime] = None
15
- last_updated: Optional[datetime] = None
16
- context: Dict[str, Optional[str]] = {}
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)