Skip to content

Commit

Permalink
fix black
Browse files Browse the repository at this point in the history
  • Loading branch information
robinostlund committed Jan 29, 2024
1 parent bb65c96 commit 34112c8
Show file tree
Hide file tree
Showing 15 changed files with 88 additions and 269 deletions.
79 changes: 19 additions & 60 deletions custom_components/volkswagencarnet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,21 +151,15 @@ def is_new(attr):
return attr not in entry.options.get(CONF_AVAILABLE_RESOURCES, [attr])

components = set()
for instrument in (
instrument for instrument in instruments if instrument.component in COMPONENTS
):
for instrument in (instrument for instrument in instruments if instrument.component in COMPONENTS):
# Add resource if it's enabled or new
if is_enabled(instrument.slug_attr) or (
is_new(instrument.slug_attr) and not entry.pref_disable_new_entities
):
if is_enabled(instrument.slug_attr) or (is_new(instrument.slug_attr) and not entry.pref_disable_new_entities):
data.instruments.add(instrument)
components.add(COMPONENTS[instrument.component])

for component in components:
coordinator.platforms.append(component)
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
hass.async_create_task(hass.config_entries.async_forward_entry_setup(entry, component))

hass.data[DOMAIN][entry.entry_id] = {
UPDATE_CALLBACK: update_callback,
Expand Down Expand Up @@ -259,9 +253,7 @@ async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> boo
class VolkswagenData:
"""Hold component state."""

def __init__(
self, config: dict, coordinator: Optional[DataUpdateCoordinator] = None
):
def __init__(self, config: dict, coordinator: Optional[DataUpdateCoordinator] = None):
"""Initialize the component state."""
self.vehicles: set[Vehicle] = set()
self.instruments: set[Instrument] = set()
Expand All @@ -274,21 +266,13 @@ def instrument(self, vin: str, component: str, attr: str) -> Instrument:
ret = next(
(
instrument
for instrument in (
self.coordinator.data
if self.coordinator is not None
else self.instruments
)
if instrument.vehicle.vin == vin
and instrument.component == component
and instrument.attr == attr
for instrument in (self.coordinator.data if self.coordinator is not None else self.instruments)
if instrument.vehicle.vin == vin and instrument.component == component and instrument.attr == attr
),
None,
)
if ret is None:
raise ValueError(
f"Instrument not found; component: {component}, attribute: {attr}"
)
raise ValueError(f"Instrument not found; component: {component}, attribute: {attr}")
return ret

def vehicle_name(self, vehicle: Vehicle) -> str:
Expand Down Expand Up @@ -364,15 +348,12 @@ def async_write_ha_state(self) -> None:
# but the stored one is a string... sigh)
if (
prev is None
or str(prev.attributes.get("last_updated", None))
!= str(backend_refresh_time)
or str(prev.attributes.get("last_updated", None)) != str(backend_refresh_time)
or str(self.state or STATE_UNKNOWN) != str(prev.state)
):
super().async_write_ha_state()
else:
_LOGGER.debug(
f"{self.name}: state not changed ('{prev.state}' == '{self.state}'), skipping update."
)
_LOGGER.debug(f"{self.name}: state not changed ('{prev.state}' == '{self.state}'), skipping update.")

@callback
def _handle_coordinator_update(self) -> None:
Expand All @@ -396,32 +377,22 @@ async def async_added_to_hass(self) -> None:
"""Register update dispatcher."""
self.restored_state = await self.async_get_last_state()
if self.coordinator is not None:
self.async_on_remove(
self.coordinator.async_add_listener(self.async_write_ha_state)
)
self.async_on_remove(self.coordinator.async_add_listener(self.async_write_ha_state))
else:
self.async_on_remove(
async_dispatcher_connect(
self.hass, SIGNAL_STATE_UPDATED, self.async_write_ha_state
)
)
self.async_on_remove(async_dispatcher_connect(self.hass, SIGNAL_STATE_UPDATED, self.async_write_ha_state))

@property
def instrument(
self,
) -> Union[
BinarySensor, Climate, DoorLock, Position, Sensor, Switch, TrunkLock, Instrument
]:
) -> Union[BinarySensor, Climate, DoorLock, Position, Sensor, Switch, TrunkLock, Instrument]:
"""Return corresponding instrument."""
return self.data.instrument(self.vin, self.component, self.attribute)

@property
def icon(self) -> Optional[str]:
"""Return the icon."""
if self.instrument.attr in ["battery_level", "charging"]:
return icon_for_battery_level(
battery_level=self.instrument.state, charging=self.vehicle.charging
)
return icon_for_battery_level(battery_level=self.instrument.state, charging=self.vehicle.charging)
else:
return self.instrument.icon

Expand Down Expand Up @@ -501,9 +472,7 @@ def notify_updated(self):
class VolkswagenCoordinator(DataUpdateCoordinator):
"""Class to manage fetching data from the API."""

def __init__(
self, hass: HomeAssistant, entry: ConfigEntry, update_interval: timedelta
):
def __init__(self, hass: HomeAssistant, entry: ConfigEntry, update_interval: timedelta):
"""Initialize the coordinator."""
self.vin = entry.data[CONF_VEHICLE].upper()
self.entry = entry
Expand All @@ -513,19 +482,15 @@ def __init__(
session=async_get_clientsession(hass),
username=self.entry.data[CONF_USERNAME],
password=self.entry.data[CONF_PASSWORD],
fulldebug=self.entry.options.get(
CONF_DEBUG, self.entry.data.get(CONF_DEBUG, DEFAULT_DEBUG)
),
fulldebug=self.entry.options.get(CONF_DEBUG, self.entry.data.get(CONF_DEBUG, DEFAULT_DEBUG)),
country=self.entry.options.get(CONF_REGION, self.entry.data[CONF_REGION]),
)

super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)

def async_update_listener(self) -> None:
"""Listen for update events."""
_LOGGER.debug(
f"Async update finished for {self.vin} ({self.name}). Next update in {self.update_interval}."
)
_LOGGER.debug(f"Async update finished for {self.vin} ({self.name}). Next update in {self.update_interval}.")

async def _async_update_data(self) -> list[Instrument]:
"""Update data via library."""
Expand All @@ -537,14 +502,10 @@ async def _async_update_data(self) -> list[Instrument]:
"Try logging in to the portal: https://www.portal.volkswagen-we.com/"
)

if self.entry.options.get(
CONF_REPORT_REQUEST, self.entry.data.get(CONF_REPORT_REQUEST, False)
):
if self.entry.options.get(CONF_REPORT_REQUEST, self.entry.data.get(CONF_REPORT_REQUEST, False)):
await self.report_request(vehicle)

convert_conf = self.entry.options.get(
CONF_CONVERT, self.entry.data.get(CONF_CONVERT, CONF_NO_CONVERSION)
)
convert_conf = self.entry.options.get(CONF_CONVERT, self.entry.data.get(CONF_CONVERT, CONF_NO_CONVERSION))

dashboard = vehicle.dashboard(
mutable=self.entry.data.get(CONF_MUTABLE),
Expand Down Expand Up @@ -600,9 +561,7 @@ async def report_request(self, vehicle: Vehicle) -> None:
"""Request car to report itself an update to Volkswagen WeConnect."""
report_interval = self.entry.options.get(
CONF_REPORT_SCAN_INTERVAL,
self.entry.data.get(
CONF_REPORT_SCAN_INTERVAL, DEFAULT_REPORT_UPDATE_INTERVAL
),
self.entry.data.get(CONF_REPORT_SCAN_INTERVAL, DEFAULT_REPORT_UPDATE_INTERVAL),
)

if not self.report_last_updated:
Expand Down
10 changes: 2 additions & 8 deletions custom_components/volkswagencarnet/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@
_LOGGER = logging.getLogger(__name__)


async def async_setup_platform(
hass: HomeAssistant, config: ConfigEntry, async_add_entities, discovery_info=None
):
async def async_setup_platform(hass: HomeAssistant, config: ConfigEntry, async_add_entities, discovery_info=None):
"""Set up the Volkswagen binary sensors platform."""
if discovery_info is None:
return
Expand All @@ -39,11 +37,7 @@ async def async_setup_entry(hass, entry, async_add_devices):
attribute=instrument.attr,
callback=hass.data[DOMAIN][entry.entry_id][UPDATE_CALLBACK],
)
for instrument in (
instrument
for instrument in data.instruments
if instrument.component == "binary_sensor"
)
for instrument in (instrument for instrument in data.instruments if instrument.component == "binary_sensor")
)

return True
Expand Down
6 changes: 1 addition & 5 deletions custom_components/volkswagencarnet/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,7 @@ async def async_setup_entry(hass, entry, async_add_devices):
component=instrument.component,
attribute=instrument.attr,
)
for instrument in (
instrument
for instrument in data.instruments
if instrument.component == "climate"
)
for instrument in (instrument for instrument in data.instruments if instrument.component == "climate")
)

return True
Expand Down
77 changes: 20 additions & 57 deletions custom_components/volkswagencarnet/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,7 @@ async def async_step_user(self, user_input=None):

return await self.async_step_login()

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

# noinspection PyBroadException
async def _async_task_login(self):
Expand All @@ -100,9 +98,7 @@ async def _async_task_login(self):
if not self._connection.logged_in:
self._errors["base"] = "cannot_connect"

self.hass.async_create_task(
self.hass.config_entries.flow.async_configure(flow_id=self.flow_id)
)
self.hass.async_create_task(self.hass.config_entries.flow.async_configure(flow_id=self.flow_id))

async def async_step_select_vehicle(self, user_input=None):
if user_input is not None:
Expand All @@ -119,9 +115,7 @@ async def async_step_select_vehicle(self, user_input=None):

async def async_step_select_instruments(self, user_input=None):
instruments = self._init_info["CONF_VEHICLES"][self._init_info[CONF_VEHICLE]]
instruments_dict = {
instrument.attr: instrument.name for instrument in instruments
}
instruments_dict = {instrument.attr: instrument.name for instrument in instruments}

if user_input is not None:
# self._init_info[CONF_RESOURCES] = user_input[CONF_RESOURCES]
Expand All @@ -146,11 +140,7 @@ async def async_step_select_instruments(self, user_input=None):
step_id="select_instruments",
errors=self._errors,
data_schema=vol.Schema(
{
vol.Optional(
CONF_RESOURCES, default=list(instruments_dict.keys())
): cv.multi_select(instruments_dict)
}
{vol.Optional(CONF_RESOURCES, default=list(instruments_dict.keys())): cv.multi_select(instruments_dict)}
),
last_step=True,
)
Expand All @@ -177,8 +167,7 @@ async def async_step_login(self, user_input=None):
_LOGGER.info(f"Found data for VIN: {vehicle.vin} from WeConnect")

self._init_info["CONF_VEHICLES"] = {
vehicle.vin: vehicle.dashboard().instruments
for vehicle in self._connection.vehicles
vehicle.vin: vehicle.dashboard().instruments for vehicle in self._connection.vehicles
}

return self.async_show_progress_done(next_step_id="select_vehicle")
Expand All @@ -198,12 +187,8 @@ async def async_step_reauth_confirm(self, user_input: dict = None) -> dict:
session=async_get_clientsession(self.hass),
username=user_input[CONF_USERNAME],
password=user_input[CONF_PASSWORD],
fulldebug=self.entry.options.get(
CONF_DEBUG, self.entry.data.get(CONF_DEBUG, DEFAULT_DEBUG)
),
country=self.entry.options.get(
CONF_REGION, self.entry.data[CONF_REGION]
),
fulldebug=self.entry.options.get(CONF_DEBUG, self.entry.data.get(CONF_DEBUG, DEFAULT_DEBUG)),
country=self.entry.options.get(CONF_REGION, self.entry.data[CONF_REGION]),
)

# noinspection PyBroadException
Expand All @@ -225,9 +210,7 @@ async def async_step_reauth_confirm(self, user_input: dict = None) -> dict:
CONF_PASSWORD: user_input[CONF_PASSWORD],
},
)
self.hass.async_create_task(
self.hass.config_entries.async_reload(self.entry.entry_id)
)
self.hass.async_create_task(self.hass.config_entries.async_reload(self.entry.entry_id))

return self.async_abort(reason="reauth_successful")
except Exception as e:
Expand All @@ -238,9 +221,7 @@ async def async_step_reauth_confirm(self, user_input: dict = None) -> dict:
step_id="reauth_confirm",
data_schema=vol.Schema(
{
vol.Required(
CONF_USERNAME, default=self.entry.data[CONF_USERNAME]
): str,
vol.Required(CONF_USERNAME, default=self.entry.data[CONF_USERNAME]): str,
vol.Required(CONF_PASSWORD): str,
}
),
Expand Down Expand Up @@ -296,9 +277,7 @@ async def async_step_user(self, user_input=None):
): cv.boolean,
vol.Optional(
CONF_CONVERT,
default=self._config_entry.data.get(
CONF_CONVERT, CONF_NO_CONVERSION
),
default=self._config_entry.data.get(CONF_CONVERT, CONF_NO_CONVERSION),
): vol.In(CONVERT_DICT),
vol.Optional(
CONF_REPORT_SCAN_INTERVAL,
Expand All @@ -314,16 +293,12 @@ async def async_step_user(self, user_input=None):
CONF_SCAN_INTERVAL,
default=self._config_entry.options.get(
CONF_SCAN_INTERVAL,
self._config_entry.data.get(
CONF_SCAN_INTERVAL, DEFAULT_UPDATE_INTERVAL
),
self._config_entry.data.get(CONF_SCAN_INTERVAL, DEFAULT_UPDATE_INTERVAL),
),
): cv.positive_int,
vol.Optional(
CONF_REGION,
default=self._config_entry.options.get(
CONF_REGION, self._config_entry.data[CONF_REGION]
),
default=self._config_entry.options.get(CONF_REGION, self._config_entry.data[CONF_REGION]),
): str,
}
),
Expand All @@ -336,9 +311,7 @@ async def async_step_select_instruments(self, user_input=None):
v: Vehicle = get_vehicle(coordinator=coordinator)
d = v.dashboard()

instruments_dict = {
instrument.attr: instrument.name for instrument in d.instruments
}
instruments_dict = {instrument.attr: instrument.name for instrument in d.instruments}

if user_input is not None:
options = {
Expand All @@ -347,24 +320,18 @@ async def async_step_select_instruments(self, user_input=None):
CONF_AVAILABLE_RESOURCES: instruments_dict,
}

removed_resources = set(data.get("options", {}).get("resources", {})) - set(
options[CONF_RESOURCES]
)
added_resources = set(options[CONF_RESOURCES]) - set(
data.get("options", {}).get("resources", {})
)
removed_resources = set(data.get("options", {}).get("resources", {})) - set(options[CONF_RESOURCES])
added_resources = set(options[CONF_RESOURCES]) - set(data.get("options", {}).get("resources", {}))

_LOGGER.info(
f"Adding resources: {added_resources}, removing resources: {removed_resources}"
)
_LOGGER.info(f"Adding resources: {added_resources}, removing resources: {removed_resources}")

# Need to recreate entitiesin some cases
# Some resource was removed
recreate_entities = len(removed_resources) > 0
# distance conversion was changed
recreate_entities = recreate_entities or self._data[
CONF_CONVERT
] != data.get("data", {}).get(CONF_CONVERT, "")
recreate_entities = recreate_entities or self._data[CONF_CONVERT] != data.get("data", {}).get(
CONF_CONVERT, ""
)

if recreate_entities:
entity_registry = async_get(self.hass)
Expand All @@ -389,11 +356,7 @@ async def async_step_select_instruments(self, user_input=None):
step_id="select_instruments",
errors=self._errors,
data_schema=vol.Schema(
{
vol.Optional(
CONF_RESOURCES, default=list(selected)
): cv.multi_select(instruments_dict)
}
{vol.Optional(CONF_RESOURCES, default=list(selected)): cv.multi_select(instruments_dict)}
),
last_step=True,
)
Loading

0 comments on commit 34112c8

Please sign in to comment.