Skip to content

Commit

Permalink
Add entity fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Bre77 committed Jan 31, 2024
1 parent d724b68 commit dac9e28
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 71 deletions.
85 changes: 15 additions & 70 deletions custom_components/teslemetry/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@
import asyncio
from typing import Any

from tesla_fleet_api.exceptions import TeslaFleetError

from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN, MODELS, TeslemetryState
from .coordinator import (
TeslemetryEnergyDataCoordinator,
TeslemetryVehicleDataCoordinator,
)
from .models import TeslemetryEnergyData, TeslemetryVehicleData
from .coordinator import TeslemetryVehicleDataCoordinator
from .models import TeslemetryVehicleData


class TeslemetryVehicleEntity(CoordinatorEntity[TeslemetryVehicleDataCoordinator]):
"""Parent class for Teslemetry Vehicle Entities."""
"""Parent class for Teslemetry Entities."""

_attr_has_entity_name = True

Expand Down Expand Up @@ -48,11 +48,18 @@ def __init__(
async def wake_up_if_asleep(self) -> None:
"""Wake up the vehicle if its asleep."""
async with self._wakelock:
wait = 0
while self.coordinator.data["state"] != TeslemetryState.ONLINE:
state = (await self.api.wake_up())["response"]["state"]
try:
state = (await self.api.wake_up())["response"]["state"]
except TeslaFleetError as err:
raise HomeAssistantError(str(err)) from err
self.coordinator.data["state"] = state
if state != TeslemetryState.ONLINE:
await asyncio.sleep(5)
wait += 5
if wait >= 15: # Give up after 30 seconds total
raise HomeAssistantError("Could not wake up vehicle")
await asyncio.sleep(wait)

def get(self, key: str | None = None, default: Any | None = None) -> Any:
"""Return a specific value from coordinator data."""
Expand All @@ -63,65 +70,3 @@ def set(self, *args: Any) -> None:
for key, value in args:
self.coordinator.data[key] = value
self.async_write_ha_state()


class TeslemetryEnergyEntity(CoordinatorEntity[TeslemetryEnergyDataCoordinator]):
"""Parent class for Teslemetry Energy Entities."""

_attr_has_entity_name = True

def __init__(
self,
energysite: TeslemetryEnergyData,
key: str,
) -> None:
"""Initialize common aspects of a Teslemetry entity."""
super().__init__(energysite.coordinator)
self.key = key
self.api = energysite.api

self._attr_translation_key = key
self._attr_unique_id = f"{energysite.id}-{key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, str(energysite.id))},
manufacturer="Tesla",
configuration_url="https://teslemetry.com/console",
name=self.coordinator.data.get("site_name", "Energy Site"),
)

def get(self, key: str | None = None, default: Any | None = None) -> Any:
"""Return a specific value from coordinator data."""
return self.coordinator.data.get(key or self.key, default)


class TeslemetryWallConnectorEntity(CoordinatorEntity[TeslemetryEnergyDataCoordinator]):
"""Parent class for Teslemetry Wall Connector Entities."""

_attr_has_entity_name = True

def __init__(
self,
energysite: TeslemetryEnergyData,
din: str,
key: str,
) -> None:
"""Initialize common aspects of a Teslemetry entity."""
super().__init__(energysite.coordinator)
self.din = din
self.key = key

self._attr_translation_key = key
self._attr_unique_id = f"{energysite.id}-{din}-{key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, din)},
manufacturer="Tesla",
configuration_url="https://teslemetry.com/console",
name="Wall Connector",
via_device=(DOMAIN, str(energysite.id)),
serial_number=din.split("-")[-1],
)

@property
def _value(self) -> int:
"""Return a specific wall connector value from coordinator data."""
return self.coordinator.data["wall_connectors"][self.din].get(self.key)
2 changes: 1 addition & 1 deletion custom_components/teslemetry/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
@callback
def minutes_to_datetime(value: StateType) -> datetime | None:
"""Convert relative hours into absolute datetime."""
if isinstance(value, (int, float)) and value > 0:
if isinstance(value, int | float) and value > 0:
return dt_util.now() + timedelta(minutes=value)
return None

Expand Down

0 comments on commit dac9e28

Please sign in to comment.