Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reconnect on Failed Authentication #39

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions custom_components/hildebrandglow_dcc/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,19 @@
import voluptuous as vol
from homeassistant import config_entries, core, data_entry_flow

from .const import APP_ID, DOMAIN
from .const import APP_ID, DEFAULT_CALORIFIC_VALUE, DEFAULT_VOLUME_CORRECTION, DOMAIN
from .glow import CannotConnect, Glow, InvalidAuth

_LOGGER = logging.getLogger(__name__)

DATA_SCHEMA = vol.Schema({"username": str, "password": str})
DATA_SCHEMA = vol.Schema(
{
vol.Required("username"): str,
vol.Required("password"): str,
vol.Optional("correction", default=DEFAULT_VOLUME_CORRECTION): float,
vol.Optional("calorific", default=DEFAULT_CALORIFIC_VALUE): float,
}
)


def config_object(data: dict, glow: Dict[str, Any]) -> Dict[str, Any]:
Expand All @@ -21,6 +28,8 @@ def config_object(data: dict, glow: Dict[str, Any]) -> Dict[str, Any]:
"password": data["password"],
"token": glow["token"],
"token_exp": glow["exp"],
"correction": data["correction"],
"calorific": data["calorific"],
}


Expand Down
6 changes: 6 additions & 0 deletions custom_components/hildebrandglow_dcc/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,9 @@

DOMAIN = "hildebrandglow_dcc"
APP_ID = "b0f1b774-a586-4f72-9edd-27ead8aa7a8d"

DEFAULT_VOLUME_CORRECTION = 1.022640
DEFAULT_CALORIFIC_VALUE = 39.9

# This ought to be in Hass!
GAS_M3 = "m³"
78 changes: 61 additions & 17 deletions custom_components/hildebrandglow_dcc/glow.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ class Glow:
def __init__(self, app_id: str, token: str):
"""Create an authenticated Glow object."""
self.app_id = app_id
self.token = token
self.update_token(token)

@classmethod
def update_token(cls, value):
"""Set the token in the class, so it is available to all instances"""
cls.token = value

@classmethod
def authenticate(cls, app_id: str, username: str, password: str) -> Dict[str, Any]:
Expand All @@ -37,8 +42,8 @@ def authenticate(cls, app_id: str, username: str, password: str) -> Dict[str, An

try:
response = requests.post(url, json=auth, headers=headers)
except requests.Timeout:
raise CannotConnect
except requests.Timeout as _timeout:
raise CannotConnect from _timeout

data = response.json()

Expand All @@ -47,15 +52,20 @@ def authenticate(cls, app_id: str, username: str, password: str) -> Dict[str, An
pprint(data)
raise InvalidAuth

async def handle_failed_auth(self, config: ConfigEntry, hass: HomeAssistant) -> None:
@classmethod
async def handle_failed_auth(cls, config: ConfigEntry, hass: HomeAssistant) -> None:
"""Attempt to refresh the current Glow token."""

_LOGGER.debug("handle_failed_auth")
glow_auth = await hass.async_add_executor_job(
Glow.authenticate,
APP_ID,
config.data["username"],
config.data["password"],
)
from .config_flow import config_object

# pylint: disable=relative-beyond-top-level
from .config_flow import config_object # isort: skip

current_config = dict(config.data.copy())
new_config = config_object(current_config, glow_auth)
Expand All @@ -71,8 +81,8 @@ def retrieve_resources(self) -> List[Dict[str, Any]]:

try:
response = requests.get(url, headers=headers)
except requests.Timeout:
raise CannotConnect
except requests.Timeout as _timeout:
raise CannotConnect from _timeout

if response.status_code != 200:
raise InvalidAuth
Expand All @@ -89,25 +99,59 @@ def current_usage(self, resource: Dict[str, Any]) -> Dict[str, Any]:
# Need to pull updated data from DCC first
catchup_url = f"{self.BASE_URL}/resource/{resource}/catchup"

url = f"{self.BASE_URL}/resource/{resource}/readings?from=" + current_date + \
"T00:00:00&to=" + current_date + "T23:59:59&period=P1D&offset=-60&function=sum"
url = (
f"{self.BASE_URL}/resource/{resource}/readings?from="
+ current_date
+ "T00:00:00&to="
+ current_date
+ "T23:59:59&period=P1D&offset=-60&function=sum"
)
headers = {"applicationId": self.app_id, "token": self.token}

try:
response = requests.get(catchup_url, headers=headers)
response = requests.get(url, headers=headers)
except requests.Timeout:
raise CannotConnect
except requests.Timeout as _timeout:
raise CannotConnect from _timeout

if response.status_code != 200:
if response.json()["error"] == "incorrect elements -from in the future":
_LOGGER.info(
"Attempted to load data from the future - expected if the day has just changed")
elif response.status_code == 401:
err = "Attempted to load data from future - expected if the day has just changed"
_LOGGER.info(err)
return None

if response.status_code == 401:
raise InvalidAuth

if response.status_code == 404:
_LOGGER.debug("404 error - treating as 401: (%s)", url)
raise InvalidAuth
else:
_LOGGER.error("Response Status Code:" + str(response.status_code))
self.available = False

status = str(response.status_code)
_LOGGER.error("Response Status Code: %s (%s)", status, url)

data = response.json()
return data

def current_tariff(self, resource: Dict[str, Any]) -> Dict[str, Any]:
"""Retrieve the current tariff for a specified resource."""
url = f"{self.BASE_URL}/resource/{resource}/tariff"
headers = {"applicationId": self.app_id, "token": self.token}

try:
response = requests.get(url, headers=headers)
except requests.Timeout as _timeout:
raise CannotConnect from _timeout

if response.status_code != 200:
if response.status_code == 401:
raise InvalidAuth
if response.status_code == 404:
_LOGGER.error("Tariff 404 error - treating as 401: %s", url)
raise InvalidAuth

status = str(response.status_code)
_LOGGER.error("Tariff Response Status Code: %s (%s)", status, url)

data = response.json()
return data
Expand Down
8 changes: 4 additions & 4 deletions custom_components/hildebrandglow_dcc/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
"domain": "hildebrandglow_dcc",
"name": "Hildebrand Glow (DCC)",
"config_flow": true,
"documentation": "https://github.com/HandyHat/ha-hildebrandglow",
"issue_tracker": "https://github.com/HandyHat/ha-hildebrandglow/issues",
"codeowners": ["@handyhat"],
"documentation": "https://github.com/HandyHat/ha-hildebrandglow-dcc",
"issue_tracker": "https://github.com/HandyHat/ha-hildebrandglow-dcc/issues",
"codeowners": ["@HandyHat"],
"iot_class": "cloud_polling",
"version": "0.3.3"
"version": "0.4.0"
}
Loading