1515from cryptography .hazmat .primitives .ciphers import Cipher , algorithms , modes
1616
1717from ..api_config import SWITCHBOT_APP_API_BASE_URL , SWITCHBOT_APP_COGNITO_POOL
18- from ..const import LockStatus , SwitchbotAuthenticationError
18+ from ..const import (
19+ LockStatus ,
20+ SwitchbotAccountConnectionError ,
21+ SwitchbotAuthenticationError ,
22+ )
1923from .device import SwitchbotDevice , SwitchbotOperationError
2024
2125COMMAND_HEADER = "57"
@@ -104,7 +108,7 @@ def retrieve_encryption_key(device_mac: str, username: str, password: str):
104108 )
105109 except cognito_idp_client .exceptions .NotAuthorizedException as err :
106110 raise SwitchbotAuthenticationError ("Failed to authenticate" ) from err
107- except BaseException as err :
111+ except Exception as err :
108112 raise SwitchbotAuthenticationError (
109113 "Unexpected error during authentication"
110114 ) from err
@@ -117,15 +121,24 @@ def retrieve_encryption_key(device_mac: str, username: str, password: str):
117121 raise SwitchbotAuthenticationError ("Unexpected authentication response" )
118122
119123 access_token = auth_response ["AuthenticationResult" ]["AccessToken" ]
120- key_response = requests .post (
121- url = SWITCHBOT_APP_API_BASE_URL + "/developStage/keys/v1/communicate" ,
122- headers = {"authorization" : access_token },
123- json = {
124- "device_mac" : device_mac ,
125- "keyType" : "user" ,
126- },
127- timeout = 10 ,
128- )
124+ try :
125+ key_response = requests .post (
126+ url = SWITCHBOT_APP_API_BASE_URL + "/developStage/keys/v1/communicate" ,
127+ headers = {"authorization" : access_token },
128+ json = {
129+ "device_mac" : device_mac ,
130+ "keyType" : "user" ,
131+ },
132+ timeout = 10 ,
133+ )
134+ except requests .exceptions .RequestException as err :
135+ raise SwitchbotAccountConnectionError (
136+ f"Failed to retrieve encryption key from SwitchBot Account: { err } "
137+ ) from err
138+ if key_response .status_code > 299 :
139+ raise SwitchbotAuthenticationError (
140+ f"Unexpected status code returned by SwitchBot Account API: { key_response .status_code } "
141+ )
129142 key_response_content = json .loads (key_response .content )
130143 if key_response_content ["statusCode" ] != 100 :
131144 raise SwitchbotAuthenticationError (
0 commit comments