Use ENERGY_KILO_WATT_HOUR constant (#33962)

This commit is contained in:
springstan 2020-04-10 20:21:29 +02:00 committed by GitHub
parent c3c4752fa5
commit 02c9e47db8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 132 additions and 60 deletions

View file

@ -10,6 +10,7 @@ from homeassistant.const import (
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_TOKEN,
ENERGY_KILO_WATT_HOUR,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
@ -25,7 +26,7 @@ MSG_LOCATION = (
"For the coordinates, "
"you need to use both latitude and longitude."
)
CO2_INTENSITY_UNIT = "CO2eq/kWh"
CO2_INTENSITY_UNIT = f"CO2eq/{ENERGY_KILO_WATT_HOUR}"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_TOKEN): cv.string,

View file

@ -1,6 +1,6 @@
"""Definitions for DSMR Reader sensors added to MQTT."""
from homeassistant.const import VOLUME_CUBIC_METERS
from homeassistant.const import ENERGY_KILO_WATT_HOUR, VOLUME_CUBIC_METERS
def dsmr_transform(value):
@ -21,22 +21,22 @@ DEFINITIONS = {
"dsmr/reading/electricity_delivered_1": {
"name": "Low tariff usage",
"icon": "mdi:flash",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
},
"dsmr/reading/electricity_returned_1": {
"name": "Low tariff returned",
"icon": "mdi:flash-outline",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
},
"dsmr/reading/electricity_delivered_2": {
"name": "High tariff usage",
"icon": "mdi:flash",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
},
"dsmr/reading/electricity_returned_2": {
"name": "High tariff returned",
"icon": "mdi:flash-outline",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
},
"dsmr/reading/electricity_currently_delivered": {
"name": "Current power usage",
@ -116,32 +116,32 @@ DEFINITIONS = {
"dsmr/day-consumption/electricity1": {
"name": "Low tariff usage",
"icon": "mdi:counter",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
},
"dsmr/day-consumption/electricity2": {
"name": "High tariff usage",
"icon": "mdi:counter",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
},
"dsmr/day-consumption/electricity1_returned": {
"name": "Low tariff return",
"icon": "mdi:counter",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
},
"dsmr/day-consumption/electricity2_returned": {
"name": "High tariff return",
"icon": "mdi:counter",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
},
"dsmr/day-consumption/electricity_merged": {
"name": "Power usage total",
"icon": "mdi:counter",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
},
"dsmr/day-consumption/electricity_returned_merged": {
"name": "Power return total",
"icon": "mdi:counter",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
},
"dsmr/day-consumption/electricity1_cost": {
"name": "Low tariff cost",

View file

@ -1,6 +1,7 @@
"""Support for August sensors."""
import logging
from homeassistant.const import ENERGY_KILO_WATT_HOUR
from homeassistant.helpers.entity import Entity
from .const import CONF_LOADZONE, DOMAIN
@ -28,7 +29,7 @@ class GriddyPriceSensor(Entity):
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return "¢/kWh"
return f"¢/{ENERGY_KILO_WATT_HOUR}"
@property
def name(self):

View file

@ -8,7 +8,12 @@ import growattServer
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_USERNAME
from homeassistant.const import (
CONF_NAME,
CONF_PASSWORD,
CONF_USERNAME,
ENERGY_KILO_WATT_HOUR,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
@ -23,15 +28,35 @@ SCAN_INTERVAL = datetime.timedelta(minutes=5)
TOTAL_SENSOR_TYPES = {
"total_money_today": ("Total money today", "", "plantMoneyText", None),
"total_money_total": ("Money lifetime", "", "totalMoneyText", None),
"total_energy_today": ("Energy Today", "kWh", "todayEnergy", "power"),
"total_energy_today": (
"Energy Today",
ENERGY_KILO_WATT_HOUR,
"todayEnergy",
"power",
),
"total_output_power": ("Output Power", "W", "invTodayPpv", "power"),
"total_energy_output": ("Lifetime energy output", "kWh", "totalEnergy", "power"),
"total_energy_output": (
"Lifetime energy output",
ENERGY_KILO_WATT_HOUR,
"totalEnergy",
"power",
),
"total_maximum_output": ("Maximum power", "W", "nominalPower", "power"),
}
INVERTER_SENSOR_TYPES = {
"inverter_energy_today": ("Energy today", "kWh", "e_today", "power"),
"inverter_energy_total": ("Lifetime energy output", "kWh", "e_total", "power"),
"inverter_energy_today": (
"Energy today",
ENERGY_KILO_WATT_HOUR,
"e_today",
"power",
),
"inverter_energy_total": (
"Lifetime energy output",
ENERGY_KILO_WATT_HOUR,
"e_total",
"power",
),
"inverter_voltage_input_1": ("Input 1 voltage", "V", "vpv1", None),
"inverter_amperage_input_1": ("Input 1 Amperage", "A", "ipv1", None),
"inverter_wattage_input_1": ("Input 1 Wattage", "W", "ppv1", "power"),

View file

@ -4,7 +4,11 @@ import logging
from pymelcloud import DEVICE_TYPE_ATA, DEVICE_TYPE_ATW
from pymelcloud.atw_device import Zone
from homeassistant.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS
from homeassistant.const import (
DEVICE_CLASS_TEMPERATURE,
ENERGY_KILO_WATT_HOUR,
TEMP_CELSIUS,
)
from homeassistant.helpers.entity import Entity
from . import MelCloudDevice
@ -29,7 +33,7 @@ ATA_SENSORS = {
"energy": {
ATTR_MEASUREMENT_NAME: "Energy",
ATTR_ICON: "mdi:factory",
ATTR_UNIT_FN: lambda x: "kWh",
ATTR_UNIT_FN: lambda x: ENERGY_KILO_WATT_HOUR,
ATTR_DEVICE_CLASS: None,
ATTR_VALUE_FN: lambda x: x.device.total_energy_consumed,
ATTR_ENABLED_FN: lambda x: x.device.has_energy_consumed_meter,
@ -147,9 +151,7 @@ class MelDeviceSensor(Entity):
class AtwZoneSensor(MelDeviceSensor):
"""Air-to-Air device sensor."""
def __init__(
self, api: MelCloudDevice, zone: Zone, measurement, definition,
):
def __init__(self, api: MelCloudDevice, zone: Zone, measurement, definition):
"""Initialize the sensor."""
super().__init__(api, measurement, definition)
self._zone = zone

View file

@ -6,7 +6,7 @@ from typing import Optional
from aiopvpc import PVPCData
from homeassistant import config_entries
from homeassistant.const import CONF_NAME
from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_call_later, async_track_time_change
@ -19,7 +19,7 @@ _LOGGER = logging.getLogger(__name__)
ATTR_PRICE = "price"
ICON = "mdi:currency-eur"
UNIT = "€/kWh"
UNIT = f"€/{ENERGY_KILO_WATT_HOUR}"
_DEFAULT_TIMEOUT = 10
@ -78,7 +78,7 @@ class ElecPriceSensor(RestoreEntity):
random_minute = randint(1, 29)
mins_update = [random_minute, random_minute + 30]
self._price_tracker = async_track_time_change(
self.hass, self.async_update_prices, second=[0], minute=mins_update,
self.hass, self.async_update_prices, second=[0], minute=mins_update
)
_LOGGER.debug(
"Setup of price sensor %s (%s) with tariff '%s', "

View file

@ -16,7 +16,7 @@ import pytest
from homeassistant.bootstrap import async_setup_component
from homeassistant.components.dsmr.sensor import DerivativeDSMREntity
from homeassistant.const import TIME_HOURS, VOLUME_CUBIC_METERS
from homeassistant.const import ENERGY_KILO_WATT_HOUR, TIME_HOURS, VOLUME_CUBIC_METERS
from tests.common import assert_setup_component
@ -62,7 +62,7 @@ async def test_default_setup(hass, mock_connection_factory):
telegram = {
CURRENT_ELECTRICITY_USAGE: CosemObject(
[{"value": Decimal("0.0"), "unit": "kWh"}]
[{"value": Decimal("0.0"), "unit": ENERGY_KILO_WATT_HOUR}]
),
ELECTRICITY_ACTIVE_TARIFF: CosemObject([{"value": "0001", "unit": ""}]),
GAS_METER_READING: MBusObject(
@ -92,7 +92,9 @@ async def test_default_setup(hass, mock_connection_factory):
# ensure entities have new state value after incoming telegram
power_consumption = hass.states.get("sensor.power_consumption")
assert power_consumption.state == "0.0"
assert power_consumption.attributes.get("unit_of_measurement") == "kWh"
assert (
power_consumption.attributes.get("unit_of_measurement") == ENERGY_KILO_WATT_HOUR
)
# tariff should be translated in human readable and have no unit
power_tariff = hass.states.get("sensor.power_tariff")

View file

@ -2,7 +2,7 @@
from datetime import timedelta
from unittest.mock import patch
from homeassistant.const import TIME_SECONDS
from homeassistant.const import ENERGY_KILO_WATT_HOUR, TIME_SECONDS
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
@ -14,7 +14,7 @@ async def test_state(hass):
"platform": "integration",
"name": "integration",
"source": "sensor.power",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
"round": 2,
}
}
@ -36,7 +36,7 @@ async def test_state(hass):
# Testing a power sensor at 1 KiloWatts for 1hour = 1kWh
assert round(float(state.state), config["sensor"]["round"]) == 1.0
assert state.attributes.get("unit_of_measurement") == "kWh"
assert state.attributes.get("unit_of_measurement") == ENERGY_KILO_WATT_HOUR
async def test_trapezoidal(hass):
@ -46,7 +46,7 @@ async def test_trapezoidal(hass):
"platform": "integration",
"name": "integration",
"source": "sensor.power",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
"round": 2,
}
}
@ -69,7 +69,7 @@ async def test_trapezoidal(hass):
assert round(float(state.state), config["sensor"]["round"]) == 8.33
assert state.attributes.get("unit_of_measurement") == "kWh"
assert state.attributes.get("unit_of_measurement") == ENERGY_KILO_WATT_HOUR
async def test_left(hass):
@ -80,7 +80,7 @@ async def test_left(hass):
"name": "integration",
"method": "left",
"source": "sensor.power",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
"round": 2,
}
}
@ -103,7 +103,7 @@ async def test_left(hass):
assert round(float(state.state), config["sensor"]["round"]) == 7.5
assert state.attributes.get("unit_of_measurement") == "kWh"
assert state.attributes.get("unit_of_measurement") == ENERGY_KILO_WATT_HOUR
async def test_right(hass):
@ -114,7 +114,7 @@ async def test_right(hass):
"name": "integration",
"method": "right",
"source": "sensor.power",
"unit": "kWh",
"unit": ENERGY_KILO_WATT_HOUR,
"round": 2,
}
}
@ -137,7 +137,7 @@ async def test_right(hass):
assert round(float(state.state), config["sensor"]["round"]) == 9.17
assert state.attributes.get("unit_of_measurement") == "kWh"
assert state.attributes.get("unit_of_measurement") == ENERGY_KILO_WATT_HOUR
async def test_prefix(hass):
@ -170,7 +170,7 @@ async def test_prefix(hass):
# Testing a power sensor at 1000 Watts for 1hour = 1kWh
assert round(float(state.state), config["sensor"]["round"]) == 1.0
assert state.attributes.get("unit_of_measurement") == "kWh"
assert state.attributes.get("unit_of_measurement") == ENERGY_KILO_WATT_HOUR
async def test_suffix(hass):

View file

@ -40,7 +40,9 @@ async def prometheus_client(loop, hass, hass_client):
sensor2.entity_id = "sensor.radio_energy"
await sensor2.async_update_ha_state()
sensor3 = DemoSensor(None, "Electricity price", 0.123, None, "SEK/kWh", None)
sensor3 = DemoSensor(
None, "Electricity price", 0.123, None, f"SEK/{ENERGY_KILO_WATT_HOUR}", None
)
sensor3.hass = hass
sensor3.entity_id = "sensor.electricity_price"
await sensor3.async_update_ha_state()

View file

@ -2,7 +2,7 @@
import pytest
from homeassistant.components.pvpc_hourly_pricing import ATTR_TARIFF, DOMAIN
from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT
from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT, ENERGY_KILO_WATT_HOUR
from tests.common import load_fixture
from tests.test_util.aiohttp import AiohttpClientMocker
@ -15,7 +15,7 @@ FIXTURE_JSON_DATA_2019_10_29 = "PVPC_CURV_DD_2019_10_29.json"
def check_valid_state(state, tariff: str, value=None, key_attr=None):
"""Ensure that sensor has a valid state and attributes."""
assert state
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "€/kWh"
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == f"€/{ENERGY_KILO_WATT_HOUR}"
try:
_ = float(state.state)
# safety margins for current electricity price (it shouldn't be out of [0, 0.2])

View file

@ -11,7 +11,11 @@ from homeassistant.components.utility_meter.const import (
SERVICE_SELECT_NEXT_TARIFF,
SERVICE_SELECT_TARIFF,
)
from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START
from homeassistant.const import (
ATTR_ENTITY_ID,
ENERGY_KILO_WATT_HOUR,
EVENT_HOMEASSISTANT_START,
)
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
@ -36,13 +40,16 @@ async def test_services(hass):
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
entity_id = config[DOMAIN]["energy_bill"]["source"]
hass.states.async_set(entity_id, 1, {"unit_of_measurement": "kWh"})
hass.states.async_set(entity_id, 1, {"unit_of_measurement": ENERGY_KILO_WATT_HOUR})
await hass.async_block_till_done()
now = dt_util.utcnow() + timedelta(seconds=10)
with patch("homeassistant.util.dt.utcnow", return_value=now):
hass.states.async_set(
entity_id, 3, {"unit_of_measurement": "kWh"}, force_update=True
entity_id,
3,
{"unit_of_measurement": ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
@ -60,7 +67,10 @@ async def test_services(hass):
now += timedelta(seconds=10)
with patch("homeassistant.util.dt.utcnow", return_value=now):
hass.states.async_set(
entity_id, 4, {"unit_of_measurement": "kWh"}, force_update=True
entity_id,
4,
{"unit_of_measurement": ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
@ -78,7 +88,10 @@ async def test_services(hass):
now += timedelta(seconds=10)
with patch("homeassistant.util.dt.utcnow", return_value=now):
hass.states.async_set(
entity_id, 5, {"unit_of_measurement": "kWh"}, force_update=True
entity_id,
5,
{"unit_of_measurement": ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()

View file

@ -12,7 +12,11 @@ from homeassistant.components.utility_meter.const import (
SERVICE_CALIBRATE_METER,
SERVICE_SELECT_TARIFF,
)
from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START
from homeassistant.const import (
ATTR_ENTITY_ID,
ENERGY_KILO_WATT_HOUR,
EVENT_HOMEASSISTANT_START,
)
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
@ -48,13 +52,16 @@ async def test_state(hass):
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
entity_id = config[DOMAIN]["energy_bill"]["source"]
hass.states.async_set(entity_id, 2, {"unit_of_measurement": "kWh"})
hass.states.async_set(entity_id, 2, {"unit_of_measurement": ENERGY_KILO_WATT_HOUR})
await hass.async_block_till_done()
now = dt_util.utcnow() + timedelta(seconds=10)
with patch("homeassistant.util.dt.utcnow", return_value=now):
hass.states.async_set(
entity_id, 3, {"unit_of_measurement": "kWh"}, force_update=True
entity_id,
3,
{"unit_of_measurement": ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
@ -82,7 +89,10 @@ async def test_state(hass):
now = dt_util.utcnow() + timedelta(seconds=20)
with patch("homeassistant.util.dt.utcnow", return_value=now):
hass.states.async_set(
entity_id, 6, {"unit_of_measurement": "kWh"}, force_update=True
entity_id,
6,
{"unit_of_measurement": ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
@ -124,13 +134,16 @@ async def test_net_consumption(hass):
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
entity_id = config[DOMAIN]["energy_bill"]["source"]
hass.states.async_set(entity_id, 2, {"unit_of_measurement": "kWh"})
hass.states.async_set(entity_id, 2, {"unit_of_measurement": ENERGY_KILO_WATT_HOUR})
await hass.async_block_till_done()
now = dt_util.utcnow() + timedelta(seconds=10)
with patch("homeassistant.util.dt.utcnow", return_value=now):
hass.states.async_set(
entity_id, 1, {"unit_of_measurement": "kWh"}, force_update=True
entity_id,
1,
{"unit_of_measurement": ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
@ -154,13 +167,16 @@ async def test_non_net_consumption(hass):
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
entity_id = config[DOMAIN]["energy_bill"]["source"]
hass.states.async_set(entity_id, 2, {"unit_of_measurement": "kWh"})
hass.states.async_set(entity_id, 2, {"unit_of_measurement": ENERGY_KILO_WATT_HOUR})
await hass.async_block_till_done()
now = dt_util.utcnow() + timedelta(seconds=10)
with patch("homeassistant.util.dt.utcnow", return_value=now):
hass.states.async_set(
entity_id, 1, {"unit_of_measurement": "kWh"}, force_update=True
entity_id,
1,
{"unit_of_measurement": ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
@ -196,14 +212,19 @@ async def _test_self_reset(hass, config, start_time, expect_reset=True):
now = dt_util.parse_datetime(start_time)
with alter_time(now):
async_fire_time_changed(hass, now)
hass.states.async_set(entity_id, 1, {"unit_of_measurement": "kWh"})
hass.states.async_set(
entity_id, 1, {"unit_of_measurement": ENERGY_KILO_WATT_HOUR}
)
await hass.async_block_till_done()
now += timedelta(seconds=30)
with alter_time(now):
async_fire_time_changed(hass, now)
hass.states.async_set(
entity_id, 3, {"unit_of_measurement": "kWh"}, force_update=True
entity_id,
3,
{"unit_of_measurement": ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
@ -212,7 +233,10 @@ async def _test_self_reset(hass, config, start_time, expect_reset=True):
async_fire_time_changed(hass, now)
await hass.async_block_till_done()
hass.states.async_set(
entity_id, 6, {"unit_of_measurement": "kWh"}, force_update=True
entity_id,
6,
{"unit_of_measurement": ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()

View file

@ -116,12 +116,14 @@ def test_multilevelsensor_value_changed_other_units(mock_openzwave):
const.COMMAND_CLASS_METER,
]
)
value = MockValue(data=190.95555, units="kWh", node=node)
value = MockValue(
data=190.95555, units=homeassistant.const.ENERGY_KILO_WATT_HOUR, node=node
)
values = MockEntityValues(primary=value)
device = sensor.get_device(node=node, values=values, node_config={})
assert device.state == 190.96
assert device.unit_of_measurement == "kWh"
assert device.unit_of_measurement == homeassistant.const.ENERGY_KILO_WATT_HOUR
value.data = 197.95555
value_changed(value)
assert device.state == 197.96