Skip to content

Commit

Permalink
Use .id, and not xxxxId (nor ._id), tweak super classes
Browse files Browse the repository at this point in the history
  • Loading branch information
zxdavb committed Sep 23, 2024
1 parent f1259ce commit af36efd
Show file tree
Hide file tree
Showing 29 changed files with 414 additions and 401 deletions.
4 changes: 2 additions & 2 deletions src/evohomeasync/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def user_data(self) -> _UserDataT | None: # TODO: deprecate?
async def _populate_user_data(
self, force_refresh: bool = False
) -> dict[str, bool | int | str]:
"""Retrieve the cached user data (excl. the session ID).
"""Retrieve the cached user data (excl. the session id).
Pull the latest JSON from the web only if force_refresh is True.
"""
Expand All @@ -241,7 +241,7 @@ async def _populate_user_data(
user_data = await self.broker.populate_user_data()
self.user_info = user_data[SZ_USER_INFO] # type: ignore[assignment]

return self.user_info # excludes session ID
return self.user_info # excludes session id

async def _get_user(self) -> _UserInfoT:
"""Return the user (if needed, get the JSON)."""
Expand Down
12 changes: 7 additions & 5 deletions src/evohomeasync/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def __init__(

self._headers: dict[str, str] = {
"content-type": "application/json"
} # NB: no sessionId yet
} # NB: no session_id yet
self._POST_DATA: Final[dict[str, str]] = {
"Username": self.username,
"Password": password,
Expand Down Expand Up @@ -142,7 +142,7 @@ async def _make_request(
async with func(url_, json=data, headers=self._headers) as response:
response_text = await response.text() # why cant I move this below the if?

# if 401/unauthorized, may need to refresh sessionId (expires in 15 mins?)
# if 401/unauthorized, may need to refresh session_id (expires in 15 mins?)
if response.status != HTTPStatus.UNAUTHORIZED or _dont_reauthenticate:
return response

Expand All @@ -159,12 +159,14 @@ async def _make_request(
# return response # ...because: the user credentials must be invalid

_LOGGER.debug(f"Session now expired/invalid ({self._session_id})...")
self._headers = {"content-type": "application/json"} # remove the sessionId
self._headers = {
"content-type": "application/json"
} # remove the session_id

_, response = await self._populate_user_data() # Get a fresh sessionId
_, response = await self._populate_user_data() # Get a fresh session_id
assert self._session_id is not None # mypy hint

_LOGGER.debug(f"... success: new sessionId = {self._session_id}")
_LOGGER.debug(f"... success: new session_id = {self._session_id}")
self._headers[SZ_SESSION_ID] = self._session_id

if "session" in url_: # retry not needed for /session
Expand Down
2 changes: 1 addition & 1 deletion src/evohomeasync/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class DeprecationError(EvohomeBaseError):


class InvalidSchema(EvohomeError):
"""The config/status JSON is invalid (e.g. missing an entity Id)."""
"""The config/status JSON is invalid (e.g. missing an entity id)."""


class RequestFailed(EvohomeError):
Expand Down
2 changes: 1 addition & 1 deletion src/evohomeasync/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
_TaskIdT = NewType("_TaskIdT", str) # TODO: int or str?


SZ_SESSION_ID: Final = "sessionId" # id Id, not ID
SZ_SESSION_ID: Final = "sessionId" # is Id, not ID

# schema keys (start with a lower case letter)
SZ_ALLOWED_MODES: Final = "allowedModes"
Expand Down
16 changes: 8 additions & 8 deletions src/evohomeasync2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

import aiohttp

from .base import EvohomeClient as _EvohomeClientNew
from .base import EvohomeClient
from .broker import AbstractTokenManager, Broker # noqa: F401
from .controlsystem import ControlSystem # noqa: F401
from .exceptions import ( # noqa: F401
Expand Down Expand Up @@ -53,8 +53,8 @@ def __init__(
) -> None:
super().__init__(username, password, websession)

self.refresh_token = refresh_token
self.access_token = access_token
self.refresh_token = refresh_token or ""
self.access_token = access_token or ""
self.access_token_expires = access_token_expires or dt.min

async def restore_access_token(self) -> None:
Expand All @@ -64,7 +64,7 @@ async def save_access_token(self) -> None:
pass


class EvohomeClient(_EvohomeClientNew):
class EvohomeClientOld(EvohomeClient):
"""A wrapper to expose the new EvohomeClient in the old style."""

def __init__(
Expand Down Expand Up @@ -95,21 +95,21 @@ def __init__(
super().__init__(self._token_manager, websession, debug=debug)

@property
def access_token(self) -> str:
def access_token(self) -> str: # type: ignore[override]
"""Return the access_token attr."""
return self._token_manager.access_token

@property
def access_token_expires(self) -> dt:
def access_token_expires(self) -> dt: # type: ignore[override]
"""Return the access_token_expires attr."""
return self._token_manager.access_token_expires

@property
def refresh_token(self) -> str:
def refresh_token(self) -> str: # type: ignore[override]
"""Return the refresh_token attr."""
return self._token_manager.refresh_token

@property
def username(self) -> str:
def username(self) -> str: # type: ignore[override]
"""Return the username attr."""
return self._token_manager.username
19 changes: 9 additions & 10 deletions src/evohomeasync2/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@
from .controlsystem import ControlSystem
from .location import Location
from .schema import SCH_FULL_CONFIG, SCH_USER_ACCOUNT
from .schema.const import SZ_USER_ID

if TYPE_CHECKING:
from .schema import _EvoDictT, _EvoListT, _LocationIdT, _ScheduleT, _SystemIdT
from .schema import _EvoDictT, _EvoListT, _ScheduleT


_LOGGER: Final = logging.getLogger(__name__.rpartition(".")[0])
Expand Down Expand Up @@ -46,12 +47,10 @@ def access_token(self) -> NoReturn:
def access_token_expires(self) -> NoReturn:
raise exc.DeprecationError(f"{self}: access_token_expires attrs is deprecated")

async def full_installation(
self, location_id: None | _LocationIdT = None
) -> NoReturn:
# if location_id is None:
# location_id = self.installation_info[0]["locationInfo"]["locationId"]
# url = f"location/{location_id}/installationInfo?" # Specific location
async def full_installation(self, loc_id: str | None = None) -> NoReturn:
# if loc_id is None:
# loc_id = self.installation_info[0][SZ_LOCATION_INFO][SZ_LOCATION_ID]
# url = f"location/{loc_id}/installationInfo?" # Specific location

raise exc.DeprecationError(
f"{self}: .full_installation() is deprecated, use .installation()"
Expand Down Expand Up @@ -228,7 +227,7 @@ async def _installation(self, refresh_status: bool = True) -> _EvoListT:
# FIXME: shouldn't really be starting again with new objects?
self.locations = [] # for now, need to clear this before GET

url = f"location/installationInfo?userId={self.account_info['userId']}"
url = f"location/installationInfo?userId={self.account_info[SZ_USER_ID]}"
url += "&includeTemperatureControlSystems=True"

self._full_config = await self.broker.get(url, schema=SCH_FULL_CONFIG) # type: ignore[assignment]
Expand Down Expand Up @@ -268,8 +267,8 @@ def _get_single_tcs(self) -> ControlSystem:
return self.locations[0]._gateways[0]._control_systems[0]

@property
def system_id(self) -> _SystemIdT: # an evohome-client anachronism, deprecate?
"""Return the ID of the default TCS (assumes only one loc/gwy/TCS)."""
def system_id(self) -> str: # an evohome-client anachronism, deprecate?
"""Return the id of the default TCS (assumes only one loc/gwy/TCS)."""
return self._get_single_tcs().systemId

async def reset_mode(self) -> None:
Expand Down
11 changes: 7 additions & 4 deletions src/evohomeasync2/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@
HTTPStatus.UNAUTHORIZED: "Unauthorized (expired access token/unknown entity id?)",
}

SZ_USERNAME: Final = "Username" # is PascalCase, not camelCase?
SZ_PASSWORD: Final = "Password"


class OAuthTokenData(TypedDict):
access_token: str
Expand Down Expand Up @@ -85,8 +88,8 @@ def __init__(
"""Initialize the token manager."""

self._user_credentials = {
"Username": username,
"Password": password,
SZ_USERNAME: username,
SZ_PASSWORD: password,
} # TODO: are only ever PascalCase?

self.websession = websession
Expand All @@ -99,12 +102,12 @@ def __str__(self) -> str:
@property
def username(self) -> str:
"""Return the username."""
return self._user_credentials["Username"]
return self._user_credentials[SZ_USERNAME]

@property # TODO: remove this whan no longer needed
def _password(self) -> str:
"""Return the username."""
return self._user_credentials["Password"]
return self._user_credentials[SZ_PASSWORD]

def _token_data_reset(self) -> None:
"""Reset the token data to its falsy state."""
Expand Down
2 changes: 1 addition & 1 deletion src/evohomeasync2/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ async def get_schedule(
evo = ctx.obj[SZ_EVO]

zon: HotWater | Zone = _get_tcs(evo, loc_idx).zones_by_id[zone_id]
schedule = {zon._id: {SZ_NAME: zon.name, SZ_SCHEDULE: await zon.get_schedule()}}
schedule = {zon.id: {SZ_NAME: zon.name, SZ_SCHEDULE: await zon.get_schedule()}}

await _write(filename, json.dumps(schedule, indent=4) + "\r\n\r\n")

Expand Down
Loading

0 comments on commit af36efd

Please sign in to comment.