From 83a934dc9d0fd104725454a1cb02a5fceebcf3b2 Mon Sep 17 00:00:00 2001 From: Scott Giminiani Date: Mon, 13 May 2024 00:02:39 -0400 Subject: [PATCH] Don't refresh login token for every request 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. --- custom_components/dae/client.py | 37 +++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/custom_components/dae/client.py b/custom_components/dae/client.py index ae8b221..dafa9de 100644 --- a/custom_components/dae/client.py +++ b/custom_components/dae/client.py @@ -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() @@ -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()) @@ -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()) @@ -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):