Skip to content

Commit

Permalink
Merge branch 'dev' into refresh-token
Browse files Browse the repository at this point in the history
  • Loading branch information
jyrkih authored Dec 27, 2023
2 parents 77754cc + 6d1b7e7 commit 1d9411a
Show file tree
Hide file tree
Showing 9 changed files with 607 additions and 120 deletions.
3 changes: 3 additions & 0 deletions custom_components/polestar_api/polestar.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ async def init(self):
self.id = vin[:8]
self.name = "Polestar " + vin[-4:]

def get_token_expiry(self):
return self.polestarApi.auth.token_expiry

def get_latest_data(self, query: str, field_name: str):
return self.polestarApi.get_latest_data(query, field_name)

Expand Down
5 changes: 4 additions & 1 deletion custom_components/polestar_api/pypolestar/polestar.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,11 @@ async def get_ev_data(self, vin: str):
self.updating = True

try:
if self.auth.token_expiry is None:
raise PolestarAuthException("No token expiry found")
if (self.auth.token_expiry - datetime.now()).total_seconds() < 300:
await self.auth.get_token(refresh=True)

except PolestarAuthException as e:
self.latest_call_code = 500
_LOGGER.warning("Auth Exception: %s", str(e))
Expand Down Expand Up @@ -140,7 +143,7 @@ def get_cache_data(self, query: str, field_name: str, skip_cache: bool = False):
cache_entry = self.cache_data[query]
data = cache_entry['data']
if data is not None:
if skip_cache is False or cache_entry['timestamp'] + timedelta(seconds=CACHE_TIME) > datetime.now():
if skip_cache is True or cache_entry['timestamp'] + timedelta(seconds=CACHE_TIME) > datetime.now():
return self._get_field_name_value(field_name, data)
return None

Expand Down
45 changes: 31 additions & 14 deletions custom_components/polestar_api/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class PolestarSensorDescription(
state_class=SensorStateClass.MEASUREMENT,
device_class=SensorDeviceClass.DISTANCE,
max_value=None,
dict_data=None
dict_data=None,
),
PolestarSensorDescription(
key="estimate_distance_to_empty_km",
Expand Down Expand Up @@ -113,7 +113,7 @@ class PolestarSensorDescription(
PolestarSensorDescription(
key="average_speed_km_per_hour",
name="Avg Speed Per Hour",
icon="mdi:map-marker-distance",
icon="mdi:speedometer",
query="getOdometerData",
field_name="averageSpeedKmPerHour",
unit='km',
Expand Down Expand Up @@ -175,7 +175,7 @@ class PolestarSensorDescription(
PolestarSensorDescription(
key="charging_status",
name="Charging status",
icon="mdi:battery-clock",
icon="mdi:ev-station",
query="getBatteryData",
field_name="chargingStatus",
unit=None,
Expand Down Expand Up @@ -212,7 +212,7 @@ class PolestarSensorDescription(
PolestarSensorDescription(
key="charger_connection_status",
name="Charging Connection Status",
icon="mdi:battery-clock",
icon="mdi:connection",
query="getBatteryData",
field_name="chargerConnectionStatus",
unit=None,
Expand Down Expand Up @@ -286,6 +286,7 @@ class PolestarSensorDescription(
PolestarSensorDescription(
key="model_name",
name="Model name",
icon="mdi:car-electric",
query="getConsumerCarsV2",
field_name="content/model/name",
unit=None,
Expand All @@ -296,6 +297,7 @@ class PolestarSensorDescription(
PolestarSensorDescription(
key="last_updated_odometer_data",
name="Last updated odometer data",
icon="mdi:counter",
query="getOdometerData",
field_name="eventUpdatedTimestamp/iso",
unit=None,
Expand Down Expand Up @@ -354,6 +356,17 @@ class PolestarSensorDescription(
max_value=None,
dict_data=API_STATUS_DICT
),
PolestarSensorDescription(
key="api_token_expires_at",
name="API token expired at",
icon="mdi:heart",
query=None,
field_name=None,
unit=None,
round_digits=None,
max_value=None,
dict_data=None
),

)

Expand Down Expand Up @@ -382,7 +395,7 @@ async def async_setup_entry(
PolestarSensor(device, description) for description in POLESTAR_SENSOR_TYPES
]
async_add_entities(sensors)
platform = entity_platform.current_platform.get()
entity_platform.current_platform.get()


class PolestarSensor(PolestarEntity, SensorEntity):
Expand All @@ -399,9 +412,11 @@ def __init__(self,
# get the last 4 character of the id
unique_id = device.vin[-4:]
self.entity_id = f"{POLESTAR_API_DOMAIN}.'polestar_'.{unique_id}_{description.key}"
self._attr_name = f"{description.name}"
#self._attr_name = f"{description.name}"
self._attr_unique_id = f"polestar_{unique_id}-{description.key}"
self.description = description
self.attr_translation_key = f"polestar_{description.key}"
self.attr_has_entity_name = True

self.entity_description = description
if description.state_class is not None:
Expand Down Expand Up @@ -430,11 +445,6 @@ def unique_id(self) -> str:
"""Return a unique ID."""
return f"{self._device.id}-{self.entity_description.key}"

@property
def name(self) -> str:
"""Return the name of the sensor."""
return self._attr_name

@property
def icon(self) -> str | None:
"""Return the icon of the sensor."""
Expand Down Expand Up @@ -462,6 +472,10 @@ def state(self) -> StateType:
return self.entity_description.dict_data.get(
self._attr_native_value, self._attr_native_value)

if self.entity_description.key == 'api_token_expires_at':
if self._device.get_token_expiry() is None:
return None
return self._device.get_token_expiry().strftime("%Y-%m-%d %H:%M:%S")
if self._attr_native_value != 0 and self._attr_native_value in (None, False):
return None

Expand Down Expand Up @@ -527,6 +541,9 @@ def unit_of_measurement(self) -> str:

async def async_update(self) -> None:
"""Get the latest data and updates the states."""
await self._device.async_update()
self._attr_native_value = self._device.get_value(
self.description.query, self.description.field_name, self.get_skip_cache())
try:
await self._device.async_update()
self._attr_native_value = self._device.get_value(
self.description.query, self.description.field_name, self.get_skip_cache())
except Exception:
_LOGGER.warning("Failed to update sensor async update")
114 changes: 95 additions & 19 deletions custom_components/polestar_api/translations/de.json
Original file line number Diff line number Diff line change
@@ -1,22 +1,98 @@
{
"config": {
"step": {
"user": {
"title": "Konfiguriere Deinen Polestar",
"description": "Eingabe der Zugangsdaten Deines Polestar",
"data": {
"name": "Anzeigename",
"username": "Benutzername",
"password": "Passwort",
"vin": "VIN"
}
}
},
"abort": {
"api_timeout": "Zeitüberschreitung bei der Verbindung mit der API.",
"api_failed": "Unerwarteter Fehler beim Erstellen der API.",
"already_configured": "Die Polestar API ist bereits konfiguriert",
"no_token": "Kein Token in der Antwort gefunden. Bitte überprüfe Deine Anmeldeinformationen."
"config": {
"step": {
"user": {
"title": "Konfiguriere Deinen Polestar",
"description": "Eingabe der Zugangsdaten Deines Polestar",
"data": {
"name": "Anzeigename",
"username": "Benutzername",
"password": "Passwort",
"vin": "VIN"
}
}
},
"abort": {
"api_timeout": "Zeitüberschreitung bei der Verbindung mit der API.",
"api_failed": "Unerwarteter Fehler beim Erstellen der API.",
"already_configured": "Die Polestar API ist bereits konfiguriert",
"no_token": "Kein Token in der Antwort gefunden. Bitte überprüfe Deine Anmeldeinformationen."
}
}
},
"entity": {
"sensor": {
"polestar_estimate_distance_to_empty_miles": {
"name": "Reichweite (Meilen)"
},
"polestar_estimate_distance_to_empty_km": {
"name": "Reichweite (km)"
},
"polestar_current_odometer_meters": {
"name": "Kilometerstand"
},
"polestar_average_speed_km_per_hour": {
"name": "Durchschnittsgeschwindigkeit (km/h)"
},
"polestar_current_trip_meter_automatic": {
"name": "Kilometerzähler automatisch"
},
"polestar_current_trip_meter_manual": {
"name": "Kilometerzähler manuell"
},
"polestar_battery_charge_level": {
"name": "Batterieladestand"
},
"polestar_estimated_charging_time_to_full_minutes": {
"name": "Geschätzte Ladezeit bis zur vollen Batterie (Minuten)"
},
"polestar_charging_status": {
"name": "Ladestatus"
},
"polestar_charging_power_watts": {
"name": "Ladeleistung (W)"
},
"polestar_charging_current_amps": {
"name": "Ladestrom (A)"
},
"polestar_charger_connection_status": {
"name": "Verbindungsstatus Ladepunkt"
},
"polestar_average_energy_consumption_kwh_per_100_km": {
"name": "Durchschnittlicher Energieverbrauch (kWh/100km)"
},
"polestar_estimated_charging_time_minutes_to_target_distance": {
"name": "Geschätzte Ladezeit bis zur Zielreichweite"
},
"polestar_vin": {
"name": "VIN"
},
"polestar_registration_number": {
"name": "Kennzeichen"
},
"polestar_estimated_fully_charged_time": {
"name": "Geschätzte Zeit zur vollen Ladung"
},
"polestar_model_name": {
"name": "Modellname"
},
"polestar_last_updated_odometer_data": {
"name": "Letzte Aktualisierung des Kilometerstands"
},
"polestar_last_updated_battery_data": {
"name": "Letzte Aktualisierung der Batteriedaten"
},
"polestar_estimate_full_charge_range_miles": {
"name": "Geschätzte Reichweite bei voller Ladung (Meilen)"
},
"polestar_estimate_full_charge_range": {
"name": "Geschätzte Reichweite bei voller Ladung"
},
"polestar_api_status_code": {
"name": "API Status Code"
},
"polestar_api_token_expires_at": {
"name": "API Token gültig bis"
}
}
}
}
Loading

0 comments on commit 1d9411a

Please sign in to comment.