2024-01-25 11:54:47 +00:00
|
|
|
"""Teslemetry Data Coordinator."""
|
2024-03-08 15:35:23 +00:00
|
|
|
|
2024-05-27 10:37:33 +00:00
|
|
|
from datetime import datetime, timedelta
|
2024-01-25 11:54:47 +00:00
|
|
|
from typing import Any
|
|
|
|
|
2024-03-04 17:42:56 +00:00
|
|
|
from tesla_fleet_api import EnergySpecific, VehicleSpecific
|
2024-03-11 21:17:42 +00:00
|
|
|
from tesla_fleet_api.const import VehicleDataEndpoint
|
2024-04-08 07:44:51 +00:00
|
|
|
from tesla_fleet_api.exceptions import (
|
2024-05-27 10:37:33 +00:00
|
|
|
Forbidden,
|
2024-04-08 07:44:51 +00:00
|
|
|
InvalidToken,
|
|
|
|
SubscriptionRequired,
|
|
|
|
TeslaFleetError,
|
|
|
|
VehicleOffline,
|
|
|
|
)
|
2024-01-25 11:54:47 +00:00
|
|
|
|
|
|
|
from homeassistant.core import HomeAssistant
|
2024-05-10 08:52:33 +00:00
|
|
|
from homeassistant.exceptions import ConfigEntryAuthFailed
|
2024-01-25 11:54:47 +00:00
|
|
|
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
|
|
|
|
|
|
|
from .const import LOGGER, TeslemetryState
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
VEHICLE_INTERVAL = timedelta(seconds=30)
|
2024-05-27 10:37:33 +00:00
|
|
|
VEHICLE_WAIT = timedelta(minutes=15)
|
2024-05-10 08:52:33 +00:00
|
|
|
ENERGY_LIVE_INTERVAL = timedelta(seconds=30)
|
|
|
|
ENERGY_INFO_INTERVAL = timedelta(seconds=30)
|
|
|
|
|
2024-03-11 21:17:42 +00:00
|
|
|
ENDPOINTS = [
|
|
|
|
VehicleDataEndpoint.CHARGE_STATE,
|
|
|
|
VehicleDataEndpoint.CLIMATE_STATE,
|
|
|
|
VehicleDataEndpoint.DRIVE_STATE,
|
|
|
|
VehicleDataEndpoint.LOCATION_DATA,
|
|
|
|
VehicleDataEndpoint.VEHICLE_STATE,
|
2024-03-24 08:29:10 +00:00
|
|
|
VehicleDataEndpoint.VEHICLE_CONFIG,
|
2024-03-11 21:17:42 +00:00
|
|
|
]
|
2024-01-25 11:54:47 +00:00
|
|
|
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
def flatten(data: dict[str, Any], parent: str | None = None) -> dict[str, Any]:
|
|
|
|
"""Flatten the data structure."""
|
|
|
|
result = {}
|
|
|
|
for key, value in data.items():
|
|
|
|
if parent:
|
|
|
|
key = f"{parent}_{key}"
|
|
|
|
if isinstance(value, dict):
|
|
|
|
result.update(flatten(value, key))
|
|
|
|
else:
|
|
|
|
result[key] = value
|
|
|
|
return result
|
|
|
|
|
2024-03-04 17:42:56 +00:00
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
class TeslemetryVehicleDataCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
|
|
|
"""Class to manage fetching data from the Teslemetry API."""
|
|
|
|
|
2024-05-24 06:55:27 +00:00
|
|
|
updated_once: bool
|
2024-05-27 10:37:33 +00:00
|
|
|
pre2021: bool
|
|
|
|
last_active: datetime
|
2024-01-25 11:54:47 +00:00
|
|
|
|
2024-03-04 17:42:56 +00:00
|
|
|
def __init__(
|
2024-05-10 08:52:33 +00:00
|
|
|
self, hass: HomeAssistant, api: VehicleSpecific, product: dict
|
2024-03-04 17:42:56 +00:00
|
|
|
) -> None:
|
|
|
|
"""Initialize Teslemetry Vehicle Update Coordinator."""
|
2024-01-25 11:54:47 +00:00
|
|
|
super().__init__(
|
|
|
|
hass,
|
|
|
|
LOGGER,
|
2024-05-10 08:52:33 +00:00
|
|
|
name="Teslemetry Vehicle",
|
|
|
|
update_interval=VEHICLE_INTERVAL,
|
2024-01-25 11:54:47 +00:00
|
|
|
)
|
|
|
|
self.api = api
|
2024-05-10 08:52:33 +00:00
|
|
|
self.data = flatten(product)
|
2024-05-24 06:55:27 +00:00
|
|
|
self.updated_once = False
|
2024-05-27 10:37:33 +00:00
|
|
|
self.last_active = datetime.now()
|
2024-01-25 11:54:47 +00:00
|
|
|
|
|
|
|
async def _async_update_data(self) -> dict[str, Any]:
|
|
|
|
"""Update vehicle data using Teslemetry API."""
|
2024-05-27 10:37:33 +00:00
|
|
|
|
|
|
|
self.update_interval = VEHICLE_INTERVAL
|
|
|
|
|
2024-01-25 11:54:47 +00:00
|
|
|
try:
|
2024-05-10 08:52:33 +00:00
|
|
|
data = (await self.api.vehicle_data(endpoints=ENDPOINTS))["response"]
|
2024-01-25 11:54:47 +00:00
|
|
|
except VehicleOffline:
|
|
|
|
self.data["state"] = TeslemetryState.OFFLINE
|
|
|
|
return self.data
|
2024-04-08 07:44:51 +00:00
|
|
|
except InvalidToken as e:
|
|
|
|
raise ConfigEntryAuthFailed from e
|
|
|
|
except SubscriptionRequired as e:
|
|
|
|
raise ConfigEntryAuthFailed from e
|
2024-01-25 11:54:47 +00:00
|
|
|
except TeslaFleetError as e:
|
|
|
|
raise UpdateFailed(e.message) from e
|
|
|
|
|
2024-05-24 06:55:27 +00:00
|
|
|
self.updated_once = True
|
2024-05-27 10:37:33 +00:00
|
|
|
|
|
|
|
if self.api.pre2021 and data["state"] == TeslemetryState.ONLINE:
|
|
|
|
# Handle pre-2021 vehicles which cannot sleep by themselves
|
|
|
|
if (
|
|
|
|
data["charge_state"].get("charging_state") == "Charging"
|
|
|
|
or data["vehicle_state"].get("is_user_present")
|
|
|
|
or data["vehicle_state"].get("sentry_mode")
|
|
|
|
):
|
|
|
|
# Vehicle is active, reset timer
|
|
|
|
self.last_active = datetime.now()
|
|
|
|
else:
|
|
|
|
elapsed = datetime.now() - self.last_active
|
|
|
|
if elapsed > timedelta(minutes=20):
|
|
|
|
# Vehicle didn't sleep, try again in 15 minutes
|
|
|
|
self.last_active = datetime.now()
|
|
|
|
elif elapsed > timedelta(minutes=15):
|
|
|
|
# Let vehicle go to sleep now
|
|
|
|
self.update_interval = VEHICLE_WAIT
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
return flatten(data)
|
2024-03-04 17:42:56 +00:00
|
|
|
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
class TeslemetryEnergySiteLiveCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
|
|
|
"""Class to manage fetching energy site live status from the Teslemetry API."""
|
2024-03-04 17:42:56 +00:00
|
|
|
|
2024-05-24 06:55:27 +00:00
|
|
|
updated_once: bool
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
def __init__(self, hass: HomeAssistant, api: EnergySpecific) -> None:
|
|
|
|
"""Initialize Teslemetry Energy Site Live coordinator."""
|
|
|
|
super().__init__(
|
|
|
|
hass,
|
|
|
|
LOGGER,
|
|
|
|
name="Teslemetry Energy Site Live",
|
|
|
|
update_interval=ENERGY_LIVE_INTERVAL,
|
|
|
|
)
|
|
|
|
self.api = api
|
2024-03-04 17:42:56 +00:00
|
|
|
|
|
|
|
async def _async_update_data(self) -> dict[str, Any]:
|
|
|
|
"""Update energy site data using Teslemetry API."""
|
|
|
|
|
|
|
|
try:
|
2024-05-10 08:52:33 +00:00
|
|
|
data = (await self.api.live_status())["response"]
|
2024-05-27 10:37:33 +00:00
|
|
|
except (InvalidToken, Forbidden, SubscriptionRequired) as e:
|
2024-04-08 07:44:51 +00:00
|
|
|
raise ConfigEntryAuthFailed from e
|
2024-03-04 17:42:56 +00:00
|
|
|
except TeslaFleetError as e:
|
|
|
|
raise UpdateFailed(e.message) from e
|
|
|
|
|
|
|
|
# Convert Wall Connectors from array to dict
|
2024-05-10 08:52:33 +00:00
|
|
|
data["wall_connectors"] = {
|
|
|
|
wc["din"]: wc for wc in (data.get("wall_connectors") or [])
|
2024-03-04 17:42:56 +00:00
|
|
|
}
|
|
|
|
|
2024-05-10 08:52:33 +00:00
|
|
|
return data
|
2024-05-10 10:38:20 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TeslemetryEnergySiteInfoCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
|
|
|
"""Class to manage fetching energy site info from the Teslemetry API."""
|
|
|
|
|
2024-05-24 06:55:27 +00:00
|
|
|
updated_once: bool
|
|
|
|
|
2024-05-10 10:38:20 +00:00
|
|
|
def __init__(self, hass: HomeAssistant, api: EnergySpecific, product: dict) -> None:
|
|
|
|
"""Initialize Teslemetry Energy Info coordinator."""
|
|
|
|
super().__init__(
|
|
|
|
hass,
|
|
|
|
LOGGER,
|
|
|
|
name="Teslemetry Energy Site Info",
|
|
|
|
update_interval=ENERGY_INFO_INTERVAL,
|
|
|
|
)
|
|
|
|
self.api = api
|
|
|
|
self.data = product
|
|
|
|
|
|
|
|
async def _async_update_data(self) -> dict[str, Any]:
|
|
|
|
"""Update energy site data using Teslemetry API."""
|
|
|
|
|
|
|
|
try:
|
|
|
|
data = (await self.api.site_info())["response"]
|
2024-05-27 10:37:33 +00:00
|
|
|
except (InvalidToken, Forbidden, SubscriptionRequired) as e:
|
2024-05-10 10:38:20 +00:00
|
|
|
raise ConfigEntryAuthFailed from e
|
|
|
|
except TeslaFleetError as e:
|
|
|
|
raise UpdateFailed(e.message) from e
|
|
|
|
|
|
|
|
return flatten(data)
|