diff --git a/homeassistant/components/adguard/sensor.py b/homeassistant/components/adguard/sensor.py index 9d0d5245d80..5abff10739a 100644 --- a/homeassistant/components/adguard/sensor.py +++ b/homeassistant/components/adguard/sensor.py @@ -11,7 +11,7 @@ from homeassistant.components.adguard.const import ( DOMAIN, ) from homeassistant.config_entries import ConfigEntry -from homeassistant.const import TIME_MILLISECONDS +from homeassistant.const import TIME_MILLISECONDS, UNIT_PERCENTAGE from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.typing import HomeAssistantType @@ -134,7 +134,7 @@ class AdGuardHomePercentageBlockedSensor(AdGuardHomeSensor): "AdGuard DNS Queries Blocked Ratio", "mdi:magnify-close", "blocked_percentage", - "%", + UNIT_PERCENTAGE, ) async def _adguard_update(self) -> None: diff --git a/homeassistant/components/airly/sensor.py b/homeassistant/components/airly/sensor.py index 2d42dac5614..a6754b4a00d 100644 --- a/homeassistant/components/airly/sensor.py +++ b/homeassistant/components/airly/sensor.py @@ -9,6 +9,7 @@ from homeassistant.const import ( DEVICE_CLASS_TEMPERATURE, PRESSURE_HPA, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.helpers.entity import Entity @@ -27,8 +28,6 @@ ATTR_ICON = "icon" ATTR_LABEL = "label" ATTR_UNIT = "unit" -HUMI_PERCENT = "%" - SENSOR_TYPES = { ATTR_API_PM1: { ATTR_DEVICE_CLASS: None, @@ -40,7 +39,7 @@ SENSOR_TYPES = { ATTR_DEVICE_CLASS: DEVICE_CLASS_HUMIDITY, ATTR_ICON: None, ATTR_LABEL: ATTR_API_HUMIDITY.capitalize(), - ATTR_UNIT: HUMI_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_API_PRESSURE: { ATTR_DEVICE_CLASS: DEVICE_CLASS_PRESSURE, diff --git a/homeassistant/components/ambient_station/__init__.py b/homeassistant/components/ambient_station/__init__.py index 63c00b05038..4fd6590b286 100644 --- a/homeassistant/components/ambient_station/__init__.py +++ b/homeassistant/components/ambient_station/__init__.py @@ -14,6 +14,7 @@ from homeassistant.const import ( CONF_API_KEY, EVENT_HOMEASSISTANT_STOP, SPEED_MILES_PER_HOUR, + UNIT_PERCENTAGE, ) from homeassistant.core import callback from homeassistant.exceptions import ConfigEntryNotReady @@ -154,18 +155,18 @@ SENSOR_TYPES = { TYPE_EVENTRAININ: ("Event Rain", "in", TYPE_SENSOR, None), TYPE_FEELSLIKE: ("Feels Like", "°F", TYPE_SENSOR, "temperature"), TYPE_HOURLYRAININ: ("Hourly Rain Rate", "in/hr", TYPE_SENSOR, None), - TYPE_HUMIDITY10: ("Humidity 10", "%", TYPE_SENSOR, "humidity"), - TYPE_HUMIDITY1: ("Humidity 1", "%", TYPE_SENSOR, "humidity"), - TYPE_HUMIDITY2: ("Humidity 2", "%", TYPE_SENSOR, "humidity"), - TYPE_HUMIDITY3: ("Humidity 3", "%", TYPE_SENSOR, "humidity"), - TYPE_HUMIDITY4: ("Humidity 4", "%", TYPE_SENSOR, "humidity"), - TYPE_HUMIDITY5: ("Humidity 5", "%", TYPE_SENSOR, "humidity"), - TYPE_HUMIDITY6: ("Humidity 6", "%", TYPE_SENSOR, "humidity"), - TYPE_HUMIDITY7: ("Humidity 7", "%", TYPE_SENSOR, "humidity"), - TYPE_HUMIDITY8: ("Humidity 8", "%", TYPE_SENSOR, "humidity"), - TYPE_HUMIDITY9: ("Humidity 9", "%", TYPE_SENSOR, "humidity"), - TYPE_HUMIDITY: ("Humidity", "%", TYPE_SENSOR, "humidity"), - TYPE_HUMIDITYIN: ("Humidity In", "%", TYPE_SENSOR, "humidity"), + TYPE_HUMIDITY10: ("Humidity 10", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_HUMIDITY1: ("Humidity 1", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_HUMIDITY2: ("Humidity 2", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_HUMIDITY3: ("Humidity 3", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_HUMIDITY4: ("Humidity 4", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_HUMIDITY5: ("Humidity 5", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_HUMIDITY6: ("Humidity 6", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_HUMIDITY7: ("Humidity 7", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_HUMIDITY8: ("Humidity 8", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_HUMIDITY9: ("Humidity 9", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_HUMIDITY: ("Humidity", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_HUMIDITYIN: ("Humidity In", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), TYPE_LASTRAIN: ("Last Rain", None, TYPE_SENSOR, "timestamp"), TYPE_MAXDAILYGUST: ("Max Gust", SPEED_MILES_PER_HOUR, TYPE_SENSOR, None), TYPE_MONTHLYRAININ: ("Monthly Rain", "in", TYPE_SENSOR, None), @@ -179,16 +180,16 @@ SENSOR_TYPES = { TYPE_RELAY7: ("Relay 7", None, TYPE_BINARY_SENSOR, "connectivity"), TYPE_RELAY8: ("Relay 8", None, TYPE_BINARY_SENSOR, "connectivity"), TYPE_RELAY9: ("Relay 9", None, TYPE_BINARY_SENSOR, "connectivity"), - TYPE_SOILHUM10: ("Soil Humidity 10", "%", TYPE_SENSOR, "humidity"), - TYPE_SOILHUM1: ("Soil Humidity 1", "%", TYPE_SENSOR, "humidity"), - TYPE_SOILHUM2: ("Soil Humidity 2", "%", TYPE_SENSOR, "humidity"), - TYPE_SOILHUM3: ("Soil Humidity 3", "%", TYPE_SENSOR, "humidity"), - TYPE_SOILHUM4: ("Soil Humidity 4", "%", TYPE_SENSOR, "humidity"), - TYPE_SOILHUM5: ("Soil Humidity 5", "%", TYPE_SENSOR, "humidity"), - TYPE_SOILHUM6: ("Soil Humidity 6", "%", TYPE_SENSOR, "humidity"), - TYPE_SOILHUM7: ("Soil Humidity 7", "%", TYPE_SENSOR, "humidity"), - TYPE_SOILHUM8: ("Soil Humidity 8", "%", TYPE_SENSOR, "humidity"), - TYPE_SOILHUM9: ("Soil Humidity 9", "%", TYPE_SENSOR, "humidity"), + TYPE_SOILHUM10: ("Soil Humidity 10", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_SOILHUM1: ("Soil Humidity 1", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_SOILHUM2: ("Soil Humidity 2", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_SOILHUM3: ("Soil Humidity 3", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_SOILHUM4: ("Soil Humidity 4", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_SOILHUM5: ("Soil Humidity 5", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_SOILHUM6: ("Soil Humidity 6", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_SOILHUM7: ("Soil Humidity 7", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_SOILHUM8: ("Soil Humidity 8", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), + TYPE_SOILHUM9: ("Soil Humidity 9", UNIT_PERCENTAGE, TYPE_SENSOR, "humidity"), TYPE_SOILTEMP10F: ("Soil Temp 10", "°F", TYPE_SENSOR, "temperature"), TYPE_SOILTEMP1F: ("Soil Temp 1", "°F", TYPE_SENSOR, "temperature"), TYPE_SOILTEMP2F: ("Soil Temp 2", "°F", TYPE_SENSOR, "temperature"), diff --git a/homeassistant/components/amcrest/sensor.py b/homeassistant/components/amcrest/sensor.py index bcff1775879..18abf28bdd5 100644 --- a/homeassistant/components/amcrest/sensor.py +++ b/homeassistant/components/amcrest/sensor.py @@ -4,7 +4,7 @@ import logging from amcrest import AmcrestError -from homeassistant.const import CONF_NAME, CONF_SENSORS +from homeassistant.const import CONF_NAME, CONF_SENSORS, UNIT_PERCENTAGE from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity @@ -20,7 +20,7 @@ SENSOR_SDCARD = "sdcard" # Sensor types are defined like: Name, units, icon SENSORS = { SENSOR_PTZ_PRESET: ["PTZ Preset", None, "mdi:camera-iris"], - SENSOR_SDCARD: ["SD Used", "%", "mdi:sd"], + SENSOR_SDCARD: ["SD Used", UNIT_PERCENTAGE, "mdi:sd"], } diff --git a/homeassistant/components/apcupsd/sensor.py b/homeassistant/components/apcupsd/sensor.py index 7947ba75999..e39696cc37a 100644 --- a/homeassistant/components/apcupsd/sensor.py +++ b/homeassistant/components/apcupsd/sensor.py @@ -12,6 +12,7 @@ from homeassistant.const import ( TEMP_CELSIUS, TIME_MINUTES, TIME_SECONDS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -28,7 +29,7 @@ SENSOR_TYPES = { "battdate": ["Battery Replaced", "", "mdi:calendar-clock"], "battstat": ["Battery Status", "", "mdi:information-outline"], "battv": ["Battery Voltage", "V", "mdi:flash"], - "bcharge": ["Battery", "%", "mdi:battery"], + "bcharge": ["Battery", UNIT_PERCENTAGE, "mdi:battery"], "cable": ["Cable Type", "", "mdi:ethernet-cable"], "cumonbatt": ["Total Time on Battery", "", "mdi:timer"], "date": ["Status Date", "", "mdi:calendar-clock"], @@ -42,20 +43,20 @@ SENSOR_TYPES = { "firmware": ["Firmware Version", "", "mdi:information-outline"], "hitrans": ["Transfer High", "V", "mdi:flash"], "hostname": ["Hostname", "", "mdi:information-outline"], - "humidity": ["Ambient Humidity", "%", "mdi:water-percent"], + "humidity": ["Ambient Humidity", UNIT_PERCENTAGE, "mdi:water-percent"], "itemp": ["Internal Temperature", TEMP_CELSIUS, "mdi:thermometer"], "lastxfer": ["Last Transfer", "", "mdi:transfer"], "linefail": ["Input Voltage Status", "", "mdi:information-outline"], "linefreq": ["Line Frequency", "Hz", "mdi:information-outline"], "linev": ["Input Voltage", "V", "mdi:flash"], - "loadpct": ["Load", "%", "mdi:gauge"], - "loadapnt": ["Load Apparent Power", "%", "mdi:gauge"], + "loadpct": ["Load", UNIT_PERCENTAGE, "mdi:gauge"], + "loadapnt": ["Load Apparent Power", UNIT_PERCENTAGE, "mdi:gauge"], "lotrans": ["Transfer Low", "V", "mdi:flash"], "mandate": ["Manufacture Date", "", "mdi:calendar"], "masterupd": ["Master Update", "", "mdi:information-outline"], "maxlinev": ["Input Voltage High", "V", "mdi:flash"], "maxtime": ["Battery Timeout", "", "mdi:timer-off"], - "mbattchg": ["Battery Shutdown", "%", "mdi:battery-alert"], + "mbattchg": ["Battery Shutdown", UNIT_PERCENTAGE, "mdi:battery-alert"], "minlinev": ["Input Voltage Low", "V", "mdi:flash"], "mintimel": ["Shutdown Time", "", "mdi:timer"], "model": ["Model", "", "mdi:information-outline"], @@ -70,7 +71,7 @@ SENSOR_TYPES = { "reg1": ["Register 1 Fault", "", "mdi:information-outline"], "reg2": ["Register 2 Fault", "", "mdi:information-outline"], "reg3": ["Register 3 Fault", "", "mdi:information-outline"], - "retpct": ["Restore Requirement", "%", "mdi:battery-alert"], + "retpct": ["Restore Requirement", UNIT_PERCENTAGE, "mdi:battery-alert"], "selftest": ["Last Self Test", "", "mdi:calendar-clock"], "sense": ["Sensitivity", "", "mdi:information-outline"], "serialno": ["Serial Number", "", "mdi:information-outline"], @@ -92,14 +93,14 @@ SPECIFIC_UNITS = {"ITEMP": TEMP_CELSIUS} INFERRED_UNITS = { " Minutes": TIME_MINUTES, " Seconds": TIME_SECONDS, - " Percent": "%", + " Percent": UNIT_PERCENTAGE, " Volts": "V", " Ampere": "A", " Volt-Ampere": "VA", " Watts": POWER_WATT, " Hz": "Hz", " C": TEMP_CELSIUS, - " Percent Load Capacity": "%", + " Percent Load Capacity": UNIT_PERCENTAGE, } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( diff --git a/homeassistant/components/aqualogic/sensor.py b/homeassistant/components/aqualogic/sensor.py index 7fff009baa5..dde092dd1fa 100644 --- a/homeassistant/components/aqualogic/sensor.py +++ b/homeassistant/components/aqualogic/sensor.py @@ -4,7 +4,12 @@ import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_MONITORED_CONDITIONS, TEMP_CELSIUS, TEMP_FAHRENHEIT +from homeassistant.const import ( + CONF_MONITORED_CONDITIONS, + TEMP_CELSIUS, + TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, +) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -14,7 +19,7 @@ from . import DOMAIN, UPDATE_TOPIC _LOGGER = logging.getLogger(__name__) TEMP_UNITS = [TEMP_CELSIUS, TEMP_FAHRENHEIT] -PERCENT_UNITS = ["%", "%"] +PERCENT_UNITS = [UNIT_PERCENTAGE, UNIT_PERCENTAGE] SALT_UNITS = ["g/L", "PPM"] WATT_UNITS = ["W", "W"] NO_UNITS = [None, None] diff --git a/homeassistant/components/arlo/sensor.py b/homeassistant/components/arlo/sensor.py index 5d11e9bc891..03e4437b257 100644 --- a/homeassistant/components/arlo/sensor.py +++ b/homeassistant/components/arlo/sensor.py @@ -11,6 +11,7 @@ from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv @@ -27,10 +28,10 @@ SENSOR_TYPES = { "last_capture": ["Last", None, "run-fast"], "total_cameras": ["Arlo Cameras", None, "video"], "captured_today": ["Captured Today", None, "file-video"], - "battery_level": ["Battery Level", "%", "battery-50"], + "battery_level": ["Battery Level", UNIT_PERCENTAGE, "battery-50"], "signal_strength": ["Signal Strength", None, "signal"], "temperature": ["Temperature", TEMP_CELSIUS, "thermometer"], - "humidity": ["Humidity", "%", "water-percent"], + "humidity": ["Humidity", UNIT_PERCENTAGE, "water-percent"], "air_quality": ["Air Quality", CONCENTRATION_PARTS_PER_MILLION, "biohazard"], } diff --git a/homeassistant/components/awair/sensor.py b/homeassistant/components/awair/sensor.py index 18fb3f2cd54..301055c7e61 100644 --- a/homeassistant/components/awair/sensor.py +++ b/homeassistant/components/awair/sensor.py @@ -16,6 +16,7 @@ from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -48,7 +49,7 @@ SENSOR_TYPES = { }, "HUMID": { "device_class": DEVICE_CLASS_HUMIDITY, - "unit_of_measurement": "%", + "unit_of_measurement": UNIT_PERCENTAGE, "icon": "mdi:water-percent", }, "CO2": { @@ -80,7 +81,7 @@ SENSOR_TYPES = { }, "score": { "device_class": DEVICE_CLASS_SCORE, - "unit_of_measurement": "%", + "unit_of_measurement": UNIT_PERCENTAGE, "icon": "mdi:percent", }, } diff --git a/homeassistant/components/beewi_smartclim/sensor.py b/homeassistant/components/beewi_smartclim/sensor.py index 187ca411988..ec124b24971 100644 --- a/homeassistant/components/beewi_smartclim/sensor.py +++ b/homeassistant/components/beewi_smartclim/sensor.py @@ -12,6 +12,7 @@ from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -24,8 +25,8 @@ DEFAULT_NAME = "BeeWi SmartClim" # Sensor config SENSOR_TYPES = [ [DEVICE_CLASS_TEMPERATURE, "Temperature", TEMP_CELSIUS], - [DEVICE_CLASS_HUMIDITY, "Humidity", "%"], - [DEVICE_CLASS_BATTERY, "Battery", "%"], + [DEVICE_CLASS_HUMIDITY, "Humidity", UNIT_PERCENTAGE], + [DEVICE_CLASS_BATTERY, "Battery", UNIT_PERCENTAGE], ] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( diff --git a/homeassistant/components/bloomsky/sensor.py b/homeassistant/components/bloomsky/sensor.py index 2ffdb8efab0..b07bca948bd 100644 --- a/homeassistant/components/bloomsky/sensor.py +++ b/homeassistant/components/bloomsky/sensor.py @@ -4,7 +4,12 @@ import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_MONITORED_CONDITIONS, TEMP_CELSIUS, TEMP_FAHRENHEIT +from homeassistant.const import ( + CONF_MONITORED_CONDITIONS, + TEMP_CELSIUS, + TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, +) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -25,7 +30,7 @@ SENSOR_TYPES = [ # Sensor units - these do not currently align with the API documentation SENSOR_UNITS_IMPERIAL = { "Temperature": TEMP_FAHRENHEIT, - "Humidity": "%", + "Humidity": UNIT_PERCENTAGE, "Pressure": "inHg", "Luminance": "cd/m²", "Voltage": "mV", @@ -34,7 +39,7 @@ SENSOR_UNITS_IMPERIAL = { # Metric units SENSOR_UNITS_METRIC = { "Temperature": TEMP_CELSIUS, - "Humidity": "%", + "Humidity": UNIT_PERCENTAGE, "Pressure": "mbar", "Luminance": "cd/m²", "Voltage": "mV", diff --git a/homeassistant/components/bme280/sensor.py b/homeassistant/components/bme280/sensor.py index e1e33210c9b..28e22c10f20 100644 --- a/homeassistant/components/bme280/sensor.py +++ b/homeassistant/components/bme280/sensor.py @@ -8,7 +8,12 @@ import smbus # pylint: disable=import-error import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_NAME, TEMP_FAHRENHEIT +from homeassistant.const import ( + CONF_MONITORED_CONDITIONS, + CONF_NAME, + TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, +) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle @@ -44,7 +49,7 @@ SENSOR_HUMID = "humidity" SENSOR_PRESS = "pressure" SENSOR_TYPES = { SENSOR_TEMP: ["Temperature", None], - SENSOR_HUMID: ["Humidity", "%"], + SENSOR_HUMID: ["Humidity", UNIT_PERCENTAGE], SENSOR_PRESS: ["Pressure", "mb"], } DEFAULT_MONITORED = [SENSOR_TEMP, SENSOR_HUMID, SENSOR_PRESS] diff --git a/homeassistant/components/bme680/sensor.py b/homeassistant/components/bme680/sensor.py index 43430f724bb..19d6fbd3086 100644 --- a/homeassistant/components/bme680/sensor.py +++ b/homeassistant/components/bme680/sensor.py @@ -8,7 +8,12 @@ from smbus import SMBus # pylint: disable=import-error import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_NAME, TEMP_FAHRENHEIT +from homeassistant.const import ( + CONF_MONITORED_CONDITIONS, + CONF_NAME, + TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, +) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util.temperature import celsius_to_fahrenheit @@ -50,10 +55,10 @@ SENSOR_GAS = "gas" SENSOR_AQ = "airquality" SENSOR_TYPES = { SENSOR_TEMP: ["Temperature", None], - SENSOR_HUMID: ["Humidity", "%"], + SENSOR_HUMID: ["Humidity", UNIT_PERCENTAGE], SENSOR_PRESS: ["Pressure", "mb"], SENSOR_GAS: ["Gas Resistance", "Ohms"], - SENSOR_AQ: ["Air Quality", "%"], + SENSOR_AQ: ["Air Quality", UNIT_PERCENTAGE], } DEFAULT_MONITORED = [SENSOR_TEMP, SENSOR_HUMID, SENSOR_PRESS, SENSOR_AQ] OVERSAMPLING_VALUES = set([0, 1, 2, 4, 8, 16]) diff --git a/homeassistant/components/bmw_connected_drive/sensor.py b/homeassistant/components/bmw_connected_drive/sensor.py index 7fb3da8b883..30c12d7d7a0 100644 --- a/homeassistant/components/bmw_connected_drive/sensor.py +++ b/homeassistant/components/bmw_connected_drive/sensor.py @@ -8,6 +8,7 @@ from homeassistant.const import ( LENGTH_KILOMETERS, LENGTH_MILES, TIME_HOURS, + UNIT_PERCENTAGE, VOLUME_GALLONS, VOLUME_LITERS, ) @@ -28,7 +29,7 @@ ATTR_TO_HA_METRIC = { "charging_time_remaining": ["mdi:update", TIME_HOURS], "charging_status": ["mdi:battery-charging", None], # No icon as this is dealt with directly as a special case in icon() - "charging_level_hv": [None, "%"], + "charging_level_hv": [None, UNIT_PERCENTAGE], } ATTR_TO_HA_IMPERIAL = { @@ -41,7 +42,7 @@ ATTR_TO_HA_IMPERIAL = { "charging_time_remaining": ["mdi:update", TIME_HOURS], "charging_status": ["mdi:battery-charging", None], # No icon as this is dealt with directly as a special case in icon() - "charging_level_hv": [None, "%"], + "charging_level_hv": [None, UNIT_PERCENTAGE], } diff --git a/homeassistant/components/bom/sensor.py b/homeassistant/components/bom/sensor.py index 836a2a79509..5ecd9c1009f 100644 --- a/homeassistant/components/bom/sensor.py +++ b/homeassistant/components/bom/sensor.py @@ -21,6 +21,7 @@ from homeassistant.const import ( CONF_NAME, SPEED_KILOMETERS_PER_HOUR, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -68,7 +69,7 @@ SENSOR_TYPES = { "press_msl": ["Pressure msl", "msl"], "press_tend": ["Pressure Tend", None], "rain_trace": ["Rain Today", "mm"], - "rel_hum": ["Relative Humidity", "%"], + "rel_hum": ["Relative Humidity", UNIT_PERCENTAGE], "sea_state": ["Sea State", None], "swell_dir_worded": ["Swell Direction", None], "swell_height": ["Swell Height", "m"], diff --git a/homeassistant/components/broadlink/sensor.py b/homeassistant/components/broadlink/sensor.py index 408593e337d..dbff4108a3f 100644 --- a/homeassistant/components/broadlink/sensor.py +++ b/homeassistant/components/broadlink/sensor.py @@ -15,6 +15,7 @@ from homeassistant.const import ( CONF_SCAN_INTERVAL, CONF_TIMEOUT, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -29,7 +30,7 @@ SCAN_INTERVAL = timedelta(seconds=300) SENSOR_TYPES = { "temperature": ["Temperature", TEMP_CELSIUS], "air_quality": ["Air Quality", " "], - "humidity": ["Humidity", "%"], + "humidity": ["Humidity", UNIT_PERCENTAGE], "light": ["Light", " "], "noise": ["Noise", " "], } diff --git a/homeassistant/components/brother/const.py b/homeassistant/components/brother/const.py index d3b7c5e2a78..e887ad6de21 100644 --- a/homeassistant/components/brother/const.py +++ b/homeassistant/components/brother/const.py @@ -1,5 +1,5 @@ """Constants for Brother integration.""" -from homeassistant.const import TIME_DAYS +from homeassistant.const import TIME_DAYS, UNIT_PERCENTAGE ATTR_BELT_UNIT_REMAINING_LIFE = "belt_unit_remaining_life" ATTR_BLACK_INK_REMAINING = "black_ink_remaining" @@ -30,7 +30,6 @@ ATTR_YELLOW_TONER_REMAINING = "yellow_toner_remaining" DOMAIN = "brother" UNIT_PAGES = "p" -UNIT_PERCENT = "%" PRINTER_TYPES = ["laser", "ink"] @@ -58,72 +57,72 @@ SENSOR_TYPES = { ATTR_DRUM_REMAINING_LIFE: { ATTR_ICON: "mdi:chart-donut", ATTR_LABEL: ATTR_DRUM_REMAINING_LIFE.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_BELT_UNIT_REMAINING_LIFE: { ATTR_ICON: "mdi:current-ac", ATTR_LABEL: ATTR_BELT_UNIT_REMAINING_LIFE.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_FUSER_REMAINING_LIFE: { ATTR_ICON: "mdi:water-outline", ATTR_LABEL: ATTR_FUSER_REMAINING_LIFE.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_LASER_REMAINING_LIFE: { ATTR_ICON: "mdi:spotlight-beam", ATTR_LABEL: ATTR_LASER_REMAINING_LIFE.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_PF_KIT_1_REMAINING_LIFE: { ATTR_ICON: "mdi:printer-3d", ATTR_LABEL: ATTR_PF_KIT_1_REMAINING_LIFE.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_PF_KIT_MP_REMAINING_LIFE: { ATTR_ICON: "mdi:printer-3d", ATTR_LABEL: ATTR_PF_KIT_MP_REMAINING_LIFE.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_BLACK_TONER_REMAINING: { ATTR_ICON: "mdi:printer-3d-nozzle", ATTR_LABEL: ATTR_BLACK_TONER_REMAINING.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_CYAN_TONER_REMAINING: { ATTR_ICON: "mdi:printer-3d-nozzle", ATTR_LABEL: ATTR_CYAN_TONER_REMAINING.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_MAGENTA_TONER_REMAINING: { ATTR_ICON: "mdi:printer-3d-nozzle", ATTR_LABEL: ATTR_MAGENTA_TONER_REMAINING.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_YELLOW_TONER_REMAINING: { ATTR_ICON: "mdi:printer-3d-nozzle", ATTR_LABEL: ATTR_YELLOW_TONER_REMAINING.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_BLACK_INK_REMAINING: { ATTR_ICON: "mdi:printer-3d-nozzle", ATTR_LABEL: ATTR_BLACK_INK_REMAINING.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_CYAN_INK_REMAINING: { ATTR_ICON: "mdi:printer-3d-nozzle", ATTR_LABEL: ATTR_CYAN_INK_REMAINING.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_MAGENTA_INK_REMAINING: { ATTR_ICON: "mdi:printer-3d-nozzle", ATTR_LABEL: ATTR_MAGENTA_INK_REMAINING.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_YELLOW_INK_REMAINING: { ATTR_ICON: "mdi:printer-3d-nozzle", ATTR_LABEL: ATTR_YELLOW_INK_REMAINING.replace("_", " ").title(), - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, }, ATTR_UPTIME: { ATTR_ICON: "mdi:timer", diff --git a/homeassistant/components/buienradar/sensor.py b/homeassistant/components/buienradar/sensor.py index 32ecf50ed9d..5d709ab1e63 100644 --- a/homeassistant/components/buienradar/sensor.py +++ b/homeassistant/components/buienradar/sensor.py @@ -31,6 +31,7 @@ from homeassistant.const import ( SPEED_KILOMETERS_PER_HOUR, TEMP_CELSIUS, TIME_HOURS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -67,7 +68,7 @@ SENSOR_TYPES = { "symbol": ["Symbol", None, None], # new in json api (>1.0.0): "feeltemperature": ["Feel temperature", TEMP_CELSIUS, "mdi:thermometer"], - "humidity": ["Humidity", "%", "mdi:water-percent"], + "humidity": ["Humidity", UNIT_PERCENTAGE, "mdi:water-percent"], "temperature": ["Temperature", TEMP_CELSIUS, "mdi:thermometer"], "groundtemperature": ["Ground temperature", TEMP_CELSIUS, "mdi:thermometer"], "windspeed": ["Wind speed", SPEED_KILOMETERS_PER_HOUR, "mdi:weather-windy"], @@ -120,16 +121,16 @@ SENSOR_TYPES = { "maxrain_3d": ["Maximum rain 3d", "mm", "mdi:weather-pouring"], "maxrain_4d": ["Maximum rain 4d", "mm", "mdi:weather-pouring"], "maxrain_5d": ["Maximum rain 5d", "mm", "mdi:weather-pouring"], - "rainchance_1d": ["Rainchance 1d", "%", "mdi:weather-pouring"], - "rainchance_2d": ["Rainchance 2d", "%", "mdi:weather-pouring"], - "rainchance_3d": ["Rainchance 3d", "%", "mdi:weather-pouring"], - "rainchance_4d": ["Rainchance 4d", "%", "mdi:weather-pouring"], - "rainchance_5d": ["Rainchance 5d", "%", "mdi:weather-pouring"], - "sunchance_1d": ["Sunchance 1d", "%", "mdi:weather-partly-cloudy"], - "sunchance_2d": ["Sunchance 2d", "%", "mdi:weather-partly-cloudy"], - "sunchance_3d": ["Sunchance 3d", "%", "mdi:weather-partly-cloudy"], - "sunchance_4d": ["Sunchance 4d", "%", "mdi:weather-partly-cloudy"], - "sunchance_5d": ["Sunchance 5d", "%", "mdi:weather-partly-cloudy"], + "rainchance_1d": ["Rainchance 1d", UNIT_PERCENTAGE, "mdi:weather-pouring"], + "rainchance_2d": ["Rainchance 2d", UNIT_PERCENTAGE, "mdi:weather-pouring"], + "rainchance_3d": ["Rainchance 3d", UNIT_PERCENTAGE, "mdi:weather-pouring"], + "rainchance_4d": ["Rainchance 4d", UNIT_PERCENTAGE, "mdi:weather-pouring"], + "rainchance_5d": ["Rainchance 5d", UNIT_PERCENTAGE, "mdi:weather-pouring"], + "sunchance_1d": ["Sunchance 1d", UNIT_PERCENTAGE, "mdi:weather-partly-cloudy"], + "sunchance_2d": ["Sunchance 2d", UNIT_PERCENTAGE, "mdi:weather-partly-cloudy"], + "sunchance_3d": ["Sunchance 3d", UNIT_PERCENTAGE, "mdi:weather-partly-cloudy"], + "sunchance_4d": ["Sunchance 4d", UNIT_PERCENTAGE, "mdi:weather-partly-cloudy"], + "sunchance_5d": ["Sunchance 5d", UNIT_PERCENTAGE, "mdi:weather-partly-cloudy"], "windforce_1d": ["Wind force 1d", "Bft", "mdi:weather-windy"], "windforce_2d": ["Wind force 2d", "Bft", "mdi:weather-windy"], "windforce_3d": ["Wind force 3d", "Bft", "mdi:weather-windy"], diff --git a/homeassistant/components/canary/sensor.py b/homeassistant/components/canary/sensor.py index 67654c99f3e..09413f9cb61 100644 --- a/homeassistant/components/canary/sensor.py +++ b/homeassistant/components/canary/sensor.py @@ -1,7 +1,7 @@ """Support for Canary sensors.""" from canary.api import SensorType -from homeassistant.const import TEMP_CELSIUS +from homeassistant.const import TEMP_CELSIUS, UNIT_PERCENTAGE from homeassistant.helpers.entity import Entity from homeassistant.helpers.icon import icon_for_battery_level @@ -14,10 +14,10 @@ ATTR_AIR_QUALITY = "air_quality" # sensor type name, unit_of_measurement, icon SENSOR_TYPES = [ ["temperature", TEMP_CELSIUS, "mdi:thermometer", ["Canary"]], - ["humidity", "%", "mdi:water-percent", ["Canary"]], + ["humidity", UNIT_PERCENTAGE, "mdi:water-percent", ["Canary"]], ["air_quality", None, "mdi:weather-windy", ["Canary"]], ["wifi", "dBm", "mdi:wifi", ["Canary Flex"]], - ["battery", "%", "mdi:battery-50", ["Canary Flex"]], + ["battery", UNIT_PERCENTAGE, "mdi:battery-50", ["Canary Flex"]], ] STATE_AIR_QUALITY_NORMAL = "normal" diff --git a/homeassistant/components/climate/device_trigger.py b/homeassistant/components/climate/device_trigger.py index 4c5dcb0ee04..187f50bc984 100644 --- a/homeassistant/components/climate/device_trigger.py +++ b/homeassistant/components/climate/device_trigger.py @@ -18,6 +18,7 @@ from homeassistant.const import ( CONF_FOR, CONF_PLATFORM, CONF_TYPE, + UNIT_PERCENTAGE, ) from homeassistant.core import CALLBACK_TYPE, HomeAssistant from homeassistant.helpers import config_validation as cv, entity_registry @@ -177,7 +178,7 @@ async def async_get_trigger_capabilities(hass: HomeAssistant, config): if trigger_type == "current_temperature_changed": unit_of_measurement = hass.config.units.temperature_unit else: - unit_of_measurement = "%" + unit_of_measurement = UNIT_PERCENTAGE return { "extra_fields": vol.Schema( diff --git a/homeassistant/components/comfoconnect/sensor.py b/homeassistant/components/comfoconnect/sensor.py index 1d189508960..5c8c0d6a75c 100644 --- a/homeassistant/components/comfoconnect/sensor.py +++ b/homeassistant/components/comfoconnect/sensor.py @@ -33,6 +33,7 @@ from homeassistant.const import ( TEMP_CELSIUS, TIME_DAYS, TIME_HOURS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect @@ -78,7 +79,7 @@ SENSOR_TYPES = { ATTR_CURRENT_HUMIDITY: { ATTR_DEVICE_CLASS: DEVICE_CLASS_HUMIDITY, ATTR_LABEL: "Inside Humidity", - ATTR_UNIT: "%", + ATTR_UNIT: UNIT_PERCENTAGE, ATTR_ICON: "mdi:water-percent", ATTR_ID: SENSOR_HUMIDITY_EXTRACT, }, @@ -93,7 +94,7 @@ SENSOR_TYPES = { ATTR_OUTSIDE_HUMIDITY: { ATTR_DEVICE_CLASS: DEVICE_CLASS_HUMIDITY, ATTR_LABEL: "Outside Humidity", - ATTR_UNIT: "%", + ATTR_UNIT: UNIT_PERCENTAGE, ATTR_ICON: "mdi:water-percent", ATTR_ID: SENSOR_HUMIDITY_OUTDOOR, }, @@ -108,7 +109,7 @@ SENSOR_TYPES = { ATTR_SUPPLY_HUMIDITY: { ATTR_DEVICE_CLASS: DEVICE_CLASS_HUMIDITY, ATTR_LABEL: "Supply Humidity", - ATTR_UNIT: "%", + ATTR_UNIT: UNIT_PERCENTAGE, ATTR_ICON: "mdi:water-percent", ATTR_ID: SENSOR_HUMIDITY_SUPPLY, }, @@ -122,7 +123,7 @@ SENSOR_TYPES = { ATTR_SUPPLY_FAN_DUTY: { ATTR_DEVICE_CLASS: None, ATTR_LABEL: "Supply Fan Duty", - ATTR_UNIT: "%", + ATTR_UNIT: UNIT_PERCENTAGE, ATTR_ICON: "mdi:fan", ATTR_ID: SENSOR_FAN_SUPPLY_DUTY, }, @@ -136,7 +137,7 @@ SENSOR_TYPES = { ATTR_EXHAUST_FAN_DUTY: { ATTR_DEVICE_CLASS: None, ATTR_LABEL: "Exhaust Fan Duty", - ATTR_UNIT: "%", + ATTR_UNIT: UNIT_PERCENTAGE, ATTR_ICON: "mdi:fan", ATTR_ID: SENSOR_FAN_EXHAUST_DUTY, }, @@ -151,7 +152,7 @@ SENSOR_TYPES = { ATTR_EXHAUST_HUMIDITY: { ATTR_DEVICE_CLASS: DEVICE_CLASS_HUMIDITY, ATTR_LABEL: "Exhaust Humidity", - ATTR_UNIT: "%", + ATTR_UNIT: UNIT_PERCENTAGE, ATTR_ICON: "mdi:water-percent", ATTR_ID: SENSOR_HUMIDITY_EXHAUST, }, @@ -172,7 +173,7 @@ SENSOR_TYPES = { ATTR_BYPASS_STATE: { ATTR_DEVICE_CLASS: None, ATTR_LABEL: "Bypass State", - ATTR_UNIT: "%", + ATTR_UNIT: UNIT_PERCENTAGE, ATTR_ICON: "mdi:camera-iris", ATTR_ID: SENSOR_BYPASS_STATE, }, diff --git a/homeassistant/components/cups/sensor.py b/homeassistant/components/cups/sensor.py index 7581891af6a..ac158388242 100644 --- a/homeassistant/components/cups/sensor.py +++ b/homeassistant/components/cups/sensor.py @@ -6,7 +6,7 @@ import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_HOST, CONF_PORT +from homeassistant.const import CONF_HOST, CONF_PORT, UNIT_PERCENTAGE from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -268,7 +268,7 @@ class MarkerSensor(Entity): @property def unit_of_measurement(self): """Return the unit of measurement.""" - return "%" + return UNIT_PERCENTAGE @property def device_state_attributes(self): diff --git a/homeassistant/components/danfoss_air/sensor.py b/homeassistant/components/danfoss_air/sensor.py index 247eb955154..73305d5c625 100644 --- a/homeassistant/components/danfoss_air/sensor.py +++ b/homeassistant/components/danfoss_air/sensor.py @@ -6,6 +6,7 @@ from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.helpers.entity import Entity @@ -45,14 +46,24 @@ def setup_platform(hass, config, add_entities, discovery_info=None): ReadCommand.extractTemperature, DEVICE_CLASS_TEMPERATURE, ], - ["Danfoss Air Remaining Filter", "%", ReadCommand.filterPercent, None], - ["Danfoss Air Humidity", "%", ReadCommand.humidity, DEVICE_CLASS_HUMIDITY], - ["Danfoss Air Fan Step", "%", ReadCommand.fan_step, None], + [ + "Danfoss Air Remaining Filter", + UNIT_PERCENTAGE, + ReadCommand.filterPercent, + None, + ], + [ + "Danfoss Air Humidity", + UNIT_PERCENTAGE, + ReadCommand.humidity, + DEVICE_CLASS_HUMIDITY, + ], + ["Danfoss Air Fan Step", UNIT_PERCENTAGE, ReadCommand.fan_step, None], ["Danfoss Air Exhaust Fan Speed", "RPM", ReadCommand.exhaust_fan_speed, None], ["Danfoss Air Supply Fan Speed", "RPM", ReadCommand.supply_fan_speed, None], [ "Danfoss Air Dial Battery", - "%", + UNIT_PERCENTAGE, ReadCommand.battery_percent, DEVICE_CLASS_BATTERY, ], diff --git a/homeassistant/components/darksky/sensor.py b/homeassistant/components/darksky/sensor.py index 46741e3aca7..26ba590888f 100644 --- a/homeassistant/components/darksky/sensor.py +++ b/homeassistant/components/darksky/sensor.py @@ -19,6 +19,7 @@ from homeassistant.const import ( SPEED_METERS_PER_SECOND, SPEED_MILES_PER_HOUR, TIME_HOURS, + UNIT_PERCENTAGE, UNIT_UV_INDEX, ) import homeassistant.helpers.config_validation as cv @@ -113,11 +114,11 @@ SENSOR_TYPES = { ], "precip_probability": [ "Precip Probability", - "%", - "%", - "%", - "%", - "%", + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, "mdi:water-percent", ["currently", "minutely", "hourly", "daily"], ], @@ -193,21 +194,21 @@ SENSOR_TYPES = { ], "cloud_cover": [ "Cloud Coverage", - "%", - "%", - "%", - "%", - "%", + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, "mdi:weather-partly-cloudy", ["currently", "hourly", "daily"], ], "humidity": [ "Humidity", - "%", - "%", - "%", - "%", - "%", + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, + UNIT_PERCENTAGE, "mdi:water-percent", ["currently", "hourly", "daily"], ], diff --git a/homeassistant/components/deconz/sensor.py b/homeassistant/components/deconz/sensor.py index c32b26f299d..fd8ffeeaaf0 100644 --- a/homeassistant/components/deconz/sensor.py +++ b/homeassistant/components/deconz/sensor.py @@ -9,7 +9,12 @@ from pydeconz.sensor import ( Thermostat, ) -from homeassistant.const import ATTR_TEMPERATURE, ATTR_VOLTAGE, DEVICE_CLASS_BATTERY +from homeassistant.const import ( + ATTR_TEMPERATURE, + ATTR_VOLTAGE, + DEVICE_CLASS_BATTERY, + UNIT_PERCENTAGE, +) from homeassistant.core import callback from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, @@ -194,7 +199,7 @@ class DeconzBattery(DeconzDevice): @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" - return "%" + return UNIT_PERCENTAGE @property def device_state_attributes(self): diff --git a/homeassistant/components/demo/sensor.py b/homeassistant/components/demo/sensor.py index d2b2464468b..6805ebb5b56 100644 --- a/homeassistant/components/demo/sensor.py +++ b/homeassistant/components/demo/sensor.py @@ -4,6 +4,7 @@ from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.helpers.entity import Entity @@ -23,7 +24,12 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= 12, ), DemoSensor( - "sensor_2", "Outside Humidity", 54, DEVICE_CLASS_HUMIDITY, "%", None + "sensor_2", + "Outside Humidity", + 54, + DEVICE_CLASS_HUMIDITY, + UNIT_PERCENTAGE, + None, ), ] ) diff --git a/homeassistant/components/dht/sensor.py b/homeassistant/components/dht/sensor.py index 26b0493cb99..b9461fae7d7 100644 --- a/homeassistant/components/dht/sensor.py +++ b/homeassistant/components/dht/sensor.py @@ -6,7 +6,12 @@ import Adafruit_DHT # pylint: disable=import-error import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_NAME, TEMP_FAHRENHEIT +from homeassistant.const import ( + CONF_MONITORED_CONDITIONS, + CONF_NAME, + TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, +) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle @@ -28,7 +33,7 @@ SENSOR_TEMPERATURE = "temperature" SENSOR_HUMIDITY = "humidity" SENSOR_TYPES = { SENSOR_TEMPERATURE: ["Temperature", None], - SENSOR_HUMIDITY: ["Humidity", "%"], + SENSOR_HUMIDITY: ["Humidity", UNIT_PERCENTAGE], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( diff --git a/homeassistant/components/dovado/sensor.py b/homeassistant/components/dovado/sensor.py index 5e3745b27ed..8328df8bd7f 100644 --- a/homeassistant/components/dovado/sensor.py +++ b/homeassistant/components/dovado/sensor.py @@ -6,7 +6,7 @@ import re import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_SENSORS, DATA_GIGABYTES +from homeassistant.const import CONF_SENSORS, DATA_GIGABYTES, UNIT_PERCENTAGE import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -24,7 +24,12 @@ SENSOR_SMS_UNREAD = "sms" SENSORS = { SENSOR_NETWORK: ("signal strength", "Network", None, "mdi:access-point-network"), - SENSOR_SIGNAL: ("signal strength", "Signal Strength", "%", "mdi:signal"), + SENSOR_SIGNAL: ( + "signal strength", + "Signal Strength", + UNIT_PERCENTAGE, + "mdi:signal", + ), SENSOR_SMS_UNREAD: ("sms unread", "SMS unread", "", "mdi:message-text-outline"), SENSOR_UPLOAD: ("traffic modem tx", "Sent", DATA_GIGABYTES, "mdi:cloud-upload"), SENSOR_DOWNLOAD: ( diff --git a/homeassistant/components/dyson/sensor.py b/homeassistant/components/dyson/sensor.py index c7f61422a2e..55f2ff69314 100644 --- a/homeassistant/components/dyson/sensor.py +++ b/homeassistant/components/dyson/sensor.py @@ -4,7 +4,7 @@ import logging from libpurecool.dyson_pure_cool import DysonPureCool from libpurecool.dyson_pure_cool_link import DysonPureCoolLink -from homeassistant.const import STATE_OFF, TEMP_CELSIUS, TIME_HOURS +from homeassistant.const import STATE_OFF, TEMP_CELSIUS, TIME_HOURS, UNIT_PERCENTAGE from homeassistant.helpers.entity import Entity from . import DYSON_DEVICES @@ -13,7 +13,7 @@ SENSOR_UNITS = { "air_quality": None, "dust": None, "filter_life": TIME_HOURS, - "humidity": "%", + "humidity": UNIT_PERCENTAGE, } SENSOR_ICONS = { diff --git a/homeassistant/components/ebox/sensor.py b/homeassistant/components/ebox/sensor.py index 208ffb99543..dc150109cf7 100644 --- a/homeassistant/components/ebox/sensor.py +++ b/homeassistant/components/ebox/sensor.py @@ -18,6 +18,7 @@ from homeassistant.const import ( CONF_USERNAME, DATA_GIGABITS, TIME_DAYS, + UNIT_PERCENTAGE, ) from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv @@ -27,7 +28,6 @@ from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) PRICE = "CAD" -PERCENT = "%" DEFAULT_NAME = "EBox" @@ -36,7 +36,7 @@ SCAN_INTERVAL = timedelta(minutes=15) MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15) SENSOR_TYPES = { - "usage": ["Usage", PERCENT, "mdi:percent"], + "usage": ["Usage", UNIT_PERCENTAGE, "mdi:percent"], "balance": ["Balance", PRICE, "mdi:square-inc-cash"], "limit": ["Data limit", DATA_GIGABITS, "mdi:download"], "days_left": ["Days left", TIME_DAYS, "mdi:calendar-today"], diff --git a/homeassistant/components/ecobee/sensor.py b/homeassistant/components/ecobee/sensor.py index ca3e7732e1b..e510cc976a6 100644 --- a/homeassistant/components/ecobee/sensor.py +++ b/homeassistant/components/ecobee/sensor.py @@ -5,6 +5,7 @@ from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) from homeassistant.helpers.entity import Entity @@ -12,7 +13,7 @@ from .const import _LOGGER, DOMAIN, ECOBEE_MODEL_TO_NAME, MANUFACTURER SENSOR_TYPES = { "temperature": ["Temperature", TEMP_FAHRENHEIT], - "humidity": ["Humidity", "%"], + "humidity": ["Humidity", UNIT_PERCENTAGE], } diff --git a/homeassistant/components/eight_sleep/sensor.py b/homeassistant/components/eight_sleep/sensor.py index af6de2657ce..457323d3bd5 100644 --- a/homeassistant/components/eight_sleep/sensor.py +++ b/homeassistant/components/eight_sleep/sensor.py @@ -1,6 +1,8 @@ """Support for Eight Sleep sensors.""" import logging +from homeassistant.const import UNIT_PERCENTAGE + from . import ( CONF_SENSORS, DATA_EIGHT, @@ -18,9 +20,9 @@ ATTR_AVG_RESP_RATE = "Average Respiratory Rate" ATTR_HEART_RATE = "Heart Rate" ATTR_AVG_HEART_RATE = "Average Heart Rate" ATTR_SLEEP_DUR = "Time Slept" -ATTR_LIGHT_PERC = "Light Sleep %" -ATTR_DEEP_PERC = "Deep Sleep %" -ATTR_REM_PERC = "REM Sleep %" +ATTR_LIGHT_PERC = f"Light Sleep {UNIT_PERCENTAGE}" +ATTR_DEEP_PERC = f"Deep Sleep {UNIT_PERCENTAGE}" +ATTR_REM_PERC = f"REM Sleep {UNIT_PERCENTAGE}" ATTR_TNT = "Tosses & Turns" ATTR_SLEEP_STAGE = "Sleep Stage" ATTR_TARGET_HEAT = "Target Heating Level" @@ -100,7 +102,7 @@ class EightHeatSensor(EightSleepHeatEntity): @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" - return "%" + return UNIT_PERCENTAGE async def async_update(self): """Retrieve latest state.""" diff --git a/homeassistant/components/enocean/sensor.py b/homeassistant/components/enocean/sensor.py index 5cf908a33a1..45a20197a4a 100644 --- a/homeassistant/components/enocean/sensor.py +++ b/homeassistant/components/enocean/sensor.py @@ -16,6 +16,7 @@ from homeassistant.const import ( STATE_CLOSED, STATE_OPEN, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv @@ -36,7 +37,7 @@ SENSOR_TYPE_WINDOWHANDLE = "windowhandle" SENSOR_TYPES = { SENSOR_TYPE_HUMIDITY: { "name": "Humidity", - "unit": "%", + "unit": UNIT_PERCENTAGE, "icon": "mdi:water-percent", "class": DEVICE_CLASS_HUMIDITY, }, diff --git a/homeassistant/components/epsonworkforce/sensor.py b/homeassistant/components/epsonworkforce/sensor.py index 3bb90eb0644..b2164325547 100644 --- a/homeassistant/components/epsonworkforce/sensor.py +++ b/homeassistant/components/epsonworkforce/sensor.py @@ -6,19 +6,19 @@ from epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS +from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS, UNIT_PERCENTAGE from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) MONITORED_CONDITIONS = { - "black": ["Ink level Black", "%", "mdi:water"], - "photoblack": ["Ink level Photoblack", "%", "mdi:water"], - "magenta": ["Ink level Magenta", "%", "mdi:water"], - "cyan": ["Ink level Cyan", "%", "mdi:water"], - "yellow": ["Ink level Yellow", "%", "mdi:water"], - "clean": ["Cleaning level", "%", "mdi:water"], + "black": ["Ink level Black", UNIT_PERCENTAGE, "mdi:water"], + "photoblack": ["Ink level Photoblack", UNIT_PERCENTAGE, "mdi:water"], + "magenta": ["Ink level Magenta", UNIT_PERCENTAGE, "mdi:water"], + "cyan": ["Ink level Cyan", UNIT_PERCENTAGE, "mdi:water"], + "yellow": ["Ink level Yellow", UNIT_PERCENTAGE, "mdi:water"], + "clean": ["Cleaning level", UNIT_PERCENTAGE, "mdi:water"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { diff --git a/homeassistant/components/fibaro/sensor.py b/homeassistant/components/fibaro/sensor.py index 5fce0da7a2b..68a39431a98 100644 --- a/homeassistant/components/fibaro/sensor.py +++ b/homeassistant/components/fibaro/sensor.py @@ -9,6 +9,7 @@ from homeassistant.const import ( DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) from homeassistant.helpers.entity import Entity @@ -28,7 +29,12 @@ SENSOR_TYPES = { None, ], "CO2": ["CO2", CONCENTRATION_PARTS_PER_MILLION, "mdi:cloud", None], - "com.fibaro.humiditySensor": ["Humidity", "%", None, DEVICE_CLASS_HUMIDITY], + "com.fibaro.humiditySensor": [ + "Humidity", + UNIT_PERCENTAGE, + None, + DEVICE_CLASS_HUMIDITY, + ], "com.fibaro.lightSensor": ["Light", "lx", None, DEVICE_CLASS_ILLUMINANCE], } diff --git a/homeassistant/components/fitbit/sensor.py b/homeassistant/components/fitbit/sensor.py index b6a4fe550c9..66c283f20ef 100644 --- a/homeassistant/components/fitbit/sensor.py +++ b/homeassistant/components/fitbit/sensor.py @@ -18,6 +18,7 @@ from homeassistant.const import ( MASS_MILLIGRAMS, TIME_MILLISECONDS, TIME_MINUTES, + UNIT_PERCENTAGE, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv @@ -91,11 +92,11 @@ FITBIT_RESOURCES_LIST = { ], "activities/tracker/steps": ["Tracker Steps", "steps", "walk"], "body/bmi": ["BMI", "BMI", "human"], - "body/fat": ["Body Fat", "%", "human"], + "body/fat": ["Body Fat", UNIT_PERCENTAGE, "human"], "body/weight": ["Weight", "", "human"], "devices/battery": ["Battery", None, None], "sleep/awakeningsCount": ["Awakenings Count", "times awaken", "sleep"], - "sleep/efficiency": ["Sleep Efficiency", "%", "sleep"], + "sleep/efficiency": ["Sleep Efficiency", UNIT_PERCENTAGE, "sleep"], "sleep/minutesAfterWakeup": ["Minutes After Wakeup", TIME_MINUTES, "sleep"], "sleep/minutesAsleep": ["Sleep Minutes Asleep", TIME_MINUTES, "sleep"], "sleep/minutesAwake": ["Sleep Minutes Awake", TIME_MINUTES, "sleep"], diff --git a/homeassistant/components/foobot/sensor.py b/homeassistant/components/foobot/sensor.py index 80d17b4f23b..e0322ccbab7 100644 --- a/homeassistant/components/foobot/sensor.py +++ b/homeassistant/components/foobot/sensor.py @@ -17,6 +17,7 @@ from homeassistant.const import ( CONF_USERNAME, TEMP_CELSIUS, TIME_SECONDS, + UNIT_PERCENTAGE, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -37,7 +38,7 @@ SENSOR_TYPES = { "time": [ATTR_TIME, TIME_SECONDS], "pm": [ATTR_PM2_5, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], - "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], + "hum": [ATTR_HUMIDITY, UNIT_PERCENTAGE, "mdi:water-percent"], "co2": [ ATTR_CARBON_DIOXIDE, CONCENTRATION_PARTS_PER_MILLION, @@ -48,7 +49,7 @@ SENSOR_TYPES = { CONCENTRATION_PARTS_PER_BILLION, "mdi:cloud", ], - "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], + "allpollu": [ATTR_FOOBOT_INDEX, UNIT_PERCENTAGE, "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) diff --git a/homeassistant/components/garmin_connect/const.py b/homeassistant/components/garmin_connect/const.py index c01f11464a1..38245ff5eb8 100644 --- a/homeassistant/components/garmin_connect/const.py +++ b/homeassistant/components/garmin_connect/const.py @@ -1,5 +1,5 @@ """Constants for the Garmin Connect integration.""" -from homeassistant.const import DEVICE_CLASS_TIMESTAMP, TIME_MINUTES +from homeassistant.const import DEVICE_CLASS_TIMESTAMP, TIME_MINUTES, UNIT_PERCENTAGE DOMAIN = "garmin_connect" ATTRIBUTION = "Data provided by garmin.com" @@ -159,45 +159,51 @@ GARMIN_ENTITY_LIST = { None, True, ], - "stressPercentage": ["Stress Percentage", "%", "mdi:flash-alert", None, False], + "stressPercentage": [ + "Stress Percentage", + UNIT_PERCENTAGE, + "mdi:flash-alert", + None, + False, + ], "restStressPercentage": [ "Rest Stress Percentage", - "%", + UNIT_PERCENTAGE, "mdi:flash-alert", None, False, ], "activityStressPercentage": [ "Activity Stress Percentage", - "%", + UNIT_PERCENTAGE, "mdi:flash-alert", None, False, ], "uncategorizedStressPercentage": [ "Uncat. Stress Percentage", - "%", + UNIT_PERCENTAGE, "mdi:flash-alert", None, False, ], "lowStressPercentage": [ "Low Stress Percentage", - "%", + UNIT_PERCENTAGE, "mdi:flash-alert", None, False, ], "mediumStressPercentage": [ "Medium Stress Percentage", - "%", + UNIT_PERCENTAGE, "mdi:flash-alert", None, False, ], "highStressPercentage": [ "High Stress Percentage", - "%", + UNIT_PERCENTAGE, "mdi:flash-alert", None, False, @@ -225,42 +231,42 @@ GARMIN_ENTITY_LIST = { ], "bodyBatteryChargedValue": [ "Body Battery Charged", - "%", + UNIT_PERCENTAGE, "mdi:battery-charging-100", None, True, ], "bodyBatteryDrainedValue": [ "Body Battery Drained", - "%", + UNIT_PERCENTAGE, "mdi:battery-alert-variant-outline", None, True, ], "bodyBatteryHighestValue": [ "Body Battery Highest", - "%", + UNIT_PERCENTAGE, "mdi:battery-heart", None, True, ], "bodyBatteryLowestValue": [ "Body Battery Lowest", - "%", + UNIT_PERCENTAGE, "mdi:battery-heart-outline", None, True, ], "bodyBatteryMostRecentValue": [ "Body Battery Most Recent", - "%", + UNIT_PERCENTAGE, "mdi:battery-positive", None, True, ], - "averageSpo2": ["Average SPO2", "%", "mdi:diabetes", None, True], - "lowestSpo2": ["Lowest SPO2", "%", "mdi:diabetes", None, True], - "latestSpo2": ["Latest SPO2", "%", "mdi:diabetes", None, True], + "averageSpo2": ["Average SPO2", UNIT_PERCENTAGE, "mdi:diabetes", None, True], + "lowestSpo2": ["Lowest SPO2", UNIT_PERCENTAGE, "mdi:diabetes", None, True], + "latestSpo2": ["Latest SPO2", UNIT_PERCENTAGE, "mdi:diabetes", None, True], "latestSpo2ReadingTimeLocal": [ "Latest SPO2 Time", "", @@ -270,7 +276,7 @@ GARMIN_ENTITY_LIST = { ], "averageMonitoringEnvironmentAltitude": [ "Average Altitude", - "%", + UNIT_PERCENTAGE, "mdi:image-filter-hdr", None, False, diff --git a/homeassistant/components/geniushub/sensor.py b/homeassistant/components/geniushub/sensor.py index bd73c700e65..196cba7212e 100644 --- a/homeassistant/components/geniushub/sensor.py +++ b/homeassistant/components/geniushub/sensor.py @@ -2,7 +2,7 @@ from datetime import timedelta from typing import Any, Dict -from homeassistant.const import DEVICE_CLASS_BATTERY +from homeassistant.const import DEVICE_CLASS_BATTERY, UNIT_PERCENTAGE from homeassistant.helpers.typing import ConfigType, HomeAssistantType import homeassistant.util.dt as dt_util @@ -77,7 +77,7 @@ class GeniusBattery(GeniusDevice): @property def unit_of_measurement(self) -> str: """Return the unit of measurement of the sensor.""" - return "%" + return UNIT_PERCENTAGE @property def state(self) -> str: diff --git a/homeassistant/components/glances/const.py b/homeassistant/components/glances/const.py index 31a3f0f69e4..53dc6352049 100644 --- a/homeassistant/components/glances/const.py +++ b/homeassistant/components/glances/const.py @@ -1,5 +1,10 @@ """Constants for Glances component.""" -from homeassistant.const import DATA_GIBIBYTES, DATA_MEBIBYTES, TEMP_CELSIUS +from homeassistant.const import ( + DATA_GIBIBYTES, + DATA_MEBIBYTES, + TEMP_CELSIUS, + UNIT_PERCENTAGE, +) DOMAIN = "glances" CONF_VERSION = "version" @@ -14,13 +19,13 @@ DATA_UPDATED = "glances_data_updated" SUPPORTED_VERSIONS = [2, 3] SENSOR_TYPES = { - "disk_use_percent": ["fs", "used percent", "%", "mdi:harddisk"], + "disk_use_percent": ["fs", "used percent", UNIT_PERCENTAGE, "mdi:harddisk"], "disk_use": ["fs", "used", DATA_GIBIBYTES, "mdi:harddisk"], "disk_free": ["fs", "free", DATA_GIBIBYTES, "mdi:harddisk"], - "memory_use_percent": ["mem", "RAM used percent", "%", "mdi:memory"], + "memory_use_percent": ["mem", "RAM used percent", UNIT_PERCENTAGE, "mdi:memory"], "memory_use": ["mem", "RAM used", DATA_MEBIBYTES, "mdi:memory"], "memory_free": ["mem", "RAM free", DATA_MEBIBYTES, "mdi:memory"], - "swap_use_percent": ["memswap", "Swap used percent", "%", "mdi:memory"], + "swap_use_percent": ["memswap", "Swap used percent", UNIT_PERCENTAGE, "mdi:memory"], "swap_use": ["memswap", "Swap used", DATA_GIBIBYTES, "mdi:memory"], "swap_free": ["memswap", "Swap free", DATA_GIBIBYTES, "mdi:memory"], "processor_load": ["load", "CPU load", "15 min", "mdi:memory"], @@ -28,10 +33,10 @@ SENSOR_TYPES = { "process_total": ["processcount", "Total", "Count", "mdi:memory"], "process_thread": ["processcount", "Thread", "Count", "mdi:memory"], "process_sleeping": ["processcount", "Sleeping", "Count", "mdi:memory"], - "cpu_use_percent": ["cpu", "CPU used", "%", "mdi:memory"], + "cpu_use_percent": ["cpu", "CPU used", UNIT_PERCENTAGE, "mdi:memory"], "sensor_temp": ["sensors", "Temp", TEMP_CELSIUS, "mdi:thermometer"], "docker_active": ["docker", "Containers active", "", "mdi:docker"], - "docker_cpu_use": ["docker", "Containers CPU used", "%", "mdi:docker"], + "docker_cpu_use": ["docker", "Containers CPU used", UNIT_PERCENTAGE, "mdi:docker"], "docker_memory_use": [ "docker", "Containers RAM used", diff --git a/homeassistant/components/history_stats/sensor.py b/homeassistant/components/history_stats/sensor.py index 0b1289ab05f..48d65145219 100644 --- a/homeassistant/components/history_stats/sensor.py +++ b/homeassistant/components/history_stats/sensor.py @@ -14,6 +14,7 @@ from homeassistant.const import ( CONF_TYPE, EVENT_HOMEASSISTANT_START, TIME_HOURS, + UNIT_PERCENTAGE, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError @@ -36,7 +37,11 @@ CONF_TYPE_COUNT = "count" CONF_TYPE_KEYS = [CONF_TYPE_TIME, CONF_TYPE_RATIO, CONF_TYPE_COUNT] DEFAULT_NAME = "unnamed statistics" -UNITS = {CONF_TYPE_TIME: TIME_HOURS, CONF_TYPE_RATIO: "%", CONF_TYPE_COUNT: ""} +UNITS = { + CONF_TYPE_TIME: TIME_HOURS, + CONF_TYPE_RATIO: UNIT_PERCENTAGE, + CONF_TYPE_COUNT: "", +} ICON = "mdi:chart-line" ATTR_VALUE = "value" diff --git a/homeassistant/components/homekit/__init__.py b/homeassistant/components/homekit/__init__.py index ca5a601068a..c46bd754319 100644 --- a/homeassistant/components/homekit/__init__.py +++ b/homeassistant/components/homekit/__init__.py @@ -23,6 +23,7 @@ from homeassistant.const import ( EVENT_HOMEASSISTANT_STOP, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entityfilter import FILTER_SCHEMA @@ -236,7 +237,7 @@ def get_accessory(hass, driver, state, aid, config): TEMP_FAHRENHEIT, ): a_type = "TemperatureSensor" - elif device_class == DEVICE_CLASS_HUMIDITY and unit == "%": + elif device_class == DEVICE_CLASS_HUMIDITY and unit == UNIT_PERCENTAGE: a_type = "HumiditySensor" elif device_class == DEVICE_CLASS_PM25 or DEVICE_CLASS_PM25 in state.entity_id: a_type = "AirQualitySensor" diff --git a/homeassistant/components/homekit_controller/sensor.py b/homeassistant/components/homekit_controller/sensor.py index ab8a6fa6672..636c10dbe79 100644 --- a/homeassistant/components/homekit_controller/sensor.py +++ b/homeassistant/components/homekit_controller/sensor.py @@ -8,6 +8,7 @@ from homeassistant.const import ( DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.core import callback @@ -18,7 +19,6 @@ TEMP_C_ICON = "mdi:thermometer" BRIGHTNESS_ICON = "mdi:brightness-6" CO2_ICON = "mdi:periodic-table-co2" -UNIT_PERCENT = "%" UNIT_LUX = "lux" @@ -52,7 +52,7 @@ class HomeKitHumiditySensor(HomeKitEntity): @property def unit_of_measurement(self): """Return units for the sensor.""" - return UNIT_PERCENT + return UNIT_PERCENTAGE def _update_relative_humidity_current(self, value): self._state = value @@ -234,7 +234,7 @@ class HomeKitBatterySensor(HomeKitEntity): @property def unit_of_measurement(self): """Return units for the sensor.""" - return UNIT_PERCENT + return UNIT_PERCENTAGE def _update_battery_level(self, value): self._state = value diff --git a/homeassistant/components/homematic/sensor.py b/homeassistant/components/homematic/sensor.py index 09d1e2f59cf..e8b97477546 100644 --- a/homeassistant/components/homematic/sensor.py +++ b/homeassistant/components/homematic/sensor.py @@ -9,6 +9,7 @@ from homeassistant.const import ( ENERGY_WATT_HOUR, POWER_WATT, SPEED_KILOMETERS_PER_HOUR, + UNIT_PERCENTAGE, VOLUME_CUBIC_METERS, ) @@ -32,7 +33,7 @@ HM_STATE_HA_CAST = { } HM_UNIT_HA_CAST = { - "HUMIDITY": "%", + "HUMIDITY": UNIT_PERCENTAGE, "TEMPERATURE": "°C", "ACTUAL_TEMPERATURE": "°C", "BRIGHTNESS": "#", diff --git a/homeassistant/components/homematicip_cloud/sensor.py b/homeassistant/components/homematicip_cloud/sensor.py index 4335eebb8b8..a45591ecc30 100644 --- a/homeassistant/components/homematicip_cloud/sensor.py +++ b/homeassistant/components/homematicip_cloud/sensor.py @@ -33,6 +33,7 @@ from homeassistant.const import ( POWER_WATT, SPEED_KILOMETERS_PER_HOUR, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.helpers.typing import HomeAssistantType @@ -155,7 +156,7 @@ class HomematicipAccesspointStatus(HomematicipGenericDevice): @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" - return "%" + return UNIT_PERCENTAGE @property def device_state_attributes(self) -> Dict[str, Any]: @@ -194,7 +195,7 @@ class HomematicipHeatingThermostat(HomematicipGenericDevice): @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" - return "%" + return UNIT_PERCENTAGE class HomematicipHumiditySensor(HomematicipGenericDevice): @@ -217,7 +218,7 @@ class HomematicipHumiditySensor(HomematicipGenericDevice): @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" - return "%" + return UNIT_PERCENTAGE class HomematicipTemperatureSensor(HomematicipGenericDevice): diff --git a/homeassistant/components/htu21d/sensor.py b/homeassistant/components/htu21d/sensor.py index 954ba60abbf..5bd77d4dcb2 100644 --- a/homeassistant/components/htu21d/sensor.py +++ b/homeassistant/components/htu21d/sensor.py @@ -8,7 +8,7 @@ import smbus # pylint: disable=import-error import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_NAME, TEMP_FAHRENHEIT +from homeassistant.const import CONF_NAME, TEMP_FAHRENHEIT, UNIT_PERCENTAGE import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle @@ -50,7 +50,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= dev = [ HTU21DSensor(sensor_handler, name, SENSOR_TEMPERATURE, temp_unit), - HTU21DSensor(sensor_handler, name, SENSOR_HUMIDITY, "%"), + HTU21DSensor(sensor_handler, name, SENSOR_HUMIDITY, UNIT_PERCENTAGE), ] async_add_entities(dev) diff --git a/homeassistant/components/icloud/sensor.py b/homeassistant/components/icloud/sensor.py index e24016795d3..5438b9ce810 100644 --- a/homeassistant/components/icloud/sensor.py +++ b/homeassistant/components/icloud/sensor.py @@ -3,7 +3,7 @@ import logging from typing import Dict from homeassistant.config_entries import ConfigEntry -from homeassistant.const import CONF_USERNAME, DEVICE_CLASS_BATTERY +from homeassistant.const import CONF_USERNAME, DEVICE_CLASS_BATTERY, UNIT_PERCENTAGE from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity from homeassistant.helpers.icon import icon_for_battery_level @@ -61,7 +61,7 @@ class IcloudDeviceBatterySensor(Entity): @property def unit_of_measurement(self) -> str: """Battery state measured in percentage.""" - return "%" + return UNIT_PERCENTAGE @property def icon(self) -> str: diff --git a/homeassistant/components/ios/sensor.py b/homeassistant/components/ios/sensor.py index 85a0a81fdf3..e12ab9b4a40 100644 --- a/homeassistant/components/ios/sensor.py +++ b/homeassistant/components/ios/sensor.py @@ -1,9 +1,13 @@ """Support for Home Assistant iOS app sensors.""" from homeassistant.components import ios +from homeassistant.const import UNIT_PERCENTAGE from homeassistant.helpers.entity import Entity from homeassistant.helpers.icon import icon_for_battery_level -SENSOR_TYPES = {"level": ["Battery Level", "%"], "state": ["Battery State", None]} +SENSOR_TYPES = { + "level": ["Battery Level", UNIT_PERCENTAGE], + "state": ["Battery State", None], +} DEFAULT_ICON_LEVEL = "mdi:battery" DEFAULT_ICON_STATE = "mdi:power-plug" diff --git a/homeassistant/components/isy994/__init__.py b/homeassistant/components/isy994/__init__.py index 3cffbdb1214..6615fc6c569 100644 --- a/homeassistant/components/isy994/__init__.py +++ b/homeassistant/components/isy994/__init__.py @@ -12,6 +12,7 @@ from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME, EVENT_HOMEASSISTANT_STOP, + UNIT_PERCENTAGE, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, discovery @@ -101,7 +102,7 @@ NODE_FILTERS = { }, "light": { "uom": ["51"], - "states": ["on", "off", "%"], + "states": ["on", "off", UNIT_PERCENTAGE], "node_def_id": [ "DimmerLampSwitch", "DimmerLampSwitch_ADV", diff --git a/homeassistant/components/isy994/sensor.py b/homeassistant/components/isy994/sensor.py index 42590b0ea13..9e2f3e90957 100644 --- a/homeassistant/components/isy994/sensor.py +++ b/homeassistant/components/isy994/sensor.py @@ -18,6 +18,7 @@ from homeassistant.const import ( TIME_MONTHS, TIME_SECONDS, TIME_YEARS, + UNIT_PERCENTAGE, UNIT_UV_INDEX, ) from homeassistant.helpers.typing import ConfigType @@ -74,7 +75,7 @@ UOM_FRIENDLY_NAME = { "48": SPEED_MILES_PER_HOUR, "49": SPEED_METERS_PER_SECOND, "50": "ohm", - "51": "%", + "51": UNIT_PERCENTAGE, "52": "lb", "53": "power factor", "54": CONCENTRATION_PARTS_PER_MILLION, diff --git a/homeassistant/components/kaiterra/const.py b/homeassistant/components/kaiterra/const.py index 6c3ea4d6f01..7f7eff99444 100644 --- a/homeassistant/components/kaiterra/const.py +++ b/homeassistant/components/kaiterra/const.py @@ -7,6 +7,7 @@ from homeassistant.const import ( CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_BILLION, CONCENTRATION_PARTS_PER_MILLION, + UNIT_PERCENTAGE, ) DOMAIN = "kaiterra" @@ -53,7 +54,7 @@ ATTR_AQI_POLLUTANT = "air_quality_index_pollutant" AVAILABLE_AQI_STANDARDS = ["us", "cn", "in"] AVAILABLE_UNITS = [ "x", - "%", + UNIT_PERCENTAGE, "C", "F", CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, diff --git a/homeassistant/components/konnected/sensor.py b/homeassistant/components/konnected/sensor.py index 4fa238166f8..e936898d7fb 100644 --- a/homeassistant/components/konnected/sensor.py +++ b/homeassistant/components/konnected/sensor.py @@ -10,6 +10,7 @@ from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect @@ -21,7 +22,7 @@ _LOGGER = logging.getLogger(__name__) SENSOR_TYPES = { DEVICE_CLASS_TEMPERATURE: ["Temperature", TEMP_CELSIUS], - DEVICE_CLASS_HUMIDITY: ["Humidity", "%"], + DEVICE_CLASS_HUMIDITY: ["Humidity", UNIT_PERCENTAGE], } @@ -119,9 +120,7 @@ class KonnectedSensor(Entity): @property def device_info(self): """Return the device info.""" - return { - "identifiers": {(KONNECTED_DOMAIN, self._device_id)}, - } + return {"identifiers": {(KONNECTED_DOMAIN, self._device_id)}} async def async_added_to_hass(self): """Store entity_id and register state change callback.""" diff --git a/homeassistant/components/lacrosse/sensor.py b/homeassistant/components/lacrosse/sensor.py index b8bde797b39..1d38764710a 100644 --- a/homeassistant/components/lacrosse/sensor.py +++ b/homeassistant/components/lacrosse/sensor.py @@ -15,6 +15,7 @@ from homeassistant.const import ( CONF_TYPE, EVENT_HOMEASSISTANT_STOP, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv @@ -193,7 +194,7 @@ class LaCrosseHumidity(LaCrosseSensor): @property def unit_of_measurement(self): """Return the unit of measurement.""" - return "%" + return UNIT_PERCENTAGE @property def state(self): diff --git a/homeassistant/components/lcn/const.py b/homeassistant/components/lcn/const.py index ff7de1987da..0a46190fbf9 100644 --- a/homeassistant/components/lcn/const.py +++ b/homeassistant/components/lcn/const.py @@ -1,7 +1,7 @@ """Constants for the LCN component.""" from itertools import product -from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT +from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT, UNIT_PERCENTAGE DOMAIN = "lcn" DATA_LCN = "lcn" @@ -153,7 +153,7 @@ VAR_UNITS = [ "LX", "M/S", "METERPERSECOND", - "%", + UNIT_PERCENTAGE, "PERCENT", "PPM", "VOLT", diff --git a/homeassistant/components/linux_battery/sensor.py b/homeassistant/components/linux_battery/sensor.py index bc02affdaed..bb1dd34dc00 100644 --- a/homeassistant/components/linux_battery/sensor.py +++ b/homeassistant/components/linux_battery/sensor.py @@ -6,7 +6,12 @@ from batinfo import Batteries import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import ATTR_NAME, CONF_NAME, DEVICE_CLASS_BATTERY +from homeassistant.const import ( + ATTR_NAME, + CONF_NAME, + DEVICE_CLASS_BATTERY, + UNIT_PERCENTAGE, +) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -98,7 +103,7 @@ class LinuxBatterySensor(Entity): @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" - return "%" + return UNIT_PERCENTAGE @property def device_state_attributes(self): diff --git a/homeassistant/components/logi_circle/const.py b/homeassistant/components/logi_circle/const.py index 4be4823f8d7..333a85e9b77 100644 --- a/homeassistant/components/logi_circle/const.py +++ b/homeassistant/components/logi_circle/const.py @@ -1,4 +1,5 @@ """Constants in Logi Circle component.""" +from homeassistant.const import UNIT_PERCENTAGE CONF_CLIENT_ID = "client_id" CONF_CLIENT_SECRET = "client_secret" @@ -15,11 +16,11 @@ RECORDING_MODE_KEY = "RECORDING_MODE" # Sensor types: Name, unit of measure, icon per sensor key. LOGI_SENSORS = { - "battery_level": ["Battery", "%", "battery-50"], + "battery_level": ["Battery", UNIT_PERCENTAGE, "battery-50"], "last_activity_time": ["Last Activity", None, "history"], "recording": ["Recording Mode", None, "eye"], "signal_strength_category": ["WiFi Signal Category", None, "wifi"], - "signal_strength_percentage": ["WiFi Signal Strength", "%", "wifi"], + "signal_strength_percentage": ["WiFi Signal Strength", UNIT_PERCENTAGE, "wifi"], "streaming": ["Streaming Mode", None, "camera"], } diff --git a/homeassistant/components/luftdaten/__init__.py b/homeassistant/components/luftdaten/__init__.py index a722829a4a2..f7ed2d72f16 100644 --- a/homeassistant/components/luftdaten/__init__.py +++ b/homeassistant/components/luftdaten/__init__.py @@ -13,6 +13,7 @@ from homeassistant.const import ( CONF_SENSORS, CONF_SHOW_ON_MAP, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.core import callback from homeassistant.exceptions import ConfigEntryNotReady @@ -42,7 +43,7 @@ TOPIC_UPDATE = f"{DOMAIN}_data_update" SENSORS = { SENSOR_TEMPERATURE: ["Temperature", "mdi:thermometer", TEMP_CELSIUS], - SENSOR_HUMIDITY: ["Humidity", "mdi:water-percent", "%"], + SENSOR_HUMIDITY: ["Humidity", "mdi:water-percent", UNIT_PERCENTAGE], SENSOR_PRESSURE: ["Pressure", "mdi:arrow-down-bold", "Pa"], SENSOR_PRESSURE_AT_SEALEVEL: ["Pressure at sealevel", "mdi:download", "Pa"], SENSOR_PM10: [ diff --git a/homeassistant/components/meteo_france/const.py b/homeassistant/components/meteo_france/const.py index 9fde6f38b51..b7647f5d97b 100644 --- a/homeassistant/components/meteo_france/const.py +++ b/homeassistant/components/meteo_france/const.py @@ -1,6 +1,11 @@ """Meteo-France component constants.""" -from homeassistant.const import SPEED_KILOMETERS_PER_HOUR, TEMP_CELSIUS, TIME_MINUTES +from homeassistant.const import ( + SPEED_KILOMETERS_PER_HOUR, + TEMP_CELSIUS, + TIME_MINUTES, + UNIT_PERCENTAGE, +) DOMAIN = "meteo_france" PLATFORMS = ["sensor", "weather"] @@ -17,25 +22,25 @@ SENSOR_TYPE_CLASS = "device_class" SENSOR_TYPES = { "rain_chance": { SENSOR_TYPE_NAME: "Rain chance", - SENSOR_TYPE_UNIT: "%", + SENSOR_TYPE_UNIT: UNIT_PERCENTAGE, SENSOR_TYPE_ICON: "mdi:weather-rainy", SENSOR_TYPE_CLASS: None, }, "freeze_chance": { SENSOR_TYPE_NAME: "Freeze chance", - SENSOR_TYPE_UNIT: "%", + SENSOR_TYPE_UNIT: UNIT_PERCENTAGE, SENSOR_TYPE_ICON: "mdi:snowflake", SENSOR_TYPE_CLASS: None, }, "thunder_chance": { SENSOR_TYPE_NAME: "Thunder chance", - SENSOR_TYPE_UNIT: "%", + SENSOR_TYPE_UNIT: UNIT_PERCENTAGE, SENSOR_TYPE_ICON: "mdi:weather-lightning", SENSOR_TYPE_CLASS: None, }, "snow_chance": { SENSOR_TYPE_NAME: "Snow chance", - SENSOR_TYPE_UNIT: "%", + SENSOR_TYPE_UNIT: UNIT_PERCENTAGE, SENSOR_TYPE_ICON: "mdi:weather-snowy", SENSOR_TYPE_CLASS: None, }, diff --git a/homeassistant/components/metoffice/sensor.py b/homeassistant/components/metoffice/sensor.py index 6e6fde06d8c..1c4ca83e5bd 100644 --- a/homeassistant/components/metoffice/sensor.py +++ b/homeassistant/components/metoffice/sensor.py @@ -15,6 +15,7 @@ from homeassistant.const import ( CONF_NAME, SPEED_MILES_PER_HOUR, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -71,8 +72,8 @@ SENSOR_TYPES = { "visibility": ["Visibility", None], "visibility_distance": ["Visibility Distance", "km"], "uv": ["UV", None], - "precipitation": ["Probability of Precipitation", "%"], - "humidity": ["Humidity", "%"], + "precipitation": ["Probability of Precipitation", UNIT_PERCENTAGE], + "humidity": ["Humidity", UNIT_PERCENTAGE], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( diff --git a/homeassistant/components/microsoft/tts.py b/homeassistant/components/microsoft/tts.py index 074605e07fe..c857cc731f4 100644 --- a/homeassistant/components/microsoft/tts.py +++ b/homeassistant/components/microsoft/tts.py @@ -6,7 +6,7 @@ from pycsspeechtts import pycsspeechtts import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider -from homeassistant.const import CONF_API_KEY, CONF_TYPE +from homeassistant.const import CONF_API_KEY, CONF_TYPE, UNIT_PERCENTAGE import homeassistant.helpers.config_validation as cv CONF_GENDER = "gender" @@ -122,8 +122,8 @@ class MicrosoftProvider(Provider): self._gender = gender self._type = ttype self._output = DEFAULT_OUTPUT - self._rate = f"{rate}%" - self._volume = f"{volume}%" + self._rate = f"{rate}{UNIT_PERCENTAGE}" + self._volume = f"{volume}{UNIT_PERCENTAGE}" self._pitch = pitch self._contour = contour self._region = region diff --git a/homeassistant/components/miflora/sensor.py b/homeassistant/components/miflora/sensor.py index 815a6e97bb8..bd551517562 100644 --- a/homeassistant/components/miflora/sensor.py +++ b/homeassistant/components/miflora/sensor.py @@ -15,6 +15,7 @@ from homeassistant.const import ( CONF_NAME, CONF_SCAN_INTERVAL, EVENT_HOMEASSISTANT_START, + UNIT_PERCENTAGE, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv @@ -43,9 +44,9 @@ SCAN_INTERVAL = timedelta(seconds=1200) SENSOR_TYPES = { "temperature": ["Temperature", "°C", "mdi:thermometer"], "light": ["Light intensity", "lx", "mdi:white-balance-sunny"], - "moisture": ["Moisture", "%", "mdi:water-percent"], + "moisture": ["Moisture", UNIT_PERCENTAGE, "mdi:water-percent"], "conductivity": ["Conductivity", "µS/cm", "mdi:flash-circle"], - "battery": ["Battery", "%", "mdi:battery-charging"], + "battery": ["Battery", UNIT_PERCENTAGE, "mdi:battery-charging"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( diff --git a/homeassistant/components/mitemp_bt/sensor.py b/homeassistant/components/mitemp_bt/sensor.py index b536149680d..febfb93cf1d 100644 --- a/homeassistant/components/mitemp_bt/sensor.py +++ b/homeassistant/components/mitemp_bt/sensor.py @@ -15,6 +15,7 @@ from homeassistant.const import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -46,8 +47,8 @@ DEFAULT_TIMEOUT = 10 # Sensor types are defined like: Name, units SENSOR_TYPES = { "temperature": [DEVICE_CLASS_TEMPERATURE, "Temperature", "°C"], - "humidity": [DEVICE_CLASS_HUMIDITY, "Humidity", "%"], - "battery": [DEVICE_CLASS_BATTERY, "Battery", "%"], + "humidity": [DEVICE_CLASS_HUMIDITY, "Humidity", UNIT_PERCENTAGE], + "battery": [DEVICE_CLASS_BATTERY, "Battery", UNIT_PERCENTAGE], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( diff --git a/homeassistant/components/mold_indicator/sensor.py b/homeassistant/components/mold_indicator/sensor.py index 0d6c6f55284..b5c72fdce29 100644 --- a/homeassistant/components/mold_indicator/sensor.py +++ b/homeassistant/components/mold_indicator/sensor.py @@ -13,6 +13,7 @@ from homeassistant.const import ( STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv @@ -245,7 +246,7 @@ class MoldIndicator(Entity): ) return None - if unit != "%": + if unit != UNIT_PERCENTAGE: _LOGGER.error( "Humidity sensor %s has unsupported unit: %s %s", state.entity_id, @@ -360,7 +361,7 @@ class MoldIndicator(Entity): @property def unit_of_measurement(self): """Return the unit of measurement.""" - return "%" + return UNIT_PERCENTAGE @property def state(self): diff --git a/homeassistant/components/mychevy/sensor.py b/homeassistant/components/mychevy/sensor.py index 844c301fe49..56335bb1650 100644 --- a/homeassistant/components/mychevy/sensor.py +++ b/homeassistant/components/mychevy/sensor.py @@ -2,6 +2,7 @@ import logging from homeassistant.components.sensor import ENTITY_ID_FORMAT +from homeassistant.const import UNIT_PERCENTAGE from homeassistant.core import callback from homeassistant.helpers.entity import Entity from homeassistant.helpers.icon import icon_for_battery_level @@ -25,7 +26,9 @@ SENSORS = [ EVSensorConfig("Electric Range", "electricRange", "miles", "mdi:speedometer"), EVSensorConfig("Charged By", "estimatedFullChargeBy"), EVSensorConfig("Charge Mode", "chargeMode"), - EVSensorConfig("Battery Level", BATTERY_SENSOR, "%", "mdi:battery", ["charging"]), + EVSensorConfig( + "Battery Level", BATTERY_SENSOR, UNIT_PERCENTAGE, "mdi:battery", ["charging"] + ), ] diff --git a/homeassistant/components/mysensors/sensor.py b/homeassistant/components/mysensors/sensor.py index 2b8cf208c14..997728ed495 100644 --- a/homeassistant/components/mysensors/sensor.py +++ b/homeassistant/components/mysensors/sensor.py @@ -7,13 +7,14 @@ from homeassistant.const import ( POWER_WATT, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) SENSORS = { "V_TEMP": [None, "mdi:thermometer"], - "V_HUM": ["%", "mdi:water-percent"], - "V_DIMMER": ["%", "mdi:percent"], - "V_PERCENTAGE": ["%", "mdi:percent"], + "V_HUM": [UNIT_PERCENTAGE, "mdi:water-percent"], + "V_DIMMER": [UNIT_PERCENTAGE, "mdi:percent"], + "V_PERCENTAGE": [UNIT_PERCENTAGE, "mdi:percent"], "V_PRESSURE": [None, "mdi:gauge"], "V_FORECAST": [None, "mdi:weather-partly-cloudy"], "V_RAIN": [None, "mdi:weather-rainy"], @@ -26,7 +27,7 @@ SENSORS = { "V_IMPEDANCE": ["ohm", None], "V_WATT": [POWER_WATT, None], "V_KWH": [ENERGY_KILO_WATT_HOUR, None], - "V_LIGHT_LEVEL": ["%", "mdi:white-balance-sunny"], + "V_LIGHT_LEVEL": [UNIT_PERCENTAGE, "mdi:white-balance-sunny"], "V_FLOW": ["m", "mdi:gauge"], "V_VOLUME": ["m³", None], "V_LEVEL": { diff --git a/homeassistant/components/neato/sensor.py b/homeassistant/components/neato/sensor.py index 70d273fe690..5573e280a99 100644 --- a/homeassistant/components/neato/sensor.py +++ b/homeassistant/components/neato/sensor.py @@ -5,6 +5,7 @@ import logging from pybotvac.exceptions import NeatoRobotException from homeassistant.components.sensor import DEVICE_CLASS_BATTERY +from homeassistant.const import UNIT_PERCENTAGE from homeassistant.helpers.entity import Entity from .const import NEATO_DOMAIN, NEATO_LOGIN, NEATO_ROBOTS, SCAN_INTERVAL_MINUTES @@ -83,7 +84,7 @@ class NeatoSensor(Entity): @property def unit_of_measurement(self): """Return unit of measurement.""" - return "%" + return UNIT_PERCENTAGE @property def device_info(self): diff --git a/homeassistant/components/nest/sensor.py b/homeassistant/components/nest/sensor.py index d52df4c6586..225caee0a90 100644 --- a/homeassistant/components/nest/sensor.py +++ b/homeassistant/components/nest/sensor.py @@ -8,6 +8,7 @@ from homeassistant.const import ( STATE_OFF, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) from . import CONF_SENSORS, DATA_NEST, DATA_NEST_CONFIG, NestSensorDevice @@ -41,7 +42,7 @@ _VALID_SENSOR_TYPES = ( + STRUCTURE_CAMERA_SENSOR_TYPES ) -SENSOR_UNITS = {"humidity": "%"} +SENSOR_UNITS = {"humidity": UNIT_PERCENTAGE} SENSOR_DEVICE_CLASSES = {"humidity": DEVICE_CLASS_HUMIDITY} diff --git a/homeassistant/components/netatmo/sensor.py b/homeassistant/components/netatmo/sensor.py index 9254f2f45ab..f52b6797a7a 100644 --- a/homeassistant/components/netatmo/sensor.py +++ b/homeassistant/components/netatmo/sensor.py @@ -11,6 +11,7 @@ from homeassistant.const import ( DEVICE_CLASS_TEMPERATURE, SPEED_KILOMETERS_PER_HOUR, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle @@ -57,13 +58,18 @@ SENSOR_TYPES = { "co2": ["CO2", CONCENTRATION_PARTS_PER_MILLION, "mdi:periodic-table-co2", None], "pressure": ["Pressure", "mbar", "mdi:gauge", None], "noise": ["Noise", "dB", "mdi:volume-high", None], - "humidity": ["Humidity", "%", "mdi:water-percent", DEVICE_CLASS_HUMIDITY], + "humidity": [ + "Humidity", + UNIT_PERCENTAGE, + "mdi:water-percent", + DEVICE_CLASS_HUMIDITY, + ], "rain": ["Rain", "mm", "mdi:weather-rainy", None], "sum_rain_1": ["sum_rain_1", "mm", "mdi:weather-rainy", None], "sum_rain_24": ["sum_rain_24", "mm", "mdi:weather-rainy", None], "battery_vp": ["Battery", "", "mdi:battery", None], "battery_lvl": ["Battery_lvl", "", "mdi:battery", None], - "battery_percent": ["battery_percent", "%", None, DEVICE_CLASS_BATTERY], + "battery_percent": ["battery_percent", UNIT_PERCENTAGE, None, DEVICE_CLASS_BATTERY], "min_temp": ["Min Temp.", TEMP_CELSIUS, "mdi:thermometer", None], "max_temp": ["Max Temp.", TEMP_CELSIUS, "mdi:thermometer", None], "windangle": ["Angle", "", "mdi:compass", None], diff --git a/homeassistant/components/netdata/sensor.py b/homeassistant/components/netdata/sensor.py index edabef9535c..4406734b094 100644 --- a/homeassistant/components/netdata/sensor.py +++ b/homeassistant/components/netdata/sensor.py @@ -13,6 +13,7 @@ from homeassistant.const import ( CONF_NAME, CONF_PORT, CONF_RESOURCES, + UNIT_PERCENTAGE, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -78,7 +79,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= try: resource_data = netdata.api.metrics[sensor] unit = ( - "%" + UNIT_PERCENTAGE if resource_data["units"] == "percentage" else resource_data["units"] ) diff --git a/homeassistant/components/netgear_lte/sensor_types.py b/homeassistant/components/netgear_lte/sensor_types.py index a744937dacd..883b4803544 100644 --- a/homeassistant/components/netgear_lte/sensor_types.py +++ b/homeassistant/components/netgear_lte/sensor_types.py @@ -1,7 +1,7 @@ """Define possible sensor types.""" from homeassistant.components.binary_sensor import DEVICE_CLASS_CONNECTIVITY -from homeassistant.const import DATA_MEBIBYTES +from homeassistant.const import DATA_MEBIBYTES, UNIT_PERCENTAGE SENSOR_SMS = "sms" SENSOR_SMS_TOTAL = "sms_total" @@ -11,7 +11,7 @@ SENSOR_UNITS = { SENSOR_SMS: "unread", SENSOR_SMS_TOTAL: "messages", SENSOR_USAGE: DATA_MEBIBYTES, - "radio_quality": "%", + "radio_quality": UNIT_PERCENTAGE, "rx_level": "dBm", "tx_level": "dBm", "upstream": None, diff --git a/homeassistant/components/nfandroidtv/notify.py b/homeassistant/components/nfandroidtv/notify.py index 52f0af607bc..280733affd2 100644 --- a/homeassistant/components/nfandroidtv/notify.py +++ b/homeassistant/components/nfandroidtv/notify.py @@ -14,7 +14,7 @@ from homeassistant.components.notify import ( PLATFORM_SCHEMA, BaseNotificationService, ) -from homeassistant.const import CONF_HOST, CONF_TIMEOUT +from homeassistant.const import CONF_HOST, CONF_TIMEOUT, UNIT_PERCENTAGE import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -66,7 +66,14 @@ POSITIONS = { "center": 4, } -TRANSPARENCIES = {"default": 0, "0%": 1, "25%": 2, "50%": 3, "75%": 4, "100%": 5} +TRANSPARENCIES = { + "default": 0, + f"0{UNIT_PERCENTAGE}": 1, + f"25{UNIT_PERCENTAGE}": 2, + f"50{UNIT_PERCENTAGE}": 3, + f"75{UNIT_PERCENTAGE}": 4, + f"100{UNIT_PERCENTAGE}": 5, +} COLORS = { "grey": "#607d8b", diff --git a/homeassistant/components/nissan_leaf/sensor.py b/homeassistant/components/nissan_leaf/sensor.py index bbdb8ad7527..33b0efa5d60 100644 --- a/homeassistant/components/nissan_leaf/sensor.py +++ b/homeassistant/components/nissan_leaf/sensor.py @@ -1,7 +1,7 @@ """Battery Charge and Range Support for the Nissan Leaf.""" import logging -from homeassistant.const import DEVICE_CLASS_BATTERY +from homeassistant.const import DEVICE_CLASS_BATTERY, UNIT_PERCENTAGE from homeassistant.helpers.icon import icon_for_battery_level from homeassistant.util.distance import LENGTH_KILOMETERS, LENGTH_MILES from homeassistant.util.unit_system import IMPERIAL_SYSTEM, METRIC_SYSTEM @@ -56,7 +56,7 @@ class LeafBatterySensor(LeafEntity): @property def unit_of_measurement(self): """Battery state measured in percentage.""" - return "%" + return UNIT_PERCENTAGE @property def icon(self): diff --git a/homeassistant/components/nut/sensor.py b/homeassistant/components/nut/sensor.py index 96db220f5ea..15dee84dd9b 100644 --- a/homeassistant/components/nut/sensor.py +++ b/homeassistant/components/nut/sensor.py @@ -19,6 +19,7 @@ from homeassistant.const import ( STATE_UNKNOWN, TEMP_CELSIUS, TIME_SECONDS, + UNIT_PERCENTAGE, ) from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv @@ -51,8 +52,8 @@ SENSOR_TYPES = { "ups.firmware": ["Firmware Version", "", "mdi:information-outline"], "ups.firmware.aux": ["Firmware Version 2", "", "mdi:information-outline"], "ups.temperature": ["UPS Temperature", TEMP_CELSIUS, "mdi:thermometer"], - "ups.load": ["Load", "%", "mdi:gauge"], - "ups.load.high": ["Overload Setting", "%", "mdi:gauge"], + "ups.load": ["Load", UNIT_PERCENTAGE, "mdi:gauge"], + "ups.load.high": ["Overload Setting", UNIT_PERCENTAGE, "mdi:gauge"], "ups.id": ["System identifier", "", "mdi:information-outline"], "ups.delay.start": ["Load Restart Delay", TIME_SECONDS, "mdi:timer"], "ups.delay.reboot": ["UPS Reboot Delay", TIME_SECONDS, "mdi:timer"], @@ -65,7 +66,7 @@ SENSOR_TYPES = { "ups.test.date": ["Self-Test Date", "", "mdi:calendar"], "ups.display.language": ["Language", "", "mdi:information-outline"], "ups.contacts": ["External Contacts", "", "mdi:information-outline"], - "ups.efficiency": ["Efficiency", "%", "mdi:gauge"], + "ups.efficiency": ["Efficiency", UNIT_PERCENTAGE, "mdi:gauge"], "ups.power": ["Current Apparent Power", "VA", "mdi:flash"], "ups.power.nominal": ["Nominal Power", "VA", "mdi:flash"], "ups.realpower": ["Current Real Power", POWER_WATT, "mdi:flash"], @@ -77,10 +78,18 @@ SENSOR_TYPES = { "ups.start.battery": ["Start on Battery", "", "mdi:information-outline"], "ups.start.reboot": ["Reboot on Battery", "", "mdi:information-outline"], "ups.shutdown": ["Shutdown Ability", "", "mdi:information-outline"], - "battery.charge": ["Battery Charge", "%", "mdi:gauge"], - "battery.charge.low": ["Low Battery Setpoint", "%", "mdi:gauge"], - "battery.charge.restart": ["Minimum Battery to Start", "%", "mdi:gauge"], - "battery.charge.warning": ["Warning Battery Setpoint", "%", "mdi:gauge"], + "battery.charge": ["Battery Charge", UNIT_PERCENTAGE, "mdi:gauge"], + "battery.charge.low": ["Low Battery Setpoint", UNIT_PERCENTAGE, "mdi:gauge"], + "battery.charge.restart": [ + "Minimum Battery to Start", + UNIT_PERCENTAGE, + "mdi:gauge", + ], + "battery.charge.warning": [ + "Warning Battery Setpoint", + UNIT_PERCENTAGE, + "mdi:gauge", + ], "battery.charger.status": ["Charging Status", "", "mdi:information-outline"], "battery.voltage": ["Battery Voltage", "V", "mdi:flash"], "battery.voltage.nominal": ["Nominal Battery Voltage", "V", "mdi:flash"], diff --git a/homeassistant/components/octoprint/__init__.py b/homeassistant/components/octoprint/__init__.py index 06a8ae44f1f..dba7e656aff 100644 --- a/homeassistant/components/octoprint/__init__.py +++ b/homeassistant/components/octoprint/__init__.py @@ -20,6 +20,7 @@ from homeassistant.const import ( CONTENT_TYPE_JSON, TEMP_CELSIUS, TIME_SECONDS, + UNIT_PERCENTAGE, ) from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv @@ -71,7 +72,13 @@ SENSOR_TYPES = { # API Endpoint, Group, Key, unit, icon "Temperatures": ["printer", "temperature", "*", TEMP_CELSIUS], "Current State": ["printer", "state", "text", None, "mdi:printer-3d"], - "Job Percentage": ["job", "progress", "completion", "%", "mdi:file-percent"], + "Job Percentage": [ + "job", + "progress", + "completion", + UNIT_PERCENTAGE, + "mdi:file-percent", + ], "Time Remaining": [ "job", "progress", diff --git a/homeassistant/components/octoprint/sensor.py b/homeassistant/components/octoprint/sensor.py index 98d878fc2ea..83b247c39cb 100644 --- a/homeassistant/components/octoprint/sensor.py +++ b/homeassistant/components/octoprint/sensor.py @@ -3,7 +3,7 @@ import logging import requests -from homeassistant.const import TEMP_CELSIUS +from homeassistant.const import TEMP_CELSIUS, UNIT_PERCENTAGE from homeassistant.helpers.entity import Entity from . import DOMAIN as COMPONENT_DOMAIN, SENSOR_TYPES @@ -111,7 +111,7 @@ class OctoPrintSensor(Entity): def state(self): """Return the state of the sensor.""" sensor_unit = self.unit_of_measurement - if sensor_unit in (TEMP_CELSIUS, "%"): + if sensor_unit in (TEMP_CELSIUS, UNIT_PERCENTAGE): # API sometimes returns null and not 0 if self._state is None: self._state = 0 diff --git a/homeassistant/components/onewire/sensor.py b/homeassistant/components/onewire/sensor.py index 6a7f282ac87..41f41a6e93d 100644 --- a/homeassistant/components/onewire/sensor.py +++ b/homeassistant/components/onewire/sensor.py @@ -8,7 +8,7 @@ from pyownet import protocol import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_HOST, CONF_PORT, TEMP_CELSIUS +from homeassistant.const import CONF_HOST, CONF_PORT, TEMP_CELSIUS, UNIT_PERCENTAGE import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -60,14 +60,14 @@ HOBBYBOARD_EF = { SENSOR_TYPES = { # SensorType: [ Measured unit, Unit ] "temperature": ["temperature", TEMP_CELSIUS], - "humidity": ["humidity", "%"], - "humidity_raw": ["humidity", "%"], + "humidity": ["humidity", UNIT_PERCENTAGE], + "humidity_raw": ["humidity", UNIT_PERCENTAGE], "pressure": ["pressure", "mb"], "illuminance": ["illuminance", "lux"], - "wetness_0": ["wetness", "%"], - "wetness_1": ["wetness", "%"], - "wetness_2": ["wetness", "%"], - "wetness_3": ["wetness", "%"], + "wetness_0": ["wetness", UNIT_PERCENTAGE], + "wetness_1": ["wetness", UNIT_PERCENTAGE], + "wetness_2": ["wetness", UNIT_PERCENTAGE], + "wetness_3": ["wetness", UNIT_PERCENTAGE], "moisture_0": ["moisture", "cb"], "moisture_1": ["moisture", "cb"], "moisture_2": ["moisture", "cb"], diff --git a/homeassistant/components/opentherm_gw/const.py b/homeassistant/components/opentherm_gw/const.py index 580f9f7b1a4..b8d427ba193 100644 --- a/homeassistant/components/opentherm_gw/const.py +++ b/homeassistant/components/opentherm_gw/const.py @@ -6,6 +6,7 @@ from homeassistant.const import ( TEMP_CELSIUS, TIME_HOURS, TIME_MINUTES, + UNIT_PERCENTAGE, ) ATTR_GW_ID = "gateway_id" @@ -38,7 +39,6 @@ SERVICE_SET_SB_TEMP = "set_setback_temperature" UNIT_BAR = "bar" UNIT_KW = "kW" UNIT_L_MIN = f"L/{TIME_MINUTES}" -UNIT_PERCENT = "%" BINARY_SENSOR_INFO = { # [device_class, friendly_name format] @@ -121,7 +121,7 @@ SENSOR_INFO = { gw_vars.DATA_MASTER_MEMBERID: [None, None, "Thermostat Member ID {}"], gw_vars.DATA_SLAVE_MEMBERID: [None, None, "Boiler Member ID {}"], gw_vars.DATA_SLAVE_OEM_FAULT: [None, None, "Boiler OEM Fault Code {}"], - gw_vars.DATA_COOLING_CONTROL: [None, UNIT_PERCENT, "Cooling Control Signal {}"], + gw_vars.DATA_COOLING_CONTROL: [None, UNIT_PERCENTAGE, "Cooling Control Signal {}"], gw_vars.DATA_CONTROL_SETPOINT_2: [ DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, @@ -134,13 +134,13 @@ SENSOR_INFO = { ], gw_vars.DATA_SLAVE_MAX_RELATIVE_MOD: [ None, - UNIT_PERCENT, + UNIT_PERCENTAGE, "Boiler Maximum Relative Modulation {}", ], gw_vars.DATA_SLAVE_MAX_CAPACITY: [None, UNIT_KW, "Boiler Maximum Capacity {}"], gw_vars.DATA_SLAVE_MIN_MOD_LEVEL: [ None, - UNIT_PERCENT, + UNIT_PERCENTAGE, "Boiler Minimum Modulation Level {}", ], gw_vars.DATA_ROOM_SETPOINT: [ @@ -148,7 +148,7 @@ SENSOR_INFO = { TEMP_CELSIUS, "Room Setpoint {}", ], - gw_vars.DATA_REL_MOD_LEVEL: [None, UNIT_PERCENT, "Relative Modulation Level {}"], + gw_vars.DATA_REL_MOD_LEVEL: [None, UNIT_PERCENTAGE, "Relative Modulation Level {}"], gw_vars.DATA_CH_WATER_PRESS: [None, UNIT_BAR, "Central Heating Water Pressure {}"], gw_vars.DATA_DHW_FLOW_RATE: [None, UNIT_L_MIN, "Hot Water Flow Rate {}"], gw_vars.DATA_ROOM_SETPOINT_2: [ diff --git a/homeassistant/components/openweathermap/sensor.py b/homeassistant/components/openweathermap/sensor.py index 5908ccfff06..ce32458f640 100644 --- a/homeassistant/components/openweathermap/sensor.py +++ b/homeassistant/components/openweathermap/sensor.py @@ -15,6 +15,7 @@ from homeassistant.const import ( SPEED_METERS_PER_SECOND, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -36,9 +37,9 @@ SENSOR_TYPES = { "temperature": ["Temperature", None], "wind_speed": ["Wind speed", SPEED_METERS_PER_SECOND], "wind_bearing": ["Wind bearing", "°"], - "humidity": ["Humidity", "%"], + "humidity": ["Humidity", UNIT_PERCENTAGE], "pressure": ["Pressure", "mbar"], - "clouds": ["Cloud coverage", "%"], + "clouds": ["Cloud coverage", UNIT_PERCENTAGE], "rain": ["Rain", "mm"], "snow": ["Snow", "mm"], "weather_code": ["Weather code", None], diff --git a/homeassistant/components/pi_hole/const.py b/homeassistant/components/pi_hole/const.py index ca4eea32bd6..94f687d9bfa 100644 --- a/homeassistant/components/pi_hole/const.py +++ b/homeassistant/components/pi_hole/const.py @@ -1,6 +1,8 @@ """Constants for the pi_hole integration.""" from datetime import timedelta +from homeassistant.const import UNIT_PERCENTAGE + DOMAIN = "pi_hole" CONF_LOCATION = "location" @@ -26,7 +28,7 @@ SENSOR_DICT = { "ads_blocked_today": ["Ads Blocked Today", "ads", "mdi:close-octagon-outline"], "ads_percentage_today": [ "Ads Percentage Blocked Today", - "%", + UNIT_PERCENTAGE, "mdi:close-octagon-outline", ], "clients_ever_seen": ["Seen Clients", "clients", "mdi:account-outline"], diff --git a/homeassistant/components/plaato/sensor.py b/homeassistant/components/plaato/sensor.py index e7c8033f2ac..34a2a1a42b6 100644 --- a/homeassistant/components/plaato/sensor.py +++ b/homeassistant/components/plaato/sensor.py @@ -2,6 +2,7 @@ import logging +from homeassistant.const import UNIT_PERCENTAGE from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, @@ -145,7 +146,7 @@ class PlaatoSensor(Entity): if self._type == ATTR_BPM: return "bpm" if self._type == ATTR_ABV: - return "%" + return UNIT_PERCENTAGE return "" diff --git a/homeassistant/components/plant/__init__.py b/homeassistant/components/plant/__init__.py index 408c7d1bf36..30542db5e23 100644 --- a/homeassistant/components/plant/__init__.py +++ b/homeassistant/components/plant/__init__.py @@ -16,6 +16,7 @@ from homeassistant.const import ( STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError @@ -131,14 +132,17 @@ class Plant(Entity): """ READINGS = { - READING_BATTERY: {ATTR_UNIT_OF_MEASUREMENT: "%", "min": CONF_MIN_BATTERY_LEVEL}, + READING_BATTERY: { + ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE, + "min": CONF_MIN_BATTERY_LEVEL, + }, READING_TEMPERATURE: { ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS, "min": CONF_MIN_TEMPERATURE, "max": CONF_MAX_TEMPERATURE, }, READING_MOISTURE: { - ATTR_UNIT_OF_MEASUREMENT: "%", + ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE, "min": CONF_MIN_MOISTURE, "max": CONF_MAX_MOISTURE, }, diff --git a/homeassistant/components/point/sensor.py b/homeassistant/components/point/sensor.py index d8ad22bb470..324565aae50 100644 --- a/homeassistant/components/point/sensor.py +++ b/homeassistant/components/point/sensor.py @@ -7,6 +7,7 @@ from homeassistant.const import ( DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.dt import parse_datetime @@ -21,7 +22,7 @@ DEVICE_CLASS_SOUND = "sound_level" SENSOR_TYPES = { DEVICE_CLASS_TEMPERATURE: (None, 1, TEMP_CELSIUS), DEVICE_CLASS_PRESSURE: (None, 0, "hPa"), - DEVICE_CLASS_HUMIDITY: (None, 1, "%"), + DEVICE_CLASS_HUMIDITY: (None, 1, UNIT_PERCENTAGE), DEVICE_CLASS_SOUND: ("mdi:ear-hearing", 1, "dBa"), } diff --git a/homeassistant/components/prometheus/__init__.py b/homeassistant/components/prometheus/__init__.py index d77cb4f56da..314695458b0 100644 --- a/homeassistant/components/prometheus/__init__.py +++ b/homeassistant/components/prometheus/__init__.py @@ -17,6 +17,7 @@ from homeassistant.const import ( EVENT_STATE_CHANGED, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) from homeassistant.helpers import entityfilter, state as state_helper import homeassistant.helpers.config_validation as cv @@ -349,7 +350,7 @@ class PrometheusMetrics: units = { TEMP_CELSIUS: "c", TEMP_FAHRENHEIT: "c", # F should go into C metric - "%": "percent", + UNIT_PERCENTAGE: "percent", } default = unit.replace("/", "_per_") default = default.lower() diff --git a/homeassistant/components/qnap/sensor.py b/homeassistant/components/qnap/sensor.py index 1ad53f4db48..475e02aba86 100644 --- a/homeassistant/components/qnap/sensor.py +++ b/homeassistant/components/qnap/sensor.py @@ -19,6 +19,7 @@ from homeassistant.const import ( DATA_GIBIBYTES, DATA_RATE_MEBIBYTES_PER_SECOND, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv @@ -61,12 +62,12 @@ _SYSTEM_MON_COND = { } _CPU_MON_COND = { "cpu_temp": ["CPU Temperature", TEMP_CELSIUS, "mdi:thermometer"], - "cpu_usage": ["CPU Usage", "%", "mdi:chip"], + "cpu_usage": ["CPU Usage", UNIT_PERCENTAGE, "mdi:chip"], } _MEMORY_MON_COND = { "memory_free": ["Memory Available", DATA_GIBIBYTES, "mdi:memory"], "memory_used": ["Memory Used", DATA_GIBIBYTES, "mdi:memory"], - "memory_percent_used": ["Memory Usage", "%", "mdi:memory"], + "memory_percent_used": ["Memory Usage", UNIT_PERCENTAGE, "mdi:memory"], } _NETWORK_MON_COND = { "network_link_status": ["Network Link", None, "mdi:checkbox-marked-circle-outline"], @@ -80,7 +81,7 @@ _DRIVE_MON_COND = { _VOLUME_MON_COND = { "volume_size_used": ["Used Space", DATA_GIBIBYTES, "mdi:chart-pie"], "volume_size_free": ["Free Space", DATA_GIBIBYTES, "mdi:chart-pie"], - "volume_percentage_used": ["Volume Used", "%", "mdi:chart-pie"], + "volume_percentage_used": ["Volume Used", UNIT_PERCENTAGE, "mdi:chart-pie"], } _MONITORED_CONDITIONS = ( diff --git a/homeassistant/components/raincloud/__init__.py b/homeassistant/components/raincloud/__init__.py index 41fefbe8fca..4f9ae7fb733 100644 --- a/homeassistant/components/raincloud/__init__.py +++ b/homeassistant/components/raincloud/__init__.py @@ -13,6 +13,7 @@ from homeassistant.const import ( CONF_USERNAME, TIME_DAYS, TIME_MINUTES, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send @@ -58,7 +59,7 @@ ICON_MAP = { UNIT_OF_MEASUREMENT_MAP = { "auto_watering": "", - "battery": "%", + "battery": UNIT_PERCENTAGE, "is_watering": "", "manual_watering": "", "next_cycle": "", diff --git a/homeassistant/components/repetier/__init__.py b/homeassistant/components/repetier/__init__.py index 1d6026a8754..a5a9224464d 100644 --- a/homeassistant/components/repetier/__init__.py +++ b/homeassistant/components/repetier/__init__.py @@ -13,6 +13,7 @@ from homeassistant.const import ( CONF_PORT, CONF_SENSORS, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform @@ -123,7 +124,7 @@ SENSOR_TYPES = { "_chamber_", ], "current_state": ["state", None, "mdi:printer-3d", ""], - "current_job": ["progress", "%", "mdi:file-percent", "_current_job"], + "current_job": ["progress", UNIT_PERCENTAGE, "mdi:file-percent", "_current_job"], "job_end": ["progress", None, "mdi:clock-end", "_job_end"], "job_start": ["progress", None, "mdi:clock-start", "_job_start"], } diff --git a/homeassistant/components/rfxtrx/__init__.py b/homeassistant/components/rfxtrx/__init__.py index ceba82cf544..39cbde08c01 100644 --- a/homeassistant/components/rfxtrx/__init__.py +++ b/homeassistant/components/rfxtrx/__init__.py @@ -18,6 +18,7 @@ from homeassistant.const import ( EVENT_HOMEASSISTANT_STOP, POWER_WATT, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -47,7 +48,7 @@ DATA_TYPES = OrderedDict( [ ("Temperature", TEMP_CELSIUS), ("Temperature2", TEMP_CELSIUS), - ("Humidity", "%"), + ("Humidity", UNIT_PERCENTAGE), ("Barometer", ""), ("Wind direction", ""), ("Rain rate", ""), diff --git a/homeassistant/components/ring/sensor.py b/homeassistant/components/ring/sensor.py index 329077a18e7..84edaf67c22 100644 --- a/homeassistant/components/ring/sensor.py +++ b/homeassistant/components/ring/sensor.py @@ -1,6 +1,7 @@ """This component provides HA sensor support for Ring Door Bell/Chimes.""" import logging +from homeassistant.const import UNIT_PERCENTAGE from homeassistant.core import callback from homeassistant.helpers.entity import Entity from homeassistant.helpers.icon import icon_for_battery_level @@ -203,7 +204,7 @@ SENSOR_TYPES = { "battery": [ "Battery", ["doorbots", "authorized_doorbots", "stickup_cams"], - "%", + UNIT_PERCENTAGE, None, None, "battery", diff --git a/homeassistant/components/sensehat/sensor.py b/homeassistant/components/sensehat/sensor.py index 980c23f8555..29aa4af967e 100644 --- a/homeassistant/components/sensehat/sensor.py +++ b/homeassistant/components/sensehat/sensor.py @@ -7,7 +7,12 @@ from sense_hat import SenseHat import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_DISPLAY_OPTIONS, CONF_NAME, TEMP_CELSIUS +from homeassistant.const import ( + CONF_DISPLAY_OPTIONS, + CONF_NAME, + TEMP_CELSIUS, + UNIT_PERCENTAGE, +) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle @@ -21,7 +26,7 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) SENSOR_TYPES = { "temperature": ["temperature", TEMP_CELSIUS], - "humidity": ["humidity", "%"], + "humidity": ["humidity", UNIT_PERCENTAGE], "pressure": ["pressure", "mb"], } diff --git a/homeassistant/components/sht31/sensor.py b/homeassistant/components/sht31/sensor.py index 8a520377896..3a66b47688c 100644 --- a/homeassistant/components/sht31/sensor.py +++ b/homeassistant/components/sht31/sensor.py @@ -13,6 +13,7 @@ from homeassistant.const import ( CONF_NAME, PRECISION_TENTHS, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -140,7 +141,7 @@ class SHTSensorHumidity(SHTSensor): @property def unit_of_measurement(self): """Return the unit of measurement.""" - return "%" + return UNIT_PERCENTAGE def update(self): """Fetch humidity from the sensor.""" diff --git a/homeassistant/components/skybeacon/sensor.py b/homeassistant/components/skybeacon/sensor.py index cbf394edf47..9bd02aec7c4 100644 --- a/homeassistant/components/skybeacon/sensor.py +++ b/homeassistant/components/skybeacon/sensor.py @@ -15,6 +15,7 @@ from homeassistant.const import ( EVENT_HOMEASSISTANT_STOP, STATE_UNKNOWN, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -82,7 +83,7 @@ class SkybeaconHumid(Entity): @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" - return "%" + return UNIT_PERCENTAGE @property def device_state_attributes(self): diff --git a/homeassistant/components/smappee/sensor.py b/homeassistant/components/smappee/sensor.py index 4ff0bb5b853..8f1e034dcac 100644 --- a/homeassistant/components/smappee/sensor.py +++ b/homeassistant/components/smappee/sensor.py @@ -2,7 +2,12 @@ from datetime import timedelta import logging -from homeassistant.const import ENERGY_KILO_WATT_HOUR, POWER_WATT, VOLUME_CUBIC_METERS +from homeassistant.const import ( + ENERGY_KILO_WATT_HOUR, + POWER_WATT, + UNIT_PERCENTAGE, + VOLUME_CUBIC_METERS, +) from homeassistant.helpers.entity import Entity from . import DATA_SMAPPEE @@ -21,7 +26,13 @@ SENSOR_TYPES = { ], "current": ["Current", "mdi:gauge", "local", "A", "current"], "voltage": ["Voltage", "mdi:gauge", "local", "V", "voltage"], - "active_cosfi": ["Power Factor", "mdi:gauge", "local", "%", "active_cosfi"], + "active_cosfi": [ + "Power Factor", + "mdi:gauge", + "local", + UNIT_PERCENTAGE, + "active_cosfi", + ], "alwayson_today": [ "Always On Today", "mdi:gauge", @@ -68,14 +79,14 @@ SENSOR_TYPES = { "Water Sensor Humidity", "mdi:water-percent", "water", - "%", + UNIT_PERCENTAGE, "humidity", ], "water_sensor_battery": [ "Water Sensor Battery", "mdi:battery", "water", - "%", + UNIT_PERCENTAGE, "battery", ], } diff --git a/homeassistant/components/smartthings/sensor.py b/homeassistant/components/smartthings/sensor.py index fb04c01c682..630fbaadd3a 100644 --- a/homeassistant/components/smartthings/sensor.py +++ b/homeassistant/components/smartthings/sensor.py @@ -16,6 +16,7 @@ from homeassistant.const import ( POWER_WATT, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) from . import SmartThingsEntity @@ -34,8 +35,10 @@ CAPABILITY_TO_SENSORS = { Map(Attribute.air_quality, "Air Quality", "CAQI", None) ], Capability.alarm: [Map(Attribute.alarm, "Alarm", None, None)], - Capability.audio_volume: [Map(Attribute.volume, "Volume", "%", None)], - Capability.battery: [Map(Attribute.battery, "Battery", "%", DEVICE_CLASS_BATTERY)], + Capability.audio_volume: [Map(Attribute.volume, "Volume", UNIT_PERCENTAGE, None)], + Capability.battery: [ + Map(Attribute.battery, "Battery", UNIT_PERCENTAGE, DEVICE_CLASS_BATTERY) + ], Capability.body_mass_index_measurement: [ Map(Attribute.bmi_measurement, "Body Mass Index", "kg/m^2", None) ], @@ -109,7 +112,7 @@ CAPABILITY_TO_SENSORS = { Map(Attribute.illuminance, "Illuminance", "lux", DEVICE_CLASS_ILLUMINANCE) ], Capability.infrared_level: [ - Map(Attribute.infrared_level, "Infrared Level", "%", None) + Map(Attribute.infrared_level, "Infrared Level", UNIT_PERCENTAGE, None) ], Capability.media_input_source: [ Map(Attribute.input_source, "Media Input Source", None, None) @@ -147,7 +150,7 @@ CAPABILITY_TO_SENSORS = { Map( Attribute.humidity, "Relative Humidity Measurement", - "%", + UNIT_PERCENTAGE, DEVICE_CLASS_HUMIDITY, ) ], diff --git a/homeassistant/components/solarlog/const.py b/homeassistant/components/solarlog/const.py index 933f8014090..26176e97e46 100644 --- a/homeassistant/components/solarlog/const.py +++ b/homeassistant/components/solarlog/const.py @@ -1,7 +1,7 @@ """Constants for the Solar-Log integration.""" from datetime import timedelta -from homeassistant.const import ENERGY_KILO_WATT_HOUR, POWER_WATT +from homeassistant.const import ENERGY_KILO_WATT_HOUR, POWER_WATT, UNIT_PERCENTAGE DOMAIN = "solarlog" @@ -77,7 +77,7 @@ SENSOR_TYPES = { POWER_WATT, "mdi:solar-power", ], - "capacity": ["CAPACITY", "capacity", "%", "mdi:solar-power"], + "capacity": ["CAPACITY", "capacity", UNIT_PERCENTAGE, "mdi:solar-power"], "efficiency": ["EFFICIENCY", "efficiency", "% W/Wp", "mdi:solar-power"], "power_available": [ "powerAVAILABLE", diff --git a/homeassistant/components/starline/sensor.py b/homeassistant/components/starline/sensor.py index 0c6cd8de683..8e17caad86c 100644 --- a/homeassistant/components/starline/sensor.py +++ b/homeassistant/components/starline/sensor.py @@ -1,6 +1,6 @@ """Reads vehicle status from StarLine API.""" from homeassistant.components.sensor import DEVICE_CLASS_TEMPERATURE -from homeassistant.const import TEMP_CELSIUS +from homeassistant.const import TEMP_CELSIUS, UNIT_PERCENTAGE from homeassistant.helpers.entity import Entity from homeassistant.helpers.icon import icon_for_battery_level, icon_for_signal_level @@ -13,7 +13,7 @@ SENSOR_TYPES = { "balance": ["Balance", None, None, "mdi:cash-multiple"], "ctemp": ["Interior Temperature", DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, None], "etemp": ["Engine Temperature", DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, None], - "gsm_lvl": ["GSM Signal", None, "%", None], + "gsm_lvl": ["GSM Signal", None, UNIT_PERCENTAGE, None], } diff --git a/homeassistant/components/startca/sensor.py b/homeassistant/components/startca/sensor.py index 82106c2da57..b6d90b99302 100644 --- a/homeassistant/components/startca/sensor.py +++ b/homeassistant/components/startca/sensor.py @@ -13,6 +13,7 @@ from homeassistant.const import ( CONF_MONITORED_VARIABLES, CONF_NAME, DATA_GIGABYTES, + UNIT_PERCENTAGE, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -24,13 +25,11 @@ _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Start.ca" CONF_TOTAL_BANDWIDTH = "total_bandwidth" -PERCENT = "%" - MIN_TIME_BETWEEN_UPDATES = timedelta(hours=1) REQUEST_TIMEOUT = 5 # seconds SENSOR_TYPES = { - "usage": ["Usage Ratio", PERCENT, "mdi:percent"], + "usage": ["Usage Ratio", UNIT_PERCENTAGE, "mdi:percent"], "usage_gb": ["Usage", DATA_GIGABYTES, "mdi:download"], "limit": ["Data limit", DATA_GIGABYTES, "mdi:download"], "used_download": ["Used Download", DATA_GIGABYTES, "mdi:download"], diff --git a/homeassistant/components/surepetcare/sensor.py b/homeassistant/components/surepetcare/sensor.py index 8dc9cf30e3c..9c1416479cb 100644 --- a/homeassistant/components/surepetcare/sensor.py +++ b/homeassistant/components/surepetcare/sensor.py @@ -4,7 +4,13 @@ from typing import Any, Dict, Optional from surepy import SureLockStateID, SureProductID -from homeassistant.const import ATTR_VOLTAGE, CONF_ID, CONF_TYPE, DEVICE_CLASS_BATTERY +from homeassistant.const import ( + ATTR_VOLTAGE, + CONF_ID, + CONF_TYPE, + DEVICE_CLASS_BATTERY, + UNIT_PERCENTAGE, +) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity @@ -40,10 +46,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= ]: entities.append(SureBattery(entity[CONF_ID], sure_type, spc)) - if sure_type in [ - SureProductID.CAT_FLAP, - SureProductID.PET_FLAP, - ]: + if sure_type in [SureProductID.CAT_FLAP, SureProductID.PET_FLAP]: entities.append(Flap(entity[CONF_ID], sure_type, spc)) async_add_entities(entities, True) @@ -52,9 +55,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= class SurePetcareSensor(Entity): """A binary sensor implementation for Sure Petcare Entities.""" - def __init__( - self, _id: int, sure_type: SureProductID, spc: SurePetcareAPI, - ): + def __init__(self, _id: int, sure_type: SureProductID, spc: SurePetcareAPI): """Initialize a Sure Petcare sensor.""" self._id = _id @@ -128,9 +129,7 @@ class Flap(SurePetcareSensor): """Return the state attributes of the device.""" attributes = None if self._state: - attributes = { - "learn_mode": bool(self._state["learn_mode"]), - } + attributes = {"learn_mode": bool(self._state["learn_mode"])} return attributes @@ -182,4 +181,4 @@ class SureBattery(SurePetcareSensor): @property def unit_of_measurement(self) -> str: """Return the unit of measurement.""" - return "%" + return UNIT_PERCENTAGE diff --git a/homeassistant/components/syncthru/sensor.py b/homeassistant/components/syncthru/sensor.py index e981154a81a..7cd99bdb261 100644 --- a/homeassistant/components/syncthru/sensor.py +++ b/homeassistant/components/syncthru/sensor.py @@ -6,7 +6,7 @@ from pysyncthru import SyncThru import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_HOST, CONF_NAME, CONF_RESOURCE +from homeassistant.const import CONF_HOST, CONF_NAME, CONF_RESOURCE, UNIT_PERCENTAGE from homeassistant.helpers import aiohttp_client import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -174,7 +174,7 @@ class SyncThruTonerSensor(SyncThruSensor): super().__init__(syncthru, name) self._name = f"{name} Toner {color}" self._color = color - self._unit_of_measurement = "%" + self._unit_of_measurement = UNIT_PERCENTAGE self._id_suffix = f"_toner_{color}" def update(self): @@ -194,7 +194,7 @@ class SyncThruDrumSensor(SyncThruSensor): super().__init__(syncthru, name) self._name = f"{name} Drum {color}" self._color = color - self._unit_of_measurement = "%" + self._unit_of_measurement = UNIT_PERCENTAGE self._id_suffix = f"_drum_{color}" def update(self): diff --git a/homeassistant/components/synologydsm/sensor.py b/homeassistant/components/synologydsm/sensor.py index d10ecaa15ed..84921b3b8d3 100644 --- a/homeassistant/components/synologydsm/sensor.py +++ b/homeassistant/components/synologydsm/sensor.py @@ -21,6 +21,7 @@ from homeassistant.const import ( DATA_RATE_KILOBYTES_PER_SECOND, EVENT_HOMEASSISTANT_START, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -37,14 +38,14 @@ DEFAULT_PORT = 5001 MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15) _UTILISATION_MON_COND = { - "cpu_other_load": ["CPU Load (Other)", "%", "mdi:chip"], - "cpu_user_load": ["CPU Load (User)", "%", "mdi:chip"], - "cpu_system_load": ["CPU Load (System)", "%", "mdi:chip"], - "cpu_total_load": ["CPU Load (Total)", "%", "mdi:chip"], - "cpu_1min_load": ["CPU Load (1 min)", "%", "mdi:chip"], - "cpu_5min_load": ["CPU Load (5 min)", "%", "mdi:chip"], - "cpu_15min_load": ["CPU Load (15 min)", "%", "mdi:chip"], - "memory_real_usage": ["Memory Usage (Real)", "%", "mdi:memory"], + "cpu_other_load": ["CPU Load (Other)", UNIT_PERCENTAGE, "mdi:chip"], + "cpu_user_load": ["CPU Load (User)", UNIT_PERCENTAGE, "mdi:chip"], + "cpu_system_load": ["CPU Load (System)", UNIT_PERCENTAGE, "mdi:chip"], + "cpu_total_load": ["CPU Load (Total)", UNIT_PERCENTAGE, "mdi:chip"], + "cpu_1min_load": ["CPU Load (1 min)", UNIT_PERCENTAGE, "mdi:chip"], + "cpu_5min_load": ["CPU Load (5 min)", UNIT_PERCENTAGE, "mdi:chip"], + "cpu_15min_load": ["CPU Load (15 min)", UNIT_PERCENTAGE, "mdi:chip"], + "memory_real_usage": ["Memory Usage (Real)", UNIT_PERCENTAGE, "mdi:memory"], "memory_size": ["Memory Size", DATA_MEGABYTES, "mdi:memory"], "memory_cached": ["Memory Cached", DATA_MEGABYTES, "mdi:memory"], "memory_available_swap": ["Memory Available (Swap)", DATA_MEGABYTES, "mdi:memory"], @@ -59,7 +60,7 @@ _STORAGE_VOL_MON_COND = { "volume_device_type": ["Type", None, "mdi:harddisk"], "volume_size_total": ["Total Size", None, "mdi:chart-pie"], "volume_size_used": ["Used Space", None, "mdi:chart-pie"], - "volume_percentage_used": ["Volume Used", "%", "mdi:chart-pie"], + "volume_percentage_used": ["Volume Used", UNIT_PERCENTAGE, "mdi:chart-pie"], "volume_disk_temp_avg": ["Average Disk Temp", None, "mdi:thermometer"], "volume_disk_temp_max": ["Maximum Disk Temp", None, "mdi:thermometer"], } diff --git a/homeassistant/components/systemmonitor/sensor.py b/homeassistant/components/systemmonitor/sensor.py index 1ea8a409052..bae42c2f50b 100644 --- a/homeassistant/components/systemmonitor/sensor.py +++ b/homeassistant/components/systemmonitor/sensor.py @@ -15,6 +15,7 @@ from homeassistant.const import ( DATA_RATE_MEGABYTES_PER_SECOND, STATE_OFF, STATE_ON, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -29,7 +30,7 @@ CONF_ARG = "arg" SENSOR_TYPES = { "disk_free": ["Disk free", DATA_GIBIBYTES, "mdi:harddisk", None], "disk_use": ["Disk use", DATA_GIBIBYTES, "mdi:harddisk", None], - "disk_use_percent": ["Disk use (percent)", "%", "mdi:harddisk", None], + "disk_use_percent": ["Disk use (percent)", UNIT_PERCENTAGE, "mdi:harddisk", None], "ipv4_address": ["IPv4 address", "", "mdi:server-network", None], "ipv6_address": ["IPv6 address", "", "mdi:server-network", None], "last_boot": ["Last boot", "", "mdi:clock", "timestamp"], @@ -38,7 +39,7 @@ SENSOR_TYPES = { "load_5m": ["Load (5m)", " ", "mdi:memory", None], "memory_free": ["Memory free", DATA_MEBIBYTES, "mdi:memory", None], "memory_use": ["Memory use", DATA_MEBIBYTES, "mdi:memory", None], - "memory_use_percent": ["Memory use (percent)", "%", "mdi:memory", None], + "memory_use_percent": ["Memory use (percent)", UNIT_PERCENTAGE, "mdi:memory", None], "network_in": ["Network in", DATA_MEBIBYTES, "mdi:server-network", None], "network_out": ["Network out", DATA_MEBIBYTES, "mdi:server-network", None], "packets_in": ["Packets in", " ", "mdi:server-network", None], @@ -56,10 +57,10 @@ SENSOR_TYPES = { None, ], "process": ["Process", " ", "mdi:memory", None], - "processor_use": ["Processor use", "%", "mdi:memory", None], + "processor_use": ["Processor use", UNIT_PERCENTAGE, "mdi:memory", None], "swap_free": ["Swap free", DATA_MEBIBYTES, "mdi:harddisk", None], "swap_use": ["Swap use", DATA_MEBIBYTES, "mdi:harddisk", None], - "swap_use_percent": ["Swap use (percent)", "%", "mdi:harddisk", None], + "swap_use_percent": ["Swap use (percent)", UNIT_PERCENTAGE, "mdi:harddisk", None], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( diff --git a/homeassistant/components/tado/sensor.py b/homeassistant/components/tado/sensor.py index f5f32a6ed1a..2cd40bee3fa 100644 --- a/homeassistant/components/tado/sensor.py +++ b/homeassistant/components/tado/sensor.py @@ -1,7 +1,7 @@ """Support for Tado sensors for each zone.""" import logging -from homeassistant.const import TEMP_CELSIUS +from homeassistant.const import TEMP_CELSIUS, UNIT_PERCENTAGE from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity @@ -134,9 +134,9 @@ class TadoSensor(Entity): if self.zone_variable == "temperature": return self.hass.config.units.temperature_unit if self.zone_variable == "humidity": - return "%" + return UNIT_PERCENTAGE if self.zone_variable == "heating": - return "%" + return UNIT_PERCENTAGE if self.zone_variable == "ac": return "" diff --git a/homeassistant/components/tahoma/sensor.py b/homeassistant/components/tahoma/sensor.py index fb8c61607c7..20364a243b3 100644 --- a/homeassistant/components/tahoma/sensor.py +++ b/homeassistant/components/tahoma/sensor.py @@ -2,7 +2,7 @@ from datetime import timedelta import logging -from homeassistant.const import ATTR_BATTERY_LEVEL, TEMP_CELSIUS +from homeassistant.const import ATTR_BATTERY_LEVEL, TEMP_CELSIUS, UNIT_PERCENTAGE from homeassistant.helpers.entity import Entity from . import DOMAIN as TAHOMA_DOMAIN, TahomaDevice @@ -51,7 +51,7 @@ class TahomaSensor(TahomaDevice, Entity): if self.tahoma_device.type == "io:LightIOSystemSensor": return "lx" if self.tahoma_device.type == "Humidity Sensor": - return "%" + return UNIT_PERCENTAGE if self.tahoma_device.type == "rtds:RTDSContactSensor": return None if self.tahoma_device.type == "rtds:RTDSMotionSensor": diff --git a/homeassistant/components/tank_utility/sensor.py b/homeassistant/components/tank_utility/sensor.py index 61a3d7367bf..5847eecc8a8 100644 --- a/homeassistant/components/tank_utility/sensor.py +++ b/homeassistant/components/tank_utility/sensor.py @@ -8,7 +8,7 @@ from tank_utility import auth, device as tank_monitor import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_DEVICES, CONF_EMAIL, CONF_PASSWORD +from homeassistant.const import CONF_DEVICES, CONF_EMAIL, CONF_PASSWORD, UNIT_PERCENTAGE import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -26,7 +26,6 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( SENSOR_TYPE = "tank" SENSOR_ROUNDING_PRECISION = 1 -SENSOR_UNIT_OF_MEASUREMENT = "%" SENSOR_ATTRS = [ "name", "address", @@ -74,7 +73,7 @@ class TankUtilitySensor(Entity): self._device = device self._state = None self._name = f"Tank Utility {self.device}" - self._unit_of_measurement = SENSOR_UNIT_OF_MEASUREMENT + self._unit_of_measurement = UNIT_PERCENTAGE self._attributes = {} @property diff --git a/homeassistant/components/teksavvy/sensor.py b/homeassistant/components/teksavvy/sensor.py index f340f4a3971..0d2d290fed9 100644 --- a/homeassistant/components/teksavvy/sensor.py +++ b/homeassistant/components/teksavvy/sensor.py @@ -11,6 +11,7 @@ from homeassistant.const import ( CONF_MONITORED_VARIABLES, CONF_NAME, DATA_GIGABYTES, + UNIT_PERCENTAGE, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -22,13 +23,11 @@ _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "TekSavvy" CONF_TOTAL_BANDWIDTH = "total_bandwidth" -PERCENT = "%" - MIN_TIME_BETWEEN_UPDATES = timedelta(hours=1) REQUEST_TIMEOUT = 5 # seconds SENSOR_TYPES = { - "usage": ["Usage Ratio", PERCENT, "mdi:percent"], + "usage": ["Usage Ratio", UNIT_PERCENTAGE, "mdi:percent"], "usage_gb": ["Usage", DATA_GIGABYTES, "mdi:download"], "limit": ["Data limit", DATA_GIGABYTES, "mdi:download"], "onpeak_download": ["On Peak Download", DATA_GIGABYTES, "mdi:download"], diff --git a/homeassistant/components/tellduslive/sensor.py b/homeassistant/components/tellduslive/sensor.py index 7aafa38c94f..11411e1d6ea 100644 --- a/homeassistant/components/tellduslive/sensor.py +++ b/homeassistant/components/tellduslive/sensor.py @@ -10,6 +10,7 @@ from homeassistant.const import ( SPEED_METERS_PER_SECOND, TEMP_CELSIUS, TIME_HOURS, + UNIT_PERCENTAGE, ) from homeassistant.helpers.dispatcher import async_dispatcher_connect @@ -37,7 +38,7 @@ SENSOR_TYPES = { None, DEVICE_CLASS_TEMPERATURE, ], - SENSOR_TYPE_HUMIDITY: ["Humidity", "%", None, DEVICE_CLASS_HUMIDITY], + SENSOR_TYPE_HUMIDITY: ["Humidity", UNIT_PERCENTAGE, None, DEVICE_CLASS_HUMIDITY], SENSOR_TYPE_RAINRATE: ["Rain rate", f"mm/{TIME_HOURS}", "mdi:water", None], SENSOR_TYPE_RAINTOTAL: ["Rain total", "mm", "mdi:water", None], SENSOR_TYPE_WINDDIRECTION: ["Wind direction", "", "", None], diff --git a/homeassistant/components/tellstick/sensor.py b/homeassistant/components/tellstick/sensor.py index 1a55e67ac43..4a3ff75b864 100644 --- a/homeassistant/components/tellstick/sensor.py +++ b/homeassistant/components/tellstick/sensor.py @@ -7,7 +7,13 @@ import tellcore.constants as tellcore_constants import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_ID, CONF_NAME, CONF_PROTOCOL, TEMP_CELSIUS +from homeassistant.const import ( + CONF_ID, + CONF_NAME, + CONF_PROTOCOL, + TEMP_CELSIUS, + UNIT_PERCENTAGE, +) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -55,7 +61,9 @@ def setup_platform(hass, config, add_entities, discovery_info=None): tellcore_constants.TELLSTICK_TEMPERATURE: DatatypeDescription( "temperature", config.get(CONF_TEMPERATURE_SCALE) ), - tellcore_constants.TELLSTICK_HUMIDITY: DatatypeDescription("humidity", "%"), + tellcore_constants.TELLSTICK_HUMIDITY: DatatypeDescription( + "humidity", UNIT_PERCENTAGE + ), tellcore_constants.TELLSTICK_RAINRATE: DatatypeDescription("rain rate", ""), tellcore_constants.TELLSTICK_RAINTOTAL: DatatypeDescription("rain total", ""), tellcore_constants.TELLSTICK_WINDDIRECTION: DatatypeDescription( diff --git a/homeassistant/components/thinkingcleaner/sensor.py b/homeassistant/components/thinkingcleaner/sensor.py index 7a45be7eb61..26175b5368a 100644 --- a/homeassistant/components/thinkingcleaner/sensor.py +++ b/homeassistant/components/thinkingcleaner/sensor.py @@ -5,6 +5,7 @@ import logging from pythinkingcleaner import Discovery from homeassistant import util +from homeassistant.const import UNIT_PERCENTAGE from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) @@ -13,7 +14,7 @@ MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(milliseconds=100) SENSOR_TYPES = { - "battery": ["Battery", "%", "mdi:battery"], + "battery": ["Battery", UNIT_PERCENTAGE, "mdi:battery"], "state": ["State", None, None], "capacity": ["Capacity", None, None], } diff --git a/homeassistant/components/toon/const.py b/homeassistant/components/toon/const.py index a22835ec215..239359c1fdf 100644 --- a/homeassistant/components/toon/const.py +++ b/homeassistant/components/toon/const.py @@ -18,6 +18,5 @@ DEFAULT_MAX_TEMP = 30.0 DEFAULT_MIN_TEMP = 6.0 CURRENCY_EUR = "EUR" -RATIO_PERCENT = "%" VOLUME_CM3 = "CM3" VOLUME_M3 = "M3" diff --git a/homeassistant/components/toon/sensor.py b/homeassistant/components/toon/sensor.py index 79a8fa28540..a5e88bb3d2f 100644 --- a/homeassistant/components/toon/sensor.py +++ b/homeassistant/components/toon/sensor.py @@ -2,7 +2,7 @@ import logging from homeassistant.config_entries import ConfigEntry -from homeassistant.const import ENERGY_KILO_WATT_HOUR, POWER_WATT +from homeassistant.const import ENERGY_KILO_WATT_HOUR, POWER_WATT, UNIT_PERCENTAGE from homeassistant.helpers.typing import HomeAssistantType from . import ( @@ -13,7 +13,7 @@ from . import ( ToonGasMeterDeviceEntity, ToonSolarDeviceEntity, ) -from .const import CURRENCY_EUR, DATA_TOON, DOMAIN, RATIO_PERCENT, VOLUME_CM3, VOLUME_M3 +from .const import CURRENCY_EUR, DATA_TOON, DOMAIN, VOLUME_CM3, VOLUME_M3 _LOGGER = logging.getLogger(__name__) @@ -195,7 +195,7 @@ async def async_setup_entry( "current_modulation_level", "Boiler Modulation Level", "mdi:percent", - RATIO_PERCENT, + UNIT_PERCENTAGE, ) ] ) diff --git a/homeassistant/components/tradfri/sensor.py b/homeassistant/components/tradfri/sensor.py index c3a08ab1675..db12ab0a5cb 100644 --- a/homeassistant/components/tradfri/sensor.py +++ b/homeassistant/components/tradfri/sensor.py @@ -1,6 +1,6 @@ """Support for IKEA Tradfri sensors.""" -from homeassistant.const import DEVICE_CLASS_BATTERY +from homeassistant.const import DEVICE_CLASS_BATTERY, UNIT_PERCENTAGE from .base_class import TradfriBaseDevice from .const import CONF_GATEWAY_ID, KEY_API, KEY_GATEWAY @@ -47,4 +47,4 @@ class TradfriSensor(TradfriBaseDevice): @property def unit_of_measurement(self): """Return the unit_of_measurement of the device.""" - return "%" + return UNIT_PERCENTAGE diff --git a/homeassistant/components/trafikverket_weatherstation/sensor.py b/homeassistant/components/trafikverket_weatherstation/sensor.py index 78f5bbbb8ca..f2e7387aa6b 100644 --- a/homeassistant/components/trafikverket_weatherstation/sensor.py +++ b/homeassistant/components/trafikverket_weatherstation/sensor.py @@ -18,6 +18,7 @@ from homeassistant.const import ( DEVICE_CLASS_TEMPERATURE, SPEED_METERS_PER_SECOND, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -81,7 +82,7 @@ SENSOR_TYPES = { ], "humidity": [ "Humidity", - "%", + UNIT_PERCENTAGE, "humidity", "mdi:water-percent", DEVICE_CLASS_HUMIDITY, diff --git a/homeassistant/components/vallox/sensor.py b/homeassistant/components/vallox/sensor.py index f7be502cecb..5bf9b8061ad 100644 --- a/homeassistant/components/vallox/sensor.py +++ b/homeassistant/components/vallox/sensor.py @@ -8,6 +8,7 @@ from homeassistant.const import ( DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_TIMESTAMP, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect @@ -39,7 +40,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= state_proxy=state_proxy, metric_key="A_CYC_FAN_SPEED", device_class=None, - unit_of_measurement="%", + unit_of_measurement=UNIT_PERCENTAGE, icon="mdi:fan", ), ValloxSensor( @@ -79,7 +80,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= state_proxy=state_proxy, metric_key="A_CYC_RH_VALUE", device_class=DEVICE_CLASS_HUMIDITY, - unit_of_measurement="%", + unit_of_measurement=UNIT_PERCENTAGE, icon=None, ), ValloxFilterRemainingSensor( diff --git a/homeassistant/components/vera/sensor.py b/homeassistant/components/vera/sensor.py index e409a123887..9ac0a36ff9c 100644 --- a/homeassistant/components/vera/sensor.py +++ b/homeassistant/components/vera/sensor.py @@ -5,7 +5,7 @@ import logging import pyvera as veraApi from homeassistant.components.sensor import ENTITY_ID_FORMAT -from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT +from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT, UNIT_PERCENTAGE from homeassistant.helpers.entity import Entity from homeassistant.util import convert @@ -54,7 +54,7 @@ class VeraSensor(VeraDevice, Entity): if self.vera_device.category == veraApi.CATEGORY_UV_SENSOR: return "level" if self.vera_device.category == veraApi.CATEGORY_HUMIDITY_SENSOR: - return "%" + return UNIT_PERCENTAGE if self.vera_device.category == veraApi.CATEGORY_POWER_METER: return "watts" diff --git a/homeassistant/components/verisure/sensor.py b/homeassistant/components/verisure/sensor.py index 5735cea335e..384042b7210 100644 --- a/homeassistant/components/verisure/sensor.py +++ b/homeassistant/components/verisure/sensor.py @@ -1,7 +1,7 @@ """Support for Verisure sensors.""" import logging -from homeassistant.const import TEMP_CELSIUS +from homeassistant.const import TEMP_CELSIUS, UNIT_PERCENTAGE from homeassistant.helpers.entity import Entity from . import CONF_HYDROMETERS, CONF_MOUSE, CONF_THERMOMETERS, HUB as hub @@ -130,7 +130,7 @@ class VerisureHygrometer(Entity): @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" - return "%" + return UNIT_PERCENTAGE # pylint: disable=no-self-use def update(self): diff --git a/homeassistant/components/vilfo/const.py b/homeassistant/components/vilfo/const.py index 1a40b8430d7..0c6414ce99a 100644 --- a/homeassistant/components/vilfo/const.py +++ b/homeassistant/components/vilfo/const.py @@ -1,5 +1,5 @@ """Constants for the Vilfo Router integration.""" -from homeassistant.const import DEVICE_CLASS_TIMESTAMP +from homeassistant.const import DEVICE_CLASS_TIMESTAMP, UNIT_PERCENTAGE DOMAIN = "vilfo" @@ -18,12 +18,10 @@ ROUTER_DEFAULT_MODEL = "Vilfo Router" ROUTER_DEFAULT_NAME = "Vilfo Router" ROUTER_MANUFACTURER = "Vilfo AB" -UNIT_PERCENT = "%" - SENSOR_TYPES = { ATTR_LOAD: { ATTR_LABEL: "Load", - ATTR_UNIT: UNIT_PERCENT, + ATTR_UNIT: UNIT_PERCENTAGE, ATTR_ICON: "mdi:memory", ATTR_API_DATA_FIELD: ATTR_API_DATA_FIELD_LOAD, }, diff --git a/homeassistant/components/waterfurnace/sensor.py b/homeassistant/components/waterfurnace/sensor.py index bf6817c2dfe..e2c92d07f9c 100644 --- a/homeassistant/components/waterfurnace/sensor.py +++ b/homeassistant/components/waterfurnace/sensor.py @@ -1,7 +1,7 @@ """Support for Waterfurnace.""" from homeassistant.components.sensor import ENTITY_ID_FORMAT -from homeassistant.const import TEMP_FAHRENHEIT +from homeassistant.const import TEMP_FAHRENHEIT, UNIT_PERCENTAGE from homeassistant.core import callback from homeassistant.helpers.entity import Entity from homeassistant.util import slugify @@ -34,9 +34,11 @@ SENSORS = [ "Loop Temp", "enteringwatertemp", "mdi:thermometer", TEMP_FAHRENHEIT ), WFSensorConfig( - "Humidity Set Point", "tstathumidsetpoint", "mdi:water-percent", "%" + "Humidity Set Point", "tstathumidsetpoint", "mdi:water-percent", UNIT_PERCENTAGE + ), + WFSensorConfig( + "Humidity", "tstatrelativehumidity", "mdi:water-percent", UNIT_PERCENTAGE ), - WFSensorConfig("Humidity", "tstatrelativehumidity", "mdi:water-percent", "%"), WFSensorConfig("Compressor Power", "compressorpower", "mdi:flash", "W"), WFSensorConfig("Fan Power", "fanpower", "mdi:flash", "W"), WFSensorConfig("Aux Power", "auxpower", "mdi:flash", "W"), diff --git a/homeassistant/components/wirelesstag/__init__.py b/homeassistant/components/wirelesstag/__init__.py index c0a30a8867f..396ca093eec 100644 --- a/homeassistant/components/wirelesstag/__init__.py +++ b/homeassistant/components/wirelesstag/__init__.py @@ -11,6 +11,7 @@ from homeassistant.const import ( ATTR_VOLTAGE, CONF_PASSWORD, CONF_USERNAME, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import dispatcher_send @@ -284,5 +285,5 @@ class WirelessTagBaseSensor(Entity): ATTR_VOLTAGE: f"{self._tag.battery_volts:.2f}V", ATTR_TAG_SIGNAL_STRENGTH: f"{self._tag.signal_strength}dBm", ATTR_TAG_OUT_OF_RANGE: not self._tag.is_in_range, - ATTR_TAG_POWER_CONSUMPTION: f"{self._tag.power_consumption:.2f}%", + ATTR_TAG_POWER_CONSUMPTION: f"{self._tag.power_consumption:.2f}{UNIT_PERCENTAGE}", } diff --git a/homeassistant/components/withings/const.py b/homeassistant/components/withings/const.py index ea3814d3b3a..781420b347a 100644 --- a/homeassistant/components/withings/const.py +++ b/homeassistant/components/withings/const.py @@ -62,6 +62,5 @@ UOM_BEATS_PER_MINUTE = "bpm" UOM_BREATHS_PER_MINUTE = f"br/{const.TIME_MINUTES}" UOM_FREQUENCY = "times" UOM_MMHG = "mmhg" -UOM_PERCENT = "%" UOM_LENGTH_M = const.LENGTH_METERS UOM_TEMP_C = const.TEMP_CELSIUS diff --git a/homeassistant/components/withings/sensor.py b/homeassistant/components/withings/sensor.py index 0fee2271067..7e58beb4419 100644 --- a/homeassistant/components/withings/sensor.py +++ b/homeassistant/components/withings/sensor.py @@ -13,7 +13,12 @@ from withings_api.common import ( ) from homeassistant.config_entries import ConfigEntry -from homeassistant.const import MASS_KILOGRAMS, SPEED_METERS_PER_SECOND, TIME_SECONDS +from homeassistant.const import ( + MASS_KILOGRAMS, + SPEED_METERS_PER_SECOND, + TIME_SECONDS, + UNIT_PERCENTAGE, +) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers.entity import Entity @@ -150,7 +155,7 @@ WITHINGS_ATTRIBUTES = [ const.MEAS_FAT_RATIO_PCT, MeasureType.FAT_RATIO, "Fat Ratio", - const.UOM_PERCENT, + UNIT_PERCENTAGE, None, ), WithingsMeasureAttribute( @@ -175,13 +180,13 @@ WITHINGS_ATTRIBUTES = [ "mdi:heart-pulse", ), WithingsMeasureAttribute( - const.MEAS_SPO2_PCT, MeasureType.SP02, "SP02", const.UOM_PERCENT, None + const.MEAS_SPO2_PCT, MeasureType.SP02, "SP02", UNIT_PERCENTAGE, None ), WithingsMeasureAttribute( const.MEAS_HYDRATION, MeasureType.HYDRATION, "Hydration", - const.UOM_PERCENT, + UNIT_PERCENTAGE, "mdi:water", ), WithingsMeasureAttribute( diff --git a/homeassistant/components/worxlandroid/sensor.py b/homeassistant/components/worxlandroid/sensor.py index fa2cae53f52..8d651800a77 100644 --- a/homeassistant/components/worxlandroid/sensor.py +++ b/homeassistant/components/worxlandroid/sensor.py @@ -7,7 +7,7 @@ import async_timeout import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_HOST, CONF_PIN, CONF_TIMEOUT +from homeassistant.const import CONF_HOST, CONF_PIN, CONF_TIMEOUT, UNIT_PERCENTAGE from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -77,7 +77,7 @@ class WorxLandroidSensor(Entity): def unit_of_measurement(self): """Return the unit of measurement of the sensor.""" if self.sensor == "battery": - return "%" + return UNIT_PERCENTAGE return None async def async_update(self): diff --git a/homeassistant/components/wunderground/sensor.py b/homeassistant/components/wunderground/sensor.py index 6a1112c028b..de1e48c9c14 100644 --- a/homeassistant/components/wunderground/sensor.py +++ b/homeassistant/components/wunderground/sensor.py @@ -26,6 +26,7 @@ from homeassistant.const import ( SPEED_MILES_PER_HOUR, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -416,7 +417,7 @@ SENSOR_TYPES = { "Relative Humidity", "conditions", value=lambda wu: int(wu.data["current_observation"]["relative_humidity"][:-1]), - unit_of_measurement="%", + unit_of_measurement=UNIT_PERCENTAGE, icon="mdi:water-percent", device_class="humidity", ), @@ -916,16 +917,36 @@ SENSOR_TYPES = { "mdi:umbrella", ), "precip_1d": WUDailySimpleForecastSensorConfig( - "Precipitation Probability Today", 0, "pop", None, "%", "mdi:umbrella" + "Precipitation Probability Today", + 0, + "pop", + None, + UNIT_PERCENTAGE, + "mdi:umbrella", ), "precip_2d": WUDailySimpleForecastSensorConfig( - "Precipitation Probability Tomorrow", 1, "pop", None, "%", "mdi:umbrella" + "Precipitation Probability Tomorrow", + 1, + "pop", + None, + UNIT_PERCENTAGE, + "mdi:umbrella", ), "precip_3d": WUDailySimpleForecastSensorConfig( - "Precipitation Probability in 3 Days", 2, "pop", None, "%", "mdi:umbrella" + "Precipitation Probability in 3 Days", + 2, + "pop", + None, + UNIT_PERCENTAGE, + "mdi:umbrella", ), "precip_4d": WUDailySimpleForecastSensorConfig( - "Precipitation Probability in 4 Days", 3, "pop", None, "%", "mdi:umbrella" + "Precipitation Probability in 4 Days", + 3, + "pop", + None, + UNIT_PERCENTAGE, + "mdi:umbrella", ), } diff --git a/homeassistant/components/xiaomi_aqara/sensor.py b/homeassistant/components/xiaomi_aqara/sensor.py index 5ad29af0aaf..d793f920349 100644 --- a/homeassistant/components/xiaomi_aqara/sensor.py +++ b/homeassistant/components/xiaomi_aqara/sensor.py @@ -7,6 +7,7 @@ from homeassistant.const import ( DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from . import PY_XIAOMI_GATEWAY, XiaomiDevice @@ -15,7 +16,7 @@ _LOGGER = logging.getLogger(__name__) SENSOR_TYPES = { "temperature": [TEMP_CELSIUS, None, DEVICE_CLASS_TEMPERATURE], - "humidity": ["%", None, DEVICE_CLASS_HUMIDITY], + "humidity": [UNIT_PERCENTAGE, None, DEVICE_CLASS_HUMIDITY], "illumination": ["lm", None, DEVICE_CLASS_ILLUMINANCE], "lux": ["lx", None, DEVICE_CLASS_ILLUMINANCE], "pressure": ["hPa", None, DEVICE_CLASS_PRESSURE], diff --git a/homeassistant/components/yr/sensor.py b/homeassistant/components/yr/sensor.py index 5e7f4ed1db5..c6aaeea7ac9 100644 --- a/homeassistant/components/yr/sensor.py +++ b/homeassistant/components/yr/sensor.py @@ -23,6 +23,7 @@ from homeassistant.const import ( PRESSURE_HPA, SPEED_METERS_PER_SECOND, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -46,12 +47,12 @@ SENSOR_TYPES = { "windGust": ["Wind gust", SPEED_METERS_PER_SECOND, None], "pressure": ["Pressure", PRESSURE_HPA, DEVICE_CLASS_PRESSURE], "windDirection": ["Wind direction", "°", None], - "humidity": ["Humidity", "%", DEVICE_CLASS_HUMIDITY], - "fog": ["Fog", "%", None], - "cloudiness": ["Cloudiness", "%", None], - "lowClouds": ["Low clouds", "%", None], - "mediumClouds": ["Medium clouds", "%", None], - "highClouds": ["High clouds", "%", None], + "humidity": ["Humidity", UNIT_PERCENTAGE, DEVICE_CLASS_HUMIDITY], + "fog": ["Fog", UNIT_PERCENTAGE, None], + "cloudiness": ["Cloudiness", UNIT_PERCENTAGE, None], + "lowClouds": ["Low clouds", UNIT_PERCENTAGE, None], + "mediumClouds": ["Medium clouds", UNIT_PERCENTAGE, None], + "highClouds": ["High clouds", UNIT_PERCENTAGE, None], "dewpointTemperature": [ "Dewpoint temperature", TEMP_CELSIUS, diff --git a/homeassistant/components/yweather/sensor.py b/homeassistant/components/yweather/sensor.py index c7f752a8836..db21c430c4d 100644 --- a/homeassistant/components/yweather/sensor.py +++ b/homeassistant/components/yweather/sensor.py @@ -16,6 +16,7 @@ from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_NAME, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -40,7 +41,7 @@ SENSOR_TYPES = { "temp_min": ["Temperature min", "temperature"], "temp_max": ["Temperature max", "temperature"], "wind_speed": ["Wind speed", "speed"], - "humidity": ["Humidity", "%"], + "humidity": ["Humidity", UNIT_PERCENTAGE], "pressure": ["Pressure", "pressure"], "visibility": ["Visibility", "distance"], } diff --git a/homeassistant/components/zamg/sensor.py b/homeassistant/components/zamg/sensor.py index 74335a2ccdd..a5eb90df218 100644 --- a/homeassistant/components/zamg/sensor.py +++ b/homeassistant/components/zamg/sensor.py @@ -18,6 +18,7 @@ from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_NAME, SPEED_KILOMETERS_PER_HOUR, + UNIT_PERCENTAGE, __version__, ) import homeassistant.helpers.config_validation as cv @@ -39,7 +40,7 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=10) SENSOR_TYPES = { "pressure": ("Pressure", "hPa", "LDstat hPa", float), "pressure_sealevel": ("Pressure at Sea Level", "hPa", "LDred hPa", float), - "humidity": ("Humidity", "%", "RF %", int), + "humidity": ("Humidity", UNIT_PERCENTAGE, "RF %", int), "wind_speed": ( "Wind Speed", SPEED_KILOMETERS_PER_HOUR, @@ -54,7 +55,7 @@ SENSOR_TYPES = { float, ), "wind_max_bearing": ("Top Wind Bearing", "°", "WSR °", int), - "sun_last_hour": ("Sun Last Hour", "%", "SO %", int), + "sun_last_hour": ("Sun Last Hour", UNIT_PERCENTAGE, f"SO {UNIT_PERCENTAGE}", int), "temperature": ("Temperature", "°C", "T °C", float), "precipitation": ("Precipitation", "l/m²", "N l/m²", float), "dewpoint": ("Dew Point", "°C", "TP °C", float), diff --git a/homeassistant/components/zha/sensor.py b/homeassistant/components/zha/sensor.py index b98c50d1fa4..e4788acfc53 100644 --- a/homeassistant/components/zha/sensor.py +++ b/homeassistant/components/zha/sensor.py @@ -17,6 +17,7 @@ from homeassistant.const import ( POWER_WATT, STATE_UNKNOWN, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect @@ -161,7 +162,7 @@ class Battery(Sensor): """Battery sensor of power configuration cluster.""" _device_class = DEVICE_CLASS_BATTERY - _unit = "%" + _unit = UNIT_PERCENTAGE @staticmethod def formatter(value): @@ -231,7 +232,7 @@ class Humidity(Sensor): _device_class = DEVICE_CLASS_HUMIDITY _divisor = 100 - _unit = "%" + _unit = UNIT_PERCENTAGE @STRICT_MATCH(channel_names=CHANNEL_ILLUMINANCE) diff --git a/homeassistant/components/zigbee/__init__.py b/homeassistant/components/zigbee/__init__.py index 3a4fa9029bd..48c96b7591f 100644 --- a/homeassistant/components/zigbee/__init__.py +++ b/homeassistant/components/zigbee/__init__.py @@ -15,6 +15,7 @@ from homeassistant.const import ( CONF_NAME, CONF_PIN, EVENT_HOMEASSISTANT_STOP, + UNIT_PERCENTAGE, ) from homeassistant.helpers import config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send @@ -448,7 +449,7 @@ class ZigBeeAnalogIn(Entity): @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" - return "%" + return UNIT_PERCENTAGE def update(self): """Get the latest reading from the ADC.""" diff --git a/homeassistant/const.py b/homeassistant/const.py index 155eff79bb3..4e4be408b40 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -395,6 +395,8 @@ MASS_POUNDS: str = "lb" # UV Index units UNIT_UV_INDEX: str = "UV index" +# Percentage units +UNIT_PERCENTAGE = "%" # Irradiation units IRRADIATION_WATTS_PER_SQUARE_METER = f"{POWER_WATT}/{AREA_SQUARE_METERS}" diff --git a/tests/components/arlo/test_sensor.py b/tests/components/arlo/test_sensor.py index ac64ad8f272..15b85959ff0 100644 --- a/tests/components/arlo/test_sensor.py +++ b/tests/components/arlo/test_sensor.py @@ -9,6 +9,7 @@ from homeassistant.const import ( ATTR_ATTRIBUTION, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, + UNIT_PERCENTAGE, ) @@ -168,7 +169,7 @@ def test_sensor_icon(temperature_sensor): def test_unit_of_measure(default_sensor, battery_sensor): """Test the unit_of_measurement property.""" assert default_sensor.unit_of_measurement is None - assert battery_sensor.unit_of_measurement == "%" + assert battery_sensor.unit_of_measurement == UNIT_PERCENTAGE def test_device_class(default_sensor, temperature_sensor, humidity_sensor): diff --git a/tests/components/awair/test_sensor.py b/tests/components/awair/test_sensor.py index 03d3f71d5f9..2d88a5019b1 100644 --- a/tests/components/awair/test_sensor.py +++ b/tests/components/awair/test_sensor.py @@ -23,6 +23,7 @@ from homeassistant.const import ( DEVICE_CLASS_TEMPERATURE, STATE_UNAVAILABLE, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.setup import async_setup_component from homeassistant.util.dt import parse_datetime, utcnow @@ -156,7 +157,7 @@ async def test_awair_score(hass): sensor = hass.states.get("sensor.awair_score") assert sensor.state == "78" assert sensor.attributes["device_class"] == DEVICE_CLASS_SCORE - assert sensor.attributes["unit_of_measurement"] == "%" + assert sensor.attributes["unit_of_measurement"] == UNIT_PERCENTAGE async def test_awair_temp(hass): @@ -176,7 +177,7 @@ async def test_awair_humid(hass): sensor = hass.states.get("sensor.awair_humidity") assert sensor.state == "32.7" assert sensor.attributes["device_class"] == DEVICE_CLASS_HUMIDITY - assert sensor.attributes["unit_of_measurement"] == "%" + assert sensor.attributes["unit_of_measurement"] == UNIT_PERCENTAGE async def test_awair_co2(hass): diff --git a/tests/components/canary/test_sensor.py b/tests/components/canary/test_sensor.py index 7d5e829a347..b9d8be50b90 100644 --- a/tests/components/canary/test_sensor.py +++ b/tests/components/canary/test_sensor.py @@ -12,6 +12,7 @@ from homeassistant.components.canary.sensor import ( STATE_AIR_QUALITY_VERY_ABNORMAL, CanarySensor, ) +from homeassistant.const import UNIT_PERCENTAGE from tests.common import get_test_home_assistant from tests.components.canary.test_init import mock_device, mock_location @@ -97,7 +98,7 @@ class TestCanarySensorSetup(unittest.TestCase): sensor.update() assert "Home Family Room Humidity" == sensor.name - assert "%" == sensor.unit_of_measurement + assert UNIT_PERCENTAGE == sensor.unit_of_measurement assert 50.46 == sensor.state assert "mdi:water-percent" == sensor.icon @@ -184,7 +185,7 @@ class TestCanarySensorSetup(unittest.TestCase): sensor.update() assert "Home Family Room Battery" == sensor.name - assert "%" == sensor.unit_of_measurement + assert UNIT_PERCENTAGE == sensor.unit_of_measurement assert 70.46 == sensor.state assert "mdi:battery-70" == sensor.icon diff --git a/tests/components/dyson/test_sensor.py b/tests/components/dyson/test_sensor.py index e540d304731..b036e3bbbdb 100644 --- a/tests/components/dyson/test_sensor.py +++ b/tests/components/dyson/test_sensor.py @@ -8,7 +8,13 @@ from libpurecool.dyson_pure_cool_link import DysonPureCoolLink from homeassistant.components import dyson as dyson_parent from homeassistant.components.dyson import sensor as dyson -from homeassistant.const import STATE_OFF, TEMP_CELSIUS, TEMP_FAHRENHEIT, TIME_HOURS +from homeassistant.const import ( + STATE_OFF, + TEMP_CELSIUS, + TEMP_FAHRENHEIT, + TIME_HOURS, + UNIT_PERCENTAGE, +) from homeassistant.helpers import discovery from homeassistant.setup import async_setup_component @@ -169,7 +175,7 @@ class DysonTest(unittest.TestCase): sensor.entity_id = "sensor.dyson_1" assert not sensor.should_poll assert sensor.state is None - assert sensor.unit_of_measurement == "%" + assert sensor.unit_of_measurement == UNIT_PERCENTAGE assert sensor.name == "Device_name Humidity" assert sensor.entity_id == "sensor.dyson_1" @@ -180,7 +186,7 @@ class DysonTest(unittest.TestCase): sensor.entity_id = "sensor.dyson_1" assert not sensor.should_poll assert sensor.state == 45 - assert sensor.unit_of_measurement == "%" + assert sensor.unit_of_measurement == UNIT_PERCENTAGE assert sensor.name == "Device_name Humidity" assert sensor.entity_id == "sensor.dyson_1" @@ -191,7 +197,7 @@ class DysonTest(unittest.TestCase): sensor.entity_id = "sensor.dyson_1" assert not sensor.should_poll assert sensor.state == STATE_OFF - assert sensor.unit_of_measurement == "%" + assert sensor.unit_of_measurement == UNIT_PERCENTAGE assert sensor.name == "Device_name Humidity" assert sensor.entity_id == "sensor.dyson_1" diff --git a/tests/components/foobot/test_sensor.py b/tests/components/foobot/test_sensor.py index a843f9a3012..f8cf38395f2 100644 --- a/tests/components/foobot/test_sensor.py +++ b/tests/components/foobot/test_sensor.py @@ -13,6 +13,7 @@ from homeassistant.const import ( CONCENTRATION_PARTS_PER_BILLION, CONCENTRATION_PARTS_PER_MILLION, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.setup import async_setup_component @@ -40,10 +41,10 @@ async def test_default_setup(hass, aioclient_mock): metrics = { "co2": ["1232.0", CONCENTRATION_PARTS_PER_MILLION], "temperature": ["21.1", TEMP_CELSIUS], - "humidity": ["49.5", "%"], + "humidity": ["49.5", UNIT_PERCENTAGE], "pm2_5": ["144.8", CONCENTRATION_MICROGRAMS_PER_CUBIC_METER], "voc": ["340.7", CONCENTRATION_PARTS_PER_BILLION], - "index": ["138.9", "%"], + "index": ["138.9", UNIT_PERCENTAGE], } for name, value in metrics.items(): diff --git a/tests/components/homekit/test_get_accessories.py b/tests/components/homekit/test_get_accessories.py index e6bf185c93b..08a04d5b88e 100644 --- a/tests/components/homekit/test_get_accessories.py +++ b/tests/components/homekit/test_get_accessories.py @@ -26,6 +26,7 @@ from homeassistant.const import ( CONF_TYPE, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) from homeassistant.core import State @@ -180,7 +181,7 @@ def test_type_media_player(type_name, entity_id, state, attrs, config): "HumiditySensor", "sensor.humidity", "20", - {ATTR_DEVICE_CLASS: "humidity", ATTR_UNIT_OF_MEASUREMENT: "%"}, + {ATTR_DEVICE_CLASS: "humidity", ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE}, ), ("LightSensor", "sensor.light", "900", {ATTR_DEVICE_CLASS: "illuminance"}), ("LightSensor", "sensor.light", "900", {ATTR_UNIT_OF_MEASUREMENT: "lm"}), diff --git a/tests/components/homekit/test_type_lights.py b/tests/components/homekit/test_type_lights.py index f357702040b..8834f730bce 100644 --- a/tests/components/homekit/test_type_lights.py +++ b/tests/components/homekit/test_type_lights.py @@ -21,6 +21,7 @@ from homeassistant.const import ( STATE_OFF, STATE_ON, STATE_UNKNOWN, + UNIT_PERCENTAGE, ) from homeassistant.core import CoreState from homeassistant.helpers import entity_registry @@ -127,7 +128,7 @@ async def test_light_brightness(hass, hk_driver, cls, events): assert call_turn_on[0].data[ATTR_ENTITY_ID] == entity_id assert call_turn_on[0].data[ATTR_BRIGHTNESS_PCT] == 20 assert len(events) == 1 - assert events[-1].data[ATTR_VALUE] == "brightness at 20%" + assert events[-1].data[ATTR_VALUE] == f"brightness at 20{UNIT_PERCENTAGE}" await hass.async_add_job(acc.char_on.client_update_value, 1) await hass.async_add_job(acc.char_brightness.client_update_value, 40) @@ -136,7 +137,7 @@ async def test_light_brightness(hass, hk_driver, cls, events): assert call_turn_on[1].data[ATTR_ENTITY_ID] == entity_id assert call_turn_on[1].data[ATTR_BRIGHTNESS_PCT] == 40 assert len(events) == 2 - assert events[-1].data[ATTR_VALUE] == "brightness at 40%" + assert events[-1].data[ATTR_VALUE] == f"brightness at 40{UNIT_PERCENTAGE}" await hass.async_add_job(acc.char_on.client_update_value, 1) await hass.async_add_job(acc.char_brightness.client_update_value, 0) @@ -235,9 +236,7 @@ async def test_light_restore(hass, hk_driver, cls, events): registry = await entity_registry.async_get_registry(hass) - registry.async_get_or_create( - "light", "hue", "1234", suggested_object_id="simple", - ) + registry.async_get_or_create("light", "hue", "1234", suggested_object_id="simple") registry.async_get_or_create( "light", "hue", diff --git a/tests/components/homekit/test_type_sensors.py b/tests/components/homekit/test_type_sensors.py index 969ea0bddc8..79d807b77c5 100644 --- a/tests/components/homekit/test_type_sensors.py +++ b/tests/components/homekit/test_type_sensors.py @@ -26,6 +26,7 @@ from homeassistant.const import ( STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) from homeassistant.core import CoreState from homeassistant.helpers import entity_registry @@ -287,7 +288,7 @@ async def test_sensor_restore(hass, hk_driver, events): "12345", suggested_object_id="humidity", device_class="humidity", - unit_of_measurement="%", + unit_of_measurement=UNIT_PERCENTAGE, ) hass.bus.async_fire(EVENT_HOMEASSISTANT_START, {}) await hass.async_block_till_done() diff --git a/tests/components/homematicip_cloud/test_sensor.py b/tests/components/homematicip_cloud/test_sensor.py index c5dbef1a499..c55a4682216 100644 --- a/tests/components/homematicip_cloud/test_sensor.py +++ b/tests/components/homematicip_cloud/test_sensor.py @@ -27,6 +27,7 @@ from homeassistant.const import ( POWER_WATT, SPEED_KILOMETERS_PER_HOUR, TEMP_CELSIUS, + UNIT_PERCENTAGE, ) from homeassistant.setup import async_setup_component @@ -55,7 +56,7 @@ async def test_hmip_accesspoint_status(hass, default_mock_hap_factory): ) assert hmip_device assert ha_state.state == "8.0" - assert ha_state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "%" + assert ha_state.attributes[ATTR_UNIT_OF_MEASUREMENT] == UNIT_PERCENTAGE await async_manipulate_test_data(hass, hmip_device, "dutyCycle", 17.3) @@ -77,7 +78,7 @@ async def test_hmip_heating_thermostat(hass, default_mock_hap_factory): ) assert ha_state.state == "0" - assert ha_state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "%" + assert ha_state.attributes[ATTR_UNIT_OF_MEASUREMENT] == UNIT_PERCENTAGE await async_manipulate_test_data(hass, hmip_device, "valvePosition", 0.37) ha_state = hass.states.get(entity_id) assert ha_state.state == "37" @@ -111,7 +112,7 @@ async def test_hmip_humidity_sensor(hass, default_mock_hap_factory): ) assert ha_state.state == "40" - assert ha_state.attributes["unit_of_measurement"] == "%" + assert ha_state.attributes["unit_of_measurement"] == UNIT_PERCENTAGE await async_manipulate_test_data(hass, hmip_device, "humidity", 45) ha_state = hass.states.get(entity_id) assert ha_state.state == "45" diff --git a/tests/components/influxdb/test_init.py b/tests/components/influxdb/test_init.py index 1dd2681b7f2..2bb9faad8e5 100644 --- a/tests/components/influxdb/test_init.py +++ b/tests/components/influxdb/test_init.py @@ -4,7 +4,13 @@ import unittest from unittest import mock import homeassistant.components.influxdb as influxdb -from homeassistant.const import EVENT_STATE_CHANGED, STATE_OFF, STATE_ON, STATE_STANDBY +from homeassistant.const import ( + EVENT_STATE_CHANGED, + STATE_OFF, + STATE_ON, + STATE_STANDBY, + UNIT_PERCENTAGE, +) from homeassistant.setup import setup_component from tests.common import get_test_home_assistant @@ -102,7 +108,7 @@ class TestInfluxDB(unittest.TestCase): "unit_of_measurement": "foobars", "longitude": "1.1", "latitude": "2.2", - "battery_level": "99%", + "battery_level": f"99{UNIT_PERCENTAGE}", "temperature": "20c", "last_seen": "Last seen 23 minutes ago", "updated_at": datetime.datetime(2017, 1, 1, 0, 0), @@ -124,7 +130,7 @@ class TestInfluxDB(unittest.TestCase): "fields": { "longitude": 1.1, "latitude": 2.2, - "battery_level_str": "99%", + "battery_level_str": f"99{UNIT_PERCENTAGE}", "battery_level": 99.0, "temperature_str": "20c", "temperature": 20.0, diff --git a/tests/components/min_max/test_sensor.py b/tests/components/min_max/test_sensor.py index fcc9a72cf7b..38b725226e7 100644 --- a/tests/components/min_max/test_sensor.py +++ b/tests/components/min_max/test_sensor.py @@ -7,6 +7,7 @@ from homeassistant.const import ( STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) from homeassistant.setup import setup_component @@ -233,7 +234,7 @@ class TestMinMaxSensor(unittest.TestCase): assert "ERR" == state.attributes.get("unit_of_measurement") self.hass.states.set( - entity_ids[2], self.values[2], {ATTR_UNIT_OF_MEASUREMENT: "%"} + entity_ids[2], self.values[2], {ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE} ) self.hass.block_till_done() diff --git a/tests/components/mobile_app/test_entity.py b/tests/components/mobile_app/test_entity.py index 65dc328186d..27ce29ecd15 100644 --- a/tests/components/mobile_app/test_entity.py +++ b/tests/components/mobile_app/test_entity.py @@ -2,6 +2,7 @@ import logging +from homeassistant.const import UNIT_PERCENTAGE from homeassistant.helpers import device_registry _LOGGER = logging.getLogger(__name__) @@ -24,7 +25,7 @@ async def test_sensor(hass, create_registrations, webhook_client): "state": 100, "type": "sensor", "unique_id": "battery_state", - "unit_of_measurement": "%", + "unit_of_measurement": UNIT_PERCENTAGE, }, }, ) @@ -40,7 +41,7 @@ async def test_sensor(hass, create_registrations, webhook_client): assert entity.attributes["device_class"] == "battery" assert entity.attributes["icon"] == "mdi:battery" - assert entity.attributes["unit_of_measurement"] == "%" + assert entity.attributes["unit_of_measurement"] == UNIT_PERCENTAGE assert entity.attributes["foo"] == "bar" assert entity.domain == "sensor" assert entity.name == "Test 1 Battery State" @@ -104,7 +105,7 @@ async def test_sensor_id_no_dupes(hass, create_registrations, webhook_client): "state": 100, "type": "sensor", "unique_id": "battery_state", - "unit_of_measurement": "%", + "unit_of_measurement": UNIT_PERCENTAGE, }, } diff --git a/tests/components/mold_indicator/test_sensor.py b/tests/components/mold_indicator/test_sensor.py index ce0450d3304..bad7430e9b2 100644 --- a/tests/components/mold_indicator/test_sensor.py +++ b/tests/components/mold_indicator/test_sensor.py @@ -6,7 +6,12 @@ from homeassistant.components.mold_indicator.sensor import ( ATTR_DEWPOINT, ) import homeassistant.components.sensor as sensor -from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT, STATE_UNKNOWN, TEMP_CELSIUS +from homeassistant.const import ( + ATTR_UNIT_OF_MEASUREMENT, + STATE_UNKNOWN, + TEMP_CELSIUS, + UNIT_PERCENTAGE, +) from homeassistant.setup import setup_component from tests.common import get_test_home_assistant @@ -25,7 +30,7 @@ class TestSensorMoldIndicator(unittest.TestCase): "test.outdoortemp", "10", {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) self.hass.states.set( - "test.indoorhumidity", "50", {ATTR_UNIT_OF_MEASUREMENT: "%"} + "test.indoorhumidity", "50", {ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE} ) def tearDown(self): @@ -50,7 +55,7 @@ class TestSensorMoldIndicator(unittest.TestCase): moldind = self.hass.states.get("sensor.mold_indicator") assert moldind - assert "%" == moldind.attributes.get("unit_of_measurement") + assert UNIT_PERCENTAGE == moldind.attributes.get("unit_of_measurement") def test_invalidcalib(self): """Test invalid sensor values.""" @@ -61,7 +66,7 @@ class TestSensorMoldIndicator(unittest.TestCase): "test.outdoortemp", "10", {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) self.hass.states.set( - "test.indoorhumidity", "0", {ATTR_UNIT_OF_MEASUREMENT: "%"} + "test.indoorhumidity", "0", {ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE} ) assert setup_component( @@ -94,7 +99,7 @@ class TestSensorMoldIndicator(unittest.TestCase): "test.outdoortemp", "10", {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) self.hass.states.set( - "test.indoorhumidity", "-1", {ATTR_UNIT_OF_MEASUREMENT: "%"} + "test.indoorhumidity", "-1", {ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE} ) assert setup_component( @@ -120,7 +125,7 @@ class TestSensorMoldIndicator(unittest.TestCase): assert moldind.attributes.get(ATTR_CRITICAL_TEMP) is None self.hass.states.set( - "test.indoorhumidity", "A", {ATTR_UNIT_OF_MEASUREMENT: "%"} + "test.indoorhumidity", "A", {ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE} ) self.hass.block_till_done() moldind = self.hass.states.get("sensor.mold_indicator") @@ -220,7 +225,9 @@ class TestSensorMoldIndicator(unittest.TestCase): "test.outdoortemp", "25", {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) self.hass.states.set( - "test.indoorhumidity", STATE_UNKNOWN, {ATTR_UNIT_OF_MEASUREMENT: "%"} + "test.indoorhumidity", + STATE_UNKNOWN, + {ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE}, ) self.hass.block_till_done() moldind = self.hass.states.get("sensor.mold_indicator") @@ -230,7 +237,7 @@ class TestSensorMoldIndicator(unittest.TestCase): assert moldind.attributes.get(ATTR_CRITICAL_TEMP) is None self.hass.states.set( - "test.indoorhumidity", "20", {ATTR_UNIT_OF_MEASUREMENT: "%"} + "test.indoorhumidity", "20", {ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE} ) self.hass.block_till_done() moldind = self.hass.states.get("sensor.mold_indicator") @@ -276,7 +283,7 @@ class TestSensorMoldIndicator(unittest.TestCase): assert self.hass.states.get("sensor.mold_indicator").state == "57" self.hass.states.set( - "test.indoorhumidity", "20", {ATTR_UNIT_OF_MEASUREMENT: "%"} + "test.indoorhumidity", "20", {ATTR_UNIT_OF_MEASUREMENT: UNIT_PERCENTAGE} ) self.hass.block_till_done() assert self.hass.states.get("sensor.mold_indicator").state == "23" diff --git a/tests/components/rflink/test_sensor.py b/tests/components/rflink/test_sensor.py index b68e1f959f1..a4904f5bc9b 100644 --- a/tests/components/rflink/test_sensor.py +++ b/tests/components/rflink/test_sensor.py @@ -12,7 +12,7 @@ from homeassistant.components.rflink import ( EVENT_KEY_SENSOR, TMP_ENTITY, ) -from homeassistant.const import STATE_UNKNOWN +from homeassistant.const import STATE_UNKNOWN, UNIT_PERCENTAGE from tests.components.rflink.test_init import mock_rflink @@ -141,7 +141,12 @@ async def test_aliases(hass, monkeypatch): # test event for config sensor event_callback( - {"id": "test_alias_02_0", "sensor": "humidity", "value": 65, "unit": "%"} + { + "id": "test_alias_02_0", + "sensor": "humidity", + "value": 65, + "unit": UNIT_PERCENTAGE, + } ) await hass.async_block_till_done() @@ -149,7 +154,7 @@ async def test_aliases(hass, monkeypatch): updated_sensor = hass.states.get("sensor.test_02") assert updated_sensor assert updated_sensor.state == "65" - assert updated_sensor.attributes["unit_of_measurement"] == "%" + assert updated_sensor.attributes["unit_of_measurement"] == UNIT_PERCENTAGE async def test_race_condition(hass, monkeypatch): diff --git a/tests/components/rfxtrx/test_sensor.py b/tests/components/rfxtrx/test_sensor.py index 652c823e0cf..e258ebb9aa1 100644 --- a/tests/components/rfxtrx/test_sensor.py +++ b/tests/components/rfxtrx/test_sensor.py @@ -4,7 +4,7 @@ import unittest import pytest from homeassistant.components import rfxtrx as rfxtrx_core -from homeassistant.const import TEMP_CELSIUS +from homeassistant.const import TEMP_CELSIUS, UNIT_PERCENTAGE from homeassistant.setup import setup_component from tests.common import get_test_home_assistant, mock_component @@ -137,7 +137,7 @@ class TestSensorRfxtrx(unittest.TestCase): assert len(rfxtrx_core.RFX_DEVICES[id]) == 2 _entity_temp = rfxtrx_core.RFX_DEVICES[id]["Temperature"] _entity_hum = rfxtrx_core.RFX_DEVICES[id]["Humidity"] - assert "%" == _entity_hum.unit_of_measurement + assert UNIT_PERCENTAGE == _entity_hum.unit_of_measurement assert "Bath" == _entity_hum.__str__() assert _entity_hum.state is None assert TEMP_CELSIUS == _entity_temp.unit_of_measurement @@ -271,7 +271,7 @@ class TestSensorRfxtrx(unittest.TestCase): assert len(rfxtrx_core.RFX_DEVICES[id]) == 2 _entity_temp = rfxtrx_core.RFX_DEVICES[id]["Temperature"] _entity_hum = rfxtrx_core.RFX_DEVICES[id]["Humidity"] - assert "%" == _entity_hum.unit_of_measurement + assert UNIT_PERCENTAGE == _entity_hum.unit_of_measurement assert "Bath" == _entity_hum.__str__() assert _entity_temp.state is None assert TEMP_CELSIUS == _entity_temp.unit_of_measurement @@ -303,7 +303,7 @@ class TestSensorRfxtrx(unittest.TestCase): assert len(rfxtrx_core.RFX_DEVICES[id]) == 2 _entity_temp = rfxtrx_core.RFX_DEVICES[id]["Temperature"] _entity_hum = rfxtrx_core.RFX_DEVICES[id]["Humidity"] - assert "%" == _entity_hum.unit_of_measurement + assert UNIT_PERCENTAGE == _entity_hum.unit_of_measurement assert 15 == _entity_hum.state assert { "Battery numeric": 9, diff --git a/tests/components/sensor/test_device_condition.py b/tests/components/sensor/test_device_condition.py index f9d8bb640c3..5d25e666110 100644 --- a/tests/components/sensor/test_device_condition.py +++ b/tests/components/sensor/test_device_condition.py @@ -4,7 +4,7 @@ import pytest import homeassistant.components.automation as automation from homeassistant.components.sensor import DOMAIN from homeassistant.components.sensor.device_condition import ENTITY_CONDITIONS -from homeassistant.const import CONF_PLATFORM, STATE_UNKNOWN +from homeassistant.const import CONF_PLATFORM, STATE_UNKNOWN, UNIT_PERCENTAGE from homeassistant.helpers import device_registry from homeassistant.setup import async_setup_component @@ -97,13 +97,13 @@ async def test_get_condition_capabilities(hass, device_reg, entity_reg): expected_capabilities = { "extra_fields": [ { - "description": {"suffix": "%"}, + "description": {"suffix": UNIT_PERCENTAGE}, "name": "above", "optional": True, "type": "float", }, { - "description": {"suffix": "%"}, + "description": {"suffix": UNIT_PERCENTAGE}, "name": "below", "optional": True, "type": "float", diff --git a/tests/components/sensor/test_device_trigger.py b/tests/components/sensor/test_device_trigger.py index 8e4b5d1792a..54c0c8f7bd0 100644 --- a/tests/components/sensor/test_device_trigger.py +++ b/tests/components/sensor/test_device_trigger.py @@ -6,7 +6,7 @@ import pytest import homeassistant.components.automation as automation from homeassistant.components.sensor import DOMAIN from homeassistant.components.sensor.device_trigger import ENTITY_TRIGGERS -from homeassistant.const import CONF_PLATFORM, STATE_UNKNOWN +from homeassistant.const import CONF_PLATFORM, STATE_UNKNOWN, UNIT_PERCENTAGE from homeassistant.helpers import device_registry from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util @@ -102,13 +102,13 @@ async def test_get_trigger_capabilities(hass, device_reg, entity_reg): expected_capabilities = { "extra_fields": [ { - "description": {"suffix": "%"}, + "description": {"suffix": UNIT_PERCENTAGE}, "name": "above", "optional": True, "type": "float", }, { - "description": {"suffix": "%"}, + "description": {"suffix": UNIT_PERCENTAGE}, "name": "below", "optional": True, "type": "float", diff --git a/tests/components/smartthings/test_sensor.py b/tests/components/smartthings/test_sensor.py index f285bc65d8d..fd8bfdca44c 100644 --- a/tests/components/smartthings/test_sensor.py +++ b/tests/components/smartthings/test_sensor.py @@ -13,6 +13,7 @@ from homeassistant.const import ( ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT, STATE_UNKNOWN, + UNIT_PERCENTAGE, ) from homeassistant.helpers.dispatcher import async_dispatcher_send @@ -37,7 +38,7 @@ async def test_entity_state(hass, device_factory): await setup_platform(hass, SENSOR_DOMAIN, devices=[device]) state = hass.states.get("sensor.sensor_1_battery") assert state.state == "100" - assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "%" + assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == UNIT_PERCENTAGE assert state.attributes[ATTR_FRIENDLY_NAME] == device.label + " Battery" diff --git a/tests/components/sonarr/test_sensor.py b/tests/components/sonarr/test_sensor.py index 300d201079b..1629a3d29c2 100644 --- a/tests/components/sonarr/test_sensor.py +++ b/tests/components/sonarr/test_sensor.py @@ -6,7 +6,7 @@ import unittest import pytest import homeassistant.components.sonarr.sensor as sonarr -from homeassistant.const import DATA_GIGABYTES +from homeassistant.const import DATA_GIGABYTES, UNIT_PERCENTAGE from tests.common import get_test_home_assistant @@ -569,7 +569,10 @@ class TestSonarrSetup(unittest.TestCase): assert "mdi:download" == device.icon assert "Episodes" == device.unit_of_measurement assert "Sonarr Queue" == device.name - assert "100.00%" == device.device_state_attributes["Game of Thrones S03E08"] + assert ( + f"100.00{UNIT_PERCENTAGE}" + == device.device_state_attributes["Game of Thrones S03E08"] + ) @unittest.mock.patch("requests.get", side_effect=mocked_requests_get) def test_series(self, req_mock): diff --git a/tests/components/spaceapi/test_init.py b/tests/components/spaceapi/test_init.py index 840931d073b..78c7991d9b3 100644 --- a/tests/components/spaceapi/test_init.py +++ b/tests/components/spaceapi/test_init.py @@ -5,6 +5,7 @@ from unittest.mock import patch import pytest from homeassistant.components.spaceapi import DOMAIN, SPACEAPI_VERSION, URL_API_SPACEAPI +from homeassistant.const import UNIT_PERCENTAGE from homeassistant.setup import async_setup_component from tests.common import mock_coro @@ -62,7 +63,9 @@ SENSOR_OUTPUT = { {"location": "Home", "name": "temp1", "unit": "°C", "value": "25"}, {"location": "Home", "name": "temp2", "unit": "°C", "value": "23"}, ], - "humidity": [{"location": "Home", "name": "hum1", "unit": "%", "value": "88"}], + "humidity": [ + {"location": "Home", "name": "hum1", "unit": UNIT_PERCENTAGE, "value": "88"} + ], } @@ -74,7 +77,9 @@ def mock_client(hass, hass_client): hass.states.async_set("test.temp1", 25, attributes={"unit_of_measurement": "°C"}) hass.states.async_set("test.temp2", 23, attributes={"unit_of_measurement": "°C"}) - hass.states.async_set("test.hum1", 88, attributes={"unit_of_measurement": "%"}) + hass.states.async_set( + "test.hum1", 88, attributes={"unit_of_measurement": UNIT_PERCENTAGE} + ) return hass.loop.run_until_complete(hass_client()) diff --git a/tests/components/startca/test_sensor.py b/tests/components/startca/test_sensor.py index 82748c122ab..23cc892900b 100644 --- a/tests/components/startca/test_sensor.py +++ b/tests/components/startca/test_sensor.py @@ -1,7 +1,7 @@ """Tests for the Start.ca sensor platform.""" from homeassistant.bootstrap import async_setup_component from homeassistant.components.startca.sensor import StartcaData -from homeassistant.const import DATA_GIGABYTES +from homeassistant.const import DATA_GIGABYTES, UNIT_PERCENTAGE from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -52,7 +52,7 @@ async def test_capped_setup(hass, aioclient_mock): await async_setup_component(hass, "sensor", {"sensor": config}) state = hass.states.get("sensor.start_ca_usage_ratio") - assert state.attributes.get("unit_of_measurement") == "%" + assert state.attributes.get("unit_of_measurement") == UNIT_PERCENTAGE assert state.state == "76.24" state = hass.states.get("sensor.start_ca_usage") @@ -147,7 +147,7 @@ async def test_unlimited_setup(hass, aioclient_mock): await async_setup_component(hass, "sensor", {"sensor": config}) state = hass.states.get("sensor.start_ca_usage_ratio") - assert state.attributes.get("unit_of_measurement") == "%" + assert state.attributes.get("unit_of_measurement") == UNIT_PERCENTAGE assert state.state == "0" state = hass.states.get("sensor.start_ca_usage") diff --git a/tests/components/teksavvy/test_sensor.py b/tests/components/teksavvy/test_sensor.py index 641112e6362..e3e7eae36a8 100644 --- a/tests/components/teksavvy/test_sensor.py +++ b/tests/components/teksavvy/test_sensor.py @@ -1,7 +1,7 @@ """Tests for the TekSavvy sensor platform.""" from homeassistant.bootstrap import async_setup_component from homeassistant.components.teksavvy.sensor import TekSavvyData -from homeassistant.const import DATA_GIGABYTES +from homeassistant.const import DATA_GIGABYTES, UNIT_PERCENTAGE from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -74,7 +74,7 @@ async def test_capped_setup(hass, aioclient_mock): assert state.state == "235.57" state = hass.states.get("sensor.teksavvy_usage_ratio") - assert state.attributes.get("unit_of_measurement") == "%" + assert state.attributes.get("unit_of_measurement") == UNIT_PERCENTAGE assert state.state == "56.69" state = hass.states.get("sensor.teksavvy_usage") @@ -159,7 +159,7 @@ async def test_unlimited_setup(hass, aioclient_mock): assert state.state == "226.75" state = hass.states.get("sensor.teksavvy_usage_ratio") - assert state.attributes.get("unit_of_measurement") == "%" + assert state.attributes.get("unit_of_measurement") == UNIT_PERCENTAGE assert state.state == "0" state = hass.states.get("sensor.teksavvy_remaining") diff --git a/tests/components/vera/test_sensor.py b/tests/components/vera/test_sensor.py index da28fc225e0..9e84815d636 100644 --- a/tests/components/vera/test_sensor.py +++ b/tests/components/vera/test_sensor.py @@ -13,6 +13,7 @@ from pyvera import ( VeraSensor, ) +from homeassistant.const import UNIT_PERCENTAGE from homeassistant.core import HomeAssistant from .common import ComponentFactory @@ -64,7 +65,7 @@ async def test_temperature_sensor_f( vera_component_factory=vera_component_factory, category=CATEGORY_TEMPERATURE_SENSOR, class_property="temperature", - assert_states=(("33", "1"), ("44", "7"),), + assert_states=(("33", "1"), ("44", "7")), setup_callback=setup_callback, ) @@ -78,7 +79,7 @@ async def test_temperature_sensor_c( vera_component_factory=vera_component_factory, category=CATEGORY_TEMPERATURE_SENSOR, class_property="temperature", - assert_states=(("33", "33"), ("44", "44"),), + assert_states=(("33", "33"), ("44", "44")), ) @@ -91,7 +92,7 @@ async def test_light_sensor( vera_component_factory=vera_component_factory, category=CATEGORY_LIGHT_SENSOR, class_property="light", - assert_states=(("12", "12"), ("13", "13"),), + assert_states=(("12", "12"), ("13", "13")), assert_unit_of_measurement="lx", ) @@ -105,7 +106,7 @@ async def test_uv_sensor( vera_component_factory=vera_component_factory, category=CATEGORY_UV_SENSOR, class_property="light", - assert_states=(("12", "12"), ("13", "13"),), + assert_states=(("12", "12"), ("13", "13")), assert_unit_of_measurement="level", ) @@ -119,8 +120,8 @@ async def test_humidity_sensor( vera_component_factory=vera_component_factory, category=CATEGORY_HUMIDITY_SENSOR, class_property="humidity", - assert_states=(("12", "12"), ("13", "13"),), - assert_unit_of_measurement="%", + assert_states=(("12", "12"), ("13", "13")), + assert_unit_of_measurement=UNIT_PERCENTAGE, ) @@ -133,7 +134,7 @@ async def test_power_meter_sensor( vera_component_factory=vera_component_factory, category=CATEGORY_POWER_METER, class_property="power", - assert_states=(("12", "12"), ("13", "13"),), + assert_states=(("12", "12"), ("13", "13")), assert_unit_of_measurement="watts", ) @@ -151,7 +152,7 @@ async def test_trippable_sensor( vera_component_factory=vera_component_factory, category=999, class_property="is_tripped", - assert_states=((True, "Tripped"), (False, "Not Tripped"), (True, "Tripped"),), + assert_states=((True, "Tripped"), (False, "Not Tripped"), (True, "Tripped")), setup_callback=setup_callback, ) @@ -169,7 +170,7 @@ async def test_unknown_sensor( vera_component_factory=vera_component_factory, category=999, class_property="is_tripped", - assert_states=((True, "Unknown"), (False, "Unknown"), (True, "Unknown"),), + assert_states=((True, "Unknown"), (False, "Unknown"), (True, "Unknown")), setup_callback=setup_callback, ) @@ -187,7 +188,7 @@ async def test_scene_controller_sensor( entity_id = "sensor.dev1_1" component_data = await vera_component_factory.configure_component( - hass=hass, devices=(vera_device,), + hass=hass, devices=(vera_device,) ) controller = component_data.controller update_callback = controller.register.call_args_list[0][0][1] diff --git a/tests/components/yr/test_sensor.py b/tests/components/yr/test_sensor.py index d3e3bd6286f..398acd7d554 100644 --- a/tests/components/yr/test_sensor.py +++ b/tests/components/yr/test_sensor.py @@ -3,7 +3,7 @@ from datetime import datetime from unittest.mock import patch from homeassistant.bootstrap import async_setup_component -from homeassistant.const import SPEED_METERS_PER_SECOND +from homeassistant.const import SPEED_METERS_PER_SECOND, UNIT_PERCENTAGE import homeassistant.util.dt as dt_util from tests.common import assert_setup_component, load_fixture @@ -63,11 +63,11 @@ async def test_custom_setup(hass, aioclient_mock): assert state.state == "103.6" state = hass.states.get("sensor.yr_humidity") - assert state.attributes.get("unit_of_measurement") == "%" + assert state.attributes.get("unit_of_measurement") == UNIT_PERCENTAGE assert state.state == "55.5" state = hass.states.get("sensor.yr_fog") - assert state.attributes.get("unit_of_measurement") == "%" + assert state.attributes.get("unit_of_measurement") == UNIT_PERCENTAGE assert state.state == "0.0" state = hass.states.get("sensor.yr_wind_speed") @@ -109,11 +109,11 @@ async def test_forecast_setup(hass, aioclient_mock): assert state.state == "148.9" state = hass.states.get("sensor.yr_humidity") - assert state.attributes.get("unit_of_measurement") == "%" + assert state.attributes.get("unit_of_measurement") == UNIT_PERCENTAGE assert state.state == "77.4" state = hass.states.get("sensor.yr_fog") - assert state.attributes.get("unit_of_measurement") == "%" + assert state.attributes.get("unit_of_measurement") == UNIT_PERCENTAGE assert state.state == "0.0" state = hass.states.get("sensor.yr_wind_speed") diff --git a/tests/components/zha/test_sensor.py b/tests/components/zha/test_sensor.py index b81e8f02c12..fce882c6949 100644 --- a/tests/components/zha/test_sensor.py +++ b/tests/components/zha/test_sensor.py @@ -19,6 +19,7 @@ from homeassistant.const import ( STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT, + UNIT_PERCENTAGE, ) from homeassistant.helpers import restore_state from homeassistant.util import dt as dt_util @@ -35,7 +36,7 @@ from .common import ( async def async_test_humidity(hass, cluster, entity_id): """Test humidity sensor.""" await send_attribute_report(hass, cluster, 0, 1000) - assert_state(hass, entity_id, "10.0", "%") + assert_state(hass, entity_id, "10.0", UNIT_PERCENTAGE) async def async_test_temperature(hass, cluster, entity_id): diff --git a/tests/components/zwave/test_sensor.py b/tests/components/zwave/test_sensor.py index 74e1ef2cd03..d7503eb10fb 100644 --- a/tests/components/zwave/test_sensor.py +++ b/tests/components/zwave/test_sensor.py @@ -151,12 +151,12 @@ def test_alarm_sensor_value_changed(mock_openzwave): node = MockNode( command_classes=[const.COMMAND_CLASS_ALARM, const.COMMAND_CLASS_SENSOR_ALARM] ) - value = MockValue(data=12.34, node=node, units="%") + value = MockValue(data=12.34, node=node, units=homeassistant.const.UNIT_PERCENTAGE) values = MockEntityValues(primary=value) device = sensor.get_device(node=node, values=values, node_config={}) assert device.state == 12.34 - assert device.unit_of_measurement == "%" + assert device.unit_of_measurement == homeassistant.const.UNIT_PERCENTAGE value.data = 45.67 value_changed(value) assert device.state == 45.67 diff --git a/tests/helpers/test_entity_platform.py b/tests/helpers/test_entity_platform.py index ee43f5d4f1d..d9cbbb31561 100644 --- a/tests/helpers/test_entity_platform.py +++ b/tests/helpers/test_entity_platform.py @@ -7,6 +7,7 @@ from unittest.mock import MagicMock, Mock, patch import asynctest import pytest +from homeassistant.const import UNIT_PERCENTAGE from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers import entity_platform, entity_registry from homeassistant.helpers.entity import async_generate_entity_id @@ -800,7 +801,7 @@ async def test_entity_info_added_to_entity_registry(hass): capability_attributes={"max": 100}, supported_features=5, device_class="mock-device-class", - unit_of_measurement="%", + unit_of_measurement=UNIT_PERCENTAGE, ) await component.async_add_entities([entity_default]) @@ -812,7 +813,7 @@ async def test_entity_info_added_to_entity_registry(hass): assert entry_default.capabilities == {"max": 100} assert entry_default.supported_features == 5 assert entry_default.device_class == "mock-device-class" - assert entry_default.unit_of_measurement == "%" + assert entry_default.unit_of_measurement == UNIT_PERCENTAGE async def test_override_restored_entities(hass): diff --git a/tests/testing_config/custom_components/test/sensor.py b/tests/testing_config/custom_components/test/sensor.py index 26497b16a16..38bf9653938 100644 --- a/tests/testing_config/custom_components/test/sensor.py +++ b/tests/testing_config/custom_components/test/sensor.py @@ -4,6 +4,7 @@ Provide a mock sensor platform. Call init before using it in your tests to ensure clean test data. """ import homeassistant.components.sensor as sensor +from homeassistant.const import UNIT_PERCENTAGE from tests.common import MockEntity @@ -11,8 +12,8 @@ DEVICE_CLASSES = list(sensor.DEVICE_CLASSES) DEVICE_CLASSES.append("none") UNITS_OF_MEASUREMENT = { - sensor.DEVICE_CLASS_BATTERY: "%", # % of battery that is left - sensor.DEVICE_CLASS_HUMIDITY: "%", # % of humidity in the air + sensor.DEVICE_CLASS_BATTERY: UNIT_PERCENTAGE, # % of battery that is left + sensor.DEVICE_CLASS_HUMIDITY: UNIT_PERCENTAGE, # % of humidity in the air sensor.DEVICE_CLASS_ILLUMINANCE: "lm", # current light level (lx/lm) sensor.DEVICE_CLASS_SIGNAL_STRENGTH: "dB", # signal strength (dB/dBm) sensor.DEVICE_CLASS_TEMPERATURE: "C", # temperature (C/F)