Skip to content

Commit

Permalink
Fix: "Use metric units" toggle has no effect and simplify sensor crea…
Browse files Browse the repository at this point in the history
…tion (#219)

* Initiate config flow and add reauth function

* remove DATA_SCHEMA

* remove DATA_SCHEMA

* add logger

* add logger

* set default metric values setting to true

* add more logging regarding metric values

* call for config entry inside get function

* update logging

* get metric_value from coordinator

* log sensor entries

* Add suggested_unit_of_measurement

* Simplify sensor generation

* change statistics SensorStateClass to TOTAL

* Rever change on statistics senosrs state_class
  • Loading branch information
CM000n authored Feb 17, 2024
1 parent 6389938 commit f602a1b
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 185 deletions.
7 changes: 4 additions & 3 deletions custom_components/toyota/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ async def async_setup_entry( # pylint: disable=too-many-statements

email = entry.data[CONF_EMAIL]
password = entry.data[CONF_PASSWORD]
use_metric_values = entry.data[CONF_METRIC_VALUES]

client = MyT(
username=email,
Expand All @@ -68,14 +67,16 @@ async def async_setup_entry( # pylint: disable=too-many-statements

async def async_get_vehicle_data() -> Optional[list[VehicleData]]:
"""Fetch vehicle data from Toyota API."""
metric_values = entry.data[CONF_METRIC_VALUES]

try:
vehicles = await asyncio.wait_for(client.get_vehicles(metric=use_metric_values), 15)
vehicles = await asyncio.wait_for(client.get_vehicles(metric=metric_values), 15)
vehicle_informations: list[VehicleData] = []
if vehicles is not None:
for vehicle in vehicles:
await vehicle.update()
vehicle_data = VehicleData(
data=vehicle, statistics=None, metric_values=use_metric_values
data=vehicle, statistics=None, metric_values=metric_values
)

if vehicle.vin is not None:
Expand Down
97 changes: 50 additions & 47 deletions custom_components/toyota/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,50 @@
"""Config flow for Toyota Connected Services integration."""
import logging
from typing import Any, Mapping

import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import selector
from mytoyota.client import MyT
from mytoyota.exceptions import ToyotaInvalidUsernameError, ToyotaLoginError

# https://github.com/PyCQA/pylint/issues/3202
from .const import CONF_METRIC_VALUES, DOMAIN # pylint: disable=unused-import
from .const import CONF_METRIC_VALUES, DOMAIN

_LOGGER = logging.getLogger(__name__)

DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_EMAIL): str,
vol.Required(CONF_PASSWORD): str,
vol.Required(
CONF_METRIC_VALUES,
default=True,
): selector.BooleanSelector(),
}
)


class ToyotaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Toyota Connected Services."""

VERSION = 1

def __init__(self):
"""Start the toyota custom component config flow."""
self._reauth_entry = None
self._email = None
self._metric_values = True

async def async_step_user(self, user_input=None) -> FlowResult:
"""Handle the initial step."""
errors = {}

if user_input is not None:
await self.async_set_unique_id(user_input[CONF_EMAIL].lower())
self._email = user_input[CONF_EMAIL]
self._metric_values = user_input[CONF_METRIC_VALUES]
unique_id = user_input[CONF_EMAIL].lower()

try:
client = MyT(
username=user_input[CONF_EMAIL],
password=user_input[CONF_PASSWORD],
)
client = MyT(
username=user_input[CONF_EMAIL],
password=user_input[CONF_PASSWORD],
)

await self.async_set_unique_id(unique_id)
if not self._reauth_entry:
self._abort_if_unique_id_configured()
try:
await client.login()

except ToyotaLoginError as ex:
errors["base"] = "invalid_auth"
_LOGGER.error(ex)
Expand All @@ -57,29 +55,34 @@ async def async_step_user(self, user_input=None) -> FlowResult:
errors["base"] = "unknown"
_LOGGER.error("An unknown error occurred during login request: %s", ex)
else:
return self.async_create_entry(title=user_input[CONF_EMAIL], data=user_input)

return self.async_show_form(step_id="user", data_schema=DATA_SCHEMA, errors=errors)

@staticmethod
@callback
def async_get_options_flow(config_entry):
"""Get async options flow."""
return ToyotaOptionsFlowHandler(config_entry)


class ToyotaOptionsFlowHandler(config_entries.OptionsFlow):
"""Config flow options handler for Toyota Connected Services."""

def __init__(self, config_entry):
"""Initialize options flow."""
self.config_entry = config_entry
self.options = dict(config_entry.options)

async def async_step_init(self, user_input=None) -> FlowResult:
"""Manage the options."""
if user_input is not None:
self.options.update(user_input)
return self.async_create_entry(
title=self.config_entry.data.get(CONF_EMAIL), data=self.options
)
if not self._reauth_entry:
return self.async_create_entry(title=user_input[CONF_EMAIL], data=user_input)
self.hass.config_entries.async_update_entry(
self._reauth_entry, data=user_input, unique_id=unique_id
)
# Reload the config entry otherwise devices will remain unavailable
self.hass.async_create_task(
self.hass.config_entries.async_reload(self._reauth_entry.entry_id)
)
return self.async_abort(reason="reauth_successful")

return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_EMAIL, default=self._email): str,
vol.Required(CONF_PASSWORD): str,
vol.Required(
CONF_METRIC_VALUES, default=self._metric_values
): selector.BooleanSelector(),
}
),
errors=errors,
)

async def async_step_reauth(self, entry_data: Mapping[str, Any]) -> FlowResult:
"""Perform reauth if the user credentials have changed."""
self._reauth_entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
self._email = entry_data[CONF_EMAIL]
self._metric_values = entry_data[CONF_METRIC_VALUES]
return await self.async_step_user()
1 change: 1 addition & 0 deletions custom_components/toyota/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
self.vehicle = self.coordinator.data[self.index]["data"]
self.statistics = self.coordinator.data[self.index]["statistics"]
self.metric_values = self.coordinator.data[self.index]["metric_values"]
super()._handle_coordinator_update()

async def async_added_to_hass(self) -> None:
Expand Down
Loading

0 comments on commit f602a1b

Please sign in to comment.