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 all 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
2 changes: 1 addition & 1 deletion homeassistant/components/bmw_connected_drive/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
"documentation": "https://www.home-assistant.io/integrations/bmw_connected_drive",
"iot_class": "cloud_polling",
"loggers": ["bimmer_connected"],
"requirements": ["bimmer_connected==0.13.0"]
"requirements": ["bimmer_connected==0.13.2"]
MartinHjelmare marked this conversation as resolved.
Show resolved Hide resolved
}
120 changes: 120 additions & 0 deletions homeassistant/components/bmw_connected_drive/number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""Number platform for BMW."""

from collections.abc import Callable, Coroutine
from dataclasses import dataclass
import logging
from typing import Any

from bimmer_connected.models import MyBMWAPIError
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.exceptions import HomeAssistantError
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_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,
)
try:
await self.entity_description.remote_service(self.vehicle, value)
except MyBMWAPIError as ex:
raise HomeAssistantError(ex) from ex
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
2 changes: 1 addition & 1 deletion requirements_all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ beautifulsoup4==4.11.1
bellows==0.35.0

# homeassistant.components.bmw_connected_drive
bimmer_connected==0.13.0
bimmer_connected==0.13.2

# homeassistant.components.bizkaibus
bizkaibus==0.1.1
Expand Down
2 changes: 1 addition & 1 deletion requirements_test_all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ beautifulsoup4==4.11.1
bellows==0.35.0

# homeassistant.components.bmw_connected_drive
bimmer_connected==0.13.0
bimmer_connected==0.13.2

# homeassistant.components.bluetooth
bleak-retry-connector==3.0.2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,22 @@
}),
]),
}),
'climate': dict({
'account_timezone': dict({
'_dst_offset': '0:00:00',
'_dst_saved': '0:00:00',
'_hasdst': False,
'_std_offset': '0:00:00',
'_tznames': list([
'UTC',
'UTC',
]),
}),
'activity': 'STANDBY',
'activity_end_time': None,
'activity_end_time_no_tz': None,
'is_climate_on': False,
}),
'condition_based_services': dict({
'is_service_required': False,
'messages': list([
Expand Down Expand Up @@ -808,6 +824,32 @@
]),
'name': 'i4 eDrive40',
'timestamp': '2023-01-04T14:57:06+00:00',
'tires': dict({
'front_left': dict({
'current_pressure': 241,
'manufacturing_week': '2021-10-04T00:00:00',
'season': 2,
'target_pressure': 269,
}),
'front_right': dict({
'current_pressure': 255,
'manufacturing_week': '2019-06-10T00:00:00',
'season': 2,
'target_pressure': 269,
}),
'rear_left': dict({
'current_pressure': 324,
'manufacturing_week': '2019-03-18T00:00:00',
'season': 2,
'target_pressure': 303,
}),
'rear_right': dict({
'current_pressure': 331,
'manufacturing_week': '2019-03-18T00:00:00',
'season': 2,
'target_pressure': 303,
}),
}),
'vehicle_location': dict({
'account_region': 'row',
'heading': '**REDACTED**',
Expand Down Expand Up @@ -969,6 +1011,22 @@
'messages': list([
]),
}),
'climate': dict({
'account_timezone': dict({
'_dst_offset': '0:00:00',
'_dst_saved': '0:00:00',
'_hasdst': False,
'_std_offset': '0:00:00',
'_tznames': list([
'UTC',
'UTC',
]),
}),
'activity': 'UNKNOWN',
'activity_end_time': None,
'activity_end_time_no_tz': None,
'is_climate_on': False,
}),
'condition_based_services': dict({
'is_service_required': False,
'messages': list([
Expand Down Expand Up @@ -1466,6 +1524,7 @@
]),
'name': 'i3 (+ REX)',
'timestamp': '2022-07-10T09:25:53+00:00',
'tires': None,
'vehicle_location': dict({
'account_region': 'row',
'heading': None,
Expand Down Expand Up @@ -2456,6 +2515,22 @@
'messages': list([
]),
}),
'climate': dict({
'account_timezone': dict({
'_dst_offset': '0:00:00',
'_dst_saved': '0:00:00',
'_hasdst': False,
'_std_offset': '0:00:00',
'_tznames': list([
'UTC',
'UTC',
]),
}),
'activity': 'UNKNOWN',
'activity_end_time': None,
'activity_end_time_no_tz': None,
'is_climate_on': False,
}),
'condition_based_services': dict({
'is_service_required': False,
'messages': list([
Expand Down Expand Up @@ -2953,6 +3028,7 @@
]),
'name': 'i3 (+ REX)',
'timestamp': '2022-07-10T09:25:53+00:00',
'tires': None,
'vehicle_location': dict({
'account_region': 'row',
'heading': None,
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
Loading