Skip to content

Commit

Permalink
#52 #48 catch correct the forbidden error, #42 on async failed set de…
Browse files Browse the repository at this point in the history
…lay to prevent DDoS Polestar server
  • Loading branch information
leeyuentuen committed Dec 31, 2023
1 parent 0dc179e commit a1d32f9
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 45 deletions.
8 changes: 4 additions & 4 deletions custom_components/polestar_api/polestar.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"""Polestar API for Polestar integration."""
import datetime
import logging

from .pypolestar.exception import PolestarApiException, PolestarAuthException

from .pypolestar.polestar import PolestarApi

from urllib3 import disable_warnings

from homeassistant.core import HomeAssistant

from .pypolestar.exception import PolestarApiException, PolestarAuthException
from .pypolestar.polestar import PolestarApi

POST_HEADER_JSON = {"Content-Type": "application/json"}

_LOGGER = logging.getLogger(__name__)
Expand Down
6 changes: 3 additions & 3 deletions custom_components/polestar_api/pypolestar/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@ class PolestarApiException(Exception):

class PolestarAuthException(Exception):
"""Base class for exceptions in Auth module."""

error_code: int = None
message: str = None

def __init__(self, message, error_code) -> None:
super().__init__(message)
self.error_code = error_code
return None


class PolestarNotAuthorizedException(Exception):
"""Exception for unauthorized call"""
"""Exception for unauthorized call."""


class PolestarNoDataException(Exception):
"""Exception for no data"""
"""Exception for no data."""
6 changes: 6 additions & 0 deletions custom_components/polestar_api/pypolestar/polestar.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ def __init__(self, username: str, password: str) -> None:
self.cache_data = {}
self.latest_call_code = None
self._client_session = httpx.AsyncClient()
self.next_update = None


async def init(self):
try:
Expand Down Expand Up @@ -106,6 +108,10 @@ async def get_ev_data(self, vin: str):
if self.updating:
return

if self.next_update is not None and self.next_update > datetime.now():
_LOGGER.debug("Skipping update, next update at %s", self.next_update)
return

self.updating = True

try:
Expand Down
68 changes: 33 additions & 35 deletions custom_components/polestar_api/sensor.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,24 @@
import logging

from dataclasses import dataclass
from datetime import datetime, timedelta
import logging
from typing import Final
from dataclasses import dataclass
from .entity import PolestarEntity
from homeassistant.helpers.typing import StateType
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback

from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
SensorDeviceClass

)
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import PERCENTAGE
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_platform
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType

from . import DOMAIN as POLESTAR_API_DOMAIN
from .entity import PolestarEntity
from .polestar import Polestar
from homeassistant.const import (
PERCENTAGE,
)


_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=15)
Expand Down Expand Up @@ -73,7 +70,7 @@ class PolestarSensorDescription(
POLESTAR_SENSOR_TYPES: Final[tuple[PolestarSensorDescription, ...]] = (
PolestarSensorDescription(
key="estimate_distance_to_empty_miles",
name="Distance miles Remaining",
name="Distance Miles Remaining",
icon="mdi:map-marker-distance",
query="getBatteryData",
field_name="estimatedDistanceToEmptyMiles",
Expand All @@ -86,7 +83,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="estimate_distance_to_empty_km",
name="Distance km Remaining",
name="Distance Km Remaining",
icon="mdi:map-marker-distance",
query="getBatteryData",
field_name="estimatedDistanceToEmptyKm",
Expand All @@ -99,24 +96,24 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="current_odometer_meters",
name="Odometer Meter",
name="Odometer",
icon="mdi:map-marker-distance",
query="getOdometerData",
field_name="odometerMeters",
unit='km',
round_digits=None,
round_digits=0,
state_class=SensorStateClass.MEASUREMENT,
device_class=SensorDeviceClass.DISTANCE,
max_value=None,
dict_data=None
),
PolestarSensorDescription(
key="average_speed_km_per_hour",
name="Avg Speed Per Hour",
name="Avg. Speed",
icon="mdi:speedometer",
query="getOdometerData",
field_name="averageSpeedKmPerHour",
unit='km',
unit='km/h',
round_digits=None,
state_class=SensorStateClass.MEASUREMENT,
device_class=SensorDeviceClass.DISTANCE,
Expand Down Expand Up @@ -151,7 +148,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="battery_charge_level",
name="Battery level",
name="Battery Level",
query="getBatteryData",
field_name="batteryChargeLevelPercentage",
unit=PERCENTAGE,
Expand All @@ -163,7 +160,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="estimated_charging_time_to_full_minutes",
name="Charging time",
name="Charging Time",
icon="mdi:battery-clock",
query="getBatteryData",
field_name="estimatedChargingTimeToFullMinutes",
Expand All @@ -174,7 +171,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="charging_status",
name="Charging status",
name="Charging Status",
icon="mdi:ev-station",
query="getBatteryData",
field_name="chargingStatus",
Expand Down Expand Up @@ -224,11 +221,11 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="average_energy_consumption_kwh_per_100_km",
name="Avg. energy consumption",
name="Avg. Energy Consumption",
icon="mdi:battery-clock",
query="getBatteryData",
field_name="averageEnergyConsumptionKwhPer100Km",
unit='Kwh/100km',
unit='kWh/100km',
round_digits=None,
max_value=None,
state_class=SensorStateClass.MEASUREMENT,
Expand All @@ -237,7 +234,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="estimated_charging_time_minutes_to_target_distance",
name="Estimated charging time to target distance",
name="Estimated Charging Time To Target Distance",
icon="mdi:battery-clock",
query="getBatteryData",
field_name="estimatedChargingTimeMinutesToTargetDistance",
Expand All @@ -261,7 +258,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="registration_number",
name="Registration number",
name="Registration Number",
icon="mdi:numeric-1-box",
query="getConsumerCarsV2",
field_name="registrationNo",
Expand All @@ -272,7 +269,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="estimated_fully_charged_time",
name="Time Full charged",
name="Time Full Charged",
icon="mdi:battery-clock",
query="getBatteryData",
field_name="estimatedChargingTimeToFullMinutes",
Expand All @@ -285,7 +282,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="model_name",
name="Model name",
name="Model Name",
icon="mdi:car-electric",
query="getConsumerCarsV2",
field_name="content/model/name",
Expand All @@ -296,7 +293,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="last_updated_odometer_data",
name="Last updated odometer data",
name="Last Updated Odometer Data",
icon="mdi:counter",
query="getOdometerData",
field_name="eventUpdatedTimestamp/iso",
Expand All @@ -309,7 +306,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="last_updated_battery_data",
name="Last updated battery data",
name="Last Updated Battery Data",
query="getBatteryData",
field_name="eventUpdatedTimestamp/iso",
unit=None,
Expand All @@ -321,7 +318,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="estimate_full_charge_range_miles",
name="Calc. miles Full Charge",
name="Calc. Miles Full Charge",
icon="mdi:map-marker-distance",
query="getBatteryData",
field_name="estimatedDistanceToEmptyMiles",
Expand All @@ -334,7 +331,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="estimate_full_charge_range",
name="Calc. km Full Charge",
name="Calc. Km Full Charge",
icon="mdi:map-marker-distance",
query="getBatteryData",
field_name="estimatedDistanceToEmptyKm",
Expand All @@ -347,7 +344,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="api_status_code",
name="API status",
name="API Status",
icon="mdi:heart",
query=None,
field_name=None,
Expand All @@ -358,7 +355,7 @@ class PolestarSensorDescription(
),
PolestarSensorDescription(
key="api_token_expires_at",
name="API token expired at",
name="API Token Expired At",
icon="mdi:heart",
query=None,
field_name=None,
Expand Down Expand Up @@ -547,3 +544,4 @@ async def async_update(self) -> None:
self.description.query, self.description.field_name, self.get_skip_cache())
except Exception:
_LOGGER.warning("Failed to update sensor async update")
self._device.polestarApi.next_update = datetime.now() + timedelta(seconds=60)
4 changes: 2 additions & 2 deletions custom_components/polestar_api/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@
"name": "Distance km Remaining"
},
"polestar_current_odometer_meters": {
"name": "Odometer Meters"
"name": "Odometer"
},
"polestar_average_speed_km_per_hour": {
"name": "Average Speed km/h"
"name": "Average Speed"
},
"polestar_current_trip_meter_automatic": {
"name": "Trip Meter Automatic"
Expand Down
2 changes: 1 addition & 1 deletion custom_components/polestar_api/translations/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"name": "Huidige kilometerstand"
},
"polestar_average_speed_km_per_hour": {
"name": "Gemiddelde snelheid (km/u)"
"name": "Gemiddelde snelheid"
},
"polestar_current_trip_meter_automatic": {
"name": "Huidige trip meter (automatisch)"
Expand Down

0 comments on commit a1d32f9

Please sign in to comment.