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 b1335bc commit bb65c96
Show file tree
Hide file tree
Showing 14 changed files with 370 additions and 107 deletions.
92 changes: 71 additions & 21 deletions custom_components/volkswagencarnet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.icon import icon_for_battery_level
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed, CoordinatorEntity
from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator,
UpdateFailed,
CoordinatorEntity,
)
from volkswagencarnet.vw_connection import Connection
from volkswagencarnet.vw_dashboard import (
Instrument,
Expand Down Expand Up @@ -147,15 +151,21 @@ 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 @@ -249,7 +259,9 @@ 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 @@ -262,13 +274,21 @@ 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 @@ -320,7 +340,11 @@ def async_write_ha_state(self) -> None:
prev: Optional[State] = self.hass.states.get(self.entity_id)

# This is not the best place to handle this, but... :shrug:..
if self.attribute == "requests_remaining" and self.state in [-1, STATE_UNAVAILABLE, STATE_UNKNOWN]:
if self.attribute == "requests_remaining" and self.state in [
-1,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
]:
restored = prev or self.restored_state
if restored is not None:
try:
Expand All @@ -340,12 +364,15 @@ 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 @@ -369,22 +396,32 @@ 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 @@ -464,7 +501,9 @@ 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 @@ -474,15 +513,19 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry, update_interval: tim
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 @@ -494,10 +537,14 @@ 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 @@ -552,7 +599,10 @@ async def update(self) -> Optional[Vehicle]:
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)
CONF_REPORT_SCAN_INTERVAL,
self.entry.data.get(
CONF_REPORT_SCAN_INTERVAL, DEFAULT_REPORT_UPDATE_INTERVAL
),
)

if not self.report_last_updated:
Expand Down
16 changes: 13 additions & 3 deletions custom_components/volkswagencarnet/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
import logging
from typing import Union

from homeassistant.components.binary_sensor import DEVICE_CLASSES, BinarySensorEntity, BinarySensorDeviceClass
from homeassistant.components.binary_sensor import (
DEVICE_CLASSES,
BinarySensorEntity,
BinarySensorDeviceClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import EntityCategory
Expand All @@ -13,7 +17,9 @@
_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 @@ -33,7 +39,11 @@ 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
13 changes: 11 additions & 2 deletions custom_components/volkswagencarnet/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,17 @@ async def async_setup_entry(hass, entry, async_add_devices):
coordinator = data.coordinator
if coordinator.data is not None:
async_add_devices(
VolkswagenClimate(data=data, vin=coordinator.vin, component=instrument.component, attribute=instrument.attr)
for instrument in (instrument for instrument in data.instruments if instrument.component == "climate")
VolkswagenClimate(
data=data,
vin=coordinator.vin,
component=instrument.component,
attribute=instrument.attr,
)
for instrument in (
instrument
for instrument in data.instruments
if instrument.component == "climate"
)
)

return True
Expand Down
Loading

0 comments on commit bb65c96

Please sign in to comment.