Skip to content

Commit

Permalink
Don't refresh login token for every request
Browse files Browse the repository at this point in the history
Before we were getting a new login cookie token before making every
request for data. Instead, we'll make a request optimistically and if it
fails login and retry the request once.
  • Loading branch information
ScottG489 committed May 13, 2024
1 parent d0d6f40 commit 83a934d
Showing 1 changed file with 31 additions and 6 deletions.
37 changes: 31 additions & 6 deletions custom_components/dae/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,10 @@ def __init__(self, username: str, password: str) -> None:
self.password = password

self.base_url = "https://meter.iotems.net/ws/home-owner.php"
self.auth_cookies = SimpleCookie()
self.auth_cookie = {}

def get_channel_meters(self) -> dict:
"""Get channel and meter data."""
self.login()
channels = self.list_channels()
meters = self.read_meters()

Expand All @@ -35,8 +34,11 @@ def login(self) -> LoginResponse:
action_type = "login"
data = {'d': action_type, 'username': self.username, 'password': self.password}

r = requests.post(self.base_url, data=data)
self.auth_cookies.load(r.headers['Set-Cookie'])
self.auth_cookie = {}
r = self._request(data)
auth_cookie = SimpleCookie()
auth_cookie.load(r.headers['Set-Cookie'])
self.auth_cookie = {'PHPSESSID': auth_cookie['PHPSESSID'].value}

return LoginResponse.from_response(r.json())

Expand All @@ -46,7 +48,7 @@ def list_channels(self) -> ListChannelsResponse:
operation_type = "list"
data = {'d': action_type, 'm': operation_type, 'username': self.username}

r = requests.post(self.base_url, data=data, cookies={'PHPSESSID': self.auth_cookies['PHPSESSID'].value})
r = self._request(data)

return ListChannelsResponse.from_response(r.json())

Expand All @@ -57,16 +59,39 @@ def read_meters(self, channel_id: int = None) -> ReadMetersResponse:
if channel_id:
data['channel-id'] = channel_id

r = requests.post(self.base_url, data=data, cookies={'PHPSESSID': self.auth_cookies['PHPSESSID'].value})
r = self._request(data)

return ReadMetersResponse.from_response(r.json())

def _request(self, data: dict):
resp = self._do_request(data)
dae_resp = DaeResponse.from_response(resp.json())

if dae_resp.result:
return resp
else:
self.login()
resp = self._do_request(data)
dae_resp = DaeResponse.from_response(resp.json())

if dae_resp.result:
return resp
else:
raise Exception("DAE request failed.")

def _do_request(self, data: dict):
return requests.post(self.base_url, data=data, cookies=self.auth_cookie)


@dataclass
class DaeResponse:
result: bool
message: str

@classmethod
def from_response(cls, resp: dict):
return DaeResponse(resp['result'], resp['message'])


@dataclass
class LoginResponse(DaeResponse):
Expand Down

0 comments on commit 83a934d

Please sign in to comment.