From f46f7eef800ccdd42bed270d8670b5d75fe4ddf1 Mon Sep 17 00:00:00 2001 From: Andrew Blake Date: Sun, 1 Jan 2023 19:02:33 +0000 Subject: [PATCH 1/2] Throw GrowattApiIncorrectPasswordException if the username / password is incorrect Throw GrowattApiUserAgentBlockedException if User Agent is being blocked (HTTP 403 error) Throw requests.exceptions.HTTPError for other API HTTP errors Throw GrowattApiUnknownException for unknown JSON response errors --- growattServer/__init__.py | 44 +++++++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/growattServer/__init__.py b/growattServer/__init__.py index 5983644..7fae297 100755 --- a/growattServer/__init__.py +++ b/growattServer/__init__.py @@ -23,6 +23,19 @@ class Timespan(IntEnum): day = 1 month = 2 + +class GrowattApiUnknownException(Exception): + pass + + +class GrowattApiIncorrectPasswordException(Exception): + pass + + +class GrowattApiUserAgentBlockedException(Exception): + pass + + class GrowattApi: server_url = 'https://server-api.growatt.com/' agent_identifier = "Dalvik/2.1.0 (Linux; U; Android 12; https://github.com/indykoning/PyPi_GrowattServer)" @@ -132,12 +145,31 @@ def login(self, username, password, is_password_hashed=False): 'userName': username, 'password': password }) - data = json.loads(response.content.decode('utf-8'))['back'] - if data['success']: - data.update({ - 'userId': data['user']['id'], - 'userLevel': data['user']['rightlevel'] - }) + + if response.status_code == 403: + # detect if the User Agent is being blocked by Growatt WAF + raise GrowattApiUserAgentBlockedException() + else: + # handle any other HTTP errors + response.raise_for_status() + + json_doc = response.content.decode('utf-8') + json_dict = json.loads(json_doc) + + if 'back' not in json_dict: + raise GrowattApiUnknownException() + + data = json_dict['back'] + if 'success' not in data: + raise GrowattApiUnknownException() + + if not data['success']: + raise GrowattApiIncorrectPasswordException() + + data.update({ + 'userId': data['user']['id'], + 'userLevel': data['user']['rightlevel'] + }) return data def plant_list(self, user_id): From 0f0eec6a4c593fb3767b94d3e358bba812b1e8f7 Mon Sep 17 00:00:00 2001 From: Andrew Blake Date: Sat, 1 Apr 2023 15:54:14 +0100 Subject: [PATCH 2/2] Change API URL --- growattServer/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/growattServer/__init__.py b/growattServer/__init__.py index 7fae297..0994b98 100755 --- a/growattServer/__init__.py +++ b/growattServer/__init__.py @@ -37,7 +37,7 @@ class GrowattApiUserAgentBlockedException(Exception): class GrowattApi: - server_url = 'https://server-api.growatt.com/' + server_url = 'https://server.growatt.com/' agent_identifier = "Dalvik/2.1.0 (Linux; U; Android 12; https://github.com/indykoning/PyPi_GrowattServer)" def __init__(self, add_random_user_id=False, agent_identifier=None):