Skip to content
This repository has been archived by the owner on Feb 29, 2024. It is now read-only.

Commit

Permalink
pylint
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas55555 committed Mar 13, 2021
1 parent 96a088d commit 29ae736
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 34 deletions.
22 changes: 14 additions & 8 deletions custom_components/husqvarna_automower/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from custom_components.husqvarna_automower.const import (
from husqvarna_automower import GetAccessToken, GetMowerData, RefreshAccessToken

from .const import (
CONF_API_KEY,
CONF_PASSWORD,
CONF_USERNAME,
DOMAIN,
PLATFORMS,
STARTUP_MESSAGE,
)
from husqvarna_automower import GetAccessToken, GetMowerData, RefreshAccessToken

SCAN_INTERVAL = timedelta(seconds=300)

Expand Down Expand Up @@ -62,6 +63,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):

class AuthenticationUpdateCoordinator(DataUpdateCoordinator):
"""Update Coordinator."""

def __init__(self, hass, username, password, api_key):
"""Initialize."""
_LOGGER.info("Inizialising UpdateCoordiantor")
Expand All @@ -83,7 +85,7 @@ def __init__(self, hass, username, password, api_key):
async def _async_update_data(self):
"""Update data via library."""
_LOGGER.info("Updating data")
if (self.access_token is None):
if self.access_token is None:
_LOGGER.debug("Getting new token, because Null")
try:
self.access_token_raw = await self.get_token.async_get_access_token()
Expand All @@ -94,26 +96,30 @@ async def _async_update_data(self):
self.token_expires_at = (
self.access_token_raw["expires_in"] + time.time()
)
_LOGGER.debug('Token expires at %i UTC', self.token_expires_at)
_LOGGER.debug("Token expires at %i UTC", self.token_expires_at)
except Exception:
_LOGGER.debug(
'Error message for UpdateFailed: %i', self.access_token_raw['status']
"Error message for UpdateFailed: %i",
self.access_token_raw["status"],
)
raise UpdateFailed("Error communicating with API")
elif self.token_expires_at < time.time():
_LOGGER.debug("Getting new token, because expired")
self.refresh_token = RefreshAccessToken(self.api_key, self.refresh_token)
try:
self.access_token_raw = await self.refresh_token.async_refresh_access_token()
self.access_token_raw = (
await self.refresh_token.async_refresh_access_token()
)
self.access_token = self.access_token_raw["access_token"]
self.refresh_token = self.access_token_raw["refresh_token"]
self.token_expires_at = (
self.access_token_raw["expires_in"] + time.time()
)
_LOGGER.debug('Token expires at %i UTC', self.token_expires_at)
_LOGGER.debug("Token expires at %i UTC", self.token_expires_at)
except Exception:
_LOGGER.debug(
'Error message for UpdateFailed: %i', self.access_token_raw['status']
"Error message for UpdateFailed: %i",
self.access_token_raw["status"],
)
raise UpdateFailed("Error communicating with API")

Expand Down
23 changes: 10 additions & 13 deletions custom_components/husqvarna_automower/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
"""Config flow to add the integration via the UI."""
import logging
import time
from collections import OrderedDict
Expand All @@ -6,15 +7,10 @@
from homeassistant import config_entries
from homeassistant.core import callback

from custom_components.husqvarna_automower.const import ( # pylint: disable=unused-import
CONF_API_KEY,
CONF_PASSWORD,
CONF_USERNAME,
DOMAIN,
HUSQVARNA_URL,
)
from husqvarna_automower import GetAccessToken, GetMowerData

from .const import CONF_API_KEY, CONF_PASSWORD, CONF_USERNAME, DOMAIN, HUSQVARNA_URL

CONF_ID = "unique_id"

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -79,8 +75,8 @@ async def try_connection(username, password, api_key):
_LOGGER.debug("Trying to connect to Husqvarna")
auth_api = GetAccessToken(api_key, username, password)
access_token_raw = await auth_api.async_get_access_token()
_LOGGER.debug('Access token raw: %s', access_token_raw)
_LOGGER.debug('Access token status: %s', access_token_raw['status'])
_LOGGER.debug("Access token raw: %s", access_token_raw)
_LOGGER.debug("Access token status: %s", access_token_raw["status"])
if access_token_raw["status"] == 200:
_LOGGER.debug("Connected with the Authentication API")
access_token = access_token_raw["access_token"]
Expand All @@ -93,20 +89,21 @@ async def try_connection(username, password, api_key):
_LOGGER.error("Error 401 - Unauthorized check your credentials")
raise Exception
else:
_LOGGER.error('Error %s', access_token_raw['status'])
_LOGGER.error("Error %s", access_token_raw["status"])
raise Exception
automower_api = GetMowerData(api_key, access_token, provider, token_type)
mower_data = await automower_api.async_mower_state()
if mower_data["status"] == 200:
_LOGGER.debug("Connected with the Automower Connect API")
elif mower_data["status"] == 403:
_LOGGER.error(
'Error 403 - Make sure that you are connected to the Authentication API and the Automower Connect API on %s', HUSQVARNA_URL
"Error 403 - Make sure that you are connected to the Authentication API and the Automower Connect API on %s",
HUSQVARNA_URL,
)
raise Exception
else:
_LOGGER.error('Error %s', mower_data['status'])
_LOGGER.error("Error %s", mower_data["status"])
raise Exception
_LOGGER.debug('Mower data: %s', mower_data)
_LOGGER.debug("Mower data: %s", mower_data)
_LOGGER.debug("Successfully connected Authentication and Automower Connect API")
time.sleep(5)
34 changes: 21 additions & 13 deletions custom_components/husqvarna_automower/vacuum.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
"""Creates a vacuum entity for the mower"""
import time

from homeassistant.components.vacuum import (
Expand All @@ -21,8 +22,8 @@
from homeassistant.helpers import entity
from homeassistant.helpers.update_coordinator import CoordinatorEntity, UpdateFailed

from custom_components.husqvarna_automower.const import DOMAIN, ERRORCODES, ICON
from husqvarna_automower import Return
from .const import DOMAIN, ERRORCODES, ICON

SUPPORT_STATE_SERVICES = (
SUPPORT_STATE
Expand Down Expand Up @@ -76,6 +77,15 @@ def __init__(self, coordinator, idx):
self.token_type = self.coordinator.data["token"]["token_type"]
self.mower_id = self.mower["id"]
self.api_key = self.coordinator.data["api_key"]
self.mower_command = None
self.mower_timestamp = None
self.mower_local_timestamp = None
self.readable_mower_local_timestamp = None
self.error_code = None
self.error_code_timestamp = None
self.next_start_timestamp = None
self.attributes = None
self.payload = None

@property
def available(self):
Expand Down Expand Up @@ -107,20 +117,18 @@ def state(self):
)
if self.mower_attributes["mower"]["state"] == "IN_OPERATION":
return f"{self.mower_attributes['mower']['activity']}"
elif self.mower_attributes["mower"]["state"] in [
if self.mower_attributes["mower"]["state"] in [
"FATAL_ERROR",
"ERROR",
"ERROR_AT_POWER_UP",
]:
self.error_code = self.mower_attributes["mower"]["errorCode"]
return ERRORCODES.get(self.error_code)
elif self.mower_attributes["mower"]["state"] == "RESTRICTED":
if self.mower_attributes["mower"]["state"] == "RESTRICTED":
if self.mower_attributes["planner"]["restrictedReason"] == "NOT_APPLICABLE":
return "Parked until further notice"
else:
return f"{self.mower_attributes['planner']['restrictedReason']}"
else:
return f"{self.mower_attributes['mower']['state']}"
return f"{self.mower_attributes['planner']['restrictedReason']}"
return f"{self.mower_attributes['mower']['state']}"

@property
def icon(self):
Expand Down Expand Up @@ -155,9 +163,9 @@ def device_state_attributes(self):
]
== 0
):
self.attr_errorCodeTimestamp = "-"
self.error_code_timestamp = "-"
else:
self.attr_errorCodeTimestamp = time.strftime(
self.error_code_timestamp = time.strftime(
"%Y-%m-%d %H:%M:%S",
time.gmtime(
(
Expand All @@ -175,9 +183,9 @@ def device_state_attributes(self):
]
== 0
):
self.attr_nextStartTimestamp = "-"
self.next_start_timestamp = "-"
else:
self.attr_nextStartTimestamp = time.strftime(
self.next_start_timestamp = time.strftime(
"%Y-%m-%d %H:%M:%S",
time.gmtime(
(
Expand All @@ -194,8 +202,8 @@ def device_state_attributes(self):
"activity": self.mower_attributes["mower"]["activity"],
"state": self.mower_attributes["mower"]["state"],
"errorCode": self.mower_attributes["mower"]["errorCode"],
"errorCodeTimestamp": self.attr_errorCodeTimestamp,
"nextStartTimestamp": self.attr_nextStartTimestamp,
"errorCodeTimestamp": self.error_code_timestamp,
"nextStartTimestamp": self.next_start_timestamp,
"action": self.mower_attributes["planner"]["override"]["action"],
"restrictedReason": self.mower_attributes["planner"]["restrictedReason"],
"statusTimestamp": time.strftime(
Expand Down

0 comments on commit 29ae736

Please sign in to comment.