Skip to content

Commit

Permalink
Merge pull request #67 from CJNE/ruff
Browse files Browse the repository at this point in the history
cleanup using ruff and refactoring of cli.py
  • Loading branch information
fredriklj authored Dec 18, 2024
2 parents 404bc31 + c9bde06 commit 6635967
Show file tree
Hide file tree
Showing 14 changed files with 571 additions and 432 deletions.
25 changes: 13 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,26 +49,27 @@ Porsche Connect CLI
positional arguments:
{list,token,capabilities,currentoverview,storedoverview,trip_statistics,pictures,location,climatise_on,climatise_off,direct_charge_on,direct_charge_off,flash_indicators,honk_and_flash,lock_vehicle,unlock_vehicle,vehicle_closed,doors_and_lids,tire_pressure_status,tire_pressures,chargingprofile}
command help
battery Prints the main battery level (BEV)
capabilities Get vehicle capabilities
currentoverview Get stored overview for vehicle
storedoverview Poll vehicle for current overview
trip_statistics Get trip statistics from backend
pictures Get vehicle pictures url
location Show location of vehicle
climatise_on Start remote climatisation
chargingprofile Update parameters in configured charging profile
climatise_off Stop remote climatisation
direct_charge_on Enable direct charging
climatise_on Start remote climatisation
connected Check if vehicle is on-line
currentoverview Get stored overview for vehicle
direct_charge_off Disable direct charging
direct_charge_on Enable direct charging
doors_and_lids List status of all doors and lids
flash_indicators Flash indicators
honk_and_flash Flash indicators and sound the horn
location Show location of vehicle
lock_vehicle Lock vehicle
pictures Get vehicle pictures url
storedoverview Poll vehicle for current overview
tire_status Check if tire pressure are ok
tire_pressures Get tire pressure readings
trip_statistics Get trip statistics from backend
unlock_vehicle Unlock vehicle
vehicle_closed Check if all doors and lids are closed
doors_and_lids List status of all doors and lids
tire_pressure_status
Check if tire pressure are ok
tire_pressures Get tire pressure readings
chargingprofile Update parameters in configured charging profile
options:
-h, --help show this help message and exit
Expand Down
18 changes: 11 additions & 7 deletions examples/example.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
"""Example code for using the pyporscheconnectapi library."""

import asyncio
from pyporscheconnectapi.connection import Connection
from pyporscheconnectapi.account import PorscheConnectAccount
from sys import argv
import contextlib
import logging
from sys import argv

from pyporscheconnectapi.account import PorscheConnectAccount
from pyporscheconnectapi.connection import Connection

logging.basicConfig()

Expand All @@ -11,20 +15,22 @@
# inherit that value. Here we set the root logger to NOTSET. This logging
# level is automatically inherited by all existing and new sub-loggers
# that do not set a less verbose level.

logging.root.setLevel(logging.DEBUG)

email = argv[1]
password = argv[2]


async def vehicles() -> None:
"""Get vehicles connected to account and print out vehicle vin, model name and model year."""
conn = Connection(email, password)
client = PorscheConnectAccount(connection=conn)

vehicles = await client.get_vehicles()
for vehicle in vehicles:
print(
f"VIN: {vehicle.vin}, Model: {vehicle.model_name}, Year: {vehicle.model_year}"
f"VIN: {vehicle.vin}, Model: {vehicle.model_name}, Year: {vehicle.model_year}",
)

await conn.close()
Expand All @@ -33,7 +39,5 @@ async def vehicles() -> None:
if __name__ == "__main__":
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
with contextlib.suppress(KeyboardInterrupt):
loop.run_until_complete(vehicles())
except KeyboardInterrupt:
pass
19 changes: 9 additions & 10 deletions examples/example2.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
"""Example code for using the pyporscheconnectapi library."""

import asyncio
from pyporscheconnectapi.connection import Connection
from pyporscheconnectapi.account import PorscheConnectAccount
import contextlib
from sys import argv
import logging

# logging.basicConfig()
# logging.root.setLevel(logging.DEBUG)
from pyporscheconnectapi.account import PorscheConnectAccount
from pyporscheconnectapi.connection import Connection

email = argv[1]
password = argv[2]


async def vehicles() -> None:
"""Make request to the API and parse out batteri level and vehicle lock status."""
conn = Connection(email, password)
client = PorscheConnectAccount(connection=conn)

Expand All @@ -20,12 +21,12 @@ async def vehicles() -> None:
vehicle = vehicle_obj.data

print(
f"VIN: {vehicle['vin']}, Model: {vehicle['modelName']}, Year: {vehicle['modelType']['year']}"
f"VIN: {vehicle['vin']}, Model: {vehicle['modelName']}, Year: {vehicle['modelType']['year']}",
)
mf = ["BATTERY_LEVEL", "LOCK_STATE_VEHICLE"]
measurements = "mf=" + "&mf=".join(mf)
data = await conn.get(
f"/connect/v1/vehicles/{vehicle['vin']}?{measurements}"
f"/connect/v1/vehicles/{vehicle['vin']}?{measurements}",
)

soc = (next((x for x in data["measurements"] if x["key"] == mf[0]), None))[
Expand All @@ -44,7 +45,5 @@ async def vehicles() -> None:
if __name__ == "__main__":
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
with contextlib.suppress(KeyboardInterrupt):
loop.run_until_complete(vehicles())
except KeyboardInterrupt:
pass
10 changes: 10 additions & 0 deletions pyporscheconnectapi/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""Library to integrate with the Porsche Connect API.
This library provides a Python interface to Porsche Connect API, with
abilities to read vechicle status data and access to remote services
to control certain vechicle functions.
NOTE: This work is not officially supported by Porsche and functionality
can stop working at any time without warning.
"""
33 changes: 18 additions & 15 deletions pyporscheconnectapi/account.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
from pyporscheconnectapi.connection import Connection
from pyporscheconnectapi.vehicle import PorscheVehicle
"""Accesses Porsche Connect account and retrieves connected vehicles."""
from __future__ import annotations

import logging

from typing import List, Optional

from pyporscheconnectapi.connection import Connection
from pyporscheconnectapi.vehicle import PorscheVehicle

_LOGGER = logging.getLogger(__name__)


class PorscheConnectAccount:
"""Establishes a connection to a Porsche Connect account."""

def __init__(
self,
username="",
password="",
token={},
connection: Optional[Connection] = None,
):
self.vehicles: List[PorscheVehicle] = []
username: str | None = None,
password: str | None = None,
token: dict | None = None,
connection: Connection | None = None,
) -> None:
"""Initialize the account."""
self.vehicles: list[PorscheVehicle] = []
self.token = token
if connection is None:
self.connection = Connection(username, password, token=token)
Expand All @@ -32,7 +35,7 @@ async def _init_vehicles(self) -> None:
vehicle_list = await self.connection.get("/connect/v1/vehicles")

for vehicle in vehicle_list:
_LOGGER.debug(f"Got vehicle {vehicle}")
_LOGGER.debug("Got vehicle %s", vehicle)
v = PorscheVehicle(
vin=vehicle["vin"],
data=vehicle,
Expand All @@ -43,17 +46,17 @@ async def _init_vehicles(self) -> None:

self.token = self.connection.token

async def get_vehicles(self, force_init: bool = False) -> List[PorscheVehicle]:
"""Retrieve vehicle data from API endpoints."""

async def get_vehicles(self, *, force_init: bool = False) -> list[PorscheVehicle]:
"""Retrieve available vehicles from API endpoints."""
_LOGGER.debug("Retrieving vehicle list")

if len(self.vehicles) == 0 or force_init:
await self._init_vehicles()

return self.vehicles

async def get_vehicle(self, vin: str) -> Optional[PorscheVehicle]:
async def get_vehicle(self, vin: str) -> PorscheVehicle | None:
"""Retrieve vehicle data from API endpoints."""
if len(self.vehicles) == 0:
await self._init_vehicles()
filtered = [v for v in self.vehicles if v.vin == vin]
Expand Down
Loading

0 comments on commit 6635967

Please sign in to comment.