mirror of
https://github.com/Electric-Special/ha-core.git
synced 2026-03-21 04:05:20 +01:00
Add charge control to NRGkick integration (new number platform) (#163273)
Co-authored-by: Josef Zweck <josef@zweck.dev>
This commit is contained in:
@@ -11,6 +11,7 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from .coordinator import NRGkickConfigEntry, NRGkickDataUpdateCoordinator
|
||||
|
||||
PLATFORMS: list[Platform] = [
|
||||
Platform.NUMBER,
|
||||
Platform.SENSOR,
|
||||
Platform.SWITCH,
|
||||
]
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
{
|
||||
"entity": {
|
||||
"number": {
|
||||
"current_set": {
|
||||
"default": "mdi:current-ac"
|
||||
},
|
||||
"energy_limit": {
|
||||
"default": "mdi:battery-charging-100"
|
||||
},
|
||||
"phase_count": {
|
||||
"default": "mdi:sine-wave"
|
||||
}
|
||||
},
|
||||
"sensor": {
|
||||
"charge_count": {
|
||||
"default": "mdi:counter"
|
||||
|
||||
155
homeassistant/components/nrgkick/number.py
Normal file
155
homeassistant/components/nrgkick/number.py
Normal file
@@ -0,0 +1,155 @@
|
||||
"""Number platform for NRGkick."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from nrgkick_api.const import (
|
||||
CONTROL_KEY_CURRENT_SET,
|
||||
CONTROL_KEY_ENERGY_LIMIT,
|
||||
CONTROL_KEY_PHASE_COUNT,
|
||||
)
|
||||
|
||||
from homeassistant.components.number import (
|
||||
NumberDeviceClass,
|
||||
NumberEntity,
|
||||
NumberEntityDescription,
|
||||
NumberMode,
|
||||
)
|
||||
from homeassistant.const import UnitOfElectricCurrent, UnitOfEnergy
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
|
||||
from .coordinator import NRGkickConfigEntry, NRGkickData, NRGkickDataUpdateCoordinator
|
||||
from .entity import NRGkickEntity
|
||||
|
||||
PARALLEL_UPDATES = 1
|
||||
|
||||
MIN_CHARGING_CURRENT = 6
|
||||
|
||||
|
||||
def _get_current_set_max(data: NRGkickData) -> float:
|
||||
"""Return the maximum current setpoint.
|
||||
|
||||
Uses the lower of the device rated current and the connector max current.
|
||||
The device always has a rated current; the connector may be absent.
|
||||
"""
|
||||
rated: float = data.info["general"]["rated_current"]
|
||||
connector_max = data.info.get("connector", {}).get("max_current")
|
||||
if connector_max is None:
|
||||
return rated
|
||||
return min(rated, float(connector_max))
|
||||
|
||||
|
||||
def _get_phase_count_max(data: NRGkickData) -> float:
|
||||
"""Return the maximum phase count based on the attached connector."""
|
||||
connector_phases = data.info.get("connector", {}).get("phase_count")
|
||||
if connector_phases is None:
|
||||
return 3.0
|
||||
return float(connector_phases)
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class NRGkickNumberEntityDescription(NumberEntityDescription):
|
||||
"""Class describing NRGkick number entities."""
|
||||
|
||||
value_fn: Callable[[NRGkickData], float | None]
|
||||
set_value_fn: Callable[[NRGkickDataUpdateCoordinator, float], Awaitable[Any]]
|
||||
max_value_fn: Callable[[NRGkickData], float] | None = None
|
||||
|
||||
|
||||
NUMBERS: tuple[NRGkickNumberEntityDescription, ...] = (
|
||||
NRGkickNumberEntityDescription(
|
||||
key="current_set",
|
||||
translation_key="current_set",
|
||||
device_class=NumberDeviceClass.CURRENT,
|
||||
native_unit_of_measurement=UnitOfElectricCurrent.AMPERE,
|
||||
native_min_value=MIN_CHARGING_CURRENT,
|
||||
native_step=0.1,
|
||||
mode=NumberMode.SLIDER,
|
||||
value_fn=lambda data: data.control.get(CONTROL_KEY_CURRENT_SET),
|
||||
set_value_fn=lambda coordinator, value: coordinator.api.set_current(value),
|
||||
max_value_fn=_get_current_set_max,
|
||||
),
|
||||
NRGkickNumberEntityDescription(
|
||||
key="energy_limit",
|
||||
translation_key="energy_limit",
|
||||
device_class=NumberDeviceClass.ENERGY,
|
||||
native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
|
||||
native_min_value=0,
|
||||
native_max_value=100000,
|
||||
native_step=1,
|
||||
mode=NumberMode.BOX,
|
||||
value_fn=lambda data: data.control.get(CONTROL_KEY_ENERGY_LIMIT),
|
||||
set_value_fn=lambda coordinator, value: coordinator.api.set_energy_limit(
|
||||
int(value)
|
||||
),
|
||||
),
|
||||
NRGkickNumberEntityDescription(
|
||||
key="phase_count",
|
||||
translation_key="phase_count",
|
||||
native_min_value=1,
|
||||
native_max_value=3,
|
||||
native_step=1,
|
||||
mode=NumberMode.SLIDER,
|
||||
value_fn=lambda data: data.control.get(CONTROL_KEY_PHASE_COUNT),
|
||||
set_value_fn=lambda coordinator, value: coordinator.api.set_phase_count(
|
||||
int(value)
|
||||
),
|
||||
max_value_fn=_get_phase_count_max,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
_hass: HomeAssistant,
|
||||
entry: NRGkickConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up NRGkick number entities based on a config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
async_add_entities(
|
||||
NRGkickNumber(coordinator, description) for description in NUMBERS
|
||||
)
|
||||
|
||||
|
||||
class NRGkickNumber(NRGkickEntity, NumberEntity):
|
||||
"""Representation of an NRGkick number entity."""
|
||||
|
||||
entity_description: NRGkickNumberEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: NRGkickDataUpdateCoordinator,
|
||||
description: NRGkickNumberEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize the number entity."""
|
||||
self.entity_description = description
|
||||
super().__init__(coordinator, description.key)
|
||||
|
||||
@property
|
||||
def native_max_value(self) -> float:
|
||||
"""Return the maximum value."""
|
||||
if self.entity_description.max_value_fn is not None:
|
||||
data = self.coordinator.data
|
||||
if TYPE_CHECKING:
|
||||
assert data is not None
|
||||
return self.entity_description.max_value_fn(data)
|
||||
return super().native_max_value
|
||||
|
||||
@property
|
||||
def native_value(self) -> float | None:
|
||||
"""Return the current value."""
|
||||
data = self.coordinator.data
|
||||
if TYPE_CHECKING:
|
||||
assert data is not None
|
||||
return self.entity_description.value_fn(data)
|
||||
|
||||
async def async_set_native_value(self, value: float) -> None:
|
||||
"""Set the value."""
|
||||
await self._async_call_api(
|
||||
self.entity_description.set_value_fn(self.coordinator, value)
|
||||
)
|
||||
@@ -44,6 +44,17 @@
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
"number": {
|
||||
"current_set": {
|
||||
"name": "Charging current"
|
||||
},
|
||||
"energy_limit": {
|
||||
"name": "Energy limit"
|
||||
},
|
||||
"phase_count": {
|
||||
"name": "Phase count"
|
||||
}
|
||||
},
|
||||
"sensor": {
|
||||
"cellular_mode": {
|
||||
"name": "Cellular mode",
|
||||
|
||||
179
tests/components/nrgkick/snapshots/test_number.ambr
Normal file
179
tests/components/nrgkick/snapshots/test_number.ambr
Normal file
@@ -0,0 +1,179 @@
|
||||
# serializer version: 1
|
||||
# name: test_number_entities[number.nrgkick_test_charging_current-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': set({
|
||||
}),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
'max': 32.0,
|
||||
'min': 6,
|
||||
'mode': <NumberMode.SLIDER: 'slider'>,
|
||||
'step': 0.1,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'number',
|
||||
'entity_category': None,
|
||||
'entity_id': 'number.nrgkick_test_charging_current',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Charging current',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <NumberDeviceClass.CURRENT: 'current'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Charging current',
|
||||
'platform': 'nrgkick',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'current_set',
|
||||
'unique_id': 'TEST123456_current_set',
|
||||
'unit_of_measurement': <UnitOfElectricCurrent.AMPERE: 'A'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_number_entities[number.nrgkick_test_charging_current-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'current',
|
||||
'friendly_name': 'NRGkick Test Charging current',
|
||||
'max': 32.0,
|
||||
'min': 6,
|
||||
'mode': <NumberMode.SLIDER: 'slider'>,
|
||||
'step': 0.1,
|
||||
'unit_of_measurement': <UnitOfElectricCurrent.AMPERE: 'A'>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'number.nrgkick_test_charging_current',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '16.0',
|
||||
})
|
||||
# ---
|
||||
# name: test_number_entities[number.nrgkick_test_energy_limit-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': set({
|
||||
}),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
'max': 100000,
|
||||
'min': 0,
|
||||
'mode': <NumberMode.BOX: 'box'>,
|
||||
'step': 1,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'number',
|
||||
'entity_category': None,
|
||||
'entity_id': 'number.nrgkick_test_energy_limit',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Energy limit',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <NumberDeviceClass.ENERGY: 'energy'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Energy limit',
|
||||
'platform': 'nrgkick',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'energy_limit',
|
||||
'unique_id': 'TEST123456_energy_limit',
|
||||
'unit_of_measurement': <UnitOfEnergy.WATT_HOUR: 'Wh'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_number_entities[number.nrgkick_test_energy_limit-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'energy',
|
||||
'friendly_name': 'NRGkick Test Energy limit',
|
||||
'max': 100000,
|
||||
'min': 0,
|
||||
'mode': <NumberMode.BOX: 'box'>,
|
||||
'step': 1,
|
||||
'unit_of_measurement': <UnitOfEnergy.WATT_HOUR: 'Wh'>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'number.nrgkick_test_energy_limit',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '0',
|
||||
})
|
||||
# ---
|
||||
# name: test_number_entities[number.nrgkick_test_phase_count-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': set({
|
||||
}),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
'max': 3.0,
|
||||
'min': 1,
|
||||
'mode': <NumberMode.SLIDER: 'slider'>,
|
||||
'step': 1,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'number',
|
||||
'entity_category': None,
|
||||
'entity_id': 'number.nrgkick_test_phase_count',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Phase count',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': 'Phase count',
|
||||
'platform': 'nrgkick',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'phase_count',
|
||||
'unique_id': 'TEST123456_phase_count',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_number_entities[number.nrgkick_test_phase_count-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'friendly_name': 'NRGkick Test Phase count',
|
||||
'max': 3.0,
|
||||
'min': 1,
|
||||
'mode': <NumberMode.SLIDER: 'slider'>,
|
||||
'step': 1,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'number.nrgkick_test_phase_count',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '3',
|
||||
})
|
||||
# ---
|
||||
180
tests/components/nrgkick/test_number.py
Normal file
180
tests/components/nrgkick/test_number.py
Normal file
@@ -0,0 +1,180 @@
|
||||
"""Tests for the NRGkick number platform."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from nrgkick_api import NRGkickCommandRejectedError
|
||||
from nrgkick_api.const import (
|
||||
CONTROL_KEY_CURRENT_SET,
|
||||
CONTROL_KEY_ENERGY_LIMIT,
|
||||
CONTROL_KEY_PHASE_COUNT,
|
||||
)
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.number import (
|
||||
ATTR_VALUE,
|
||||
DOMAIN as NUMBER_DOMAIN,
|
||||
SERVICE_SET_VALUE,
|
||||
)
|
||||
from homeassistant.const import ATTR_ENTITY_ID, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from . import setup_integration
|
||||
|
||||
from tests.common import MockConfigEntry, snapshot_platform
|
||||
|
||||
pytestmark = pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
|
||||
|
||||
async def test_number_entities(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_nrgkick_api: AsyncMock,
|
||||
entity_registry: er.EntityRegistry,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test number entities."""
|
||||
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
|
||||
|
||||
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
|
||||
|
||||
|
||||
async def test_set_charging_current(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_nrgkick_api: AsyncMock,
|
||||
) -> None:
|
||||
"""Test setting charging current calls the API and updates state."""
|
||||
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
|
||||
|
||||
entity_id = "number.nrgkick_test_charging_current"
|
||||
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.state == "16.0"
|
||||
|
||||
# Set current to 10A
|
||||
control_data = mock_nrgkick_api.get_control.return_value.copy()
|
||||
control_data[CONTROL_KEY_CURRENT_SET] = 10.0
|
||||
mock_nrgkick_api.get_control.return_value = control_data
|
||||
await hass.services.async_call(
|
||||
NUMBER_DOMAIN,
|
||||
SERVICE_SET_VALUE,
|
||||
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 10.0},
|
||||
blocking=True,
|
||||
)
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.state == "10.0"
|
||||
|
||||
mock_nrgkick_api.set_current.assert_awaited_once_with(10.0)
|
||||
|
||||
|
||||
async def test_set_energy_limit(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_nrgkick_api: AsyncMock,
|
||||
) -> None:
|
||||
"""Test setting energy limit calls the API and updates state."""
|
||||
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
|
||||
|
||||
entity_id = "number.nrgkick_test_energy_limit"
|
||||
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.state == "0"
|
||||
|
||||
# Set energy limit to 5000 Wh
|
||||
control_data = mock_nrgkick_api.get_control.return_value.copy()
|
||||
control_data[CONTROL_KEY_ENERGY_LIMIT] = 5000
|
||||
mock_nrgkick_api.get_control.return_value = control_data
|
||||
await hass.services.async_call(
|
||||
NUMBER_DOMAIN,
|
||||
SERVICE_SET_VALUE,
|
||||
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 5000},
|
||||
blocking=True,
|
||||
)
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.state == "5000"
|
||||
|
||||
mock_nrgkick_api.set_energy_limit.assert_awaited_once_with(5000)
|
||||
|
||||
|
||||
async def test_set_phase_count(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_nrgkick_api: AsyncMock,
|
||||
) -> None:
|
||||
"""Test setting phase count calls the API and updates state."""
|
||||
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
|
||||
|
||||
entity_id = "number.nrgkick_test_phase_count"
|
||||
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.state == "3"
|
||||
|
||||
# Set to 1 phase
|
||||
control_data = mock_nrgkick_api.get_control.return_value.copy()
|
||||
control_data[CONTROL_KEY_PHASE_COUNT] = 1
|
||||
mock_nrgkick_api.get_control.return_value = control_data
|
||||
await hass.services.async_call(
|
||||
NUMBER_DOMAIN,
|
||||
SERVICE_SET_VALUE,
|
||||
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 1},
|
||||
blocking=True,
|
||||
)
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.state == "1"
|
||||
|
||||
mock_nrgkick_api.set_phase_count.assert_awaited_once_with(1)
|
||||
|
||||
|
||||
async def test_number_command_rejected_by_device(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_nrgkick_api: AsyncMock,
|
||||
) -> None:
|
||||
"""Test number entity surfaces device rejection messages."""
|
||||
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
|
||||
|
||||
entity_id = "number.nrgkick_test_charging_current"
|
||||
|
||||
mock_nrgkick_api.set_current.side_effect = NRGkickCommandRejectedError(
|
||||
"Current change blocked by solar-charging"
|
||||
)
|
||||
|
||||
with pytest.raises(HomeAssistantError) as err:
|
||||
await hass.services.async_call(
|
||||
NUMBER_DOMAIN,
|
||||
SERVICE_SET_VALUE,
|
||||
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 10.0},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
assert err.value.translation_key == "command_rejected"
|
||||
assert err.value.translation_placeholders == {
|
||||
"reason": "Current change blocked by solar-charging"
|
||||
}
|
||||
|
||||
# State should reflect actual device control data (unchanged).
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.state == "16.0"
|
||||
|
||||
|
||||
async def test_charging_current_max_limited_by_connector(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_nrgkick_api: AsyncMock,
|
||||
) -> None:
|
||||
"""Test that the charging current max is limited by the connector."""
|
||||
# Device rated at 32A, but connector only supports 16A.
|
||||
mock_nrgkick_api.get_info.return_value["general"]["rated_current"] = 32.0
|
||||
mock_nrgkick_api.get_info.return_value["connector"]["max_current"] = 16.0
|
||||
|
||||
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
|
||||
|
||||
entity_id = "number.nrgkick_test_charging_current"
|
||||
|
||||
assert (state := hass.states.get(entity_id))
|
||||
assert state.attributes["max"] == 16.0
|
||||
Reference in New Issue
Block a user