Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move BMW Target SoC to number platform #91081

Merged
merged 7 commits into from
Apr 29, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions homeassistant/components/bmw_connected_drive/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
Platform.DEVICE_TRACKER,
Platform.LOCK,
Platform.NOTIFY,
Platform.NUMBER,
Platform.SELECT,
Platform.SENSOR,
]
Expand Down
115 changes: 115 additions & 0 deletions homeassistant/components/bmw_connected_drive/number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""Number platform for BMW."""
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
import logging
from typing import Any

from bimmer_connected.vehicle import MyBMWVehicle

from homeassistant.components.number import (
NumberDeviceClass,
NumberEntity,
NumberEntityDescription,
NumberMode,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from . import BMWBaseEntity
from .const import DOMAIN
from .coordinator import BMWDataUpdateCoordinator

_LOGGER = logging.getLogger(__name__)


@dataclass
class BMWRequiredKeysMixin:
"""Mixin for required keys."""

value_fn: Callable[[MyBMWVehicle], float | int | None]
remote_service: Callable[[MyBMWVehicle, float | int], Coroutine[Any, Any, Any]]


@dataclass
class BMWNumberEntityDescription(NumberEntityDescription, BMWRequiredKeysMixin):
"""Describes BMW number entity."""

is_available: Callable[[MyBMWVehicle], bool] = lambda _: False
dynamic_options: Callable[[MyBMWVehicle], list[str]] | None = None
mode: NumberMode = NumberMode.AUTO


NUMBER_TYPES: list[BMWNumberEntityDescription] = [
BMWNumberEntityDescription(
key="target_soc",
name="Target SoC",
device_class=NumberDeviceClass.BATTERY,
is_available=lambda v: v.is_remote_set_target_soc_enabled,
native_max_value=100.0,
native_min_value=20.0,
native_step=5.0,
mode=NumberMode.SLIDER,
value_fn=lambda v: v.fuel_and_battery.charging_target,
remote_service=lambda v, o: v.remote_services.trigger_charging_settings_update(
target_soc=int(o)
),
icon="mdi:battery-charging-medium",
),
]


async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the MyBMW number from config entry."""
coordinator: BMWDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]

entities: list[BMWNumber] = []

for vehicle in coordinator.account.vehicles:
if not coordinator.read_only:
entities.extend(
[
BMWNumber(coordinator, vehicle, description)
for description in NUMBER_TYPES
if description.is_available(vehicle)
]
)
async_add_entities(entities)


class BMWNumber(BMWBaseEntity, NumberEntity):
"""Representation of BMW Number entity."""

entity_description: BMWNumberEntityDescription

def __init__(
self,
coordinator: BMWDataUpdateCoordinator,
vehicle: MyBMWVehicle,
description: BMWNumberEntityDescription,
) -> None:
"""Initialize an BMW Number."""
super().__init__(coordinator, vehicle)
self.entity_description = description
self._attr_unique_id = f"{vehicle.vin}-{description.key}"
self._attr_native_value = description.value_fn(vehicle)
rikroe marked this conversation as resolved.
Show resolved Hide resolved
self._attr_mode = description.mode

@property
def native_value(self) -> float | None:
"""Return the entity value to represent the entity state."""
return self.entity_description.value_fn(self.vehicle)

async def async_set_native_value(self, value: float) -> None:
"""Update to the vehicle."""
_LOGGER.debug(
"Executing '%s' on vehicle '%s' to value '%s'",
self.entity_description.key,
self.vehicle.vin,
value,
)
await self.entity_description.remote_service(self.vehicle, value)
MartinHjelmare marked this conversation as resolved.
Show resolved Hide resolved
15 changes: 1 addition & 14 deletions homeassistant/components/bmw_connected_drive/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import PERCENTAGE, UnitOfElectricCurrent
from homeassistant.const import UnitOfElectricCurrent
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback

Expand Down Expand Up @@ -37,19 +37,6 @@ class BMWSelectEntityDescription(SelectEntityDescription, BMWRequiredKeysMixin):


SELECT_TYPES: dict[str, BMWSelectEntityDescription] = {
# --- Generic ---
"target_soc": BMWSelectEntityDescription(
key="target_soc",
name="Target SoC",
is_available=lambda v: v.is_remote_set_target_soc_enabled,
options=[str(i * 5 + 20) for i in range(17)],
current_option=lambda v: str(v.fuel_and_battery.charging_target),
remote_service=lambda v, o: v.remote_services.trigger_charging_settings_update(
target_soc=int(o)
),
icon="mdi:battery-charging-medium",
unit_of_measurement=PERCENTAGE,
),
"ac_limit": BMWSelectEntityDescription(
key="ac_limit",
name="AC Charging Limit",
Expand Down
22 changes: 22 additions & 0 deletions tests/components/bmw_connected_drive/snapshots/test_number.ambr
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# serializer version: 1
# name: test_entity_state_attrs
list([
StateSnapshot({
'attributes': ReadOnlyDict({
'attribution': 'Data provided by MyBMW',
'device_class': 'battery',
'friendly_name': 'i4 eDrive40 Target SoC',
'icon': 'mdi:battery-charging-medium',
'max': 100.0,
'min': 20.0,
'mode': <NumberMode.SLIDER: 'slider'>,
'step': 5.0,
}),
'context': <ANY>,
'entity_id': 'number.i4_edrive40_target_soc',
'last_changed': <ANY>,
'last_updated': <ANY>,
'state': '80',
}),
])
# ---
32 changes: 0 additions & 32 deletions tests/components/bmw_connected_drive/snapshots/test_select.ambr
Original file line number Diff line number Diff line change
@@ -1,38 +1,6 @@
# serializer version: 1
# name: test_entity_state_attrs
list([
StateSnapshot({
'attributes': ReadOnlyDict({
'attribution': 'Data provided by MyBMW',
'friendly_name': 'i4 eDrive40 Target SoC',
'icon': 'mdi:battery-charging-medium',
'options': list([
'20',
'25',
'30',
'35',
'40',
'45',
'50',
'55',
'60',
'65',
'70',
'75',
'80',
'85',
'90',
'95',
'100',
]),
'unit_of_measurement': '%',
}),
'context': <ANY>,
'entity_id': 'select.i4_edrive40_target_soc',
'last_changed': <ANY>,
'last_updated': <ANY>,
'state': '80',
}),
StateSnapshot({
'attributes': ReadOnlyDict({
'attribution': 'Data provided by MyBMW',
Expand Down
80 changes: 80 additions & 0 deletions tests/components/bmw_connected_drive/test_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"""Test BMW numbers."""
from bimmer_connected.vehicle.remote_services import RemoteServices
import pytest
import respx
from syrupy.assertion import SnapshotAssertion

from homeassistant.core import HomeAssistant

from . import setup_mocked_integration


async def test_entity_state_attrs(
hass: HomeAssistant,
bmw_fixture: respx.Router,
snapshot: SnapshotAssertion,
) -> None:
"""Test number options and values.."""

# Setup component
assert await setup_mocked_integration(hass)

# Get all number entities
assert hass.states.async_all("number") == snapshot


@pytest.mark.parametrize(
("entity_id", "value"),
[
("number.i4_edrive40_target_soc", "80"),
],
)
async def test_update_triggers_success(
hass: HomeAssistant,
entity_id: str,
value: str,
bmw_fixture: respx.Router,
) -> None:
"""Test allowed values for number inputs."""

# Setup component
assert await setup_mocked_integration(hass)

# Test
await hass.services.async_call(
"number",
"set_value",
service_data={"value": value},
blocking=True,
target={"entity_id": entity_id},
)
assert RemoteServices.trigger_remote_service.call_count == 1


@pytest.mark.parametrize(
("entity_id", "value"),
[
("number.i4_edrive40_target_soc", "81"),
],
)
async def test_update_triggers_fail(
hass: HomeAssistant,
entity_id: str,
value: str,
bmw_fixture: respx.Router,
) -> None:
"""Test not allowed values for number inputs."""

# Setup component
assert await setup_mocked_integration(hass)

# Test
with pytest.raises(ValueError):
await hass.services.async_call(
"number",
"set_value",
service_data={"value": value},
blocking=True,
target={"entity_id": entity_id},
)
assert RemoteServices.trigger_remote_service.call_count == 0
2 changes: 0 additions & 2 deletions tests/components/bmw_connected_drive/test_select.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ async def test_entity_state_attrs(
[
("select.i3_rex_charging_mode", "IMMEDIATE_CHARGING"),
("select.i4_edrive40_ac_charging_limit", "16"),
("select.i4_edrive40_target_soc", "80"),
("select.i4_edrive40_charging_mode", "DELAYED_CHARGING"),
],
)
Expand Down Expand Up @@ -58,7 +57,6 @@ async def test_update_triggers_success(
("entity_id", "value"),
[
("select.i4_edrive40_ac_charging_limit", "17"),
("select.i4_edrive40_target_soc", "81"),
],
)
async def test_update_triggers_fail(
Expand Down