|
| 1 | +# Copyright (c) 2025, Kris Van Biesen <kvanbiesen@gmail.com>, Renaud Allard <renaud@allard.it>, Jyri Saukkonen <jyri.saukkonen+jjyksi@gmail.com> |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# Redistribution and use in source and binary forms, with or without |
| 5 | +# modification, are permitted provided that the following conditions are met: |
| 6 | +# |
| 7 | +# 1. Redistributions of source code must retain the above copyright notice, |
| 8 | +# this list of conditions and the following disclaimer. |
| 9 | +# |
| 10 | +# 2. Redistributions in binary form must reproduce the above copyright notice, |
| 11 | +# this list of conditions and the following disclaimer in the documentation |
| 12 | +# and/or other materials provided with the distribution. |
| 13 | +# |
| 14 | +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 15 | +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 16 | +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 17 | +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |
| 18 | +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 19 | +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 20 | +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 21 | +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 22 | +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 23 | +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 24 | +# POSSIBILITY OF SUCH DAMAGE. |
| 25 | + |
| 26 | +"""Number entities for BMW CarData integration.""" |
| 27 | + |
| 28 | +from __future__ import annotations |
| 29 | + |
| 30 | +import logging |
| 31 | +from typing import TYPE_CHECKING |
| 32 | + |
| 33 | +from homeassistant.components.number import NumberEntity, NumberMode |
| 34 | +from homeassistant.config_entries import ConfigEntry |
| 35 | +from homeassistant.const import EntityCategory, UnitOfEnergy |
| 36 | +from homeassistant.core import HomeAssistant |
| 37 | +from homeassistant.helpers.device_registry import DeviceInfo |
| 38 | +from homeassistant.helpers.entity_platform import AddEntitiesCallback |
| 39 | +from homeassistant.helpers.restore_state import RestoreEntity |
| 40 | + |
| 41 | +from .const import DOMAIN, MANUAL_CAPACITY_DESCRIPTOR |
| 42 | +from .utils import redact_vin |
| 43 | + |
| 44 | +if TYPE_CHECKING: |
| 45 | + from .coordinator import CardataCoordinator |
| 46 | + from .runtime import CardataRuntimeData |
| 47 | + |
| 48 | +_LOGGER = logging.getLogger(__name__) |
| 49 | + |
| 50 | + |
| 51 | +async def async_setup_entry( |
| 52 | + hass: HomeAssistant, |
| 53 | + entry: ConfigEntry, |
| 54 | + async_add_entities: AddEntitiesCallback, |
| 55 | +) -> None: |
| 56 | + """Set up BMW CarData number entities.""" |
| 57 | + runtime: CardataRuntimeData = hass.data[DOMAIN][entry.entry_id] |
| 58 | + coordinator = runtime.coordinator |
| 59 | + |
| 60 | + entities: list[NumberEntity] = [] |
| 61 | + |
| 62 | + # Create manual battery capacity input for each known EV/PHEV vehicle |
| 63 | + for vin in coordinator.data.keys(): |
| 64 | + # Check if this vehicle has HV battery (EV/PHEV) |
| 65 | + vehicle_data = coordinator.data.get(vin, {}) |
| 66 | + if "vehicle.drivetrain.batteryManagement.header" in vehicle_data: |
| 67 | + vehicle_name = coordinator.names.get(vin, redact_vin(vin)) |
| 68 | + |
| 69 | + entities.append( |
| 70 | + ManualBatteryCapacityNumber( |
| 71 | + coordinator=coordinator, |
| 72 | + vin=vin, |
| 73 | + vehicle_name=vehicle_name, |
| 74 | + entry_id=entry.entry_id, |
| 75 | + ) |
| 76 | + ) |
| 77 | + _LOGGER.debug("Created manual battery capacity input for %s (%s)", vehicle_name, redact_vin(vin)) |
| 78 | + |
| 79 | + if entities: |
| 80 | + async_add_entities(entities) |
| 81 | + _LOGGER.debug("Added %d number entities", len(entities)) |
| 82 | + |
| 83 | + |
| 84 | +class ManualBatteryCapacityNumber(NumberEntity, RestoreEntity): |
| 85 | + """Number entity for manual battery capacity input.""" |
| 86 | + |
| 87 | + _attr_icon = "mdi:car-battery" |
| 88 | + _attr_entity_category = EntityCategory.CONFIG |
| 89 | + _attr_has_entity_name = True |
| 90 | + _attr_native_min_value = 0.0 |
| 91 | + _attr_native_max_value = 150.0 |
| 92 | + _attr_native_step = 0.1 |
| 93 | + _attr_native_unit_of_measurement = UnitOfEnergy.KILO_WATT_HOUR |
| 94 | + _attr_mode = NumberMode.BOX |
| 95 | + _attr_entity_registry_enabled_default = False |
| 96 | + |
| 97 | + def __init__( |
| 98 | + self, |
| 99 | + coordinator: CardataCoordinator, |
| 100 | + vin: str, |
| 101 | + vehicle_name: str, |
| 102 | + entry_id: str, |
| 103 | + ) -> None: |
| 104 | + """Initialize the number entity.""" |
| 105 | + self._coordinator = coordinator |
| 106 | + self._vin = vin |
| 107 | + self._attr_unique_id = f"{vin}_{MANUAL_CAPACITY_DESCRIPTOR}" |
| 108 | + self._attr_name = "Manual Battery Capacity" |
| 109 | + self._attr_device_info = DeviceInfo( |
| 110 | + identifiers={(DOMAIN, vin)}, |
| 111 | + name=vehicle_name, |
| 112 | + ) |
| 113 | + |
| 114 | + async def async_added_to_hass(self) -> None: |
| 115 | + """Restore previous value when entity is added.""" |
| 116 | + await super().async_added_to_hass() |
| 117 | + |
| 118 | + # Restore previous value |
| 119 | + last_state = await self.async_get_last_state() |
| 120 | + last_number_data = await self.async_get_last_number_data() |
| 121 | + |
| 122 | + if last_number_data is not None and last_number_data.native_value is not None: |
| 123 | + value = last_number_data.native_value |
| 124 | + # Store restored value in coordinator |
| 125 | + if value > 0: |
| 126 | + self._coordinator.set_manual_battery_capacity(self._vin, value) |
| 127 | + _LOGGER.debug( |
| 128 | + "Restored manual battery capacity for %s: %.1f kWh", |
| 129 | + redact_vin(self._vin), |
| 130 | + value, |
| 131 | + ) |
| 132 | + self._attr_native_value = value |
| 133 | + elif last_state is not None and last_state.state not in ("unknown", "unavailable"): |
| 134 | + try: |
| 135 | + value = float(last_state.state) |
| 136 | + if value > 0: |
| 137 | + self._coordinator.set_manual_battery_capacity(self._vin, value) |
| 138 | + _LOGGER.debug( |
| 139 | + "Restored manual battery capacity for %s: %.1f kWh", |
| 140 | + redact_vin(self._vin), |
| 141 | + value, |
| 142 | + ) |
| 143 | + self._attr_native_value = value |
| 144 | + except (ValueError, TypeError): |
| 145 | + self._attr_native_value = 0.0 |
| 146 | + else: |
| 147 | + # Default to 0 (disabled/not set) |
| 148 | + self._attr_native_value = 0.0 |
| 149 | + |
| 150 | + @property |
| 151 | + def native_value(self) -> float | None: |
| 152 | + """Return the current value.""" |
| 153 | + return self._attr_native_value |
| 154 | + |
| 155 | + async def async_set_native_value(self, value: float) -> None: |
| 156 | + """Set new value.""" |
| 157 | + self._attr_native_value = value |
| 158 | + # Store in coordinator for immediate use |
| 159 | + if value > 0: |
| 160 | + self._coordinator.set_manual_battery_capacity(self._vin, value) |
| 161 | + _LOGGER.info( |
| 162 | + "Manual battery capacity set for %s: %.1f kWh", |
| 163 | + redact_vin(self._vin), |
| 164 | + value, |
| 165 | + ) |
| 166 | + else: |
| 167 | + # Value of 0 disables manual override |
| 168 | + self._coordinator.set_manual_battery_capacity(self._vin, None) |
| 169 | + _LOGGER.info( |
| 170 | + "Manual battery capacity cleared for %s (auto-detect enabled)", |
| 171 | + redact_vin(self._vin), |
| 172 | + ) |
| 173 | + self.async_write_ha_state() |
0 commit comments