2024-01-25 11:54:47 +00:00
|
|
|
"""Teslemetry parent entity class."""
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
from abc import abstractmethod
|
2024-01-25 11:54:47 +00:00
|
|
|
import asyncio
|
|
|
|
from typing import Any
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
from tesla_fleet_api import EnergySpecific, VehicleSpecific
|
2024-02-22 09:50:44 +00:00
|
|
|
from tesla_fleet_api.exceptions import TeslaFleetError
|
|
|
|
|
2024-04-23 20:11:41 +00:00
|
|
|
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
|
2024-01-25 11:54:47 +00:00
|
|
|
from homeassistant.helpers.device_registry import DeviceInfo
|
|
|
|
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
from .const import DOMAIN, LOGGER, TeslemetryState
|
2024-03-04 17:42:56 +00:00
|
|
|
from .coordinator import (
|
2024-05-10 10:38:20 +00:00
|
|
|
TeslemetryEnergySiteInfoCoordinator,
|
2024-05-10 08:52:33 +00:00
|
|
|
TeslemetryEnergySiteLiveCoordinator,
|
2024-03-04 17:42:56 +00:00
|
|
|
TeslemetryVehicleDataCoordinator,
|
|
|
|
)
|
|
|
|
from .models import TeslemetryEnergyData, TeslemetryVehicleData
|
2024-01-25 11:54:47 +00:00
|
|
|
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
class TeslemetryEntity(
|
|
|
|
CoordinatorEntity[
|
2024-05-10 10:38:20 +00:00
|
|
|
TeslemetryVehicleDataCoordinator
|
|
|
|
| TeslemetryEnergySiteLiveCoordinator
|
|
|
|
| TeslemetryEnergySiteInfoCoordinator
|
2024-05-10 08:52:33 +00:00
|
|
|
]
|
|
|
|
):
|
|
|
|
"""Parent class for all Teslemetry entities."""
|
2024-01-25 11:54:47 +00:00
|
|
|
|
|
|
|
_attr_has_entity_name = True
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
2024-05-10 08:52:33 +00:00
|
|
|
coordinator: TeslemetryVehicleDataCoordinator
|
2024-05-10 10:38:20 +00:00
|
|
|
| TeslemetryEnergySiteLiveCoordinator
|
|
|
|
| TeslemetryEnergySiteInfoCoordinator,
|
2024-05-10 08:52:33 +00:00
|
|
|
api: VehicleSpecific | EnergySpecific,
|
2024-01-25 11:54:47 +00:00
|
|
|
key: str,
|
|
|
|
) -> None:
|
|
|
|
"""Initialize common aspects of a Teslemetry entity."""
|
2024-05-10 08:52:33 +00:00
|
|
|
super().__init__(coordinator)
|
|
|
|
self.api = api
|
2024-01-25 11:54:47 +00:00
|
|
|
self.key = key
|
2024-05-10 08:52:33 +00:00
|
|
|
self._attr_translation_key = self.key
|
|
|
|
self._async_update_attrs()
|
2024-01-25 11:54:47 +00:00
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
@property
|
|
|
|
def available(self) -> bool:
|
|
|
|
"""Return if sensor is available."""
|
|
|
|
return self.coordinator.last_update_success and self._attr_available
|
2024-01-25 11:54:47 +00:00
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
@property
|
|
|
|
def _value(self) -> Any | None:
|
|
|
|
"""Return a specific value from coordinator data."""
|
|
|
|
return self.coordinator.data.get(self.key)
|
|
|
|
|
|
|
|
def get(self, key: str, default: Any | None = None) -> Any | None:
|
|
|
|
"""Return a specific value from coordinator data."""
|
|
|
|
return self.coordinator.data.get(key, default)
|
|
|
|
|
2024-05-26 09:02:35 +00:00
|
|
|
def get_number(self, key: str, default: float) -> float:
|
|
|
|
"""Return a specific number from coordinator data."""
|
|
|
|
if isinstance(value := self.coordinator.data.get(key), (int, float)):
|
|
|
|
return value
|
|
|
|
return default
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
@property
|
|
|
|
def is_none(self) -> bool:
|
|
|
|
"""Return if the value is a literal None."""
|
|
|
|
return self.get(self.key, False) is None
|
|
|
|
|
|
|
|
@property
|
|
|
|
def has(self) -> bool:
|
|
|
|
"""Return True if a specific value is in coordinator data."""
|
|
|
|
return self.key in self.coordinator.data
|
|
|
|
|
|
|
|
async def handle_command(self, command) -> dict[str, Any]:
|
|
|
|
"""Handle a command."""
|
|
|
|
try:
|
|
|
|
result = await command
|
|
|
|
except TeslaFleetError as e:
|
|
|
|
raise HomeAssistantError(f"Teslemetry command failed, {e.message}") from e
|
2024-05-13 02:37:59 +00:00
|
|
|
LOGGER.debug("Command result: %s", result)
|
2024-05-10 08:52:33 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
def _handle_coordinator_update(self) -> None:
|
|
|
|
"""Handle updated data from the coordinator."""
|
|
|
|
self._async_update_attrs()
|
|
|
|
self.async_write_ha_state()
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def _async_update_attrs(self) -> None:
|
|
|
|
"""Update the attributes of the entity."""
|
|
|
|
|
2024-05-15 16:17:28 +00:00
|
|
|
def raise_for_scope(self):
|
|
|
|
"""Raise an error if a scope is not available."""
|
|
|
|
if not self.scoped:
|
|
|
|
raise ServiceValidationError("Missing required scope")
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
|
|
|
|
class TeslemetryVehicleEntity(TeslemetryEntity):
|
|
|
|
"""Parent class for Teslemetry Vehicle entities."""
|
|
|
|
|
|
|
|
_last_update: int = 0
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
data: TeslemetryVehicleData,
|
|
|
|
key: str,
|
|
|
|
) -> None:
|
|
|
|
"""Initialize common aspects of a Teslemetry entity."""
|
|
|
|
|
|
|
|
self._attr_unique_id = f"{data.vin}-{key}"
|
|
|
|
self._wakelock = data.wakelock
|
|
|
|
|
|
|
|
self._attr_device_info = data.device
|
|
|
|
super().__init__(data.coordinator, data.api, key)
|
2024-01-25 11:54:47 +00:00
|
|
|
|
2024-03-16 10:54:37 +00:00
|
|
|
@property
|
|
|
|
def _value(self) -> Any | None:
|
|
|
|
"""Return a specific value from coordinator data."""
|
|
|
|
return self.coordinator.data.get(self.key)
|
|
|
|
|
2024-01-25 11:54:47 +00:00
|
|
|
async def wake_up_if_asleep(self) -> None:
|
|
|
|
"""Wake up the vehicle if its asleep."""
|
|
|
|
async with self._wakelock:
|
2024-02-22 09:50:44 +00:00
|
|
|
times = 0
|
2024-01-25 11:54:47 +00:00
|
|
|
while self.coordinator.data["state"] != TeslemetryState.ONLINE:
|
2024-02-22 09:50:44 +00:00
|
|
|
try:
|
|
|
|
if times == 0:
|
|
|
|
cmd = await self.api.wake_up()
|
|
|
|
else:
|
|
|
|
cmd = await self.api.vehicle()
|
|
|
|
state = cmd["response"]["state"]
|
|
|
|
except TeslaFleetError as e:
|
|
|
|
raise HomeAssistantError(str(e)) from e
|
2024-01-25 11:54:47 +00:00
|
|
|
self.coordinator.data["state"] = state
|
|
|
|
if state != TeslemetryState.ONLINE:
|
2024-02-22 09:50:44 +00:00
|
|
|
times += 1
|
|
|
|
if times >= 4: # Give up after 30 seconds total
|
|
|
|
raise HomeAssistantError("Could not wake up vehicle")
|
|
|
|
await asyncio.sleep(times * 5)
|
2024-01-25 11:54:47 +00:00
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
async def handle_command(self, command) -> dict[str, Any]:
|
|
|
|
"""Handle a vehicle command."""
|
|
|
|
result = await super().handle_command(command)
|
|
|
|
if (response := result.get("response")) is None:
|
2024-05-13 02:37:59 +00:00
|
|
|
if error := result.get("error"):
|
2024-05-10 08:52:33 +00:00
|
|
|
# No response with error
|
2024-05-13 02:37:59 +00:00
|
|
|
raise HomeAssistantError(error)
|
2024-05-10 08:52:33 +00:00
|
|
|
# No response without error (unexpected)
|
2024-05-13 02:37:59 +00:00
|
|
|
raise HomeAssistantError(f"Unknown response: {response}")
|
|
|
|
if (result := response.get("result")) is not True:
|
|
|
|
if reason := response.get("reason"):
|
|
|
|
if reason in ("already_set", "not_charging", "requested"):
|
|
|
|
# Reason is acceptable
|
|
|
|
return result
|
2024-05-10 08:52:33 +00:00
|
|
|
# Result of false with reason
|
2024-05-13 02:37:59 +00:00
|
|
|
raise HomeAssistantError(reason)
|
2024-05-10 08:52:33 +00:00
|
|
|
# Result of false without reason (unexpected)
|
2024-05-13 02:37:59 +00:00
|
|
|
raise HomeAssistantError("Command failed with no reason")
|
2024-05-10 08:52:33 +00:00
|
|
|
# Response with result of true
|
|
|
|
return result
|
2024-03-04 17:42:56 +00:00
|
|
|
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
class TeslemetryEnergyLiveEntity(TeslemetryEntity):
|
|
|
|
"""Parent class for Teslemetry Energy Site Live entities."""
|
2024-03-04 17:42:56 +00:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
2024-05-10 08:52:33 +00:00
|
|
|
data: TeslemetryEnergyData,
|
2024-03-04 17:42:56 +00:00
|
|
|
key: str,
|
|
|
|
) -> None:
|
2024-05-10 08:52:33 +00:00
|
|
|
"""Initialize common aspects of a Teslemetry Energy Site Live entity."""
|
|
|
|
self._attr_unique_id = f"{data.id}-{key}"
|
|
|
|
self._attr_device_info = data.device
|
2024-03-04 17:42:56 +00:00
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
super().__init__(data.live_coordinator, data.api, key)
|
2024-03-04 17:42:56 +00:00
|
|
|
|
|
|
|
|
2024-05-10 10:38:20 +00:00
|
|
|
class TeslemetryEnergyInfoEntity(TeslemetryEntity):
|
|
|
|
"""Parent class for Teslemetry Energy Site Info Entities."""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
data: TeslemetryEnergyData,
|
|
|
|
key: str,
|
|
|
|
) -> None:
|
|
|
|
"""Initialize common aspects of a Teslemetry Energy Site Info entity."""
|
|
|
|
self._attr_unique_id = f"{data.id}-{key}"
|
|
|
|
self._attr_device_info = data.device
|
|
|
|
|
|
|
|
super().__init__(data.info_coordinator, data.api, key)
|
|
|
|
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
class TeslemetryWallConnectorEntity(
|
|
|
|
TeslemetryEntity, CoordinatorEntity[TeslemetryEnergySiteLiveCoordinator]
|
|
|
|
):
|
2024-03-04 17:42:56 +00:00
|
|
|
"""Parent class for Teslemetry Wall Connector Entities."""
|
|
|
|
|
|
|
|
_attr_has_entity_name = True
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
2024-05-10 08:52:33 +00:00
|
|
|
data: TeslemetryEnergyData,
|
2024-03-04 17:42:56 +00:00
|
|
|
din: str,
|
|
|
|
key: str,
|
|
|
|
) -> None:
|
|
|
|
"""Initialize common aspects of a Teslemetry entity."""
|
|
|
|
self.din = din
|
2024-05-10 08:52:33 +00:00
|
|
|
self._attr_unique_id = f"{data.id}-{din}-{key}"
|
2024-03-04 17:42:56 +00:00
|
|
|
self._attr_device_info = DeviceInfo(
|
|
|
|
identifiers={(DOMAIN, din)},
|
|
|
|
manufacturer="Tesla",
|
|
|
|
configuration_url="https://teslemetry.com/console",
|
|
|
|
name="Wall Connector",
|
2024-05-10 08:52:33 +00:00
|
|
|
via_device=(DOMAIN, str(data.id)),
|
2024-03-04 17:42:56 +00:00
|
|
|
serial_number=din.split("-")[-1],
|
|
|
|
)
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
super().__init__(data.live_coordinator, data.api, key)
|
|
|
|
|
2024-03-04 17:42:56 +00:00
|
|
|
@property
|
|
|
|
def _value(self) -> int:
|
|
|
|
"""Return a specific wall connector value from coordinator data."""
|
2024-05-10 08:52:33 +00:00
|
|
|
return (
|
|
|
|
self.coordinator.data.get("wall_connectors", {})
|
|
|
|
.get(self.din, {})
|
|
|
|
.get(self.key)
|
|
|
|
)
|