Skip to content

Commit

Permalink
chore: Refactor RemainingRangeSensor and ClimateControlSwitch
Browse files Browse the repository at this point in the history
Fixes runtime errors when the data is missing
  • Loading branch information
remuslazar committed Jul 1, 2024
1 parent a9a827f commit e825a02
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
12 changes: 10 additions & 2 deletions custom_components/nissan_carwings/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,12 @@ def __init__(self, coordinator: CarwingsDataUpdateCoordinator, *, is_ac_on: bool
@property
def native_value(self) -> float | None:
"""Battery range in miles or kms."""
data: pycarwings3.responses.CarwingsLatestBatteryStatusResponse = self.coordinator.data[DATA_BATTERY_STATUS_KEY]
ret: float | None
if self._ac_on:
ret = self.coordinator.data[DATA_BATTERY_STATUS_KEY].cruising_range_ac_on_km
ret = data.cruising_range_ac_on_km
else:
ret = self.coordinator.data[DATA_BATTERY_STATUS_KEY].cruising_range_ac_off_km
ret = data.cruising_range_ac_off_km

if ret is None:
return None
Expand All @@ -121,6 +122,13 @@ def native_unit_of_measurement(self) -> str:
return UnitOfLength.MILES
return UnitOfLength.KILOMETERS

@property
def available(self) -> bool:
"""Sensor availability."""
data: pycarwings3.responses.CarwingsLatestBatteryStatusResponse = self.coordinator.data[DATA_BATTERY_STATUS_KEY]
attr = "cruising_range_ac_on_km" if self._ac_on else "cruising_range_ac_off_km"
return hasattr(data, attr)


class BatteryCapacitySensor(NissanCarwingsEntity, SensorEntity):
"""Current Battery Capacity Sensor."""
Expand Down
3 changes: 2 additions & 1 deletion custom_components/nissan_carwings/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ def is_on(self) -> bool:
data: pycarwings3.responses.CarwingsLatestClimateControlStatusResponse = self.coordinator.data[
DATA_CLIMATE_STATUS_KEY
]
return data.is_hvac_running
# assume the AC is not running when the data is not available
return data.is_hvac_running if data else False

async def async_turn_on(self, **_: Any) -> None:
"""Turn on the switch."""
Expand Down

0 comments on commit e825a02

Please sign in to comment.