Use UnitOfLength in integrations (#84034)

This commit is contained in:
epenet 2022-12-15 12:42:53 +01:00 committed by GitHub
parent bf4c399b19
commit d72c28a135
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 106 additions and 119 deletions

View File

@ -1,10 +1,5 @@
"""Const file for the MyBMW integration.""" """Const file for the MyBMW integration."""
from homeassistant.const import ( from homeassistant.const import VOLUME_GALLONS, VOLUME_LITERS, UnitOfLength
LENGTH_KILOMETERS,
LENGTH_MILES,
VOLUME_GALLONS,
VOLUME_LITERS,
)
DOMAIN = "bmw_connected_drive" DOMAIN = "bmw_connected_drive"
ATTRIBUTION = "Data provided by MyBMW" ATTRIBUTION = "Data provided by MyBMW"
@ -20,8 +15,8 @@ CONF_REFRESH_TOKEN = "refresh_token"
DATA_HASS_CONFIG = "hass_config" DATA_HASS_CONFIG = "hass_config"
UNIT_MAP = { UNIT_MAP = {
"KILOMETERS": LENGTH_KILOMETERS, "KILOMETERS": UnitOfLength.KILOMETERS,
"MILES": LENGTH_MILES, "MILES": UnitOfLength.MILES,
"LITERS": VOLUME_LITERS, "LITERS": VOLUME_LITERS,
"GALLONS": VOLUME_GALLONS, "GALLONS": VOLUME_GALLONS,
} }

View File

@ -24,8 +24,7 @@ from homeassistant.const import (
CONF_LONGITUDE, CONF_LONGITUDE,
CONF_NAME, CONF_NAME,
CONF_RADIUS, CONF_RADIUS,
LENGTH_FEET, UnitOfLength,
LENGTH_METERS,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import PlatformNotReady from homeassistant.exceptions import PlatformNotReady
@ -172,7 +171,9 @@ async def async_setup_platform(
radius = config.get(CONF_RADIUS, 0) radius = config.get(CONF_RADIUS, 0)
name = config[CONF_NAME] name = config[CONF_NAME]
if hass.config.units is US_CUSTOMARY_SYSTEM: if hass.config.units is US_CUSTOMARY_SYSTEM:
radius = DistanceConverter.convert(radius, LENGTH_FEET, LENGTH_METERS) radius = DistanceConverter.convert(
radius, UnitOfLength.FEET, UnitOfLength.METERS
)
# Create a single instance of CityBikesNetworks. # Create a single instance of CityBikesNetworks.
networks = hass.data.setdefault(CITYBIKES_NETWORKS, CityBikesNetworks(hass)) networks = hass.data.setdefault(CITYBIKES_NETWORKS, CityBikesNetworks(hass))

View File

@ -7,7 +7,7 @@ import async_timeout
from homeassistant.components.sensor import SensorEntity, SensorStateClass from homeassistant.components.sensor import SensorEntity, SensorStateClass
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import LENGTH_METERS from homeassistant.const import UnitOfLength
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.device_registry import DeviceEntryType from homeassistant.helpers.device_registry import DeviceEntryType
@ -23,7 +23,7 @@ from .const import DOMAIN
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
UNIT_MAPPING = { UNIT_MAPPING = {
"http://qudt.org/1.1/vocab/unit#Meter": LENGTH_METERS, "http://qudt.org/1.1/vocab/unit#Meter": UnitOfLength.METERS,
} }

View File

@ -11,8 +11,7 @@ from homeassistant.const import (
CONF_LONGITUDE, CONF_LONGITUDE,
CONF_RADIUS, CONF_RADIUS,
CONF_SCAN_INTERVAL, CONF_SCAN_INTERVAL,
LENGTH_KILOMETERS, UnitOfLength,
LENGTH_MILES,
) )
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import aiohttp_client, config_validation as cv from homeassistant.helpers import aiohttp_client, config_validation as cv
@ -89,7 +88,9 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
radius = config_entry.data[CONF_RADIUS] radius = config_entry.data[CONF_RADIUS]
if hass.config.units is US_CUSTOMARY_SYSTEM: if hass.config.units is US_CUSTOMARY_SYSTEM:
radius = DistanceConverter.convert(radius, LENGTH_MILES, LENGTH_KILOMETERS) radius = DistanceConverter.convert(
radius, UnitOfLength.MILES, UnitOfLength.KILOMETERS
)
# Create feed entity manager for all platforms. # Create feed entity manager for all platforms.
manager = GdacsFeedEntityManager(hass, config_entry, radius) manager = GdacsFeedEntityManager(hass, config_entry, radius)
feeds[config_entry.entry_id] = manager feeds[config_entry.entry_id] = manager

View File

@ -10,7 +10,7 @@ from aio_georss_gdacs.feed_entry import GdacsFeedEntry
from homeassistant.components.geo_location import GeolocationEvent from homeassistant.components.geo_location import GeolocationEvent
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import LENGTH_KILOMETERS, LENGTH_MILES from homeassistant.const import UnitOfLength
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
@ -89,7 +89,7 @@ class GdacsEvent(GeolocationEvent):
self._feed_manager = feed_manager self._feed_manager = feed_manager
self._external_id = external_id self._external_id = external_id
self._attr_unique_id = f"{integration_id}_{external_id}" self._attr_unique_id = f"{integration_id}_{external_id}"
self._attr_unit_of_measurement = LENGTH_KILOMETERS self._attr_unit_of_measurement = UnitOfLength.KILOMETERS
self._alert_level = None self._alert_level = None
self._country = None self._country = None
self._description = None self._description = None
@ -108,7 +108,7 @@ class GdacsEvent(GeolocationEvent):
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
"""Call when entity is added to hass.""" """Call when entity is added to hass."""
if self.hass.config.units is US_CUSTOMARY_SYSTEM: if self.hass.config.units is US_CUSTOMARY_SYSTEM:
self._attr_unit_of_measurement = LENGTH_MILES self._attr_unit_of_measurement = UnitOfLength.MILES
self._remove_signal_delete = async_dispatcher_connect( self._remove_signal_delete = async_dispatcher_connect(
self.hass, f"gdacs_delete_{self._external_id}", self._delete_callback self.hass, f"gdacs_delete_{self._external_id}", self._delete_callback
) )
@ -151,7 +151,7 @@ class GdacsEvent(GeolocationEvent):
# Convert distance if not metric system. # Convert distance if not metric system.
if self.hass.config.units is US_CUSTOMARY_SYSTEM: if self.hass.config.units is US_CUSTOMARY_SYSTEM:
self._attr_distance = DistanceConverter.convert( self._attr_distance = DistanceConverter.convert(
feed_entry.distance_to_home, LENGTH_KILOMETERS, LENGTH_MILES feed_entry.distance_to_home, UnitOfLength.KILOMETERS, UnitOfLength.MILES
) )
else: else:
self._attr_distance = feed_entry.distance_to_home self._attr_distance = feed_entry.distance_to_home

View File

@ -18,7 +18,7 @@ from homeassistant.const import (
CONF_SCAN_INTERVAL, CONF_SCAN_INTERVAL,
CONF_URL, CONF_URL,
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_START,
LENGTH_KILOMETERS, UnitOfLength,
) )
from homeassistant.core import Event, HomeAssistant, callback from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.helpers import aiohttp_client from homeassistant.helpers import aiohttp_client
@ -146,7 +146,7 @@ class GeoJsonLocationEvent(GeolocationEvent):
_attr_should_poll = False _attr_should_poll = False
_attr_source = SOURCE _attr_source = SOURCE
_attr_unit_of_measurement = LENGTH_KILOMETERS _attr_unit_of_measurement = UnitOfLength.KILOMETERS
def __init__(self, feed_manager: GenericFeedManager, external_id: str) -> None: def __init__(self, feed_manager: GenericFeedManager, external_id: str) -> None:
"""Initialize entity with data from feed entry.""" """Initialize entity with data from feed entry."""

View File

@ -22,7 +22,7 @@ from homeassistant.const import (
CONF_RADIUS, CONF_RADIUS,
CONF_UNIT_OF_MEASUREMENT, CONF_UNIT_OF_MEASUREMENT,
CONF_URL, CONF_URL,
LENGTH_KILOMETERS, UnitOfLength,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -162,7 +162,9 @@ class GeoRssServiceSensor(SensorEntity):
# And now compute the attributes from the filtered events. # And now compute the attributes from the filtered events.
matrix = {} matrix = {}
for entry in feed_entries: for entry in feed_entries:
matrix[entry.title] = f"{entry.distance_to_home:.0f}{LENGTH_KILOMETERS}" matrix[
entry.title
] = f"{entry.distance_to_home:.0f}{UnitOfLength.KILOMETERS}"
self._state_attributes = matrix self._state_attributes = matrix
elif status == UPDATE_OK_NO_DATA: elif status == UPDATE_OK_NO_DATA:
_LOGGER.debug("Update successful, but no data received from %s", self._feed) _LOGGER.debug("Update successful, but no data received from %s", self._feed)

View File

@ -11,8 +11,7 @@ from homeassistant.const import (
CONF_LONGITUDE, CONF_LONGITUDE,
CONF_RADIUS, CONF_RADIUS,
CONF_SCAN_INTERVAL, CONF_SCAN_INTERVAL,
LENGTH_KILOMETERS, UnitOfLength,
LENGTH_MILES,
) )
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import aiohttp_client, config_validation as cv from homeassistant.helpers import aiohttp_client, config_validation as cv
@ -96,7 +95,9 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
radius = config_entry.data[CONF_RADIUS] radius = config_entry.data[CONF_RADIUS]
if hass.config.units is US_CUSTOMARY_SYSTEM: if hass.config.units is US_CUSTOMARY_SYSTEM:
radius = DistanceConverter.convert(radius, LENGTH_MILES, LENGTH_KILOMETERS) radius = DistanceConverter.convert(
radius, UnitOfLength.MILES, UnitOfLength.KILOMETERS
)
# Create feed entity manager for all platforms. # Create feed entity manager for all platforms.
manager = GeonetnzQuakesFeedEntityManager(hass, config_entry, radius) manager = GeonetnzQuakesFeedEntityManager(hass, config_entry, radius)
feeds[config_entry.entry_id] = manager feeds[config_entry.entry_id] = manager

View File

@ -9,7 +9,7 @@ from aio_geojson_geonetnz_quakes.feed_entry import GeonetnzQuakesFeedEntry
from homeassistant.components.geo_location import GeolocationEvent from homeassistant.components.geo_location import GeolocationEvent
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_TIME, LENGTH_KILOMETERS, LENGTH_MILES from homeassistant.const import ATTR_TIME, UnitOfLength
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
@ -81,7 +81,7 @@ class GeonetnzQuakesEvent(GeolocationEvent):
self._feed_manager = feed_manager self._feed_manager = feed_manager
self._external_id = external_id self._external_id = external_id
self._attr_unique_id = f"{integration_id}_{external_id}" self._attr_unique_id = f"{integration_id}_{external_id}"
self._attr_unit_of_measurement = LENGTH_KILOMETERS self._attr_unit_of_measurement = UnitOfLength.KILOMETERS
self._depth = None self._depth = None
self._locality = None self._locality = None
self._magnitude = None self._magnitude = None
@ -94,7 +94,7 @@ class GeonetnzQuakesEvent(GeolocationEvent):
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
"""Call when entity is added to hass.""" """Call when entity is added to hass."""
if self.hass.config.units is US_CUSTOMARY_SYSTEM: if self.hass.config.units is US_CUSTOMARY_SYSTEM:
self._attr_unit_of_measurement = LENGTH_MILES self._attr_unit_of_measurement = UnitOfLength.MILES
self._remove_signal_delete = async_dispatcher_connect( self._remove_signal_delete = async_dispatcher_connect(
self.hass, self.hass,
f"geonetnz_quakes_delete_{self._external_id}", f"geonetnz_quakes_delete_{self._external_id}",
@ -138,7 +138,7 @@ class GeonetnzQuakesEvent(GeolocationEvent):
# Convert distance if not metric system. # Convert distance if not metric system.
if self.hass.config.units is US_CUSTOMARY_SYSTEM: if self.hass.config.units is US_CUSTOMARY_SYSTEM:
self._attr_distance = DistanceConverter.convert( self._attr_distance = DistanceConverter.convert(
feed_entry.distance_to_home, LENGTH_KILOMETERS, LENGTH_MILES feed_entry.distance_to_home, UnitOfLength.KILOMETERS, UnitOfLength.MILES
) )
else: else:
self._attr_distance = feed_entry.distance_to_home self._attr_distance = feed_entry.distance_to_home

View File

@ -14,8 +14,7 @@ from homeassistant.const import (
CONF_RADIUS, CONF_RADIUS,
CONF_SCAN_INTERVAL, CONF_SCAN_INTERVAL,
CONF_UNIT_SYSTEM, CONF_UNIT_SYSTEM,
LENGTH_KILOMETERS, UnitOfLength,
LENGTH_MILES,
) )
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import aiohttp_client, config_validation as cv from homeassistant.helpers import aiohttp_client, config_validation as cv
@ -92,7 +91,9 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
radius = config_entry.data[CONF_RADIUS] radius = config_entry.data[CONF_RADIUS]
unit_system = config_entry.data[CONF_UNIT_SYSTEM] unit_system = config_entry.data[CONF_UNIT_SYSTEM]
if unit_system == IMPERIAL_UNITS: if unit_system == IMPERIAL_UNITS:
radius = DistanceConverter.convert(radius, LENGTH_MILES, LENGTH_KILOMETERS) radius = DistanceConverter.convert(
radius, UnitOfLength.MILES, UnitOfLength.KILOMETERS
)
# Create feed entity manager for all platforms. # Create feed entity manager for all platforms.
manager = GeonetnzVolcanoFeedEntityManager(hass, config_entry, radius, unit_system) manager = GeonetnzVolcanoFeedEntityManager(hass, config_entry, radius, unit_system)
hass.data[DOMAIN][FEED][config_entry.entry_id] = manager hass.data[DOMAIN][FEED][config_entry.entry_id] = manager

View File

@ -5,12 +5,7 @@ import logging
from homeassistant.components.sensor import SensorEntity from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE, UnitOfLength
ATTR_LATITUDE,
ATTR_LONGITUDE,
LENGTH_KILOMETERS,
LENGTH_MILES,
)
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
@ -115,7 +110,9 @@ class GeonetnzVolcanoSensor(SensorEntity):
if self._unit_system == IMPERIAL_UNITS: if self._unit_system == IMPERIAL_UNITS:
self._distance = round( self._distance = round(
DistanceConverter.convert( DistanceConverter.convert(
feed_entry.distance_to_home, LENGTH_KILOMETERS, LENGTH_MILES feed_entry.distance_to_home,
UnitOfLength.KILOMETERS,
UnitOfLength.MILES,
), ),
1, 1,
) )

View File

@ -13,7 +13,7 @@ from homeassistant.components.sensor import (
SensorStateClass, SensorStateClass,
) )
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import LENGTH_METERS, SIGNAL_STRENGTH_DECIBELS_MILLIWATT from homeassistant.const import SIGNAL_STRENGTH_DECIBELS_MILLIWATT, UnitOfLength
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
@ -58,7 +58,7 @@ SENSOR_DESCRIPTIONS = (
key="estimated_distance", key="estimated_distance",
name="Estimated Distance", name="Estimated Distance",
icon="mdi:signal-distance-variant", icon="mdi:signal-distance-variant",
native_unit_of_measurement=LENGTH_METERS, native_unit_of_measurement=UnitOfLength.METERS,
value_fn=lambda ibeacon_advertisement: ibeacon_advertisement.distance, value_fn=lambda ibeacon_advertisement: ibeacon_advertisement.distance,
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
device_class=SensorDeviceClass.DISTANCE, device_class=SensorDeviceClass.DISTANCE,

View File

@ -19,7 +19,7 @@ from homeassistant.const import (
CONF_RADIUS, CONF_RADIUS,
CONF_SCAN_INTERVAL, CONF_SCAN_INTERVAL,
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_START,
LENGTH_KILOMETERS, UnitOfLength,
) )
from homeassistant.core import Event, HomeAssistant, callback from homeassistant.core import Event, HomeAssistant, callback
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -146,7 +146,7 @@ class IgnSismologiaLocationEvent(GeolocationEvent):
_attr_icon = "mdi:pulse" _attr_icon = "mdi:pulse"
_attr_should_poll = False _attr_should_poll = False
_attr_source = SOURCE _attr_source = SOURCE
_attr_unit_of_measurement = LENGTH_KILOMETERS _attr_unit_of_measurement = UnitOfLength.KILOMETERS
def __init__( def __init__(
self, feed_manager: IgnSismologiaFeedEntityManager, external_id: str self, feed_manager: IgnSismologiaFeedEntityManager, external_id: str

View File

@ -11,12 +11,7 @@ from typing import Any
from life360 import Life360, Life360Error, LoginError from life360 import Life360, Life360Error, LoginError
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import UnitOfLength
LENGTH_FEET,
LENGTH_KILOMETERS,
LENGTH_METERS,
LENGTH_MILES,
)
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
@ -211,7 +206,7 @@ class Life360DataUpdateCoordinator(DataUpdateCoordinator[Life360Data]):
speed = max(0, float(loc["speed"]) * SPEED_FACTOR_MPH) speed = max(0, float(loc["speed"]) * SPEED_FACTOR_MPH)
if self._hass.config.units is METRIC_SYSTEM: if self._hass.config.units is METRIC_SYSTEM:
speed = DistanceConverter.convert( speed = DistanceConverter.convert(
speed, LENGTH_MILES, LENGTH_KILOMETERS speed, UnitOfLength.MILES, UnitOfLength.KILOMETERS
) )
data.members[member_id] = Life360Member( data.members[member_id] = Life360Member(
@ -225,7 +220,9 @@ class Life360DataUpdateCoordinator(DataUpdateCoordinator[Life360Data]):
# gps_accuracy in meters. # gps_accuracy in meters.
round( round(
DistanceConverter.convert( DistanceConverter.convert(
float(loc["accuracy"]), LENGTH_FEET, LENGTH_METERS float(loc["accuracy"]),
UnitOfLength.FEET,
UnitOfLength.METERS,
) )
), ),
dt_util.utc_from_timestamp(int(loc["timestamp"])), dt_util.utc_from_timestamp(int(loc["timestamp"])),

View File

@ -12,12 +12,7 @@ from homeassistant.components.sensor import (
SensorStateClass, SensorStateClass,
) )
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import PERCENTAGE, PRESSURE_PSI, UnitOfLength
LENGTH_KILOMETERS,
LENGTH_MILES,
PERCENTAGE,
PRESSURE_PSI,
)
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
@ -52,8 +47,8 @@ class MazdaSensorEntityDescription(
def _get_distance_unit(unit_system: UnitSystem) -> str: def _get_distance_unit(unit_system: UnitSystem) -> str:
"""Return the distance unit for the given unit system.""" """Return the distance unit for the given unit system."""
if unit_system is US_CUSTOMARY_SYSTEM: if unit_system is US_CUSTOMARY_SYSTEM:
return LENGTH_MILES return UnitOfLength.MILES
return LENGTH_KILOMETERS return UnitOfLength.KILOMETERS
def _fuel_remaining_percentage_supported(data): def _fuel_remaining_percentage_supported(data):
@ -109,14 +104,18 @@ def _ev_remaining_range_supported(data):
def _fuel_distance_remaining_value(data, unit_system): def _fuel_distance_remaining_value(data, unit_system):
"""Get the fuel distance remaining value.""" """Get the fuel distance remaining value."""
return round( return round(
unit_system.length(data["status"]["fuelDistanceRemainingKm"], LENGTH_KILOMETERS) unit_system.length(
data["status"]["fuelDistanceRemainingKm"], UnitOfLength.KILOMETERS
)
) )
def _odometer_value(data, unit_system): def _odometer_value(data, unit_system):
"""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(unit_system.length(data["status"]["odometerKm"], LENGTH_KILOMETERS)) return int(
unit_system.length(data["status"]["odometerKm"], UnitOfLength.KILOMETERS)
)
def _front_left_tire_pressure_value(data, unit_system): def _front_left_tire_pressure_value(data, unit_system):
@ -148,7 +147,7 @@ def _ev_remaining_range_value(data, unit_system):
"""Get the remaining range value.""" """Get the remaining range value."""
return round( return round(
unit_system.length( unit_system.length(
data["evStatus"]["chargeInfo"]["drivingRangeKm"], LENGTH_KILOMETERS data["evStatus"]["chargeInfo"]["drivingRangeKm"], UnitOfLength.KILOMETERS
) )
) )

View File

@ -16,9 +16,8 @@ from homeassistant.const import (
CONF_LATITUDE, CONF_LATITUDE,
CONF_LONGITUDE, CONF_LONGITUDE,
EVENT_CORE_CONFIG_UPDATE, EVENT_CORE_CONFIG_UPDATE,
LENGTH_FEET,
LENGTH_METERS,
Platform, Platform,
UnitOfLength,
) )
from homeassistant.core import Event, HomeAssistant from homeassistant.core import Event, HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
@ -161,7 +160,11 @@ class MetWeatherData:
if not self._is_metric: if not self._is_metric:
elevation = int( elevation = int(
round(DistanceConverter.convert(elevation, LENGTH_FEET, LENGTH_METERS)) round(
DistanceConverter.convert(
elevation, UnitOfLength.FEET, UnitOfLength.METERS
)
)
) )
coordinates = { coordinates = {

View File

@ -6,7 +6,7 @@ import logging
from voluptuous.validators import Number from voluptuous.validators import Number
from homeassistant.components.sensor import SensorDeviceClass, SensorEntity from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
from homeassistant.const import LENGTH_KILOMETERS, LENGTH_MILES, PERCENTAGE from homeassistant.const import PERCENTAGE, UnitOfLength
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.icon import icon_for_battery_level from homeassistant.helpers.icon import icon_for_battery_level
@ -117,7 +117,9 @@ class LeafRangeSensor(LeafEntity, SensorEntity):
return None return None
if self.car.hass.config.units is US_CUSTOMARY_SYSTEM or self.car.force_miles: if self.car.hass.config.units is US_CUSTOMARY_SYSTEM or self.car.force_miles:
ret = DistanceConverter.convert(ret, LENGTH_KILOMETERS, LENGTH_MILES) ret = DistanceConverter.convert(
ret, UnitOfLength.KILOMETERS, UnitOfLength.MILES
)
return round(ret) return round(ret)
@ -125,5 +127,5 @@ class LeafRangeSensor(LeafEntity, SensorEntity):
def native_unit_of_measurement(self) -> str: def native_unit_of_measurement(self) -> str:
"""Battery range unit.""" """Battery range unit."""
if self.car.hass.config.units is US_CUSTOMARY_SYSTEM or self.car.force_miles: if self.car.hass.config.units is US_CUSTOMARY_SYSTEM or self.car.force_miles:
return LENGTH_MILES return UnitOfLength.MILES
return LENGTH_KILOMETERS return UnitOfLength.KILOMETERS

View File

@ -21,7 +21,7 @@ from homeassistant.const import (
CONF_SCAN_INTERVAL, CONF_SCAN_INTERVAL,
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STOP, EVENT_HOMEASSISTANT_STOP,
LENGTH_KILOMETERS, UnitOfLength,
) )
from homeassistant.core import Event, HomeAssistant, callback from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.helpers import aiohttp_client, config_validation as cv from homeassistant.helpers import aiohttp_client, config_validation as cv
@ -181,7 +181,7 @@ class NswRuralFireServiceLocationEvent(GeolocationEvent):
_attr_should_poll = False _attr_should_poll = False
_attr_source = SOURCE _attr_source = SOURCE
_attr_unit_of_measurement = LENGTH_KILOMETERS _attr_unit_of_measurement = UnitOfLength.KILOMETERS
def __init__( def __init__(
self, feed_manager: NswRuralFireServiceFeedEntityManager, external_id: str self, feed_manager: NswRuralFireServiceFeedEntityManager, external_id: str

View File

@ -11,10 +11,10 @@ from homeassistant.components.sensor import (
) )
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
LENGTH_CENTIMETERS,
PERCENTAGE, PERCENTAGE,
SIGNAL_STRENGTH_DECIBELS_MILLIWATT, SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
TEMP_CELSIUS, TEMP_CELSIUS,
UnitOfLength,
) )
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity import EntityCategory
@ -28,7 +28,7 @@ _LOGGER = logging.getLogger(__name__)
SENSOR_TYPES: tuple[SensorEntityDescription, ...] = ( SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription( SensorEntityDescription(
key="dist", key="dist",
native_unit_of_measurement=LENGTH_CENTIMETERS, native_unit_of_measurement=UnitOfLength.CENTIMETERS,
device_class=SensorDeviceClass.DISTANCE, device_class=SensorDeviceClass.DISTANCE,
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
), ),

View File

@ -14,8 +14,7 @@ from homeassistant.const import (
CONF_LONGITUDE, CONF_LONGITUDE,
CONF_NAME, CONF_NAME,
CONF_RADIUS, CONF_RADIUS,
LENGTH_KILOMETERS, UnitOfLength,
LENGTH_METERS,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -107,7 +106,7 @@ class OpenSkySensor(SensorEntity):
self._latitude = latitude self._latitude = latitude
self._longitude = longitude self._longitude = longitude
self._radius = DistanceConverter.convert( self._radius = DistanceConverter.convert(
radius, LENGTH_KILOMETERS, LENGTH_METERS radius, UnitOfLength.KILOMETERS, UnitOfLength.METERS
) )
self._altitude = altitude self._altitude = altitude
self._state = 0 self._state = 0

View File

@ -11,11 +11,7 @@ from homeassistant.const import (
CONF_DEVICES, CONF_DEVICES,
CONF_UNIT_OF_MEASUREMENT, CONF_UNIT_OF_MEASUREMENT,
CONF_ZONE, CONF_ZONE,
LENGTH_FEET, UnitOfLength,
LENGTH_KILOMETERS,
LENGTH_METERS,
LENGTH_MILES,
LENGTH_YARD,
) )
from homeassistant.core import HomeAssistant, State from homeassistant.core import HomeAssistant, State
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -42,11 +38,11 @@ DEFAULT_TOLERANCE = 1
DOMAIN = "proximity" DOMAIN = "proximity"
UNITS = [ UNITS = [
LENGTH_METERS, UnitOfLength.METERS,
LENGTH_KILOMETERS, UnitOfLength.KILOMETERS,
LENGTH_FEET, UnitOfLength.FEET,
LENGTH_YARD, UnitOfLength.YARDS,
LENGTH_MILES, UnitOfLength.MILES,
] ]
ZONE_SCHEMA = vol.Schema( ZONE_SCHEMA = vol.Schema(
@ -236,7 +232,7 @@ class Proximity(Entity):
continue continue
distances_to_zone[device] = round( distances_to_zone[device] = round(
DistanceConverter.convert( DistanceConverter.convert(
proximity, LENGTH_METERS, self.unit_of_measurement proximity, UnitOfLength.METERS, self.unit_of_measurement
), ),
1, 1,
) )

View File

@ -19,7 +19,7 @@ from homeassistant.const import (
CONF_RADIUS, CONF_RADIUS,
CONF_SCAN_INTERVAL, CONF_SCAN_INTERVAL,
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_START,
LENGTH_KILOMETERS, UnitOfLength,
) )
from homeassistant.core import Event, HomeAssistant, callback from homeassistant.core import Event, HomeAssistant, callback
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -154,7 +154,7 @@ class QldBushfireLocationEvent(GeolocationEvent):
_attr_icon = "mdi:fire" _attr_icon = "mdi:fire"
_attr_should_poll = False _attr_should_poll = False
_attr_source = SOURCE _attr_source = SOURCE
_attr_unit_of_measurement = LENGTH_KILOMETERS _attr_unit_of_measurement = UnitOfLength.KILOMETERS
def __init__( def __init__(
self, feed_manager: QldBushfireFeedEntityManager, external_id: str self, feed_manager: QldBushfireFeedEntityManager, external_id: str

View File

@ -24,10 +24,10 @@ from homeassistant.components.sensor import (
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
ENERGY_KILO_WATT_HOUR, ENERGY_KILO_WATT_HOUR,
LENGTH_KILOMETERS,
PERCENTAGE, PERCENTAGE,
TEMP_CELSIUS, TEMP_CELSIUS,
TIME_MINUTES, TIME_MINUTES,
UnitOfLength,
UnitOfPower, UnitOfPower,
UnitOfVolume, UnitOfVolume,
) )
@ -246,7 +246,7 @@ SENSOR_TYPES: tuple[RenaultSensorEntityDescription[Any], ...] = (
entity_class=RenaultSensor[KamereonVehicleBatteryStatusData], entity_class=RenaultSensor[KamereonVehicleBatteryStatusData],
icon="mdi:ev-station", icon="mdi:ev-station",
name="Battery autonomy", name="Battery autonomy",
native_unit_of_measurement=LENGTH_KILOMETERS, native_unit_of_measurement=UnitOfLength.KILOMETERS,
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
), ),
RenaultSensorEntityDescription( RenaultSensorEntityDescription(
@ -287,7 +287,7 @@ SENSOR_TYPES: tuple[RenaultSensorEntityDescription[Any], ...] = (
entity_class=RenaultSensor[KamereonVehicleCockpitData], entity_class=RenaultSensor[KamereonVehicleCockpitData],
icon="mdi:sign-direction", icon="mdi:sign-direction",
name="Mileage", name="Mileage",
native_unit_of_measurement=LENGTH_KILOMETERS, native_unit_of_measurement=UnitOfLength.KILOMETERS,
state_class=SensorStateClass.TOTAL_INCREASING, state_class=SensorStateClass.TOTAL_INCREASING,
value_lambda=_get_rounded_value, value_lambda=_get_rounded_value,
), ),
@ -299,7 +299,7 @@ SENSOR_TYPES: tuple[RenaultSensorEntityDescription[Any], ...] = (
entity_class=RenaultSensor[KamereonVehicleCockpitData], entity_class=RenaultSensor[KamereonVehicleCockpitData],
icon="mdi:gas-station", icon="mdi:gas-station",
name="Fuel autonomy", name="Fuel autonomy",
native_unit_of_measurement=LENGTH_KILOMETERS, native_unit_of_measurement=UnitOfLength.KILOMETERS,
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
requires_fuel=True, requires_fuel=True,
value_lambda=_get_rounded_value, value_lambda=_get_rounded_value,

View File

@ -11,9 +11,9 @@ from homeassistant.components.sensor import (
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
ELECTRIC_POTENTIAL_VOLT, ELECTRIC_POTENTIAL_VOLT,
LENGTH_KILOMETERS,
PERCENTAGE, PERCENTAGE,
TEMP_CELSIUS, TEMP_CELSIUS,
UnitOfLength,
UnitOfVolume, UnitOfVolume,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
@ -80,7 +80,7 @@ SENSOR_TYPES: tuple[StarlineSensorEntityDescription, ...] = (
StarlineSensorEntityDescription( StarlineSensorEntityDescription(
key="mileage", key="mileage",
name_="Mileage", name_="Mileage",
native_unit_of_measurement=LENGTH_KILOMETERS, native_unit_of_measurement=UnitOfLength.KILOMETERS,
device_class=SensorDeviceClass.DISTANCE, device_class=SensorDeviceClass.DISTANCE,
icon="mdi:counter", icon="mdi:counter",
), ),

View File

@ -13,13 +13,7 @@ from homeassistant.components.sensor import (
SensorStateClass, SensorStateClass,
) )
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import PERCENTAGE, PRESSURE_HPA, UnitOfLength, UnitOfVolume
LENGTH_KILOMETERS,
LENGTH_MILES,
PERCENTAGE,
PRESSURE_HPA,
UnitOfVolume,
)
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
@ -55,7 +49,7 @@ FUEL_CONSUMPTION_LITERS_PER_HUNDRED_KILOMETERS = "L/100km"
FUEL_CONSUMPTION_MILES_PER_GALLON = "mi/gal" FUEL_CONSUMPTION_MILES_PER_GALLON = "mi/gal"
L_PER_GAL = VolumeConverter.convert(1, UnitOfVolume.GALLONS, UnitOfVolume.LITERS) L_PER_GAL = VolumeConverter.convert(1, UnitOfVolume.GALLONS, UnitOfVolume.LITERS)
KM_PER_MI = DistanceConverter.convert(1, LENGTH_MILES, LENGTH_KILOMETERS) KM_PER_MI = DistanceConverter.convert(1, UnitOfLength.MILES, UnitOfLength.KILOMETERS)
# Sensor available to "Subaru Safety Plus" subscribers with Gen1 or Gen2 vehicles # Sensor available to "Subaru Safety Plus" subscribers with Gen1 or Gen2 vehicles
SAFETY_SENSORS = [ SAFETY_SENSORS = [
@ -64,7 +58,7 @@ SAFETY_SENSORS = [
device_class=SensorDeviceClass.DISTANCE, device_class=SensorDeviceClass.DISTANCE,
icon="mdi:road-variant", icon="mdi:road-variant",
name="Odometer", name="Odometer",
native_unit_of_measurement=LENGTH_KILOMETERS, native_unit_of_measurement=UnitOfLength.KILOMETERS,
state_class=SensorStateClass.TOTAL_INCREASING, state_class=SensorStateClass.TOTAL_INCREASING,
), ),
] ]
@ -83,7 +77,7 @@ API_GEN_2_SENSORS = [
device_class=SensorDeviceClass.DISTANCE, device_class=SensorDeviceClass.DISTANCE,
icon="mdi:gas-station", icon="mdi:gas-station",
name="Range", name="Range",
native_unit_of_measurement=LENGTH_KILOMETERS, native_unit_of_measurement=UnitOfLength.KILOMETERS,
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
), ),
SensorEntityDescription( SensorEntityDescription(
@ -123,7 +117,7 @@ EV_SENSORS = [
device_class=SensorDeviceClass.DISTANCE, device_class=SensorDeviceClass.DISTANCE,
icon="mdi:ev-station", icon="mdi:ev-station",
name="EV range", name="EV range",
native_unit_of_measurement=LENGTH_MILES, native_unit_of_measurement=UnitOfLength.MILES,
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
), ),
SensorEntityDescription( SensorEntityDescription(

View File

@ -16,7 +16,7 @@ from homeassistant.const import (
CONF_NAME, CONF_NAME,
CONF_RADIUS, CONF_RADIUS,
CONF_SHOW_ON_MAP, CONF_SHOW_ON_MAP,
LENGTH_KILOMETERS, UnitOfLength,
) )
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.data_entry_flow import FlowResult from homeassistant.data_entry_flow import FlowResult
@ -204,7 +204,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
min=1.0, min=1.0,
max=25, max=25,
step=0.1, step=0.1,
unit_of_measurement=LENGTH_KILOMETERS, unit_of_measurement=UnitOfLength.KILOMETERS,
), ),
), ),
} }

View File

@ -22,7 +22,6 @@ from homeassistant.const import (
ELECTRIC_CURRENT_AMPERE, ELECTRIC_CURRENT_AMPERE,
ELECTRIC_POTENTIAL_VOLT, ELECTRIC_POTENTIAL_VOLT,
ENERGY_KILO_WATT_HOUR, ENERGY_KILO_WATT_HOUR,
LENGTH_CENTIMETERS,
LIGHT_LUX, LIGHT_LUX,
PERCENTAGE, PERCENTAGE,
PRESSURE_HPA, PRESSURE_HPA,
@ -36,6 +35,7 @@ from homeassistant.const import (
TEMP_KELVIN, TEMP_KELVIN,
UnitOfApparentPower, UnitOfApparentPower,
UnitOfFrequency, UnitOfFrequency,
UnitOfLength,
UnitOfMass, UnitOfMass,
UnitOfPower, UnitOfPower,
) )
@ -217,7 +217,7 @@ SENSOR_UNIT_MAP = {
hc.ELECTRICAL_VOLT_AMPERE: UnitOfApparentPower.VOLT_AMPERE, hc.ELECTRICAL_VOLT_AMPERE: UnitOfApparentPower.VOLT_AMPERE,
hc.ENERGY_KILO_WATT_HOUR: ENERGY_KILO_WATT_HOUR, hc.ENERGY_KILO_WATT_HOUR: ENERGY_KILO_WATT_HOUR,
hc.FREQUENCY_HERTZ: UnitOfFrequency.HERTZ, hc.FREQUENCY_HERTZ: UnitOfFrequency.HERTZ,
hc.LENGTH_CENTIMETERS: LENGTH_CENTIMETERS, hc.LENGTH_CENTIMETERS: UnitOfLength.CENTIMETERS,
hc.LIGHT_LUX: LIGHT_LUX, hc.LIGHT_LUX: LIGHT_LUX,
hc.MASS_KILOGRAMS: UnitOfMass.KILOGRAMS, hc.MASS_KILOGRAMS: UnitOfMass.KILOGRAMS,
hc.PERCENTAGE: PERCENTAGE, hc.PERCENTAGE: PERCENTAGE,

View File

@ -20,7 +20,7 @@ from homeassistant.const import (
CONF_RADIUS, CONF_RADIUS,
CONF_SCAN_INTERVAL, CONF_SCAN_INTERVAL,
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_START,
LENGTH_KILOMETERS, UnitOfLength,
) )
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import aiohttp_client from homeassistant.helpers import aiohttp_client
@ -48,7 +48,7 @@ CONF_MINIMUM_MAGNITUDE = "minimum_magnitude"
DEFAULT_MINIMUM_MAGNITUDE = 0.0 DEFAULT_MINIMUM_MAGNITUDE = 0.0
DEFAULT_RADIUS_IN_KM = 50.0 DEFAULT_RADIUS_IN_KM = 50.0
DEFAULT_UNIT_OF_MEASUREMENT = LENGTH_KILOMETERS DEFAULT_UNIT_OF_MEASUREMENT = UnitOfLength.KILOMETERS
SCAN_INTERVAL = timedelta(minutes=5) SCAN_INTERVAL = timedelta(minutes=5)

View File

@ -15,8 +15,8 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
ELECTRIC_CURRENT_AMPERE, ELECTRIC_CURRENT_AMPERE,
ENERGY_KILO_WATT_HOUR, ENERGY_KILO_WATT_HOUR,
LENGTH_KILOMETERS,
PERCENTAGE, PERCENTAGE,
UnitOfLength,
UnitOfPower, UnitOfPower,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
@ -86,7 +86,7 @@ SENSOR_TYPES: dict[str, WallboxSensorEntityDescription] = {
icon="mdi:map-marker-distance", icon="mdi:map-marker-distance",
name="Added Range", name="Added Range",
precision=0, precision=0,
native_unit_of_measurement=LENGTH_KILOMETERS, native_unit_of_measurement=UnitOfLength.KILOMETERS,
device_class=SensorDeviceClass.DISTANCE, device_class=SensorDeviceClass.DISTANCE,
state_class=SensorStateClass.TOTAL_INCREASING, state_class=SensorStateClass.TOTAL_INCREASING,
), ),

View File

@ -16,9 +16,8 @@ from homeassistant.const import (
CONF_NAME, CONF_NAME,
CONF_REGION, CONF_REGION,
EVENT_HOMEASSISTANT_STARTED, EVENT_HOMEASSISTANT_STARTED,
LENGTH_KILOMETERS,
LENGTH_MILES,
TIME_MINUTES, TIME_MINUTES,
UnitOfLength,
) )
from homeassistant.core import CoreState, HomeAssistant from homeassistant.core import CoreState, HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntryType from homeassistant.helpers.device_registry import DeviceEntryType
@ -210,7 +209,7 @@ class WazeTravelTimeData:
if units == IMPERIAL_UNITS: if units == IMPERIAL_UNITS:
# Convert to miles. # Convert to miles.
self.distance = DistanceConverter.convert( self.distance = DistanceConverter.convert(
distance, LENGTH_KILOMETERS, LENGTH_MILES distance, UnitOfLength.KILOMETERS, UnitOfLength.MILES
) )
else: else:
self.distance = distance self.distance = distance