Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Tesla Fleet helper functions."""
2 
3 import asyncio
4 from collections.abc import Awaitable
5 from typing import Any
6 
7 from tesla_fleet_api.exceptions import TeslaFleetError
8 
9 from homeassistant.exceptions import HomeAssistantError
10 
11 from .const import DOMAIN, LOGGER, TeslaFleetState
12 from .models import TeslaFleetVehicleData
13 
14 
15 async def wake_up_vehicle(vehicle: TeslaFleetVehicleData) -> None:
16  """Wake up a vehicle."""
17  async with vehicle.wakelock:
18  times = 0
19  while vehicle.coordinator.data["state"] != TeslaFleetState.ONLINE:
20  try:
21  if times == 0:
22  cmd = await vehicle.api.wake_up()
23  else:
24  cmd = await vehicle.api.vehicle()
25  state = cmd["response"]["state"]
26  except TeslaFleetError as e:
27  raise HomeAssistantError(str(e)) from e
28  vehicle.coordinator.data["state"] = state
29  if state != TeslaFleetState.ONLINE:
30  times += 1
31  if times >= 4: # Give up after 30 seconds total
32  raise HomeAssistantError("Could not wake up vehicle")
33  await asyncio.sleep(times * 5)
34 
35 
36 async def handle_command(command: Awaitable) -> dict[str, Any]:
37  """Handle a command."""
38  try:
39  result = await command
40  except TeslaFleetError as e:
41  raise HomeAssistantError(
42  translation_domain=DOMAIN,
43  translation_key="command_failed",
44  translation_placeholders={"message": e.message},
45  ) from e
46  LOGGER.debug("Command result: %s", result)
47  return result
48 
49 
50 async def handle_vehicle_command(command: Awaitable) -> bool:
51  """Handle a vehicle command."""
52  result = await handle_command(command)
53  if (response := result.get("response")) is None:
54  if error := result.get("error"):
55  # No response with error
56  raise HomeAssistantError(
57  translation_domain=DOMAIN,
58  translation_key="command_error",
59  translation_placeholders={"error": error},
60  )
61  # No response without error (unexpected)
62  raise HomeAssistantError(f"Unknown response: {response}")
63  if (result := response.get("result")) is not True:
64  if reason := response.get("reason"):
65  if reason in ("already_set", "not_charging", "requested"):
66  # Reason is acceptable
67  return result
68  # Result of false with reason
69  raise HomeAssistantError(
70  translation_domain=DOMAIN,
71  translation_key="command_reason",
72  translation_placeholders={"reason": reason},
73  )
74  # Result of false without reason (unexpected)
75  raise HomeAssistantError(
76  translation_domain=DOMAIN,
77  translation_key="command_no_reason",
78  )
79  # Response with result of true
80  return result
bool handle_vehicle_command(Awaitable command)
Definition: helpers.py:50
None wake_up_vehicle(TeslaFleetVehicleData vehicle)
Definition: helpers.py:15
dict[str, Any] handle_command(Awaitable command)
Definition: helpers.py:36