Skip to content

Commit

Permalink
Used python 3.9 compatible Optional[x] instead of 'x | None'
Browse files Browse the repository at this point in the history
  • Loading branch information
joro75 committed Nov 25, 2023
1 parent 91dec31 commit 898c977
Show file tree
Hide file tree
Showing 10 changed files with 98 additions and 88 deletions.
29 changes: 14 additions & 15 deletions mytoyota/api.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
"""Toyota Connected Services API"""
from datetime import datetime
from typing import Any
from datetime import date, datetime
from typing import Any, Optional
from uuid import uuid4
from datetime import date

from .const import BASE_URL
from .controller import Controller
Expand All @@ -18,7 +17,7 @@ def __init__(self, controller: Controller) -> None:
self.controller = controller

@property
def uuid(self) -> str | None:
def uuid(self) -> Optional[str]:
"""Returns uuid from controller"""
return self.controller.uuid

Expand All @@ -44,7 +43,7 @@ async def get_wake_endpoint(self) -> None:
method="POST", base_url=BASE_URL, endpoint="/v2/global/remote/wake"
)

async def get_vehicles_endpoint(self) -> list[dict[str, Any] | None] | None:
async def get_vehicles_endpoint(self) -> Optional[list[Optional[dict[str, Any]]]]:
"""Retrieves list of cars you have registered with MyT"""
return await self.controller.request(
method="GET",
Expand All @@ -54,7 +53,7 @@ async def get_vehicles_endpoint(self) -> list[dict[str, Any] | None] | None:

async def get_location_endpoint(
self, vin: str
) -> dict[str, Any] | None: # pragma: no cover
) -> Optional[dict[str, Any]]: # pragma: no cover
"""Get where you have parked your car."""
ret = await self.controller.request(
method="GET",
Expand All @@ -71,7 +70,7 @@ async def get_location_endpoint(

async def get_vehicle_health_status_endpoint(
self, vin: str
) -> dict[str, Any] | None:
) -> Optional[dict[str, Any]]:
"""Get information about the vehicle."""
return await self.controller.request(
method="GET",
Expand All @@ -80,7 +79,7 @@ async def get_vehicle_health_status_endpoint(
headers={"VIN": vin},
)

async def get_vehicle_status_endpoint(self, vin: str) -> dict[str, Any] | None:
async def get_vehicle_status_endpoint(self, vin: str) -> Optional[dict[str, Any]]:
"""Get information about the vehicle."""
return await self.controller.request(
method="GET",
Expand All @@ -91,7 +90,7 @@ async def get_vehicle_status_endpoint(self, vin: str) -> dict[str, Any] | None:

async def get_vehicle_electric_status_endpoint(
self, vin: str
) -> dict[str, Any] | None:
) -> Optional[dict[str, Any]]:
"""Get information about the vehicle."""
try:
return await self.controller.request(
Expand All @@ -104,7 +103,7 @@ async def get_vehicle_electric_status_endpoint(
# TODO This is wrong, but lets change the Vehicle class
return None

async def get_telemetry_endpoint(self, vin: str) -> dict[str, Any] | None:
async def get_telemetry_endpoint(self, vin: str) -> Optional[dict[str, Any]]:
"""Get information about the vehicle."""
return await self.controller.request(
method="GET",
Expand All @@ -113,7 +112,7 @@ async def get_telemetry_endpoint(self, vin: str) -> dict[str, Any] | None:
headers={"vin": vin},
)

async def get_notification_endpoint(self, vin: str) -> dict[str, Any] | None:
async def get_notification_endpoint(self, vin: str) -> Optional[dict[str, Any]]:
"""Get information about the vehicle."""
resp = await self.controller.request(
method="GET",
Expand All @@ -125,8 +124,8 @@ async def get_notification_endpoint(self, vin: str) -> dict[str, Any] | None:
return resp[0]["notifications"]

async def get_driving_statistics_endpoint(
self, vin: str, from_date: str, interval: str | None = None
) -> dict[str, Any] | None:
self, vin: str, from_date: str, interval: Optional[str] = None
) -> Optional[dict[str, Any]]:
"""Get driving statistic"""
return await self.controller.request(
method="GET",
Expand Down Expand Up @@ -170,7 +169,7 @@ async def get_trip_endpoint(self, vin: str, trip_id: str) -> Trips:

async def set_lock_unlock_vehicle_endpoint(
self, vin: str, action: str
) -> dict[str, str] | None:
) -> Optional[dict[str, str]]:
"""Lock vehicle."""
return await self.controller.request(
method="POST",
Expand All @@ -181,7 +180,7 @@ async def set_lock_unlock_vehicle_endpoint(

async def get_lock_unlock_request_status(
self, vin: str, request_id: str
) -> dict[str, Any] | None:
) -> Optional[dict[str, Any]]:
"""Check lock/unlock status given a request ID"""
return await self.controller.request(
method="GET",
Expand Down
3 changes: 2 additions & 1 deletion mytoyota/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from __future__ import annotations

import logging
from typing import Optional

from mytoyota.api import Api
from mytoyota.const import SUPPORTED_REGIONS
Expand Down Expand Up @@ -41,7 +42,7 @@ def __init__(
locale: str = "en-gb",
region: str = "europe",
brand: str = "T",
uuid: str | None = None,
uuid: Optional[str] = None,
controller_class=Controller,
disable_locale_check: bool = False,
) -> None:
Expand Down
38 changes: 19 additions & 19 deletions mytoyota/controller.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Toyota Connected Services Controller """
import logging
from datetime import datetime, timedelta
from http import HTTPStatus
from typing import Any
import logging
from typing import Any, Optional, Union
from urllib import parse # For parse query string, can this be done with httpx?

import httpx
Expand Down Expand Up @@ -31,16 +31,16 @@ def __init__(
username: str,
password: str,
brand: str,
uuid: str | None = None,
uuid: Optional[str] = None,
) -> None:
self._locale: str = locale
self._region: str = region
self._username: str = username
self._password: str = password
self._brand: str = brand
self._uuid: str = uuid
self._token: str | None = None
self._token_expiration: datetime | None = None
self._token: Optional[str] = None
self._token_expiration: Optional[datetime] = None

@property
def _authorize_endpoint(self) -> str:
Expand All @@ -64,7 +64,7 @@ def _authenticate_endpoint(self) -> str:

@property
# TODO Dont think this is required outside of the controller anymore.
def uuid(self) -> str | None:
def uuid(self) -> Optional[str]:
"""Return uuid."""
return self._uuid

Expand Down Expand Up @@ -177,10 +177,10 @@ async def request_raw(
self, # pylint: disable=too-many-branches
method: str,
endpoint: str,
base_url: str | None = None,
body: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
headers: dict[str, Any] | None = None,
base_url: Optional[str] = None,
body: Optional[dict[str, Any]] = None,
params: Optional[dict[str, Any]] = None,
headers: Optional[dict[str, Any]] = None,
) -> httpx.Response:
"""Shared request method"""
if method not in ("GET", "POST", "PUT", "DELETE"):
Expand Down Expand Up @@ -248,10 +248,10 @@ async def request_json(
self,
method: str,
endpoint: str,
base_url: str | None = None,
body: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
headers: dict[str, Any] | None = None,
base_url: Optional[str] = None,
body: Optional[dict[str, Any]] = None,
params: Optional[dict[str, Any]] = None,
headers: Optional[dict[str, Any]] = None,
):
response = await self.request_raw(
method, endpoint, base_url, body, params, headers
Expand All @@ -263,11 +263,11 @@ async def request(
self,
method: str,
endpoint: str,
base_url: str | None = None,
body: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
headers: dict[str, Any] | None = None,
) -> dict[str, Any] | list[Any] | None:
base_url: Optional[str] = None,
body: Optional[dict[str, Any]] = None,
params: Optional[dict[str, Any]] = None,
headers: Optional[dict[str, Any]] = None,
) -> Optional[Union[dict[str, Any], list[Any]]]:
# TODO possibly remove if/when fully pydantic
response = await self.request_raw(
method, endpoint, base_url, body, params, headers
Expand Down
18 changes: 10 additions & 8 deletions mytoyota/models/dashboard.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"""Models for vehicle sensors."""
from typing import Optional

from mytoyota.models.data import VehicleData
from mytoyota.utils.conversions import convert_to_miles

Expand All @@ -14,36 +16,36 @@ def is_metric(self) -> bool:
return False

@property
def odometer(self) -> int | None:
def odometer(self) -> Optional[int]:
"""Shows the odometer distance."""
if self._data["odometer"]["unit"] == "mi":
return self._data["odometer"]["value"]

return convert_to_miles(self._data["odometer"]["value"])

@property
def fuel_level(self) -> float | None:
def fuel_level(self) -> Optional[float]:
"""Shows the fuellevel of the vehicle."""
return self._data["fuelLevel"]

@property
def fuel_range(self) -> float | None:
def fuel_range(self) -> Optional[float]:
"""Shows the range if available."""
if self._data["fuelRange"]["unit"] == "mi":
return self._data["odometer"]["value"]

return convert_to_miles(self._data["fuelRange"]["value"])

@property
def battery_level(self) -> float | None:
def battery_level(self) -> Optional[float]:
"""Shows the battery level if a hybrid."""
if "batteryLevel" in self._data:
return self._data["batteryLevel"]

return None

@property
def battery_range(self) -> float | None:
def battery_range(self) -> Optional[float]:
"""Shows the battery range if a hybrid."""
if "evRange" in self._data:
if self._data["evRange"]["unit"] == "mi":
Expand All @@ -54,7 +56,7 @@ def battery_range(self) -> float | None:
return None

@property
def battery_range_with_aircon(self) -> float | None:
def battery_range_with_aircon(self) -> Optional[float]:
"""Shows the battery range with aircon on, if a hybrid."""
if "evRangeWithAc" in self._data:
if self._data["evRangeWithAc"]["unit"] == "mi":
Expand All @@ -65,15 +67,15 @@ def battery_range_with_aircon(self) -> float | None:
return None

@property
def charging_status(self) -> str | None:
def charging_status(self) -> Optional[str]:
"""Shows the charging status if a hybrid."""
if "chargingStatus" in self._data:
return self._data["chargingStatus"]

return None

@property
def remaining_charge_time(self) -> int | None:
def remaining_charge_time(self) -> Optional[int]:
"""Shows the remaining time to a full charge, if a hybrid."""
# TODO: What units?
if "remainingChargeTime" in self._data:
Expand Down
10 changes: 6 additions & 4 deletions mytoyota/models/endpoints/trip.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from pydantic import BaseModel, Field
from datetime import date, datetime
from typing import Optional
from uuid import UUID

from pydantic import BaseModel, Field


class _Pagination(BaseModel):
currentPage: int
Expand All @@ -27,7 +29,7 @@ class _Scores(BaseModel):
advice: int = Field(ge=0, le=100, default=0)
braking: int = Field(ge=0, le=100)
constantSpeed: int = Field(ge=0, le=100, default=0)
global_: int | None = Field(ge=0, le=100, alias="global", default=None)
global_: Optional[int] = Field(ge=0, le=100, alias="global", default=None)


class _Summary(BaseModel):
Expand Down Expand Up @@ -59,7 +61,7 @@ class _HDC(BaseModel):


class _MonthSummary(BaseModel):
hdc: _HDC | None = Field(default=None) # Only available on EV cars
hdc: Optional[_HDC] = Field(default=None) # Only available on EV cars
# histograms not imported
month: int = Field(..., ge=1, le=12)
scores: _Scores
Expand All @@ -81,7 +83,7 @@ class _TripSummary(_Summary):
class _Trip(BaseModel):
# behaviours not imported
category: int
hdc: _HDC | None = Field(default=None) # Only available on EV cars
hdc: Optional[_HDC] = Field(default=None) # Only available on EV cars
id: UUID
scores: _Scores
summary: _TripSummary
Expand Down
Loading

0 comments on commit 898c977

Please sign in to comment.