mirror of
https://github.com/home-assistant/core.git
synced 2026-09-26 01:11:51 -04:00
Add Besen charging current control (#180617)
This commit is contained in:
@@ -7,4 +7,4 @@ from homeassistant.const import Platform
|
||||
DOMAIN: Final = "besen"
|
||||
NAME: Final = "Besen"
|
||||
|
||||
PLATFORMS: Final = [Platform.SENSOR, Platform.SWITCH]
|
||||
PLATFORMS: Final = [Platform.NUMBER, Platform.SENSOR, Platform.SWITCH]
|
||||
|
||||
@@ -90,6 +90,11 @@ class BesenCoordinator(DataUpdateCoordinator[BesenData]):
|
||||
|
||||
await self._async_run_command(self.client.async_stop_charging())
|
||||
|
||||
async def async_set_charge_amps(self, amps: int) -> None:
|
||||
"""Set the charging current."""
|
||||
|
||||
await self._async_run_command(self.client.async_set_charge_amps(amps))
|
||||
|
||||
async def _async_run_command(self, command: Awaitable[None]) -> None:
|
||||
"""Run a charger command and translate command failures."""
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Number platform for Besen."""
|
||||
|
||||
from typing import override
|
||||
|
||||
from besen.const import FALLBACK_MAX_CHARGE_AMPS, MIN_CHARGE_AMPS
|
||||
|
||||
from homeassistant.components.number import NumberDeviceClass, NumberEntity, NumberMode
|
||||
from homeassistant.const import EntityCategory, UnitOfElectricCurrent
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
|
||||
from . import BesenConfigEntry
|
||||
from .coordinator import BesenCoordinator
|
||||
from .entity import BesenEntity
|
||||
|
||||
PARALLEL_UPDATES = 0
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: BesenConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up the Besen number platform."""
|
||||
|
||||
async_add_entities([BesenChargingCurrentNumber(entry.runtime_data)])
|
||||
|
||||
|
||||
class BesenChargingCurrentNumber(BesenEntity, NumberEntity):
|
||||
"""Charging current control."""
|
||||
|
||||
_attr_device_class = NumberDeviceClass.CURRENT
|
||||
_attr_entity_category = EntityCategory.CONFIG
|
||||
_attr_mode = NumberMode.BOX
|
||||
_attr_native_min_value = MIN_CHARGE_AMPS
|
||||
_attr_native_step = 1
|
||||
_attr_native_unit_of_measurement = UnitOfElectricCurrent.AMPERE
|
||||
|
||||
def __init__(self, coordinator: BesenCoordinator) -> None:
|
||||
"""Initialize the charging current control."""
|
||||
|
||||
super().__init__(coordinator, "charging_current")
|
||||
|
||||
@property
|
||||
@override
|
||||
def native_max_value(self) -> float:
|
||||
"""Return the maximum charging current."""
|
||||
|
||||
return self.coordinator.data.info.output_max_amps or FALLBACK_MAX_CHARGE_AMPS
|
||||
|
||||
@property
|
||||
@override
|
||||
def native_value(self) -> float | None:
|
||||
"""Return the configured charging current."""
|
||||
|
||||
return self.coordinator.data.config.charge_amps
|
||||
|
||||
@override
|
||||
async def async_set_native_value(self, value: float) -> None:
|
||||
"""Set the charging current."""
|
||||
|
||||
await self.coordinator.async_set_charge_amps(int(value))
|
||||
@@ -38,6 +38,9 @@
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
"number": {
|
||||
"charging_current": { "name": "Charging current" }
|
||||
},
|
||||
"sensor": {
|
||||
"charging_power": { "name": "Charging power" },
|
||||
"external_temperature": { "name": "External temperature" },
|
||||
|
||||
@@ -50,6 +50,8 @@ FAKE_SERVICE_INFO = BluetoothServiceInfoBleak(
|
||||
def charger_state(
|
||||
*,
|
||||
charger_status: bool | None = True,
|
||||
charge_amps: int | None = 16,
|
||||
output_max_amps: int | None = 32,
|
||||
available: bool = True,
|
||||
authenticated: bool = True,
|
||||
phases: int = 1,
|
||||
@@ -66,8 +68,13 @@ def charger_state(
|
||||
model="BS20",
|
||||
hardware_version="HW1",
|
||||
software_version="SW1",
|
||||
output_max_amps=output_max_amps,
|
||||
),
|
||||
config=ChargerConfig(
|
||||
charge_amps=charge_amps,
|
||||
device_name="Garage",
|
||||
rssi=-55,
|
||||
),
|
||||
config=ChargerConfig(device_name="Garage", rssi=-55),
|
||||
charge=(
|
||||
charge
|
||||
if charge is not None
|
||||
@@ -100,6 +107,7 @@ def _configure_client_mock(client: Mock) -> None:
|
||||
client.async_stop = AsyncMock()
|
||||
client.async_start_charging = AsyncMock()
|
||||
client.async_stop_charging = AsyncMock()
|
||||
client.async_set_charge_amps = AsyncMock()
|
||||
client.add_listener.return_value = Mock()
|
||||
|
||||
|
||||
@@ -157,8 +165,12 @@ def mock_besen_client() -> Generator[Mock]:
|
||||
async def async_stop_charging() -> None:
|
||||
publish_besen_state(client, charger_state(charger_status=False))
|
||||
|
||||
async def async_set_charge_amps(amps: int) -> None:
|
||||
publish_besen_state(client, charger_state(charge_amps=amps))
|
||||
|
||||
client.async_start_charging.side_effect = async_start_charging
|
||||
client.async_stop_charging.side_effect = async_stop_charging
|
||||
client.async_set_charge_amps.side_effect = async_set_charge_amps
|
||||
yield client
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# serializer version: 1
|
||||
# name: test_number_state[number.garage_charging_current-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<NumberEntityCapabilityAttribute.MAX: 'max'>: 32,
|
||||
<NumberEntityCapabilityAttribute.MIN: 'min'>: 6,
|
||||
<NumberEntityCapabilityAttribute.MODE: 'mode'>: <NumberMode.BOX: 'box'>,
|
||||
<NumberEntityCapabilityAttribute.STEP: 'step'>: 1,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'number',
|
||||
'entity_category': <EntityCategory.CONFIG: 'config'>,
|
||||
'entity_id': 'number.garage_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': 'besen',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'charging_current',
|
||||
'unique_id': 'AA:BB_charging_current',
|
||||
'unit_of_measurement': <UnitOfElectricCurrent.AMPERE: 'A'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_number_state[number.garage_charging_current-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'current',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Garage Charging current',
|
||||
<NumberEntityCapabilityAttribute.MAX: 'max'>: 32,
|
||||
<NumberEntityCapabilityAttribute.MIN: 'min'>: 6,
|
||||
<NumberEntityCapabilityAttribute.MODE: 'mode'>: <NumberMode.BOX: 'box'>,
|
||||
<NumberEntityCapabilityAttribute.STEP: 'step'>: 1,
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: <UnitOfElectricCurrent.AMPERE: 'A'>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'number.garage_charging_current',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '16',
|
||||
})
|
||||
# ---
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Tests for the Besen number platform."""
|
||||
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
from besen.const import FALLBACK_MAX_CHARGE_AMPS
|
||||
from besen.exceptions import CommandFailed
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.besen.const import DOMAIN
|
||||
from homeassistant.components.number import (
|
||||
ATTR_MAX,
|
||||
ATTR_VALUE,
|
||||
DOMAIN as NUMBER_DOMAIN,
|
||||
SERVICE_SET_VALUE,
|
||||
)
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID,
|
||||
STATE_UNAVAILABLE,
|
||||
STATE_UNKNOWN,
|
||||
Platform,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.helpers.entity_component import async_update_entity
|
||||
|
||||
from . import publish_besen_state
|
||||
from .conftest import charger_state, setup_integration
|
||||
|
||||
from tests.common import MockConfigEntry, snapshot_platform
|
||||
|
||||
ENTITY_ID = "number.garage_charging_current"
|
||||
|
||||
|
||||
async def test_number_state(
|
||||
hass: HomeAssistant,
|
||||
snapshot: SnapshotAssertion,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_besen_client: Mock,
|
||||
) -> None:
|
||||
"""Test number entity state and registry data."""
|
||||
|
||||
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
|
||||
|
||||
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
|
||||
mock_besen_client.async_start.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_number_updates_from_client(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_besen_client: Mock,
|
||||
) -> None:
|
||||
"""Test number state updates from client push data."""
|
||||
|
||||
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
|
||||
|
||||
publish_besen_state(mock_besen_client, charger_state(charge_amps=20))
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
assert state is not None
|
||||
assert state.state == "20"
|
||||
|
||||
|
||||
async def test_number_updates_on_refresh(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_besen_client: Mock,
|
||||
) -> None:
|
||||
"""Test number state updates when the coordinator refreshes."""
|
||||
|
||||
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
|
||||
|
||||
mock_besen_client.state = charger_state(charge_amps=20)
|
||||
await async_update_entity(hass, ENTITY_ID)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
assert state is not None
|
||||
assert state.state == "20"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("available", "authenticated"),
|
||||
[
|
||||
(False, True),
|
||||
(True, False),
|
||||
],
|
||||
)
|
||||
async def test_number_unavailable_from_client_state(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_besen_client: Mock,
|
||||
available: bool,
|
||||
authenticated: bool,
|
||||
) -> None:
|
||||
"""Test number availability follows client availability and authentication."""
|
||||
|
||||
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
|
||||
|
||||
publish_besen_state(
|
||||
mock_besen_client,
|
||||
charger_state(available=available, authenticated=authenticated),
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
assert state is not None
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
|
||||
|
||||
async def test_number_unknown_without_reported_current(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_besen_client: Mock,
|
||||
) -> None:
|
||||
"""Test the number is unknown before the charger reports its current."""
|
||||
|
||||
mock_besen_client.state = charger_state(charge_amps=None)
|
||||
|
||||
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
|
||||
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
assert state is not None
|
||||
assert state.state == STATE_UNKNOWN
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("output_max_amps", "expected_max"),
|
||||
[
|
||||
(16, 16),
|
||||
(None, FALLBACK_MAX_CHARGE_AMPS),
|
||||
],
|
||||
)
|
||||
async def test_number_maximum(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_besen_client: Mock,
|
||||
output_max_amps: int | None,
|
||||
expected_max: int,
|
||||
) -> None:
|
||||
"""Test the maximum uses charger information with a safe fallback."""
|
||||
|
||||
mock_besen_client.state = charger_state(
|
||||
charge_amps=16,
|
||||
output_max_amps=output_max_amps,
|
||||
)
|
||||
|
||||
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
|
||||
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
assert state is not None
|
||||
assert state.attributes[ATTR_MAX] == expected_max
|
||||
|
||||
|
||||
async def test_number_set_value(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_besen_client: Mock,
|
||||
) -> None:
|
||||
"""Test setting the charging current calls the client and updates state."""
|
||||
|
||||
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
|
||||
|
||||
await hass.services.async_call(
|
||||
NUMBER_DOMAIN,
|
||||
SERVICE_SET_VALUE,
|
||||
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_VALUE: 20},
|
||||
blocking=True,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
mock_besen_client.async_set_charge_amps.assert_awaited_once_with(20)
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
assert state is not None
|
||||
assert state.state == "20"
|
||||
|
||||
|
||||
async def test_number_command_failure(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_besen_client: Mock,
|
||||
) -> None:
|
||||
"""Test command failures are translated to Home Assistant errors."""
|
||||
|
||||
mock_besen_client.async_set_charge_amps = AsyncMock(
|
||||
side_effect=CommandFailed("failed")
|
||||
)
|
||||
|
||||
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
|
||||
|
||||
with pytest.raises(HomeAssistantError) as err:
|
||||
await hass.services.async_call(
|
||||
NUMBER_DOMAIN,
|
||||
SERVICE_SET_VALUE,
|
||||
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_VALUE: 20},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
assert err.value.translation_domain == DOMAIN
|
||||
assert err.value.translation_key == "command_failed"
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
assert state is not None
|
||||
assert state.state == "16"
|
||||
Reference in New Issue
Block a user