Add distance sensor device class to Mazda integration (#84659)

This commit is contained in:
Brandon Rothweiler 2022-12-29 11:17:11 -05:00 committed by GitHub
parent 187b03446e
commit 8678b36e71
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 49 deletions

View file

@ -16,7 +16,6 @@ from homeassistant.const import PERCENTAGE, UnitOfLength, UnitOfPressure
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType from homeassistant.helpers.typing import StateType
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM, UnitSystem
from . import MazdaEntity from . import MazdaEntity
from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN
@ -27,7 +26,7 @@ class MazdaSensorRequiredKeysMixin:
"""Mixin for required keys.""" """Mixin for required keys."""
# Function to determine the value for this sensor, given the coordinator data and the configured unit system # Function to determine the value for this sensor, given the coordinator data and the configured unit system
value: Callable[[dict[str, Any], UnitSystem], StateType] value: Callable[[dict[str, Any]], StateType]
@dataclass @dataclass
@ -39,17 +38,6 @@ class MazdaSensorEntityDescription(
# Function to determine whether the vehicle supports this sensor, given the coordinator data # Function to determine whether the vehicle supports this sensor, given the coordinator data
is_supported: Callable[[dict[str, Any]], bool] = lambda data: True is_supported: Callable[[dict[str, Any]], bool] = lambda data: True
# Function to determine the unit of measurement for this sensor, given the configured unit system
# Falls back to description.native_unit_of_measurement if it is not provided
unit: Callable[[UnitSystem], str | None] | None = None
def _get_distance_unit(unit_system: UnitSystem) -> str:
"""Return the distance unit for the given unit system."""
if unit_system is US_CUSTOMARY_SYSTEM:
return UnitOfLength.MILES
return UnitOfLength.KILOMETERS
def _fuel_remaining_percentage_supported(data): def _fuel_remaining_percentage_supported(data):
"""Determine if fuel remaining percentage is supported.""" """Determine if fuel remaining percentage is supported."""
@ -101,55 +89,45 @@ def _ev_remaining_range_supported(data):
) )
def _fuel_distance_remaining_value(data, unit_system): def _fuel_distance_remaining_value(data):
"""Get the fuel distance remaining value.""" """Get the fuel distance remaining value."""
return round( return round(data["status"]["fuelDistanceRemainingKm"])
unit_system.length(
data["status"]["fuelDistanceRemainingKm"], UnitOfLength.KILOMETERS
)
)
def _odometer_value(data, unit_system): def _odometer_value(data):
"""Get the odometer value.""" """Get the odometer value."""
# In order to match the behavior of the Mazda mobile app, we always round down # In order to match the behavior of the Mazda mobile app, we always round down
return int( return int(data["status"]["odometerKm"])
unit_system.length(data["status"]["odometerKm"], UnitOfLength.KILOMETERS)
)
def _front_left_tire_pressure_value(data, unit_system): def _front_left_tire_pressure_value(data):
"""Get the front left tire pressure value.""" """Get the front left tire pressure value."""
return round(data["status"]["tirePressure"]["frontLeftTirePressurePsi"]) return round(data["status"]["tirePressure"]["frontLeftTirePressurePsi"])
def _front_right_tire_pressure_value(data, unit_system): def _front_right_tire_pressure_value(data):
"""Get the front right tire pressure value.""" """Get the front right tire pressure value."""
return round(data["status"]["tirePressure"]["frontRightTirePressurePsi"]) return round(data["status"]["tirePressure"]["frontRightTirePressurePsi"])
def _rear_left_tire_pressure_value(data, unit_system): def _rear_left_tire_pressure_value(data):
"""Get the rear left tire pressure value.""" """Get the rear left tire pressure value."""
return round(data["status"]["tirePressure"]["rearLeftTirePressurePsi"]) return round(data["status"]["tirePressure"]["rearLeftTirePressurePsi"])
def _rear_right_tire_pressure_value(data, unit_system): def _rear_right_tire_pressure_value(data):
"""Get the rear right tire pressure value.""" """Get the rear right tire pressure value."""
return round(data["status"]["tirePressure"]["rearRightTirePressurePsi"]) return round(data["status"]["tirePressure"]["rearRightTirePressurePsi"])
def _ev_charge_level_value(data, unit_system): def _ev_charge_level_value(data):
"""Get the charge level value.""" """Get the charge level value."""
return round(data["evStatus"]["chargeInfo"]["batteryLevelPercentage"]) return round(data["evStatus"]["chargeInfo"]["batteryLevelPercentage"])
def _ev_remaining_range_value(data, unit_system): def _ev_remaining_range_value(data):
"""Get the remaining range value.""" """Get the remaining range value."""
return round( return round(data["evStatus"]["chargeInfo"]["drivingRangeKm"])
unit_system.length(
data["evStatus"]["chargeInfo"]["drivingRangeKm"], UnitOfLength.KILOMETERS
)
)
SENSOR_ENTITIES = [ SENSOR_ENTITIES = [
@ -160,13 +138,14 @@ SENSOR_ENTITIES = [
native_unit_of_measurement=PERCENTAGE, native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
is_supported=_fuel_remaining_percentage_supported, is_supported=_fuel_remaining_percentage_supported,
value=lambda data, unit_system: data["status"]["fuelRemainingPercent"], value=lambda data: data["status"]["fuelRemainingPercent"],
), ),
MazdaSensorEntityDescription( MazdaSensorEntityDescription(
key="fuel_distance_remaining", key="fuel_distance_remaining",
name="Fuel distance remaining", name="Fuel distance remaining",
icon="mdi:gas-station", icon="mdi:gas-station",
unit=_get_distance_unit, device_class=SensorDeviceClass.DISTANCE,
native_unit_of_measurement=UnitOfLength.KILOMETERS,
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
is_supported=_fuel_distance_remaining_supported, is_supported=_fuel_distance_remaining_supported,
value=_fuel_distance_remaining_value, value=_fuel_distance_remaining_value,
@ -175,7 +154,8 @@ SENSOR_ENTITIES = [
key="odometer", key="odometer",
name="Odometer", name="Odometer",
icon="mdi:speedometer", icon="mdi:speedometer",
unit=_get_distance_unit, device_class=SensorDeviceClass.DISTANCE,
native_unit_of_measurement=UnitOfLength.KILOMETERS,
state_class=SensorStateClass.TOTAL_INCREASING, state_class=SensorStateClass.TOTAL_INCREASING,
is_supported=lambda data: data["status"]["odometerKm"] is not None, is_supported=lambda data: data["status"]["odometerKm"] is not None,
value=_odometer_value, value=_odometer_value,
@ -233,7 +213,8 @@ SENSOR_ENTITIES = [
key="ev_remaining_range", key="ev_remaining_range",
name="Remaining range", name="Remaining range",
icon="mdi:ev-station", icon="mdi:ev-station",
unit=_get_distance_unit, device_class=SensorDeviceClass.DISTANCE,
native_unit_of_measurement=UnitOfLength.KILOMETERS,
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
is_supported=_ev_remaining_range_supported, is_supported=_ev_remaining_range_supported,
value=_ev_remaining_range_value, value=_ev_remaining_range_value,
@ -275,13 +256,6 @@ class MazdaSensorEntity(MazdaEntity, SensorEntity):
self._attr_unique_id = f"{self.vin}_{description.key}" self._attr_unique_id = f"{self.vin}_{description.key}"
@property @property
def native_unit_of_measurement(self): def native_value(self) -> StateType:
"""Return the unit of measurement for the sensor, according to the configured unit system."""
if unit_fn := self.entity_description.unit:
return unit_fn(self.hass.config.units)
return self.entity_description.native_unit_of_measurement
@property
def native_value(self):
"""Return the state of the sensor.""" """Return the state of the sensor."""
return self.entity_description.value(self.data, self.hass.config.units) return self.entity_description.value(self.data)

View file

@ -49,6 +49,7 @@ async def test_sensors(hass):
state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Fuel distance remaining" state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Fuel distance remaining"
) )
assert state.attributes.get(ATTR_ICON) == "mdi:gas-station" assert state.attributes.get(ATTR_ICON) == "mdi:gas-station"
assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.DISTANCE
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == LENGTH_KILOMETERS assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == LENGTH_KILOMETERS
assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.MEASUREMENT assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.MEASUREMENT
assert state.state == "381" assert state.state == "381"
@ -61,6 +62,7 @@ async def test_sensors(hass):
assert state assert state
assert state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Odometer" assert state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Odometer"
assert state.attributes.get(ATTR_ICON) == "mdi:speedometer" assert state.attributes.get(ATTR_ICON) == "mdi:speedometer"
assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.DISTANCE
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == LENGTH_KILOMETERS assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == LENGTH_KILOMETERS
assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.TOTAL_INCREASING assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.TOTAL_INCREASING
assert state.state == "2795" assert state.state == "2795"
@ -130,12 +132,16 @@ async def test_sensors(hass):
assert entry.unique_id == "JM000000000000000_rear_right_tire_pressure" assert entry.unique_id == "JM000000000000000_rear_right_tire_pressure"
async def test_sensors_imperial_units(hass): async def test_sensors_us_customary_units(hass):
"""Test that the sensors work properly with imperial units.""" """Test that the sensors work properly with US customary units."""
hass.config.units = US_CUSTOMARY_SYSTEM hass.config.units = US_CUSTOMARY_SYSTEM
await init_integration(hass) await init_integration(hass)
# In the US, miles are used for vehicle odometers.
# These tests verify that the unit conversion logic for the distance
# sensor device class automatically converts the unit to miles.
# Fuel Distance Remaining # Fuel Distance Remaining
state = hass.states.get("sensor.my_mazda3_fuel_distance_remaining") state = hass.states.get("sensor.my_mazda3_fuel_distance_remaining")
assert state assert state
@ -181,6 +187,7 @@ async def test_electric_vehicle_sensors(hass):
assert state assert state
assert state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Remaining range" assert state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Remaining range"
assert state.attributes.get(ATTR_ICON) == "mdi:ev-station" assert state.attributes.get(ATTR_ICON) == "mdi:ev-station"
assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.DISTANCE
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == LENGTH_KILOMETERS assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == LENGTH_KILOMETERS
assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.MEASUREMENT assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.MEASUREMENT
assert state.state == "218" assert state.state == "218"