Skip to content

Commit

Permalink
Maintenance
Browse files Browse the repository at this point in the history
- Improve Invalid Credential error management and related messages
- Use async_forward_entry_setups from HA 2022.8
- Minor improvement in aiohttp session management
- Remove outdated errors translations
  • Loading branch information
ollo69 committed Jul 16, 2022
1 parent 4337f03 commit 1fa23b8
Show file tree
Hide file tree
Showing 16 changed files with 103 additions and 54 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[![](https://img.shields.io/github/release/ollo69/ha-smartthinq-washer/all.svg?style=for-the-badge)](https://github.com/ollo69/ha-smartthinq-sensors/releases)
[![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge)](https://github.com/hacs/integration)
[![](https://img.shields.io/github/license/ollo69/ha-smartthinq-washer?style=for-the-badge)](LICENSE)
[![](https://img.shields.io/github/release/ollo69/ha-smartthinq-sensors/all.svg?style=for-the-badge)](https://github.com/ollo69/ha-smartthinq-sensors/releases)
[![hacs_badge](https://img.shields.io/badge/HACS-Default-41BDF5.svg?style=for-the-badge)](https://github.com/hacs/integration)
[![](https://img.shields.io/github/license/ollo69/ha-smartthinq-sensors?style=for-the-badge)](LICENSE)
[![](https://img.shields.io/badge/MAINTAINER-%40ollo69-red?style=for-the-badge)](https://github.com/ollo69)
[![](https://img.shields.io/badge/COMMUNITY-FORUM-success?style=for-the-badge)](https://community.home-assistant.io)

Expand Down
43 changes: 33 additions & 10 deletions custom_components/smartthinq_sensors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from __future__ import annotations

from collections.abc import Iterable
from datetime import timedelta
import logging

Expand All @@ -16,6 +17,7 @@
)
from .wideq.core_async import ClientAsync
from .wideq.core_exceptions import (
AuthenticationError,
InvalidCredentialError,
MonitorRefreshError,
MonitorUnavailableError,
Expand Down Expand Up @@ -125,14 +127,31 @@ async def create_client_from_token(
)


def is_valid_ha_version() -> bool:
"""Check if HA version is valid for this integration."""
def is_min_ha_version(min_ha_major_ver: int, min_ha_minor_ver: int) -> bool:
"""Check if HA version at least a specific version."""
return (
MAJOR_VERSION > MIN_HA_MAJ_VER or
(MAJOR_VERSION == MIN_HA_MAJ_VER and MINOR_VERSION >= MIN_HA_MIN_VER)
MAJOR_VERSION > min_ha_major_ver or
(MAJOR_VERSION == min_ha_major_ver and MINOR_VERSION >= min_ha_minor_ver)
)


async def async_setup_entity_platforms(
hass: HomeAssistant,
config_entry: ConfigEntry,
platforms: Iterable[Platform | str],
) -> None:
"""Set up entity platforms using new method from HA version 2022.8."""
if is_min_ha_version(2022, 8):
await hass.config_entries.async_forward_entry_setups(config_entry, platforms)
else:
hass.config_entries.async_setup_platforms(config_entry, platforms)


def is_valid_ha_version() -> bool:
"""Check if HA version is valid for this integration."""
return is_min_ha_version(MIN_HA_MAJ_VER, MIN_HA_MIN_VER)


def _notify_error(hass, notification_id, title, message) -> None:
"""Notify user with persistent notification"""
hass.async_create_task(
Expand Down Expand Up @@ -188,13 +207,16 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try:
client = await lge_auth.create_client_from_token(hass, refresh_token, oauth_url)

except InvalidCredentialError:
except (AuthenticationError, InvalidCredentialError) as exc:
msg = "Invalid ThinQ credential error, integration setup aborted." \
" Please use the LG App on your mobile device to ensure your" \
" credentials are correct, then restart HomeAssistant." \
" If your credential changed, you must reconfigure integration"
" credentials are correct or there are new Term of Service" \
" to accept, then restart HomeAssistant." \
" If your credential changed, you must reconfigure integration." \
" Account based on social network are not supported and in most" \
" case do not work with this integration."
_notify_error(hass, "inv_credential", "SmartThinQ Sensors", msg)
_LOGGER.error(msg)
_LOGGER.exception(msg, exc_info=exc)
return False

except Exception as exc:
Expand Down Expand Up @@ -225,7 +247,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
LGE_DEVICES: lge_devices,
UNSUPPORTED_DEVICES: unsupported_devices,
}
hass.config_entries.async_setup_platforms(entry, SMARTTHINQ_PLATFORMS)
await async_setup_entity_platforms(hass, entry, SMARTTHINQ_PLATFORMS)

return True

Expand All @@ -235,7 +257,8 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
if unload_ok := await hass.config_entries.async_unload_platforms(
entry, SMARTTHINQ_PLATFORMS
):
hass.data.pop(DOMAIN)
data = hass.data.pop(DOMAIN)
await data[CLIENT].close()

return unload_ok

Expand Down
12 changes: 12 additions & 0 deletions custom_components/smartthinq_sensors/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import voluptuous as vol

from .wideq.core_async import ClientAsync
from .wideq.core_exceptions import AuthenticationError, InvalidCredentialError

from homeassistant import config_entries
from homeassistant.core import callback
Expand Down Expand Up @@ -38,6 +39,7 @@
RESULT_SUCCESS = 0
RESULT_FAIL = 1
RESULT_NO_DEV = 2
RESULT_CRED_FAIL = 3

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -188,13 +190,21 @@ async def _check_connection(
client = await lge_auth.create_client_from_token(
self.hass, self._token, self._oauth_url
)
except (AuthenticationError, InvalidCredentialError) as exc:
msg = "Invalid ThinQ credential error. Please use the LG App on your" \
" mobile device to verify if there are Term of Service to accept." \
" Account based on social network are not supported and in most" \
" case do not work with this integration."
_LOGGER.exception(msg, exc_info=exc)
return None, RESULT_CRED_FAIL
except Exception as exc:
_LOGGER.exception("Error connecting to ThinQ", exc_info=exc)
return None, RESULT_FAIL

if not client:
return None, RESULT_NO_DEV

await client.close()
if not client.has_devices:
return None, RESULT_NO_DEV

Expand All @@ -207,6 +217,8 @@ async def _manage_error(self, error_code: int, is_user_step=False) -> FlowResult

self._error = "unknown"
if error_code == RESULT_FAIL:
self._error = "error_connect"
elif error_code == RESULT_CRED_FAIL:
self._error = "invalid_credentials"

if is_user_step:
Expand Down
2 changes: 1 addition & 1 deletion custom_components/smartthinq_sensors/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Support to interface with LGE ThinQ Devices.
"""

__version__ = "0.23.3"
__version__ = "0.23.4"
PROJECT_URL = "https://github.com/ollo69/ha-smartthinq-sensors/"
ISSUE_URL = "{}issues".format(PROJECT_URL)

Expand Down
2 changes: 1 addition & 1 deletion custom_components/smartthinq_sensors/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@
],
"config_flow": true,
"iot_class": "cloud_polling",
"version": "0.23.3"
"version": "0.23.4"
}
1 change: 0 additions & 1 deletion custom_components/smartthinq_sensors/translations/el.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"invalid_region": "Μη έγκυρη μορφή περιοχής.",
"invalid_language": "Μη έγκυρη μορφή γλώσσας.",
"invalid_url": "Μη έγκυρη διεύθυνση URL ανακατεύθυνσης. Βεβαιωθείτε ότι έχετε πρόσβαση στην εφαρμογή ThinQ στο τηλέφωνό σας. Μπορείτε να λάβετε υποστήριξη [εδώ](https://git.io/JTjid).",
"invalid_credentials": "Δεν είναι έγκυρα τα διαπιστευτήρια SmartThinQ. Δοκιμάστε ξανά και βεβαιωθείτε ότι έχετε πρόσβαση στην εφαρμογή ThinQ στο τηλέφωνό σας.",
"no_user_info": "Απαιτείται όνομα χρήστη και κωδικός πρόσβασης.",
"unknown": "Άγνωστο σφάλμα."
},
Expand Down
3 changes: 2 additions & 1 deletion custom_components/smartthinq_sensors/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
"reconfigured": "Configuration successfully completed."
},
"error": {
"error_connect": "Error connecting to SmartThinQ. Try again, and make sure you can access the ThinQ app on your phone.",
"error_url": "Error retrieving login URL from ThinQ.",
"invalid_region": "Invalid region format.",
"invalid_language": "Invalid language format.",
"invalid_url": "Invalid redirection URL. Make sure you can access the ThinQ app on your phone. You can get support [over here](https://git.io/JTjid).",
"invalid_credentials": "Invalid SmartThinQ credentials. Try again, and make sure you can access the ThinQ app on your phone.",
"invalid_credentials": "Invalid SmartThinQ credentials. Use the LG App on your mobile device to verify if there are Term of Service to accept. Account based on social network are not supported and in most case do not work with this integration.",
"invalid_config": "Found invalid configuration, please reconfigure.",
"no_user_info": "User Name and Password are required.",
"unknown": "Unknown error."
Expand Down
3 changes: 1 addition & 2 deletions custom_components/smartthinq_sensors/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
"error": {
"invalid_region": "Formato de país no válido.",
"invalid_language": "Formato de idioma no válido.",
"invalid_url": "URL de redireccionamiento no válida",
"invalid_credentials": "Credenciales SmartThinQ no válidas."
"invalid_url": "URL de redireccionamiento no válida"
},
"step": {
"user": {
Expand Down
3 changes: 1 addition & 2 deletions custom_components/smartthinq_sensors/translations/hr.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
"error": {
"invalid_region": "Neispravan format regije.",
"invalid_language": "Neispravan format jezika.",
"invalid_url": "Neispravan URL za preusmjeravanje.",
"invalid_credentials": "Neispravne SmartThinQ vjerodajnice."
"invalid_url": "Neispravan URL za preusmjeravanje."
},
"step": {
"user": {
Expand Down
3 changes: 2 additions & 1 deletion custom_components/smartthinq_sensors/translations/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
"reconfigured": "Configurazione completata con successo."
},
"error": {
"error_connect": "Errore di connessione a SmartThinQ. Riprova, assicurandoti prima di poter accedere dall'applicazione ThinQ sul telefono",
"error_url": "Errore nel recuperare l'URL di login da ThinQ.",
"invalid_region": "Formato Paese non valido.",
"invalid_language": "Formato lingua non valido.",
"invalid_url": "URL di reindizzamento non valido. Accertati di poter accedere alla app ThinQ sul tuo smartphone. Puoi richiedere supporto [qui](https://git.io/JTjid).",
"invalid_credentials": "Credenziali SmartThinQ non valide. Riprova, assicurandoti prima di poter accedere dall'applicazione ThinQ sul telefono",
"invalid_credentials": "Credenziali SmartThinQ non valide. Utilizza l'applicazione ThinQ sul telefono per verificare che non siano presenti Condizioni di Servizio da accettare. Gli account basati su social network non sono supportati e nella maggior parte dei casi non funzionano con questa integrazione.",
"invalid_config": "Trovata configurazione non valida, riconfigurare.",
"no_user_info": "Nome utente e Password sono campi obbligatori.",
"unknown": "Errore sconosciuto."
Expand Down
3 changes: 1 addition & 2 deletions custom_components/smartthinq_sensors/translations/nb.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
"error": {
"invalid_region": "Ugyldig regionformat.",
"invalid_language": "Ugyldig språkformat.",
"invalid_url": "Ugyldig URL for omdirigering.",
"invalid_credentials": "Ugyldige SmartThinQ-legitimasjoner."
"invalid_url": "Ugyldig URL for omdirigering."
},
"step": {
"user": {
Expand Down
1 change: 0 additions & 1 deletion custom_components/smartthinq_sensors/translations/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"invalid_region": "Nieprawidłowy format regionu.",
"invalid_language": "Niepoprawny format języka.",
"invalid_url": "Nieprawidłowy adres URL przekierowania.",
"invalid_credentials": "Nieprawidłowe dane logowania SmartThinQ.",
"no_user_info": "Nazwa użytkownika i hasło są wymagane."
},
"step": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"invalid_region": "Formato de região inválido.",
"invalid_language": "Formato de idioma inválido.",
"invalid_url": "URL de redirecionamento inválida. Certifique-se que tem acesso ao app ThinQ através do smartphone. Pode obter ajuda [aqui](https://git.io/JTjid).",
"invalid_credentials": "Credenciais SmartThinQ inválidas. Tente novamente e verifique se você tem acesso ao app ThinQ em seu smartphone.",
"no_user_info": "Usuário e Senha são requiridos."
},
"step": {
Expand Down
1 change: 0 additions & 1 deletion custom_components/smartthinq_sensors/translations/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"invalid_region": "Formato da região inválido.",
"invalid_language": "Formato do idioma inválido.",
"invalid_url": "URL de redirecionamento inválido. Certifique-se que tem acesso à app ThinQ através do smartphone. Pode obter ajuda [aqui](https://git.io/JTjid).",
"invalid_credentials": "Credenciais SmartThinQ inválidas. Tente novamente e verifique se tem acesso à app ThinQ através do seu smartphone.",
"no_user_info": "O nome de utilizador e senha são obrigatórios."
},
"step": {
Expand Down
3 changes: 1 addition & 2 deletions custom_components/smartthinq_sensors/translations/sk.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
"error": {
"invalid_region": "Nesprávny formát regiónu.",
"invalid_language": "Nesprávny formát jazyka.",
"invalid_url": "Nesrpávna spätná URL.",
"invalid_credentials": "Nesprávne SmartThinQ prihlásenie."
"invalid_url": "Nesrpávna spätná URL."
},
"step": {
"user": {
Expand Down
Loading

0 comments on commit 1fa23b8

Please sign in to comment.