Skip to content

Commit

Permalink
Merge pull request #2 from yaleman/main
Browse files Browse the repository at this point in the history
Typing fixes
  • Loading branch information
Bre77 authored Apr 28, 2024
2 parents dcf996c + 08c1534 commit d4aa2ff
Show file tree
Hide file tree
Showing 8 changed files with 47 additions and 29 deletions.
15 changes: 15 additions & 0 deletions tesla_fleet_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,18 @@
from .user import User
from .vehicle import Vehicle
from .vehiclespecific import VehicleSpecific


__all__ = [
"TeslaFleetApi",
"TeslaFleetOAuth",
"Teslemetry",
"Tessie",
"Charging",
"Energy",
"EnergySpecific",
"Partner",
"User",
"Vehicle",
"VehicleSpecific",
]
2 changes: 1 addition & 1 deletion tesla_fleet_api/energy.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ async def grid_import_export(
self,
energy_site_id: int,
disallow_charge_from_grid_with_solar_installed: bool | None = None,
customer_preferred_export_rule: EnergyExportMode|str | None = None,
customer_preferred_export_rule: EnergyExportMode | str | None = None,
) -> dict[str, Any]:
"""Allow/disallow charging from the grid and exporting energy to the grid."""
return await self._request(
Expand Down
22 changes: 12 additions & 10 deletions tesla_fleet_api/teslafleetapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@
class TeslaFleetApi:
"""Class describing the Tesla Fleet API."""

server: str
server: str | None = None
session: aiohttp.ClientSession
headers: dict[str, str]
raise_for_status: bool

def __init__(
self,
session: aiohttp.ClientSession,
access_token: str,
access_token: str | None = None,
region: str | None = None,
server: str | None = None,
raise_for_status: bool = True,
Expand All @@ -38,9 +38,10 @@ def __init__(
self.session = session
self.access_token = access_token

if region and not server and region not in SERVERS:
raise ValueError(f"Region must be one of {', '.join(SERVERS.keys())}")
self.server = server or SERVERS.get(region)
if region is not None:
if not server and region not in SERVERS:
raise ValueError(f"Region must be one of {', '.join(SERVERS.keys())}")
self.server = server or SERVERS.get(region)
self.raise_for_status = raise_for_status

LOGGER.debug("Using server %s", self.server)
Expand All @@ -61,7 +62,8 @@ async def find_server(self) -> str:
for server in SERVERS.values():
self.server = server
try:
response = await (self.user.region()).get("response")
region_response = await self.user.region()
response = region_response.get("response")
if response:
self.server = response["fleet_api_base_url"]
LOGGER.debug("Using server %s", self.server)
Expand All @@ -74,9 +76,9 @@ async def _request(
self,
method: Method,
path: str,
params: dict[str:Any] | None = None,
json: dict[str:Any] | None = None,
):
params: dict[str, Any] | None = None,
json: dict[str, Any] | None = None,
) -> dict[str, Any] | str:
"""Send a request to the Tesla Fleet API."""

if not self.server:
Expand Down Expand Up @@ -125,7 +127,7 @@ async def _request(
LOGGER.debug("Response Text: %s", data)
return data

async def status(self):
async def status(self) -> str:
"""This endpoint returns the string "ok" if the API is operating normally. No HTTP headers are required."""
if not self.server:
raise ValueError("Server was not set at init. Call find_server() first.")
Expand Down
16 changes: 9 additions & 7 deletions tesla_fleet_api/teslafleetoauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ def get_login_url(
"""Get the login URL."""
return f"https://auth.tesla.com/oauth2/v3/authorize?response_type=code&client_id={self.client_id}&redirect_uri={redirect_uri}&scope={' '.join(scopes)}&state={state}"

async def get_refresh_token(self, client_secret: str, code: str, redirect_uri: str):
async def get_refresh_token(
self, client_secret: str, code: str, redirect_uri: str
) -> None:
"""Get the refresh token."""
async with self.session.post(
"https://auth.tesla.com/oauth2/v3/token",
Expand All @@ -63,13 +65,13 @@ async def get_refresh_token(self, client_secret: str, code: str, redirect_uri: s
region = code.split("_")[0].lower()
self.server = SERVERS.get(region)

async def check_access_token(self) -> str | None:
async def check_access_token(self) -> dict[str, Any] | None:
"""Get the access token."""
if self.access_token and self.expires > time.time():
return
return None
return await self.refresh_access_token()

async def refresh_access_token(self) -> str:
async def refresh_access_token(self) -> dict[str, Any]:
"""Refresh the access token."""
if not self.refresh_token:
raise ValueError("Refresh token is missing")
Expand All @@ -93,9 +95,9 @@ async def _request(
self,
method: Method,
path: str,
params: dict | None = None,
data: dict | None = None,
):
params: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
) -> str | dict[str, Any]:
"""Send a request to the Tesla Fleet API."""
await self.check_access_token()
return await super()._request(method, path, params, data)
9 changes: 5 additions & 4 deletions tesla_fleet_api/teslemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,18 @@ async def metadata(self, update_region=True) -> dict[str, Any]:
LOGGER.debug("Using server %s", self.server)
return resp

async def find_server(self):
# TODO: type this properly, it probably should return something
async def find_server(self) -> None:
"""Find the server URL for the Tesla Fleet API."""
await self.metadata(True)

async def _request(
self,
method: Method,
path: str,
params: dict[str:Any] | None = None,
json: dict[str:Any] | None = None,
):
params: dict[str, Any] | None = None,
json: dict[str, Any] | None = None,
) -> str | dict[str, Any]:
"""Send a request to the Teslemetry API."""
async with rate_limit:
return await super()._request(method, path, params, json)
3 changes: 1 addition & 2 deletions tesla_fleet_api/tessie.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from typing import Any
from .teslafleetapi import TeslaFleetApi
from .const import Method
from .vehiclespecific import VehicleSpecific


class Tessie(TeslaFleetApi):
Expand All @@ -23,7 +22,7 @@ def __init__(
energy_scope=False,
)

async def find_server(self):
async def find_server(self) -> str:
"""Find the server URL for the Tesla Fleet API."""
raise NotImplementedError("Do not use this function for Tessie.")

Expand Down
7 changes: 3 additions & 4 deletions tesla_fleet_api/vehicle.py
Original file line number Diff line number Diff line change
Expand Up @@ -567,7 +567,7 @@ async def trigger_homelink(
lon: float | None = None,
) -> dict[str, Any]:
"""Turns on HomeLink (used to open and close garage doors)."""
data = {}
data: dict[str, str | float] = {}
if token:
data["token"] = token
if lat and lon:
Expand Down Expand Up @@ -742,12 +742,11 @@ async def vehicle_data(
endpoints: List[VehicleDataEndpoint] | List[str] | None = None,
) -> dict[str, Any]:
"""Makes a live call to the vehicle. This may return cached data if the vehicle is offline. For vehicles running firmware versions 2023.38+, location_data is required to fetch vehicle location. This will result in a location sharing icon to show on the vehicle UI."""
if isinstance(endpoints, list):
endpoints = ";".join(endpoints)
endpoint_payload = ";".join(endpoints) if endpoints else None
return await self._request(
Method.GET,
f"api/1/vehicles/{vehicle_tag}/vehicle_data",
{"endpoints": endpoints},
{"endpoints": endpoint_payload},
)

async def vehicle_subscriptions(
Expand Down
2 changes: 1 addition & 1 deletion tesla_fleet_api/vehiclespecific.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
class VehicleSpecific:
"""Class describing the Tesla Fleet API vehicle endpoints and commands for a specific vehicle."""

def __init__(self, parent, vin: str | None = None):
def __init__(self, parent, vin: str | int | None = None):
self._parent = parent
self.vin = vin

Expand Down

0 comments on commit d4aa2ff

Please sign in to comment.