sherif-fanous/Pyecobee

Connection error handling

welwisher101 opened this issue · 4 comments

Thanks a lot for the python interface. You saved me a lot of time for a small project that I am trying to do with my home automation.

I am able to successfully use this package but only thing I cannot figure out is how to prevent script from crashing when there is not internet connection.

When there is no internet connection, it throws an error. Instead, it should report to user that it is not able to reach ecobee server and they should try again later.

My guess is you're not surrounding your code within a try/except block. If you do and handle the exception you can then report the error to the user.

I'd need to see your code though to really help you.

Thank you so much for the prompt response. I do have it wrapped in try...except statement but not sure how to handle connection error with that. I do refresh token when I get error and then run the function again but incase of connection error, I am not sure how to capture that.

This is what I am doing. But when there is no internet connection, it crashes my script.

def Ecobee_polling():
	selection = Selection(selection_type=SelectionType.REGISTERED.value, selection_match='', include_alerts=False,
						  include_device=False, include_electricity=False, include_equipment_status=False,
						  include_events=False, include_extended_runtime=False, include_house_details=False,
						  include_location=False, include_management=False, include_notification_settings=False,
						  include_oem_cfg=False, include_privacy=False, include_program=False, include_reminders=False,
						  include_runtime=False, include_security_settings=False, include_sensors=True,
						  include_settings=False, include_technician=False, include_utility=False, include_version=False,
						  include_weather=False)
	try:
		thermostat_response = ecobee_service.request_thermostats(selection)
		exception = 0

	except:
		exception = 1

	if exception == 1:
			refresh_token()
			Ecobee_polling()

This is the error I get when I try to run it without internet connection

Traceback (most recent call last):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 159, in _new_conn
    conn = connection.create_connection(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\util\connection.py", line 61, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 918, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 381, in _make_request
    self._validate_conn(conn)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 976, in _validate_conn
    conn.connect()
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 308, in connect
    conn = self._new_conn()
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 171, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x0C6247F0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 724, in urlopen
    retries = retries.increment(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\util\retry.py", line 439, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.ecobee.com', port=443): Max retries exceeded with url: /token?client_id=AdbrrAcNYEulyFtXqlYACvAGFVXW59Hn&code=Ft109OUkbOViflfpahUJyZws5hSPu2OJ&grant_type=refresh_token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0C6247F0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\t5750h0\Desktop\HAE\server.py", line 40, in refresh_token
    token_response = ecobee_service.refresh_tokens()
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyecobee\service.py", line 212, in refresh_tokens
    response = Utilities.make_http_request(requests.post,
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyecobee\utilities.py", line 277, in make_http_request
    six.reraise(EcobeeRequestsException, value_, traceback_)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\six.py", line 703, in reraise
    raise value
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyecobee\utilities.py", line 268, in make_http_request
    return requests_http_method(url,
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 119, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.ecobee.com', port=443): Max retries exceeded with url: /token?client_id=AdbrrAcNYEulyFtXqlYACvAGFVXW59Hn&code=Ft109OUkbOViflfpahUJyZws5hSPu2OJ&grant_type=refresh_token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0C6247F0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 159, in _new_conn
    conn = connection.create_connection(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\util\connection.py", line 61, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 918, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 381, in _make_request
    self._validate_conn(conn)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 976, in _validate_conn
    conn.connect()
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 308, in connect
    conn = self._new_conn()
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 171, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x0C624C70>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 724, in urlopen
    retries = retries.increment(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\util\retry.py", line 439, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.ecobee.com', port=443): Max retries exceeded with url: /authorize?client_id=AdbrrAcNYEulyFtXqlYACvAGFVXW59Hn&response_type=ecobeePin&scope=smartWrite (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0C624C70>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\t5750h0\Desktop\HAE\server.py", line 160, in <module>
    loop_3m()
  File "C:\Users\t5750h0\Desktop\HAE\server.py", line 142, in loop_3m
    Ecobee_polling()
  File "C:\Users\t5750h0\Desktop\HAE\server.py", line 106, in Ecobee_polling
    refresh_token()
  File "C:\Users\t5750h0\Desktop\HAE\server.py", line 42, in refresh_token
    Ecobee_authenticate()
  File "C:\Users\t5750h0\Desktop\HAE\server.py", line 64, in Ecobee_authenticate
    authorize_response = ecobee_service.authorize()
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyecobee\service.py", line 142, in authorize
    response = Utilities.make_http_request(requests.get,
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyecobee\utilities.py", line 277, in make_http_request
    six.reraise(EcobeeRequestsException, value_, traceback_)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\six.py", line 703, in reraise
    raise value
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyecobee\utilities.py", line 268, in make_http_request
    return requests_http_method(url,
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.ecobee.com', port=443): Max retries exceeded with url: /authorize?client_id=AdbrrAcNYEulyFtXqlYACvAGFVXW59Hn&response_type=ecobeePin&scope=smartWrite (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0C624C70>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

You want to catch the different exceptions (See this section). In your particular case you're interested in the EcobeeRequestsException which will get raised when there is no Internet connection.

Right now your code is always assuming that an error means that the token expired and refreshes it and then recursively calls Ecobee_polling!!! You certainly don't need to refresh the token on every failure (See this section on how to determine if the token expired and how to refresh it)

Here's more or less how I'd code this

try:
    thermostat_response = ecobee_service.request_thermostats(selection)
except EcobeeApiException as e:
    if e.status_code == 14:
        refresh_token()
        Ecobee_polling()
except EcobeeRequestsException:
    print('Looks like there is a problem with your connection')

In the EcobeeRequestsException block you can then decide what you want your script to do (i.e. Exit the script or perhaps sleep for some time (e.g. 1 minute) and try again)

Wow! Thanks a lot and sorry for not reading all the documentation. When I put this in for some reason EcobeeRequestsException is not catching the connection error and ends up crashing my script. However I can put a general except and delay it as now I know its not an authentication exception.

Traceback (most recent call last):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 159, in _new_conn
    conn = connection.create_connection(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\util\connection.py", line 61, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 918, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 381, in _make_request
    self._validate_conn(conn)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 976, in _validate_conn
    conn.connect()
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 308, in connect
    conn = self._new_conn()
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 171, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x0CDB3208>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 724, in urlopen
    retries = retries.increment(
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\util\retry.py", line 439, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.ecobee.com', port=443): Max retries exceeded with url: /1/thermostat?json=%7B%0A++%22selection%22%3A+%7B%0A++++%22includeAlerts%22%3A+false%2C%0A++++%22includeDevice%22%3A+false%2C%0A++++%22includeElectricity%22%3A+false%2C%0A++++%22includeEquipmentStatus%22%3A+false%2C%0A++++%22includeEvents%22%3A+false%2C%0A++++%22includeExtendedRuntime%22%3A+false%2C%0A++++%22includeHouseDetails%22%3A+false%2C%0A++++%22includeLocation%22%3A+false%2C%0A++++%22includeManagement%22%3A+false%2C%0A++++%22includeNotificationSettings%22%3A+false%2C%0A++++%22includeOemCfg%22%3A+false%2C%0A++++%22includePrivacy%22%3A+false%2C%0A++++%22includeProgram%22%3A+false%2C%0A++++%22includeReminders%22%3A+false%2C%0A++++%22includeRuntime%22%3A+false%2C%0A++++%22includeSecuritySettings%22%3A+false%2C%0A++++%22includeSensors%22%3A+true%2C%0A++++%22includeSettings%22%3A+false%2C%0A++++%22includeTechnician%22%3A+false%2C%0A++++%22includeUtility%22%3A+false%2C%0A++++%22includeVersion%22%3A+false%2C%0A++++%22includeWeather%22%3A+false%2C%0A++++%22selectionMatch%22%3A+%22%22%2C%0A++++%22selectionType%22%3A+%22registered%22%0A++%7D%0A%7D (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0CDB3208>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\t5750h0\Desktop\HAE\server.py", line 160, in <module>
    loop_3m()
  File "C:\Users\t5750h0\Desktop\HAE\server.py", line 142, in loop_3m
    Ecobee_polling()
  File "C:\Users\t5750h0\Desktop\HAE\server.py", line 91, in Ecobee_polling
    thermostat_response = ecobee_service.request_thermostats(selection)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyecobee\service.py", line 284, in request_thermostats
    response = Utilities.make_http_request(requests.get,
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyecobee\utilities.py", line 277, in make_http_request
    six.reraise(EcobeeRequestsException, value_, traceback_)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\six.py", line 703, in reraise
    raise value
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyecobee\utilities.py", line 268, in make_http_request
    return requests_http_method(url,
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\t5750h0\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.ecobee.com', port=443): Max retries exceeded with url: /1/thermostat?json=%7B%0A++%22selection%22%3A+%7B%0A++++%22includeAlerts%22%3A+false%2C%0A++++%22includeDevice%22%3A+false%2C%0A++++%22includeElectricity%22%3A+false%2C%0A++++%22includeEquipmentStatus%22%3A+false%2C%0A++++%22includeEvents%22%3A+false%2C%0A++++%22includeExtendedRuntime%22%3A+false%2C%0A++++%22includeHouseDetails%22%3A+false%2C%0A++++%22includeLocation%22%3A+false%2C%0A++++%22includeManagement%22%3A+false%2C%0A++++%22includeNotificationSettings%22%3A+false%2C%0A++++%22includeOemCfg%22%3A+false%2C%0A++++%22includePrivacy%22%3A+false%2C%0A++++%22includeProgram%22%3A+false%2C%0A++++%22includeReminders%22%3A+false%2C%0A++++%22includeRuntime%22%3A+false%2C%0A++++%22includeSecuritySettings%22%3A+false%2C%0A++++%22includeSensors%22%3A+true%2C%0A++++%22includeSettings%22%3A+false%2C%0A++++%22includeTechnician%22%3A+false%2C%0A++++%22includeUtility%22%3A+false%2C%0A++++%22includeVersion%22%3A+false%2C%0A++++%22includeWeather%22%3A+false%2C%0A++++%22selectionMatch%22%3A+%22%22%2C%0A++++%22selectionType%22%3A+%22registered%22%0A++%7D%0A%7D (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0CDB3208>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))