From 706e8d56128787478c0f1a28061005db097a8a5e Mon Sep 17 00:00:00 2001 From: G Johansson Date: Tue, 28 Mar 2023 09:35:09 +0200 Subject: [PATCH] Add product calculation to Group sensor (#87373) * Group product * config flow --- homeassistant/components/group/config_flow.py | 1 + homeassistant/components/group/sensor.py | 14 ++++++++++++++ tests/components/group/test_sensor.py | 3 +++ 3 files changed, 18 insertions(+) diff --git a/homeassistant/components/group/config_flow.py b/homeassistant/components/group/config_flow.py index 069f74bf707..53a8fd06264 100644 --- a/homeassistant/components/group/config_flow.py +++ b/homeassistant/components/group/config_flow.py @@ -31,6 +31,7 @@ _STATISTIC_MEASURES = [ selector.SelectOptionDict(value="last", label="Most recently updated"), selector.SelectOptionDict(value="range", label="Statistical range"), selector.SelectOptionDict(value="sum", label="Sum"), + selector.SelectOptionDict(value="product", label="Product"), ] diff --git a/homeassistant/components/group/sensor.py b/homeassistant/components/group/sensor.py index 265e1640d06..4c6e8dccc1e 100644 --- a/homeassistant/components/group/sensor.py +++ b/homeassistant/components/group/sensor.py @@ -54,6 +54,7 @@ ATTR_LAST = "last" ATTR_LAST_ENTITY_ID = "last_entity_id" ATTR_RANGE = "range" ATTR_SUM = "sum" +ATTR_PRODUCT = "product" SENSOR_TYPES = { ATTR_MIN_VALUE: "min", ATTR_MAX_VALUE: "max", @@ -62,6 +63,7 @@ SENSOR_TYPES = { ATTR_LAST: "last", ATTR_RANGE: "range", ATTR_SUM: "sum", + ATTR_PRODUCT: "product", } SENSOR_TYPE_TO_ATTR = {v: k for k, v in SENSOR_TYPES.items()} @@ -226,6 +228,17 @@ def calc_sum( return {}, result +def calc_product( + sensor_values: list[tuple[str, float, State]] +) -> tuple[dict[str, str | None], float]: + """Calculate a product of values.""" + result = 1.0 + for _, sensor_value, _ in sensor_values: + result *= sensor_value + + return {}, result + + CALC_TYPES: dict[ str, Callable[ @@ -239,6 +252,7 @@ CALC_TYPES: dict[ "last": calc_last, "range": calc_range, "sum": calc_sum, + "product": calc_product, } diff --git a/tests/components/group/test_sensor.py b/tests/components/group/test_sensor.py index 5f85aa64854..39c9b788d56 100644 --- a/tests/components/group/test_sensor.py +++ b/tests/components/group/test_sensor.py @@ -1,6 +1,7 @@ """The tests for the Group Sensor platform.""" from __future__ import annotations +from math import prod import statistics from typing import Any from unittest.mock import patch @@ -45,6 +46,7 @@ MEAN = statistics.mean(VALUES) MEDIAN = statistics.median(VALUES) RANGE = max(VALUES) - min(VALUES) SUM_VALUE = sum(VALUES) +PRODUCT_VALUE = prod(VALUES) @pytest.mark.parametrize( @@ -57,6 +59,7 @@ SUM_VALUE = sum(VALUES) ("last", VALUES[2], {ATTR_LAST_ENTITY_ID: "sensor.test_3"}), ("range", RANGE, {}), ("sum", SUM_VALUE, {}), + ("product", PRODUCT_VALUE, {}), ], ) async def test_sensors(